@runtypelabs/persona 3.21.0 → 3.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -1
- package/dist/index.cjs +12 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.global.js +26 -26
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +12 -12
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +54 -26
- package/dist/theme-editor.js +54 -26
- package/package.json +1 -1
- package/src/session.test.ts +151 -0
- package/src/session.ts +78 -21
- package/src/ui.ask-user-question-plugin.test.ts +42 -0
package/dist/index.global.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var Fx=Object.create;var es=Object.defineProperty;var Nx=Object.getOwnPropertyDescriptor;var _x=Object.getOwnPropertyNames;var $x=Object.getPrototypeOf,Ux=Object.prototype.hasOwnProperty;var Um=e=>{throw TypeError(e)};var qx=(e,r,t)=>r in e?es(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var qm=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),zx=(e,r)=>{for(var t in r)es(e,t,{get:r[t],enumerable:!0})},zm=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of _x(r))!Ux.call(e,o)&&o!==t&&es(e,o,{get:()=>r[o],enumerable:!(n=Nx(r,o))||n.enumerable});return e};var Bl=(e,r,t)=>(t=e!=null?Fx($x(e)):{},zm(r||!e||!e.__esModule?es(t,"default",{value:e,enumerable:!0}):t,e)),Vx=e=>zm(es({},"__esModule",{value:!0}),e);var er=(e,r,t)=>qx(e,typeof r!="symbol"?r+"":r,t),jx=(e,r,t)=>r.has(e)||Um("Cannot "+t);var Vm=(e,r,t)=>r.has(e)?Um("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t);var ai=(e,r,t)=>(jx(e,r,"access private method"),t);var Zl=qm(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 hi=qm(Ir=>{"use strict";var Qy=Ir&&Ir.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(r,t);(!o||("get"in o?!r.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,o)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),Zy=Ir&&Ir.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&Qy(r,e,t)};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.Allow=Ir.MalformedJSON=Ir.PartialJSON=Ir.parseJSON=Ir.parse=void 0;var Jr=Zl();Object.defineProperty(Ir,"Allow",{enumerable:!0,get:function(){return Jr.Allow}});Zy(Zl(),Ir);var mi=class extends Error{};Ir.PartialJSON=mi;var gi=class extends Error{};Ir.MalformedJSON=gi;function kg(e,r=Jr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return eb(e.trim(),r)}Ir.parseJSON=kg;var eb=(e,r)=>{let t=e.length,n=0,o=
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var Fx=Object.create;var es=Object.defineProperty;var Nx=Object.getOwnPropertyDescriptor;var _x=Object.getOwnPropertyNames;var $x=Object.getPrototypeOf,Ux=Object.prototype.hasOwnProperty;var Um=e=>{throw TypeError(e)};var qx=(e,r,t)=>r in e?es(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var qm=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),zx=(e,r)=>{for(var t in r)es(e,t,{get:r[t],enumerable:!0})},zm=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of _x(r))!Ux.call(e,o)&&o!==t&&es(e,o,{get:()=>r[o],enumerable:!(n=Nx(r,o))||n.enumerable});return e};var Bl=(e,r,t)=>(t=e!=null?Fx($x(e)):{},zm(r||!e||!e.__esModule?es(t,"default",{value:e,enumerable:!0}):t,e)),Vx=e=>zm(es({},"__esModule",{value:!0}),e);var er=(e,r,t)=>qx(e,typeof r!="symbol"?r+"":r,t),jx=(e,r,t)=>r.has(e)||Um("Cannot "+t);var Vm=(e,r,t)=>r.has(e)?Um("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t);var ai=(e,r,t)=>(jx(e,r,"access private method"),t);var Zl=qm(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 hi=qm(Ir=>{"use strict";var Qy=Ir&&Ir.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(r,t);(!o||("get"in o?!r.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,o)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),Zy=Ir&&Ir.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&Qy(r,e,t)};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.Allow=Ir.MalformedJSON=Ir.PartialJSON=Ir.parseJSON=Ir.parse=void 0;var Jr=Zl();Object.defineProperty(Ir,"Allow",{enumerable:!0,get:function(){return Jr.Allow}});Zy(Zl(),Ir);var mi=class extends Error{};Ir.PartialJSON=mi;var gi=class extends Error{};Ir.MalformedJSON=gi;function kg(e,r=Jr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return eb(e.trim(),r)}Ir.parseJSON=kg;var eb=(e,r)=>{let t=e.length,n=0,o=f=>{throw new mi(`${f} at position ${n}`)},a=f=>{throw new gi(`${f} at position ${n}`)},s=()=>(p(),n>=t&&o("Unexpected end of input"),e[n]==='"'?i():e[n]==="{"?d():e[n]==="["?l():e.substring(n,n+4)==="null"||Jr.Allow.NULL&r&&t-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||Jr.Allow.BOOL&r&&t-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||Jr.Allow.BOOL&r&&t-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||Jr.Allow.INFINITY&r&&t-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||Jr.Allow._INFINITY&r&&1<t-n&&t-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||Jr.Allow.NAN&r&&t-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),i=()=>{let f=n,m=!1;for(n++;n<t&&(e[n]!=='"'||m&&e[n-1]==="\\");)m=e[n]==="\\"?!m:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(f,++n-Number(m)))}catch(C){a(String(C))}else if(Jr.Allow.STR&r)try{return JSON.parse(e.substring(f,n-Number(m))+'"')}catch{return JSON.parse(e.substring(f,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},d=()=>{n++,p();let f={};try{for(;e[n]!=="}";){if(p(),n>=t&&Jr.Allow.OBJ&r)return f;let m=i();p(),n++;try{let C=s();f[m]=C}catch(C){if(Jr.Allow.OBJ&r)return f;throw C}p(),e[n]===","&&n++}}catch{if(Jr.Allow.OBJ&r)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;e[n]!=="]";)f.push(s()),p(),e[n]===","&&n++}catch{if(Jr.Allow.ARR&r)return f;o("Expected ']' at end of array")}return n++,f},u=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Jr.Allow.NUM&r)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let f=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==t&&!(Jr.Allow.NUM&r)&&o("Unterminated number literal");try{return JSON.parse(e.substring(f,n))}catch{e.substring(f,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(e.substring(f,e.lastIndexOf("e")))}catch(C){a(String(C))}}},p=()=>{for(;n<t&&`
|
|
2
2
|
\r `.includes(e[n]);)n++};return s()},tb=kg;Ir.parse=tb});var ew={};zx(ew,{ASK_USER_QUESTION_TOOL_NAME:()=>bp,AgentWidgetClient:()=>Yo,AgentWidgetSession:()=>wa,AttachmentManager:()=>ta,DEFAULT_COMPONENTS:()=>Zc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>qi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>mn,DEFAULT_PALETTE:()=>Yc,DEFAULT_SEMANTIC:()=>Qc,DEFAULT_WIDGET_CONFIG:()=>jt,PRESETS:()=>Gp,PRESET_FULLSCREEN:()=>jp,PRESET_MINIMAL:()=>Vp,PRESET_SHOP:()=>zp,THEME_ZONES:()=>jg,VERSION:()=>ia,accessibilityPlugin:()=>wx,animationsPlugin:()=>vx,applyThemeVariables:()=>vo,attachHeaderToContainer:()=>na,brandPlugin:()=>Ax,buildComposer:()=>ka,buildDefaultHeader:()=>dp,buildHeader:()=>ao,buildHeaderWithLayout:()=>Ta,buildMinimalHeader:()=>cp,collectEnrichedPageContext:()=>ax,componentRegistry:()=>lo,createActionManager:()=>Ds,createAgentExperience:()=>Tl,createAskUserQuestionBubble:()=>Sh,createBestAvailableVoiceProvider:()=>Ii,createBubbleWithLayout:()=>dh,createCSATFeedback:()=>vl,createComboButton:()=>ol,createComponentMiddleware:()=>Nh,createComponentStreamParser:()=>yl,createDefaultSanitizer:()=>Ql,createDemoCarousel:()=>Cx,createDirectivePostprocessor:()=>pg,createDropdownMenu:()=>ko,createFlexibleJsonStreamParser:()=>Lg,createIconButton:()=>Qt,createImagePart:()=>Dg,createJsonStreamParser:()=>Ai,createLabelButton:()=>Ls,createLocalStorageAdapter:()=>xl,createMarkdownProcessor:()=>is,createMarkdownProcessorFromConfig:()=>Xo,createMessageActions:()=>gp,createNPSFeedback:()=>Al,createPlainTextParser:()=>wi,createPlugin:()=>kx,createRegexJsonParser:()=>vi,createStandardBubble:()=>Ea,createTextPart:()=>gs,createTheme:()=>Aa,createThemeObserver:()=>Gi,createToggleGroup:()=>Ps,createTypingIndicator:()=>oa,createVoiceProvider:()=>ea,createWidgetHostLayout:()=>Os,createXmlParser:()=>Si,defaultActionHandlers:()=>sa,defaultJsonActionParser:()=>Ws,defaultParseRules:()=>_p,detectColorScheme:()=>bs,directivePostprocessor:()=>ug,ensureAskUserQuestionSheet:()=>Ra,escapeHtml:()=>Jo,extractComponentDirectiveFromMessage:()=>wl,fileToImagePart:()=>Og,formatEnrichedContext:()=>sx,generateAssistantMessageId:()=>Qo,generateCodeSnippet:()=>fx,generateMessageId:()=>Ig,generateStableSelector:()=>$p,generateUserMessageId:()=>Ca,getActiveTheme:()=>Sa,getColorScheme:()=>tp,getDisplayText:()=>Hg,getHeaderLayout:()=>pp,getImageParts:()=>Wg,getPreset:()=>Mx,hasComponentDirective:()=>Cl,hasImages:()=>Bg,headerLayouts:()=>al,highContrastPlugin:()=>Tx,initAgentWidget:()=>Xh,isAskUserQuestionMessage:()=>so,isComponentDirectiveType:()=>Fh,isDockedMountMode:()=>hr,isVoiceSupported:()=>xs,listRegisteredStreamAnimations:()=>ap,markdownPostprocessor:()=>ql,mergeWithDefaults:()=>zi,normalizeContent:()=>Rg,parseAskUserQuestionPayload:()=>io,pluginRegistry:()=>Bs,reducedMotionPlugin:()=>Sx,registerStreamAnimationPlugin:()=>ra,removeAskUserQuestionSheet:()=>Lo,renderComponentDirective:()=>bl,renderLoadingIndicatorWithFallback:()=>mp,renderLucideIcon:()=>Ce,resolveDockConfig:()=>vn,resolveSanitizer:()=>ya,resolveTokens:()=>Vi,themeToCssVariables:()=>ji,unregisterStreamAnimationPlugin:()=>op,validateImageFile:()=>Fg,validateTheme:()=>ep});function Ol(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Go=Ol();function Ym(e){Go=e}var Qm=/[&<>"']/,Gx=new RegExp(Qm.source,"g"),Zm=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Xx=new RegExp(Zm.source,"g"),Jx={"&":"&","<":"<",">":">",'"':""","'":"'"},jm=e=>Jx[e];function un(e,r){if(r){if(Qm.test(e))return e.replace(Gx,jm)}else if(Zm.test(e))return e.replace(Xx,jm);return e}var Kx=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Yx(e){return e.replace(Kx,(r,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 Qx=/(^|[^\[])\^/g;function Kt(e,r){let t=typeof e=="string"?e:e.source;r=r||"";let n={replace:(o,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(Qx,"$1"),t=t.replace(o,s),n},getRegex:()=>new RegExp(t,r)};return n}function Gm(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch{return null}return e}var rs={exec:()=>null};function Xm(e,r){let t=e.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(),r)if(n.length>r)n.splice(r);else for(;n.length<r;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(/\\\|/g,"|");return n}function si(e,r,t){let n=e.length;if(n===0)return"";let o=0;for(;o<n;){let a=e.charAt(n-o-1);if(a===r&&!t)o++;else if(a!==r&&t)o++;else break}return e.slice(0,n-o)}function Zx(e,r){if(e.indexOf(r[1])===-1)return-1;let t=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===r[0])t++;else if(e[n]===r[1]&&(t--,t<0))return n;return-1}function Jm(e,r,t,n){let o=r.href,a=r.title?un(r.title):null,s=e[1].replace(/\\([\[\]])/g,"$1");if(e[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:un(s)}}function ey(e,r){let t=e.match(/^(\s+)(?:```)/);if(t===null)return r;let n=t[1];return r.split(`
|
|
3
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
4
|
`)}var ha=class{constructor(r){er(this,"options");er(this,"rules");er(this,"lexer");this.options=r||Go}space(r){let t=this.rules.block.newline.exec(r);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(r){let t=this.rules.block.code.exec(r);if(t){let n=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:si(n,`
|
|
5
5
|
`)}}}fences(r){let t=this.rules.block.fences.exec(r);if(t){let n=t[0],o=ey(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(r){let t=this.rules.block.heading.exec(r);if(t){let n=t[2].trim();if(/#$/.test(n)){let o=si(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(r){let t=this.rules.block.hr.exec(r);if(t)return{type:"hr",raw:t[0]}}blockquote(r){let t=this.rules.block.blockquote.exec(r);if(t){let n=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
|
|
6
6
|
$1`);n=si(n.replace(/^ *>[ \t]?/gm,""),`
|
|
7
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(r){let t=this.rules.block.list.exec(r);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(;r;){let u=!1;if(!(t=s.exec(r))||this.rules.block.hr.test(r))break;i=t[0],r=r.substring(i.length);let p=t[2].split(`
|
|
8
|
-
`,1)[0].replace(/^\t+/,T=>" ".repeat(3*T.length)),
|
|
9
|
-
`,1)[0],
|
|
10
|
-
`,r=r.substring(
|
|
11
|
-
`,1)[0];if(
|
|
12
|
-
`+
|
|
13
|
-
`+
|
|
14
|
-
`,r=r.substring(
|
|
8
|
+
`,1)[0].replace(/^\t+/,T=>" ".repeat(3*T.length)),f=r.split(`
|
|
9
|
+
`,1)[0],m=0;this.options.pedantic?(m=2,d=p.trimStart()):(m=t[2].search(/[^ ]/),m=m>4?1:m,d=p.slice(m),m+=t[1].length);let C=!1;if(!p&&/^ *$/.test(f)&&(i+=f+`
|
|
10
|
+
`,r=r.substring(f.length+1),u=!0),!u){let T=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),S=new RegExp(`^ {0,${Math.min(3,m-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),E=new RegExp(`^ {0,${Math.min(3,m-1)}}(?:\`\`\`|~~~)`),b=new RegExp(`^ {0,${Math.min(3,m-1)}}#`);for(;r;){let y=r.split(`
|
|
11
|
+
`,1)[0];if(f=y,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),E.test(f)||b.test(f)||T.test(f)||S.test(r))break;if(f.search(/[^ ]/)>=m||!f.trim())d+=`
|
|
12
|
+
`+f.slice(m);else{if(C||p.search(/[^ ]/)>=4||E.test(p)||b.test(p)||S.test(p))break;d+=`
|
|
13
|
+
`+f}!C&&!f.trim()&&(C=!0),i+=y+`
|
|
14
|
+
`,r=r.substring(y.length+1),p=f.slice(m)}}a.loose||(l?a.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let A=null,k;this.options.gfm&&(A=/^\[[ xX]\] /.exec(d),A&&(k=A[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),a.items.push({type:"list_item",raw:i,task:!!A,checked:k,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 p=a.items[u].tokens.filter(m=>m.type==="space"),f=p.length>0&&p.some(m=>/\n.*\n/.test(m.raw));a.loose=f}if(a.loose)for(let u=0;u<a.items.length;u++)a.items[u].loose=!0;return a}}html(r){let t=this.rules.block.html.exec(r);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(r){let t=this.rules.block.def.exec(r);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(r){let t=this.rules.block.table.exec(r);if(!t||!/[:|]/.test(t[2]))return;let n=Xm(t[1]),o=t[2].replace(/^\||\| *$/g,"").split("|"),a=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(`
|
|
15
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(Xm(i,s.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return s}}lheading(r){let t=this.rules.block.lheading.exec(r);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(r){let t=this.rules.block.paragraph.exec(r);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(r){let t=this.rules.block.text.exec(r);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(r){let t=this.rules.inline.escape.exec(r);if(t)return{type:"escape",raw:t[0],text:un(t[1])}}tag(r){let t=this.rules.inline.tag.exec(r);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(r){let t=this.rules.inline.link.exec(r);if(t){let n=t[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let s=si(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=Zx(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)),Jm(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer)}}reflink(r,t){let n;if((n=this.rules.inline.reflink.exec(r))||(n=this.rules.inline.nolink.exec(r))){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 Jm(n,a,n[0],this.lexer)}}emStrong(r,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(r);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,p=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*r.length+s);(o=p.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
|
|
16
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(r){let t=this.rules.block.text.exec(r);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(r){let t=this.rules.inline.escape.exec(r);if(t)return{type:"escape",raw:t[0],text:un(t[1])}}tag(r){let t=this.rules.inline.tag.exec(r);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(r){let t=this.rules.inline.link.exec(r);if(t){let n=t[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let s=si(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=Zx(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)),Jm(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer)}}reflink(r,t){let n;if((n=this.rules.inline.reflink.exec(r))||(n=this.rules.inline.nolink.exec(r))){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 Jm(n,a,n[0],this.lexer)}}emStrong(r,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(r);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,p=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*r.length+s);(o=p.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 f=[...o[0]][0].length,m=r.slice(0,s+o.index+f+d);if(Math.min(s,d)%2){let A=m.slice(1,-1);return{type:"em",raw:m,text:A,tokens:this.lexer.inlineTokens(A)}}let C=m.slice(2,-2);return{type:"strong",raw:m,text:C,tokens:this.lexer.inlineTokens(C)}}}}codespan(r){let t=this.rules.inline.code.exec(r);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=un(n,!0),{type:"codespan",raw:t[0],text:n}}}br(r){let t=this.rules.inline.br.exec(r);if(t)return{type:"br",raw:t[0]}}del(r){let t=this.rules.inline.del.exec(r);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(r){let t=this.rules.inline.autolink.exec(r);if(t){let n,o;return t[2]==="@"?(n=un(t[1]),o="mailto:"+n):(n=un(t[1]),o=n),{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(r){var n,o;let t;if(t=this.rules.inline.url.exec(r)){let a,s;if(t[2]==="@")a=un(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=un(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(r){let t=this.rules.inline.text.exec(r);if(t){let n;return this.lexer.state.inRawBlock?n=t[0]:n=un(t[0]),{type:"text",raw:t[0],text:n}}}},ty=/^(?: *(?:\n|$))+/,ry=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,ny=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,as=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,oy=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,eg=/(?:[*+-]|\d{1,9}[.)])/,tg=Kt(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,eg).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(),Fl=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ay=/^[^\n]+/,Nl=/(?!\s*\])(?:\\.|[^\[\]\\])+/,sy=Kt(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",Nl).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),iy=Kt(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,eg).getRegex(),di="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",_l=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ly=Kt("^ {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",_l).replace("tag",di).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),rg=Kt(Fl).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",di).getRegex(),dy=Kt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",rg).getRegex(),$l={blockquote:dy,code:ry,def:sy,fences:ny,heading:oy,hr:as,html:ly,lheading:tg,list:iy,newline:ty,paragraph:rg,table:rs,text:ay},Km=Kt("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",di).getRegex(),cy={...$l,table:Km,paragraph:Kt(Fl).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Km).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",di).getRegex()},py={...$l,html:Kt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_l).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:rs,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Kt(Fl).replace("hr",as).replace("heading",` *#{1,6} *[^
|
|
17
17
|
]`).replace("lheading",tg).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ng=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,uy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,og=/^( {2,}|\\)\n(?!\s*$)/,fy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ss="\\p{P}\\p{S}",my=Kt(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,ss).getRegex(),gy=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,hy=Kt(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,ss).getRegex(),xy=Kt("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,ss).getRegex(),yy=Kt("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,ss).getRegex(),by=Kt(/\\([punct])/,"gu").replace(/punct/g,ss).getRegex(),Cy=Kt(/^<(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(),wy=Kt(_l).replace("(?:-->|$)","-->").getRegex(),vy=Kt("^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",wy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),li=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ay=Kt(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",li).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ag=Kt(/^!?\[(label)\]\[(ref)\]/).replace("label",li).replace("ref",Nl).getRegex(),sg=Kt(/^!?\[(ref)\](?:\[\])?/).replace("ref",Nl).getRegex(),Sy=Kt("reflink|nolink(?!\\()","g").replace("reflink",ag).replace("nolink",sg).getRegex(),Ul={_backpedal:rs,anyPunctuation:by,autolink:Cy,blockSkip:gy,br:og,code:uy,del:rs,emStrongLDelim:hy,emStrongRDelimAst:xy,emStrongRDelimUnd:yy,escape:ng,link:Ay,nolink:sg,punctuation:my,reflink:ag,reflinkSearch:Sy,tag:vy,text:fy,url:rs},Ty={...Ul,link:Kt(/^!?\[(label)\]\((.*?)\)/).replace("label",li).getRegex(),reflink:Kt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",li).getRegex()},Wl={...Ul,escape:Kt(ng).replace("])","~|])").getRegex(),url:Kt(/^((?: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.!#$%&'*+\/=?_`{\|}~-]+@)))/},ky={...Wl,br:Kt(og).replace("{2,}","*").getRegex(),text:Kt(Wl.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ii={normal:$l,gfm:cy,pedantic:py},ts={normal:Ul,gfm:Wl,breaks:ky,pedantic:Ty},to=class e{constructor(r){er(this,"tokens");er(this,"options");er(this,"state");er(this,"tokenizer");er(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=r||Go,this.options.tokenizer=this.options.tokenizer||new ha,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={block: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(r,t){return new e(t).lex(r)}static lexInline(r,t){return new e(t).inlineTokens(r)}lex(r){r=r.replace(/\r\n|\r/g,`
|
|
18
18
|
`),this.blockTokens(r,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(r,t=[]){this.options.pedantic?r=r.replace(/\t/g," ").replace(/^ +$/gm,""):r=r.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,a,s;for(;r;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},r,t))?(r=r.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.space(r)){r=r.substring(n.raw.length),n.raw.length===1&&t.length>0?t[t.length-1].raw+=`
|
|
19
19
|
`:t.push(n);continue}if(n=this.tokenizer.code(r)){r=r.substring(n.raw.length),o=t[t.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
`+n.raw,o.text+=`
|
|
25
25
|
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n),s=a.length!==r.length,r=r.substring(n.raw.length);continue}if(n=this.tokenizer.text(r)){r=r.substring(n.raw.length),o=t[t.length-1],o&&o.type==="text"?(o.raw+=`
|
|
26
26
|
`+n.raw,o.text+=`
|
|
27
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n);continue}if(r){let i="Infinite loop on byte: "+r.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,t}inline(r,t=[]){return this.inlineQueue.push({src:r,tokens:t}),t}inlineTokens(r,t=[]){let n,o,a,s=r,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(;r;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(n=u.call({lexer:this},r,t))?(r=r.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.escape(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.tag(r)){r=r.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(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.reflink(r,this.tokens.links)){r=r.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(r,s,l)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.codespan(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.br(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.del(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.autolink(r)){r=r.substring(n.raw.length),t.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(r))){r=r.substring(n.raw.length),t.push(n);continue}if(a=r,this.options.extensions&&this.options.extensions.startInline){let u=1/0,p=r.slice(1),
|
|
27
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n);continue}if(r){let i="Infinite loop on byte: "+r.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,t}inline(r,t=[]){return this.inlineQueue.push({src:r,tokens:t}),t}inlineTokens(r,t=[]){let n,o,a,s=r,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(;r;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(n=u.call({lexer:this},r,t))?(r=r.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.escape(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.tag(r)){r=r.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(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.reflink(r,this.tokens.links)){r=r.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(r,s,l)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.codespan(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.br(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.del(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.autolink(r)){r=r.substring(n.raw.length),t.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(r))){r=r.substring(n.raw.length),t.push(n);continue}if(a=r,this.options.extensions&&this.options.extensions.startInline){let u=1/0,p=r.slice(1),f;this.options.extensions.startInline.forEach(m=>{f=m.call({lexer:this},p),typeof f=="number"&&f>=0&&(u=Math.min(u,f))}),u<1/0&&u>=0&&(a=r.substring(0,u+1))}if(n=this.tokenizer.inlineText(a)){r=r.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(r){let u="Infinite loop on byte: "+r.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}},xa=class{constructor(r){er(this,"options");this.options=r||Go}code(r,t,n){var a;let o=(a=(t||"").match(/^\S*/))==null?void 0:a[0];return r=r.replace(/\n$/,"")+`
|
|
28
28
|
`,o?'<pre><code class="language-'+un(o)+'">'+(n?r:un(r,!0))+`</code></pre>
|
|
29
29
|
`:"<pre><code>"+(n?r:un(r,!0))+`</code></pre>
|
|
30
30
|
`}blockquote(r){return`<blockquote>
|
|
@@ -42,17 +42,17 @@ ${r}</blockquote>
|
|
|
42
42
|
`}tablerow(r){return`<tr>
|
|
43
43
|
${r}</tr>
|
|
44
44
|
`}tablecell(r,t){let n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+r+`</${n}>
|
|
45
|
-
`}strong(r){return`<strong>${r}</strong>`}em(r){return`<em>${r}</em>`}codespan(r){return`<code>${r}</code>`}br(){return"<br>"}del(r){return`<del>${r}</del>`}link(r,t,n){let o=Gm(r);if(o===null)return n;r=o;let a='<a href="'+r+'"';return t&&(a+=' title="'+t+'"'),a+=">"+n+"</a>",a}image(r,t,n){let o=Gm(r);if(o===null)return n;r=o;let a=`<img src="${r}" alt="${n}"`;return t&&(a+=` title="${t}"`),a+=">",a}text(r){return r}},ns=class{strong(r){return r}em(r){return r}codespan(r){return r}del(r){return r}html(r){return r}text(r){return r}link(r,t,n){return""+n}image(r,t,n){return""+n}br(){return""}},ro=class e{constructor(r){er(this,"options");er(this,"renderer");er(this,"textRenderer");this.options=r||Go,this.options.renderer=this.options.renderer||new xa,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new ns}static parse(r,t){return new e(t).parse(r)}static parseInline(r,t){return new e(t).parseInline(r)}parse(r,t=!0){let n="";for(let o=0;o<r.length;o++){let a=r[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,Yx(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 p=s.rows[u];d="";for(let
|
|
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(r,t){t=t||this.renderer;let n="";for(let o=0;o<r.length;o++){let a=r[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}},zo=class{constructor(r){er(this,"options");this.options=r||Go}preprocess(r){return r}postprocess(r){return r}processAllTokens(r){return r}};er(zo,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var jo,Dl,ig,os=class{constructor(...r){Vm(this,jo);er(this,"defaults",Ol());er(this,"options",this.setOptions);er(this,"parse",ai(this,jo,Dl).call(this,to.lex,ro.parse));er(this,"parseInline",ai(this,jo,Dl).call(this,to.lexInline,ro.parseInline));er(this,"Parser",ro);er(this,"Renderer",xa);er(this,"TextRenderer",ns);er(this,"Lexer",to);er(this,"Tokenizer",ha);er(this,"Hooks",zo);this.use(...r)}walkTokens(r,t){var o,a;let n=[];for(let s of r)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(...r){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return r.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 xa(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 p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p||""}}o.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new ha(this.defaults);for(let s in n.tokenizer){if(!(s in a))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,d=n.tokenizer[i],l=a[i];a[i]=(...u)=>{let p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p}}o.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new zo;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];zo.passThroughHooks.has(s)?a[i]=u=>{if(this.defaults.async)return Promise.resolve(d.call(a,u)).then(
|
|
47
|
-
Please report this to https://github.com/markedjs/marked.`,r){let o="<p>An error occurred:</p><pre>"+un(n.message+"",!0)+"</pre>";return t?Promise.resolve(o):o}if(t)return Promise.reject(n);throw n}};var Vo=new os;function Jt(e,r){return Vo.parse(e,r)}Jt.options=Jt.setOptions=function(e){return Vo.setOptions(e),Jt.defaults=Vo.defaults,Ym(Jt.defaults),Jt};Jt.getDefaults=Ol;Jt.defaults=Go;Jt.use=function(...e){return Vo.use(...e),Jt.defaults=Vo.defaults,Ym(Jt.defaults),Jt};Jt.walkTokens=function(e,r){return Vo.walkTokens(e,r)};Jt.parseInline=Vo.parseInline;Jt.Parser=ro;Jt.parser=ro.parse;Jt.Renderer=xa;Jt.TextRenderer=ns;Jt.Lexer=to;Jt.lexer=to.lex;Jt.Tokenizer=ha;Jt.Hooks=zo;Jt.parse=Jt;var nw=Jt.options,ow=Jt.setOptions,aw=Jt.use,sw=Jt.walkTokens,iw=Jt.parseInline;var lw=ro.parse,dw=to.lex;var Ey=e=>{if(e)return e},is=e=>{var o,a;let r=e==null?void 0:e.markedOptions,t=new os({gfm:(o=r==null?void 0:r.gfm)!=null?o:!0,breaks:(a=r==null?void 0:r.breaks)!=null?a:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=Ey(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),s=>t.parse(s)},Xo=e=>e?is({markedOptions:e.options,renderer:e.renderer}):is(),My=is(),ql=e=>My(e),Jo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),dg=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),lg=e=>`%%FORM_PLACEHOLDER_${e}%%`,cg=(e,r)=>{let t=e;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=lg(r.length);return r.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=lg(r.length);return r.push({token:a,type:o}),a}),t},pg=e=>{let r=Xo(e);return t=>{let n=[],o=cg(t,n),a=r(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="${dg(i)}"></div>`;a=a.replace(d,u)}),a}},ug=e=>{let r=[],t=cg(e,r),n=ql(t);return r.forEach(({token:o,type:a})=>{let s=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${dg(a)}"></div>`;n=n.replace(s,d)}),n};var{entries:wg,setPrototypeOf:fg,isFrozen:Ly,getPrototypeOf:Py,getOwnPropertyDescriptor:Iy}=Object,{freeze:Gr,seal:wn,create:ui}=Object,{apply:Kl,construct:Yl}=typeof Reflect!="undefined"&&Reflect;Gr||(Gr=function(r){return r});wn||(wn=function(r){return r});Kl||(Kl=function(r,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 r.apply(t,o)});Yl||(Yl=function(r){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 r(...n)});var ci=Xr(Array.prototype.forEach),Ry=Xr(Array.prototype.lastIndexOf),mg=Xr(Array.prototype.pop),ls=Xr(Array.prototype.push),Hy=Xr(Array.prototype.splice),fi=Xr(String.prototype.toLowerCase),zl=Xr(String.prototype.toString),Vl=Xr(String.prototype.match),ds=Xr(String.prototype.replace),By=Xr(String.prototype.indexOf),Wy=Xr(String.prototype.trim),fn=Xr(Object.prototype.hasOwnProperty),jr=Xr(RegExp.prototype.test),cs=Dy(TypeError);function Xr(e){return function(r){r instanceof RegExp&&(r.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 Kl(e,r,n)}}function Dy(e){return function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return Yl(e,t)}}function At(e,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fi;fg&&fg(e,null);let n=r.length;for(;n--;){let o=r[n];if(typeof o=="string"){let a=t(o);a!==o&&(Ly(r)||(r[n]=a),o=a)}e[o]=!0}return e}function Oy(e){for(let r=0;r<e.length;r++)fn(e,r)||(e[r]=null);return e}function Un(e){let r=ui(null);for(let[t,n]of wg(e))fn(e,t)&&(Array.isArray(n)?r[t]=Oy(n):n&&typeof n=="object"&&n.constructor===Object?r[t]=Un(n):r[t]=n);return r}function ps(e,r){for(;e!==null;){let n=Iy(e,r);if(n){if(n.get)return Xr(n.get);if(typeof n.value=="function")return Xr(n.value)}e=Py(e)}function t(){return null}return t}var gg=Gr(["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"]),jl=Gr(["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"]),Gl=Gr(["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"]),Fy=Gr(["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"]),Xl=Gr(["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"]),Ny=Gr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),hg=Gr(["#text"]),xg=Gr(["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"]),Jl=Gr(["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"]),yg=Gr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),pi=Gr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_y=wn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),$y=wn(/<%[\w\W]*|[\w\W]*%>/gm),Uy=wn(/\$\{[\w\W]*/gm),qy=wn(/^data-[\-\w.\u00B7-\uFFFF]+$/),zy=wn(/^aria-[\-\w]+$/),vg=wn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vy=wn(/^(?:\w+script|data):/i),jy=wn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ag=wn(/^html$/i),Gy=wn(/^[a-z][.\w]*(-[.\w]+)+$/i),bg=Object.freeze({__proto__:null,ARIA_ATTR:zy,ATTR_WHITESPACE:jy,CUSTOM_ELEMENT:Gy,DATA_ATTR:qy,DOCTYPE_NAME:Ag,ERB_EXPR:$y,IS_ALLOWED_URI:vg,IS_SCRIPT_OR_DATA:Vy,MUSTACHE_EXPR:_y,TMPLIT_EXPR:Uy}),us={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Xy=function(){return typeof window=="undefined"?null:window},Jy=function(r,t){if(typeof r!="object"||typeof r.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 r.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Cg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Sg(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Xy(),r=Ie=>Sg(Ie);if(r.version="3.3.3",r.removed=[],!e||!e.document||e.document.nodeType!==us.document||!e.Element)return r.isSupported=!1,r;let{document:t}=e,n=t,o=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:i,Element:d,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:f}=e,w=d.prototype,v=ps(w,"cloneNode"),k=ps(w,"remove"),T=ps(w,"nextSibling"),A=ps(w,"childNodes"),E=ps(w,"parentNode");if(typeof s=="function"){let Ie=t.createElement("template");Ie.content&&Ie.content.ownerDocument&&(t=Ie.content.ownerDocument)}let b,h="",{implementation:S,createNodeIterator:L,createDocumentFragment:O,getElementsByTagName:H}=t,{importNode:R}=n,B=Cg();r.isSupported=typeof wg=="function"&&typeof E=="function"&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:j,ERB_EXPR:oe,TMPLIT_EXPR:ue,DATA_ATTR:De,ARIA_ATTR:Xe,IS_SCRIPT_OR_DATA:xe,ATTR_WHITESPACE:ge,CUSTOM_ELEMENT:Le}=bg,{IS_ALLOWED_URI:Ge}=bg,Q=null,Se=At({},[...gg,...jl,...Gl,...Xl,...hg]),J=null,ce=At({},[...xg,...Jl,...yg,...pi]),pe=Object.seal(ui(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ie=null,Oe=null,Pe=Object.seal(ui(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),K=!0,_e=!0,$e=!1,Y=!0,G=!1,we=!0,ke=!1,ae=!1,ve=!1,ye=!1,Mt=!1,ne=!1,He=!0,fr=!1,Ot="user-content-",Yt=!0,Fr=!1,Ar={},F=null,le=At({},["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"]),Fe=null,Ke=At({},["audio","video","img","source","image","track"]),Ue=null,qe=At({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),nt="http://www.w3.org/1998/Math/MathML",Ct="http://www.w3.org/2000/svg",Pt="http://www.w3.org/1999/xhtml",$t=Pt,N=!1,de=null,Ee=At({},[nt,Ct,Pt],zl),ut=At({},["mi","mo","mn","ms","mtext"]),Ye=At({},["annotation-xml"]),Ut=At({},["title","style","font","a","script"]),or=null,It=["application/xhtml+xml","text/html"],St="text/html",rt=null,it=null,tr=t.createElement("form"),gn=function(M){return M instanceof RegExp||M instanceof Function},Rr=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(it&&it===M)){if((!M||typeof M!="object")&&(M={}),M=Un(M),or=It.indexOf(M.PARSER_MEDIA_TYPE)===-1?St:M.PARSER_MEDIA_TYPE,rt=or==="application/xhtml+xml"?zl:fi,Q=fn(M,"ALLOWED_TAGS")?At({},M.ALLOWED_TAGS,rt):Se,J=fn(M,"ALLOWED_ATTR")?At({},M.ALLOWED_ATTR,rt):ce,de=fn(M,"ALLOWED_NAMESPACES")?At({},M.ALLOWED_NAMESPACES,zl):Ee,Ue=fn(M,"ADD_URI_SAFE_ATTR")?At(Un(qe),M.ADD_URI_SAFE_ATTR,rt):qe,Fe=fn(M,"ADD_DATA_URI_TAGS")?At(Un(Ke),M.ADD_DATA_URI_TAGS,rt):Ke,F=fn(M,"FORBID_CONTENTS")?At({},M.FORBID_CONTENTS,rt):le,ie=fn(M,"FORBID_TAGS")?At({},M.FORBID_TAGS,rt):Un({}),Oe=fn(M,"FORBID_ATTR")?At({},M.FORBID_ATTR,rt):Un({}),Ar=fn(M,"USE_PROFILES")?M.USE_PROFILES:!1,K=M.ALLOW_ARIA_ATTR!==!1,_e=M.ALLOW_DATA_ATTR!==!1,$e=M.ALLOW_UNKNOWN_PROTOCOLS||!1,Y=M.ALLOW_SELF_CLOSE_IN_ATTR!==!1,G=M.SAFE_FOR_TEMPLATES||!1,we=M.SAFE_FOR_XML!==!1,ke=M.WHOLE_DOCUMENT||!1,ye=M.RETURN_DOM||!1,Mt=M.RETURN_DOM_FRAGMENT||!1,ne=M.RETURN_TRUSTED_TYPE||!1,ve=M.FORCE_BODY||!1,He=M.SANITIZE_DOM!==!1,fr=M.SANITIZE_NAMED_PROPS||!1,Yt=M.KEEP_CONTENT!==!1,Fr=M.IN_PLACE||!1,Ge=M.ALLOWED_URI_REGEXP||vg,$t=M.NAMESPACE||Pt,ut=M.MATHML_TEXT_INTEGRATION_POINTS||ut,Ye=M.HTML_INTEGRATION_POINTS||Ye,pe=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&gn(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(pe.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&gn(M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(pe.attributeNameCheck=M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M.CUSTOM_ELEMENT_HANDLING&&typeof M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(pe.allowCustomizedBuiltInElements=M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(_e=!1),Mt&&(ye=!0),Ar&&(Q=At({},hg),J=ui(null),Ar.html===!0&&(At(Q,gg),At(J,xg)),Ar.svg===!0&&(At(Q,jl),At(J,Jl),At(J,pi)),Ar.svgFilters===!0&&(At(Q,Gl),At(J,Jl),At(J,pi)),Ar.mathMl===!0&&(At(Q,Xl),At(J,yg),At(J,pi))),fn(M,"ADD_TAGS")||(Pe.tagCheck=null),fn(M,"ADD_ATTR")||(Pe.attributeCheck=null),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?Pe.tagCheck=M.ADD_TAGS:(Q===Se&&(Q=Un(Q)),At(Q,M.ADD_TAGS,rt))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?Pe.attributeCheck=M.ADD_ATTR:(J===ce&&(J=Un(J)),At(J,M.ADD_ATTR,rt))),M.ADD_URI_SAFE_ATTR&&At(Ue,M.ADD_URI_SAFE_ATTR,rt),M.FORBID_CONTENTS&&(F===le&&(F=Un(F)),At(F,M.FORBID_CONTENTS,rt)),M.ADD_FORBID_CONTENTS&&(F===le&&(F=Un(F)),At(F,M.ADD_FORBID_CONTENTS,rt)),Yt&&(Q["#text"]=!0),ke&&At(Q,["html","head","body"]),Q.table&&(At(Q,["tbody"]),delete ie.tbody),M.TRUSTED_TYPES_POLICY){if(typeof M.TRUSTED_TYPES_POLICY.createHTML!="function")throw cs('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw cs('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=M.TRUSTED_TYPES_POLICY,h=b.createHTML("")}else b===void 0&&(b=Jy(f,o)),b!==null&&typeof h=="string"&&(h=b.createHTML(""));Gr&&Gr(M),it=M}},Tn=At({},[...jl,...Gl,...Fy]),Tt=At({},[...Xl,...Ny]),hn=function(M){let Z=E(M);(!Z||!Z.tagName)&&(Z={namespaceURI:$t,tagName:"template"});let se=fi(M.tagName),kt=fi(Z.tagName);return de[M.namespaceURI]?M.namespaceURI===Ct?Z.namespaceURI===Pt?se==="svg":Z.namespaceURI===nt?se==="svg"&&(kt==="annotation-xml"||ut[kt]):!!Tn[se]:M.namespaceURI===nt?Z.namespaceURI===Pt?se==="math":Z.namespaceURI===Ct?se==="math"&&Ye[kt]:!!Tt[se]:M.namespaceURI===Pt?Z.namespaceURI===Ct&&!Ye[kt]||Z.namespaceURI===nt&&!ut[kt]?!1:!Tt[se]&&(Ut[se]||!Tn[se]):!!(or==="application/xhtml+xml"&&de[M.namespaceURI]):!1},ur=function(M){ls(r.removed,{element:M});try{E(M).removeChild(M)}catch{k(M)}},Sr=function(M,Z){try{ls(r.removed,{attribute:Z.getAttributeNode(M),from:Z})}catch{ls(r.removed,{attribute:null,from:Z})}if(Z.removeAttribute(M),M==="is")if(ye||Mt)try{ur(Z)}catch{}else try{Z.setAttribute(M,"")}catch{}},Yr=function(M){let Z=null,se=null;if(ve)M="<remove></remove>"+M;else{let Bt=Vl(M,/^[\r\n\t ]+/);se=Bt&&Bt[0]}or==="application/xhtml+xml"&&$t===Pt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");let kt=b?b.createHTML(M):M;if($t===Pt)try{Z=new m().parseFromString(kt,or)}catch{}if(!Z||!Z.documentElement){Z=S.createDocument($t,"template",null);try{Z.documentElement.innerHTML=N?h:kt}catch{}}let qt=Z.body||Z.documentElement;return M&&se&&qt.insertBefore(t.createTextNode(se),qt.childNodes[0]||null),$t===Pt?H.call(Z,ke?"html":"body")[0]:ke?Z.documentElement:qt},xt=function(M){return L.call(M.ownerDocument||M,M,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},kn=function(M){return M instanceof p&&(typeof M.nodeName!="string"||typeof M.textContent!="string"||typeof M.removeChild!="function"||!(M.attributes instanceof u)||typeof M.removeAttribute!="function"||typeof M.setAttribute!="function"||typeof M.namespaceURI!="string"||typeof M.insertBefore!="function"||typeof M.hasChildNodes!="function")},nn=function(M){return typeof i=="function"&&M instanceof i};function Tr(Ie,M,Z){ci(Ie,se=>{se.call(r,M,Z,it)})}let kr=function(M){let Z=null;if(Tr(B.beforeSanitizeElements,M,null),kn(M))return ur(M),!0;let se=rt(M.nodeName);if(Tr(B.uponSanitizeElement,M,{tagName:se,allowedTags:Q}),we&&M.hasChildNodes()&&!nn(M.firstElementChild)&&jr(/<[/\w!]/g,M.innerHTML)&&jr(/<[/\w!]/g,M.textContent)||M.nodeType===us.progressingInstruction||we&&M.nodeType===us.comment&&jr(/<[/\w]/g,M.data))return ur(M),!0;if(!(Pe.tagCheck instanceof Function&&Pe.tagCheck(se))&&(!Q[se]||ie[se])){if(!ie[se]&&En(se)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,se)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(se)))return!1;if(Yt&&!F[se]){let kt=E(M)||M.parentNode,qt=A(M)||M.childNodes;if(qt&&kt){let Bt=qt.length;for(let ar=Bt-1;ar>=0;--ar){let xr=v(qt[ar],!0);xr.__removalCount=(M.__removalCount||0)+1,kt.insertBefore(xr,T(M))}}}return ur(M),!0}return M instanceof d&&!hn(M)||(se==="noscript"||se==="noembed"||se==="noframes")&&jr(/<\/no(script|embed|frames)/i,M.innerHTML)?(ur(M),!0):(G&&M.nodeType===us.text&&(Z=M.textContent,ci([j,oe,ue],kt=>{Z=ds(Z,kt," ")}),M.textContent!==Z&&(ls(r.removed,{element:M.cloneNode()}),M.textContent=Z)),Tr(B.afterSanitizeElements,M,null),!1)},Vn=function(M,Z,se){if(Oe[Z]||He&&(Z==="id"||Z==="name")&&(se in t||se in tr))return!1;if(!(_e&&!Oe[Z]&&jr(De,Z))){if(!(K&&jr(Xe,Z))){if(!(Pe.attributeCheck instanceof Function&&Pe.attributeCheck(Z,M))){if(!J[Z]||Oe[Z]){if(!(En(M)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,M)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(M))&&(pe.attributeNameCheck instanceof RegExp&&jr(pe.attributeNameCheck,Z)||pe.attributeNameCheck instanceof Function&&pe.attributeNameCheck(Z,M))||Z==="is"&&pe.allowCustomizedBuiltInElements&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,se)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(se))))return!1}else if(!Ue[Z]){if(!jr(Ge,ds(se,ge,""))){if(!((Z==="src"||Z==="xlink:href"||Z==="href")&&M!=="script"&&By(se,"data:")===0&&Fe[M])){if(!($e&&!jr(xe,ds(se,ge,"")))){if(se)return!1}}}}}}}return!0},En=function(M){return M!=="annotation-xml"&&Vl(M,Le)},xn=function(M){Tr(B.beforeSanitizeAttributes,M,null);let{attributes:Z}=M;if(!Z||kn(M))return;let se={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J,forceKeepAttr:void 0},kt=Z.length;for(;kt--;){let qt=Z[kt],{name:Bt,namespaceURI:ar,value:xr}=qt,Nr=rt(Bt),Er=xr,ot=Bt==="value"?Er:Wy(Er);if(se.attrName=Nr,se.attrValue=ot,se.keepAttr=!0,se.forceKeepAttr=void 0,Tr(B.uponSanitizeAttribute,M,se),ot=se.attrValue,fr&&(Nr==="id"||Nr==="name")&&(Sr(Bt,M),ot=Ot+ot),we&&jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,ot)){Sr(Bt,M);continue}if(Nr==="attributename"&&Vl(ot,"href")){Sr(Bt,M);continue}if(se.forceKeepAttr)continue;if(!se.keepAttr){Sr(Bt,M);continue}if(!Y&&jr(/\/>/i,ot)){Sr(Bt,M);continue}G&&ci([j,oe,ue],_r=>{ot=ds(ot,_r," ")});let wr=rt(M.nodeName);if(!Vn(wr,Nr,ot)){Sr(Bt,M);continue}if(b&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!ar)switch(f.getAttributeType(wr,Nr)){case"TrustedHTML":{ot=b.createHTML(ot);break}case"TrustedScriptURL":{ot=b.createScriptURL(ot);break}}if(ot!==Er)try{ar?M.setAttributeNS(ar,Bt,ot):M.setAttribute(Bt,ot),kn(M)?ur(M):mg(r.removed)}catch{Sr(Bt,M)}}Tr(B.afterSanitizeAttributes,M,null)},wt=function Ie(M){let Z=null,se=xt(M);for(Tr(B.beforeSanitizeShadowDOM,M,null);Z=se.nextNode();)Tr(B.uponSanitizeShadowNode,Z,null),kr(Z),xn(Z),Z.content instanceof a&&Ie(Z.content);Tr(B.afterSanitizeShadowDOM,M,null)};return r.sanitize=function(Ie){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Z=null,se=null,kt=null,qt=null;if(N=!Ie,N&&(Ie="<!-->"),typeof Ie!="string"&&!nn(Ie))if(typeof Ie.toString=="function"){if(Ie=Ie.toString(),typeof Ie!="string")throw cs("dirty is not a string, aborting")}else throw cs("toString is not a function");if(!r.isSupported)return Ie;if(ae||Rr(M),r.removed=[],typeof Ie=="string"&&(Fr=!1),Fr){if(Ie.nodeName){let xr=rt(Ie.nodeName);if(!Q[xr]||ie[xr])throw cs("root node is forbidden and cannot be sanitized in-place")}}else if(Ie instanceof i)Z=Yr("<!---->"),se=Z.ownerDocument.importNode(Ie,!0),se.nodeType===us.element&&se.nodeName==="BODY"||se.nodeName==="HTML"?Z=se:Z.appendChild(se);else{if(!ye&&!G&&!ke&&Ie.indexOf("<")===-1)return b&&ne?b.createHTML(Ie):Ie;if(Z=Yr(Ie),!Z)return ye?null:ne?h:""}Z&&ve&&ur(Z.firstChild);let Bt=xt(Fr?Ie:Z);for(;kt=Bt.nextNode();)kr(kt),xn(kt),kt.content instanceof a&&wt(kt.content);if(Fr)return Ie;if(ye){if(Mt)for(qt=O.call(Z.ownerDocument);Z.firstChild;)qt.appendChild(Z.firstChild);else qt=Z;return(J.shadowroot||J.shadowrootmode)&&(qt=R.call(n,qt,!0)),qt}let ar=ke?Z.outerHTML:Z.innerHTML;return ke&&Q["!doctype"]&&Z.ownerDocument&&Z.ownerDocument.doctype&&Z.ownerDocument.doctype.name&&jr(Ag,Z.ownerDocument.doctype.name)&&(ar="<!DOCTYPE "+Z.ownerDocument.doctype.name+`>
|
|
48
|
-
`+ar),G&&ci([j,oe,ue],xr=>{ar=ds(ar,xr," ")}),b&&ne?b.createHTML(ar):ar},r.setConfig=function(){let Ie=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rr(Ie),ae=!0},r.clearConfig=function(){it=null,ae=!1},r.isValidAttribute=function(Ie,
|
|
45
|
+
`}strong(r){return`<strong>${r}</strong>`}em(r){return`<em>${r}</em>`}codespan(r){return`<code>${r}</code>`}br(){return"<br>"}del(r){return`<del>${r}</del>`}link(r,t,n){let o=Gm(r);if(o===null)return n;r=o;let a='<a href="'+r+'"';return t&&(a+=' title="'+t+'"'),a+=">"+n+"</a>",a}image(r,t,n){let o=Gm(r);if(o===null)return n;r=o;let a=`<img src="${r}" alt="${n}"`;return t&&(a+=` title="${t}"`),a+=">",a}text(r){return r}},ns=class{strong(r){return r}em(r){return r}codespan(r){return r}del(r){return r}html(r){return r}text(r){return r}link(r,t,n){return""+n}image(r,t,n){return""+n}br(){return""}},ro=class e{constructor(r){er(this,"options");er(this,"renderer");er(this,"textRenderer");this.options=r||Go,this.options.renderer=this.options.renderer||new xa,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new ns}static parse(r,t){return new e(t).parse(r)}static parseInline(r,t){return new e(t).parseInline(r)}parse(r,t=!0){let n="";for(let o=0;o<r.length;o++){let a=r[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,Yx(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 p=s.rows[u];d="";for(let f=0;f<p.length;f++)d+=this.renderer.tablecell(this.parseInline(p[f].tokens),{header:!1,align:s.align[f]});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 p=0;p<s.items.length;p++){let f=s.items[p],m=f.checked,C=f.task,A="";if(f.task){let k=this.renderer.checkbox(!!m);l?f.tokens.length>0&&f.tokens[0].type==="paragraph"?(f.tokens[0].text=k+" "+f.tokens[0].text,f.tokens[0].tokens&&f.tokens[0].tokens.length>0&&f.tokens[0].tokens[0].type==="text"&&(f.tokens[0].tokens[0].text=k+" "+f.tokens[0].tokens[0].text)):f.tokens.unshift({type:"text",text:k+" "}):A+=k+" "}A+=this.parse(f.tokens,l),u+=this.renderer.listitem(A,C,!!m)}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<r.length&&r[o+1].type==="text";)s=r[++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(r,t){t=t||this.renderer;let n="";for(let o=0;o<r.length;o++){let a=r[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}},zo=class{constructor(r){er(this,"options");this.options=r||Go}preprocess(r){return r}postprocess(r){return r}processAllTokens(r){return r}};er(zo,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var jo,Dl,ig,os=class{constructor(...r){Vm(this,jo);er(this,"defaults",Ol());er(this,"options",this.setOptions);er(this,"parse",ai(this,jo,Dl).call(this,to.lex,ro.parse));er(this,"parseInline",ai(this,jo,Dl).call(this,to.lexInline,ro.parseInline));er(this,"Parser",ro);er(this,"Renderer",xa);er(this,"TextRenderer",ns);er(this,"Lexer",to);er(this,"Tokenizer",ha);er(this,"Hooks",zo);this.use(...r)}walkTokens(r,t){var o,a;let n=[];for(let s of r)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(...r){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return r.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 xa(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 p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p||""}}o.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new ha(this.defaults);for(let s in n.tokenizer){if(!(s in a))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,d=n.tokenizer[i],l=a[i];a[i]=(...u)=>{let p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p}}o.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new zo;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];zo.passThroughHooks.has(s)?a[i]=u=>{if(this.defaults.async)return Promise.resolve(d.call(a,u)).then(f=>l.call(a,f));let p=d.call(a,u);return l.call(a,p)}:a[i]=(...u)=>{let p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p}}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(r){return this.defaults={...this.defaults,...r},this}lexer(r,t){return to.lex(r,t!=null?t:this.defaults)}parser(r,t){return ro.parse(r,t!=null?t:this.defaults)}};jo=new WeakSet,Dl=function(r,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=ai(this,jo,ig).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=>r(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=r(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)}}},ig=function(r,t){return n=>{if(n.message+=`
|
|
47
|
+
Please report this to https://github.com/markedjs/marked.`,r){let o="<p>An error occurred:</p><pre>"+un(n.message+"",!0)+"</pre>";return t?Promise.resolve(o):o}if(t)return Promise.reject(n);throw n}};var Vo=new os;function Jt(e,r){return Vo.parse(e,r)}Jt.options=Jt.setOptions=function(e){return Vo.setOptions(e),Jt.defaults=Vo.defaults,Ym(Jt.defaults),Jt};Jt.getDefaults=Ol;Jt.defaults=Go;Jt.use=function(...e){return Vo.use(...e),Jt.defaults=Vo.defaults,Ym(Jt.defaults),Jt};Jt.walkTokens=function(e,r){return Vo.walkTokens(e,r)};Jt.parseInline=Vo.parseInline;Jt.Parser=ro;Jt.parser=ro.parse;Jt.Renderer=xa;Jt.TextRenderer=ns;Jt.Lexer=to;Jt.lexer=to.lex;Jt.Tokenizer=ha;Jt.Hooks=zo;Jt.parse=Jt;var nw=Jt.options,ow=Jt.setOptions,aw=Jt.use,sw=Jt.walkTokens,iw=Jt.parseInline;var lw=ro.parse,dw=to.lex;var Ey=e=>{if(e)return e},is=e=>{var o,a;let r=e==null?void 0:e.markedOptions,t=new os({gfm:(o=r==null?void 0:r.gfm)!=null?o:!0,breaks:(a=r==null?void 0:r.breaks)!=null?a:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=Ey(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),s=>t.parse(s)},Xo=e=>e?is({markedOptions:e.options,renderer:e.renderer}):is(),My=is(),ql=e=>My(e),Jo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),dg=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),lg=e=>`%%FORM_PLACEHOLDER_${e}%%`,cg=(e,r)=>{let t=e;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=lg(r.length);return r.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=lg(r.length);return r.push({token:a,type:o}),a}),t},pg=e=>{let r=Xo(e);return t=>{let n=[],o=cg(t,n),a=r(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="${dg(i)}"></div>`;a=a.replace(d,u)}),a}},ug=e=>{let r=[],t=cg(e,r),n=ql(t);return r.forEach(({token:o,type:a})=>{let s=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${dg(a)}"></div>`;n=n.replace(s,d)}),n};var{entries:wg,setPrototypeOf:fg,isFrozen:Ly,getPrototypeOf:Py,getOwnPropertyDescriptor:Iy}=Object,{freeze:Gr,seal:wn,create:ui}=Object,{apply:Kl,construct:Yl}=typeof Reflect!="undefined"&&Reflect;Gr||(Gr=function(r){return r});wn||(wn=function(r){return r});Kl||(Kl=function(r,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 r.apply(t,o)});Yl||(Yl=function(r){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 r(...n)});var ci=Xr(Array.prototype.forEach),Ry=Xr(Array.prototype.lastIndexOf),mg=Xr(Array.prototype.pop),ls=Xr(Array.prototype.push),Hy=Xr(Array.prototype.splice),fi=Xr(String.prototype.toLowerCase),zl=Xr(String.prototype.toString),Vl=Xr(String.prototype.match),ds=Xr(String.prototype.replace),By=Xr(String.prototype.indexOf),Wy=Xr(String.prototype.trim),fn=Xr(Object.prototype.hasOwnProperty),jr=Xr(RegExp.prototype.test),cs=Dy(TypeError);function Xr(e){return function(r){r instanceof RegExp&&(r.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 Kl(e,r,n)}}function Dy(e){return function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return Yl(e,t)}}function At(e,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fi;fg&&fg(e,null);let n=r.length;for(;n--;){let o=r[n];if(typeof o=="string"){let a=t(o);a!==o&&(Ly(r)||(r[n]=a),o=a)}e[o]=!0}return e}function Oy(e){for(let r=0;r<e.length;r++)fn(e,r)||(e[r]=null);return e}function Un(e){let r=ui(null);for(let[t,n]of wg(e))fn(e,t)&&(Array.isArray(n)?r[t]=Oy(n):n&&typeof n=="object"&&n.constructor===Object?r[t]=Un(n):r[t]=n);return r}function ps(e,r){for(;e!==null;){let n=Iy(e,r);if(n){if(n.get)return Xr(n.get);if(typeof n.value=="function")return Xr(n.value)}e=Py(e)}function t(){return null}return t}var gg=Gr(["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"]),jl=Gr(["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"]),Gl=Gr(["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"]),Fy=Gr(["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"]),Xl=Gr(["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"]),Ny=Gr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),hg=Gr(["#text"]),xg=Gr(["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"]),Jl=Gr(["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"]),yg=Gr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),pi=Gr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_y=wn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),$y=wn(/<%[\w\W]*|[\w\W]*%>/gm),Uy=wn(/\$\{[\w\W]*/gm),qy=wn(/^data-[\-\w.\u00B7-\uFFFF]+$/),zy=wn(/^aria-[\-\w]+$/),vg=wn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vy=wn(/^(?:\w+script|data):/i),jy=wn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ag=wn(/^html$/i),Gy=wn(/^[a-z][.\w]*(-[.\w]+)+$/i),bg=Object.freeze({__proto__:null,ARIA_ATTR:zy,ATTR_WHITESPACE:jy,CUSTOM_ELEMENT:Gy,DATA_ATTR:qy,DOCTYPE_NAME:Ag,ERB_EXPR:$y,IS_ALLOWED_URI:vg,IS_SCRIPT_OR_DATA:Vy,MUSTACHE_EXPR:_y,TMPLIT_EXPR:Uy}),us={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Xy=function(){return typeof window=="undefined"?null:window},Jy=function(r,t){if(typeof r!="object"||typeof r.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 r.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Cg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Sg(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Xy(),r=Ie=>Sg(Ie);if(r.version="3.3.3",r.removed=[],!e||!e.document||e.document.nodeType!==us.document||!e.Element)return r.isSupported=!1,r;let{document:t}=e,n=t,o=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:i,Element:d,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:f,trustedTypes:m}=e,C=d.prototype,A=ps(C,"cloneNode"),k=ps(C,"remove"),T=ps(C,"nextSibling"),S=ps(C,"childNodes"),E=ps(C,"parentNode");if(typeof s=="function"){let Ie=t.createElement("template");Ie.content&&Ie.content.ownerDocument&&(t=Ie.content.ownerDocument)}let b,y="",{implementation:v,createNodeIterator:M,createDocumentFragment:B,getElementsByTagName:W}=t,{importNode:R}=n,H=Cg();r.isSupported=typeof wg=="function"&&typeof E=="function"&&v&&v.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:j,ERB_EXPR:oe,TMPLIT_EXPR:ue,DATA_ATTR:De,ARIA_ATTR:Xe,IS_SCRIPT_OR_DATA:xe,ATTR_WHITESPACE:ge,CUSTOM_ELEMENT:Le}=bg,{IS_ALLOWED_URI:Ge}=bg,Q=null,Se=At({},[...gg,...jl,...Gl,...Xl,...hg]),J=null,ce=At({},[...xg,...Jl,...yg,...pi]),pe=Object.seal(ui(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ie=null,Oe=null,Pe=Object.seal(ui(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),K=!0,_e=!0,$e=!1,Y=!0,G=!1,we=!0,ke=!1,ae=!1,ve=!1,ye=!1,Mt=!1,ne=!1,He=!0,fr=!1,Ot="user-content-",Yt=!0,Fr=!1,Ar={},F=null,le=At({},["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"]),Fe=null,Ke=At({},["audio","video","img","source","image","track"]),Ue=null,qe=At({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),nt="http://www.w3.org/1998/Math/MathML",Ct="http://www.w3.org/2000/svg",Pt="http://www.w3.org/1999/xhtml",$t=Pt,N=!1,de=null,Ee=At({},[nt,Ct,Pt],zl),ut=At({},["mi","mo","mn","ms","mtext"]),Ye=At({},["annotation-xml"]),Ut=At({},["title","style","font","a","script"]),or=null,It=["application/xhtml+xml","text/html"],St="text/html",rt=null,it=null,tr=t.createElement("form"),gn=function(L){return L instanceof RegExp||L instanceof Function},Rr=function(){let L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(it&&it===L)){if((!L||typeof L!="object")&&(L={}),L=Un(L),or=It.indexOf(L.PARSER_MEDIA_TYPE)===-1?St:L.PARSER_MEDIA_TYPE,rt=or==="application/xhtml+xml"?zl:fi,Q=fn(L,"ALLOWED_TAGS")?At({},L.ALLOWED_TAGS,rt):Se,J=fn(L,"ALLOWED_ATTR")?At({},L.ALLOWED_ATTR,rt):ce,de=fn(L,"ALLOWED_NAMESPACES")?At({},L.ALLOWED_NAMESPACES,zl):Ee,Ue=fn(L,"ADD_URI_SAFE_ATTR")?At(Un(qe),L.ADD_URI_SAFE_ATTR,rt):qe,Fe=fn(L,"ADD_DATA_URI_TAGS")?At(Un(Ke),L.ADD_DATA_URI_TAGS,rt):Ke,F=fn(L,"FORBID_CONTENTS")?At({},L.FORBID_CONTENTS,rt):le,ie=fn(L,"FORBID_TAGS")?At({},L.FORBID_TAGS,rt):Un({}),Oe=fn(L,"FORBID_ATTR")?At({},L.FORBID_ATTR,rt):Un({}),Ar=fn(L,"USE_PROFILES")?L.USE_PROFILES:!1,K=L.ALLOW_ARIA_ATTR!==!1,_e=L.ALLOW_DATA_ATTR!==!1,$e=L.ALLOW_UNKNOWN_PROTOCOLS||!1,Y=L.ALLOW_SELF_CLOSE_IN_ATTR!==!1,G=L.SAFE_FOR_TEMPLATES||!1,we=L.SAFE_FOR_XML!==!1,ke=L.WHOLE_DOCUMENT||!1,ye=L.RETURN_DOM||!1,Mt=L.RETURN_DOM_FRAGMENT||!1,ne=L.RETURN_TRUSTED_TYPE||!1,ve=L.FORCE_BODY||!1,He=L.SANITIZE_DOM!==!1,fr=L.SANITIZE_NAMED_PROPS||!1,Yt=L.KEEP_CONTENT!==!1,Fr=L.IN_PLACE||!1,Ge=L.ALLOWED_URI_REGEXP||vg,$t=L.NAMESPACE||Pt,ut=L.MATHML_TEXT_INTEGRATION_POINTS||ut,Ye=L.HTML_INTEGRATION_POINTS||Ye,pe=L.CUSTOM_ELEMENT_HANDLING||{},L.CUSTOM_ELEMENT_HANDLING&&gn(L.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(pe.tagNameCheck=L.CUSTOM_ELEMENT_HANDLING.tagNameCheck),L.CUSTOM_ELEMENT_HANDLING&&gn(L.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(pe.attributeNameCheck=L.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),L.CUSTOM_ELEMENT_HANDLING&&typeof L.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(pe.allowCustomizedBuiltInElements=L.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(_e=!1),Mt&&(ye=!0),Ar&&(Q=At({},hg),J=ui(null),Ar.html===!0&&(At(Q,gg),At(J,xg)),Ar.svg===!0&&(At(Q,jl),At(J,Jl),At(J,pi)),Ar.svgFilters===!0&&(At(Q,Gl),At(J,Jl),At(J,pi)),Ar.mathMl===!0&&(At(Q,Xl),At(J,yg),At(J,pi))),fn(L,"ADD_TAGS")||(Pe.tagCheck=null),fn(L,"ADD_ATTR")||(Pe.attributeCheck=null),L.ADD_TAGS&&(typeof L.ADD_TAGS=="function"?Pe.tagCheck=L.ADD_TAGS:(Q===Se&&(Q=Un(Q)),At(Q,L.ADD_TAGS,rt))),L.ADD_ATTR&&(typeof L.ADD_ATTR=="function"?Pe.attributeCheck=L.ADD_ATTR:(J===ce&&(J=Un(J)),At(J,L.ADD_ATTR,rt))),L.ADD_URI_SAFE_ATTR&&At(Ue,L.ADD_URI_SAFE_ATTR,rt),L.FORBID_CONTENTS&&(F===le&&(F=Un(F)),At(F,L.FORBID_CONTENTS,rt)),L.ADD_FORBID_CONTENTS&&(F===le&&(F=Un(F)),At(F,L.ADD_FORBID_CONTENTS,rt)),Yt&&(Q["#text"]=!0),ke&&At(Q,["html","head","body"]),Q.table&&(At(Q,["tbody"]),delete ie.tbody),L.TRUSTED_TYPES_POLICY){if(typeof L.TRUSTED_TYPES_POLICY.createHTML!="function")throw cs('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof L.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw cs('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=L.TRUSTED_TYPES_POLICY,y=b.createHTML("")}else b===void 0&&(b=Jy(m,o)),b!==null&&typeof y=="string"&&(y=b.createHTML(""));Gr&&Gr(L),it=L}},Tn=At({},[...jl,...Gl,...Fy]),Tt=At({},[...Xl,...Ny]),hn=function(L){let Z=E(L);(!Z||!Z.tagName)&&(Z={namespaceURI:$t,tagName:"template"});let se=fi(L.tagName),kt=fi(Z.tagName);return de[L.namespaceURI]?L.namespaceURI===Ct?Z.namespaceURI===Pt?se==="svg":Z.namespaceURI===nt?se==="svg"&&(kt==="annotation-xml"||ut[kt]):!!Tn[se]:L.namespaceURI===nt?Z.namespaceURI===Pt?se==="math":Z.namespaceURI===Ct?se==="math"&&Ye[kt]:!!Tt[se]:L.namespaceURI===Pt?Z.namespaceURI===Ct&&!Ye[kt]||Z.namespaceURI===nt&&!ut[kt]?!1:!Tt[se]&&(Ut[se]||!Tn[se]):!!(or==="application/xhtml+xml"&&de[L.namespaceURI]):!1},ur=function(L){ls(r.removed,{element:L});try{E(L).removeChild(L)}catch{k(L)}},Sr=function(L,Z){try{ls(r.removed,{attribute:Z.getAttributeNode(L),from:Z})}catch{ls(r.removed,{attribute:null,from:Z})}if(Z.removeAttribute(L),L==="is")if(ye||Mt)try{ur(Z)}catch{}else try{Z.setAttribute(L,"")}catch{}},Yr=function(L){let Z=null,se=null;if(ve)L="<remove></remove>"+L;else{let Bt=Vl(L,/^[\r\n\t ]+/);se=Bt&&Bt[0]}or==="application/xhtml+xml"&&$t===Pt&&(L='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+L+"</body></html>");let kt=b?b.createHTML(L):L;if($t===Pt)try{Z=new f().parseFromString(kt,or)}catch{}if(!Z||!Z.documentElement){Z=v.createDocument($t,"template",null);try{Z.documentElement.innerHTML=N?y:kt}catch{}}let qt=Z.body||Z.documentElement;return L&&se&&qt.insertBefore(t.createTextNode(se),qt.childNodes[0]||null),$t===Pt?W.call(Z,ke?"html":"body")[0]:ke?Z.documentElement:qt},xt=function(L){return M.call(L.ownerDocument||L,L,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},kn=function(L){return L instanceof p&&(typeof L.nodeName!="string"||typeof L.textContent!="string"||typeof L.removeChild!="function"||!(L.attributes instanceof u)||typeof L.removeAttribute!="function"||typeof L.setAttribute!="function"||typeof L.namespaceURI!="string"||typeof L.insertBefore!="function"||typeof L.hasChildNodes!="function")},nn=function(L){return typeof i=="function"&&L instanceof i};function Tr(Ie,L,Z){ci(Ie,se=>{se.call(r,L,Z,it)})}let kr=function(L){let Z=null;if(Tr(H.beforeSanitizeElements,L,null),kn(L))return ur(L),!0;let se=rt(L.nodeName);if(Tr(H.uponSanitizeElement,L,{tagName:se,allowedTags:Q}),we&&L.hasChildNodes()&&!nn(L.firstElementChild)&&jr(/<[/\w!]/g,L.innerHTML)&&jr(/<[/\w!]/g,L.textContent)||L.nodeType===us.progressingInstruction||we&&L.nodeType===us.comment&&jr(/<[/\w]/g,L.data))return ur(L),!0;if(!(Pe.tagCheck instanceof Function&&Pe.tagCheck(se))&&(!Q[se]||ie[se])){if(!ie[se]&&En(se)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,se)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(se)))return!1;if(Yt&&!F[se]){let kt=E(L)||L.parentNode,qt=S(L)||L.childNodes;if(qt&&kt){let Bt=qt.length;for(let ar=Bt-1;ar>=0;--ar){let xr=A(qt[ar],!0);xr.__removalCount=(L.__removalCount||0)+1,kt.insertBefore(xr,T(L))}}}return ur(L),!0}return L instanceof d&&!hn(L)||(se==="noscript"||se==="noembed"||se==="noframes")&&jr(/<\/no(script|embed|frames)/i,L.innerHTML)?(ur(L),!0):(G&&L.nodeType===us.text&&(Z=L.textContent,ci([j,oe,ue],kt=>{Z=ds(Z,kt," ")}),L.textContent!==Z&&(ls(r.removed,{element:L.cloneNode()}),L.textContent=Z)),Tr(H.afterSanitizeElements,L,null),!1)},Vn=function(L,Z,se){if(Oe[Z]||He&&(Z==="id"||Z==="name")&&(se in t||se in tr))return!1;if(!(_e&&!Oe[Z]&&jr(De,Z))){if(!(K&&jr(Xe,Z))){if(!(Pe.attributeCheck instanceof Function&&Pe.attributeCheck(Z,L))){if(!J[Z]||Oe[Z]){if(!(En(L)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,L)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(L))&&(pe.attributeNameCheck instanceof RegExp&&jr(pe.attributeNameCheck,Z)||pe.attributeNameCheck instanceof Function&&pe.attributeNameCheck(Z,L))||Z==="is"&&pe.allowCustomizedBuiltInElements&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,se)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(se))))return!1}else if(!Ue[Z]){if(!jr(Ge,ds(se,ge,""))){if(!((Z==="src"||Z==="xlink:href"||Z==="href")&&L!=="script"&&By(se,"data:")===0&&Fe[L])){if(!($e&&!jr(xe,ds(se,ge,"")))){if(se)return!1}}}}}}}return!0},En=function(L){return L!=="annotation-xml"&&Vl(L,Le)},xn=function(L){Tr(H.beforeSanitizeAttributes,L,null);let{attributes:Z}=L;if(!Z||kn(L))return;let se={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J,forceKeepAttr:void 0},kt=Z.length;for(;kt--;){let qt=Z[kt],{name:Bt,namespaceURI:ar,value:xr}=qt,Nr=rt(Bt),Er=xr,ot=Bt==="value"?Er:Wy(Er);if(se.attrName=Nr,se.attrValue=ot,se.keepAttr=!0,se.forceKeepAttr=void 0,Tr(H.uponSanitizeAttribute,L,se),ot=se.attrValue,fr&&(Nr==="id"||Nr==="name")&&(Sr(Bt,L),ot=Ot+ot),we&&jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,ot)){Sr(Bt,L);continue}if(Nr==="attributename"&&Vl(ot,"href")){Sr(Bt,L);continue}if(se.forceKeepAttr)continue;if(!se.keepAttr){Sr(Bt,L);continue}if(!Y&&jr(/\/>/i,ot)){Sr(Bt,L);continue}G&&ci([j,oe,ue],_r=>{ot=ds(ot,_r," ")});let wr=rt(L.nodeName);if(!Vn(wr,Nr,ot)){Sr(Bt,L);continue}if(b&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!ar)switch(m.getAttributeType(wr,Nr)){case"TrustedHTML":{ot=b.createHTML(ot);break}case"TrustedScriptURL":{ot=b.createScriptURL(ot);break}}if(ot!==Er)try{ar?L.setAttributeNS(ar,Bt,ot):L.setAttribute(Bt,ot),kn(L)?ur(L):mg(r.removed)}catch{Sr(Bt,L)}}Tr(H.afterSanitizeAttributes,L,null)},wt=function Ie(L){let Z=null,se=xt(L);for(Tr(H.beforeSanitizeShadowDOM,L,null);Z=se.nextNode();)Tr(H.uponSanitizeShadowNode,Z,null),kr(Z),xn(Z),Z.content instanceof a&&Ie(Z.content);Tr(H.afterSanitizeShadowDOM,L,null)};return r.sanitize=function(Ie){let L=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Z=null,se=null,kt=null,qt=null;if(N=!Ie,N&&(Ie="<!-->"),typeof Ie!="string"&&!nn(Ie))if(typeof Ie.toString=="function"){if(Ie=Ie.toString(),typeof Ie!="string")throw cs("dirty is not a string, aborting")}else throw cs("toString is not a function");if(!r.isSupported)return Ie;if(ae||Rr(L),r.removed=[],typeof Ie=="string"&&(Fr=!1),Fr){if(Ie.nodeName){let xr=rt(Ie.nodeName);if(!Q[xr]||ie[xr])throw cs("root node is forbidden and cannot be sanitized in-place")}}else if(Ie instanceof i)Z=Yr("<!---->"),se=Z.ownerDocument.importNode(Ie,!0),se.nodeType===us.element&&se.nodeName==="BODY"||se.nodeName==="HTML"?Z=se:Z.appendChild(se);else{if(!ye&&!G&&!ke&&Ie.indexOf("<")===-1)return b&&ne?b.createHTML(Ie):Ie;if(Z=Yr(Ie),!Z)return ye?null:ne?y:""}Z&&ve&&ur(Z.firstChild);let Bt=xt(Fr?Ie:Z);for(;kt=Bt.nextNode();)kr(kt),xn(kt),kt.content instanceof a&&wt(kt.content);if(Fr)return Ie;if(ye){if(Mt)for(qt=B.call(Z.ownerDocument);Z.firstChild;)qt.appendChild(Z.firstChild);else qt=Z;return(J.shadowroot||J.shadowrootmode)&&(qt=R.call(n,qt,!0)),qt}let ar=ke?Z.outerHTML:Z.innerHTML;return ke&&Q["!doctype"]&&Z.ownerDocument&&Z.ownerDocument.doctype&&Z.ownerDocument.doctype.name&&jr(Ag,Z.ownerDocument.doctype.name)&&(ar="<!DOCTYPE "+Z.ownerDocument.doctype.name+`>
|
|
48
|
+
`+ar),G&&ci([j,oe,ue],xr=>{ar=ds(ar,xr," ")}),b&&ne?b.createHTML(ar):ar},r.setConfig=function(){let Ie=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rr(Ie),ae=!0},r.clearConfig=function(){it=null,ae=!1},r.isValidAttribute=function(Ie,L,Z){it||Rr({});let se=rt(Ie),kt=rt(L);return Vn(se,kt,Z)},r.addHook=function(Ie,L){typeof L=="function"&&ls(H[Ie],L)},r.removeHook=function(Ie,L){if(L!==void 0){let Z=Ry(H[Ie],L);return Z===-1?void 0:Hy(H[Ie],Z,1)[0]}return mg(H[Ie])},r.removeHooks=function(Ie){H[Ie]=[]},r.removeAllHooks=function(){H=Cg()},r}var Tg=Sg();var Ky={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"]},Yy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ql=()=>{let e=Tg(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!Yy.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Ky)},ya=e=>e===!1?null:typeof e=="function"?e:Ql();var no=Bl(hi(),1),xi=e=>e.replace(/\\n/g,`
|
|
49
49
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ba=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},rb=e=>{var s,i;let r=(s=e.completedAt)!=null?s:Date.now(),t=(i=e.startedAt)!=null?i:r,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Eg=e=>e.status==="complete"?rb(e):e.status==="pending"?"Waiting":"",nb=e=>{var o,a,s;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((s=(a=e.startedAt)!=null?a:e.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 Mg=e=>e.status==="complete"?nb(e):"Using tool...",yi=e=>{let r=e/1e3;return r<.1?"<0.1s":r>=10?`${Math.round(r)}s`:`${r.toFixed(1).replace(/\.0$/,"")}s`},ms=e=>{var t,n,o;let r=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(n=e.startedAt)!=null?n:e.completedAt)!=null?o:Date.now()));return yi(r)},bi=e=>{var t,n,o;let r=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(n=e.startedAt)!=null?n:e.completedAt)!=null?o:Date.now()));return yi(r)},ed=(e,r,t)=>{var a;if(!r)return t;let n=((a=e.name)==null?void 0:a.trim())||"tool",o=ms(e);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Ci=(e,r)=>{let t=e.replace(/\{toolName\}/g,r),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=o.exec(t))!==null;)s.index>a&&fs(n,t.slice(a,s.index),[]),s[1]!==void 0?fs(n,s[1],["bold"]):s[2]!==void 0?fs(n,s[2],["italic"]):s[3]!==void 0&&fs(n,s[3],["dim"]),a=s.index+s[0].length;return a<t.length&&fs(n,t.slice(a),[]),n},fs=(e,r,t)=>{let n=r.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&e.push({text:n[o],styles:t}),o<n.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},ob=()=>{let e=null,r=0,t=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(o);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
50
50
|
`).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,`
|
|
51
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let a=t(n);return a!==null&&(e=a),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Ko=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},wi=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},vi=()=>{var r;let e=ob();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},Ai=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let o=(0,no.parse)(t,no.STR|no.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?xi(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=xi(o.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Lg=e=>{let r=null,t=0,o=e||(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:()=>r,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return r!==null?{text:r,raw:a}:null;try{let i=(0,no.parse)(a,no.STR|no.OBJ),d=o(i);d!==null&&(r=d)}catch{}return t=a.length,{text:r||"",raw:a}},close:()=>{}}},Si=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var Ti=class{constructor(r,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=r,this.gapTimeoutMs=t}push(r,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(r,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(r,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(r,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 ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:r,payload:t,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let r=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(r.payloadType,r.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 r=[...this.buffer.entries()].sort((t,n)=>t[0]-n[0]);for(let[t,n]of r)this.buffer.delete(t),this.emitter(n.payloadType,n.payload);r.length>0&&(this.nextExpectedSeq=r[r.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var ab="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com";function sb(e){var a,s;let r=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[r];if(n)return`attachment.${n}`;let o=r.indexOf("/");if(o>0){let i=(s=(a=r.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 td=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ib(e){switch(e){case"json":return Ai;case"regex-json":return vi;case"xml":return Si;default:return wi}}var Pg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lb(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let o=Pg(t);if(!Pg(n))return e;if(!o||n===t||n.startsWith(t))return r;let s=Ko(e);return Ko(r)!==null&&s===null?r:e}var Yo=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,o;this.apiUrl=(t=r.apiUrl)!=null?t:ab,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:ib(r.parserType),this.contextProviders=(o=r.contextProviders)!=null?o:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,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,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let r=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},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}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/client/feedback`}async sendFeedback(r){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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,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:r,comment:t})}async submitNPSFeedback(r,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:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var o,a,s,i;let n=new AbortController;r.signal&&r.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.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o);let f=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:f}),f}let l=await this.buildPayload(r.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,p={sessionId:d.sessionId,messages:r.messages.filter(td).map(f=>{var w,v,k;return{id:f.id,role:f.role,content:(k=(v=(w=f.contentParts)!=null?w:f.llmContent)!=null?v:f.rawContent)!=null?k:f.content}}),...r.assistantMessageId&&{assistantMessageId:r.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}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!m.ok){let f=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(m.status===429){let v=new Error(f.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let w=new Error(f.error||"Failed to send message");throw t({type:"error",error:w}),w}if(!m.body){let f=new Error("No response body received");throw t({type:"error",error:f}),f}t({type:"status",status:"connected"});try{await this.streamResponse(m.body,t,r.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(r.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(r.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,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var s;let o=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/agents/${r.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:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(r,t,n){var i,d;let a=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||ki}/resume`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(a,{method:"POST",headers:s,body:JSON.stringify({executionId:r,toolOutputs:t,streamResponse:(d=n==null?void 0:n.streamResponse)!=null?d:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(td).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,a)=>{let s=new Date(o.createdAt).getTime(),i=new Date(a.createdAt).getTime();return s-i}).map(o=>{var a,s,i;return{role:o.role,content:(i=(s=(a=o.contentParts)!=null?a:o.llmContent)!=null?s:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async a=>{try{let s=await a({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(o,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(o).length&&(n.context=o)}return n}async buildPayload(r){let n={messages:r.slice().filter(td).sort((o,a)=>{let s=new Date(o.createdAt).getTime(),i=new Date(a.createdAt).getTime();return s-i}).map(o=>{var a,s,i;return{role:o.role,content:(i=(s=(a=o.contentParts)!=null?a:o.llmContent)!=null?s:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async a=>{try{let s=await a({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(o,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(o).length&&(n.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...n},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return n}async handleCustomSSEEvent(r,t,n,o,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=u=>{let p={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=p,o(p),p},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(r,t,n){var Ot,Yt,Fr,Ar;let o=r.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=F=>{let le=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,Fe=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ke=F.tools?F.tools.map(Ue=>({...Ue,chunks:Ue.chunks?[...Ue.chunks]:void 0})):void 0;return{...F,reasoning:le,toolCall:Fe,tools:Ke}},p=F=>{t({type:"message",message:u(F)})},m=null,f={current:null},w={current:null},v=!1,k=new Map,T=new Map,A=new Map,E=new Map,b={lastId:null,byStep:new Map},h={lastId:null,byCall:new Map},S=(F,le,Fe="")=>`${F}::${le}::${Fe}`,L=(F,le)=>`${F}::${le}::`,O=(F,le,Fe,Ke)=>{let Ue=S(F,le,Fe),qe=A.get(Ue);if(qe)return qe;let nt=Fe?`-${Fe}`:"",Ct={id:`nested-${F}-${le}${nt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Fe?{partId:Fe}:{},agentMetadata:{executionId:Ke,parentToolId:F,parentStepId:le}};return A.set(Ue,Ct),p(Ct),Ct},H=F=>{if(F==null)return null;try{return String(F)}catch{return null}},R=F=>{var le,Fe,Ke,Ue,qe;return H((qe=(Ue=(Ke=(Fe=(le=F.stepId)!=null?le:F.step_id)!=null?Fe:F.step)!=null?Ke:F.parentId)!=null?Ue:F.flowStepId)!=null?qe:F.flow_step_id)},B=F=>{var le,Fe,Ke,Ue,qe,nt,Ct;return H((Ct=(nt=(qe=(Ue=(Ke=(Fe=(le=F.callId)!=null?le:F.call_id)!=null?Fe:F.requestId)!=null?Ke:F.request_id)!=null?Ue:F.toolCallId)!=null?qe:F.tool_call_id)!=null?nt:F.stepId)!=null?Ct:F.step_id)},j=n,oe=!1,ue=()=>{if(m)return m;let F;return!oe&&j?(F=j,oe=!0):j&&w.current?F=`${j}_${w.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(m),m},De=(F,le)=>{b.lastId=le,F&&b.byStep.set(F,le)},Xe=(F,le)=>{var qe;let Fe=(qe=F.reasoningId)!=null?qe:F.id,Ke=R(F);if(Fe){let nt=String(Fe);return De(Ke,nt),nt}if(Ke){let nt=b.byStep.get(Ke);if(nt)return b.lastId=nt,nt}if(b.lastId&&!le)return b.lastId;if(!le)return null;let Ue=`reason-${l()}`;return De(Ke,Ue),Ue},xe=F=>{let le=k.get(F);if(le)return le;let Fe={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return k.set(F,Fe),p(Fe),Fe},ge=(F,le)=>{h.lastId=le,F&&h.byCall.set(F,le)},Le=new Set,Ge=new Map,Q=new Set,Se=new Map,J=F=>{if(!F)return!1;let le=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return le==="emit_artifact_markdown"||le==="emit_artifact_component"},ce=(F,le)=>{var qe;let Fe=(qe=F.toolId)!=null?qe:F.id,Ke=B(F);if(Fe){let nt=String(Fe);return ge(Ke,nt),nt}if(Ke){let nt=h.byCall.get(Ke);if(nt)return h.lastId=nt,nt}if(h.lastId&&!le)return h.lastId;if(!le)return null;let Ue=`tool-${l()}`;return ge(Ke,Ue),Ue},pe=F=>{let le=T.get(F);if(le)return le;let Fe={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return T.set(F,Fe),p(Fe),Fe},ie=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let le=Number(F);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let Fe=Date.parse(F);if(!Number.isNaN(Fe))return Fe}return Date.now()},Oe=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Pe=new Map,K=new Map,_e=new Map,$e=new Map,Y=null,G=(F,le,Fe)=>{var Ct;let Ke=_e.get(F);Ke||(Ke=[],_e.set(F,Ke));let Ue=0,qe=Ke.length;for(;Ue<qe;){let Pt=Ue+qe>>>1;Ke[Pt].seq<le?Ue=Pt+1:qe=Pt}((Ct=Ke[Ue])==null?void 0:Ct.seq)===le?Ke[Ue]={seq:le,text:Fe}:Ke.splice(Ue,0,{seq:le,text:Fe});let nt="";for(let Pt=0;Pt<Ke.length;Pt++)nt+=Ke[Pt].text;return nt},we=(F,le)=>{let Fe=Oe(le),Ke=K.get(F.id),Ue=lb(Ke,Fe);F.rawContent=Ue;let qe=Pe.get(F.id),nt=de=>{var ut;let Ee=(ut=F.content)!=null?ut:"";de.trim()!==""&&(Ee.trim().length===0||de.startsWith(Ee)||de.trimStart().startsWith(Ee.trim()))&&(F.content=de)},Ct=()=>{var de;if(qe){let Ee=(de=qe.close)==null?void 0:de.call(qe);Ee instanceof Promise&&Ee.catch(()=>{})}Pe.delete(F.id),K.delete(F.id),F.streaming=!1,p(F)};if(!qe){nt(Fe),Ct();return}let Pt=Ko(Ue);if(Pt!==null&&Pt.trim()!==""){nt(Pt),Ct();return}let $t=de=>{var Ye;let Ee=typeof de=="string"?de:(Ye=de==null?void 0:de.text)!=null?Ye:null;if(Ee!==null&&Ee.trim()!=="")return Ee;let ut=qe.getExtractedText();return ut!==null&&ut.trim()!==""?ut:Fe},N;try{N=qe.processChunk(Ue)}catch{nt(Fe),Ct();return}if(N instanceof Promise){N.then(de=>{nt($t(de)),Ct()}).catch(()=>{nt(Fe),Ct()});return}nt($t(N)),Ct()},ke=[],ae=!1,ve,ye=()=>{ae||(ae=!0,queueMicrotask(()=>{ae=!1,ve()}))},Mt=new Ti((F,le)=>{ke.push({payloadType:F,payload:le}),ye()}),ne=null,He=new Map,fr=(Ot=this.config.iterationDisplay)!=null?Ot:"separate";for(ve=()=>{var F,le,Fe,Ke,Ue,qe,nt,Ct,Pt,$t,N,de,Ee,ut,Ye,Ut,or,It,St,rt,it,tr,gn,Rr,Tn,Tt,hn,ur,Sr,Yr,xt,kn,nn,Tr,kr,Vn,En,xn,wt,Ie,M,Z,se,kt,qt,Bt,ar,xr,Nr,Er,ot,wr,_r,po,jn,uo,Fn,on,Mn,vt,sr,ir,an,fo,yn,Ln,sn,q,he,ln,Pn,Nn,Oa,In,Rn,Hn,Gn,Ro,Ns,Fa,_s,la,bt,Na,bn,Qr,$s,Us,da,Xn,qs,Ho,_a,Jn,$a,mo,go,zs,Vs,Hl,Bo,ho,js,Ua,xo,Gs,qa,yo,za,Xs,Kn,Js,bo,Nt,ca,pa,Va,_n,Ks,ja,Ga,Xa,Ja,$r,dn,Yn,dt,Ka,Wo,Bn,Ys,ua,fa,Do,Co,Qs,Zs,Wn;for(let Qn=0;Qn<ke.length;Qn++){let Ze=ke[Qn].payloadType,P=ke[Qn].payload;if(Ze==="reason_start"){let z=(F=Xe(P,!0))!=null?F:`reason-${l()}`,I=xe(z);I.reasoning=(le=I.reasoning)!=null?le:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Ke=I.reasoning.startedAt)!=null?Ke:ie((Fe=P.startedAt)!=null?Fe:P.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ze==="reason_delta"||Ze==="reason_chunk"){let z=(qe=(Ue=Xe(P,!1))!=null?Ue:Xe(P,!0))!=null?qe:`reason-${l()}`,I=xe(z);I.reasoning=(nt=I.reasoning)!=null?nt:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Pt=I.reasoning.startedAt)!=null?Pt:ie((Ct=P.startedAt)!=null?Ct:P.timestamp);let V=(de=(N=($t=P.reasoningText)!=null?$t:P.text)!=null?N:P.delta)!=null?de:"";if(V&&P.hidden!==!0){let fe=typeof P.sequenceIndex=="number"?P.sequenceIndex:void 0;if(fe!==void 0){let te=G(z,fe,String(V));I.reasoning.chunks=[te]}else I.reasoning.chunks.push(String(V))}if(I.reasoning.status=P.done?"complete":"streaming",P.done){I.reasoning.completedAt=ie((Ee=P.completedAt)!=null?Ee:P.timestamp);let fe=(ut=I.reasoning.startedAt)!=null?ut:Date.now();I.reasoning.durationMs=Math.max(0,((Ye=I.reasoning.completedAt)!=null?Ye:Date.now())-fe)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ze==="reason_complete"){let z=(or=(Ut=Xe(P,!1))!=null?Ut:Xe(P,!0))!=null?or:`reason-${l()}`,I=k.get(z);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=ie((It=P.completedAt)!=null?It:P.timestamp);let fe=(St=I.reasoning.startedAt)!=null?St:Date.now();I.reasoning.durationMs=Math.max(0,((rt=I.reasoning.completedAt)!=null?rt:Date.now())-fe),I.streaming=!1,p(I)}let V=R(P);V&&b.byStep.delete(V)}else if(Ze==="tool_start"){let z=(it=ce(P,!0))!=null?it:`tool-${l()}`,I=(tr=P.toolName)!=null?tr:P.name;if(J(I)){Le.add(z);continue}let V=pe(z),fe=(gn=V.toolCall)!=null?gn:{id:z,status:"pending"};fe.name=I!=null?I:fe.name,fe.status="running",P.args!==void 0?fe.args=P.args:P.parameters!==void 0&&(fe.args=P.parameters),fe.startedAt=(Tn=fe.startedAt)!=null?Tn:ie((Rr=P.startedAt)!=null?Rr:P.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,V.toolCall=fe,V.streaming=!0;let te=P.agentContext;(te||P.executionId)&&(V.agentMetadata={executionId:(Tt=te==null?void 0:te.executionId)!=null?Tt:P.executionId,iteration:(hn=te==null?void 0:te.iteration)!=null?hn:P.iteration}),p(V)}else if(Ze==="tool_chunk"||Ze==="tool_delta"){let z=(Sr=(ur=ce(P,!1))!=null?ur:ce(P,!0))!=null?Sr:`tool-${l()}`;if(Le.has(z))continue;let I=pe(z),V=(Yr=I.toolCall)!=null?Yr:{id:z,status:"running"};V.startedAt=(kn=V.startedAt)!=null?kn:ie((xt=P.startedAt)!=null?xt:P.timestamp);let fe=(kr=(Tr=(nn=P.text)!=null?nn:P.delta)!=null?Tr:P.message)!=null?kr:"";fe&&(V.chunks=(Vn=V.chunks)!=null?Vn:[],V.chunks.push(String(fe))),V.status="running",I.toolCall=V,I.streaming=!0;let te=P.agentContext;(te||P.executionId)&&(I.agentMetadata=(wt=I.agentMetadata)!=null?wt:{executionId:(En=te==null?void 0:te.executionId)!=null?En:P.executionId,iteration:(xn=te==null?void 0:te.iteration)!=null?xn:P.iteration}),p(I)}else if(Ze==="tool_complete"){let z=(M=(Ie=ce(P,!1))!=null?Ie:ce(P,!0))!=null?M:`tool-${l()}`;if(Le.has(z)){Le.delete(z);continue}let I=pe(z),V=(Z=I.toolCall)!=null?Z:{id:z,status:"running"};V.status="complete",P.result!==void 0&&(V.result=P.result),typeof P.duration=="number"&&(V.duration=P.duration),V.completedAt=ie((se=P.completedAt)!=null?se:P.timestamp);let fe=(kt=P.duration)!=null?kt:P.executionTime;if(typeof fe=="number")V.durationMs=fe;else{let ze=(qt=V.startedAt)!=null?qt:Date.now();V.durationMs=Math.max(0,((Bt=V.completedAt)!=null?Bt:Date.now())-ze)}I.toolCall=V,I.streaming=!1;let te=P.agentContext;(te||P.executionId)&&(I.agentMetadata=(Nr=I.agentMetadata)!=null?Nr:{executionId:(ar=te==null?void 0:te.executionId)!=null?ar:P.executionId,iteration:(xr=te==null?void 0:te.iteration)!=null?xr:P.iteration}),p(I);let et=B(P);et&&h.byCall.delete(et)}else if(Ze==="step_await"&&P.awaitReason==="local_tool_required"&&P.toolName){let z=(Er=P.toolId)!=null?Er:`local-${l()}`,I=pe(z),V=(ot=I.toolCall)!=null?ot:{id:z,status:"pending"};V.name=P.toolName,V.args=P.parameters,V.status="complete",V.chunks=(wr=V.chunks)!=null?wr:[],V.startedAt=(po=V.startedAt)!=null?po:ie((_r=P.startedAt)!=null?_r:P.timestamp),V.completedAt=(jn=V.completedAt)!=null?jn:V.startedAt,I.toolCall=V,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:(Fn=P.executionId)!=null?Fn:(uo=I.agentMetadata)==null?void 0:uo.executionId,awaitingLocalTool:!0},p(I)}else if(Ze==="text_start"){if((on=P.toolContext)!=null&&on.toolId)continue;let z=P.partId;if(z!==void 0&&w.current!==null&&z!==w.current){let I=m;I&&(I.streaming=!1,p(I),Y=I,m=null,v=!0)}z!==void 0&&(w.current=z)}else if(Ze==="text_end"){if((Mn=P.toolContext)!=null&&Mn.toolId)continue;let z=m;z&&(z.streaming=!1,p(z),Y=z,m=null,v=!0)}else if(Ze==="step_chunk"||Ze==="step_delta"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let V=P.toolContext;if(V!=null&&V.toolId){let ze=String((sr=(vt=P.id)!=null?vt:V.stepId)!=null?sr:`step-${l()}`),ct=P.partId!==void 0&&P.partId!==null?String(P.partId):"",at=`${V.toolId}::${ze}`,_t=E.get(at);if(ct!==""&&_t!==void 0&&_t!==""&&_t!==ct){let Rt=A.get(S(V.toolId,ze,_t));Rt&&Rt.streaming!==!1&&(Rt.streaming=!1,p(Rt))}ct!==""&&E.set(at,ct);let Gt=O(V.toolId,ze,ct,V.executionId),lr=(yn=(fo=(an=(ir=P.text)!=null?ir:P.delta)!=null?an:P.content)!=null?fo:P.chunk)!=null?yn:"";lr&&(Gt.content+=String(lr),Gt.streaming=!0,p(Gt)),P.isComplete&&(Gt.streaming=!1,p(Gt));continue}let fe=P.partId;if(fe!==void 0&&w.current!==null&&fe!==w.current){let ze=m;ze&&(ze.streaming=!1,p(ze),Y=ze,m=null,v=!0)}fe!==void 0&&(w.current=fe);let te=fe!==void 0&&(Ln=$e.get(fe))!=null?Ln:ue();fe!==void 0&&(te.partId||(te.partId=fe),$e.set(fe,te));let et=(ln=(he=(q=(sn=P.text)!=null?sn:P.delta)!=null?q:P.content)!=null?he:P.chunk)!=null?ln:"";if(et){let ze=typeof P.seq=="number"?P.seq:void 0,ct=fe!=null?fe:te.id,at=ze!==void 0?G(ct,ze,String(et)):((Pn=K.get(te.id))!=null?Pn:"")+et;te.rawContent=at,Pe.has(te.id)||Pe.set(te.id,this.createStreamParser());let _t=Pe.get(te.id),Gt=at.trim().startsWith("{")||at.trim().startsWith("[");if(Gt&&K.set(te.id,at),_t.__isPlainTextParser===!0){te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te);continue}let Rt=_t.processChunk(at);if(Rt instanceof Promise)Rt.then(Lt=>{var Hr;let yr=typeof Lt=="string"?Lt:(Hr=Lt==null?void 0:Lt.text)!=null?Hr:null;if(yr!==null&&yr.trim()!=="")te.content=yr,p(te);else if(!Gt&&!at.trim().startsWith("<")){let Mr=m,dr=Mr&&Mr.id===te.id?Mr:te;dr.id===te.id&&(dr.content=ze!==void 0?at:dr.content+et,K.delete(dr.id),Pe.delete(dr.id),dr.rawContent=void 0,p(dr))}}).catch(()=>{te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te)});else{let Lt=typeof Rt=="string"?Rt:(Nn=Rt==null?void 0:Rt.text)!=null?Nn:null;Lt!==null&&Lt.trim()!==""?(te.content=Lt,p(te)):!Gt&&!at.trim().startsWith("<")&&(te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te))}}if(P.isComplete){let ze=(In=(Oa=P.result)==null?void 0:Oa.response)!=null?In:te.content;if(ze){let ct=K.get(te.id),at=ct!=null?ct:Oe(ze);te.rawContent=at;let _t=Pe.get(te.id),Gt=null,lr=!1;if(_t&&(Gt=_t.getExtractedText(),Gt===null&&(Gt=Ko(at)),Gt===null)){let Rt=_t.processChunk(at);Rt instanceof Promise?(lr=!0,Rt.then(Lt=>{var Hr;let yr=typeof Lt=="string"?Lt:(Hr=Lt==null?void 0:Lt.text)!=null?Hr:null;if(yr!==null){let Mr=m;Mr&&Mr.id===te.id&&(Mr.content=yr,Mr.streaming=!1,Pe.delete(Mr.id),K.delete(Mr.id),p(Mr))}})):Gt=typeof Rt=="string"?Rt:(Rn=Rt==null?void 0:Rt.text)!=null?Rn:null}if(!lr){Gt!==null&&Gt.trim()!==""?te.content=Gt:K.has(te.id)||(te.content=Oe(ze));let Rt=Pe.get(te.id);if(Rt){let Lt=(Hn=Rt.close)==null?void 0:Hn.call(Rt);Lt instanceof Promise&&Lt.catch(()=>{}),Pe.delete(te.id)}K.delete(te.id),te.streaming=!1,p(te)}}}}else if(Ze==="step_complete"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let V=P.toolContext;if(V!=null&&V.toolId){let ze=String((Ro=(Gn=P.id)!=null?Gn:V.stepId)!=null?Ro:"");if(ze){let ct=L(V.toolId,ze);for(let[at,_t]of A)at.startsWith(ct)&&_t.streaming!==!1&&(_t.streaming=!1,p(_t));E.delete(`${V.toolId}::${ze}`)}continue}let fe=P.stopReason;if(v){if(m!==null){let at=m;fe&&(at.stopReason=fe),Pe.delete(at.id),K.delete(at.id),at.streaming!==!1&&(at.streaming=!1,p(at))}let ze=(Ns=P.result)==null?void 0:Ns.response,ct=Y;ct&&(fe&&(ct.stopReason=fe),ze!=null?we(ct,ze):(Pe.delete(ct.id),K.delete(ct.id))),Y=null;continue}let te=(Fa=P.result)==null?void 0:Fa.response,et=ue();if(fe&&(et.stopReason=fe),te!=null){let ze=Pe.get(et.id),ct=!1,at=!1;if(ze){let _t=ze.getExtractedText(),Gt=K.get(et.id),lr=Gt!=null?Gt:Oe(te);if(et.rawContent=lr,_t!==null&&_t.trim()!=="")et.content=_t,ct=!0;else{let Rt=Ko(lr);if(Rt!==null)et.content=Rt,ct=!0;else{let Lt=ze.processChunk(lr);if(Lt instanceof Promise)at=!0,Lt.then(yr=>{var Mr;let Hr=typeof yr=="string"?yr:(Mr=yr==null?void 0:yr.text)!=null?Mr:null;if(Hr!==null&&Hr.trim()!==""){let dr=m;dr&&dr.id===et.id&&(dr.content=Hr,dr.streaming=!1,Pe.delete(dr.id),K.delete(dr.id),p(dr))}else{let dr=ze.getExtractedText(),vr=m;vr&&vr.id===et.id&&(dr!==null&&dr.trim()!==""?vr.content=dr:K.has(vr.id)||(vr.content=Oe(te)),vr.streaming=!1,Pe.delete(vr.id),K.delete(vr.id),p(vr))}});else{let yr=typeof Lt=="string"?Lt:(_s=Lt==null?void 0:Lt.text)!=null?_s:null;if(yr!==null&&yr.trim()!=="")et.content=yr,ct=!0;else{let Hr=ze.getExtractedText();Hr!==null&&Hr.trim()!==""&&(et.content=Hr,ct=!0)}}}}}if(!at){if(!et.rawContent){let _t=K.get(et.id);et.rawContent=_t!=null?_t:Oe(te)}if(!ct&&!K.has(et.id)&&(et.content=Oe(te)),ze){let _t=(la=ze.close)==null?void 0:la.call(ze);_t instanceof Promise&&_t.catch(()=>{})}Pe.delete(et.id),K.delete(et.id),et.streaming=!1,p(et)}}else Pe.delete(et.id),K.delete(et.id),et.streaming=!1,p(et)}else if(Ze==="flow_complete"){let z=(bt=P.result)==null?void 0:bt.response;if(v){if(m!==null){let I=m;Pe.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(z!=null){let I=ue(),V=K.get(I.id),fe=V!=null?V:Oe(z);I.rawContent=fe;let te=Oe(z),et=Pe.get(I.id);if(et){let at=Ko(fe);if(at!==null)te=at;else{let _t=et.processChunk(fe);_t instanceof Promise&&_t.then(lr=>{var Lt;let Rt=typeof lr=="string"?lr:(Lt=lr==null?void 0:lr.text)!=null?Lt:null;Rt!==null&&(I.content=Rt,I.streaming=!1,p(I))});let Gt=et.getExtractedText();Gt!==null&&(te=Gt)}}Pe.delete(I.id),K.delete(I.id);let ze=te!==I.content,ct=I.streaming!==!1;ze&&(I.content=te),I.streaming=!1,(ze||ct)&&p(I)}else if(m!==null){let I=m;Pe.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}t({type:"status",status:"idle"})}else if(Ze==="agent_start")ne={executionId:P.executionId,agentId:(Na=P.agentId)!=null?Na:"virtual",agentName:(bn=P.agentName)!=null?bn:"",status:"running",currentIteration:0,maxTurns:(Qr=P.maxTurns)!=null?Qr:1,startedAt:ie(P.startedAt)};else if(Ze==="agent_iteration_start"){if(ne&&(ne.currentIteration=P.iteration),fr==="separate"&&P.iteration>1){let z=m;z&&(z.streaming=!1,p(z),He.set(P.iteration-1,z),m=null)}}else if(Ze!=="agent_turn_start"){if(Ze==="agent_turn_delta"){if(P.contentType==="text"){let z=ue();z.content+=($s=P.delta)!=null?$s:"",z.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId,agentName:ne==null?void 0:ne.agentName},p(z)}else if(P.contentType==="thinking"){let z=(Us=P.turnId)!=null?Us:`agent-think-${P.iteration}`,I=xe(z);I.reasoning=(da=I.reasoning)!=null?da:{id:z,status:"streaming",chunks:[]},I.reasoning.chunks.push((Xn=P.delta)!=null?Xn:""),I.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId},p(I)}else if(P.contentType==="tool_input"){let z=(qs=P.toolCallId)!=null?qs:h.lastId;if(z){let I=T.get(z);I!=null&&I.toolCall&&(I.toolCall.chunks=(Ho=I.toolCall.chunks)!=null?Ho:[],I.toolCall.chunks.push((_a=P.delta)!=null?_a:""),p(I))}}}else if(Ze==="agent_turn_complete"){let z=P.turnId;if(z){let V=k.get(z);if(V!=null&&V.reasoning){V.reasoning.status="complete",V.reasoning.completedAt=ie(P.completedAt);let fe=(Jn=V.reasoning.startedAt)!=null?Jn:Date.now();V.reasoning.durationMs=Math.max(0,(($a=V.reasoning.completedAt)!=null?$a:Date.now())-fe),V.streaming=!1,p(V)}}let I=P.stopReason;if(I&&m!==null){let V=P.turnId;(!V||((mo=m.agentMetadata)==null?void 0:mo.turnId)===V)&&(m.stopReason=I,p(m))}}else if(Ze==="agent_tool_start"){let z=(go=P.toolCallId)!=null?go:`agent-tool-${l()}`;ge(B(P),z);let I=pe(z),V=(zs=I.toolCall)!=null?zs:{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};V.name=(Hl=(Vs=P.toolName)!=null?Vs:P.name)!=null?Hl:V.name,V.status="running",P.parameters!==void 0&&(V.args=P.parameters),V.startedAt=ie((Bo=P.startedAt)!=null?Bo:P.timestamp),I.toolCall=V,I.streaming=!0,I.agentMetadata={executionId:P.executionId,iteration:P.iteration},p(I)}else if(Ze==="agent_tool_delta"){let z=(ho=P.toolCallId)!=null?ho:h.lastId;if(z){let I=(js=T.get(z))!=null?js:pe(z);I.toolCall&&(I.toolCall.chunks=(Ua=I.toolCall.chunks)!=null?Ua:[],I.toolCall.chunks.push((xo=P.delta)!=null?xo:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ze==="agent_tool_complete"){let z=(Gs=P.toolCallId)!=null?Gs:h.lastId;if(z){let I=(qa=T.get(z))!=null?qa:pe(z);if(I.toolCall){I.toolCall.status="complete",P.result!==void 0&&(I.toolCall.result=P.result),typeof P.executionTime=="number"&&(I.toolCall.durationMs=P.executionTime),I.toolCall.completedAt=ie((yo=P.completedAt)!=null?yo:P.timestamp),I.streaming=!1,p(I);let V=B(P);V&&h.byCall.delete(V)}}}else if(Ze==="agent_media"){let z=Array.isArray(P.media)?P.media:[],I=[];for(let V of z){if(!V||typeof V!="object")continue;let fe=V,te=typeof fe.type=="string"?fe.type:void 0,et=typeof fe.mediaType=="string"?fe.mediaType.toLowerCase():"",ze=null,ct="";if(te==="media"){let at=typeof fe.data=="string"?fe.data:void 0;if(!at)continue;ct=et.length>0?et:"application/octet-stream",ze=`data:${ct};base64,${at}`}else if(te==="image-url"){let at=typeof fe.url=="string"?fe.url:void 0;if(!at)continue;ct=et,ze=at}else if(te==="file-url"){let at=typeof fe.url=="string"?fe.url:void 0;if(!at)continue;ct=et,ze=at}else continue;if(ze)if(te==="image-url"||ct.startsWith("image/"))I.push({type:"image",image:ze,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))I.push({type:"audio",audio:ze,mimeType:ct});else if(ct.startsWith("video/"))I.push({type:"video",video:ze,mimeType:ct});else{let at=ct||"application/octet-stream";I.push({type:"file",data:ze,mimeType:at,filename:sb(at)})}}if(I.length>0){let V=l(),fe=P.toolCallId,et={id:`agent-media-${typeof fe=="string"&&fe.length>0?`${fe}-${V}`:String(V)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:V,agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(et);let ze=m;ze&&(ze.streaming=!1,p(ze)),m=null,f.current=null}}else if(Ze!=="agent_iteration_complete"){if(Ze==="agent_reflection"||Ze==="agent_reflect"){let z=`agent-reflection-${P.executionId}-${P.iteration}`,I={id:z,role:"assistant",content:(za=P.reflection)!=null?za:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Xs=P.reflection)!=null?Xs:""]},agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(I)}else if(Ze==="agent_complete"){ne&&(ne.status=P.success?"complete":"error",ne.completedAt=ie(P.completedAt),ne.stopReason=P.stopReason);let z=m;z&&(z.streaming=!1,p(z)),t({type:"status",status:"idle"})}else if(Ze==="agent_error"){let z=typeof P.error=="string"?P.error:(Js=(Kn=P.error)==null?void 0:Kn.message)!=null?Js:"Agent execution error";P.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):t({type:"error",error:new Error(z)})}else if(Ze!=="agent_ping"){if(Ze==="agent_approval_start"){let z=(bo=P.approvalId)!=null?bo:`approval-${l()}`,I={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Nt=ne==null?void 0:ne.agentId)!=null?Nt:"virtual",executionId:(pa=(ca=P.executionId)!=null?ca:ne==null?void 0:ne.executionId)!=null?pa:"",toolName:(Va=P.toolName)!=null?Va:"",toolType:P.toolType,description:(Ks=P.description)!=null?Ks:`Execute ${(_n=P.toolName)!=null?_n:"tool"}`,parameters:P.parameters}};p(I)}else if(Ze==="step_await"&&P.awaitReason==="approval_required"){let z=(ja=P.approvalId)!=null?ja:`approval-${l()}`,I={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ga=ne==null?void 0:ne.agentId)!=null?Ga:"virtual",executionId:(Ja=(Xa=P.executionId)!=null?Xa:ne==null?void 0:ne.executionId)!=null?Ja:"",toolName:($r=P.toolName)!=null?$r:"",toolType:P.toolType,description:(Yn=P.description)!=null?Yn:`Execute ${(dn=P.toolName)!=null?dn:"tool"}`,parameters:P.parameters}};p(I)}else if(Ze==="agent_approval_complete"){let z=P.approvalId;if(z){let V={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(dt=P.decision)!=null?dt:"approved",agentId:(Ka=ne==null?void 0:ne.agentId)!=null?Ka:"virtual",executionId:(Bn=(Wo=P.executionId)!=null?Wo:ne==null?void 0:ne.executionId)!=null?Bn:"",toolName:(Ys=P.toolName)!=null?Ys:"",description:(ua=P.description)!=null?ua:"",resolvedAt:Date.now()}};p(V)}}else if(Ze==="artifact_start"||Ze==="artifact_delta"||Ze==="artifact_update"||Ze==="artifact_complete"){if(Ze==="artifact_start"){let z=P.artifactType,I=String(P.id),V=typeof P.title=="string"?P.title:void 0;if(t({type:"artifact_start",id:I,artifactType:z,title:V,component:typeof P.component=="string"?P.component:void 0}),Se.set(I,{markdown:"",title:V}),!Q.has(I)){Q.add(I);let fe={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:V,artifactType:z,status:"streaming"}})};Ge.set(I,fe),p(fe)}}else if(Ze==="artifact_delta"){let z=String(P.id),I=typeof P.delta=="string"?P.delta:String((fa=P.delta)!=null?fa:"");t({type:"artifact_delta",id:z,artDelta:I});let V=Se.get(z);V&&(V.markdown+=I)}else if(Ze==="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(Ze==="artifact_complete"){let z=String(P.id);t({type:"artifact_complete",id:z});let I=Ge.get(z);if(I){I.streaming=!1;try{let V=JSON.parse((Do=I.rawContent)!=null?Do:"{}");if(V.props){V.props.status="complete";let fe=Se.get(z);fe!=null&&fe.markdown&&(V.props.markdown=fe.markdown)}I.rawContent=JSON.stringify(V)}catch{}Se.delete(z),p(I),Ge.delete(z)}}}else if(Ze==="transcript_insert"){let z=P.message;if(!z||typeof z!="object")continue;let I=String((Co=z.id)!=null?Co:`msg-${l()}`),V=z.role,te={id:I,role:V==="user"?"user":V==="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(te),te.rawContent)try{let et=JSON.parse(te.rawContent),ze=(Qs=et==null?void 0:et.props)==null?void 0:Qs.artifactId;typeof ze=="string"&&Q.add(ze)}catch{}m=null,f.current=null,Pe.delete(I),K.delete(I)}else if(Ze==="error"||Ze==="step_error"||Ze==="dispatch_error"||Ze==="flow_error"){let z=null;if(P.error instanceof Error)z=P.error;else if(Ze==="dispatch_error"){let I=(Zs=P.message)!=null?Zs:P.error;I!=null&&I!==""&&(z=new Error(String(I)))}else if(Ze==="step_error"||Ze==="flow_error"){let I=P.error;typeof I=="string"&&I!==""?z=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(z=new Error(String((Wn=I.message)!=null?Wn:I)))}else Ze==="error"&&P.error!=null&&P.error!==""&&(z=new Error(String(P.error)));if(z){t({type:"error",error:z});let I=m;I&&I.streaming&&(I.streaming=!1,p(I)),t({type:"status",status:"idle"})}}}}}}ke.length=0};;){let{done:F,value:le}=await o.read();if(F)break;s+=a.decode(le,{stream:!0});let Fe=s.split(`
|
|
51
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let a=t(n);return a!==null&&(e=a),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Ko=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},wi=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},vi=()=>{var r;let e=ob();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},Ai=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let o=(0,no.parse)(t,no.STR|no.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?xi(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=xi(o.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Lg=e=>{let r=null,t=0,o=e||(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:()=>r,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return r!==null?{text:r,raw:a}:null;try{let i=(0,no.parse)(a,no.STR|no.OBJ),d=o(i);d!==null&&(r=d)}catch{}return t=a.length,{text:r||"",raw:a}},close:()=>{}}},Si=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var Ti=class{constructor(r,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=r,this.gapTimeoutMs=t}push(r,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(r,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(r,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(r,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 ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:r,payload:t,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let r=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(r.payloadType,r.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 r=[...this.buffer.entries()].sort((t,n)=>t[0]-n[0]);for(let[t,n]of r)this.buffer.delete(t),this.emitter(n.payloadType,n.payload);r.length>0&&(this.nextExpectedSeq=r[r.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var ab="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com";function sb(e){var a,s;let r=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[r];if(n)return`attachment.${n}`;let o=r.indexOf("/");if(o>0){let i=(s=(a=r.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 td=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ib(e){switch(e){case"json":return Ai;case"regex-json":return vi;case"xml":return Si;default:return wi}}var Pg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lb(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let o=Pg(t);if(!Pg(n))return e;if(!o||n===t||n.startsWith(t))return r;let s=Ko(e);return Ko(r)!==null&&s===null?r:e}var Yo=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,o;this.apiUrl=(t=r.apiUrl)!=null?t:ab,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:ib(r.parserType),this.contextProviders=(o=r.contextProviders)!=null?o:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,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,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let r=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},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}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/client/feedback`}async sendFeedback(r){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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,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:r,comment:t})}async submitNPSFeedback(r,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:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var o,a,s,i;let n=new AbortController;r.signal&&r.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.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let l=await this.buildPayload(r.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:r.messages.filter(td).map(m=>{var C,A,k;return{id:m.id,role:m.role,content:(k=(A=(C=m.contentParts)!=null?C:m.llmContent)!=null?A:m.rawContent)!=null?k:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.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}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s);let A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(f.status===429){let A=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(r.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(r.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,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var s;let o=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/agents/${r.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:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(r,t,n){var i,d;let a=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||ki}/resume`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(a,{method:"POST",headers:s,body:JSON.stringify({executionId:r,toolOutputs:t,streamResponse:(d=n==null?void 0:n.streamResponse)!=null?d:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(td).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,a)=>{let s=new Date(o.createdAt).getTime(),i=new Date(a.createdAt).getTime();return s-i}).map(o=>{var a,s,i;return{role:o.role,content:(i=(s=(a=o.contentParts)!=null?a:o.llmContent)!=null?s:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async a=>{try{let s=await a({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(o,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(o).length&&(n.context=o)}return n}async buildPayload(r){let n={messages:r.slice().filter(td).sort((o,a)=>{let s=new Date(o.createdAt).getTime(),i=new Date(a.createdAt).getTime();return s-i}).map(o=>{var a,s,i;return{role:o.role,content:(i=(s=(a=o.contentParts)!=null?a:o.llmContent)!=null?s:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async a=>{try{let s=await a({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(o,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(o).length&&(n.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...n},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return n}async handleCustomSSEEvent(r,t,n,o,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=u=>{let p={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=p,o(p),p},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(r,t,n){var Ot,Yt,Fr,Ar;let o=r.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=F=>{let le=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,Fe=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ke=F.tools?F.tools.map(Ue=>({...Ue,chunks:Ue.chunks?[...Ue.chunks]:void 0})):void 0;return{...F,reasoning:le,toolCall:Fe,tools:Ke}},p=F=>{t({type:"message",message:u(F)})},f=null,m={current:null},C={current:null},A=!1,k=new Map,T=new Map,S=new Map,E=new Map,b={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},v=(F,le,Fe="")=>`${F}::${le}::${Fe}`,M=(F,le)=>`${F}::${le}::`,B=(F,le,Fe,Ke)=>{let Ue=v(F,le,Fe),qe=S.get(Ue);if(qe)return qe;let nt=Fe?`-${Fe}`:"",Ct={id:`nested-${F}-${le}${nt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Fe?{partId:Fe}:{},agentMetadata:{executionId:Ke,parentToolId:F,parentStepId:le}};return S.set(Ue,Ct),p(Ct),Ct},W=F=>{if(F==null)return null;try{return String(F)}catch{return null}},R=F=>{var le,Fe,Ke,Ue,qe;return W((qe=(Ue=(Ke=(Fe=(le=F.stepId)!=null?le:F.step_id)!=null?Fe:F.step)!=null?Ke:F.parentId)!=null?Ue:F.flowStepId)!=null?qe:F.flow_step_id)},H=F=>{var le,Fe,Ke,Ue,qe,nt,Ct;return W((Ct=(nt=(qe=(Ue=(Ke=(Fe=(le=F.callId)!=null?le:F.call_id)!=null?Fe:F.requestId)!=null?Ke:F.request_id)!=null?Ue:F.toolCallId)!=null?qe:F.tool_call_id)!=null?nt:F.stepId)!=null?Ct:F.step_id)},j=n,oe=!1,ue=()=>{if(f)return f;let F;return!oe&&j?(F=j,oe=!0):j&&C.current?F=`${j}_${C.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,le)=>{b.lastId=le,F&&b.byStep.set(F,le)},Xe=(F,le)=>{var qe;let Fe=(qe=F.reasoningId)!=null?qe:F.id,Ke=R(F);if(Fe){let nt=String(Fe);return De(Ke,nt),nt}if(Ke){let nt=b.byStep.get(Ke);if(nt)return b.lastId=nt,nt}if(b.lastId&&!le)return b.lastId;if(!le)return null;let Ue=`reason-${l()}`;return De(Ke,Ue),Ue},xe=F=>{let le=k.get(F);if(le)return le;let Fe={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return k.set(F,Fe),p(Fe),Fe},ge=(F,le)=>{y.lastId=le,F&&y.byCall.set(F,le)},Le=new Set,Ge=new Map,Q=new Set,Se=new Map,J=F=>{if(!F)return!1;let le=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return le==="emit_artifact_markdown"||le==="emit_artifact_component"},ce=(F,le)=>{var qe;let Fe=(qe=F.toolId)!=null?qe:F.id,Ke=H(F);if(Fe){let nt=String(Fe);return ge(Ke,nt),nt}if(Ke){let nt=y.byCall.get(Ke);if(nt)return y.lastId=nt,nt}if(y.lastId&&!le)return y.lastId;if(!le)return null;let Ue=`tool-${l()}`;return ge(Ke,Ue),Ue},pe=F=>{let le=T.get(F);if(le)return le;let Fe={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return T.set(F,Fe),p(Fe),Fe},ie=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let le=Number(F);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let Fe=Date.parse(F);if(!Number.isNaN(Fe))return Fe}return Date.now()},Oe=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Pe=new Map,K=new Map,_e=new Map,$e=new Map,Y=null,G=(F,le,Fe)=>{var Ct;let Ke=_e.get(F);Ke||(Ke=[],_e.set(F,Ke));let Ue=0,qe=Ke.length;for(;Ue<qe;){let Pt=Ue+qe>>>1;Ke[Pt].seq<le?Ue=Pt+1:qe=Pt}((Ct=Ke[Ue])==null?void 0:Ct.seq)===le?Ke[Ue]={seq:le,text:Fe}:Ke.splice(Ue,0,{seq:le,text:Fe});let nt="";for(let Pt=0;Pt<Ke.length;Pt++)nt+=Ke[Pt].text;return nt},we=(F,le)=>{let Fe=Oe(le),Ke=K.get(F.id),Ue=lb(Ke,Fe);F.rawContent=Ue;let qe=Pe.get(F.id),nt=de=>{var ut;let Ee=(ut=F.content)!=null?ut:"";de.trim()!==""&&(Ee.trim().length===0||de.startsWith(Ee)||de.trimStart().startsWith(Ee.trim()))&&(F.content=de)},Ct=()=>{var de;if(qe){let Ee=(de=qe.close)==null?void 0:de.call(qe);Ee instanceof Promise&&Ee.catch(()=>{})}Pe.delete(F.id),K.delete(F.id),F.streaming=!1,p(F)};if(!qe){nt(Fe),Ct();return}let Pt=Ko(Ue);if(Pt!==null&&Pt.trim()!==""){nt(Pt),Ct();return}let $t=de=>{var Ye;let Ee=typeof de=="string"?de:(Ye=de==null?void 0:de.text)!=null?Ye:null;if(Ee!==null&&Ee.trim()!=="")return Ee;let ut=qe.getExtractedText();return ut!==null&&ut.trim()!==""?ut:Fe},N;try{N=qe.processChunk(Ue)}catch{nt(Fe),Ct();return}if(N instanceof Promise){N.then(de=>{nt($t(de)),Ct()}).catch(()=>{nt(Fe),Ct()});return}nt($t(N)),Ct()},ke=[],ae=!1,ve,ye=()=>{ae||(ae=!0,queueMicrotask(()=>{ae=!1,ve()}))},Mt=new Ti((F,le)=>{ke.push({payloadType:F,payload:le}),ye()}),ne=null,He=new Map,fr=(Ot=this.config.iterationDisplay)!=null?Ot:"separate";for(ve=()=>{var F,le,Fe,Ke,Ue,qe,nt,Ct,Pt,$t,N,de,Ee,ut,Ye,Ut,or,It,St,rt,it,tr,gn,Rr,Tn,Tt,hn,ur,Sr,Yr,xt,kn,nn,Tr,kr,Vn,En,xn,wt,Ie,L,Z,se,kt,qt,Bt,ar,xr,Nr,Er,ot,wr,_r,po,jn,uo,Fn,on,Mn,vt,sr,ir,an,fo,yn,Ln,sn,q,he,ln,Pn,Nn,Oa,In,Rn,Hn,Gn,Ro,Ns,Fa,_s,la,bt,Na,bn,Qr,$s,Us,da,Xn,qs,Ho,_a,Jn,$a,mo,go,zs,Vs,Hl,Bo,ho,js,Ua,xo,Gs,qa,yo,za,Xs,Kn,Js,bo,Nt,ca,pa,Va,_n,Ks,ja,Ga,Xa,Ja,$r,dn,Yn,dt,Ka,Wo,Bn,Ys,ua,fa,Do,Co,Qs,Zs,Wn;for(let Qn=0;Qn<ke.length;Qn++){let Ze=ke[Qn].payloadType,P=ke[Qn].payload;if(Ze==="reason_start"){let z=(F=Xe(P,!0))!=null?F:`reason-${l()}`,I=xe(z);I.reasoning=(le=I.reasoning)!=null?le:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Ke=I.reasoning.startedAt)!=null?Ke:ie((Fe=P.startedAt)!=null?Fe:P.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ze==="reason_delta"||Ze==="reason_chunk"){let z=(qe=(Ue=Xe(P,!1))!=null?Ue:Xe(P,!0))!=null?qe:`reason-${l()}`,I=xe(z);I.reasoning=(nt=I.reasoning)!=null?nt:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Pt=I.reasoning.startedAt)!=null?Pt:ie((Ct=P.startedAt)!=null?Ct:P.timestamp);let V=(de=(N=($t=P.reasoningText)!=null?$t:P.text)!=null?N:P.delta)!=null?de:"";if(V&&P.hidden!==!0){let fe=typeof P.sequenceIndex=="number"?P.sequenceIndex:void 0;if(fe!==void 0){let te=G(z,fe,String(V));I.reasoning.chunks=[te]}else I.reasoning.chunks.push(String(V))}if(I.reasoning.status=P.done?"complete":"streaming",P.done){I.reasoning.completedAt=ie((Ee=P.completedAt)!=null?Ee:P.timestamp);let fe=(ut=I.reasoning.startedAt)!=null?ut:Date.now();I.reasoning.durationMs=Math.max(0,((Ye=I.reasoning.completedAt)!=null?Ye:Date.now())-fe)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ze==="reason_complete"){let z=(or=(Ut=Xe(P,!1))!=null?Ut:Xe(P,!0))!=null?or:`reason-${l()}`,I=k.get(z);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=ie((It=P.completedAt)!=null?It:P.timestamp);let fe=(St=I.reasoning.startedAt)!=null?St:Date.now();I.reasoning.durationMs=Math.max(0,((rt=I.reasoning.completedAt)!=null?rt:Date.now())-fe),I.streaming=!1,p(I)}let V=R(P);V&&b.byStep.delete(V)}else if(Ze==="tool_start"){let z=(it=ce(P,!0))!=null?it:`tool-${l()}`,I=(tr=P.toolName)!=null?tr:P.name;if(J(I)){Le.add(z);continue}let V=pe(z),fe=(gn=V.toolCall)!=null?gn:{id:z,status:"pending"};fe.name=I!=null?I:fe.name,fe.status="running",P.args!==void 0?fe.args=P.args:P.parameters!==void 0&&(fe.args=P.parameters),fe.startedAt=(Tn=fe.startedAt)!=null?Tn:ie((Rr=P.startedAt)!=null?Rr:P.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,V.toolCall=fe,V.streaming=!0;let te=P.agentContext;(te||P.executionId)&&(V.agentMetadata={executionId:(Tt=te==null?void 0:te.executionId)!=null?Tt:P.executionId,iteration:(hn=te==null?void 0:te.iteration)!=null?hn:P.iteration}),p(V)}else if(Ze==="tool_chunk"||Ze==="tool_delta"){let z=(Sr=(ur=ce(P,!1))!=null?ur:ce(P,!0))!=null?Sr:`tool-${l()}`;if(Le.has(z))continue;let I=pe(z),V=(Yr=I.toolCall)!=null?Yr:{id:z,status:"running"};V.startedAt=(kn=V.startedAt)!=null?kn:ie((xt=P.startedAt)!=null?xt:P.timestamp);let fe=(kr=(Tr=(nn=P.text)!=null?nn:P.delta)!=null?Tr:P.message)!=null?kr:"";fe&&(V.chunks=(Vn=V.chunks)!=null?Vn:[],V.chunks.push(String(fe))),V.status="running",I.toolCall=V,I.streaming=!0;let te=P.agentContext;(te||P.executionId)&&(I.agentMetadata=(wt=I.agentMetadata)!=null?wt:{executionId:(En=te==null?void 0:te.executionId)!=null?En:P.executionId,iteration:(xn=te==null?void 0:te.iteration)!=null?xn:P.iteration}),p(I)}else if(Ze==="tool_complete"){let z=(L=(Ie=ce(P,!1))!=null?Ie:ce(P,!0))!=null?L:`tool-${l()}`;if(Le.has(z)){Le.delete(z);continue}let I=pe(z),V=(Z=I.toolCall)!=null?Z:{id:z,status:"running"};V.status="complete",P.result!==void 0&&(V.result=P.result),typeof P.duration=="number"&&(V.duration=P.duration),V.completedAt=ie((se=P.completedAt)!=null?se:P.timestamp);let fe=(kt=P.duration)!=null?kt:P.executionTime;if(typeof fe=="number")V.durationMs=fe;else{let ze=(qt=V.startedAt)!=null?qt:Date.now();V.durationMs=Math.max(0,((Bt=V.completedAt)!=null?Bt:Date.now())-ze)}I.toolCall=V,I.streaming=!1;let te=P.agentContext;(te||P.executionId)&&(I.agentMetadata=(Nr=I.agentMetadata)!=null?Nr:{executionId:(ar=te==null?void 0:te.executionId)!=null?ar:P.executionId,iteration:(xr=te==null?void 0:te.iteration)!=null?xr:P.iteration}),p(I);let et=H(P);et&&y.byCall.delete(et)}else if(Ze==="step_await"&&P.awaitReason==="local_tool_required"&&P.toolName){let z=(Er=P.toolId)!=null?Er:`local-${l()}`,I=pe(z),V=(ot=I.toolCall)!=null?ot:{id:z,status:"pending"};V.name=P.toolName,V.args=P.parameters,V.status="complete",V.chunks=(wr=V.chunks)!=null?wr:[],V.startedAt=(po=V.startedAt)!=null?po:ie((_r=P.startedAt)!=null?_r:P.timestamp),V.completedAt=(jn=V.completedAt)!=null?jn:V.startedAt,I.toolCall=V,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:(Fn=P.executionId)!=null?Fn:(uo=I.agentMetadata)==null?void 0:uo.executionId,awaitingLocalTool:!0},p(I)}else if(Ze==="text_start"){if((on=P.toolContext)!=null&&on.toolId)continue;let z=P.partId;if(z!==void 0&&C.current!==null&&z!==C.current){let I=f;I&&(I.streaming=!1,p(I),Y=I,f=null,A=!0)}z!==void 0&&(C.current=z)}else if(Ze==="text_end"){if((Mn=P.toolContext)!=null&&Mn.toolId)continue;let z=f;z&&(z.streaming=!1,p(z),Y=z,f=null,A=!0)}else if(Ze==="step_chunk"||Ze==="step_delta"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let V=P.toolContext;if(V!=null&&V.toolId){let ze=String((sr=(vt=P.id)!=null?vt:V.stepId)!=null?sr:`step-${l()}`),ct=P.partId!==void 0&&P.partId!==null?String(P.partId):"",at=`${V.toolId}::${ze}`,_t=E.get(at);if(ct!==""&&_t!==void 0&&_t!==""&&_t!==ct){let Rt=S.get(v(V.toolId,ze,_t));Rt&&Rt.streaming!==!1&&(Rt.streaming=!1,p(Rt))}ct!==""&&E.set(at,ct);let Gt=B(V.toolId,ze,ct,V.executionId),lr=(yn=(fo=(an=(ir=P.text)!=null?ir:P.delta)!=null?an:P.content)!=null?fo:P.chunk)!=null?yn:"";lr&&(Gt.content+=String(lr),Gt.streaming=!0,p(Gt)),P.isComplete&&(Gt.streaming=!1,p(Gt));continue}let fe=P.partId;if(fe!==void 0&&C.current!==null&&fe!==C.current){let ze=f;ze&&(ze.streaming=!1,p(ze),Y=ze,f=null,A=!0)}fe!==void 0&&(C.current=fe);let te=fe!==void 0&&(Ln=$e.get(fe))!=null?Ln:ue();fe!==void 0&&(te.partId||(te.partId=fe),$e.set(fe,te));let et=(ln=(he=(q=(sn=P.text)!=null?sn:P.delta)!=null?q:P.content)!=null?he:P.chunk)!=null?ln:"";if(et){let ze=typeof P.seq=="number"?P.seq:void 0,ct=fe!=null?fe:te.id,at=ze!==void 0?G(ct,ze,String(et)):((Pn=K.get(te.id))!=null?Pn:"")+et;te.rawContent=at,Pe.has(te.id)||Pe.set(te.id,this.createStreamParser());let _t=Pe.get(te.id),Gt=at.trim().startsWith("{")||at.trim().startsWith("[");if(Gt&&K.set(te.id,at),_t.__isPlainTextParser===!0){te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te);continue}let Rt=_t.processChunk(at);if(Rt instanceof Promise)Rt.then(Lt=>{var Hr;let yr=typeof Lt=="string"?Lt:(Hr=Lt==null?void 0:Lt.text)!=null?Hr:null;if(yr!==null&&yr.trim()!=="")te.content=yr,p(te);else if(!Gt&&!at.trim().startsWith("<")){let Mr=f,dr=Mr&&Mr.id===te.id?Mr:te;dr.id===te.id&&(dr.content=ze!==void 0?at:dr.content+et,K.delete(dr.id),Pe.delete(dr.id),dr.rawContent=void 0,p(dr))}}).catch(()=>{te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te)});else{let Lt=typeof Rt=="string"?Rt:(Nn=Rt==null?void 0:Rt.text)!=null?Nn:null;Lt!==null&&Lt.trim()!==""?(te.content=Lt,p(te)):!Gt&&!at.trim().startsWith("<")&&(te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te))}}if(P.isComplete){let ze=(In=(Oa=P.result)==null?void 0:Oa.response)!=null?In:te.content;if(ze){let ct=K.get(te.id),at=ct!=null?ct:Oe(ze);te.rawContent=at;let _t=Pe.get(te.id),Gt=null,lr=!1;if(_t&&(Gt=_t.getExtractedText(),Gt===null&&(Gt=Ko(at)),Gt===null)){let Rt=_t.processChunk(at);Rt instanceof Promise?(lr=!0,Rt.then(Lt=>{var Hr;let yr=typeof Lt=="string"?Lt:(Hr=Lt==null?void 0:Lt.text)!=null?Hr:null;if(yr!==null){let Mr=f;Mr&&Mr.id===te.id&&(Mr.content=yr,Mr.streaming=!1,Pe.delete(Mr.id),K.delete(Mr.id),p(Mr))}})):Gt=typeof Rt=="string"?Rt:(Rn=Rt==null?void 0:Rt.text)!=null?Rn:null}if(!lr){Gt!==null&&Gt.trim()!==""?te.content=Gt:K.has(te.id)||(te.content=Oe(ze));let Rt=Pe.get(te.id);if(Rt){let Lt=(Hn=Rt.close)==null?void 0:Hn.call(Rt);Lt instanceof Promise&&Lt.catch(()=>{}),Pe.delete(te.id)}K.delete(te.id),te.streaming=!1,p(te)}}}}else if(Ze==="step_complete"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let V=P.toolContext;if(V!=null&&V.toolId){let ze=String((Ro=(Gn=P.id)!=null?Gn:V.stepId)!=null?Ro:"");if(ze){let ct=M(V.toolId,ze);for(let[at,_t]of S)at.startsWith(ct)&&_t.streaming!==!1&&(_t.streaming=!1,p(_t));E.delete(`${V.toolId}::${ze}`)}continue}let fe=P.stopReason;if(A){if(f!==null){let at=f;fe&&(at.stopReason=fe),Pe.delete(at.id),K.delete(at.id),at.streaming!==!1&&(at.streaming=!1,p(at))}let ze=(Ns=P.result)==null?void 0:Ns.response,ct=Y;ct&&(fe&&(ct.stopReason=fe),ze!=null?we(ct,ze):(Pe.delete(ct.id),K.delete(ct.id))),Y=null;continue}let te=(Fa=P.result)==null?void 0:Fa.response,et=ue();if(fe&&(et.stopReason=fe),te!=null){let ze=Pe.get(et.id),ct=!1,at=!1;if(ze){let _t=ze.getExtractedText(),Gt=K.get(et.id),lr=Gt!=null?Gt:Oe(te);if(et.rawContent=lr,_t!==null&&_t.trim()!=="")et.content=_t,ct=!0;else{let Rt=Ko(lr);if(Rt!==null)et.content=Rt,ct=!0;else{let Lt=ze.processChunk(lr);if(Lt instanceof Promise)at=!0,Lt.then(yr=>{var Mr;let Hr=typeof yr=="string"?yr:(Mr=yr==null?void 0:yr.text)!=null?Mr:null;if(Hr!==null&&Hr.trim()!==""){let dr=f;dr&&dr.id===et.id&&(dr.content=Hr,dr.streaming=!1,Pe.delete(dr.id),K.delete(dr.id),p(dr))}else{let dr=ze.getExtractedText(),vr=f;vr&&vr.id===et.id&&(dr!==null&&dr.trim()!==""?vr.content=dr:K.has(vr.id)||(vr.content=Oe(te)),vr.streaming=!1,Pe.delete(vr.id),K.delete(vr.id),p(vr))}});else{let yr=typeof Lt=="string"?Lt:(_s=Lt==null?void 0:Lt.text)!=null?_s:null;if(yr!==null&&yr.trim()!=="")et.content=yr,ct=!0;else{let Hr=ze.getExtractedText();Hr!==null&&Hr.trim()!==""&&(et.content=Hr,ct=!0)}}}}}if(!at){if(!et.rawContent){let _t=K.get(et.id);et.rawContent=_t!=null?_t:Oe(te)}if(!ct&&!K.has(et.id)&&(et.content=Oe(te)),ze){let _t=(la=ze.close)==null?void 0:la.call(ze);_t instanceof Promise&&_t.catch(()=>{})}Pe.delete(et.id),K.delete(et.id),et.streaming=!1,p(et)}}else Pe.delete(et.id),K.delete(et.id),et.streaming=!1,p(et)}else if(Ze==="flow_complete"){let z=(bt=P.result)==null?void 0:bt.response;if(A){if(f!==null){let I=f;Pe.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(z!=null){let I=ue(),V=K.get(I.id),fe=V!=null?V:Oe(z);I.rawContent=fe;let te=Oe(z),et=Pe.get(I.id);if(et){let at=Ko(fe);if(at!==null)te=at;else{let _t=et.processChunk(fe);_t instanceof Promise&&_t.then(lr=>{var Lt;let Rt=typeof lr=="string"?lr:(Lt=lr==null?void 0:lr.text)!=null?Lt:null;Rt!==null&&(I.content=Rt,I.streaming=!1,p(I))});let Gt=et.getExtractedText();Gt!==null&&(te=Gt)}}Pe.delete(I.id),K.delete(I.id);let ze=te!==I.content,ct=I.streaming!==!1;ze&&(I.content=te),I.streaming=!1,(ze||ct)&&p(I)}else if(f!==null){let I=f;Pe.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}t({type:"status",status:"idle"})}else if(Ze==="agent_start")ne={executionId:P.executionId,agentId:(Na=P.agentId)!=null?Na:"virtual",agentName:(bn=P.agentName)!=null?bn:"",status:"running",currentIteration:0,maxTurns:(Qr=P.maxTurns)!=null?Qr:1,startedAt:ie(P.startedAt)};else if(Ze==="agent_iteration_start"){if(ne&&(ne.currentIteration=P.iteration),fr==="separate"&&P.iteration>1){let z=f;z&&(z.streaming=!1,p(z),He.set(P.iteration-1,z),f=null)}}else if(Ze!=="agent_turn_start"){if(Ze==="agent_turn_delta"){if(P.contentType==="text"){let z=ue();z.content+=($s=P.delta)!=null?$s:"",z.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId,agentName:ne==null?void 0:ne.agentName},p(z)}else if(P.contentType==="thinking"){let z=(Us=P.turnId)!=null?Us:`agent-think-${P.iteration}`,I=xe(z);I.reasoning=(da=I.reasoning)!=null?da:{id:z,status:"streaming",chunks:[]},I.reasoning.chunks.push((Xn=P.delta)!=null?Xn:""),I.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId},p(I)}else if(P.contentType==="tool_input"){let z=(qs=P.toolCallId)!=null?qs:y.lastId;if(z){let I=T.get(z);I!=null&&I.toolCall&&(I.toolCall.chunks=(Ho=I.toolCall.chunks)!=null?Ho:[],I.toolCall.chunks.push((_a=P.delta)!=null?_a:""),p(I))}}}else if(Ze==="agent_turn_complete"){let z=P.turnId;if(z){let V=k.get(z);if(V!=null&&V.reasoning){V.reasoning.status="complete",V.reasoning.completedAt=ie(P.completedAt);let fe=(Jn=V.reasoning.startedAt)!=null?Jn:Date.now();V.reasoning.durationMs=Math.max(0,(($a=V.reasoning.completedAt)!=null?$a:Date.now())-fe),V.streaming=!1,p(V)}}let I=P.stopReason;if(I&&f!==null){let V=P.turnId;(!V||((mo=f.agentMetadata)==null?void 0:mo.turnId)===V)&&(f.stopReason=I,p(f))}}else if(Ze==="agent_tool_start"){let z=(go=P.toolCallId)!=null?go:`agent-tool-${l()}`;ge(H(P),z);let I=pe(z),V=(zs=I.toolCall)!=null?zs:{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};V.name=(Hl=(Vs=P.toolName)!=null?Vs:P.name)!=null?Hl:V.name,V.status="running",P.parameters!==void 0&&(V.args=P.parameters),V.startedAt=ie((Bo=P.startedAt)!=null?Bo:P.timestamp),I.toolCall=V,I.streaming=!0,I.agentMetadata={executionId:P.executionId,iteration:P.iteration},p(I)}else if(Ze==="agent_tool_delta"){let z=(ho=P.toolCallId)!=null?ho:y.lastId;if(z){let I=(js=T.get(z))!=null?js:pe(z);I.toolCall&&(I.toolCall.chunks=(Ua=I.toolCall.chunks)!=null?Ua:[],I.toolCall.chunks.push((xo=P.delta)!=null?xo:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ze==="agent_tool_complete"){let z=(Gs=P.toolCallId)!=null?Gs:y.lastId;if(z){let I=(qa=T.get(z))!=null?qa:pe(z);if(I.toolCall){I.toolCall.status="complete",P.result!==void 0&&(I.toolCall.result=P.result),typeof P.executionTime=="number"&&(I.toolCall.durationMs=P.executionTime),I.toolCall.completedAt=ie((yo=P.completedAt)!=null?yo:P.timestamp),I.streaming=!1,p(I);let V=H(P);V&&y.byCall.delete(V)}}}else if(Ze==="agent_media"){let z=Array.isArray(P.media)?P.media:[],I=[];for(let V of z){if(!V||typeof V!="object")continue;let fe=V,te=typeof fe.type=="string"?fe.type:void 0,et=typeof fe.mediaType=="string"?fe.mediaType.toLowerCase():"",ze=null,ct="";if(te==="media"){let at=typeof fe.data=="string"?fe.data:void 0;if(!at)continue;ct=et.length>0?et:"application/octet-stream",ze=`data:${ct};base64,${at}`}else if(te==="image-url"){let at=typeof fe.url=="string"?fe.url:void 0;if(!at)continue;ct=et,ze=at}else if(te==="file-url"){let at=typeof fe.url=="string"?fe.url:void 0;if(!at)continue;ct=et,ze=at}else continue;if(ze)if(te==="image-url"||ct.startsWith("image/"))I.push({type:"image",image:ze,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))I.push({type:"audio",audio:ze,mimeType:ct});else if(ct.startsWith("video/"))I.push({type:"video",video:ze,mimeType:ct});else{let at=ct||"application/octet-stream";I.push({type:"file",data:ze,mimeType:at,filename:sb(at)})}}if(I.length>0){let V=l(),fe=P.toolCallId,et={id:`agent-media-${typeof fe=="string"&&fe.length>0?`${fe}-${V}`:String(V)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:V,agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(et);let ze=f;ze&&(ze.streaming=!1,p(ze)),f=null,m.current=null}}else if(Ze!=="agent_iteration_complete"){if(Ze==="agent_reflection"||Ze==="agent_reflect"){let z=`agent-reflection-${P.executionId}-${P.iteration}`,I={id:z,role:"assistant",content:(za=P.reflection)!=null?za:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Xs=P.reflection)!=null?Xs:""]},agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(I)}else if(Ze==="agent_complete"){ne&&(ne.status=P.success?"complete":"error",ne.completedAt=ie(P.completedAt),ne.stopReason=P.stopReason);let z=f;z&&(z.streaming=!1,p(z)),t({type:"status",status:"idle"})}else if(Ze==="agent_error"){let z=typeof P.error=="string"?P.error:(Js=(Kn=P.error)==null?void 0:Kn.message)!=null?Js:"Agent execution error";P.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):t({type:"error",error:new Error(z)})}else if(Ze!=="agent_ping"){if(Ze==="agent_approval_start"){let z=(bo=P.approvalId)!=null?bo:`approval-${l()}`,I={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Nt=ne==null?void 0:ne.agentId)!=null?Nt:"virtual",executionId:(pa=(ca=P.executionId)!=null?ca:ne==null?void 0:ne.executionId)!=null?pa:"",toolName:(Va=P.toolName)!=null?Va:"",toolType:P.toolType,description:(Ks=P.description)!=null?Ks:`Execute ${(_n=P.toolName)!=null?_n:"tool"}`,parameters:P.parameters}};p(I)}else if(Ze==="step_await"&&P.awaitReason==="approval_required"){let z=(ja=P.approvalId)!=null?ja:`approval-${l()}`,I={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ga=ne==null?void 0:ne.agentId)!=null?Ga:"virtual",executionId:(Ja=(Xa=P.executionId)!=null?Xa:ne==null?void 0:ne.executionId)!=null?Ja:"",toolName:($r=P.toolName)!=null?$r:"",toolType:P.toolType,description:(Yn=P.description)!=null?Yn:`Execute ${(dn=P.toolName)!=null?dn:"tool"}`,parameters:P.parameters}};p(I)}else if(Ze==="agent_approval_complete"){let z=P.approvalId;if(z){let V={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(dt=P.decision)!=null?dt:"approved",agentId:(Ka=ne==null?void 0:ne.agentId)!=null?Ka:"virtual",executionId:(Bn=(Wo=P.executionId)!=null?Wo:ne==null?void 0:ne.executionId)!=null?Bn:"",toolName:(Ys=P.toolName)!=null?Ys:"",description:(ua=P.description)!=null?ua:"",resolvedAt:Date.now()}};p(V)}}else if(Ze==="artifact_start"||Ze==="artifact_delta"||Ze==="artifact_update"||Ze==="artifact_complete"){if(Ze==="artifact_start"){let z=P.artifactType,I=String(P.id),V=typeof P.title=="string"?P.title:void 0;if(t({type:"artifact_start",id:I,artifactType:z,title:V,component:typeof P.component=="string"?P.component:void 0}),Se.set(I,{markdown:"",title:V}),!Q.has(I)){Q.add(I);let fe={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:V,artifactType:z,status:"streaming"}})};Ge.set(I,fe),p(fe)}}else if(Ze==="artifact_delta"){let z=String(P.id),I=typeof P.delta=="string"?P.delta:String((fa=P.delta)!=null?fa:"");t({type:"artifact_delta",id:z,artDelta:I});let V=Se.get(z);V&&(V.markdown+=I)}else if(Ze==="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(Ze==="artifact_complete"){let z=String(P.id);t({type:"artifact_complete",id:z});let I=Ge.get(z);if(I){I.streaming=!1;try{let V=JSON.parse((Do=I.rawContent)!=null?Do:"{}");if(V.props){V.props.status="complete";let fe=Se.get(z);fe!=null&&fe.markdown&&(V.props.markdown=fe.markdown)}I.rawContent=JSON.stringify(V)}catch{}Se.delete(z),p(I),Ge.delete(z)}}}else if(Ze==="transcript_insert"){let z=P.message;if(!z||typeof z!="object")continue;let I=String((Co=z.id)!=null?Co:`msg-${l()}`),V=z.role,te={id:I,role:V==="user"?"user":V==="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(te),te.rawContent)try{let et=JSON.parse(te.rawContent),ze=(Qs=et==null?void 0:et.props)==null?void 0:Qs.artifactId;typeof ze=="string"&&Q.add(ze)}catch{}f=null,m.current=null,Pe.delete(I),K.delete(I)}else if(Ze==="error"||Ze==="step_error"||Ze==="dispatch_error"||Ze==="flow_error"){let z=null;if(P.error instanceof Error)z=P.error;else if(Ze==="dispatch_error"){let I=(Zs=P.message)!=null?Zs:P.error;I!=null&&I!==""&&(z=new Error(String(I)))}else if(Ze==="step_error"||Ze==="flow_error"){let I=P.error;typeof I=="string"&&I!==""?z=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(z=new Error(String((Wn=I.message)!=null?Wn:I)))}else Ze==="error"&&P.error!=null&&P.error!==""&&(z=new Error(String(P.error)));if(z){t({type:"error",error:z});let I=f;I&&I.streaming&&(I.streaming=!1,p(I)),t({type:"status",status:"idle"})}}}}}}ke.length=0};;){let{done:F,value:le}=await o.read();if(F)break;s+=a.decode(le,{stream:!0});let Fe=s.split(`
|
|
52
52
|
|
|
53
53
|
`);s=(Yt=Fe.pop())!=null?Yt:"";for(let Ke of Fe){let Ue=Ke.split(`
|
|
54
|
-
`),qe="message",nt="";for(let $t of Ue)$t.startsWith("event:")?qe=$t.replace("event:","").trim():$t.startsWith("data:")&&(nt+=$t.replace("data:","").trim());if(!nt)continue;let Ct;try{Ct=JSON.parse(nt)}catch($t){t({type:"error",error:$t instanceof Error?$t:new Error("Failed to parse chat stream payload")});continue}let Pt=qe!=="message"?qe:(Fr=Ct.type)!=null?Fr:"message";if((Ar=this.onSSEEvent)==null||Ar.call(this,Pt,Ct),this.parseSSEEvent){f.current=m;let $t=await this.handleCustomSSEEvent(Ct,t,f,p,l,w);if(f.current&&f.current!==m&&(m=f.current),$t)continue}Mt.push(Pt,Ct),ve()}}Mt.flushPending(),ve(),Mt.destroy()}};function Ig(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Ca(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Qo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ei="[Image]";function Rg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Hg(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Bg(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Wg(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function gs(e){return{type:"text",text:e}}function Dg(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Og(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;r({type:"image",image:o,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Fg(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.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: ${r.join(", ")}`}}var Ng=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],db=["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"],oo=[...Ng,...db];function cb(e){return Ng.includes(e)||e.startsWith("image/")}function Mi(e){return cb(e.type)}async function _g(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;Mi(e)?r({type:"image",image:o,mimeType:e.type,alt:e.name}):r({type:"file",data:o,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function $g(e,r=oo,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function pb(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Ug(e,r){let t=pb(r).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var Li=class{constructor(r=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=r}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 r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,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 r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),o=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let a=0;a<t;a++){let s=o.getInt16(a*2,!0);n[a]=s/32768}return n}};var Pi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,o,a){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 hs=class{constructor(r){this.config=r;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 Pi;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,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=(r=this.config)==null?void 0:r.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=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let w=!1,v=T=>{w||(w=!0,clearTimeout(k),f(new Error(T)))},k=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(k),m())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!w){let A=T.code!==1006?` (code ${T.code})`:"";v("WebSocket connection failed"+A+"."+p)}},{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(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(r.response.audio).catch(o=>this.errorCallbacks.forEach(a=>a(o instanceof Error?o:new Error(String(o)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.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(r.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Li(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,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=(r=this.config)==null?void 0:r.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(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),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(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var a,s;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.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(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){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(r),o=this.getFormatFromMimeType(r.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(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result.split(",")[1];t(s)},o.onerror=n,o.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let l=0;l<t.length;l++)n[l]=t.charCodeAt(l);let o=r.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(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Zo=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,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=((r=this.config)==null?void 0:r.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(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ea(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!Zo.isSupported())throw new Error("Browser speech recognition not supported");return new Zo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ii(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ea({type:"runtype",runtype:e.runtype});if(Zo.isSupported())return ea({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function xs(e){try{return Ii(e),!0}catch{return!1}}var wa=class e{constructor(r={},t){this.config=r;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,o,a,s,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(o=r.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n,o;this.messages=[...(n=r.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 Yo(r);for(let a of(o=r.initialArtifacts)!=null?o:[])this.artifacts.set(a.id,{...a,status:"complete"});r.initialSelectedArtifactId!=null&&(this.selectedArtifactId=r.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return xs((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,o;try{let a=r||this.getVoiceConfigFromConfig();if(!a)throw new Error("Voice configuration not provided");this.voiceProvider=ea(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,p,m,f,w,v;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}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((m=l.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=l.text)!=null&&f.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let k=(v=this.pendingVoiceAssistantMessageId)!=null?v:(w=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:w.id;k&&this.ttsSpokenMessageIds.add(k)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.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(r){console.error("Failed to start voice:",r)}}}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 r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((o=r.runtype)==null?void 0:o.clientToken)||"",host:(a=r.runtype)==null?void 0:a.host,voiceId:(s=r.runtype)==null?void 0:s.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=r.browser)==null?void 0:l.language)||"en-US",continuous:(u=r.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Yo(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=r,f={id:s!=null?s:t==="user"?Ca():t==="assistant"?Qo():`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},...p!==void 0&&{rawContent:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:o,content:a,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:m,rawContent:f}=n,v={id:d!=null?d:o==="user"?Ca():o==="assistant"?Qo():`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:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};t.push(v)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(r){let{component:t,props:n={},text:o="",llmContent:a,id:s,createdAt:i,sequence:d}=r,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(r,t){var l,u,p,m,f;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let o=Ca(),a=Qo(),s={id:o,role:"user",content:n||Ei,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(w){let v=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!v){let k={id:a,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(k)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(w instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,w):(f=(m=this.callbacks).onError)==null||f.call(m,new Error(String(w))))}}async continueConversation(){var o,a,s,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let r=Qo();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:r},this.handleEvent)}catch(l){let u={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,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(r,t){var o,a,s;if(this.streaming)return;(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(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,l,u;let n=`approval-${r.id}`,o={...r,status:t,resolvedAt:Date.now()},a={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(a);let s=this.config.approval,i=s&&typeof s=="object"?s.onDecision:void 0;try{let p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let m=null;if(p instanceof Response){if(!p.ok){let f=await p.json().catch(()=>null);throw new Error((d=f==null?void 0:f.error)!=null?d:`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(u=(l=this.callbacks).onError)==null||u.call(l,p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(r,t){let n=this.messages.find(o=>o.id===r.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(r,t){let n=this.messages.find(o=>o.id===r.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(r,t){var u,p,m,f,w,v,k,T,A,E,b;let n=this.messages.find(h=>h.id===r.id);if(((u=n==null?void 0:n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(p=r.agentMetadata)==null?void 0:p.executionId,a=(m=r.toolCall)==null?void 0:m.name;if(!o||!a){(w=(f=this.callbacks).onError)==null||w.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 h=(v=r.toolCall)==null?void 0:v.args,S=Array.isArray(h==null?void 0:h.questions)?h.questions:[];if(S.length===1){let L=typeof((k=S[0])==null?void 0:k.question)=="string"?S[0].question:"";L&&(s={[L]:t})}}this.markAskUserQuestionResolved(r,s);let i=r.toolCall.id,d=(T=r.toolCall)==null?void 0:T.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let h=typeof t=="string"?t:Object.entries(t).map(([S,L])=>`${S}: ${Array.isArray(L)?L.join(", "):L}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let h=s!=null?s:{};l.forEach((S,L)=>{let O=typeof(S==null?void 0:S.question)=="string"?S.question:"";if(!O)return;let H=h[O],R=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${L}`,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${L}`,role:"user",content:R||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let h=await this.client.resumeFlow(o,{[a]:t});if(!h.ok){let S=await h.json().catch(()=>null);throw new Error((A=S==null?void 0:S.error)!=null?A:`Resume failed: ${h.status}`)}h.body&&await this.connectStream(h.body)}catch(h){(b=(E=this.callbacks).onError)==null||b.call(E,h instanceof Error?h:new Error(String(h)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var o;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let a={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,a),this.selectedArtifactId=t,this.emitArtifactsState(),a}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(o=r.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 r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let o=this.artifacts.get(r.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let o=this.artifacts.get(r.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...r.props},r.component&&(o.component=r.component));break}case"artifact_complete":{let o=this.artifacts.get(r.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.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(r,t=null){this.artifacts.clear();for(let n of r)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.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,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(r),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):e.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(r){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=r.find(s=>s.name===o);if(a)return a}return(n=r.find(o=>o.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(o=>o.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,a)=>{var i;if(a!==n)return o;let s={...o,...t};return((i=o.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].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 x=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},qn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var rd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var nd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var od=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ad=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var sd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var id=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var ld=[["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 dd=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var cd=[["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 pd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var ud=[["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 fd=[["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 md=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var gd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var hd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var xd=[["path",{d:"M20 6 9 17l-5-5"}]];var yd=[["path",{d:"m6 9 6 6 6-6"}]];var bd=[["path",{d:"m15 18-6-6 6-6"}]];var Cd=[["path",{d:"m9 18 6-6-6-6"}]];var wd=[["path",{d:"m18 15-6-6-6 6"}]];var Ri=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Hi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var vd=[["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 Ad=[["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 Sd=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Td=[["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 kd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Ed=[["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 Md=[["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 Bi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Wi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ld=[["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 Pd=[["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 Id=[["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 Rd=[["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 Hd=[["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 Bd=[["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 Wd=[["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 Dd=[["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 Od=[["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 Fd=[["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 Nd=[["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 _d=[["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 Di=[["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 $d=[["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 Ud=[["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 qd=[["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 zd=[["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 Vd=[["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 jd=[["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 Oi=[["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 Gd=[["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 Xd=[["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 Jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Kd=[["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 Yd=[["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 Fi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Qd=[["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 Zd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var ec=[["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 tc=[["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 rc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var nc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var oc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var ac=[["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 sc=[["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 ic=[["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 lc=[["path",{d:"M5 12h14"}]];var dc=[["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 cc=[["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 pc=[["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 uc=[["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 fc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var mc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var gc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var hc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var xc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var yc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var bc=[["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 Cc=[["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 wc=[["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 vc=[["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 Ac=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Sc=[["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 Tc=[["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 kc=[["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 Ec=[["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 Mc=[["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 Ni=[["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 Lc=[["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 Pc=[["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 Ic=[["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 Rc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var _i=[["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 Hc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Bc=[["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 Wc=[["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 Dc=[["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 Oc=[["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 Fc=[["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 Nc=[["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 _c=[["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 $c=[["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 Uc=[["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 $i=[["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 qc=[["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 zc=[["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 Vc=[["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 jc=[["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 Gc=[["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 Xc=[["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 Jc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Kc=[["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 ub={activity:rd,"arrow-down":nd,"arrow-up":id,"arrow-up-right":sd,bot:ud,"chevron-down":yd,"chevron-up":wd,"chevron-right":Cd,"chevron-left":bd,check:xd,clipboard:Ad,"clipboard-copy":vd,copy:Td,file:Wd,"file-code":Rd,"file-spreadsheet":Hd,"file-text":Bd,"image-plus":Gd,loader:Qd,"loader-circle":Fi,mic:sc,paperclip:uc,"refresh-cw":Cc,search:Ac,send:Sc,"shield-alert":Ec,"shield-check":Mc,"shield-x":Ni,square:Hc,"thumbs-down":Fc,"thumbs-up":Nc,upload:zc,"volume-2":jc,x:Jc,user:Vc,mail:ec,phone:hc,calendar:gd,clock:Sd,building:fd,"map-pin":tc,lock:Zd,key:Kd,"credit-card":kd,"at-sign":ld,hash:qd,globe:Ud,link:Yd,"circle-check":Ri,"circle-x":Hi,"triangle-alert":$i,info:Jd,ban:dd,shield:Lc,"arrow-left":od,"arrow-right":ad,"external-link":Ld,ellipsis:Wi,"ellipsis-vertical":Bi,menu:nc,house:Oi,plus:yc,minus:lc,pencil:mc,trash:Uc,"trash-2":$c,save:vc,download:Md,share:kc,funnel:Di,settings:Tc,"rotate-cw":wc,maximize:rc,minimize:ic,"shopping-cart":Ic,"shopping-bag":Pc,package:pc,truck:qc,tag:Oc,gift:$d,receipt:bc,wallet:Xc,store:Wc,"dollar-sign":Ed,percent:gc,play:xc,pause:fc,"volume-x":Gc,camera:hd,image:Xd,film:Od,headphones:zd,"message-circle":oc,"message-square":ac,bell:cd,heart:Vd,star:Bc,eye:Id,"eye-off":Pd,bookmark:pd,"calendar-days":md,history:jd,timer:_c,folder:_d,"folder-open":Nd,files:Dd,sparkles:_i,zap:Kc,sun:Dc,moon:cc,flag:Fd,monitor:dc,smartphone:Rc},Ce=(e,r=24,t="currentColor",n=2)=>{let o=ub[e];return o?fb(o,r,t,n):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function fb(e,r,t,n){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(r)),o.setAttribute("height",String(r)),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"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),o.appendChild(d)}),o}var Ui={allowedTypes:oo,maxFileSize:10*1024*1024,maxFiles:4};function mb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function gb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ta=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,o;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ui.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Ui.maxFileSize,maxFiles:(o=r.maxFiles)!=null?o:Ui.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:Ui.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,o,a,s,i,d;if(r.length){for(let l of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,l,"count");continue}let u=$g(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(o=u.error)!=null&&o.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,p);continue}try{let p=await _g(l),m=Mi(l)?URL.createObjectURL(l):null,f={id:mb(),file:l,previewUrl:m,contentPart:p};this.attachments.push(f),this.renderPreview(f)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var a,s,i;let t=this.attachments.findIndex(d=>d.id===r);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="${r}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=Mi(r.file),n=x("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let s=x("img");s.src=r.previewUrl,s.alt=r.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=x("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=gb(r.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=x("span");l.textContent=Ug(r.file.type,r.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=x("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=Ce("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(r.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ys(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,o]of Object.entries(r)){let a=t[n];qg(a)&&qg(o)?t[n]=ys(a,o):t[n]=o}return t}var mn="min(440px, calc(100vw - 24px))",qi="440px",jt={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:mn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function zg(e,r){if(!(!e&&!r))return e?r?ys(e,r):e:r}function zi(e){var r,t,n,o,a,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h;return e?{...jt,...e,theme:zg(jt.theme,e.theme),darkTheme:zg(jt.darkTheme,e.darkTheme),launcher:{...jt.launcher,...e.launcher,dock:{...(r=jt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=jt.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...jt.copy,...e.copy},sendButton:{...jt.sendButton,...e.sendButton},statusIndicator:{...jt.statusIndicator,...e.statusIndicator},voiceRecognition:{...jt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ge,Le,Ge,Q,Se,J,ce,pe;let S=(ge=jt.features)==null?void 0:ge.artifacts,L=(Le=e.features)==null?void 0:Le.artifacts,O=(Ge=jt.features)==null?void 0:Ge.scrollToBottom,H=(Q=e.features)==null?void 0:Q.scrollToBottom,R=(Se=jt.features)==null?void 0:Se.streamAnimation,B=(J=e.features)==null?void 0:J.streamAnimation,j=(ce=jt.features)==null?void 0:ce.askUserQuestion,oe=(pe=e.features)==null?void 0:pe.askUserQuestion,ue=S===void 0&&L===void 0?void 0:{...S,...L,layout:{...S==null?void 0:S.layout,...L==null?void 0:L.layout}},De=O===void 0&&H===void 0?void 0:{...O,...H},Xe=R===void 0&&B===void 0?void 0:{...R,...B},xe=j===void 0&&oe===void 0?void 0:{...j,...oe,styles:{...j==null?void 0:j.styles,...oe==null?void 0:oe.styles}};return{...jt.features,...e.features,...De!==void 0?{scrollToBottom:De}:{},...ue!==void 0?{artifacts:ue}:{},...Xe!==void 0?{streamAnimation:Xe}:{},...xe!==void 0?{askUserQuestion:xe}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:jt.suggestionChips,suggestionChipsConfig:{...jt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...jt.layout,...e.layout,header:{...(s=jt.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=jt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=jt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(f=(m=e.layout)==null?void 0:m.messages)==null?void 0:f.avatar},timestamp:{...(v=(w=jt.layout)==null?void 0:w.messages)==null?void 0:v.timestamp,...(T=(k=e.layout)==null?void 0:k.messages)==null?void 0:T.timestamp}},slots:{...(A=jt.layout)==null?void 0:A.slots,...(E=e.layout)==null?void 0:E.slots}},markdown:{...jt.markdown,...e.markdown,options:{...(b=jt.markdown)==null?void 0:b.options,...(h=e.markdown)==null?void 0:h.options}},messageActions:{...jt.messageActions,...e.messageActions}}:jt}var Yc={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"}},Qc={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"}},Zc={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:mn,maxWidth:qi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function va(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;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."))?va(e,n):n}function Vi(e){let r={};function t(n,o){for(let[a,s]of Object.entries(n)){let i=`${o}.${a}`;if(typeof s=="string"){let d=va(e,s);d!==void 0&&(r[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(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function ep(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function Vg(e,r){let t={...e};for(let[n,o]of Object.entries(r)){let a=t[n];a&&typeof a=="object"&&!Array.isArray(a)&&o&&typeof o=="object"&&!Array.isArray(o)?t[n]=Vg(a,o):t[n]=o}return t}function hb(e,r){return r?Vg(e,r):e}function Aa(e,r={}){var o,a,s,i,d,l,u,p,m,f,w,v,k;let t={palette:Yc,semantic:Qc,components:Zc},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...t.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(m=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:m.interactive},feedback:{...t.semantic.colors.feedback,...(w=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:w.feedback}},spacing:{...t.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:hb(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let T=ep(n);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(A=>A.message).join(", ")}`)}if(r.plugins)for(let T of r.plugins)n=T.transform(n);return n}function ji(e){var v,k,T,A,E,b,h,S,L,O,H,R,B,j,oe,ue,De,Xe,xe,ge,Le,Ge,Q,Se,J,ce,pe,ie,Oe,Pe,K,_e,$e,Y,G,we,ke,ae,ve,ye,Mt,ne,He,fr,Ot,Yt,Fr,Ar,F,le,Fe,Ke,Ue,qe,nt,Ct,Pt,$t,N,de,Ee,ut,Ye,Ut,or,It,St,rt,it,tr,gn,Rr,Tn,Tt,hn,ur,Sr,Yr,xt,kn,nn,Tr,kr,Vn,En,xn,wt,Ie,M,Z,se,kt,qt,Bt,ar,xr,Nr,Er,ot,wr,_r,po,jn,uo,Fn,on,Mn,vt,sr,ir,an,fo,yn,Ln,sn,q;let r=Vi(e),t={};for(let[he,ln]of Object.entries(r)){let Pn=he.replace(/\./g,"-");t[`--persona-${Pn}`]=ln.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(k=t["--persona-semantic-colors-secondary"])!=null?k: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"]=(A=t["--persona-semantic-colors-surface"])!=null?A:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(E=t["--persona-semantic-colors-background"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(b=t["--persona-semantic-colors-container"])!=null?b:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(h=t["--persona-semantic-colors-text"])!=null?h:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(S=t["--persona-semantic-colors-text-muted"])!=null?S:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(L=t["--persona-semantic-colors-text-inverse"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(O=t["--persona-semantic-colors-border"])!=null?O:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(H=t["--persona-semantic-colors-divider"])!=null?H:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(B=t["--persona-components-voice-recording-background"])!=null?B:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(j=t["--persona-components-voice-processing-icon"])!=null?j:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ue=t["--persona-components-approval-requested-background"])!=null?ue:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(De=t["--persona-components-approval-requested-border"])!=null?De:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Xe=t["--persona-components-approval-requested-text"])!=null?Xe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(xe=t["--persona-components-approval-approve-background"])!=null?xe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ge=t["--persona-components-approval-deny-background"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Le=t["--persona-components-attachment-image-background"])!=null?Le:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Ge=t["--persona-components-attachment-image-border"])!=null?Ge:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Q=t["--persona-semantic-typography-fontFamily"])!=null?Q:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Se=t["--persona-semantic-typography-fontSize"])!=null?Se:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(J=t["--persona-semantic-typography-fontWeight"])!=null?J:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ce=t["--persona-semantic-typography-lineHeight"])!=null?ce: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"]=(pe=t["--persona-palette-radius-sm"])!=null?pe:"0.125rem",t["--persona-radius-md"]=(ie=t["--persona-palette-radius-md"])!=null?ie:"0.375rem",t["--persona-radius-lg"]=(Oe=t["--persona-palette-radius-lg"])!=null?Oe:"0.5rem",t["--persona-radius-xl"]=(Pe=t["--persona-palette-radius-xl"])!=null?Pe:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=($e=(_e=t["--persona-components-launcher-borderRadius"])!=null?_e:t["--persona-palette-radius-full"])!=null?$e:"9999px",t["--persona-launcher-bg"]=(Y=t["--persona-components-launcher-background"])!=null?Y:t["--persona-primary"],t["--persona-launcher-fg"]=(G=t["--persona-components-launcher-foreground"])!=null?G:t["--persona-text-inverse"],t["--persona-launcher-border"]=(we=t["--persona-components-launcher-border"])!=null?we:t["--persona-border"],t["--persona-button-primary-bg"]=(ke=t["--persona-components-button-primary-background"])!=null?ke:t["--persona-primary"],t["--persona-button-primary-fg"]=(ae=t["--persona-components-button-primary-foreground"])!=null?ae:t["--persona-text-inverse"],t["--persona-button-radius"]=(ye=(ve=t["--persona-components-button-primary-borderRadius"])!=null?ve:t["--persona-palette-radius-full"])!=null?ye:"9999px",t["--persona-panel-radius"]=(ne=(Mt=t["--persona-components-panel-borderRadius"])!=null?Mt:t["--persona-radius-xl"])!=null?ne:"0.75rem",t["--persona-panel-border"]=(He=t["--persona-components-panel-border"])!=null?He:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ot=(fr=t["--persona-components-panel-shadow"])!=null?fr:t["--persona-palette-shadows-xl"])!=null?Ot:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Fr=(Yt=t["--persona-components-input-borderRadius"])!=null?Yt:t["--persona-radius-lg"])!=null?Fr:"0.5rem",t["--persona-message-user-radius"]=(F=(Ar=t["--persona-components-message-user-borderRadius"])!=null?Ar:t["--persona-radius-lg"])!=null?F:"0.5rem",t["--persona-message-assistant-radius"]=(Fe=(le=t["--persona-components-message-assistant-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?Fe:"0.5rem",t["--persona-header-bg"]=(Ke=t["--persona-components-header-background"])!=null?Ke:t["--persona-surface"],t["--persona-header-border"]=(Ue=t["--persona-components-header-border"])!=null?Ue:t["--persona-divider"],t["--persona-header-icon-bg"]=(qe=t["--persona-components-header-iconBackground"])!=null?qe:t["--persona-primary"],t["--persona-header-icon-fg"]=(nt=t["--persona-components-header-iconForeground"])!=null?nt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ct=t["--persona-components-header-titleForeground"])!=null?Ct:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Pt=t["--persona-components-header-subtitleForeground"])!=null?Pt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=($t=t["--persona-components-header-actionIconForeground"])!=null?$t:t["--persona-muted"];let n=(N=e.components)==null?void 0:N.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom);let o=(de=e.components)==null?void 0:de.introCard;t["--persona-intro-card-bg"]=(Ee=t["--persona-components-introCard-background"])!=null?Ee:t["--persona-surface"],t["--persona-intro-card-radius"]=(ut=t["--persona-components-introCard-borderRadius"])!=null?ut:"1rem",t["--persona-intro-card-padding"]=(Ye=t["--persona-components-introCard-padding"])!=null?Ye:"1.5rem",t["--persona-intro-card-shadow"]=(or=(Ut=o==null?void 0:o.shadow)!=null?Ut:t["--persona-components-introCard-shadow"])!=null?or:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(It=t["--persona-components-input-background"])!=null?It:t["--persona-surface"],t["--persona-input-placeholder"]=(St=t["--persona-components-input-placeholder"])!=null?St:t["--persona-text-muted"],t["--persona-message-user-bg"]=(rt=t["--persona-components-message-user-background"])!=null?rt:t["--persona-accent"],t["--persona-message-user-text"]=(it=t["--persona-components-message-user-text"])!=null?it:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(tr=t["--persona-components-message-user-shadow"])!=null?tr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(gn=t["--persona-components-message-assistant-background"])!=null?gn:t["--persona-surface"],t["--persona-message-assistant-text"]=(Rr=t["--persona-components-message-assistant-text"])!=null?Rr:t["--persona-text"],t["--persona-message-assistant-border"]=(Tn=t["--persona-components-message-assistant-border"])!=null?Tn:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Tt=t["--persona-components-message-assistant-shadow"])!=null?Tt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(hn=t["--persona-components-scrollToBottom-background"])!=null?hn:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Yr=(Sr=t["--persona-components-scrollToBottom-foreground"])!=null?Sr:t["--persona-button-primary-fg"])!=null?Yr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(xt=t["--persona-components-scrollToBottom-border"])!=null?xt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(kn=t["--persona-components-scrollToBottom-size"])!=null?kn:"40px",t["--persona-scroll-to-bottom-radius"]=(kr=(Tr=(nn=t["--persona-components-scrollToBottom-borderRadius"])!=null?nn:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?kr:"9999px",t["--persona-scroll-to-bottom-shadow"]=(En=(Vn=t["--persona-components-scrollToBottom-shadow"])!=null?Vn:t["--persona-palette-shadows-sm"])!=null?En:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(xn=t["--persona-components-scrollToBottom-padding"])!=null?xn:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(wt=t["--persona-components-scrollToBottom-gap"])!=null?wt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(M=(Ie=t["--persona-components-scrollToBottom-fontSize"])!=null?Ie:t["--persona-palette-typography-fontSize-sm"])!=null?M:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Z=t["--persona-components-scrollToBottom-iconSize"])!=null?Z:"14px",t["--persona-tool-bubble-shadow"]=(se=t["--persona-components-toolBubble-shadow"])!=null?se:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(kt=t["--persona-components-reasoningBubble-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(qt=t["--persona-components-composer-shadow"])!=null?qt:"none",t["--persona-md-inline-code-bg"]=(Bt=t["--persona-components-markdown-inlineCode-background"])!=null?Bt:t["--persona-container"],t["--persona-md-inline-code-color"]=(ar=t["--persona-components-markdown-inlineCode-foreground"])!=null?ar:t["--persona-text"],t["--persona-md-link-color"]=(Nr=(xr=t["--persona-components-markdown-link-foreground"])!=null?xr:t["--persona-accent"])!=null?Nr:"#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"]=(Er=t["--persona-components-markdown-codeBlock-background"])!=null?Er:t["--persona-container"],t["--persona-md-code-block-border-color"]=(ot=t["--persona-components-markdown-codeBlock-borderColor"])!=null?ot:t["--persona-border"],t["--persona-md-code-block-text-color"]=(wr=t["--persona-components-markdown-codeBlock-textColor"])!=null?wr:"inherit",t["--persona-md-table-header-bg"]=(_r=t["--persona-components-markdown-table-headerBackground"])!=null?_r:t["--persona-container"],t["--persona-md-table-border-color"]=(po=t["--persona-components-markdown-table-borderColor"])!=null?po:t["--persona-border"],t["--persona-md-hr-color"]=(jn=t["--persona-components-markdown-hr-color"])!=null?jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(uo=t["--persona-components-markdown-blockquote-borderColor"])!=null?uo:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Fn=t["--persona-components-markdown-blockquote-background"])!=null?Fn:"transparent",t["--persona-md-blockquote-text-color"]=(on=t["--persona-components-markdown-blockquote-textColor"])!=null?on:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Mn=t["--persona-components-collapsibleWidget-container"])!=null?Mn:t["--persona-surface"],t["--cw-surface"]=(vt=t["--persona-components-collapsibleWidget-surface"])!=null?vt:t["--persona-surface"],t["--cw-border"]=(sr=t["--persona-components-collapsibleWidget-border"])!=null?sr:t["--persona-border"],t["--persona-message-border"]=(ir=t["--persona-components-message-border"])!=null?ir:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let m=u==null?void 0:u.labelButton;m&&(m.background&&(t["--persona-label-btn-bg"]=m.background),m.border&&(t["--persona-label-btn-border"]=m.border),m.color&&(t["--persona-label-btn-color"]=m.color),m.padding&&(t["--persona-label-btn-padding"]=m.padding),m.borderRadius&&(t["--persona-label-btn-radius"]=m.borderRadius),m.hoverBackground&&(t["--persona-label-btn-hover-bg"]=m.hoverBackground),m.fontSize&&(t["--persona-label-btn-font-size"]=m.fontSize),m.gap&&(t["--persona-label-btn-gap"]=m.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 w=u==null?void 0:u.artifact;if(w!=null&&w.toolbar){let he=w.toolbar;he.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,t["--persona-dropdown-bg"]=(an=t["--persona-dropdown-bg"])!=null?an:he.copyMenuBackground),he.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,t["--persona-dropdown-border"]=(fo=t["--persona-dropdown-border"])!=null?fo:he.copyMenuBorder),he.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,t["--persona-dropdown-shadow"]=(yn=t["--persona-dropdown-shadow"])!=null?yn:he.copyMenuShadow),he.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Ln=t["--persona-dropdown-radius"])!=null?Ln:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(sn=t["--persona-dropdown-item-hover-bg"])!=null?sn:he.copyMenuItemHoverBackground),he.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(w!=null&&w.tab){let he=w.tab;he.background&&(t["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(t["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(t["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(t["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(t["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(t["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(t["--persona-artifact-tab-list-padding"]=he.listPadding)}if(w!=null&&w.pane){let he=w.pane;if(he.toolbarBackground){let ln=(q=va(e,he.toolbarBackground))!=null?q:he.toolbarBackground;t["--persona-artifact-toolbar-bg"]=ln}}return t}var jg={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 xb={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"}}},Gg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},yb=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":bs()},tp=e=>yb(e),bb=e=>Aa(e),Cb=e=>{var t;let r=Aa(void 0,{validate:!1});return Aa({...e,palette:{...r.palette,colors:{...xb.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Sa=e=>{let r=tp(e),t=Gg(e==null?void 0:e.theme),n=Gg(e==null?void 0:e.darkTheme);return r==="dark"?Cb(ys(t!=null?t:{},n!=null?n:{})):bb(t)},wb=e=>ji(e),vo=(e,r)=>{var a;let t=Sa(r),n=wb(t);for(let[s,i]of Object.entries(n))e.style.setProperty(s,i);let o=(a=r==null?void 0:r.toolCall)==null?void 0:a.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},Gi=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(bs())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(bs());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Xg=(function(){"use strict";let e=()=>{},r={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:m=>m.getAttribute("im-preserve")==="true",shouldReAppend:m=>m.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function t(m,f,w={}){m=u(m);let v=p(f),k=l(m,v,w),T=o(k,()=>i(k,m,v,A=>A.morphStyle==="innerHTML"?(a(A,m,v),Array.from(m.childNodes)):n(A,m,v)));return k.pantry.remove(),T}function n(m,f,w){let v=p(f);return a(m,v,w,f,f.nextSibling),Array.from(v.childNodes)}function o(m,f){var E;if(!m.config.restoreFocus)return f();let w=document.activeElement;if(!(w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement))return f();let{id:v,selectionStart:k,selectionEnd:T}=w,A=f();return v&&v!==((E=document.activeElement)==null?void 0:E.getAttribute("id"))&&(w=m.target.querySelector(`[id="${v}"]`),w==null||w.focus()),w&&!w.selectionEnd&&T&&w.setSelectionRange(k,T),A}let a=(function(){function m(b,h,S,L=null,O=null){h instanceof HTMLTemplateElement&&S instanceof HTMLTemplateElement&&(h=h.content,S=S.content),L||(L=h.firstChild);for(let H of S.childNodes){if(L&&L!=O){let B=w(b,H,L,O);if(B){B!==L&&k(b,L,B),s(B,H,b),L=B.nextSibling;continue}}if(H instanceof Element){let B=H.getAttribute("id");if(b.persistentIds.has(B)){let j=T(h,B,L,b);s(j,H,b),L=j.nextSibling;continue}}let R=f(h,H,L,b);R&&(L=R.nextSibling)}for(;L&&L!=O;){let H=L;L=L.nextSibling,v(b,H)}}function f(b,h,S,L){if(L.callbacks.beforeNodeAdded(h)===!1)return null;if(L.idMap.has(h)){let O=document.createElement(h.tagName);return b.insertBefore(O,S),s(O,h,L),L.callbacks.afterNodeAdded(O),O}else{let O=document.importNode(h,!0);return b.insertBefore(O,S),L.callbacks.afterNodeAdded(O),O}}let w=(function(){function b(L,O,H,R){let B=null,j=O.nextSibling,oe=0,ue=H;for(;ue&&ue!=R;){if(S(ue,O)){if(h(L,ue,O))return ue;B===null&&(L.idMap.has(ue)||(B=ue))}if(B===null&&j&&S(ue,j)&&(oe++,j=j.nextSibling,oe>=2&&(B=void 0)),L.activeElementAndParents.includes(ue))break;ue=ue.nextSibling}return B||null}function h(L,O,H){let R=L.idMap.get(O),B=L.idMap.get(H);if(!B||!R)return!1;for(let j of R)if(B.has(j))return!0;return!1}function S(L,O){var B,j,oe;let H=L,R=O;return H.nodeType===R.nodeType&&H.tagName===R.tagName&&(!((B=H.getAttribute)!=null&&B.call(H,"id"))||((j=H.getAttribute)==null?void 0:j.call(H,"id"))===((oe=R.getAttribute)==null?void 0:oe.call(R,"id")))}return b})();function v(b,h){var S;if(b.idMap.has(h))E(b.pantry,h,null);else{if(b.callbacks.beforeNodeRemoved(h)===!1)return;(S=h.parentNode)==null||S.removeChild(h),b.callbacks.afterNodeRemoved(h)}}function k(b,h,S){let L=h;for(;L&&L!==S;){let O=L;L=L.nextSibling,v(b,O)}return L}function T(b,h,S,L){var H,R;let O=((R=(H=L.target).getAttribute)==null?void 0:R.call(H,"id"))===h&&L.target||L.target.querySelector(`[id="${h}"]`)||L.pantry.querySelector(`[id="${h}"]`);return A(O,L),E(b,O,S),O}function A(b,h){let S=b.getAttribute("id");for(;b=b.parentNode;){let L=h.idMap.get(b);L&&(L.delete(S),L.size||h.idMap.delete(b))}}function E(b,h,S){if(b.moveBefore)try{b.moveBefore(h,S)}catch{b.insertBefore(h,S)}else b.insertBefore(h,S)}return m})(),s=(function(){function m(A,E,b){return b.ignoreActive&&A===document.activeElement?null:(b.callbacks.beforeNodeMorphed(A,E)===!1||(A instanceof HTMLHeadElement&&b.head.ignore||(A instanceof HTMLHeadElement&&b.head.style!=="morph"?d(A,E,b):(f(A,E,b),T(A,b)||a(b,A,E))),b.callbacks.afterNodeMorphed(A,E)),A)}function f(A,E,b){let h=E.nodeType;if(h===1){let S=A,L=E,O=S.attributes,H=L.attributes;for(let R of H)k(R.name,S,"update",b)||S.getAttribute(R.name)!==R.value&&S.setAttribute(R.name,R.value);for(let R=O.length-1;0<=R;R--){let B=O[R];if(B&&!L.hasAttribute(B.name)){if(k(B.name,S,"remove",b))continue;S.removeAttribute(B.name)}}T(S,b)||w(S,L,b)}(h===8||h===3)&&A.nodeValue!==E.nodeValue&&(A.nodeValue=E.nodeValue)}function w(A,E,b){if(A instanceof HTMLInputElement&&E instanceof HTMLInputElement&&E.type!=="file"){let h=E.value,S=A.value;v(A,E,"checked",b),v(A,E,"disabled",b),E.hasAttribute("value")?S!==h&&(k("value",A,"update",b)||(A.setAttribute("value",h),A.value=h)):k("value",A,"remove",b)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&E instanceof HTMLOptionElement)v(A,E,"selected",b);else if(A instanceof HTMLTextAreaElement&&E instanceof HTMLTextAreaElement){let h=E.value,S=A.value;if(k("value",A,"update",b))return;h!==S&&(A.value=h),A.firstChild&&A.firstChild.nodeValue!==h&&(A.firstChild.nodeValue=h)}}function v(A,E,b,h){let S=E[b],L=A[b];if(S!==L){let O=k(b,A,"update",h);O||(A[b]=E[b]),S?O||A.setAttribute(b,""):k(b,A,"remove",h)||A.removeAttribute(b)}}function k(A,E,b,h){return A==="value"&&h.ignoreActiveValue&&E===document.activeElement?!0:h.callbacks.beforeAttributeUpdated(A,E,b)===!1}function T(A,E){return!!E.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return m})();function i(m,f,w,v){if(m.head.block){let k=f.querySelector("head"),T=w.querySelector("head");if(k&&T){let A=d(k,T,m);return Promise.all(A).then(()=>{let E=Object.assign(m,{head:{block:!1,ignore:!0}});return v(E)})}}return v(m)}function d(m,f,w){let v=[],k=[],T=[],A=[],E=new Map;for(let h of f.children)E.set(h.outerHTML,h);for(let h of m.children){let S=E.has(h.outerHTML),L=w.head.shouldReAppend(h),O=w.head.shouldPreserve(h);S||O?L?k.push(h):(E.delete(h.outerHTML),T.push(h)):w.head.style==="append"?L&&(k.push(h),A.push(h)):w.head.shouldRemove(h)!==!1&&k.push(h)}A.push(...E.values());let b=[];for(let h of A){let S=document.createRange().createContextualFragment(h.outerHTML).firstChild;if(w.callbacks.beforeNodeAdded(S)!==!1){if("href"in S&&S.href||"src"in S&&S.src){let L,O=new Promise(function(H){L=H});S.addEventListener("load",function(){L()}),b.push(O)}m.appendChild(S),w.callbacks.afterNodeAdded(S),v.push(S)}}for(let h of k)w.callbacks.beforeNodeRemoved(h)!==!1&&(m.removeChild(h),w.callbacks.afterNodeRemoved(h));return w.head.afterHeadMorphed(m,{added:v,kept:T,removed:k}),b}let l=(function(){function m(b,h,S){let{persistentIds:L,idMap:O}=A(b,h),H=f(S),R=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:b,newContent:h,config:H,morphStyle:R,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:O,persistentIds:L,pantry:w(),activeElementAndParents:v(b),callbacks:H.callbacks,head:H.head}}function f(b){let h=Object.assign({},r);return Object.assign(h,b),h.callbacks=Object.assign({},r.callbacks,b.callbacks),h.head=Object.assign({},r.head,b.head),h}function w(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function v(b){let h=[],S=document.activeElement;if((S==null?void 0:S.tagName)!=="BODY"&&b.contains(S))for(;S&&(h.push(S),S!==b);)S=S.parentElement;return h}function k(b){var S;let h=Array.from(b.querySelectorAll("[id]"));return(S=b.getAttribute)!=null&&S.call(b,"id")&&h.push(b),h}function T(b,h,S,L){for(let O of L){let H=O.getAttribute("id");if(h.has(H)){let R=O;for(;R;){let B=b.get(R);if(B==null&&(B=new Set,b.set(R,B)),B.add(H),R===S)break;R=R.parentElement}}}}function A(b,h){let S=k(b),L=k(h),O=E(S,L),H=new Map;T(H,O,b,S);let R=h.__idiomorphRoot||h;return T(H,O,R,L),{persistentIds:O,idMap:H}}function E(b,h){let S=new Set,L=new Map;for(let{id:H,tagName:R}of b)L.has(H)?S.add(H):L.set(H,R);let O=new Set;for(let{id:H,tagName:R}of h)O.has(H)?S.add(H):L.get(H)===R&&O.add(H);for(let H of S)O.delete(H);return O}return m})(),{normalizeElement:u,normalizeParent:p}=(function(){let m=new WeakSet;function f(T){return T instanceof Document?T.documentElement:T}function w(T){if(T==null)return document.createElement("div");if(typeof T=="string")return w(k(T));if(m.has(T))return T;if(T instanceof Node){if(T.parentNode)return new v(T);{let A=document.createElement("div");return A.append(T),A}}else{let A=document.createElement("div");for(let E of[...T])A.append(E);return A}}class v{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],E=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;E&&E!=this.nextSibling;)A.push(E),E=E.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((E,b)=>{if(b instanceof Element){b.matches(A)&&E.push(b);let h=b.querySelectorAll(A);for(let S=0;S<h.length;S++)E.push(h[S])}return E},[])}insertBefore(A,E){return this.realParentNode.insertBefore(A,E)}moveBefore(A,E){return this.realParentNode.moveBefore(A,E)}get __idiomorphRoot(){return this.originalNode}}function k(T){let A=new DOMParser,E=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(E.match(/<\/html>/)||E.match(/<\/head>/)||E.match(/<\/body>/)){let b=A.parseFromString(T,"text/html");if(E.match(/<\/html>/))return m.add(b),b;{let h=b.firstChild;return h&&m.add(h),h}}else{let h=A.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return m.add(h),h}}return{normalizeElement:f,normalizeParent:w}})();return{morph:t,defaults:r}})();var Xi=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Xg.morph(e,r.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}}}}})};function Jg(e,r){var t,n,o,a,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h,S,L,O,H,R,B,j,oe,ue,De;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(a=(o=e.content)==null?void 0:o.slice(-32))!=null?a:"",e.streaming?"1":"0",(s=e.variant)!=null?s:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(m=(p=e.approval)==null?void 0:p.status)!=null?m:"",(w=(f=e.toolCall)==null?void 0:f.status)!=null?w:"",(k=(v=e.toolCall)==null?void 0:v.name)!=null?k:"",(E=(A=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:A.length)!=null?E:0,(L=(S=(h=(b=e.toolCall)==null?void 0:b.chunks)==null?void 0:h[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?L:"",typeof((O=e.toolCall)==null?void 0:O.args)=="string"?e.toolCall.args.length:(H=e.toolCall)!=null&&H.args?JSON.stringify(e.toolCall.args).length:0,(j=(B=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:B.length)!=null?j:0,(ue=(oe=e.contentParts)==null?void 0:oe.length)!=null?ue:0,(De=e.stopReason)!=null?De:"",r].join("\0")}function Kg(){return new Map}function Yg(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Qg(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Zg(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Ji(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Cs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ws(e,r){return Cs(e)-e.scrollTop<=r}function Ki(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-n;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:t}:!r&&o&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:r&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:r&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Yi(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return r&&t<0?"pause":!r&&o&&t>0&&n?"resume":"none"}var Dr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Or=1e5,Ao=Or+1;var vs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},vb=["pre","code","a","script","style"],Qi=e=>{var r,t,n,o,a;return{type:(r=e==null?void 0:e.type)!=null?r:vs.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:vs.placeholder,speed:(n=e==null?void 0:e.speed)!=null?n:vs.speed,duration:(o=e==null?void 0:e.duration)!=null?o:vs.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:vs.buffer}},th=[{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"}],As=new Map;for(let e of th)As.set(e.name,e);var ra=e=>{As.set(e.name,e)},op=e=>{th.some(r=>r.name===e)||As.delete(e)},ap=()=>Array.from(As.keys()),Ss=(e,r)=>{var t,n;return e==="none"?null:r&&Object.prototype.hasOwnProperty.call(r,e)?(t=r[e])!=null?t:null:(n=As.get(e))!=null?n:null},Zi=(e,r,t,n,o)=>{if(!o)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,n);if(!e)return e;if(r==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(r==="line"){let a=e.lastIndexOf(`
|
|
55
|
-
`);return a<0?"":e.slice(0,a)}return e},Ab=(e,r,t,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=r,o},Sb=(e,r,t,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=r,o},rp=/\s/,Tb=(e,r)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let n=t;if(r.has(n.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},kb=(e,r,t)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=(d=e.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(rp.test(a[i])){let l=i;for(;l<a.length&&rp.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&&!rp.test(a[u]);)l.appendChild(Ab(n,a[u],r,t.value)),t.value+=1,u+=1;s.appendChild(l),i=u}o.replaceChild(s,e)},Eb=(e,r,t)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=(d=e.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(Sb(n,l,r,t.value)),t.value+=1));o.replaceChild(s,e)},Ts=(e,r,t,n)=>{var p,
|
|
54
|
+
`),qe="message",nt="";for(let $t of Ue)$t.startsWith("event:")?qe=$t.replace("event:","").trim():$t.startsWith("data:")&&(nt+=$t.replace("data:","").trim());if(!nt)continue;let Ct;try{Ct=JSON.parse(nt)}catch($t){t({type:"error",error:$t instanceof Error?$t:new Error("Failed to parse chat stream payload")});continue}let Pt=qe!=="message"?qe:(Fr=Ct.type)!=null?Fr:"message";if((Ar=this.onSSEEvent)==null||Ar.call(this,Pt,Ct),this.parseSSEEvent){m.current=f;let $t=await this.handleCustomSSEEvent(Ct,t,m,p,l,C);if(m.current&&m.current!==f&&(f=m.current),$t)continue}Mt.push(Pt,Ct),ve()}}Mt.flushPending(),ve(),Mt.destroy()}};function Ig(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Ca(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Qo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ei="[Image]";function Rg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Hg(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Bg(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Wg(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function gs(e){return{type:"text",text:e}}function Dg(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Og(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;r({type:"image",image:o,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Fg(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.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: ${r.join(", ")}`}}var Ng=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],db=["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"],oo=[...Ng,...db];function cb(e){return Ng.includes(e)||e.startsWith("image/")}function Mi(e){return cb(e.type)}async function _g(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;Mi(e)?r({type:"image",image:o,mimeType:e.type,alt:e.name}):r({type:"file",data:o,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function $g(e,r=oo,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function pb(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Ug(e,r){let t=pb(r).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var Li=class{constructor(r=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=r}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 r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,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 r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),o=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let a=0;a<t;a++){let s=o.getInt16(a*2,!0);n[a]=s/32768}return n}};var Pi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,o,a){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 hs=class{constructor(r){this.config=r;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 Pi;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,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=(r=this.config)==null?void 0:r.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=...`,p=" 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 C=!1,A=T=>{C||(C=!0,clearTimeout(k),m(new Error(T)))},k=setTimeout(()=>A("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(k),f())},{once:!0}),this.ws.addEventListener("error",()=>{A("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!C){let S=T.code!==1006?` (code ${T.code})`:"";A("WebSocket connection failed"+S+"."+p)}},{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(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(r.response.audio).catch(o=>this.errorCallbacks.forEach(a=>a(o instanceof Error?o:new Error(String(o)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.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(r.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Li(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,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=(r=this.config)==null?void 0:r.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(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),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(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var a,s;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.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(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){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(r),o=this.getFormatFromMimeType(r.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(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result.split(",")[1];t(s)},o.onerror=n,o.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let l=0;l<t.length;l++)n[l]=t.charCodeAt(l);let o=r.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(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Zo=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,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=((r=this.config)==null?void 0:r.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(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ea(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!Zo.isSupported())throw new Error("Browser speech recognition not supported");return new Zo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ii(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ea({type:"runtype",runtype:e.runtype});if(Zo.isSupported())return ea({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function xs(e){try{return Ii(e),!0}catch{return!1}}var wa=class e{constructor(r={},t){this.config=r;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,o,a,s,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(o=r.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n,o;this.messages=[...(n=r.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 Yo(r);for(let a of(o=r.initialArtifacts)!=null?o:[])this.artifacts.set(a.id,{...a,status:"complete"});r.initialSelectedArtifactId!=null&&(this.selectedArtifactId=r.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return xs((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,o;try{let a=r||this.getVoiceConfigFromConfig();if(!a)throw new Error("Voice configuration not provided");this.voiceProvider=ea(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,p,f,m,C,A;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}):(p=l.transcript)!=null&&p.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 k=(A=this.pendingVoiceAssistantMessageId)!=null?A:(C=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:C.id;k&&this.ttsSpokenMessageIds.add(k)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.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(r){console.error("Failed to start voice:",r)}}}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 r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((o=r.runtype)==null?void 0:o.clientToken)||"",host:(a=r.runtype)==null?void 0:a.host,voiceId:(s=r.runtype)==null?void 0:s.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=r.browser)==null?void 0:l.language)||"en-US",continuous:(u=r.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Yo(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=r,m={id:s!=null?s:t==="user"?Ca():t==="assistant"?Qo():`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},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:o,content:a,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:m}=n,A={id:d!=null?d:o==="user"?Ca():o==="assistant"?Qo():`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:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};t.push(A)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(r){let{component:t,props:n={},text:o="",llmContent:a,id:s,createdAt:i,sequence:d}=r,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(r,t){var l,u,p,f,m;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let o=Ca(),a=Qo(),s={id:o,role:"user",content:n||Ei,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(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!A){let k={id:a,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(k)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,A||(C instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,C):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(C))))}}async continueConversation(){var o,a,s,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let r=Qo();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:r},this.handleEvent)}catch(l){let u={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,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(r,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(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,l,u,p;let n=`approval-${r.id}`,o={...r,status:t,resolvedAt:Date.now()},a={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(a),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let s=this.config.approval,i=s&&typeof s=="object"?s.onDecision:void 0;try{let f;if(i?f=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):f=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),f){let m=null;if(f instanceof Response){if(!f.ok){let C=await f.json().catch(()=>null);throw new Error((l=C==null?void 0:C.error)!=null?l:`Approval request failed: ${f.status}`)}m=f.body}else f instanceof ReadableStream&&(m=f);m?await this.connectStream(m,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${r.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(f){let m=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(r,t){let n=this.messages.find(o=>o.id===r.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(r,t){let n=this.messages.find(o=>o.id===r.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(r,t){var u,p,f,m,C,A,k,T,S,E,b,y;let n=this.messages.find(v=>v.id===r.id);if(((u=n==null?void 0:n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(p=r.agentMetadata)==null?void 0:p.executionId,a=(f=r.toolCall)==null?void 0:f.name;if(!o||!a){(C=(m=this.callbacks).onError)==null||C.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof t=="string"?void 0:t;if(s===void 0&&typeof t=="string"){let v=(A=r.toolCall)==null?void 0:A.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let B=typeof((k=M[0])==null?void 0:k.question)=="string"?M[0].question:"";B&&(s={[B]:t})}}this.markAskUserQuestionResolved(r,s),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=r.toolCall.id,d=(S=r.toolCall)==null?void 0:S.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof t=="string"?t:Object.entries(t).map(([M,B])=>`${M}: ${Array.isArray(B)?B.join(", "):B}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};l.forEach((M,B)=>{let W=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!W)return;let R=v[W],H=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${B}`,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${B}`,role:"user",content:H||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(o,{[a]:t});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((E=M==null?void 0:M.error)!=null?E:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(y=(b=this.callbacks).onError)==null||y.call(b,v instanceof Error?v:new Error(String(v)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var o;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let a={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,a),this.selectedArtifactId=t,this.emitArtifactsState(),a}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(o=r.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 r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let o=this.artifacts.get(r.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let o=this.artifacts.get(r.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...r.props},r.component&&(o.component=r.component));break}case"artifact_complete":{let o=this.artifacts.get(r.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.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(r,t=null){this.artifacts.clear();for(let n of r)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.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,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(r),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):e.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(r){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=r.find(s=>s.name===o);if(a)return a}return(n=r.find(o=>o.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(o=>o.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,a)=>{var i;if(a!==n)return o;let s={...o,...t};return((i=o.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].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 h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},qn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var rd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var nd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var od=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ad=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var sd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var id=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var ld=[["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 dd=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var cd=[["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 pd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var ud=[["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 fd=[["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 md=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var gd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var hd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var xd=[["path",{d:"M20 6 9 17l-5-5"}]];var yd=[["path",{d:"m6 9 6 6 6-6"}]];var bd=[["path",{d:"m15 18-6-6 6-6"}]];var Cd=[["path",{d:"m9 18 6-6-6-6"}]];var wd=[["path",{d:"m18 15-6-6-6 6"}]];var Ri=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Hi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var vd=[["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 Ad=[["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 Sd=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Td=[["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 kd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Ed=[["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 Md=[["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 Bi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Wi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ld=[["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 Pd=[["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 Id=[["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 Rd=[["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 Hd=[["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 Bd=[["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 Wd=[["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 Dd=[["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 Od=[["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 Fd=[["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 Nd=[["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 _d=[["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 Di=[["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 $d=[["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 Ud=[["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 qd=[["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 zd=[["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 Vd=[["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 jd=[["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 Oi=[["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 Gd=[["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 Xd=[["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 Jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Kd=[["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 Yd=[["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 Fi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Qd=[["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 Zd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var ec=[["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 tc=[["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 rc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var nc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var oc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var ac=[["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 sc=[["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 ic=[["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 lc=[["path",{d:"M5 12h14"}]];var dc=[["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 cc=[["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 pc=[["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 uc=[["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 fc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var mc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var gc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var hc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var xc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var yc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var bc=[["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 Cc=[["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 wc=[["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 vc=[["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 Ac=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Sc=[["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 Tc=[["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 kc=[["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 Ec=[["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 Mc=[["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 Ni=[["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 Lc=[["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 Pc=[["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 Ic=[["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 Rc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var _i=[["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 Hc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Bc=[["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 Wc=[["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 Dc=[["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 Oc=[["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 Fc=[["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 Nc=[["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 _c=[["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 $c=[["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 Uc=[["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 $i=[["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 qc=[["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 zc=[["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 Vc=[["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 jc=[["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 Gc=[["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 Xc=[["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 Jc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Kc=[["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 ub={activity:rd,"arrow-down":nd,"arrow-up":id,"arrow-up-right":sd,bot:ud,"chevron-down":yd,"chevron-up":wd,"chevron-right":Cd,"chevron-left":bd,check:xd,clipboard:Ad,"clipboard-copy":vd,copy:Td,file:Wd,"file-code":Rd,"file-spreadsheet":Hd,"file-text":Bd,"image-plus":Gd,loader:Qd,"loader-circle":Fi,mic:sc,paperclip:uc,"refresh-cw":Cc,search:Ac,send:Sc,"shield-alert":Ec,"shield-check":Mc,"shield-x":Ni,square:Hc,"thumbs-down":Fc,"thumbs-up":Nc,upload:zc,"volume-2":jc,x:Jc,user:Vc,mail:ec,phone:hc,calendar:gd,clock:Sd,building:fd,"map-pin":tc,lock:Zd,key:Kd,"credit-card":kd,"at-sign":ld,hash:qd,globe:Ud,link:Yd,"circle-check":Ri,"circle-x":Hi,"triangle-alert":$i,info:Jd,ban:dd,shield:Lc,"arrow-left":od,"arrow-right":ad,"external-link":Ld,ellipsis:Wi,"ellipsis-vertical":Bi,menu:nc,house:Oi,plus:yc,minus:lc,pencil:mc,trash:Uc,"trash-2":$c,save:vc,download:Md,share:kc,funnel:Di,settings:Tc,"rotate-cw":wc,maximize:rc,minimize:ic,"shopping-cart":Ic,"shopping-bag":Pc,package:pc,truck:qc,tag:Oc,gift:$d,receipt:bc,wallet:Xc,store:Wc,"dollar-sign":Ed,percent:gc,play:xc,pause:fc,"volume-x":Gc,camera:hd,image:Xd,film:Od,headphones:zd,"message-circle":oc,"message-square":ac,bell:cd,heart:Vd,star:Bc,eye:Id,"eye-off":Pd,bookmark:pd,"calendar-days":md,history:jd,timer:_c,folder:_d,"folder-open":Nd,files:Dd,sparkles:_i,zap:Kc,sun:Dc,moon:cc,flag:Fd,monitor:dc,smartphone:Rc},Ce=(e,r=24,t="currentColor",n=2)=>{let o=ub[e];return o?fb(o,r,t,n):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function fb(e,r,t,n){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(r)),o.setAttribute("height",String(r)),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"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),o.appendChild(d)}),o}var Ui={allowedTypes:oo,maxFileSize:10*1024*1024,maxFiles:4};function mb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function gb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ta=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,o;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ui.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Ui.maxFileSize,maxFiles:(o=r.maxFiles)!=null?o:Ui.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:Ui.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,o,a,s,i,d;if(r.length){for(let l of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,l,"count");continue}let u=$g(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(o=u.error)!=null&&o.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,p);continue}try{let p=await _g(l),f=Mi(l)?URL.createObjectURL(l):null,m={id:mb(),file:l,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var a,s,i;let t=this.attachments.findIndex(d=>d.id===r);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="${r}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=Mi(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let s=h("img");s.src=r.previewUrl,s.alt=r.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=h("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=gb(r.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=h("span");l.textContent=Ug(r.file.type,r.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=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let a=Ce("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(r.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ys(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,o]of Object.entries(r)){let a=t[n];qg(a)&&qg(o)?t[n]=ys(a,o):t[n]=o}return t}var mn="min(440px, calc(100vw - 24px))",qi="440px",jt={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:mn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function zg(e,r){if(!(!e&&!r))return e?r?ys(e,r):e:r}function zi(e){var r,t,n,o,a,s,i,d,l,u,p,f,m,C,A,k,T,S,E,b,y;return e?{...jt,...e,theme:zg(jt.theme,e.theme),darkTheme:zg(jt.darkTheme,e.darkTheme),launcher:{...jt.launcher,...e.launcher,dock:{...(r=jt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=jt.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...jt.copy,...e.copy},sendButton:{...jt.sendButton,...e.sendButton},statusIndicator:{...jt.statusIndicator,...e.statusIndicator},voiceRecognition:{...jt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ge,Le,Ge,Q,Se,J,ce,pe;let v=(ge=jt.features)==null?void 0:ge.artifacts,M=(Le=e.features)==null?void 0:Le.artifacts,B=(Ge=jt.features)==null?void 0:Ge.scrollToBottom,W=(Q=e.features)==null?void 0:Q.scrollToBottom,R=(Se=jt.features)==null?void 0:Se.streamAnimation,H=(J=e.features)==null?void 0:J.streamAnimation,j=(ce=jt.features)==null?void 0:ce.askUserQuestion,oe=(pe=e.features)==null?void 0:pe.askUserQuestion,ue=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},De=B===void 0&&W===void 0?void 0:{...B,...W},Xe=R===void 0&&H===void 0?void 0:{...R,...H},xe=j===void 0&&oe===void 0?void 0:{...j,...oe,styles:{...j==null?void 0:j.styles,...oe==null?void 0:oe.styles}};return{...jt.features,...e.features,...De!==void 0?{scrollToBottom:De}:{},...ue!==void 0?{artifacts:ue}:{},...Xe!==void 0?{streamAnimation:Xe}:{},...xe!==void 0?{askUserQuestion:xe}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:jt.suggestionChips,suggestionChipsConfig:{...jt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...jt.layout,...e.layout,header:{...(s=jt.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=jt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=jt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(A=(C=jt.layout)==null?void 0:C.messages)==null?void 0:A.timestamp,...(T=(k=e.layout)==null?void 0:k.messages)==null?void 0:T.timestamp}},slots:{...(S=jt.layout)==null?void 0:S.slots,...(E=e.layout)==null?void 0:E.slots}},markdown:{...jt.markdown,...e.markdown,options:{...(b=jt.markdown)==null?void 0:b.options,...(y=e.markdown)==null?void 0:y.options}},messageActions:{...jt.messageActions,...e.messageActions}}:jt}var Yc={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"}},Qc={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"}},Zc={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:mn,maxWidth:qi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function va(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;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."))?va(e,n):n}function Vi(e){let r={};function t(n,o){for(let[a,s]of Object.entries(n)){let i=`${o}.${a}`;if(typeof s=="string"){let d=va(e,s);d!==void 0&&(r[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(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function ep(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function Vg(e,r){let t={...e};for(let[n,o]of Object.entries(r)){let a=t[n];a&&typeof a=="object"&&!Array.isArray(a)&&o&&typeof o=="object"&&!Array.isArray(o)?t[n]=Vg(a,o):t[n]=o}return t}function hb(e,r){return r?Vg(e,r):e}function Aa(e,r={}){var o,a,s,i,d,l,u,p,f,m,C,A,k;let t={palette:Yc,semantic:Qc,components:Zc},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...t.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(A=e==null?void 0:e.semantic)==null?void 0:A.spacing},typography:{...t.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:hb(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let T=ep(n);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let T of r.plugins)n=T.transform(n);return n}function ji(e){var A,k,T,S,E,b,y,v,M,B,W,R,H,j,oe,ue,De,Xe,xe,ge,Le,Ge,Q,Se,J,ce,pe,ie,Oe,Pe,K,_e,$e,Y,G,we,ke,ae,ve,ye,Mt,ne,He,fr,Ot,Yt,Fr,Ar,F,le,Fe,Ke,Ue,qe,nt,Ct,Pt,$t,N,de,Ee,ut,Ye,Ut,or,It,St,rt,it,tr,gn,Rr,Tn,Tt,hn,ur,Sr,Yr,xt,kn,nn,Tr,kr,Vn,En,xn,wt,Ie,L,Z,se,kt,qt,Bt,ar,xr,Nr,Er,ot,wr,_r,po,jn,uo,Fn,on,Mn,vt,sr,ir,an,fo,yn,Ln,sn,q;let r=Vi(e),t={};for(let[he,ln]of Object.entries(r)){let Pn=he.replace(/\./g,"-");t[`--persona-${Pn}`]=ln.value}t["--persona-primary"]=(A=t["--persona-semantic-colors-primary"])!=null?A:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(k=t["--persona-semantic-colors-secondary"])!=null?k: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"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(E=t["--persona-semantic-colors-background"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(b=t["--persona-semantic-colors-container"])!=null?b:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(y=t["--persona-semantic-colors-text"])!=null?y:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(v=t["--persona-semantic-colors-text-muted"])!=null?v:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(M=t["--persona-semantic-colors-text-inverse"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(B=t["--persona-semantic-colors-border"])!=null?B:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(W=t["--persona-semantic-colors-divider"])!=null?W:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(H=t["--persona-components-voice-recording-background"])!=null?H:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(j=t["--persona-components-voice-processing-icon"])!=null?j:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ue=t["--persona-components-approval-requested-background"])!=null?ue:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(De=t["--persona-components-approval-requested-border"])!=null?De:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Xe=t["--persona-components-approval-requested-text"])!=null?Xe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(xe=t["--persona-components-approval-approve-background"])!=null?xe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ge=t["--persona-components-approval-deny-background"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Le=t["--persona-components-attachment-image-background"])!=null?Le:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Ge=t["--persona-components-attachment-image-border"])!=null?Ge:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Q=t["--persona-semantic-typography-fontFamily"])!=null?Q:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Se=t["--persona-semantic-typography-fontSize"])!=null?Se:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(J=t["--persona-semantic-typography-fontWeight"])!=null?J:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ce=t["--persona-semantic-typography-lineHeight"])!=null?ce: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"]=(pe=t["--persona-palette-radius-sm"])!=null?pe:"0.125rem",t["--persona-radius-md"]=(ie=t["--persona-palette-radius-md"])!=null?ie:"0.375rem",t["--persona-radius-lg"]=(Oe=t["--persona-palette-radius-lg"])!=null?Oe:"0.5rem",t["--persona-radius-xl"]=(Pe=t["--persona-palette-radius-xl"])!=null?Pe:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=($e=(_e=t["--persona-components-launcher-borderRadius"])!=null?_e:t["--persona-palette-radius-full"])!=null?$e:"9999px",t["--persona-launcher-bg"]=(Y=t["--persona-components-launcher-background"])!=null?Y:t["--persona-primary"],t["--persona-launcher-fg"]=(G=t["--persona-components-launcher-foreground"])!=null?G:t["--persona-text-inverse"],t["--persona-launcher-border"]=(we=t["--persona-components-launcher-border"])!=null?we:t["--persona-border"],t["--persona-button-primary-bg"]=(ke=t["--persona-components-button-primary-background"])!=null?ke:t["--persona-primary"],t["--persona-button-primary-fg"]=(ae=t["--persona-components-button-primary-foreground"])!=null?ae:t["--persona-text-inverse"],t["--persona-button-radius"]=(ye=(ve=t["--persona-components-button-primary-borderRadius"])!=null?ve:t["--persona-palette-radius-full"])!=null?ye:"9999px",t["--persona-panel-radius"]=(ne=(Mt=t["--persona-components-panel-borderRadius"])!=null?Mt:t["--persona-radius-xl"])!=null?ne:"0.75rem",t["--persona-panel-border"]=(He=t["--persona-components-panel-border"])!=null?He:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ot=(fr=t["--persona-components-panel-shadow"])!=null?fr:t["--persona-palette-shadows-xl"])!=null?Ot:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Fr=(Yt=t["--persona-components-input-borderRadius"])!=null?Yt:t["--persona-radius-lg"])!=null?Fr:"0.5rem",t["--persona-message-user-radius"]=(F=(Ar=t["--persona-components-message-user-borderRadius"])!=null?Ar:t["--persona-radius-lg"])!=null?F:"0.5rem",t["--persona-message-assistant-radius"]=(Fe=(le=t["--persona-components-message-assistant-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?Fe:"0.5rem",t["--persona-header-bg"]=(Ke=t["--persona-components-header-background"])!=null?Ke:t["--persona-surface"],t["--persona-header-border"]=(Ue=t["--persona-components-header-border"])!=null?Ue:t["--persona-divider"],t["--persona-header-icon-bg"]=(qe=t["--persona-components-header-iconBackground"])!=null?qe:t["--persona-primary"],t["--persona-header-icon-fg"]=(nt=t["--persona-components-header-iconForeground"])!=null?nt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ct=t["--persona-components-header-titleForeground"])!=null?Ct:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Pt=t["--persona-components-header-subtitleForeground"])!=null?Pt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=($t=t["--persona-components-header-actionIconForeground"])!=null?$t:t["--persona-muted"];let n=(N=e.components)==null?void 0:N.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom);let o=(de=e.components)==null?void 0:de.introCard;t["--persona-intro-card-bg"]=(Ee=t["--persona-components-introCard-background"])!=null?Ee:t["--persona-surface"],t["--persona-intro-card-radius"]=(ut=t["--persona-components-introCard-borderRadius"])!=null?ut:"1rem",t["--persona-intro-card-padding"]=(Ye=t["--persona-components-introCard-padding"])!=null?Ye:"1.5rem",t["--persona-intro-card-shadow"]=(or=(Ut=o==null?void 0:o.shadow)!=null?Ut:t["--persona-components-introCard-shadow"])!=null?or:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(It=t["--persona-components-input-background"])!=null?It:t["--persona-surface"],t["--persona-input-placeholder"]=(St=t["--persona-components-input-placeholder"])!=null?St:t["--persona-text-muted"],t["--persona-message-user-bg"]=(rt=t["--persona-components-message-user-background"])!=null?rt:t["--persona-accent"],t["--persona-message-user-text"]=(it=t["--persona-components-message-user-text"])!=null?it:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(tr=t["--persona-components-message-user-shadow"])!=null?tr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(gn=t["--persona-components-message-assistant-background"])!=null?gn:t["--persona-surface"],t["--persona-message-assistant-text"]=(Rr=t["--persona-components-message-assistant-text"])!=null?Rr:t["--persona-text"],t["--persona-message-assistant-border"]=(Tn=t["--persona-components-message-assistant-border"])!=null?Tn:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Tt=t["--persona-components-message-assistant-shadow"])!=null?Tt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(hn=t["--persona-components-scrollToBottom-background"])!=null?hn:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Yr=(Sr=t["--persona-components-scrollToBottom-foreground"])!=null?Sr:t["--persona-button-primary-fg"])!=null?Yr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(xt=t["--persona-components-scrollToBottom-border"])!=null?xt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(kn=t["--persona-components-scrollToBottom-size"])!=null?kn:"40px",t["--persona-scroll-to-bottom-radius"]=(kr=(Tr=(nn=t["--persona-components-scrollToBottom-borderRadius"])!=null?nn:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?kr:"9999px",t["--persona-scroll-to-bottom-shadow"]=(En=(Vn=t["--persona-components-scrollToBottom-shadow"])!=null?Vn:t["--persona-palette-shadows-sm"])!=null?En:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(xn=t["--persona-components-scrollToBottom-padding"])!=null?xn:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(wt=t["--persona-components-scrollToBottom-gap"])!=null?wt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(L=(Ie=t["--persona-components-scrollToBottom-fontSize"])!=null?Ie:t["--persona-palette-typography-fontSize-sm"])!=null?L:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Z=t["--persona-components-scrollToBottom-iconSize"])!=null?Z:"14px",t["--persona-tool-bubble-shadow"]=(se=t["--persona-components-toolBubble-shadow"])!=null?se:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(kt=t["--persona-components-reasoningBubble-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(qt=t["--persona-components-composer-shadow"])!=null?qt:"none",t["--persona-md-inline-code-bg"]=(Bt=t["--persona-components-markdown-inlineCode-background"])!=null?Bt:t["--persona-container"],t["--persona-md-inline-code-color"]=(ar=t["--persona-components-markdown-inlineCode-foreground"])!=null?ar:t["--persona-text"],t["--persona-md-link-color"]=(Nr=(xr=t["--persona-components-markdown-link-foreground"])!=null?xr:t["--persona-accent"])!=null?Nr:"#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"]=(Er=t["--persona-components-markdown-codeBlock-background"])!=null?Er:t["--persona-container"],t["--persona-md-code-block-border-color"]=(ot=t["--persona-components-markdown-codeBlock-borderColor"])!=null?ot:t["--persona-border"],t["--persona-md-code-block-text-color"]=(wr=t["--persona-components-markdown-codeBlock-textColor"])!=null?wr:"inherit",t["--persona-md-table-header-bg"]=(_r=t["--persona-components-markdown-table-headerBackground"])!=null?_r:t["--persona-container"],t["--persona-md-table-border-color"]=(po=t["--persona-components-markdown-table-borderColor"])!=null?po:t["--persona-border"],t["--persona-md-hr-color"]=(jn=t["--persona-components-markdown-hr-color"])!=null?jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(uo=t["--persona-components-markdown-blockquote-borderColor"])!=null?uo:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Fn=t["--persona-components-markdown-blockquote-background"])!=null?Fn:"transparent",t["--persona-md-blockquote-text-color"]=(on=t["--persona-components-markdown-blockquote-textColor"])!=null?on:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Mn=t["--persona-components-collapsibleWidget-container"])!=null?Mn:t["--persona-surface"],t["--cw-surface"]=(vt=t["--persona-components-collapsibleWidget-surface"])!=null?vt:t["--persona-surface"],t["--cw-border"]=(sr=t["--persona-components-collapsibleWidget-border"])!=null?sr:t["--persona-border"],t["--persona-message-border"]=(ir=t["--persona-components-message-border"])!=null?ir:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let C=u==null?void 0:u.artifact;if(C!=null&&C.toolbar){let he=C.toolbar;he.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,t["--persona-dropdown-bg"]=(an=t["--persona-dropdown-bg"])!=null?an:he.copyMenuBackground),he.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,t["--persona-dropdown-border"]=(fo=t["--persona-dropdown-border"])!=null?fo:he.copyMenuBorder),he.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,t["--persona-dropdown-shadow"]=(yn=t["--persona-dropdown-shadow"])!=null?yn:he.copyMenuShadow),he.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Ln=t["--persona-dropdown-radius"])!=null?Ln:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(sn=t["--persona-dropdown-item-hover-bg"])!=null?sn:he.copyMenuItemHoverBackground),he.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(C!=null&&C.tab){let he=C.tab;he.background&&(t["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(t["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(t["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(t["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(t["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(t["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(t["--persona-artifact-tab-list-padding"]=he.listPadding)}if(C!=null&&C.pane){let he=C.pane;if(he.toolbarBackground){let ln=(q=va(e,he.toolbarBackground))!=null?q:he.toolbarBackground;t["--persona-artifact-toolbar-bg"]=ln}}return t}var jg={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 xb={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"}}},Gg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},yb=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":bs()},tp=e=>yb(e),bb=e=>Aa(e),Cb=e=>{var t;let r=Aa(void 0,{validate:!1});return Aa({...e,palette:{...r.palette,colors:{...xb.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Sa=e=>{let r=tp(e),t=Gg(e==null?void 0:e.theme),n=Gg(e==null?void 0:e.darkTheme);return r==="dark"?Cb(ys(t!=null?t:{},n!=null?n:{})):bb(t)},wb=e=>ji(e),vo=(e,r)=>{var a;let t=Sa(r),n=wb(t);for(let[s,i]of Object.entries(n))e.style.setProperty(s,i);let o=(a=r==null?void 0:r.toolCall)==null?void 0:a.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},Gi=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(bs())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(bs());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Xg=(function(){"use strict";let e=()=>{},r={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:f=>f.getAttribute("im-preserve")==="true",shouldReAppend:f=>f.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function t(f,m,C={}){f=u(f);let A=p(m),k=l(f,A,C),T=o(k,()=>i(k,f,A,S=>S.morphStyle==="innerHTML"?(a(S,f,A),Array.from(f.childNodes)):n(S,f,A)));return k.pantry.remove(),T}function n(f,m,C){let A=p(m);return a(f,A,C,m,m.nextSibling),Array.from(A.childNodes)}function o(f,m){var E;if(!f.config.restoreFocus)return m();let C=document.activeElement;if(!(C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement))return m();let{id:A,selectionStart:k,selectionEnd:T}=C,S=m();return A&&A!==((E=document.activeElement)==null?void 0:E.getAttribute("id"))&&(C=f.target.querySelector(`[id="${A}"]`),C==null||C.focus()),C&&!C.selectionEnd&&T&&C.setSelectionRange(k,T),S}let a=(function(){function f(b,y,v,M=null,B=null){y instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(y=y.content,v=v.content),M||(M=y.firstChild);for(let W of v.childNodes){if(M&&M!=B){let H=C(b,W,M,B);if(H){H!==M&&k(b,M,H),s(H,W,b),M=H.nextSibling;continue}}if(W instanceof Element){let H=W.getAttribute("id");if(b.persistentIds.has(H)){let j=T(y,H,M,b);s(j,W,b),M=j.nextSibling;continue}}let R=m(y,W,M,b);R&&(M=R.nextSibling)}for(;M&&M!=B;){let W=M;M=M.nextSibling,A(b,W)}}function m(b,y,v,M){if(M.callbacks.beforeNodeAdded(y)===!1)return null;if(M.idMap.has(y)){let B=document.createElement(y.tagName);return b.insertBefore(B,v),s(B,y,M),M.callbacks.afterNodeAdded(B),B}else{let B=document.importNode(y,!0);return b.insertBefore(B,v),M.callbacks.afterNodeAdded(B),B}}let C=(function(){function b(M,B,W,R){let H=null,j=B.nextSibling,oe=0,ue=W;for(;ue&&ue!=R;){if(v(ue,B)){if(y(M,ue,B))return ue;H===null&&(M.idMap.has(ue)||(H=ue))}if(H===null&&j&&v(ue,j)&&(oe++,j=j.nextSibling,oe>=2&&(H=void 0)),M.activeElementAndParents.includes(ue))break;ue=ue.nextSibling}return H||null}function y(M,B,W){let R=M.idMap.get(B),H=M.idMap.get(W);if(!H||!R)return!1;for(let j of R)if(H.has(j))return!0;return!1}function v(M,B){var H,j,oe;let W=M,R=B;return W.nodeType===R.nodeType&&W.tagName===R.tagName&&(!((H=W.getAttribute)!=null&&H.call(W,"id"))||((j=W.getAttribute)==null?void 0:j.call(W,"id"))===((oe=R.getAttribute)==null?void 0:oe.call(R,"id")))}return b})();function A(b,y){var v;if(b.idMap.has(y))E(b.pantry,y,null);else{if(b.callbacks.beforeNodeRemoved(y)===!1)return;(v=y.parentNode)==null||v.removeChild(y),b.callbacks.afterNodeRemoved(y)}}function k(b,y,v){let M=y;for(;M&&M!==v;){let B=M;M=M.nextSibling,A(b,B)}return M}function T(b,y,v,M){var W,R;let B=((R=(W=M.target).getAttribute)==null?void 0:R.call(W,"id"))===y&&M.target||M.target.querySelector(`[id="${y}"]`)||M.pantry.querySelector(`[id="${y}"]`);return S(B,M),E(b,B,v),B}function S(b,y){let v=b.getAttribute("id");for(;b=b.parentNode;){let M=y.idMap.get(b);M&&(M.delete(v),M.size||y.idMap.delete(b))}}function E(b,y,v){if(b.moveBefore)try{b.moveBefore(y,v)}catch{b.insertBefore(y,v)}else b.insertBefore(y,v)}return f})(),s=(function(){function f(S,E,b){return b.ignoreActive&&S===document.activeElement?null:(b.callbacks.beforeNodeMorphed(S,E)===!1||(S instanceof HTMLHeadElement&&b.head.ignore||(S instanceof HTMLHeadElement&&b.head.style!=="morph"?d(S,E,b):(m(S,E,b),T(S,b)||a(b,S,E))),b.callbacks.afterNodeMorphed(S,E)),S)}function m(S,E,b){let y=E.nodeType;if(y===1){let v=S,M=E,B=v.attributes,W=M.attributes;for(let R of W)k(R.name,v,"update",b)||v.getAttribute(R.name)!==R.value&&v.setAttribute(R.name,R.value);for(let R=B.length-1;0<=R;R--){let H=B[R];if(H&&!M.hasAttribute(H.name)){if(k(H.name,v,"remove",b))continue;v.removeAttribute(H.name)}}T(v,b)||C(v,M,b)}(y===8||y===3)&&S.nodeValue!==E.nodeValue&&(S.nodeValue=E.nodeValue)}function C(S,E,b){if(S instanceof HTMLInputElement&&E instanceof HTMLInputElement&&E.type!=="file"){let y=E.value,v=S.value;A(S,E,"checked",b),A(S,E,"disabled",b),E.hasAttribute("value")?v!==y&&(k("value",S,"update",b)||(S.setAttribute("value",y),S.value=y)):k("value",S,"remove",b)||(S.value="",S.removeAttribute("value"))}else if(S instanceof HTMLOptionElement&&E instanceof HTMLOptionElement)A(S,E,"selected",b);else if(S instanceof HTMLTextAreaElement&&E instanceof HTMLTextAreaElement){let y=E.value,v=S.value;if(k("value",S,"update",b))return;y!==v&&(S.value=y),S.firstChild&&S.firstChild.nodeValue!==y&&(S.firstChild.nodeValue=y)}}function A(S,E,b,y){let v=E[b],M=S[b];if(v!==M){let B=k(b,S,"update",y);B||(S[b]=E[b]),v?B||S.setAttribute(b,""):k(b,S,"remove",y)||S.removeAttribute(b)}}function k(S,E,b,y){return S==="value"&&y.ignoreActiveValue&&E===document.activeElement?!0:y.callbacks.beforeAttributeUpdated(S,E,b)===!1}function T(S,E){return!!E.ignoreActiveValue&&S===document.activeElement&&S!==document.body}return f})();function i(f,m,C,A){if(f.head.block){let k=m.querySelector("head"),T=C.querySelector("head");if(k&&T){let S=d(k,T,f);return Promise.all(S).then(()=>{let E=Object.assign(f,{head:{block:!1,ignore:!0}});return A(E)})}}return A(f)}function d(f,m,C){let A=[],k=[],T=[],S=[],E=new Map;for(let y of m.children)E.set(y.outerHTML,y);for(let y of f.children){let v=E.has(y.outerHTML),M=C.head.shouldReAppend(y),B=C.head.shouldPreserve(y);v||B?M?k.push(y):(E.delete(y.outerHTML),T.push(y)):C.head.style==="append"?M&&(k.push(y),S.push(y)):C.head.shouldRemove(y)!==!1&&k.push(y)}S.push(...E.values());let b=[];for(let y of S){let v=document.createRange().createContextualFragment(y.outerHTML).firstChild;if(C.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,B=new Promise(function(W){M=W});v.addEventListener("load",function(){M()}),b.push(B)}f.appendChild(v),C.callbacks.afterNodeAdded(v),A.push(v)}}for(let y of k)C.callbacks.beforeNodeRemoved(y)!==!1&&(f.removeChild(y),C.callbacks.afterNodeRemoved(y));return C.head.afterHeadMorphed(f,{added:A,kept:T,removed:k}),b}let l=(function(){function f(b,y,v){let{persistentIds:M,idMap:B}=S(b,y),W=m(v),R=W.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:b,newContent:y,config:W,morphStyle:R,ignoreActive:W.ignoreActive,ignoreActiveValue:W.ignoreActiveValue,restoreFocus:W.restoreFocus,idMap:B,persistentIds:M,pantry:C(),activeElementAndParents:A(b),callbacks:W.callbacks,head:W.head}}function m(b){let y=Object.assign({},r);return Object.assign(y,b),y.callbacks=Object.assign({},r.callbacks,b.callbacks),y.head=Object.assign({},r.head,b.head),y}function C(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function A(b){let y=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&b.contains(v))for(;v&&(y.push(v),v!==b);)v=v.parentElement;return y}function k(b){var v;let y=Array.from(b.querySelectorAll("[id]"));return(v=b.getAttribute)!=null&&v.call(b,"id")&&y.push(b),y}function T(b,y,v,M){for(let B of M){let W=B.getAttribute("id");if(y.has(W)){let R=B;for(;R;){let H=b.get(R);if(H==null&&(H=new Set,b.set(R,H)),H.add(W),R===v)break;R=R.parentElement}}}}function S(b,y){let v=k(b),M=k(y),B=E(v,M),W=new Map;T(W,B,b,v);let R=y.__idiomorphRoot||y;return T(W,B,R,M),{persistentIds:B,idMap:W}}function E(b,y){let v=new Set,M=new Map;for(let{id:W,tagName:R}of b)M.has(W)?v.add(W):M.set(W,R);let B=new Set;for(let{id:W,tagName:R}of y)B.has(W)?v.add(W):M.get(W)===R&&B.add(W);for(let W of v)B.delete(W);return B}return f})(),{normalizeElement:u,normalizeParent:p}=(function(){let f=new WeakSet;function m(T){return T instanceof Document?T.documentElement:T}function C(T){if(T==null)return document.createElement("div");if(typeof T=="string")return C(k(T));if(f.has(T))return T;if(T instanceof Node){if(T.parentNode)return new A(T);{let S=document.createElement("div");return S.append(T),S}}else{let S=document.createElement("div");for(let E of[...T])S.append(E);return S}}class A{constructor(S){this.originalNode=S,this.realParentNode=S.parentNode,this.previousSibling=S.previousSibling,this.nextSibling=S.nextSibling}get childNodes(){let S=[],E=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;E&&E!=this.nextSibling;)S.push(E),E=E.nextSibling;return S}querySelectorAll(S){return this.childNodes.reduce((E,b)=>{if(b instanceof Element){b.matches(S)&&E.push(b);let y=b.querySelectorAll(S);for(let v=0;v<y.length;v++)E.push(y[v])}return E},[])}insertBefore(S,E){return this.realParentNode.insertBefore(S,E)}moveBefore(S,E){return this.realParentNode.moveBefore(S,E)}get __idiomorphRoot(){return this.originalNode}}function k(T){let S=new DOMParser,E=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(E.match(/<\/html>/)||E.match(/<\/head>/)||E.match(/<\/body>/)){let b=S.parseFromString(T,"text/html");if(E.match(/<\/html>/))return f.add(b),b;{let y=b.firstChild;return y&&f.add(y),y}}else{let y=S.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return f.add(y),y}}return{normalizeElement:m,normalizeParent:C}})();return{morph:t,defaults:r}})();var Xi=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Xg.morph(e,r.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}}}}})};function Jg(e,r){var t,n,o,a,s,i,d,l,u,p,f,m,C,A,k,T,S,E,b,y,v,M,B,W,R,H,j,oe,ue,De;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(a=(o=e.content)==null?void 0:o.slice(-32))!=null?a:"",e.streaming?"1":"0",(s=e.variant)!=null?s:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(k=(A=e.toolCall)==null?void 0:A.name)!=null?k:"",(E=(S=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:S.length)!=null?E:0,(M=(v=(y=(b=e.toolCall)==null?void 0:b.chunks)==null?void 0:y[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((B=e.toolCall)==null?void 0:B.args)=="string"?e.toolCall.args.length:(W=e.toolCall)!=null&&W.args?JSON.stringify(e.toolCall.args).length:0,(j=(H=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:H.length)!=null?j:0,(ue=(oe=e.contentParts)==null?void 0:oe.length)!=null?ue:0,(De=e.stopReason)!=null?De:"",r].join("\0")}function Kg(){return new Map}function Yg(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Qg(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Zg(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Ji(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Cs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ws(e,r){return Cs(e)-e.scrollTop<=r}function Ki(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-n;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:t}:!r&&o&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:r&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:r&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Yi(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return r&&t<0?"pause":!r&&o&&t>0&&n?"resume":"none"}var Dr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Or=1e5,Ao=Or+1;var vs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},vb=["pre","code","a","script","style"],Qi=e=>{var r,t,n,o,a;return{type:(r=e==null?void 0:e.type)!=null?r:vs.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:vs.placeholder,speed:(n=e==null?void 0:e.speed)!=null?n:vs.speed,duration:(o=e==null?void 0:e.duration)!=null?o:vs.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:vs.buffer}},th=[{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"}],As=new Map;for(let e of th)As.set(e.name,e);var ra=e=>{As.set(e.name,e)},op=e=>{th.some(r=>r.name===e)||As.delete(e)},ap=()=>Array.from(As.keys()),Ss=(e,r)=>{var t,n;return e==="none"?null:r&&Object.prototype.hasOwnProperty.call(r,e)?(t=r[e])!=null?t:null:(n=As.get(e))!=null?n:null},Zi=(e,r,t,n,o)=>{if(!o)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,n);if(!e)return e;if(r==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(r==="line"){let a=e.lastIndexOf(`
|
|
55
|
+
`);return a<0?"":e.slice(0,a)}return e},Ab=(e,r,t,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=r,o},Sb=(e,r,t,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=r,o},rp=/\s/,Tb=(e,r)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let n=t;if(r.has(n.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},kb=(e,r,t)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=(d=e.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(rp.test(a[i])){let l=i;for(;l<a.length&&rp.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&&!rp.test(a[u]);)l.appendChild(Ab(n,a[u],r,t.value)),t.value+=1,u+=1;s.appendChild(l),i=u}o.replaceChild(s,e)},Eb=(e,r,t)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=(d=e.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(Sb(n,l,r,t.value)),t.value+=1));o.replaceChild(s,e)},Ts=(e,r,t,n)=>{var p,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set(((p=n==null?void 0:n.skipTags)!=null?p:vb).map(m=>m.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=s.nextNode();for(;d;)Tb(d,a)||i.push(d),d=s.nextNode();let l={value:(f=n==null?void 0:n.startIndex)!=null?f:0},u=r==="char"?kb:Eb;for(let m of i)u(m,t,l);return o.innerHTML},el=(e=document)=>{let r=e.createElement("span");return r.className="persona-stream-caret",r.setAttribute("aria-hidden","true"),r.setAttribute("data-preserve-animation","stream-caret"),r},ks=(e=document)=>{let r=e.createElement("div");r.className="persona-stream-skeleton",r.setAttribute("data-preserve-animation","stream-skeleton"),r.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",r.appendChild(t),r},eh=new WeakMap,Mb=(e,r)=>{var a;if(!e.styles)return;let t=eh.get(r);if(t||(t=new Set,eh.set(r,t)),t.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(r.querySelector(`style[data-persona-animation="${s}"]`))return;t.delete(e.name)}t.add(e.name);let o=(r instanceof ShadowRoot?r.ownerDocument:(a=r.ownerDocument)!=null?a:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,r.appendChild(o)},np=new WeakMap,Lb=(e,r)=>{if(!e.onAttach)return;let t=np.get(r);if(t||(t=new Map,np.set(r,t)),t.has(e.name))return;let n=e.onAttach(r);t.set(e.name,n)},rh=e=>{let r=np.get(e);if(r){for(let t of r.values())typeof t=="function"&&t();r.clear()}},sp=(e,r)=>{Mb(e,r),Lb(e,r)};function ip(e,r=Or){let t=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{s&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=o}}var Es=0,So=null;function lp(e=document){var t;if(Es++,Es===1){let n=e.body,a=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;So={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 r=!1;return()=>{var n;if(!r&&(r=!0,Es=Math.max(0,Es-1),Es===0&&So)){let o=e.body,a=(n=e.defaultView)!=null?n:window;o.style.overflow=So.originalOverflow,o.style.position=So.originalPosition,o.style.top=So.originalTop,o.style.width=So.originalWidth,a.scrollTo(0,So.scrollY),So=null}}}var tl={side:"right",width:"420px",animate:!0,reveal:"resize"},hr=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},To=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="composer-bar"},vn=e=>{var t,n,o,a,s;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:tl.side,width:(o=r==null?void 0:r.width)!=null?o:tl.width,animate:(a=r==null?void 0:r.animate)!=null?a:tl.animate,reveal:(s=r==null?void 0:r.reveal)!=null?s:tl.reveal}};var On={"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 Ms=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
56
56
|
<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>
|
|
57
57
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
58
58
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -60,14 +60,14 @@ Please report this to https://github.com/markedjs/marked.`,r){let o="<p>An error
|
|
|
60
60
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
61
61
|
</span>
|
|
62
62
|
<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>
|
|
63
|
-
`,t.addEventListener("click",r);let n=a=>{var E,b,h,S,L,O,H,R,B,j,oe,ue,De,Xe;let s=(E=a.launcher)!=null?E:{},i=hr(a),d=t.querySelector("[data-role='launcher-title']");if(d){let xe=(b=s.title)!=null?b:"Chat Assistant";d.textContent=xe,d.setAttribute("title",xe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let xe=(h=s.subtitle)!=null?h:"Get answers fast";l.textContent=xe,l.setAttribute("title",xe)}let u=t.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(s.agentIconHidden)p.style.display="none";else{let xe=(S=s.agentIconSize)!=null?S:"40px";if(p.style.height=xe,p.style.width=xe,p.innerHTML="",s.agentIconName){let ge=parseFloat(xe)||24,Le=Ce(s.agentIconName,ge*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(p.appendChild(Le),p.style.display=""):(p.textContent=(L=s.agentIconText)!=null?L:"\u{1F4AC}",p.style.display="")}else s.iconUrl?p.style.display="none":(p.textContent=(O=s.agentIconText)!=null?O:"\u{1F4AC}",p.style.display="")}let m=t.querySelector("[data-role='launcher-image']");if(m){let xe=(H=s.agentIconSize)!=null?H:"40px";m.style.height=xe,m.style.width=xe,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(m.src=s.iconUrl,m.style.display="block"):m.style.display="none"}let f=t.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let xe=(R=s.callToActionIconSize)!=null?R:"32px";f.style.height=xe,f.style.width=xe,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 ge=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,ge=(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 Le=parseFloat(xe)||24,Ge=Math.max(Le-ge,8),Q=Ce(s.callToActionIconName,Ge,"currentColor",2);Q?f.appendChild(Q):f.textContent=(B=s.callToActionIconText)!=null?B:"\u2197"}else f.textContent=(j=s.callToActionIconText)!=null?j:"\u2197"}let w=s.position&&On[s.position]?On[s.position]:On["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?k:`${v} ${w}`,i||(t.style.zIndex=String((oe=s.zIndex)!=null?oe:Or));let T="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(ue=s.border)!=null?ue:T,t.style.boxShadow=(De=s.shadow)!=null?De:A,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=(Xe=s.collapsedMaxWidth)!=null?Xe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:o}};var Pb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",rl=(e,r={})=>{var v,k,T,A,E,b;let{showClose:t=!0,wrapperClassName:n=Pb,buttonSize:o,iconSize:a="28px"}=r,s=(v=e==null?void 0:e.launcher)!=null?v:{},i=(k=o!=null?o:s.closeButtonSize)!=null?k:"32px",d=x("div",n),l=x("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",p=(A=s.closeButtonShowTooltip)!=null?A:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let m=(E=s.closeButtonIconName)!=null?E:"x",f=(b=s.closeButtonIconText)!=null?b:"\xD7";l.style.color=s.closeButtonColor||Kr.actionIconColor;let w=Ce(m,a,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):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 h=s.closeButtonBorderWidth||"0px",S=s.closeButtonBorderColor||"transparent";l.style.border=`${h} solid ${S}`,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),p&&u){let h=null,S=()=>{if(h)return;let O=l.ownerDocument,H=O.body;if(!H)return;h=qn(O,"div","persona-clear-chat-tooltip"),h.textContent=u;let R=qn(O,"div");R.className="persona-clear-chat-tooltip-arrow",h.appendChild(R);let B=l.getBoundingClientRect();h.style.position="fixed",h.style.zIndex=String(Ao),h.style.left=`${B.left+B.width/2}px`,h.style.top=`${B.top-8}px`,h.style.transform="translate(-50%, -100%)",H.appendChild(h)},L=()=>{h&&h.parentNode&&(h.parentNode.removeChild(h),h=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",L),l.addEventListener("focus",S),l.addEventListener("blur",L),d._cleanupTooltip=()=>{L(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",L),l.removeEventListener("focus",S),l.removeEventListener("blur",L)}}return{button:l,wrapper:d}},Ib="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",nl=(e,r={})=>{var h,S,L,O,H,R,B,j,oe,ue,De,Xe,xe;let{wrapperClassName:t=Ib,buttonSize:n,iconSize:o="20px"}=r,s=(S=((h=e==null?void 0:e.launcher)!=null?h:{}).clearChat)!=null?S:{},i=(L=n!=null?n:s.size)!=null?L:"32px",d=(O=s.iconName)!=null?O:"refresh-cw",l=(H=s.iconColor)!=null?H:"",u=(R=s.backgroundColor)!=null?R:"",p=(B=s.borderWidth)!=null?B:"",m=(j=s.borderColor)!=null?j:"",f=(oe=s.borderRadius)!=null?oe:"",w=(ue=s.paddingX)!=null?ue:"",v=(De=s.paddingY)!=null?De:"",k=(Xe=s.tooltipText)!=null?Xe:"Clear chat",T=(xe=s.showTooltip)!=null?xe:!0,A=x("div",t),E=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");E.style.height=i,E.style.width=i,E.type="button",E.setAttribute("aria-label",k),E.style.color=l||Kr.actionIconColor;let b=Ce(d,o,"currentColor",1);if(b&&(b.style.display="block",E.appendChild(b)),u&&(E.style.backgroundColor=u,E.classList.remove("hover:persona-bg-gray-100")),p||m){let ge=p||"0px",Le=m||"transparent";E.style.border=`${ge} solid ${Le}`,E.classList.remove("persona-border-none")}if(f&&(E.style.borderRadius=f,E.classList.remove("persona-rounded-full")),w&&(E.style.paddingLeft=w,E.style.paddingRight=w),v&&(E.style.paddingTop=v,E.style.paddingBottom=v),A.appendChild(E),T&&k){let ge=null,Le=()=>{if(ge)return;let Q=E.ownerDocument,Se=Q.body;if(!Se)return;ge=qn(Q,"div","persona-clear-chat-tooltip"),ge.textContent=k;let J=qn(Q,"div");J.className="persona-clear-chat-tooltip-arrow",ge.appendChild(J);let ce=E.getBoundingClientRect();ge.style.position="fixed",ge.style.zIndex=String(Ao),ge.style.left=`${ce.left+ce.width/2}px`,ge.style.top=`${ce.top-8}px`,ge.style.transform="translate(-50%, -100%)",Se.appendChild(ge)},Ge=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};A.addEventListener("mouseenter",Le),A.addEventListener("mouseleave",Ge),E.addEventListener("focus",Le),E.addEventListener("blur",Ge),A._cleanupTooltip=()=>{Ge(),A.removeEventListener("mouseenter",Le),A.removeEventListener("mouseleave",Ge),E.removeEventListener("focus",Le),E.removeEventListener("blur",Ge)}}return{button:E,wrapper:A}};var Kr={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))"},ao=e=>{var h,S,L,O,H,R,B,j,oe,ue,De,Xe,xe,ge,Le,Ge;let{config:r,showClose:t=!0}=e,n=x("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=(h=r==null?void 0:r.launcher)!=null?h:{},a=(S=o.headerIconSize)!=null?S:"48px",s=(L=o.closeButtonPlacement)!=null?L:"inline",i=(O=o.headerIconHidden)!=null?O:!1,d=o.headerIconName,l=x("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 Q=parseFloat(a)||24,Se=Ce(d,Q*.6,"currentColor",1);Se?l.replaceChildren(Se):l.textContent=(R=(H=r==null?void 0:r.launcher)==null?void 0:H.agentIconText)!=null?R:"\u{1F4AC}"}else if((B=r==null?void 0:r.launcher)!=null&&B.iconUrl){let Q=x("img");Q.src=r.launcher.iconUrl,Q.alt="",Q.className="persona-rounded-xl persona-object-cover",Q.style.height=a,Q.style.width=a,l.replaceChildren(Q)}else l.textContent=(oe=(j=r==null?void 0:r.launcher)==null?void 0:j.agentIconText)!=null?oe:"\u{1F4AC}";let u=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=x("span","persona-text-base persona-font-semibold");p.style.color=Kr.titleColor,p.textContent=(De=(ue=r==null?void 0:r.launcher)==null?void 0:ue.title)!=null?De:"Chat Assistant";let m=x("span","persona-text-xs");m.style.color=Kr.subtitleColor,m.textContent=(xe=(Xe=r==null?void 0:r.launcher)==null?void 0:Xe.subtitle)!=null?xe:"Here to help you get answers fast",u.append(p,m),i?n.append(u):n.append(l,u);let f=(ge=o.clearChat)!=null?ge:{},w=(Le=f.enabled)!=null?Le:!0,v=(Ge=f.placement)!=null?Ge:"inline",k=null,T=null;if(w){let Se=nl(r,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=Se.button,T=Se.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&n.appendChild(T)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:E,wrapper:b}=rl(r,{showClose:t,wrapperClassName:A});return s!=="top-right"&&n.appendChild(b),{header:n,iconHolder:l,headerTitle:p,headerSubtitle:m,closeButton:E,closeButtonWrapper:b,clearChatButton:k,clearChatButtonWrapper:T}},na=(e,r,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";e.appendChild(r.header),o==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function ko(e){let{items:r,onSelect:t,anchor:n,position:o="bottom-left",portal:a}=e,s=x("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(Ao)):(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 r){if(f.dividerBefore){let k=document.createElement("hr");s.appendChild(k)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",f.id),f.destructive&&w.setAttribute("data-destructive",""),f.icon){let k=Ce(f.icon,16,"currentColor",1.5);k&&w.appendChild(k)}let v=document.createElement("span");v.textContent=f.label,w.appendChild(v),w.addEventListener("click",k=>{k.stopPropagation(),u(),t(f.id)}),s.appendChild(w)}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=w=>{!s.contains(w.target)&&!n.contains(w.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 p(){s.classList.contains("persona-hidden")?l():u()}function m(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:u,toggle:p,destroy:m}}function Qt(e){let{icon:r,label:t,size:n,strokeWidth:o,className:a,onClick:s,aria:i}=e,d=x("button","persona-icon-btn"+(a?" "+a:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Ce(r,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),s&&d.addEventListener("click",s),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ls(e){let{icon:r,label:t,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:d}=e,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,s&&(l+=" "+s);let u=x("button",l);if(u.type="button",u.setAttribute("aria-label",t),r){let m=Ce(r,a!=null?a:14,"currentColor",2);m&&u.appendChild(m)}let p=x("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[m,f]of Object.entries(d))u.setAttribute(m,f);return u}function Ps(e){let{items:r,selectedId:t,onSelect:n,className:o}=e,a=x("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 r){let p;u.icon?p=Qt({icon:u.icon,label:u.label,onClick:()=>{s=u.id,d(),n(u.id)}}):(p=x("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{s=u.id,d(),n(u.id)})),p.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:p}),a.appendChild(p)}function l(u){s=u,d()}return{element:a,setSelected:l}}function ol(e){var f,w;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:d}=e,l=x("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",r);let u=x("span","persona-combo-btn-label");u.textContent=r,l.appendChild(u);let p=Ce(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(w=d.padding)!=null?w:"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 v,k;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(k=d.border)!=null?k:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let m=ko({items:n,onSelect:v=>{l.setAttribute("aria-expanded","false"),o(v)},anchor:l,position:a,portal:s});return s||l.appendChild(m.element),l.addEventListener("click",v=>{v.stopPropagation();let k=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",k?"false":"true"),m.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{u.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),m.show()},close:()=>{l.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let v=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),l.remove()}}}var dp=e=>{var n;let r=ao({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let o=r.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 r};function Rb(e,r,t){var n,o,a;if(r!=null&&r.length)for(let s of r){let i=x("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=Ce(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=x("div","persona-relative");d.appendChild(i);let l=ko({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()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(s.id)),e.appendChild(i)}}var cp=e=>{var A,E,b,h,S,L,O,H,R;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=(A=r==null?void 0:r.launcher)!=null?A:{},i=x("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=ol({label:(E=s.title)!=null?E:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Kr.titleColor,u=(b=l.querySelector(".persona-combo-btn-label"))!=null?b:l;else{if(l=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=x("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Kr.titleColor,u.textContent=(h=s.title)!=null?h:"Chat Assistant",l.appendChild(u),Rb(l,o==null?void 0:o.trailingActions,(S=o==null?void 0:o.onAction)!=null?S:a),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let j=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||j()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),j())})}let B=o==null?void 0:o.titleRowHover;B&&(l.style.borderRadius=(L=B.borderRadius)!=null?L:"10px",l.style.padding=(O=B.padding)!=null?O:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var j,oe;l.style.backgroundColor=(j=B.background)!=null?j:"",l.style.borderColor=(oe=B.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(H=s.closeButtonSize)!=null?H:"32px",m=x("div",""),f=x("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=p,f.style.width=p,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=t?"":"none",f.style.color=s.closeButtonColor||Kr.actionIconColor;let w=(R=s.closeButtonIconName)!=null?R:"x",v=Ce(w,"28px","currentColor",1);v?f.appendChild(v):f.textContent="\xD7",n&&f.addEventListener("click",n),m.appendChild(f),i.appendChild(m);let k=x("div");k.style.display="none";let T=x("span");return T.style.display="none",{header:i,iconHolder:k,headerTitle:u,headerSubtitle:T,closeButton:f,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}},al={default:dp,minimal:cp},pp=e=>{var r;return(r=al[e])!=null?r:al.default},Ta=(e,r,t)=>{var s,i,d;if(r!=null&&r.render){let l=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),u=x("div");u.style.display="none";let p=x("span"),m=x("span"),f=x("button");f.style.display="none";let w=x("div");return w.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:m,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let n=(s=r==null?void 0:r.layout)!=null?s:"default",a=pp(n)({config:e,showClose:(d=(i=r==null?void 0:r.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:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(a.iconHolder.style.display="none"),r.showTitle===!1&&(a.headerTitle.style.display="none"),r.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(a.closeButton.style.display="none"),r.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var sl=e=>{var s,i;let r=x("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",r.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",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,n=20;r.style.maxHeight=`${t*n}px`,r.style.overflowY="auto";let o=()=>{let d=parseFloat(r.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*n},a=()=>{r.addEventListener("input",()=>{r.style.height="auto";let d=Math.min(r.scrollHeight,o());r.style.height=`${d}px`})};return r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:a}},il=e=>{var h,S,L,O,H,R,B,j,oe,ue,De,Xe;let r=(h=e==null?void 0:e.sendButton)!=null?h:{},t=(S=r.useIcon)!=null?S:!1,n=(L=r.iconText)!=null?L:"\u2191",o=r.iconName,a=(O=r.stopIconName)!=null?O:"square",s=(H=r.tooltipText)!=null?H:"Send message",i=(R=r.stopTooltipText)!=null?R:"Stop generating",d=(j=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?j:"Send",l=(ue=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?ue:"Stop",u=(De=r.showTooltip)!=null?De:!1,p=(Xe=r.size)!=null?Xe:"40px",m=r.backgroundColor,f=r.textColor,w=x("div","persona-send-button-wrapper"),v=x("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");v.type="submit",v.setAttribute("data-persona-composer-submit","");let k=null,T=null;if(t){v.style.width=p,v.style.height=p,v.style.minWidth=p,v.style.minHeight=p,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",f?v.style.color=f:v.style.color="var(--persona-button-primary-fg, #ffffff)";let xe=parseFloat(p)||24,ge=(f==null?void 0:f.trim())||"currentColor";o?(k=Ce(o,xe,ge,2),k?v.appendChild(k):v.textContent=n):v.textContent=n,T=Ce(a,xe,ge,2),m?v.style.backgroundColor=m:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,f?v.style.color=f:v.classList.add("persona-text-white");r.borderWidth&&(v.style.borderWidth=r.borderWidth,v.style.borderStyle="solid"),r.borderColor&&(v.style.borderColor=r.borderColor),r.paddingX?(v.style.paddingLeft=r.paddingX,v.style.paddingRight=r.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.paddingY?(v.style.paddingTop=r.paddingY,v.style.paddingBottom=r.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let A=null;u&&s&&(A=x("div","persona-send-button-tooltip"),A.textContent=s,w.appendChild(A)),v.setAttribute("aria-label",s),w.appendChild(v);let E="send";return{button:v,wrapper:w,setMode:xe=>{if(xe===E)return;E=xe;let ge=xe==="stop"?i:s;if(v.setAttribute("aria-label",ge),A&&(A.textContent=ge),t){if(k&&T){let Le=xe==="stop"?T:k,Ge=xe==="stop"?k:T;Ge.parentNode===v?v.replaceChild(Le,Ge):v.appendChild(Le)}}else v.textContent=xe==="stop"?l:d}}},ll=e=>{var A,E,b,h,S,L,O,H,R,B,j,oe;let r=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(r.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((E=r.provider)==null?void 0:E.type)==="runtype";if(!(n||o))return null;let s=(h=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?h:"40px",i=x("div","persona-send-button-wrapper"),d=x("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=(S=r.iconName)!=null?S:"mic",u=(L=r.iconSize)!=null?L:s,p=parseFloat(u)||24,m=(H=r.backgroundColor)!=null?H:(O=e==null?void 0:e.sendButton)==null?void 0:O.backgroundColor,f=(B=r.iconColor)!=null?B:(R=e==null?void 0:e.sendButton)==null?void 0:R.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 v=Ce(l,p,f||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",m&&(d.style.backgroundColor=m),r.borderWidth&&(d.style.borderWidth=r.borderWidth,d.style.borderStyle="solid"),r.borderColor&&(d.style.borderColor=r.borderColor),r.paddingX&&(d.style.paddingLeft=r.paddingX,d.style.paddingRight=r.paddingX),r.paddingY&&(d.style.paddingTop=r.paddingY,d.style.paddingBottom=r.paddingY),i.appendChild(d);let k=(j=r.tooltipText)!=null?j:"Start voice recognition";if(((oe=r.showTooltip)!=null?oe:!1)&&k){let ue=x("div","persona-send-button-tooltip");ue.textContent=k,i.appendChild(ue)}return{button:d,wrapper:i}},dl=e=>{var w,v,k,T,A,E,b,h;let r=(w=e==null?void 0:e.attachments)!=null?w:{};if(r.enabled!==!0)return null;let t=(k=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?k:"40px",n=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=x("input");o.type="file",o.accept=((T=r.allowedTypes)!=null?T:oo).join(","),o.multiple=((A=r.maxFiles)!=null?A:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let a=x("div","persona-send-button-wrapper"),s=x("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",(E=r.buttonTooltipText)!=null?E:"Attach file");let i=(b=r.buttonIconName)!=null?b:"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 p=Ce(i,u,"currentColor",1.5);p?s.appendChild(p):s.textContent="\u{1F4CE}",s.addEventListener("click",S=>{S.preventDefault(),o.click()}),a.appendChild(s);let m=(h=r.buttonTooltipText)!=null?h:"Attach file",f=x("div","persona-send-button-tooltip");return f.textContent=m,a.appendChild(f),{button:s,wrapper:a,input:o,previewsContainer:n}},cl=e=>{var s,i,d;let r=(s=e==null?void 0:e.statusIndicator)!=null?s:{},t=r.align==="left"?"persona-text-left":r.align==="center"?"persona-text-center":"persona-text-right",n=x("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=r.visible)!=null?i:!0;n.style.display=o?"":"none";let a=(d=r.idleText)!=null?d:"Online";if(r.idleLink){let l=x("a");l.href=r.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},pl=()=>x("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ka=e=>{var w,v,k,T,A,E;let{config:r}=e,t=x("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=pl(),o=x("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}=sl(r);s();let i=il(r),d=ll(r),l=dl(r),u=cl(r);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(a);let p=x("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),m=x("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=x("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&m.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),p.append(m,f),o.append(p),o.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.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:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:p,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var nh=()=>{let e=x("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let r=x("span","persona-pill-peek__icon"),t=Ce("message-square",16,"currentColor",1.5);t&&r.appendChild(t);let n=x("span","persona-pill-peek__text"),o=x("span","persona-pill-peek__caret"),a=Ce("chevron-up",16,"currentColor",1.5);return a&&o.appendChild(a),e.append(r,n,o),{root:e,textNode:n}},oh=e=>{var w,v,k,T,A,E;let{config:r}=e,t=x("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let n=pl();n.style.display="none";let o=cl(r);o.style.display="none";let{textarea:a,attachAutoResize:s}=sl(r);a.style.maxHeight="100px",s();let i=il(r),d=ll(r),l=dl(r);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=x("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=x("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let m=x("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&m.append(d.wrapper),m.append(i.wrapper),u.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&u.append(l.input),u.append(p,a,m),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:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var ah=e=>{var u,p,m,f,w,v,k,T,A,E,b,h,S,L,O,H,R;let r=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=hr(e);if(To(e)){let B=(f=(m=e==null?void 0:e.launcher)==null?void 0:m.composerBar)!=null?f:{},j=x("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(w=B.expandedSize)!=null?w:"anchored",j.style.zIndex=String((k=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?k:Or);let oe=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",j.appendChild(oe);let ue=x("div","persona-widget-pill-root");return ue.setAttribute("data-persona-composer-bar",""),ue.dataset.state="collapsed",ue.dataset.expandedSize=(T=B.expandedSize)!=null?T:"anchored",ue.style.zIndex=String((E=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?E:Or),{wrapper:j,panel:oe,pillRoot:ue}}if(t){let B=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return B.appendChild(j),{wrapper:B,panel:j}}if(!r){let B=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(h=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?h:"100%";return B.style.width=oe,j.style.width="100%",B.appendChild(j),{wrapper:B,panel:j}}let o=(S=e==null?void 0:e.launcher)!=null?S:{},a=o.position&&On[o.position]?On[o.position]:On["bottom-right"],s=x("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((O=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?O:Or);let i=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:mn;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},Hb=(e,r)=>{var b,h,S,L,O,H,R,B,j;let t=x("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}=rl(e,{showClose:r,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=(S=(h=(b=e==null?void 0:e.launcher)==null?void 0:b.clearChat)==null?void 0:h.enabled)!=null?S:!0,s=null,i=null;if(a){let oe=nl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=x("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=x("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=x("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 p=x("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(O=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?O:"Hello \u{1F44B}";let m=x("p","persona-mt-2 persona-text-sm persona-text-persona-muted");m.textContent=(R=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",u.append(p,m);let f=x("div","persona-flex persona-flex-col persona-gap-3"),w=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;w&&(f.style.maxWidth=w,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((j=e==null?void 0:e.copy)==null?void 0:j.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,f);let k=x("div","persona-composer-overlay persona-pointer-events-none");k.setAttribute("data-persona-composer-overlay",""),k.style.position="absolute",k.style.left="0",k.style.right="0",k.style.bottom="0",k.style.zIndex="20";let T=oh({config:e}),{root:A,textNode:E}=nh();return t.append(d,o,l,k),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:f,composerOverlay:k,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:m,closeButton:n,closeButtonWrapper:o,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:A,peekTextNode:E}},sh=(e,r=!0)=>{var k,T,A,E,b,h,S,L,O;if(To(e))return Hb(e,r);let t=x("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=(k=e==null?void 0:e.layout)==null?void 0:k.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,a=n?Ta(e,n,{showClose:r}):ao({config:e,showClose:r}),s=x("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");s.id="persona-scroll-container",s.setAttribute("data-persona-theme-zone","messages");let i=x("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=hr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=x("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(E=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?E:"Hello \u{1F44B}";let l=x("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(h=(b=e==null?void 0:e.copy)==null?void 0:b.welcomeSubtitle)!=null?h:"Ask anything about your account or products.",i.append(d,l);let u=x("div","persona-flex persona-flex-col persona-gap-3"),p=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((L=e==null?void 0:e.copy)==null?void 0:L.showWelcomeCard)!==!1||(i.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(i,u);let f=ka({config:e}),w=((O=e==null?void 0:e.layout)==null?void 0:O.showFooter)!==!1;o?na(t,a,e):(a.header.style.display="none",na(t,a,e)),t.append(s);let v=x("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",w||(f.footer.style.display="none"),t.append(f.footer),t.append(v),{container:t,body:s,messagesWrapper:u,composerOverlay:v,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 Bb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Wb=(e,r)=>{if(!e)return null;let t=Bb(e);if(t===null)return null;let n=r==null?void 0:r[e],o=n!==void 0?n:t;return o||null},Db=(e,r)=>{let t=x("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=r,t},Ob=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},up=e=>{let r=e.toLowerCase();return r.startsWith("javascript:")||r.startsWith("data:text/html")||r.startsWith("data:text/javascript")||r.startsWith("data:text/xml")||r.startsWith("data:application/xhtml")||r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:")||!e.includes(":"))},fp=320,lh=320,Fb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="audio"&&typeof r.audio=="string"&&r.audio.trim().length>0),_b=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="video"&&typeof r.video=="string"&&r.video.trim().length>0),$b=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="file"&&typeof r.data=="string"&&r.data.trim().length>0),Ub=(e,r,t)=>{if(e.length===0)return null;try{let n=x("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=x("img");l.alt=((p=i.alt)==null?void 0:p.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=`${fp}px`,l.style.maxHeight=`${lh}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}),Ob(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}},qb=e=>{if(e.length===0)return null;try{let r=x("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(n=>{if(!up(n.audio))return;let o=x("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${fp}px`,r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},zb=e=>{if(e.length===0)return null;try{let r=x("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","video");let t=0;return e.forEach(n=>{if(!up(n.video))return;let o=x("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${fp}px`,o.style.maxHeight=`${lh}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},Vb=e=>{if(e.length===0)return null;try{let r=x("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","files");let t=0;return e.forEach(n=>{if(!up(n.data))return;let o=x("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",r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},oa=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="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",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(o),e},mp=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:oa};if(r){let o=r(n);if(o!==null)return o}return oa()},jb=(e,r)=>{let t=x("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=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=x("img");o.src=n,o.alt=r==="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(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},ih=(e,r)=>{let t=x("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Gb=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="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"),e==="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"),e==="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},gp=(e,r,t)=>{var f,w,v,k,T,A;let n=(f=r.showCopy)!=null?f:!0,o=(w=r.showUpvote)!=null?w:!0,a=(v=r.showDownvote)!=null?v:!0;if(!n&&!o&&!a){let E=x("div");return E.style.display="none",E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id),E}let s=(k=r.visibility)!=null?k:"hover",i=(T=r.align)!=null?T:"right",d=(A=r.layout)!=null?A:"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],p=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${s==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(E,b,h)=>{let S=Qt({icon:E,label:b,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",h),S};return n&&p.appendChild(m("copy","Copy message","copy")),o&&p.appendChild(m("thumbs-up","Upvote","upvote")),a&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Ea=(e,r,t,n,o,a)=>{var Q,Se,J,ce,pe,ie,Oe,Pe,K,_e,$e,Y,G,we,ke,ae,ve;let s=t!=null?t:{},i=(Q=s.layout)!=null?Q:"bubble",d=s.avatar,l=s.timestamp,u=(Se=d==null?void 0:d.show)!=null?Se:!1,p=(J=l==null?void 0:l.show)!=null?J:!1,m=(ce=d==null?void 0:d.position)!=null?ce:"left",f=(pe=l==null?void 0:l.position)!=null?pe:"below",w=Gb(e.role,i),v=x("div",w.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=Fb(e),T=(Oe=(ie=e.content)==null?void 0:ie.trim())!=null?Oe:"",E=k.length>0&&T===Ei,b=Qi((K=(Pe=a==null?void 0:a.widgetConfig)==null?void 0:Pe.features)==null?void 0:K.streamAnimation),h=(Y=($e=(_e=a==null?void 0:a.widgetConfig)==null?void 0:_e.features)==null?void 0:$e.streamAnimation)==null?void 0:Y.plugins,S=e.role==="assistant"&&b.type!=="none"?Ss(b.type,h):null,L=e.role==="assistant"&&((G=S==null?void 0:S.isAnimating)==null?void 0:G.call(S,e))===!0,O=e.role==="assistant"&&S!==null&&(!!e.streaming||L);O&&(S!=null&&S.bubbleClass)&&v.classList.add(S.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),O&&S&&(S.containerClass&&H.classList.add(S.containerClass),H.style.setProperty("--persona-stream-step",`${b.speed}ms`),H.style.setProperty("--persona-stream-duration",`${b.duration}ms`));let R=O?Zi((we=e.content)!=null?we:"",b.buffer,S,e,!!e.streaming):(ke=e.content)!=null?ke:"",B=r({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),j=B;O&&(S==null?void 0:S.wrap)==="char"?j=Ts(B,"char",e.id,{skipTags:S.skipTags}):O&&(S==null?void 0:S.wrap)==="word"&&(j=Ts(B,"word",e.id,{skipTags:S.skipTags}));let oe=null;if(E?(oe=document.createElement("div"),oe.innerHTML=j,oe.style.display="none",H.appendChild(oe)):H.innerHTML=j,O&&(S!=null&&S.useCaret)&&!E&&T){let ye=el(),Mt=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ne=Mt[Mt.length-1];if(ne!=null&&ne.parentNode)ne.parentNode.insertBefore(ye,ne.nextSibling);else{let He=H.lastElementChild;He?He.appendChild(ye):H.appendChild(ye)}}if(p&&f==="inline"&&e.createdAt){let ye=ih(e,l);ye.classList.add("persona-ml-2","persona-inline"),H.appendChild(ye)}if(k.length>0){let ye=Ub(k,!E&&!!T,()=>{E&&oe&&(oe.style.display="")});ye?v.appendChild(ye):E&&oe&&(oe.style.display="")}let ue=Nb(e);if(ue.length>0){let ye=qb(ue);ye&&v.appendChild(ye)}let De=_b(e);if(De.length>0){let ye=zb(De);ye&&v.appendChild(ye)}let Xe=$b(e);if(Xe.length>0){let ye=Vb(Xe);ye&&v.appendChild(ye)}if(v.appendChild(H),p&&f==="below"&&e.createdAt){let ye=ih(e,l);ye.classList.add("persona-mt-1"),v.appendChild(ye)}let xe=e.role==="assistant"?Wb(e.stopReason,(ve=(ae=a==null?void 0:a.widgetConfig)==null?void 0:ae.copy)==null?void 0:ve.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ye=!!(R&&R.trim()),Mt=b.placeholder==="skeleton",ne=Mt&&b.buffer==="line"&&ye;if(ye)ne&&v.appendChild(ks());else if(Mt)v.appendChild(ks());else{let He=mp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);He&&v.appendChild(He)}}if(xe&&e.stopReason&&!e.streaming&&(T||(H.style.display="none"),v.appendChild(Db(e.stopReason,xe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let ye=gp(e,n,o);v.appendChild(ye)}if(!u||e.role==="system")return v;let Le=x("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ge=jb(d,e.role);return m==="right"||m==="left"&&e.role==="user"?Le.append(v,Ge):Le.append(Ge,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},dh=(e,r,t,n,o,a)=>{let s=t!=null?t:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ea(e,r,t,n,o,a)};var Ma=new Set,Xb=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Jb=(e,r)=>{var n,o;let t=(o=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
|
|
64
|
-
`):""},ch=(e,r)=>{let t=Ma.has(e),n=r.querySelector('button[data-expand-header="true"]'),o=r.querySelector(".persona-border-t"),a=r.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=Ce(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")},hp=(e,r)=>{var De,Xe,xe,ge,Le,Ge,Q,Se,J,ce,pe;let t=e.reasoning,n=
|
|
63
|
+
`,t.addEventListener("click",r);let n=a=>{var E,b,y,v,M,B,W,R,H,j,oe,ue,De,Xe;let s=(E=a.launcher)!=null?E:{},i=hr(a),d=t.querySelector("[data-role='launcher-title']");if(d){let xe=(b=s.title)!=null?b:"Chat Assistant";d.textContent=xe,d.setAttribute("title",xe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let xe=(y=s.subtitle)!=null?y:"Get answers fast";l.textContent=xe,l.setAttribute("title",xe)}let u=t.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(s.agentIconHidden)p.style.display="none";else{let xe=(v=s.agentIconSize)!=null?v:"40px";if(p.style.height=xe,p.style.width=xe,p.innerHTML="",s.agentIconName){let ge=parseFloat(xe)||24,Le=Ce(s.agentIconName,ge*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(p.appendChild(Le),p.style.display=""):(p.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",p.style.display="")}else s.iconUrl?p.style.display="none":(p.textContent=(B=s.agentIconText)!=null?B:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let xe=(W=s.agentIconSize)!=null?W:"40px";f.style.height=xe,f.style.width=xe,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(f.src=s.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let xe=(R=s.callToActionIconSize)!=null?R:"32px";m.style.height=xe,m.style.width=xe,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let ge=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,ge=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let Le=parseFloat(xe)||24,Ge=Math.max(Le-ge,8),Q=Ce(s.callToActionIconName,Ge,"currentColor",2);Q?m.appendChild(Q):m.textContent=(H=s.callToActionIconText)!=null?H:"\u2197"}else m.textContent=(j=s.callToActionIconText)!=null?j:"\u2197"}let C=s.position&&On[s.position]?On[s.position]:On["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?k:`${A} ${C}`,i||(t.style.zIndex=String((oe=s.zIndex)!=null?oe:Or));let T="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(ue=s.border)!=null?ue:T,t.style.boxShadow=(De=s.shadow)!=null?De:S,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=(Xe=s.collapsedMaxWidth)!=null?Xe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:o}};var Pb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",rl=(e,r={})=>{var A,k,T,S,E,b;let{showClose:t=!0,wrapperClassName:n=Pb,buttonSize:o,iconSize:a="28px"}=r,s=(A=e==null?void 0:e.launcher)!=null?A:{},i=(k=o!=null?o:s.closeButtonSize)!=null?k:"32px",d=h("div",n),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(T=s.closeButtonTooltipText)!=null?T:"Close chat",p=(S=s.closeButtonShowTooltip)!=null?S:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(E=s.closeButtonIconName)!=null?E:"x",m=(b=s.closeButtonIconText)!=null?b:"\xD7";l.style.color=s.closeButtonColor||Kr.actionIconColor;let C=Ce(f,a,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):l.textContent=m,s.closeButtonBackgroundColor?(l.style.backgroundColor=s.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let y=s.closeButtonBorderWidth||"0px",v=s.closeButtonBorderColor||"transparent";l.style.border=`${y} solid ${v}`,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),p&&u){let y=null,v=()=>{if(y)return;let B=l.ownerDocument,W=B.body;if(!W)return;y=qn(B,"div","persona-clear-chat-tooltip"),y.textContent=u;let R=qn(B,"div");R.className="persona-clear-chat-tooltip-arrow",y.appendChild(R);let H=l.getBoundingClientRect();y.style.position="fixed",y.style.zIndex=String(Ao),y.style.left=`${H.left+H.width/2}px`,y.style.top=`${H.top-8}px`,y.style.transform="translate(-50%, -100%)",W.appendChild(y)},M=()=>{y&&y.parentNode&&(y.parentNode.removeChild(y),y=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",M),l.addEventListener("focus",v),l.addEventListener("blur",M),d._cleanupTooltip=()=>{M(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",M),l.removeEventListener("focus",v),l.removeEventListener("blur",M)}}return{button:l,wrapper:d}},Ib="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",nl=(e,r={})=>{var y,v,M,B,W,R,H,j,oe,ue,De,Xe,xe;let{wrapperClassName:t=Ib,buttonSize:n,iconSize:o="20px"}=r,s=(v=((y=e==null?void 0:e.launcher)!=null?y:{}).clearChat)!=null?v:{},i=(M=n!=null?n:s.size)!=null?M:"32px",d=(B=s.iconName)!=null?B:"refresh-cw",l=(W=s.iconColor)!=null?W:"",u=(R=s.backgroundColor)!=null?R:"",p=(H=s.borderWidth)!=null?H:"",f=(j=s.borderColor)!=null?j:"",m=(oe=s.borderRadius)!=null?oe:"",C=(ue=s.paddingX)!=null?ue:"",A=(De=s.paddingY)!=null?De:"",k=(Xe=s.tooltipText)!=null?Xe:"Clear chat",T=(xe=s.showTooltip)!=null?xe:!0,S=h("div",t),E=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");E.style.height=i,E.style.width=i,E.type="button",E.setAttribute("aria-label",k),E.style.color=l||Kr.actionIconColor;let b=Ce(d,o,"currentColor",1);if(b&&(b.style.display="block",E.appendChild(b)),u&&(E.style.backgroundColor=u,E.classList.remove("hover:persona-bg-gray-100")),p||f){let ge=p||"0px",Le=f||"transparent";E.style.border=`${ge} solid ${Le}`,E.classList.remove("persona-border-none")}if(m&&(E.style.borderRadius=m,E.classList.remove("persona-rounded-full")),C&&(E.style.paddingLeft=C,E.style.paddingRight=C),A&&(E.style.paddingTop=A,E.style.paddingBottom=A),S.appendChild(E),T&&k){let ge=null,Le=()=>{if(ge)return;let Q=E.ownerDocument,Se=Q.body;if(!Se)return;ge=qn(Q,"div","persona-clear-chat-tooltip"),ge.textContent=k;let J=qn(Q,"div");J.className="persona-clear-chat-tooltip-arrow",ge.appendChild(J);let ce=E.getBoundingClientRect();ge.style.position="fixed",ge.style.zIndex=String(Ao),ge.style.left=`${ce.left+ce.width/2}px`,ge.style.top=`${ce.top-8}px`,ge.style.transform="translate(-50%, -100%)",Se.appendChild(ge)},Ge=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};S.addEventListener("mouseenter",Le),S.addEventListener("mouseleave",Ge),E.addEventListener("focus",Le),E.addEventListener("blur",Ge),S._cleanupTooltip=()=>{Ge(),S.removeEventListener("mouseenter",Le),S.removeEventListener("mouseleave",Ge),E.removeEventListener("focus",Le),E.removeEventListener("blur",Ge)}}return{button:E,wrapper:S}};var Kr={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))"},ao=e=>{var y,v,M,B,W,R,H,j,oe,ue,De,Xe,xe,ge,Le,Ge;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(y=r==null?void 0:r.launcher)!=null?y:{},a=(v=o.headerIconSize)!=null?v:"48px",s=(M=o.closeButtonPlacement)!=null?M:"inline",i=(B=o.headerIconHidden)!=null?B:!1,d=o.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=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 Q=parseFloat(a)||24,Se=Ce(d,Q*.6,"currentColor",1);Se?l.replaceChildren(Se):l.textContent=(R=(W=r==null?void 0:r.launcher)==null?void 0:W.agentIconText)!=null?R:"\u{1F4AC}"}else if((H=r==null?void 0:r.launcher)!=null&&H.iconUrl){let Q=h("img");Q.src=r.launcher.iconUrl,Q.alt="",Q.className="persona-rounded-xl persona-object-cover",Q.style.height=a,Q.style.width=a,l.replaceChildren(Q)}else l.textContent=(oe=(j=r==null?void 0:r.launcher)==null?void 0:j.agentIconText)!=null?oe:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=Kr.titleColor,p.textContent=(De=(ue=r==null?void 0:r.launcher)==null?void 0:ue.title)!=null?De:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Kr.subtitleColor,f.textContent=(xe=(Xe=r==null?void 0:r.launcher)==null?void 0:Xe.subtitle)!=null?xe:"Here to help you get answers fast",u.append(p,f),i?n.append(u):n.append(l,u);let m=(ge=o.clearChat)!=null?ge:{},C=(Le=m.enabled)!=null?Le:!0,A=(Ge=m.placement)!=null?Ge:"inline",k=null,T=null;if(C){let Se=nl(r,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=Se.button,T=Se.wrapper,A==="top-right"&&(T.style.right="48px"),A==="inline"&&n.appendChild(T)}let S=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:E,wrapper:b}=rl(r,{showClose:t,wrapperClassName:S});return s!=="top-right"&&n.appendChild(b),{header:n,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:E,closeButtonWrapper:b,clearChatButton:k,clearChatButtonWrapper:T}},na=(e,r,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";e.appendChild(r.header),o==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function ko(e){let{items:r,onSelect:t,anchor:n,position:o="bottom-left",portal:a}=e,s=h("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(Ao)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",o==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of r){if(m.dividerBefore){let k=document.createElement("hr");s.appendChild(k)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",m.id),m.destructive&&C.setAttribute("data-destructive",""),m.icon){let k=Ce(m.icon,16,"currentColor",1.5);k&&C.appendChild(k)}let A=document.createElement("span");A.textContent=m.label,C.appendChild(A),C.addEventListener("click",k=>{k.stopPropagation(),u(),t(m.id)}),s.appendChild(C)}let i=null;function d(){if(!a)return;let m=n.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,o==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function l(){d(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=C=>{!s.contains(C.target)&&!n.contains(C.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function p(){s.classList.contains("persona-hidden")?l():u()}function f(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:u,toggle:p,destroy:f}}function Qt(e){let{icon:r,label:t,size:n,strokeWidth:o,className:a,onClick:s,aria:i}=e,d=h("button","persona-icon-btn"+(a?" "+a:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Ce(r,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),s&&d.addEventListener("click",s),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ls(e){let{icon:r,label:t,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:d}=e,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,s&&(l+=" "+s);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),r){let f=Ce(r,a!=null?a:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function Ps(e){let{items:r,selectedId:t,onSelect:n,className:o}=e,a=h("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 r){let p;u.icon?p=Qt({icon:u.icon,label:u.label,onClick:()=>{s=u.id,d(),n(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{s=u.id,d(),n(u.id)})),p.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:p}),a.appendChild(p)}function l(u){s=u,d()}return{element:a,setSelected:l}}function ol(e){var m,C;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",r);let u=h("span","persona-combo-btn-label");u.textContent=r,l.appendChild(u);let p=Ce(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(C=d.padding)!=null?C:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var A,k;l.style.backgroundColor=(A=d.background)!=null?A:"",l.style.borderColor=(k=d.border)!=null?k:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=ko({items:n,onSelect:A=>{l.setAttribute("aria-expanded","false"),o(A)},anchor:l,position:a,portal:s});return s||l.appendChild(f.element),l.addEventListener("click",A=>{A.stopPropagation();let k=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",k?"false":"true"),f.toggle()}),l.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),l.click())}),{element:l,setLabel:A=>{u.textContent=A,l.setAttribute("aria-label",A)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let A=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",A?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var dp=e=>{var n;let r=ao({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let o=r.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 r};function Rb(e,r,t){var n,o,a;if(r!=null&&r.length)for(let s of r){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=s.ariaLabel)!=null?n:s.label)!=null?o:s.id),s.icon){let d=Ce(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=h("div","persona-relative");d.appendChild(i);let l=ko({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()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(s.id)),e.appendChild(i)}}var cp=e=>{var S,E,b,y,v,M,B,W,R;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=(S=r==null?void 0:r.launcher)!=null?S:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,u;if(d)l=ol({label:(E=s.title)!=null?E:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Kr.titleColor,u=(b=l.querySelector(".persona-combo-btn-label"))!=null?b:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Kr.titleColor,u.textContent=(y=s.title)!=null?y:"Chat Assistant",l.appendChild(u),Rb(l,o==null?void 0:o.trailingActions,(v=o==null?void 0:o.onAction)!=null?v:a),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let j=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||j()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),j())})}let H=o==null?void 0:o.titleRowHover;H&&(l.style.borderRadius=(M=H.borderRadius)!=null?M:"10px",l.style.padding=(B=H.padding)!=null?B:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var j,oe;l.style.backgroundColor=(j=H.background)!=null?j:"",l.style.borderColor=(oe=H.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(W=s.closeButtonSize)!=null?W:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=s.closeButtonColor||Kr.actionIconColor;let C=(R=s.closeButtonIconName)!=null?R:"x",A=Ce(C,"28px","currentColor",1);A?m.appendChild(A):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let k=h("div");k.style.display="none";let T=h("span");return T.style.display="none",{header:i,iconHolder:k,headerTitle:u,headerSubtitle:T,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},al={default:dp,minimal:cp},pp=e=>{var r;return(r=al[e])!=null?r:al.default},Ta=(e,r,t)=>{var s,i,d;if(r!=null&&r.render){let l=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let C=h("div");return C.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let n=(s=r==null?void 0:r.layout)!=null?s:"default",a=pp(n)({config:e,showClose:(d=(i=r==null?void 0:r.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:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(a.iconHolder.style.display="none"),r.showTitle===!1&&(a.headerTitle.style.display="none"),r.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(a.closeButton.style.display="none"),r.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var sl=e=>{var s,i;let r=h("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",r.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",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,n=20;r.style.maxHeight=`${t*n}px`,r.style.overflowY="auto";let o=()=>{let d=parseFloat(r.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*n},a=()=>{r.addEventListener("input",()=>{r.style.height="auto";let d=Math.min(r.scrollHeight,o());r.style.height=`${d}px`})};return r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:a}},il=e=>{var y,v,M,B,W,R,H,j,oe,ue,De,Xe;let r=(y=e==null?void 0:e.sendButton)!=null?y:{},t=(v=r.useIcon)!=null?v:!1,n=(M=r.iconText)!=null?M:"\u2191",o=r.iconName,a=(B=r.stopIconName)!=null?B:"square",s=(W=r.tooltipText)!=null?W:"Send message",i=(R=r.stopTooltipText)!=null?R:"Stop generating",d=(j=(H=e==null?void 0:e.copy)==null?void 0:H.sendButtonLabel)!=null?j:"Send",l=(ue=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?ue:"Stop",u=(De=r.showTooltip)!=null?De:!1,p=(Xe=r.size)!=null?Xe:"40px",f=r.backgroundColor,m=r.textColor,C=h("div","persona-send-button-wrapper"),A=h("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");A.type="submit",A.setAttribute("data-persona-composer-submit","");let k=null,T=null;if(t){A.style.width=p,A.style.height=p,A.style.minWidth=p,A.style.minHeight=p,A.style.fontSize="18px",A.style.lineHeight="1",A.innerHTML="",m?A.style.color=m:A.style.color="var(--persona-button-primary-fg, #ffffff)";let xe=parseFloat(p)||24,ge=(m==null?void 0:m.trim())||"currentColor";o?(k=Ce(o,xe,ge,2),k?A.appendChild(k):A.textContent=n):A.textContent=n,T=Ce(a,xe,ge,2),f?A.style.backgroundColor=f:A.classList.add("persona-bg-persona-primary")}else A.textContent=d,m?A.style.color=m:A.classList.add("persona-text-white");r.borderWidth&&(A.style.borderWidth=r.borderWidth,A.style.borderStyle="solid"),r.borderColor&&(A.style.borderColor=r.borderColor),r.paddingX?(A.style.paddingLeft=r.paddingX,A.style.paddingRight=r.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),r.paddingY?(A.style.paddingTop=r.paddingY,A.style.paddingBottom=r.paddingY):(A.style.paddingTop="",A.style.paddingBottom="");let S=null;u&&s&&(S=h("div","persona-send-button-tooltip"),S.textContent=s,C.appendChild(S)),A.setAttribute("aria-label",s),C.appendChild(A);let E="send";return{button:A,wrapper:C,setMode:xe=>{if(xe===E)return;E=xe;let ge=xe==="stop"?i:s;if(A.setAttribute("aria-label",ge),S&&(S.textContent=ge),t){if(k&&T){let Le=xe==="stop"?T:k,Ge=xe==="stop"?k:T;Ge.parentNode===A?A.replaceChild(Le,Ge):A.appendChild(Le)}}else A.textContent=xe==="stop"?l:d}}},ll=e=>{var S,E,b,y,v,M,B,W,R,H,j,oe;let r=(S=e==null?void 0:e.voiceRecognition)!=null?S:{};if(!(r.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((E=r.provider)==null?void 0:E.type)==="runtype";if(!(n||o))return null;let s=(y=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?y:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=r.iconName)!=null?v:"mic",u=(M=r.iconSize)!=null?M:s,p=parseFloat(u)||24,f=(W=r.backgroundColor)!=null?W:(B=e==null?void 0:e.sendButton)==null?void 0:B.backgroundColor,m=(H=r.iconColor)!=null?H:(R=e==null?void 0:e.sendButton)==null?void 0:R.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",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let A=Ce(l,p,m||"currentColor",1.5);A?d.appendChild(A):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),r.borderWidth&&(d.style.borderWidth=r.borderWidth,d.style.borderStyle="solid"),r.borderColor&&(d.style.borderColor=r.borderColor),r.paddingX&&(d.style.paddingLeft=r.paddingX,d.style.paddingRight=r.paddingX),r.paddingY&&(d.style.paddingTop=r.paddingY,d.style.paddingBottom=r.paddingY),i.appendChild(d);let k=(j=r.tooltipText)!=null?j:"Start voice recognition";if(((oe=r.showTooltip)!=null?oe:!1)&&k){let ue=h("div","persona-send-button-tooltip");ue.textContent=k,i.appendChild(ue)}return{button:d,wrapper:i}},dl=e=>{var C,A,k,T,S,E,b,y;let r=(C=e==null?void 0:e.attachments)!=null?C:{};if(r.enabled!==!0)return null;let t=(k=(A=e==null?void 0:e.sendButton)==null?void 0:A.size)!=null?k:"40px",n=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=h("input");o.type="file",o.accept=((T=r.allowedTypes)!=null?T:oo).join(","),o.multiple=((S=r.maxFiles)!=null?S:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let a=h("div","persona-send-button-wrapper"),s=h("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",(E=r.buttonTooltipText)!=null?E:"Attach file");let i=(b=r.buttonIconName)!=null?b:"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 p=Ce(i,u,"currentColor",1.5);p?s.appendChild(p):s.textContent="\u{1F4CE}",s.addEventListener("click",v=>{v.preventDefault(),o.click()}),a.appendChild(s);let f=(y=r.buttonTooltipText)!=null?y:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,a.appendChild(m),{button:s,wrapper:a,input:o,previewsContainer:n}},cl=e=>{var s,i,d;let r=(s=e==null?void 0:e.statusIndicator)!=null?s:{},t=r.align==="left"?"persona-text-left":r.align==="center"?"persona-text-center":"persona-text-right",n=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=r.visible)!=null?i:!0;n.style.display=o?"":"none";let a=(d=r.idleText)!=null?d:"Online";if(r.idleLink){let l=h("a");l.href=r.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},pl=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ka=e=>{var C,A,k,T,S,E;let{config:r}=e,t=h("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=pl(),o=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:a,attachAutoResize:s}=sl(r);s();let i=il(r),d=ll(r),l=dl(r),u=cl(r);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(a);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("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),p.append(f,m),o.append(p),o.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.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:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(A=d==null?void 0:d.wrapper)!=null?A:null,statusText:u,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(S=l==null?void 0:l.input)!=null?S:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:p,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var nh=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let r=h("span","persona-pill-peek__icon"),t=Ce("message-square",16,"currentColor",1.5);t&&r.appendChild(t);let n=h("span","persona-pill-peek__text"),o=h("span","persona-pill-peek__caret"),a=Ce("chevron-up",16,"currentColor",1.5);return a&&o.appendChild(a),e.append(r,n,o),{root:e,textNode:n}},oh=e=>{var C,A,k,T,S,E;let{config:r}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let n=pl();n.style.display="none";let o=cl(r);o.style.display="none";let{textarea:a,attachAutoResize:s}=sl(r);a.style.maxHeight="100px",s();let i=il(r),d=ll(r),l=dl(r);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&u.append(l.input),u.append(p,a,f),l&&t.append(l.previewsContainer),t.append(u,n,o);let m=u;return{footer:t,suggestions:n,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(A=d==null?void 0:d.wrapper)!=null?A:null,statusText:o,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(S=l==null?void 0:l.input)!=null?S:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var ah=e=>{var u,p,f,m,C,A,k,T,S,E,b,y,v,M,B,W,R;let r=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=hr(e);if(To(e)){let H=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},j=h("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(C=H.expandedSize)!=null?C:"anchored",j.style.zIndex=String((k=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?k:Or);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",j.appendChild(oe);let ue=h("div","persona-widget-pill-root");return ue.setAttribute("data-persona-composer-bar",""),ue.dataset.state="collapsed",ue.dataset.expandedSize=(T=H.expandedSize)!=null?T:"anchored",ue.style.zIndex=String((E=(S=e==null?void 0:e.launcher)==null?void 0:S.zIndex)!=null?E:Or),{wrapper:j,panel:oe,pillRoot:ue}}if(t){let H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return H.appendChild(j),{wrapper:H,panel:j}}if(!r){let H=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(y=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?y:"100%";return H.style.width=oe,j.style.width="100%",H.appendChild(j),{wrapper:H,panel:j}}let o=(v=e==null?void 0:e.launcher)!=null?v:{},a=o.position&&On[o.position]?On[o.position]:On["bottom-right"],s=h("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((B=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?B:Or);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(W=e==null?void 0:e.launcher)==null?void 0:W.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:mn;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},Hb=(e,r)=>{var b,y,v,M,B,W,R,H,j;let t=h("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}=rl(e,{showClose:r,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=(v=(y=(b=e==null?void 0:e.launcher)==null?void 0:b.clearChat)==null?void 0:y.enabled)!=null?v:!0,s=null,i=null;if(a){let oe=nl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("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 p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(B=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?B:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(R=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",u.append(p,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),C=(H=e==null?void 0:e.layout)==null?void 0:H.contentMaxWidth;C&&(m.style.maxWidth=C,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((j=e==null?void 0:e.copy)==null?void 0:j.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let k=h("div","persona-composer-overlay persona-pointer-events-none");k.setAttribute("data-persona-composer-overlay",""),k.style.position="absolute",k.style.left="0",k.style.right="0",k.style.bottom="0",k.style.zIndex="20";let T=oh({config:e}),{root:S,textNode:E}=nh();return t.append(d,o,l,k),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:m,composerOverlay:k,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:f,closeButton:n,closeButtonWrapper:o,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:S,peekTextNode:E}},sh=(e,r=!0)=>{var k,T,S,E,b,y,v,M,B;if(To(e))return Hb(e,r);let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(k=e==null?void 0:e.layout)==null?void 0:k.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,a=n?Ta(e,n,{showClose:r}):ao({config:e,showClose:r}),s=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");s.id="persona-scroll-container",s.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=hr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(E=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeTitle)!=null?E:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(y=(b=e==null?void 0:e.copy)==null?void 0:b.welcomeSubtitle)!=null?y:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(i.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(i,u);let m=ka({config:e}),C=((B=e==null?void 0:e.layout)==null?void 0:B.showFooter)!==!1;o?na(t,a,e):(a.header.style.display="none",na(t,a,e)),t.append(s);let A=h("div","persona-composer-overlay persona-pointer-events-none");return A.setAttribute("data-persona-composer-overlay",""),A.style.position="absolute",A.style.left="0",A.style.right="0",A.style.bottom="0",A.style.zIndex="20",C||(m.footer.style.display="none"),t.append(m.footer),t.append(A),{container:t,body:s,messagesWrapper:u,composerOverlay:A,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Bb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Wb=(e,r)=>{if(!e)return null;let t=Bb(e);if(t===null)return null;let n=r==null?void 0:r[e],o=n!==void 0?n:t;return o||null},Db=(e,r)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=r,t},Ob=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},up=e=>{let r=e.toLowerCase();return r.startsWith("javascript:")||r.startsWith("data:text/html")||r.startsWith("data:text/javascript")||r.startsWith("data:text/xml")||r.startsWith("data:application/xhtml")||r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:")||!e.includes(":"))},fp=320,lh=320,Fb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="audio"&&typeof r.audio=="string"&&r.audio.trim().length>0),_b=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="video"&&typeof r.video=="string"&&r.video.trim().length>0),$b=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="file"&&typeof r.data=="string"&&r.data.trim().length>0),Ub=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.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=`${fp}px`,l.style.maxHeight=`${lh}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}),Ob(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}},qb=e=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(n=>{if(!up(n.audio))return;let o=h("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${fp}px`,r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},zb=e=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","video");let t=0;return e.forEach(n=>{if(!up(n.video))return;let o=h("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${fp}px`,o.style.maxHeight=`${lh}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},Vb=e=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","files");let t=0;return e.forEach(n=>{if(!up(n.data))return;let o=h("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},oa=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="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",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(o),e},mp=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:oa};if(r){let o=r(n);if(o!==null)return o}return oa()},jb=(e,r)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=h("img");o.src=n,o.alt=r==="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(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},ih=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Gb=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="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"),e==="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"),e==="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},gp=(e,r,t)=>{var m,C,A,k,T,S;let n=(m=r.showCopy)!=null?m:!0,o=(C=r.showUpvote)!=null?C:!0,a=(A=r.showDownvote)!=null?A:!0;if(!n&&!o&&!a){let E=h("div");return E.style.display="none",E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id),E}let s=(k=r.visibility)!=null?k:"hover",i=(T=r.align)!=null?T:"right",d=(S=r.layout)!=null?S:"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],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${s==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(E,b,y)=>{let v=Qt({icon:E,label:b,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",y),v};return n&&p.appendChild(f("copy","Copy message","copy")),o&&p.appendChild(f("thumbs-up","Upvote","upvote")),a&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Ea=(e,r,t,n,o,a)=>{var Q,Se,J,ce,pe,ie,Oe,Pe,K,_e,$e,Y,G,we,ke,ae,ve;let s=t!=null?t:{},i=(Q=s.layout)!=null?Q:"bubble",d=s.avatar,l=s.timestamp,u=(Se=d==null?void 0:d.show)!=null?Se:!1,p=(J=l==null?void 0:l.show)!=null?J:!1,f=(ce=d==null?void 0:d.position)!=null?ce:"left",m=(pe=l==null?void 0:l.position)!=null?pe:"below",C=Gb(e.role,i),A=h("div",C.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=Fb(e),T=(Oe=(ie=e.content)==null?void 0:ie.trim())!=null?Oe:"",E=k.length>0&&T===Ei,b=Qi((K=(Pe=a==null?void 0:a.widgetConfig)==null?void 0:Pe.features)==null?void 0:K.streamAnimation),y=(Y=($e=(_e=a==null?void 0:a.widgetConfig)==null?void 0:_e.features)==null?void 0:$e.streamAnimation)==null?void 0:Y.plugins,v=e.role==="assistant"&&b.type!=="none"?Ss(b.type,y):null,M=e.role==="assistant"&&((G=v==null?void 0:v.isAnimating)==null?void 0:G.call(v,e))===!0,B=e.role==="assistant"&&v!==null&&(!!e.streaming||M);B&&(v!=null&&v.bubbleClass)&&A.classList.add(v.bubbleClass);let W=document.createElement("div");W.classList.add("persona-message-content"),B&&v&&(v.containerClass&&W.classList.add(v.containerClass),W.style.setProperty("--persona-stream-step",`${b.speed}ms`),W.style.setProperty("--persona-stream-duration",`${b.duration}ms`));let R=B?Zi((we=e.content)!=null?we:"",b.buffer,v,e,!!e.streaming):(ke=e.content)!=null?ke:"",H=r({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),j=H;B&&(v==null?void 0:v.wrap)==="char"?j=Ts(H,"char",e.id,{skipTags:v.skipTags}):B&&(v==null?void 0:v.wrap)==="word"&&(j=Ts(H,"word",e.id,{skipTags:v.skipTags}));let oe=null;if(E?(oe=document.createElement("div"),oe.innerHTML=j,oe.style.display="none",W.appendChild(oe)):W.innerHTML=j,B&&(v!=null&&v.useCaret)&&!E&&T){let ye=el(),Mt=W.querySelectorAll(".persona-stream-char, .persona-stream-word"),ne=Mt[Mt.length-1];if(ne!=null&&ne.parentNode)ne.parentNode.insertBefore(ye,ne.nextSibling);else{let He=W.lastElementChild;He?He.appendChild(ye):W.appendChild(ye)}}if(p&&m==="inline"&&e.createdAt){let ye=ih(e,l);ye.classList.add("persona-ml-2","persona-inline"),W.appendChild(ye)}if(k.length>0){let ye=Ub(k,!E&&!!T,()=>{E&&oe&&(oe.style.display="")});ye?A.appendChild(ye):E&&oe&&(oe.style.display="")}let ue=Nb(e);if(ue.length>0){let ye=qb(ue);ye&&A.appendChild(ye)}let De=_b(e);if(De.length>0){let ye=zb(De);ye&&A.appendChild(ye)}let Xe=$b(e);if(Xe.length>0){let ye=Vb(Xe);ye&&A.appendChild(ye)}if(A.appendChild(W),p&&m==="below"&&e.createdAt){let ye=ih(e,l);ye.classList.add("persona-mt-1"),A.appendChild(ye)}let xe=e.role==="assistant"?Wb(e.stopReason,(ve=(ae=a==null?void 0:a.widgetConfig)==null?void 0:ae.copy)==null?void 0:ve.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ye=!!(R&&R.trim()),Mt=b.placeholder==="skeleton",ne=Mt&&b.buffer==="line"&&ye;if(ye)ne&&A.appendChild(ks());else if(Mt)A.appendChild(ks());else{let He=mp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);He&&A.appendChild(He)}}if(xe&&e.stopReason&&!e.streaming&&(T||(W.style.display="none"),A.appendChild(Db(e.stopReason,xe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let ye=gp(e,n,o);A.appendChild(ye)}if(!u||e.role==="system")return A;let Le=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ge=jb(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Le.append(A,Ge):Le.append(Ge,A),A.classList.remove("persona-max-w-[85%]"),A.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},dh=(e,r,t,n,o,a)=>{let s=t!=null?t:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ea(e,r,t,n,o,a)};var Ma=new Set,Xb=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Jb=(e,r)=>{var n,o;let t=(o=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
|
|
64
|
+
`):""},ch=(e,r)=>{let t=Ma.has(e),n=r.querySelector('button[data-expand-header="true"]'),o=r.querySelector(".persona-border-t"),a=r.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=Ce(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")},hp=(e,r)=>{var De,Xe,xe,ge,Le,Ge,Q,Se,J,ce,pe;let t=e.reasoning,n=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let o=(Xe=(De=r==null?void 0:r.features)==null?void 0:De.reasoningDisplay)!=null?Xe:{},a=o.expandable!==!1,s=a&&Ma.has(e.id),i=t.status!=="complete",d=Jb(e,(xe=o.previewMaxLines)!=null?xe:3),l=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");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=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(ge=r==null?void 0:r.reasoning)!=null?ge:{},C=String((Le=t.startedAt)!=null?Le:Date.now()),A=()=>{let ie=h("span","");return ie.setAttribute("data-tool-elapsed",C),ie.textContent=bi(t),ie},k=(Ge=m.renderCollapsedSummary)==null?void 0:Ge.call(m,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:r!=null?r:{},elapsed:bi(t),createElapsedElement:A});typeof k=="string"&&k.trim()?(p.textContent=k,u.appendChild(p)):k instanceof HTMLElement?u.appendChild(k):(p.textContent=f,u.appendChild(p));let T=h("span","persona-text-xs persona-text-persona-primary");T.textContent=Eg(t),u.appendChild(T);let S=(Q=o.loadingAnimation)!=null?Q:"none",E=m.activeTextTemplate,b=m.completeTextTemplate,y=i?E:b,v=k instanceof HTMLElement,M=(ie,Oe,Pe)=>{let K=Pe;for(let _e of Oe){let $e=h("span","persona-tool-char");$e.style.setProperty("--char-index",String(K)),$e.textContent=_e===" "?"\xA0":_e,ie.appendChild($e),K++}return K},B=(ie,Oe)=>{p.textContent="";let Pe=Ci(ie,""),K=0;for(let _e of Pe){let $e=_e.styles.length>0?(()=>{let Y=h("span",_e.styles.map(G=>`persona-tool-text-${G}`).join(" "));return p.appendChild(Y),Y})():p;if(_e.isDuration&&i)$e.appendChild(A());else{let Y=_e.isDuration?bi(t):_e.text;Oe?K=M($e,Y,K):$e.appendChild(document.createTextNode(Y))}}};if(!v&&y)if(T.style.display="none",p.style.display="",i&&S!=="none"){let ie=(Se=m.loadingAnimationDuration)!=null?Se:2e3;p.setAttribute("data-preserve-animation","true"),S==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),B(y,!1)):(p.classList.add(`persona-tool-loading-${S}`),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),B(y,!0))}else B(y,!1);else if(!v&&i&&S!=="none"){p.style.display="";let ie=(J=m.loadingAnimationDuration)!=null?J:2e3;if(p.setAttribute("data-preserve-animation","true"),S==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`);else{p.classList.add(`persona-tool-loading-${S}`),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Oe=p.textContent||f;p.textContent="",M(p,Oe,0)}t.status==="complete"&&(p.style.display="none")}else v||(t.status==="complete"?p.style.display="none":p.style.display="");let W=null;if(a){W=h("div","persona-flex persona-items-center");let Oe=Ce(s?"chevron-up":"chevron-down",16,"currentColor",2);Oe?W.appendChild(Oe):W.textContent=s?"Hide":"Show";let Pe=h("div","persona-flex persona-items-center persona-ml-auto");Pe.append(W),l.append(u,Pe)}else l.append(u);let R=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!s&&i&&o.activePreview&&d){let ie=(pe=(ce=r==null?void 0:r.reasoning)==null?void 0:ce.renderCollapsedPreview)==null?void 0:pe.call(ce,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:r!=null?r:{}});Xb(R,ie)||(R.textContent=d),R.style.display=""}if(!s&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!a)return n.append(l,R),n;let H=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");H.style.display=s?"":"none";let j=t.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=j||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),H.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),W){W.innerHTML="";let Oe=Ce(s?"chevron-up":"chevron-down",16,"currentColor",2);Oe?W.appendChild(Oe):W.textContent=s?"Hide":"Show"}H.style.display=s?"":"none",R.style.display=s?"none":R.textContent||R.childNodes.length?"":"none"})(),n.append(l,R,H),n};var La=new Set,Kb=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Yb=(e,r)=>{var a;let t=e.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(-r).join(`
|
|
65
65
|
`);let o=ba(t.args).trim();return o?o.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,r).join(`
|
|
66
|
-
`):""},Qb=(e,r)=>{var u,p,m,f,w;let t=e.toolCall,n=(u=r==null?void 0:r.features)==null?void 0:u.toolCallDisplay,o=(p=n==null?void 0:n.collapsedMode)!=null?p:"tool-call",a=Yb(e,(m=n==null?void 0:n.previewMaxLines)!=null?m:3),s=t?Mg(t):"";if(!t)return{summary:s,previewText:a,isActive:!1};let i=t.status!=="complete",d=(f=r==null?void 0:r.toolCall)!=null?f:{},l=s;return o==="tool-name"?l=((w=t.name)==null?void 0:w.trim())||s:o==="tool-preview"&&a&&(l=a),i&&d.activeTextTemplate?l=ed(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ed(t,d.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},ph=(e,r,t)=>{var u;let n=La.has(e),o=(u=t==null?void 0:t.toolCall)!=null?u:{},a=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),i=r.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 p=o.toggleTextColor||o.headerTextColor||"currentColor",m=Ce(n?"chevron-up":"chevron-down",16,p,2);m?l.appendChild(m):l.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},xp=(e,r)=>{var j,oe,ue,De,Xe,xe,ge,Le,Ge;let t=e.toolCall,n=(j=r==null?void 0:r.toolCall)!=null?j:{},o=x("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!t)return o;let a=(ue=(oe=r==null?void 0:r.features)==null?void 0:oe.toolCallDisplay)!=null?ue:{},s=a.expandable!==!1,i=s&&La.has(e.id),{summary:d,previewText:l,isActive:u}=Qb(e,r),p=x("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");p.type="button",s&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(p.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(p.style.paddingLeft=n.headerPaddingX,p.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(p.style.paddingTop=n.headerPaddingY,p.style.paddingBottom=n.headerPaddingY);let m=x("div","persona-flex persona-flex-col persona-text-left"),f=x("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let w=String((De=t.startedAt)!=null?De:Date.now()),v=()=>{let Q=x("span","");return Q.setAttribute("data-tool-elapsed",w),Q.textContent=ms(t),Q},k=(xe=n.renderCollapsedSummary)==null?void 0:xe.call(n,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Xe=a.collapsedMode)!=null?Xe:"tool-call",isActive:u,config:r!=null?r:{},elapsed:ms(t),createElapsedElement:v});typeof k=="string"&&k.trim()?(f.textContent=k,m.appendChild(f)):k instanceof HTMLElement?m.appendChild(k):(f.textContent=d,m.appendChild(f));let T=(ge=a.loadingAnimation)!=null?ge:"none",A=n.activeTextTemplate,E=n.completeTextTemplate,b=u?A:E,h=k instanceof HTMLElement,S=(Q,Se,J)=>{let ce=J;for(let pe of Se){let ie=x("span","persona-tool-char");ie.style.setProperty("--char-index",String(ce)),ie.textContent=pe===" "?"\xA0":pe,Q.appendChild(ie),ce++}return ce},L=(Q,Se)=>{var ie;f.textContent="";let J=((ie=t.name)==null?void 0:ie.trim())||"tool",ce=Ci(Q,J),pe=0;for(let Oe of ce){let Pe=Oe.styles.length>0?(()=>{let K=x("span",Oe.styles.map(_e=>`persona-tool-text-${_e}`).join(" "));return f.appendChild(K),K})():f;if(Oe.isDuration&&u)Pe.appendChild(v());else{let K=Oe.isDuration?ms(t):Oe.text;Se?pe=S(Pe,K,pe):Pe.appendChild(document.createTextNode(K))}}};if(!h)if(u&&T!=="none"){let Q=(Le=n.loadingAnimationDuration)!=null?Le:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),b&&L(b,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${Q}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)),b)L(b,!0);else{let Se=f.textContent||d;f.textContent="",S(f,Se,0)}}else b&&L(b,!1);let O=null;if(s){O=x("div","persona-flex persona-items-center");let Q=n.toggleTextColor||n.headerTextColor||"currentColor",Se=Ce(i?"chevron-up":"chevron-down",16,Q,2);Se?O.appendChild(Se):O.textContent=i?"Hide":"Show";let J=x("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");J.append(O),p.append(m,J)}else p.append(m);let H=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&l){let Q=(Ge=n.renderCollapsedPreview)==null?void 0:Ge.call(n,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:r!=null?r:{}});Kb(H,Q)||(H.textContent=l),H.style.display=""}if(!i&&u&&a.activeMinHeight&&(o.style.minHeight=a.activeMinHeight),!s)return o.append(p,H),o;let R=x("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),t.name){let Q=x("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?Q.style.color=n.contentTextColor:n.headerTextColor&&(Q.style.color=n.headerTextColor),Q.textContent=t.name,R.appendChild(Q)}if(t.args!==void 0){let Q=x("div","persona-space-y-1"),Se=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Arguments";let J=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=ba(t.args),Q.append(Se,J),R.appendChild(Q)}if(t.chunks&&t.chunks.length){let Q=x("div","persona-space-y-1"),Se=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Activity";let J=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=t.chunks.join(""),Q.append(Se,J),R.appendChild(Q)}if(t.status==="complete"&&t.result!==void 0){let Q=x("div","persona-space-y-1"),Se=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Result";let J=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=ba(t.result),Q.append(Se,J),R.appendChild(Q)}if(t.status==="complete"&&typeof t.duration=="number"){let Q=x("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(Q.style.color=n.contentTextColor),Q.textContent=`Duration: ${t.duration}ms`,R.appendChild(Q)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let Q=n.toggleTextColor||n.headerTextColor||"currentColor",Se=Ce(i?"chevron-up":"chevron-down",16,Q,2);Se?O.appendChild(Se):O.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),o.append(p,H,R),o};var Eo=Bl(hi(),1);var bp="ask_user_question",yp=8,Pa="data-persona-ask-sheet-for",Zb="Other",e0="Other\u2026",fh="Type your own answer here",mh="Send",t0="Next",r0="Back",n0="Submit all",o0="Skip",a0=3,Cp="data-ask-current-index",wp="data-ask-question-count",gh="data-ask-answers",vp="data-ask-grouped",hh="data-ask-layout",s0=e=>e.layout==="pills"?"pills":"rows",i0=e=>e.getAttribute(hh)==="pills"?"pills":"rows",uh=!1,xh=e=>e.replace(/["\\]/g,"\\$&"),so=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===bp,ul=e=>{var r,t;return(t=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion)!=null?t:{}},io=e=>{let r=e.toolCall;if(!r)return{payload:null,complete:!1};let t=r.status==="complete";if(r.args&&typeof r.args=="object")return{payload:r.args,complete:t};let n=r.chunks;if(!n||n.length===0)return{payload:null,complete:t};try{let o=n.join(""),a=(0,Eo.parse)(o,Eo.STR|Eo.OBJ|Eo.ARR);if(a&&typeof a=="object")return{payload:a,complete:t}}catch{}return{payload:null,complete:t}},Is=e=>{let r=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return r.length>yp&&!uh&&(uh=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${r.length} questions; truncating to ${yp}.`)),r.slice(0,yp)},l0=e=>{var r;return(r=Is(e)[0])!=null?r:null},d0=(e,r)=>{var t;return(t=Is(e)[r])!=null?t:null},yh=(e,r)=>{let t=r.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},bh=(e,r,t)=>{if(e!=="rows")return null;let n=x("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),r){let o=x("span","persona-ask-row-check");n.appendChild(o)}else{let o=x("span","persona-ask-row-badge");o.textContent=String(t+1),n.appendChild(o)}return n},c0=(e,r,t,n)=>{let a=x("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(r)),a.setAttribute("data-option-label",e.label),t==="rows"){let s=x("span","persona-ask-row-content"),i=x("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=x("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let d=bh(t,n,r);d&&a.appendChild(d)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},p0=e=>{let t=x("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},u0=(e,r,t,n)=>{var u,p,m;let a=x("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!t){for(let f=0;f<a0;f++)a.appendChild(p0(n));return a}if(d.forEach((f,w)=>{a.appendChild(c0(f,w,n,s))}),(e==null?void 0:e.allowFreeText)!==!1){let f=n==="rows"?Zb:e0;if(n==="rows"){let w=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let v=x("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(u=r.freeTextPlaceholder)!=null?u:fh,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(p=r.freeTextLabel)!=null?p:f),v.appendChild(k),w.appendChild(v);let T=bh(n,s,d.length);T&&w.appendChild(T),a.appendChild(w)}else{let w=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(m=r.freeTextLabel)!=null?m:f,a.appendChild(w)}}return a},Ch=(e,r)=>{var a,s;let n=x("div",r==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(a=e.freeTextPlaceholder)!=null?a:fh,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),r!=="rows"){let i=x("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:mh,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},f0=e=>{var n;let r=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");r.setAttribute("data-ask-multi-actions","true");let t=x("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(n=e.submitLabel)!=null?n:mh,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,r.appendChild(t),r},m0=(e,r,t)=>{var l,u,p,m;let n=x("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=x("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=t.backLabel)!=null?l:r0,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,n.appendChild(o);let a=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=x("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=t.skipLabel)!=null?u:o0,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=x("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===r-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:n0:(m=t.nextLabel)!=null?m:t0,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n},aa=e=>{let r=e.getAttribute(gh);if(!r)return{};try{let t=JSON.parse(r);return t&&typeof t=="object"?t:{}}catch{return{}}},wh=(e,r)=>{e.setAttribute(gh,JSON.stringify(r))},An=e=>{var t;let r=Number((t=e.getAttribute(Cp))!=null?t:"0");return Number.isFinite(r)?Math.max(0,Math.floor(r)):0},g0=(e,r)=>{e.setAttribute(Cp,String(Math.max(0,Math.floor(r))))},Ia=e=>{var t;let r=Number((t=e.getAttribute(wp))!=null?t:"1");return Number.isFinite(r)?Math.max(1,Math.floor(r)):1},Mo=e=>e.getAttribute(vp)==="true",h0=(e,r)=>{var o;let t=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let n={};return r.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},x0=(e,r)=>{var n;let t=(n=e.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(r-1,Math.floor(t)))},fl=(e,r)=>{let{payload:t}=io(r),n=Is(t),o=aa(e),a={},s=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(a[l]=o[d]))}),a},vh=e=>{let r=aa(e),t=An(e),n=r[t],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",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=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!s.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Ah=e=>{if(!Mo(e))return;let r=aa(e),t=An(e),n=r[t],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!o);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Ap=(e,r,t)=>{let n=ul(t),o=i0(e),{payload:a,complete:s}=io(r),i=Mo(e),d=An(e),l=Ia(e),u=i?d0(a,d):l0(a),p=!!(u!=null&&u.multiSelect),m=e.querySelector('[data-ask-step-inline="true"]');m&&(m.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let A=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=A,w.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let A=u0(u,n,s,o);v.replaceWith(A)}if(o!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Ch(n,o))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(f0(n)):(!p||i)&&k&&k.remove(),e.setAttribute("data-multi-select",p?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=m0(d,l,n);T?T.replaceWith(A):e.appendChild(A)}else T&&T.remove();vh(e),Ah(e)},y0=(e,r,t)=>{let n=ul(r),o=s0(n),a=e.toolCall.id,s=Is(t),i=Math.max(1,s.length),d=i>1,l=h0(e,s),u=d?x0(e,i):0,p=x("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Pa,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(wp,String(i)),p.setAttribute(Cp,String(u)),p.setAttribute(vp,d?"true":"false"),p.setAttribute(hh,o),wh(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),yh(p,n);let m=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=x("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",m.appendChild(f);let w=x("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",m.appendChild(w),p.appendChild(m);let k=x("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),p.appendChild(k),o!=="rows"&&p.appendChild(Ch(n,o)),Ap(p,e,r),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},b0=(e,r,t)=>{let{payload:n}=io(r),o=Math.max(1,Is(n).length);o>Ia(e)&&(e.setAttribute(wp,String(o)),o>1&&!Mo(e)&&e.setAttribute(vp,"true")),Ap(e,r,t)},Sh=(e,r)=>{let t=x("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let n=ul(r);yh(t,n);let o=x("span","persona-ask-stub-label"),{complete:a}=io(e);return o.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},Ra=(e,r,t)=>{if(!t||!so(e)||ul(r).enabled===!1)return;let o=e.toolCall.id;t.querySelectorAll(`[${Pa}]`).forEach(l=>{l.getAttribute(Pa)!==o&&l.remove()});let s=t.querySelector(`[${Pa}="${xh(o)}"]`);if(s){b0(s,e,r);return}let{payload:i}=io(e),d=y0(e,r,i);t.appendChild(d)},Lo=(e,r)=>{if(!e)return;let t=r?`[${Pa}="${xh(r)}"]`:`[${Pa}]`;e.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)})},Sp=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(r=>r.getAttribute("data-option-label")).filter(r=>typeof r=="string"&&r.length>0),Po=(e,r)=>{let t=aa(e),n=An(e);typeof r=="string"&&r.length===0||Array.isArray(r)&&r.length===0?delete t[n]:t[n]=r,wh(e,t),vh(e),Ah(e)},ml=(e,r,t,n)=>{let o=Ia(e),a=Math.max(0,Math.min(o-1,n));g0(e,a),Ap(e,r,t)};var Tp=(e,r)=>{var v,k,T,A,E,b,h,S,L,O,H,R;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,o=(t==null?void 0:t.status)==="pending",a=x("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(v=n==null?void 0:n.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(k=n==null?void 0:n.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return a;let s=x("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=x("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)":(T=n==null?void 0:n.titleColor)!=null?T:"currentColor",u=Ce(d,20,l,2);u&&i.appendChild(u);let p=x("div","persona-flex-1 persona-min-w-0"),m=x("div","persona-flex persona-items-center persona-gap-2"),f=x("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(A=n==null?void 0:n.title)!=null?A:"Approval Required",m.appendChild(f),!o){let B=x("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",t.status),t.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",B.style.color="var(--persona-palette-colors-success-700, #15803d)",B.textContent="Approved"):t.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",B.style.color="var(--persona-palette-colors-error-700, #b91c1c)",B.textContent="Denied"):t.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",B.style.color="var(--persona-palette-colors-warning-700, #b45309)",B.textContent="Timeout"),m.appendChild(B)}p.appendChild(m);let w=x("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(w.style.color=n.descriptionColor),w.textContent=t.description,p.appendChild(w),t.parameters){let B=x("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&&(B.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(B.style.color=n.parameterTextColor),B.style.fontSize="0.75rem",B.style.lineHeight="1rem",B.textContent=ba(t.parameters),p.appendChild(B)}if(o){let B=x("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let j=x("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");j.type="button",j.style.backgroundColor=(E=n==null?void 0:n.approveButtonColor)!=null?E:"var(--persona-approval-approve-bg, #22c55e)",j.style.color=(b=n==null?void 0:n.approveButtonTextColor)!=null?b:"#ffffff",j.setAttribute("data-approval-action","approve");let oe=Ce("shield-check",14,(h=n==null?void 0:n.approveButtonTextColor)!=null?h:"#ffffff",2);oe&&(oe.style.marginRight="4px",j.appendChild(oe));let ue=document.createTextNode((S=n==null?void 0:n.approveLabel)!=null?S:"Approve");j.appendChild(ue);let De=x("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");De.type="button",De.style.backgroundColor=(L=n==null?void 0:n.denyButtonColor)!=null?L:"transparent",De.style.color=(O=n==null?void 0:n.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",De.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,De.setAttribute("data-approval-action","deny");let Xe=Ce("shield-x",14,(H=n==null?void 0:n.denyButtonTextColor)!=null?H:"var(--persona-feedback-error, #dc2626)",2);Xe&&(Xe.style.marginRight="4px",De.appendChild(Xe));let xe=document.createTextNode((R=n==null?void 0:n.denyLabel)!=null?R:"Deny");De.appendChild(xe),B.append(j,De),p.appendChild(B)}return s.append(i,p),a.appendChild(s),a};var Th=e=>{let r=[];return{buttons:r,render:(n,o,a,s,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(s!=null?s:o?o.getMessages():[]).some(f=>f.role==="user"))return;let u=document.createDocumentFragment(),p=o?o.isStreaming():!1,m=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(f=>{let w=x("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");w.type="button",w.textContent=f,w.disabled=p,i!=null&&i.fontFamily&&(w.style.fontFamily=m(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",o.sendMessage(f))}),u.appendChild(w),r.push(w)}),e.appendChild(u)}}};var Rs=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;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=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Hs=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,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,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of r)n.put(o)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{r(s.result)},s.onerror=()=>{t(s.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{r()},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((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of r)n.put(o)}catch{}}};function Ha(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var C0={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)"}},w0={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},v0=["flowName","stepName","reasoningText","text","name","tool","toolName"],A0=100;function S0(e,r){let t={...C0,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return w0}function T0(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function k0(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),o=String(r.getSeconds()).padStart(2,"0"),a=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${o}.${a}`}function E0(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){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 M0(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function L0(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function P0(e,r,t){let n,o;try{o=JSON.parse(e.payload),n=JSON.stringify(o,null,2)}catch{o=e.payload,n=e.payload}let a=r.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&t){let i=a.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>s(),parsedPayload:o});if(i)return i}return s();function s(){let i=x("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=x("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 kp(e,r,t,n,o,a,s,i){var m;let d=o.has(e.id),l=x("div","persona-border-b persona-border-persona-divider persona-text-xs");Ha(l,(m=n.classNames)==null?void 0:m.eventRow);let u=s.find(f=>f.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let f=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>a(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(p()),l;function p(){var j,oe;let f=x("div",""),w=x("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");w.setAttribute("data-event-id",e.id);let v=x("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),k=Ce(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&v.appendChild(k);let T=x("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(j=n.timestampFormat)!=null?j:"relative";T.textContent=A==="relative"?T0(e.timestamp,t):k0(e.timestamp);let E=null;n.showSequenceNumbers!==!1&&(E=x("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(r+1));let b=S0(e.type,n.badgeColors),h=x("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");h.style.backgroundColor=b.bg,h.style.color=b.text,h.style.borderColor=b.text+"50",h.textContent=e.type;let S=(oe=n.descriptionFields)!=null?oe:v0,L=E0(e.payload,S),O=null;L&&(O=x("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=L);let H=x("div","persona-flex-1 persona-min-w-0"),R=x("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"),B=Ce("clipboard","12px","currentColor",1.5);return B&&R.appendChild(B),R.addEventListener("click",async ue=>{ue.stopPropagation(),await M0(L0(e)),R.innerHTML="";let De=Ce("check","12px","currentColor",1.5);De&&R.appendChild(De),setTimeout(()=>{R.innerHTML="";let Xe=Ce("clipboard","12px","currentColor",1.5);Xe&&R.appendChild(Xe)},1500)}),w.appendChild(v),w.appendChild(T),E&&w.appendChild(E),w.appendChild(h),O&&w.appendChild(O),w.appendChild(H),w.appendChild(R),f.appendChild(w),d&&f.appendChild(P0(e,s,i)),f}}function kh(e){var f,w,v,k,T;let{buffer:r,getFullHistory:t,onClose:n,config:o,plugins:a=[]}=e,s=(f=o==null?void 0:o.features)==null?void 0:f.scrollToBottom,i=(s==null?void 0:s.enabled)!==!1,d=(w=s==null?void 0:s.iconName)!=null?w:"arrow-down",l=(v=s==null?void 0:s.label)!=null?v:"",u=(T=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?T:{},p=a.find(A=>A.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&o){let A=p.renderEventStreamView({config:o,events:r.getAll(),defaultRenderer:()=>m().element,onClose:n});if(A)return{element:A,update:()=>{},destroy:()=>{}}}return m();function m(){let A=u.classNames,E=x("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ha(E,A==null?void 0:A.panel);let b=[],h="",S="",L=null,O=[],H={},R=0,B=Ji(),j=0,oe=0,ue=!1,De=null,Xe=!1,xe=0,ge=new Set,Le=new Map,Ge="",Q="",Se=null,J,ce,pe,ie,Oe;function Pe(){let N=x("div","persona-flex persona-flex-col persona-flex-shrink-0"),de=x("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");Ha(de,A==null?void 0:A.headerBar);let Ee=x("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ee.textContent="Events",J=x("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"),J.textContent="0";let ut=x("div","persona-flex-1");ce=x("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 Ye=x("option","");Ye.value="",Ye.textContent="All events",ce.appendChild(Ye),pe=x("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"),pe.type="button",pe.title="Copy All";let or=Ce("clipboard-copy","12px","currentColor",1.5);or&&pe.appendChild(or);let It=x("span","persona-text-xs");It.textContent="Copy All",pe.appendChild(It),de.appendChild(Ee),de.appendChild(J),de.appendChild(ut),de.appendChild(ce),de.appendChild(pe);let St=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ha(St,A==null?void 0:A.searchBar);let rt=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),it=x("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");rt&&it.appendChild(rt),ie=x("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"),Ha(ie,A==null?void 0:A.searchInput),ie.type="text",ie.placeholder="Search event payloads...",Oe=x("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"),Oe.type="button",Oe.style.display="none";let tr=Ce("x","12px","currentColor",2);return tr&&Oe.appendChild(tr),St.appendChild(it),St.appendChild(ie),St.appendChild(Oe),N.appendChild(de),N.appendChild(St),N}let K,_e=a.find(N=>N.renderEventStreamToolbar);if(_e!=null&&_e.renderEventStreamToolbar&&o){let N=_e.renderEventStreamToolbar({config:o,defaultRenderer:()=>Pe(),eventCount:r.getSize(),filteredCount:0,onFilterChange:de=>{h=de,He(),Yt()},onSearchChange:de=>{S=de,He(),Yt()}});K=N!=null?N:Pe()}else K=Pe();let $e=x("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");$e.style.display="none";let Y=x("div","persona-flex-1 persona-min-h-0 persona-relative"),G=x("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let we=x("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");Ha(we,A==null?void 0:A.scrollIndicator),we.style.display="none",we.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let ke=Ce(d,"14px","currentColor",2);ke&&we.appendChild(ke);let ae=x("span","");ae.textContent=l,we.appendChild(ae);let ve=x("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ve.style.display="none",Y.appendChild(G),Y.appendChild(ve),Y.appendChild(we),E.setAttribute("tabindex","0"),E.appendChild(K),E.appendChild($e),E.appendChild(Y);function ye(){let N=r.getAll(),de={};for(let It of N)de[It.type]=(de[It.type]||0)+1;let Ee=Object.keys(de).sort(),ut=Ee.length!==O.length||!Ee.every((It,St)=>It===O[St]),Ye=!ut&&Ee.some(It=>de[It]!==H[It]),Ut=N.length!==Object.values(H).reduce((It,St)=>It+St,0);if(!ut&&!Ye&&!Ut||(O=Ee,H=de,!ce))return;let or=ce.value;if(ce.options[0].textContent="All events",ut){for(;ce.options.length>1;)ce.remove(1);for(let It of Ee){let St=x("option","");St.value=It,St.textContent=`${It} (${de[It]||0})`,ce.appendChild(St)}or&&Ee.includes(or)?ce.value=or:or&&(ce.value="",h="")}else for(let It=1;It<ce.options.length;It++){let St=ce.options[It];St.textContent=`${St.value} (${de[St.value]||0})`}}function Mt(){let N=r.getAll();if(h&&(N=N.filter(de=>de.type===h)),S){let de=S.toLowerCase();N=N.filter(Ee=>Ee.type.toLowerCase().includes(de)||Ee.payload.toLowerCase().includes(de))}return N}function ne(){return h!==""||S!==""}function He(){R=0,j=0,B.resume(),we.style.display="none"}function fr(N){ge.has(N)?ge.delete(N):ge.add(N),Se=N;let de=G.scrollTop,Ee=B.isFollowing();Xe=!0,B.pause(),Yt(),G.scrollTop=de,Ee&&B.resume(),Xe=!1}function Ot(){return ws(G,50)}function Yt(){oe=Date.now(),ue=!1,ye();let N=r.getEvictedCount();N>0?($e.textContent=`${N.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",b=Mt();let de=b.length,Ee=r.getSize()>0;J&&(J.textContent=String(r.getSize())),de===0&&Ee&&ne()?(ve.textContent=S?`No events matching '${S}'`:"No events matching filter",ve.style.display="",G.style.display="none"):(ve.style.display="none",G.style.display=""),pe&&(pe.title=ne()?`Copy Filtered (${de})`:"Copy All"),i&&!B.isFollowing()&&de>R&&(j+=de-R,ae.textContent=l?`${l}${j>0?` (${j})`:""}`:"",we.style.display=""),R=de;let ut=r.getAll(),Ye=ut.length>0?ut[0].timestamp:0,Ut=new Set(b.map(St=>St.id));for(let St of ge)Ut.has(St)||ge.delete(St);let or=h!==Ge||S!==Q,It=Le.size===0&&b.length>0;if(or||It||b.length===0){G.innerHTML="",Le.clear();let St=document.createDocumentFragment();for(let rt=0;rt<b.length;rt++){let it=kp(b[rt],rt,Ye,u,ge,fr,a,o);Le.set(b[rt].id,it),St.appendChild(it)}G.appendChild(St),Ge=h,Q=S,Se=null}else{if(Se!==null){let rt=Le.get(Se);if(rt&&rt.parentNode===G){let it=b.findIndex(tr=>tr.id===Se);if(it>=0){let tr=kp(b[it],it,Ye,u,ge,fr,a,o);G.insertBefore(tr,rt),rt.remove(),Le.set(Se,tr)}}Se=null}let St=new Set(b.map(rt=>rt.id));for(let[rt,it]of Le)St.has(rt)||(it.remove(),Le.delete(rt));for(let rt=0;rt<b.length;rt++){let it=b[rt];if(!Le.has(it.id)){let tr=kp(it,rt,Ye,u,ge,fr,a,o);Le.set(it.id,tr),G.appendChild(tr)}}}B.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Fr(){if(Date.now()-oe>=A0){De!==null&&(cancelAnimationFrame(De),De=null),Yt();return}ue||(ue=!0,De=requestAnimationFrame(()=>{De=null,Yt()}))}let Ar=(N,de)=>{if(!pe)return;pe.innerHTML="";let Ee=Ce(N,"12px","currentColor",1.5);Ee&&pe.appendChild(Ee);let ut=x("span","persona-text-xs");ut.textContent="Copy All",pe.appendChild(ut),setTimeout(()=>{pe.innerHTML="";let Ye=Ce("clipboard-copy","12px","currentColor",1.5);Ye&&pe.appendChild(Ye);let Ut=x("span","persona-text-xs");Ut.textContent="Copy All",pe.appendChild(Ut),pe.disabled=!1},de)},F=async()=>{if(pe){pe.disabled=!0;try{let N;ne()?N=b:t?(N=await t(),N.length===0&&(N=r.getAll())):N=r.getAll();let de=N.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(de,null,2)),Ar("check",1500)}catch{Ar("x",1500)}}},le=()=>{ce&&(h=ce.value,He(),Yt())},Fe=()=>{!ie||!Oe||(Oe.style.display=ie.value?"":"none",L&&clearTimeout(L),L=setTimeout(()=>{S=ie.value,He(),Yt()},150))},Ke=()=>{!ie||!Oe||(ie.value="",S="",Oe.style.display="none",L&&clearTimeout(L),He(),Yt())},Ue=()=>{if(Xe)return;let N=G.scrollTop,{action:de,nextLastScrollTop:Ee}=Ki({following:B.isFollowing(),currentScrollTop:N,lastScrollTop:xe,nearBottom:Ot(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=Ee,de==="resume"?(B.resume(),j=0,we.style.display="none"):de==="pause"&&(B.pause(),i&&(ae.textContent=l,we.style.display=""))},qe=N=>{let de=Yi({following:B.isFollowing(),deltaY:N.deltaY,nearBottom:Ot(),resumeWhenNearBottom:!0});de==="pause"?(B.pause(),i&&(ae.textContent=l,we.style.display="")):de==="resume"&&(B.resume(),j=0,we.style.display="none")},nt=()=>{i&&(G.scrollTop=G.scrollHeight,B.resume(),j=0,we.style.display="none")},Ct=N=>{let de=N.target;if(!de||de.closest("button"))return;let Ee=de.closest("[data-event-id]");if(!Ee)return;let ut=Ee.getAttribute("data-event-id");ut&&fr(ut)},Pt=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),ie==null||ie.focus(),ie==null||ie.select();return}N.key==="Escape"&&(ie&&document.activeElement===ie?(Ke(),ie.blur(),E.focus()):n&&n())};pe&&pe.addEventListener("click",F),ce&&ce.addEventListener("change",le),ie&&ie.addEventListener("input",Fe),Oe&&Oe.addEventListener("click",Ke),G.addEventListener("scroll",Ue),G.addEventListener("wheel",qe,{passive:!0}),G.addEventListener("click",Ct),we.addEventListener("click",nt),E.addEventListener("keydown",Pt);function $t(){L&&clearTimeout(L),De!==null&&(cancelAnimationFrame(De),De=null),ue=!1,Le.clear(),pe&&pe.removeEventListener("click",F),ce&&ce.removeEventListener("change",le),ie&&ie.removeEventListener("input",Fe),Oe&&Oe.removeEventListener("click",Ke),G.removeEventListener("scroll",Ue),G.removeEventListener("wheel",qe),G.removeEventListener("click",Ct),we.removeEventListener("click",nt),E.removeEventListener("keydown",Pt)}return{element:E,update:Fr,destroy:$t}}}function Eh(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${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 p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let m=document.createElement("span");m.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",m.style.backgroundColor="var(--persona-primary, #171717)",m.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(m);let f=document.createElement("span");f.textContent=`Generating ${s.toLowerCase()}...`,p.appendChild(f)}else p.textContent=s;if(l.append(u,p),i.append(d,l),o==="complete"){let m=document.createElement("button");m.type="button",m.textContent="Download",m.title=`Download ${t}`,m.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-text, #1f2937)",m.style.backgroundColor="transparent",m.style.cursor="pointer",m.setAttribute("data-download-artifact",n),i.append(m)}return i}var Mh=(e,r)=>{var n,o,a;let t=(a=(o=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:a.renderCard;if(t){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:s,artifactType:l,status:d},config:r.config,defaultRenderer:()=>Eh(e,r)});if(u)return u}return Eh(e,r)};var Ep=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},lo=new Ep;lo.register("PersonaArtifactCard",Mh);function I0(e){var o;let r=x("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=x("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),r.appendChild(t),r.appendChild(n),r}function Lh(e,r){var pe,ie,Oe,Pe;let t=(ie=(pe=e.features)==null?void 0:pe.artifacts)==null?void 0:ie.layout,o=((Oe=t==null?void 0:t.toolbarPreset)!=null?Oe:"default")==="document",a=(Pe=t==null?void 0:t.panePadding)==null?void 0:Pe.trim(),s=e.markdown?Xo(e.markdown):null,i=ya(e.sanitize),d=K=>{let _e=s?s(K):Jo(K);return i?i(_e):_e},l=typeof document!="undefined"?x("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"),p.classList.remove("persona-artifact-drawer-open"),B==null||B.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let p=x("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");p.setAttribute("data-persona-theme-zone","artifact-pane"),o&&p.classList.add("persona-artifact-pane-document");let m=x("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");m.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&m.classList.add("persona-artifact-toolbar-document");let f=x("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let w=x("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let v="rendered",k=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Qt({icon:"eye",label:"Rendered view"}),A=o?Qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Qt({icon:"code-2",label:"Source"}),E=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),b=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,h=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,S=t==null?void 0:t.documentToolbarCopyMenuItems,L=!!(h&&S&&S.length>0),O=null,H,R=null,B=null;if(o&&(b||h)&&!L){if(H=b?Ls({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),h){let K=Ce("chevron-down",14,"currentColor",2);K&&H.appendChild(K)}}else o&&L?(O=x("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=b?Ls({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Qt({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"}}),O.append(H,R)):o?H=Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=Qt({icon:"copy",label:"Copy"});let j=o?Qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"refresh-cw",label:"Refresh"}),oe=o?Qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"x",label:"Close"}),ue=()=>{var G,we,ke;let K=(G=Ge.find(ae=>ae.id===Q))!=null?G:Ge[Ge.length-1],_e=(we=K==null?void 0:K.id)!=null?we:null,$e=(K==null?void 0:K.artifactType)==="markdown"&&(ke=K.markdown)!=null?ke:"",Y=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:$e,jsonPayload:Y,id:_e}},De=async()=>{var G;let{markdown:K,jsonPayload:_e}=ue(),$e=(G=Ge.find(we=>we.id===Q))!=null?G:Ge[Ge.length-1],Y=($e==null?void 0:$e.artifactType)==="markdown"?K:$e?_e:"";try{await navigator.clipboard.writeText(Y)}catch{}};if(H.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&L){let{markdown:_e,jsonPayload:$e,id:Y}=ue();try{await K({actionId:"primary",artifactId:Y,markdown:_e,jsonPayload:$e})}catch{}return}await De()}),R&&(S!=null&&S.length)){let K=()=>{var $e;return($e=p.closest("[data-persona-root]"))!=null?$e:document.body},_e=()=>{B=ko({items:S.map($e=>({id:$e.id,label:$e.label})),onSelect:async $e=>{let{markdown:Y,jsonPayload:G,id:we}=ue(),ke=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ke?await ke({actionId:$e,artifactId:we,markdown:Y,jsonPayload:G}):$e==="markdown"||$e==="md"?await navigator.clipboard.writeText(Y):$e==="json"||$e==="source"?await navigator.clipboard.writeText(G):await navigator.clipboard.writeText(Y||G)}catch{}},anchor:O!=null?O:R,position:"bottom-right",portal:K()})};p.isConnected?_e():requestAnimationFrame(_e),R.addEventListener("click",$e=>{$e.stopPropagation(),B==null||B.toggle()})}j.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}J()}),oe.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let Xe=()=>{o&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),A.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",Xe(),J()}),A.addEventListener("click",()=>{v="source",Xe(),J()});let xe=x("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(m.replaceChildren(),k.append(T,A),O?E.append(O,j,oe):E.append(H,j,oe),m.append(k,xe,E),Xe()):(m.appendChild(f),m.appendChild(w)),a&&(m.style.paddingLeft=a,m.style.paddingRight=a);let ge=x("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"),Le=x("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(ge.style.paddingLeft=a,ge.style.paddingRight=a,Le.style.padding=a),p.appendChild(m),p.appendChild(ge),p.appendChild(Le);let Ge=[],Q=null,Se=!1,J=()=>{var Y,G,we,ke;let K=o&&Ge.length<=1;ge.classList.toggle("persona-hidden",K),ge.replaceChildren();for(let ae of Ge){let ve=x("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");ve.type="button",ve.textContent=ae.title||ae.id.slice(0,8),ae.id===Q&&ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),ve.addEventListener("click",()=>r.onSelect(ae.id)),ge.appendChild(ve)}Le.replaceChildren();let _e=Q&&Ge.find(ae=>ae.id===Q)||Ge[Ge.length-1];if(!_e)return;if(o){let ae=_e.artifactType==="markdown"?"MD":(Y=_e.component)!=null?Y:"Component",ye=(_e.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${ye} \xB7 ${ae}`}else f.textContent="Artifacts";if(_e.artifactType==="markdown"){if(o&&v==="source"){let ve=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ve.textContent=(G=_e.markdown)!=null?G:"",Le.appendChild(ve);return}let ae=x("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ae.innerHTML=d((we=_e.markdown)!=null?we:""),Le.appendChild(ae);return}let $e=_e.component?lo.get(_e.component):void 0;if($e){let ve={message:{id:_e.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let ye=$e((ke=_e.props)!=null?ke:{},ve);if(ye){Le.appendChild(ye);return}}catch{}}Le.appendChild(I0(_e))},ce=()=>{var _e;let K=Ge.length>0;if(p.classList.toggle("persona-hidden",!K),l){let $e=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,G=((_e=$e==null?void 0:$e.classList.contains("persona-artifact-narrow-host"))!=null?_e:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&G&&Se?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var _e,$e,Y;Ge=K.artifacts,Q=(Y=($e=K.selectedId)!=null?$e:(_e=K.artifacts[K.artifacts.length-1])==null?void 0:_e.id)!=null?Y:null,Ge.length>0&&(Se=!0),J(),ce()},setMobileOpen(K){Se=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ce()}}}function Sn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Ph(e,r){var a,s,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Sn(r))return;let t=(s=(a=r.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?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function R0(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function gl(e,r){var d,l,u,p,m,f,w,v,k,T;if(!Sn(r)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),R0(e),Ph(e,r);return}let t=(l=(d=r.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(m=t==null?void 0:t.paneMaxWidth)!=null?m:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=t==null?void 0:t.paneBackground)==null?void 0:f.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let o=(w=t==null?void 0:t.panePadding)==null?void 0:w.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let a=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(k=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:k.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ph(e,r)}var Ih=["panel","seamless"];function hl(e,r){var i,d,l,u,p,m;for(let f of Ih)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Sn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",o=Ih.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let a=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((m=t.unifiedSplitOuterRadius)==null?void 0:m.trim())||a;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Rh(e,r){var t,n,o;return!r||!Sn(e)?!1:((o=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function H0(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function B0(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function W0(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function D0(e,r,t,n){let o=e-n-2*r-t;return Math.max(0,o)}function Hh(e,r){var s;let n=(s=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function Bh(e,r,t,n,o,a){let s=H0(o,200),i=D0(r,t,n,200);i=Math.max(s,i);let d=B0(a);return d!==null&&(i=Math.min(i,d)),W0(e,s,i)}var Wh={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"}},Mp=(e,r,t,n)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(a=>{var w,v,k;if(a.dataset.enhanced==="true")return;let s=(w=a.dataset.tvForm)!=null?w:"init";a.dataset.enhanced="true";let i=(v=Wh[s])!=null?v:Wh.init;a.classList.add("persona-form-card","persona-space-y-4");let d=x("div","persona-space-y-1"),l=x("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=x("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 S,L;let A=x("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${r.id}-${s}-${T.name}`;let E=x("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=T.label,A.appendChild(E);let b=(S=T.type)!=null?S:"text",h;b==="textarea"?(h=document.createElement("textarea"),h.rows=3):(h=document.createElement("input"),h.type=b),h.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",h.id=`${r.id}-${s}-${T.name}`,h.name=T.name,h.placeholder=(L=T.placeholder)!=null?L:"",T.required&&(h.required=!0),A.appendChild(h),u.appendChild(A)});let p=x("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),m=x("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=x("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(k=i.submitLabel)!=null?k:"Submit",p.appendChild(m),p.appendChild(f),u.appendChild(p),a.replaceChildren(d,u),u.addEventListener("submit",async T=>{var h,S;T.preventDefault();let A=(h=t.formEndpoint)!=null?h:"/form",E=new FormData(u),b={};E.forEach((L,O)=>{b[O]=L}),b.type=s,f.disabled=!0,m.textContent="Submitting\u2026";try{let L=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let O=await L.json();m.textContent=(S=O.message)!=null?S:"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await n.sendMessage(String(O.nextPrompt))}catch(L){m.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Lp=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,o;return((n=t.priority)!=null?n:0)-((o=r.priority)!=null?o:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(a=>a.id));return[...t.filter(a=>!n.has(a.id)),...r].sort((a,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=a.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Bs=new Lp;var Dh=()=>{let e=new Map,r=(o,a)=>(e.has(o)||e.set(o,new Set),e.get(o).add(a),()=>t(o,a)),t=(o,a)=>{var s;(s=e.get(o))==null||s.delete(a)};return{on:r,off:t,emit:(o,a)=>{var s;(s=e.get(o))==null||s.forEach(i=>{try{i(a)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var O0=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},F0=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let o=t;o<r.length;o+=1){let a=r[o];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return r.slice(t,o+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=O0(e),t=F0(r);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}},Pp=e=>typeof e=="string"?e:e==null?"":String(e),sa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pp(e.payload.text)},messageAndClick:(e,r)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,n=Pp(t.element);if(n&&((o=r.document)!=null&&o.querySelector)){let a=r.document.querySelector(n);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Pp(t.text)}}},Oh=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ds=e=>{let r=new Set(Oh(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Oh(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(r);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||r.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;r.add(a.message.id),n();let d={action:i,message:a.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var N0=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},_0=e=>e.map(r=>({...r,streaming:!1})),$0=e=>e.map(r=>({...r,status:"complete"})),xl=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?N0(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let o={...t,messages:t.messages?_0(t.messages):void 0,artifacts:t.artifacts?$0(t.artifacts):void 0};n.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Ba=Bl(hi(),1);function U0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function q0(e,r){if(!U0(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function yl(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let o=(0,Ba.parse)(t,Ba.STR|Ba.OBJ),a=q0(o,t);a&&(e=a)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Fh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function bl(e,r){let{config:t,message:n,onPropsUpdate:o}=r,a=lo.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:n,config:t,updateProps:i=>{o&&o(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Nh(){let e=yl();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function _h(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let r=e.content.trim();if(r.startsWith("{")||r.startsWith("["))return e.content}return null}function Cl(e){let r=_h(e);if(!r)return!1;try{let t=JSON.parse(r);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function wl(e){let r=_h(e);if(!r)return null;try{let t=JSON.parse(r);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:r}}}catch{}return null}var z0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vl(e){let{onSubmit:r,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=z0}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=n,f.appendChild(w);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,f.appendChild(v),m.appendChild(f);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let S=1;S<=5;S++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),L.title=l[S-1],L.dataset.rating=String(S),L.innerHTML=`
|
|
66
|
+
`):""},Qb=(e,r)=>{var u,p,f,m,C;let t=e.toolCall,n=(u=r==null?void 0:r.features)==null?void 0:u.toolCallDisplay,o=(p=n==null?void 0:n.collapsedMode)!=null?p:"tool-call",a=Yb(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),s=t?Mg(t):"";if(!t)return{summary:s,previewText:a,isActive:!1};let i=t.status!=="complete",d=(m=r==null?void 0:r.toolCall)!=null?m:{},l=s;return o==="tool-name"?l=((C=t.name)==null?void 0:C.trim())||s:o==="tool-preview"&&a&&(l=a),i&&d.activeTextTemplate?l=ed(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ed(t,d.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},ph=(e,r,t)=>{var u;let n=La.has(e),o=(u=t==null?void 0:t.toolCall)!=null?u:{},a=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),i=r.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 p=o.toggleTextColor||o.headerTextColor||"currentColor",f=Ce(n?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},xp=(e,r)=>{var j,oe,ue,De,Xe,xe,ge,Le,Ge;let t=e.toolCall,n=(j=r==null?void 0:r.toolCall)!=null?j:{},o=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!t)return o;let a=(ue=(oe=r==null?void 0:r.features)==null?void 0:oe.toolCallDisplay)!=null?ue:{},s=a.expandable!==!1,i=s&&La.has(e.id),{summary:d,previewText:l,isActive:u}=Qb(e,r),p=h("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",s&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(p.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(p.style.paddingLeft=n.headerPaddingX,p.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(p.style.paddingTop=n.headerPaddingY,p.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(m.style.color=n.headerTextColor);let C=String((De=t.startedAt)!=null?De:Date.now()),A=()=>{let Q=h("span","");return Q.setAttribute("data-tool-elapsed",C),Q.textContent=ms(t),Q},k=(xe=n.renderCollapsedSummary)==null?void 0:xe.call(n,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Xe=a.collapsedMode)!=null?Xe:"tool-call",isActive:u,config:r!=null?r:{},elapsed:ms(t),createElapsedElement:A});typeof k=="string"&&k.trim()?(m.textContent=k,f.appendChild(m)):k instanceof HTMLElement?f.appendChild(k):(m.textContent=d,f.appendChild(m));let T=(ge=a.loadingAnimation)!=null?ge:"none",S=n.activeTextTemplate,E=n.completeTextTemplate,b=u?S:E,y=k instanceof HTMLElement,v=(Q,Se,J)=>{let ce=J;for(let pe of Se){let ie=h("span","persona-tool-char");ie.style.setProperty("--char-index",String(ce)),ie.textContent=pe===" "?"\xA0":pe,Q.appendChild(ie),ce++}return ce},M=(Q,Se)=>{var ie;m.textContent="";let J=((ie=t.name)==null?void 0:ie.trim())||"tool",ce=Ci(Q,J),pe=0;for(let Oe of ce){let Pe=Oe.styles.length>0?(()=>{let K=h("span",Oe.styles.map(_e=>`persona-tool-text-${_e}`).join(" "));return m.appendChild(K),K})():m;if(Oe.isDuration&&u)Pe.appendChild(A());else{let K=Oe.isDuration?ms(t):Oe.text;Se?pe=v(Pe,K,pe):Pe.appendChild(document.createTextNode(K))}}};if(!y)if(u&&T!=="none"){let Q=(Le=n.loadingAnimationDuration)!=null?Le:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),b&&M(b,!1);else if(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),T==="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)),b)M(b,!0);else{let Se=m.textContent||d;m.textContent="",v(m,Se,0)}}else b&&M(b,!1);let B=null;if(s){B=h("div","persona-flex persona-items-center");let Q=n.toggleTextColor||n.headerTextColor||"currentColor",Se=Ce(i?"chevron-up":"chevron-down",16,Q,2);Se?B.appendChild(Se):B.textContent=i?"Hide":"Show";let J=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");J.append(B),p.append(f,J)}else p.append(f);let W=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","tool"),W.style.display="none",W.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&l){let Q=(Ge=n.renderCollapsedPreview)==null?void 0:Ge.call(n,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:r!=null?r:{}});Kb(W,Q)||(W.textContent=l),W.style.display=""}if(!i&&u&&a.activeMinHeight&&(o.style.minHeight=a.activeMinHeight),!s)return o.append(p,W),o;let R=h("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),t.name){let Q=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?Q.style.color=n.contentTextColor:n.headerTextColor&&(Q.style.color=n.headerTextColor),Q.textContent=t.name,R.appendChild(Q)}if(t.args!==void 0){let Q=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Arguments";let J=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=ba(t.args),Q.append(Se,J),R.appendChild(Q)}if(t.chunks&&t.chunks.length){let Q=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Activity";let J=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=t.chunks.join(""),Q.append(Se,J),R.appendChild(Q)}if(t.status==="complete"&&t.result!==void 0){let Q=h("div","persona-space-y-1"),Se=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Result";let J=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=ba(t.result),Q.append(Se,J),R.appendChild(Q)}if(t.status==="complete"&&typeof t.duration=="number"){let Q=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(Q.style.color=n.contentTextColor),Q.textContent=`Duration: ${t.duration}ms`,R.appendChild(Q)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),B){B.innerHTML="";let Q=n.toggleTextColor||n.headerTextColor||"currentColor",Se=Ce(i?"chevron-up":"chevron-down",16,Q,2);Se?B.appendChild(Se):B.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",W.style.display=i?"none":W.textContent||W.childNodes.length?"":"none"})(),o.append(p,W,R),o};var Eo=Bl(hi(),1);var bp="ask_user_question",yp=8,Pa="data-persona-ask-sheet-for",Zb="Other",e0="Other\u2026",fh="Type your own answer here",mh="Send",t0="Next",r0="Back",n0="Submit all",o0="Skip",a0=3,Cp="data-ask-current-index",wp="data-ask-question-count",gh="data-ask-answers",vp="data-ask-grouped",hh="data-ask-layout",s0=e=>e.layout==="pills"?"pills":"rows",i0=e=>e.getAttribute(hh)==="pills"?"pills":"rows",uh=!1,xh=e=>e.replace(/["\\]/g,"\\$&"),so=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===bp,ul=e=>{var r,t;return(t=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion)!=null?t:{}},io=e=>{let r=e.toolCall;if(!r)return{payload:null,complete:!1};let t=r.status==="complete";if(r.args&&typeof r.args=="object")return{payload:r.args,complete:t};let n=r.chunks;if(!n||n.length===0)return{payload:null,complete:t};try{let o=n.join(""),a=(0,Eo.parse)(o,Eo.STR|Eo.OBJ|Eo.ARR);if(a&&typeof a=="object")return{payload:a,complete:t}}catch{}return{payload:null,complete:t}},Is=e=>{let r=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return r.length>yp&&!uh&&(uh=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${r.length} questions; truncating to ${yp}.`)),r.slice(0,yp)},l0=e=>{var r;return(r=Is(e)[0])!=null?r:null},d0=(e,r)=>{var t;return(t=Is(e)[r])!=null?t:null},yh=(e,r)=>{let t=r.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},bh=(e,r,t)=>{if(e!=="rows")return null;let n=h("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),r){let o=h("span","persona-ask-row-check");n.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(t+1),n.appendChild(o)}return n},c0=(e,r,t,n)=>{let a=h("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(r)),a.setAttribute("data-option-label",e.label),t==="rows"){let s=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let d=bh(t,n,r);d&&a.appendChild(d)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},p0=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},u0=(e,r,t,n)=>{var u,p,f;let a=h("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<a0;m++)a.appendChild(p0(n));return a}if(d.forEach((m,C)=>{a.appendChild(c0(m,C,n,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=n==="rows"?Zb:e0;if(n==="rows"){let C=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let A=h("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(u=r.freeTextPlaceholder)!=null?u:fh,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(p=r.freeTextLabel)!=null?p:m),A.appendChild(k),C.appendChild(A);let T=bh(n,s,d.length);T&&C.appendChild(T),a.appendChild(C)}else{let C=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(f=r.freeTextLabel)!=null?f:m,a.appendChild(C)}}return a},Ch=(e,r)=>{var a,s;let n=h("div",r==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(a=e.freeTextPlaceholder)!=null?a:fh,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),r!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:mh,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},f0=e=>{var n;let r=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");r.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(n=e.submitLabel)!=null?n:mh,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,r.appendChild(t),r},m0=(e,r,t)=>{var l,u,p,f;let n=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=t.backLabel)!=null?l:r0,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,n.appendChild(o);let a=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=h("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=t.skipLabel)!=null?u:o0,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===r-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:n0:(f=t.nextLabel)!=null?f:t0,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n},aa=e=>{let r=e.getAttribute(gh);if(!r)return{};try{let t=JSON.parse(r);return t&&typeof t=="object"?t:{}}catch{return{}}},wh=(e,r)=>{e.setAttribute(gh,JSON.stringify(r))},An=e=>{var t;let r=Number((t=e.getAttribute(Cp))!=null?t:"0");return Number.isFinite(r)?Math.max(0,Math.floor(r)):0},g0=(e,r)=>{e.setAttribute(Cp,String(Math.max(0,Math.floor(r))))},Ia=e=>{var t;let r=Number((t=e.getAttribute(wp))!=null?t:"1");return Number.isFinite(r)?Math.max(1,Math.floor(r)):1},Mo=e=>e.getAttribute(vp)==="true",h0=(e,r)=>{var o;let t=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let n={};return r.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},x0=(e,r)=>{var n;let t=(n=e.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(r-1,Math.floor(t)))},fl=(e,r)=>{let{payload:t}=io(r),n=Is(t),o=aa(e),a={},s=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(a[l]=o[d]))}),a},vh=e=>{let r=aa(e),t=An(e),n=r[t],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",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=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!s.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Ah=e=>{if(!Mo(e))return;let r=aa(e),t=An(e),n=r[t],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!o);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Ap=(e,r,t)=>{let n=ul(t),o=i0(e),{payload:a,complete:s}=io(r),i=Mo(e),d=An(e),l=Ia(e),u=i?d0(a,d):l0(a),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let S=typeof(u==null?void 0:u.question)=="string"?u.question:"";C.textContent=S,C.classList.toggle("persona-ask-question-skeleton",!S&&!s)}let A=e.querySelector('[data-ask-pill-list="true"]');if(A){let S=u0(u,n,s,o);A.replaceWith(S)}if(o!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(Ch(n,o))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(f0(n)):(!p||i)&&k&&k.remove(),e.setAttribute("data-multi-select",p?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let S=m0(d,l,n);T?T.replaceWith(S):e.appendChild(S)}else T&&T.remove();vh(e),Ah(e)},y0=(e,r,t)=>{let n=ul(r),o=s0(n),a=e.toolCall.id,s=Is(t),i=Math.max(1,s.length),d=i>1,l=h0(e,s),u=d?x0(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Pa,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(wp,String(i)),p.setAttribute(Cp,String(u)),p.setAttribute(vp,d?"true":"false"),p.setAttribute(hh,o),wh(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),yh(p,n);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let C=h("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",f.appendChild(C),p.appendChild(f);let k=h("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),p.appendChild(k),o!=="rows"&&p.appendChild(Ch(n,o)),Ap(p,e,r),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},b0=(e,r,t)=>{let{payload:n}=io(r),o=Math.max(1,Is(n).length);o>Ia(e)&&(e.setAttribute(wp,String(o)),o>1&&!Mo(e)&&e.setAttribute(vp,"true")),Ap(e,r,t)},Sh=(e,r)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let n=ul(r);yh(t,n);let o=h("span","persona-ask-stub-label"),{complete:a}=io(e);return o.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},Ra=(e,r,t)=>{if(!t||!so(e)||ul(r).enabled===!1)return;let o=e.toolCall.id;t.querySelectorAll(`[${Pa}]`).forEach(l=>{l.getAttribute(Pa)!==o&&l.remove()});let s=t.querySelector(`[${Pa}="${xh(o)}"]`);if(s){b0(s,e,r);return}let{payload:i}=io(e),d=y0(e,r,i);t.appendChild(d)},Lo=(e,r)=>{if(!e)return;let t=r?`[${Pa}="${xh(r)}"]`:`[${Pa}]`;e.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)})},Sp=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(r=>r.getAttribute("data-option-label")).filter(r=>typeof r=="string"&&r.length>0),Po=(e,r)=>{let t=aa(e),n=An(e);typeof r=="string"&&r.length===0||Array.isArray(r)&&r.length===0?delete t[n]:t[n]=r,wh(e,t),vh(e),Ah(e)},ml=(e,r,t,n)=>{let o=Ia(e),a=Math.max(0,Math.min(o-1,n));g0(e,a),Ap(e,r,t)};var Tp=(e,r)=>{var A,k,T,S,E,b,y,v,M,B,W,R;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,o=(t==null?void 0:t.status)==="pending",a=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(A=n==null?void 0:n.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(k=n==null?void 0:n.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return a;let s=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=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)":(T=n==null?void 0:n.titleColor)!=null?T:"currentColor",u=Ce(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(S=n==null?void 0:n.title)!=null?S:"Approval Required",f.appendChild(m),!o){let H=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");H.setAttribute("data-approval-status",t.status),t.status==="approved"?(H.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",H.style.color="var(--persona-palette-colors-success-700, #15803d)",H.textContent="Approved"):t.status==="denied"?(H.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",H.style.color="var(--persona-palette-colors-error-700, #b91c1c)",H.textContent="Denied"):t.status==="timeout"&&(H.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",H.style.color="var(--persona-palette-colors-warning-700, #b45309)",H.textContent="Timeout"),f.appendChild(H)}p.appendChild(f);let C=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(C.style.color=n.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let H=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(H.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(H.style.color=n.parameterTextColor),H.style.fontSize="0.75rem",H.style.lineHeight="1rem",H.textContent=ba(t.parameters),p.appendChild(H)}if(o){let H=h("div","persona-flex persona-gap-2 persona-mt-2");H.setAttribute("data-approval-buttons","true");let j=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");j.type="button",j.style.backgroundColor=(E=n==null?void 0:n.approveButtonColor)!=null?E:"var(--persona-approval-approve-bg, #22c55e)",j.style.color=(b=n==null?void 0:n.approveButtonTextColor)!=null?b:"#ffffff",j.setAttribute("data-approval-action","approve");let oe=Ce("shield-check",14,(y=n==null?void 0:n.approveButtonTextColor)!=null?y:"#ffffff",2);oe&&(oe.style.marginRight="4px",j.appendChild(oe));let ue=document.createTextNode((v=n==null?void 0:n.approveLabel)!=null?v:"Approve");j.appendChild(ue);let De=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");De.type="button",De.style.backgroundColor=(M=n==null?void 0:n.denyButtonColor)!=null?M:"transparent",De.style.color=(B=n==null?void 0:n.denyButtonTextColor)!=null?B:"var(--persona-feedback-error, #dc2626)",De.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,De.setAttribute("data-approval-action","deny");let Xe=Ce("shield-x",14,(W=n==null?void 0:n.denyButtonTextColor)!=null?W:"var(--persona-feedback-error, #dc2626)",2);Xe&&(Xe.style.marginRight="4px",De.appendChild(Xe));let xe=document.createTextNode((R=n==null?void 0:n.denyLabel)!=null?R:"Deny");De.appendChild(xe),H.append(j,De),p.appendChild(H)}return s.append(i,p),a.appendChild(s),a};var Th=e=>{let r=[];return{buttons:r,render:(n,o,a,s,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(s!=null?s:o?o.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=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 C=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",o.sendMessage(m))}),u.appendChild(C),r.push(C)}),e.appendChild(u)}}};var Rs=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;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=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Hs=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,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,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of r)n.put(o)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{r(s.result)},s.onerror=()=>{t(s.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{r()},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((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of r)n.put(o)}catch{}}};function Ha(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var C0={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)"}},w0={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},v0=["flowName","stepName","reasoningText","text","name","tool","toolName"],A0=100;function S0(e,r){let t={...C0,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return w0}function T0(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function k0(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),o=String(r.getSeconds()).padStart(2,"0"),a=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${o}.${a}`}function E0(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){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 M0(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function L0(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function P0(e,r,t){let n,o;try{o=JSON.parse(e.payload),n=JSON.stringify(o,null,2)}catch{o=e.payload,n=e.payload}let a=r.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&t){let i=a.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>s(),parsedPayload:o});if(i)return i}return s();function s(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function kp(e,r,t,n,o,a,s,i){var f;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Ha(l,(f=n.classNames)==null?void 0:f.eventRow);let u=s.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>a(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var j,oe;let m=h("div",""),C=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let A=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),k=Ce(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&A.appendChild(k);let T=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(j=n.timestampFormat)!=null?j:"relative";T.textContent=S==="relative"?T0(e.timestamp,t):k0(e.timestamp);let E=null;n.showSequenceNumbers!==!1&&(E=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(r+1));let b=S0(e.type,n.badgeColors),y=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");y.style.backgroundColor=b.bg,y.style.color=b.text,y.style.borderColor=b.text+"50",y.textContent=e.type;let v=(oe=n.descriptionFields)!=null?oe:v0,M=E0(e.payload,v),B=null;M&&(B=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=M);let W=h("div","persona-flex-1 persona-min-w-0"),R=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),H=Ce("clipboard","12px","currentColor",1.5);return H&&R.appendChild(H),R.addEventListener("click",async ue=>{ue.stopPropagation(),await M0(L0(e)),R.innerHTML="";let De=Ce("check","12px","currentColor",1.5);De&&R.appendChild(De),setTimeout(()=>{R.innerHTML="";let Xe=Ce("clipboard","12px","currentColor",1.5);Xe&&R.appendChild(Xe)},1500)}),C.appendChild(A),C.appendChild(T),E&&C.appendChild(E),C.appendChild(y),B&&C.appendChild(B),C.appendChild(W),C.appendChild(R),m.appendChild(C),d&&m.appendChild(P0(e,s,i)),m}}function kh(e){var m,C,A,k,T;let{buffer:r,getFullHistory:t,onClose:n,config:o,plugins:a=[]}=e,s=(m=o==null?void 0:o.features)==null?void 0:m.scrollToBottom,i=(s==null?void 0:s.enabled)!==!1,d=(C=s==null?void 0:s.iconName)!=null?C:"arrow-down",l=(A=s==null?void 0:s.label)!=null?A:"",u=(T=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?T:{},p=a.find(S=>S.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&o){let S=p.renderEventStreamView({config:o,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(S)return{element:S,update:()=>{},destroy:()=>{}}}return f();function f(){let S=u.classNames,E=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ha(E,S==null?void 0:S.panel);let b=[],y="",v="",M=null,B=[],W={},R=0,H=Ji(),j=0,oe=0,ue=!1,De=null,Xe=!1,xe=0,ge=new Set,Le=new Map,Ge="",Q="",Se=null,J,ce,pe,ie,Oe;function Pe(){let N=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),de=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Ha(de,S==null?void 0:S.headerBar);let Ee=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ee.textContent="Events",J=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),J.textContent="0";let ut=h("div","persona-flex-1");ce=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ye=h("option","");Ye.value="",Ye.textContent="All events",ce.appendChild(Ye),pe=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),pe.type="button",pe.title="Copy All";let or=Ce("clipboard-copy","12px","currentColor",1.5);or&&pe.appendChild(or);let It=h("span","persona-text-xs");It.textContent="Copy All",pe.appendChild(It),de.appendChild(Ee),de.appendChild(J),de.appendChild(ut),de.appendChild(ce),de.appendChild(pe);let St=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ha(St,S==null?void 0:S.searchBar);let rt=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),it=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");rt&&it.appendChild(rt),ie=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ha(ie,S==null?void 0:S.searchInput),ie.type="text",ie.placeholder="Search event payloads...",Oe=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Oe.type="button",Oe.style.display="none";let tr=Ce("x","12px","currentColor",2);return tr&&Oe.appendChild(tr),St.appendChild(it),St.appendChild(ie),St.appendChild(Oe),N.appendChild(de),N.appendChild(St),N}let K,_e=a.find(N=>N.renderEventStreamToolbar);if(_e!=null&&_e.renderEventStreamToolbar&&o){let N=_e.renderEventStreamToolbar({config:o,defaultRenderer:()=>Pe(),eventCount:r.getSize(),filteredCount:0,onFilterChange:de=>{y=de,He(),Yt()},onSearchChange:de=>{v=de,He(),Yt()}});K=N!=null?N:Pe()}else K=Pe();let $e=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");$e.style.display="none";let Y=h("div","persona-flex-1 persona-min-h-0 persona-relative"),G=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let we=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ha(we,S==null?void 0:S.scrollIndicator),we.style.display="none",we.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let ke=Ce(d,"14px","currentColor",2);ke&&we.appendChild(ke);let ae=h("span","");ae.textContent=l,we.appendChild(ae);let ve=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ve.style.display="none",Y.appendChild(G),Y.appendChild(ve),Y.appendChild(we),E.setAttribute("tabindex","0"),E.appendChild(K),E.appendChild($e),E.appendChild(Y);function ye(){let N=r.getAll(),de={};for(let It of N)de[It.type]=(de[It.type]||0)+1;let Ee=Object.keys(de).sort(),ut=Ee.length!==B.length||!Ee.every((It,St)=>It===B[St]),Ye=!ut&&Ee.some(It=>de[It]!==W[It]),Ut=N.length!==Object.values(W).reduce((It,St)=>It+St,0);if(!ut&&!Ye&&!Ut||(B=Ee,W=de,!ce))return;let or=ce.value;if(ce.options[0].textContent="All events",ut){for(;ce.options.length>1;)ce.remove(1);for(let It of Ee){let St=h("option","");St.value=It,St.textContent=`${It} (${de[It]||0})`,ce.appendChild(St)}or&&Ee.includes(or)?ce.value=or:or&&(ce.value="",y="")}else for(let It=1;It<ce.options.length;It++){let St=ce.options[It];St.textContent=`${St.value} (${de[St.value]||0})`}}function Mt(){let N=r.getAll();if(y&&(N=N.filter(de=>de.type===y)),v){let de=v.toLowerCase();N=N.filter(Ee=>Ee.type.toLowerCase().includes(de)||Ee.payload.toLowerCase().includes(de))}return N}function ne(){return y!==""||v!==""}function He(){R=0,j=0,H.resume(),we.style.display="none"}function fr(N){ge.has(N)?ge.delete(N):ge.add(N),Se=N;let de=G.scrollTop,Ee=H.isFollowing();Xe=!0,H.pause(),Yt(),G.scrollTop=de,Ee&&H.resume(),Xe=!1}function Ot(){return ws(G,50)}function Yt(){oe=Date.now(),ue=!1,ye();let N=r.getEvictedCount();N>0?($e.textContent=`${N.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",b=Mt();let de=b.length,Ee=r.getSize()>0;J&&(J.textContent=String(r.getSize())),de===0&&Ee&&ne()?(ve.textContent=v?`No events matching '${v}'`:"No events matching filter",ve.style.display="",G.style.display="none"):(ve.style.display="none",G.style.display=""),pe&&(pe.title=ne()?`Copy Filtered (${de})`:"Copy All"),i&&!H.isFollowing()&&de>R&&(j+=de-R,ae.textContent=l?`${l}${j>0?` (${j})`:""}`:"",we.style.display=""),R=de;let ut=r.getAll(),Ye=ut.length>0?ut[0].timestamp:0,Ut=new Set(b.map(St=>St.id));for(let St of ge)Ut.has(St)||ge.delete(St);let or=y!==Ge||v!==Q,It=Le.size===0&&b.length>0;if(or||It||b.length===0){G.innerHTML="",Le.clear();let St=document.createDocumentFragment();for(let rt=0;rt<b.length;rt++){let it=kp(b[rt],rt,Ye,u,ge,fr,a,o);Le.set(b[rt].id,it),St.appendChild(it)}G.appendChild(St),Ge=y,Q=v,Se=null}else{if(Se!==null){let rt=Le.get(Se);if(rt&&rt.parentNode===G){let it=b.findIndex(tr=>tr.id===Se);if(it>=0){let tr=kp(b[it],it,Ye,u,ge,fr,a,o);G.insertBefore(tr,rt),rt.remove(),Le.set(Se,tr)}}Se=null}let St=new Set(b.map(rt=>rt.id));for(let[rt,it]of Le)St.has(rt)||(it.remove(),Le.delete(rt));for(let rt=0;rt<b.length;rt++){let it=b[rt];if(!Le.has(it.id)){let tr=kp(it,rt,Ye,u,ge,fr,a,o);Le.set(it.id,tr),G.appendChild(tr)}}}H.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Fr(){if(Date.now()-oe>=A0){De!==null&&(cancelAnimationFrame(De),De=null),Yt();return}ue||(ue=!0,De=requestAnimationFrame(()=>{De=null,Yt()}))}let Ar=(N,de)=>{if(!pe)return;pe.innerHTML="";let Ee=Ce(N,"12px","currentColor",1.5);Ee&&pe.appendChild(Ee);let ut=h("span","persona-text-xs");ut.textContent="Copy All",pe.appendChild(ut),setTimeout(()=>{pe.innerHTML="";let Ye=Ce("clipboard-copy","12px","currentColor",1.5);Ye&&pe.appendChild(Ye);let Ut=h("span","persona-text-xs");Ut.textContent="Copy All",pe.appendChild(Ut),pe.disabled=!1},de)},F=async()=>{if(pe){pe.disabled=!0;try{let N;ne()?N=b:t?(N=await t(),N.length===0&&(N=r.getAll())):N=r.getAll();let de=N.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(de,null,2)),Ar("check",1500)}catch{Ar("x",1500)}}},le=()=>{ce&&(y=ce.value,He(),Yt())},Fe=()=>{!ie||!Oe||(Oe.style.display=ie.value?"":"none",M&&clearTimeout(M),M=setTimeout(()=>{v=ie.value,He(),Yt()},150))},Ke=()=>{!ie||!Oe||(ie.value="",v="",Oe.style.display="none",M&&clearTimeout(M),He(),Yt())},Ue=()=>{if(Xe)return;let N=G.scrollTop,{action:de,nextLastScrollTop:Ee}=Ki({following:H.isFollowing(),currentScrollTop:N,lastScrollTop:xe,nearBottom:Ot(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=Ee,de==="resume"?(H.resume(),j=0,we.style.display="none"):de==="pause"&&(H.pause(),i&&(ae.textContent=l,we.style.display=""))},qe=N=>{let de=Yi({following:H.isFollowing(),deltaY:N.deltaY,nearBottom:Ot(),resumeWhenNearBottom:!0});de==="pause"?(H.pause(),i&&(ae.textContent=l,we.style.display="")):de==="resume"&&(H.resume(),j=0,we.style.display="none")},nt=()=>{i&&(G.scrollTop=G.scrollHeight,H.resume(),j=0,we.style.display="none")},Ct=N=>{let de=N.target;if(!de||de.closest("button"))return;let Ee=de.closest("[data-event-id]");if(!Ee)return;let ut=Ee.getAttribute("data-event-id");ut&&fr(ut)},Pt=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),ie==null||ie.focus(),ie==null||ie.select();return}N.key==="Escape"&&(ie&&document.activeElement===ie?(Ke(),ie.blur(),E.focus()):n&&n())};pe&&pe.addEventListener("click",F),ce&&ce.addEventListener("change",le),ie&&ie.addEventListener("input",Fe),Oe&&Oe.addEventListener("click",Ke),G.addEventListener("scroll",Ue),G.addEventListener("wheel",qe,{passive:!0}),G.addEventListener("click",Ct),we.addEventListener("click",nt),E.addEventListener("keydown",Pt);function $t(){M&&clearTimeout(M),De!==null&&(cancelAnimationFrame(De),De=null),ue=!1,Le.clear(),pe&&pe.removeEventListener("click",F),ce&&ce.removeEventListener("change",le),ie&&ie.removeEventListener("input",Fe),Oe&&Oe.removeEventListener("click",Ke),G.removeEventListener("scroll",Ue),G.removeEventListener("wheel",qe),G.removeEventListener("click",Ct),we.removeEventListener("click",nt),E.removeEventListener("keydown",Pt)}return{element:E,update:Fr,destroy:$t}}}function Eh(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${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 p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.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",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,p.appendChild(m)}else p.textContent=s;if(l.append(u,p),i.append(d,l),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,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 Mh=(e,r)=>{var n,o,a;let t=(a=(o=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:a.renderCard;if(t){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:s,artifactType:l,status:d},config:r.config,defaultRenderer:()=>Eh(e,r)});if(u)return u}return Eh(e,r)};var Ep=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},lo=new Ep;lo.register("PersonaArtifactCard",Mh);function I0(e){var o;let r=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),r.appendChild(t),r.appendChild(n),r}function Lh(e,r){var pe,ie,Oe,Pe;let t=(ie=(pe=e.features)==null?void 0:pe.artifacts)==null?void 0:ie.layout,o=((Oe=t==null?void 0:t.toolbarPreset)!=null?Oe:"default")==="document",a=(Pe=t==null?void 0:t.panePadding)==null?void 0:Pe.trim(),s=e.markdown?Xo(e.markdown):null,i=ya(e.sanitize),d=K=>{let _e=s?s(K):Jo(K);return i?i(_e):_e},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),H==null||H.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),o&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let A="rendered",k=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Qt({icon:"eye",label:"Rendered view"}),S=o?Qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Qt({icon:"code-2",label:"Source"}),E=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),b=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,y=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,v=t==null?void 0:t.documentToolbarCopyMenuItems,M=!!(y&&v&&v.length>0),B=null,W,R=null,H=null;if(o&&(b||y)&&!M){if(W=b?Ls({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),y){let K=Ce("chevron-down",14,"currentColor",2);K&&W.appendChild(K)}}else o&&M?(B=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),W=b?Ls({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Qt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),B.append(W,R)):o?W=Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):W=Qt({icon:"copy",label:"Copy"});let j=o?Qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"refresh-cw",label:"Refresh"}),oe=o?Qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"x",label:"Close"}),ue=()=>{var G,we,ke;let K=(G=Ge.find(ae=>ae.id===Q))!=null?G:Ge[Ge.length-1],_e=(we=K==null?void 0:K.id)!=null?we:null,$e=(K==null?void 0:K.artifactType)==="markdown"&&(ke=K.markdown)!=null?ke:"",Y=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:$e,jsonPayload:Y,id:_e}},De=async()=>{var G;let{markdown:K,jsonPayload:_e}=ue(),$e=(G=Ge.find(we=>we.id===Q))!=null?G:Ge[Ge.length-1],Y=($e==null?void 0:$e.artifactType)==="markdown"?K:$e?_e:"";try{await navigator.clipboard.writeText(Y)}catch{}};if(W.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&M){let{markdown:_e,jsonPayload:$e,id:Y}=ue();try{await K({actionId:"primary",artifactId:Y,markdown:_e,jsonPayload:$e})}catch{}return}await De()}),R&&(v!=null&&v.length)){let K=()=>{var $e;return($e=p.closest("[data-persona-root]"))!=null?$e:document.body},_e=()=>{H=ko({items:v.map($e=>({id:$e.id,label:$e.label})),onSelect:async $e=>{let{markdown:Y,jsonPayload:G,id:we}=ue(),ke=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ke?await ke({actionId:$e,artifactId:we,markdown:Y,jsonPayload:G}):$e==="markdown"||$e==="md"?await navigator.clipboard.writeText(Y):$e==="json"||$e==="source"?await navigator.clipboard.writeText(G):await navigator.clipboard.writeText(Y||G)}catch{}},anchor:B!=null?B:R,position:"bottom-right",portal:K()})};p.isConnected?_e():requestAnimationFrame(_e),R.addEventListener("click",$e=>{$e.stopPropagation(),H==null||H.toggle()})}j.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}J()}),oe.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let Xe=()=>{o&&(T.setAttribute("aria-pressed",A==="rendered"?"true":"false"),S.setAttribute("aria-pressed",A==="source"?"true":"false"))};T.addEventListener("click",()=>{A="rendered",Xe(),J()}),S.addEventListener("click",()=>{A="source",Xe(),J()});let xe=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),k.append(T,S),B?E.append(B,j,oe):E.append(W,j,oe),f.append(k,xe,E),Xe()):(f.appendChild(m),f.appendChild(C)),a&&(f.style.paddingLeft=a,f.style.paddingRight=a);let ge=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(ge.style.paddingLeft=a,ge.style.paddingRight=a,Le.style.padding=a),p.appendChild(f),p.appendChild(ge),p.appendChild(Le);let Ge=[],Q=null,Se=!1,J=()=>{var Y,G,we,ke;let K=o&&Ge.length<=1;ge.classList.toggle("persona-hidden",K),ge.replaceChildren();for(let ae of Ge){let ve=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ve.type="button",ve.textContent=ae.title||ae.id.slice(0,8),ae.id===Q&&ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),ve.addEventListener("click",()=>r.onSelect(ae.id)),ge.appendChild(ve)}Le.replaceChildren();let _e=Q&&Ge.find(ae=>ae.id===Q)||Ge[Ge.length-1];if(!_e)return;if(o){let ae=_e.artifactType==="markdown"?"MD":(Y=_e.component)!=null?Y:"Component",ye=(_e.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${ye} \xB7 ${ae}`}else m.textContent="Artifacts";if(_e.artifactType==="markdown"){if(o&&A==="source"){let ve=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ve.textContent=(G=_e.markdown)!=null?G:"",Le.appendChild(ve);return}let ae=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ae.innerHTML=d((we=_e.markdown)!=null?we:""),Le.appendChild(ae);return}let $e=_e.component?lo.get(_e.component):void 0;if($e){let ve={message:{id:_e.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let ye=$e((ke=_e.props)!=null?ke:{},ve);if(ye){Le.appendChild(ye);return}}catch{}}Le.appendChild(I0(_e))},ce=()=>{var _e;let K=Ge.length>0;if(p.classList.toggle("persona-hidden",!K),l){let $e=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,G=((_e=$e==null?void 0:$e.classList.contains("persona-artifact-narrow-host"))!=null?_e:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&G&&Se?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var _e,$e,Y;Ge=K.artifacts,Q=(Y=($e=K.selectedId)!=null?$e:(_e=K.artifacts[K.artifacts.length-1])==null?void 0:_e.id)!=null?Y:null,Ge.length>0&&(Se=!0),J(),ce()},setMobileOpen(K){Se=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ce()}}}function Sn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Ph(e,r){var a,s,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Sn(r))return;let t=(s=(a=r.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?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function R0(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function gl(e,r){var d,l,u,p,f,m,C,A,k,T;if(!Sn(r)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),R0(e),Ph(e,r);return}let t=(l=(d=r.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let o=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let a=(A=t==null?void 0:t.documentToolbarIconColor)==null?void 0:A.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(k=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:k.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ph(e,r)}var Ih=["panel","seamless"];function hl(e,r){var i,d,l,u,p,f;for(let m of Ih)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Sn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",o=Ih.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let a=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Rh(e,r){var t,n,o;return!r||!Sn(e)?!1:((o=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function H0(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function B0(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function W0(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function D0(e,r,t,n){let o=e-n-2*r-t;return Math.max(0,o)}function Hh(e,r){var s;let n=(s=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function Bh(e,r,t,n,o,a){let s=H0(o,200),i=D0(r,t,n,200);i=Math.max(s,i);let d=B0(a);return d!==null&&(i=Math.min(i,d)),W0(e,s,i)}var Wh={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"}},Mp=(e,r,t,n)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(a=>{var C,A,k;if(a.dataset.enhanced==="true")return;let s=(C=a.dataset.tvForm)!=null?C:"init";a.dataset.enhanced="true";let i=(A=Wh[s])!=null?A:Wh.init;a.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=h("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var v,M;let S=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${r.id}-${s}-${T.name}`;let E=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=T.label,S.appendChild(E);let b=(v=T.type)!=null?v:"text",y;b==="textarea"?(y=document.createElement("textarea"),y.rows=3):(y=document.createElement("input"),y.type=b),y.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",y.id=`${r.id}-${s}-${T.name}`,y.name=T.name,y.placeholder=(M=T.placeholder)!=null?M:"",T.required&&(y.required=!0),S.appendChild(y),u.appendChild(S)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(k=i.submitLabel)!=null?k:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),a.replaceChildren(d,u),u.addEventListener("submit",async T=>{var y,v;T.preventDefault();let S=(y=t.formEndpoint)!=null?y:"/form",E=new FormData(u),b={};E.forEach((M,B)=>{b[B]=M}),b.type=s,m.disabled=!0,f.textContent="Submitting\u2026";try{let M=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let B=await M.json();f.textContent=(v=B.message)!=null?v:"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await n.sendMessage(String(B.nextPrompt))}catch(M){f.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Lp=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,o;return((n=t.priority)!=null?n:0)-((o=r.priority)!=null?o:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(a=>a.id));return[...t.filter(a=>!n.has(a.id)),...r].sort((a,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=a.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Bs=new Lp;var Dh=()=>{let e=new Map,r=(o,a)=>(e.has(o)||e.set(o,new Set),e.get(o).add(a),()=>t(o,a)),t=(o,a)=>{var s;(s=e.get(o))==null||s.delete(a)};return{on:r,off:t,emit:(o,a)=>{var s;(s=e.get(o))==null||s.forEach(i=>{try{i(a)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var O0=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},F0=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let o=t;o<r.length;o+=1){let a=r[o];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return r.slice(t,o+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=O0(e),t=F0(r);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}},Pp=e=>typeof e=="string"?e:e==null?"":String(e),sa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pp(e.payload.text)},messageAndClick:(e,r)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,n=Pp(t.element);if(n&&((o=r.document)!=null&&o.querySelector)){let a=r.document.querySelector(n);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Pp(t.text)}}},Oh=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ds=e=>{let r=new Set(Oh(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Oh(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(r);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||r.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;r.add(a.message.id),n();let d={action:i,message:a.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var N0=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},_0=e=>e.map(r=>({...r,streaming:!1})),$0=e=>e.map(r=>({...r,status:"complete"})),xl=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?N0(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let o={...t,messages:t.messages?_0(t.messages):void 0,artifacts:t.artifacts?$0(t.artifacts):void 0};n.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Ba=Bl(hi(),1);function U0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function q0(e,r){if(!U0(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function yl(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let o=(0,Ba.parse)(t,Ba.STR|Ba.OBJ),a=q0(o,t);a&&(e=a)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Fh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function bl(e,r){let{config:t,message:n,onPropsUpdate:o}=r,a=lo.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:n,config:t,updateProps:i=>{o&&o(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Nh(){let e=yl();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function _h(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let r=e.content.trim();if(r.startsWith("{")||r.startsWith("["))return e.content}return null}function Cl(e){let r=_h(e);if(!r)return!1;try{let t=JSON.parse(r);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function wl(e){let r=_h(e);if(!r)return null;try{let t=JSON.parse(r);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:r}}}catch{}return null}var z0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vl(e){let{onSubmit:r,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=z0}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,m.appendChild(C);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=o,m.appendChild(A),f.appendChild(m);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let v=1;v<=5;v++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),M.title=l[v-1],M.dataset.rating=String(v),M.innerHTML=`
|
|
67
67
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
68
68
|
<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>
|
|
69
69
|
</svg>
|
|
70
|
-
`,L.addEventListener("click",()=>{p=S,T.forEach((O,H)=>{let R=H<S;O.classList.toggle("selected",R),O.setAttribute("aria-checked",H===S-1?"true":"false")})}),T.push(L),k.appendChild(L)}m.appendChild(k);let A=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),S.appendChild(A),m.appendChild(S)}let E=document.createElement("div");E.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=i,b.addEventListener("click",()=>{t==null||t(),u.remove()});let h=document.createElement("button");return h.type="button",h.className="persona-feedback-btn persona-feedback-btn-submit",h.textContent=s,h.addEventListener("click",async()=>{if(p===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}h.disabled=!0,h.textContent="Submitting...";try{let S=(A==null?void 0:A.value.trim())||void 0;await r(p,S),u.remove()}catch(S){h.disabled=!1,h.textContent=s,console.error("[CSAT Feedback] Failed to submit:",S)}}),E.appendChild(b),E.appendChild(h),m.appendChild(E),u.appendChild(m),u}function Al(e){let{onSubmit:r,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"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,w.appendChild(v);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=o,w.appendChild(k),f.appendChild(w);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=l;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=u,A.appendChild(E),A.appendChild(b);let h=document.createElement("div");h.className="persona-feedback-numbers";let S=[];for(let B=0;B<=10;B++){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 ${B} out of 10`),j.textContent=String(B),j.dataset.rating=String(B),B<=6?j.classList.add("persona-feedback-detractor"):B<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{m=B,S.forEach((oe,ue)=>{oe.classList.toggle("selected",ue===B),oe.setAttribute("aria-checked",ue===B?"true":"false")})}),S.push(j),h.appendChild(j)}T.appendChild(A),T.appendChild(h),f.appendChild(T);let L=null;if(d){let B=document.createElement("div");B.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),B.appendChild(L),f.appendChild(B)}let O=document.createElement("div");O.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{t==null||t(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=s,R.addEventListener("click",async()=>{if(m===null){h.classList.add("persona-feedback-shake"),setTimeout(()=>h.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let B=(L==null?void 0:L.value.trim())||void 0;await r(m,B),p.remove()}catch(B){R.disabled=!1,R.textContent=s,console.error("[NPS Feedback] Failed to submit:",B)}}),O.appendChild(H),O.appendChild(R),f.appendChild(O),p.appendChild(f),p}var Wa="persona-chat-history",V0=30*1e3,j0={"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 G0(e){var n,o,a;if(!e)return[];let r=[],t=Array.from((n=e.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){r.push(i);continue}let d=(o=j0[i.type])!=null?o:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&r.push(s);return r}function Sl(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function X0(e){var r,t,n,o,a,s,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(n=e.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function J0(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ip=e=>!e||typeof e!="object"?{}:{...e},$h=e=>e.map(r=>({...r,streaming:!1})),Uh=(e,r,t)=>{let n=e!=null&&e.markdown?Xo(e.markdown):null,o=ya(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var l,u,p;let s=(l=a.text)!=null?l:"",i=(u=a.message.rawContent)!=null?u:null;if(r){let m=r.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});m!==null&&(s=m.text,m.persist||(a.message.__skipPersist=!0),m.resubmit&&!a.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...a,text:s,raw:(p=i!=null?i:a.text)!=null?p:""}):n?d=n(s):d=Jo(s),o?o(d):d}};function qh(e){var i,d,l,u;let r=x("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=Ce(t,n,o,a);if(s&&r.appendChild(s),e!=null&&e.label){let p=x("span","persona-drop-overlay-label");p.textContent=e.label,r.appendChild(p)}return r}var Tl=(e,r,t)=>{var Qp,Zp,eu,tu,ru,nu,ou,au,su,iu,lu,du,cu,pu,uu,fu,mu,gu,hu,xu,yu,bu,Cu,wu,vu,Au,Su,Tu,ku,Eu,Mu,Lu,Pu,Iu,Ru,Hu,Bu,Wu,Du,Ou,Fu,Nu,_u,$u,Uu,qu,zu;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=zi(r),o=Bs.getForInstance(n.plugins);n.components&&lo.registerAll(n.components);let a=Dh(),i=n.persistState===!1?null:(Qp=n.storageAdapter)!=null?Qp:xl(),d={},l=null,u=!1,p=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:C}=g;return C&&(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 p(y)});else{let g=c!=null?c:{messages:[],metadata:{}},y=p(g);y.metadata&&(d=Ip(y.metadata)),(Zp=y.messages)!=null&&Zp.length&&(n={...n,initialMessages:y.messages}),(eu=y.artifacts)!=null&&eu.length&&(n={...n,initialArtifacts:y.artifacts,initialSelectedArtifactId:(tu=y.selectedArtifactId)!=null?tu:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=p({messages:[],metadata:{}});(ru=c.messages)!=null&&ru.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let m=()=>d,f=c=>{var y;d=(y=c({...d}))!=null?y:{},da()},w=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ws],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[sa.message,sa.messageAndClick],k=Ds({parsers:w,handlers:v,getSessionMetadata:m,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let T=(ou=(nu=n.launcher)==null?void 0:nu.enabled)!=null?ou:!0,A=(su=(au=n.launcher)==null?void 0:au.autoExpand)!=null?su:!1,E=(iu=n.autoFocusInput)!=null?iu:!1,b=A,h=T,S=(du=(lu=n.layout)==null?void 0:lu.header)==null?void 0:du.layout,L=!1,O=()=>To(n),H=()=>T||O(),R=O()?!1:T?A:!0,B=!1,j=null,oe=()=>{B=!0,j&&clearTimeout(j),j=setTimeout(()=>{B&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),B=!1)},1e4)},ue=Uh(n,k,oe),De=(pu=(cu=n.features)==null?void 0:cu.showReasoning)!=null?pu:!0,Xe=(fu=(uu=n.features)==null?void 0:uu.showToolCalls)!=null?fu:!0,xe=(gu=(mu=n.features)==null?void 0:mu.showEventStreamToggle)!=null?gu:!1,ge=(xu=(hu=n.features)==null?void 0:hu.scrollToBottom)!=null?xu:{},Ge=`${(bu=typeof n.persistState=="object"?(yu=n.persistState)==null?void 0:yu.keyPrefix:void 0)!=null?bu:"persona-"}event-stream`,Q=xe?new Hs(Ge):null,Se=(vu=(wu=(Cu=n.features)==null?void 0:Cu.eventStream)==null?void 0:wu.maxEvents)!=null?vu:2e3,J=xe?new Rs(Se,Q):null,ce=null,pe=!1,ie=null,Oe=0;Q==null||Q.open().then(()=>J==null?void 0:J.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Pe={onCopy:c=>{var g,y;a.emit("message:copy",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.id,"copy").catch(C=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(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(C=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},K=(Au=n.statusIndicator)!=null?Au:{},_e=c=>{var g,y,C,D;return c==="idle"?(g=K.idleText)!=null?g:Dr.idle:c==="connecting"?(y=K.connectingText)!=null?y:Dr.connecting:c==="connected"?(C=K.connectedText)!=null?C:Dr.connected:c==="error"?(D=K.errorText)!=null?D:Dr.error:Dr[c]};function $e(c,g,y,C){if(C==="idle"&&y.idleLink){c.textContent="";let D=document.createElement("a");D.href=y.idleLink,D.target="_blank",D.rel="noopener noreferrer",D.textContent=g,D.style.color="inherit",D.style.textDecoration="none",c.appendChild(D)}else c.textContent=g}let{wrapper:Y,panel:G,pillRoot:we}=ah(n),ke=sh(n,H()),{container:ae,body:ve,messagesWrapper:ye,suggestions:Mt,textarea:ne,sendButton:He,sendButtonWrapper:fr,composerForm:Ot,statusText:Yt,introTitle:Fr,introSubtitle:Ar,closeButton:F,iconHolder:le,headerTitle:Fe,headerSubtitle:Ke,header:Ue,footer:qe,actionsRow:nt,leftActions:Ct,rightActions:Pt}=ke,$t=ke.setSendButtonMode,N=ke.micButton,de=ke.micButtonWrapper,Ee=ke.attachmentButton,ut=ke.attachmentButtonWrapper,Ye=ke.attachmentInput,Ut=ke.attachmentPreviewsContainer;ae.classList.add("persona-relative"),ve.classList.add("persona-relative");let or=12,It=()=>{var c;return(c=ge.label)!=null?c:""},St=()=>{var c;return(c=ge.iconName)!=null?c:"arrow-down"},rt=()=>ge.enabled!==!1,it=x("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 tr=x("span","persona-flex persona-items-center"),gn=x("span","");it.append(tr,gn),ae.appendChild(it);let Rr=()=>{let g=qe.style.display==="none"?0:qe.offsetHeight;it.style.bottom=`${g+or}px`};Rr();let Tn=()=>{let c=!!It();it.setAttribute("aria-label",It()||"Jump to latest"),it.title=It(),it.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),tr.innerHTML="";let g=Ce(St(),"14px","currentColor",2);g?(tr.appendChild(g),tr.style.display=""):tr.style.display="none",gn.textContent=It(),gn.style.display=c?"":"none"};Tn();let Tt=null,hn=null,ur=o.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:n,defaultRenderer:()=>{let g=ao({config:n,showClose:H()});return na(ae,g,n),g.header},onClose:()=>Nt(!1,"user")});if(c){let g=ae.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ue=c)}}let Sr=()=>{var g,y,C,D;if(!J)return;if(pe=!0,!ce&&J&&(ce=kh({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Yr(),config:n,plugins:o})),ce&&(ve.style.display="none",(g=qe.parentNode)==null||g.insertBefore(ce.element,qe),ce.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${Kr.actionIconColor}`;let $=(D=(C=(y=n.features)==null?void 0:y.eventStream)==null?void 0:C.classNames)==null?void 0:D.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!pe)return;let $=Date.now();$-Oe>=200&&(ce==null||ce.update(),Oe=$),ie=requestAnimationFrame(c)};Oe=0,ie=requestAnimationFrame(c),Jn(),a.emit("eventStream:opened",{timestamp:Date.now()})},Yr=()=>{var c,g,y;if(pe){if(pe=!1,ce&&ce.element.remove(),ve.style.display="",xt){xt.style.boxShadow="";let C=(y=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;C&&C.split(/\s+/).forEach(D=>D&&xt.classList.remove(D))}ie!==null&&(cancelAnimationFrame(ie),ie=null),Jn(),a.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(xe){let c=(Tu=(Su=n.features)==null?void 0:Su.eventStream)==null?void 0:Tu.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=x("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=Kr.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let y=Ce("activity","18px","currentColor",1.5);y&&xt.appendChild(y);let C=ke.clearChatButtonWrapper,D=ke.closeButtonWrapper,$=C||D;$&&$.parentNode===Ue?Ue.insertBefore(xt,$):Ue.appendChild(xt),xt.addEventListener("click",()=>{pe?Yr():Sr()})}let kn=c=>{var C,D,$;let g=n.attachments;if(!(g!=null&&g.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=x("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=x("input");U.type="file",U.accept=((C=g.allowedTypes)!=null?C:oo).join(","),U.multiple=((D=g.maxFiles)!=null?D:4)>1,U.style.display="none",U.setAttribute("aria-label",($=g.buttonTooltipText)!=null?$:"Attach files"),c.appendChild(U)}},nn=o.find(c=>c.renderComposer);if(nn!=null&&nn.renderComposer){let c=n.composer,g=nn.renderComposer({config:n,defaultRenderer:()=>ka({config:n}).footer,onSubmit:y=>{var U;if(!q||q.isStreaming())return;let C=y.trim(),D=(U=Tt==null?void 0:Tt.hasAttachments())!=null?U:!1;if(!C&&!D)return;ja();let $;D&&($=[],$.push(...Tt.getContentParts()),C&&$.push(gs(C))),q.sendMessage(C,{contentParts:$}),D&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.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:((ku=n.voiceRecognition)==null?void 0:ku.enabled)===!0?()=>{hn==null||hn()}:void 0});g&&(qe.replaceWith(g),qe=g)}let Tr=c=>{let g=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),C=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),$=c.querySelector("[data-persona-composer-status]");g&&(Ot=g),y&&(ne=y),C&&(He=C),D&&(N=D,de=D.parentElement),$&&(Yt=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Mt=U);let X=c.querySelector(".persona-attachment-button");X&&(Ee=X,ut=X.parentElement),Ye=c.querySelector('input[type="file"]'),Ut=c.querySelector(".persona-attachment-previews");let _=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(nt=_)};kn(qe),Tr(qe);let kr=(Iu=(Eu=n.layout)==null?void 0:Eu.contentMaxWidth)!=null?Iu:O()?(Pu=(Lu=(Mu=n.launcher)==null?void 0:Mu.composerBar)==null?void 0:Lu.contentMaxWidth)!=null?Pu:"720px":void 0;if(kr&&(ye.style.maxWidth=kr,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%"),kr&&Ot&&!O()&&(Ot.style.maxWidth=kr,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),kr&&Mt&&!O()&&(Mt.style.maxWidth=kr,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),kr&&Ut&&!O()&&(Ut.style.maxWidth=kr,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(Ru=n.attachments)!=null&&Ru.enabled&&Ye&&Ut){Tt=ta.fromConfig(n.attachments),Tt.setPreviewsContainer(Ut),Ye.addEventListener("change",y=>{let C=y.target;Tt==null||Tt.handleFileSelect(C.files),C.value=""});let c=n.attachments.dropOverlay,g=qh(c);ae.appendChild(g)}(()=>{var C,D;let c=(D=(C=n.layout)==null?void 0:C.slots)!=null?D:{},g=$=>{switch($){case"body-top":return ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ye;case"footer-top":return Mt;case"composer":return Ot;case"footer-bottom":return Yt;default:return null}},y=($,U)=>{var X;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Ue.insertBefore(U,Ue.firstChild);else if($==="header-right")Ue.appendChild(U);else{let _=Ue.querySelector(".persona-flex-col");_?(X=_.parentNode)==null||X.insertBefore(U,_.nextSibling):Ue.appendChild(U)}break;case"body-top":{let _=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(U):ve.insertBefore(U,ve.firstChild);break}case"body-bottom":ve.appendChild(U);break;case"footer-top":Mt.replaceWith(U);break;case"footer-bottom":Yt.replaceWith(U);break;default:break}};for(let[$,U]of Object.entries(c))if(U)try{let X=U({config:n,defaultContent:()=>g($)});X&&y($,X)}catch(X){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,X)}})();let En=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let C=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=y.getAttribute("data-bubble-type");$==="reasoning"?(Ma.has(D)?Ma.delete(D):Ma.add(D),ch(D,C)):$==="tool"&&(La.has(D)?La.delete(D):La.add(D),ph(D,C,n)),ln.delete(D)};ye.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),En(c))}),ye.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),En(c))});let xn=new Map;ye.addEventListener("click",c=>{var U;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.closest("[data-actions-for]");if(!C)return;let D=C.getAttribute("data-actions-for");if(!D)return;let $=y.getAttribute("data-action");if($==="copy"){let _=q.getMessages().find(Te=>Te.id===D);if(_&&Pe.onCopy){let Te=_.content||"";navigator.clipboard.writeText(Te).then(()=>{y.classList.add("persona-message-action-success");let me=Ce("check",14,"currentColor",2);me&&(y.innerHTML="",y.appendChild(me)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let re=Ce("copy",14,"currentColor",2);re&&(y.innerHTML="",y.appendChild(re))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),Pe.onCopy(_)}}else if($==="upvote"||$==="downvote"){let _=((U=xn.get(D))!=null?U:null)===$,Te=$==="upvote"?"thumbs-up":"thumbs-down";if(_){xn.delete(D),y.classList.remove("persona-message-action-active");let me=Ce(Te,14,"currentColor",2);me&&(y.innerHTML="",y.appendChild(me))}else{let me=$==="upvote"?"downvote":"upvote",re=C.querySelector(`[data-action="${me}"]`);if(re){re.classList.remove("persona-message-action-active");let tt=Ce(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(re.innerHTML="",re.appendChild(tt))}xn.set(D,$),y.classList.add("persona-message-action-active");let be=Ce(Te,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(be)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ve=q.getMessages().find(lt=>lt.id===D);Ve&&Pe.onFeedback&&Pe.onFeedback({type:$,messageId:Ve.id,message:Ve})}}}),ye.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.closest(".persona-approval-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=y.getAttribute("data-approval-action");if(!$)return;let U=$==="approve"?"approved":"denied",_=q.getMessages().find(me=>me.id===D);if(!(_!=null&&_.approval))return;let Te=C.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),q.resolveApproval(_.approval,U)});let wt=null,Ie=null,M={artifacts:[],selectedId:null},Z=!1,se={current:null};ye.addEventListener("click",c=>{var re,be,Me,Ve,lt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.getAttribute("data-download-artifact");if(!C||((Me=(be=(re=n.features)==null?void 0:re.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Me.call(be,{type:"download",artifactId:C}))===!0)return;let $=q.getArtifactById(C),U=$==null?void 0:$.markdown,X=($==null?void 0:$.title)||"artifact";if(!U){let tt=y.closest("[data-open-artifact]"),ft=tt==null?void 0:tt.closest("[data-message-id]"),mt=ft==null?void 0:ft.getAttribute("data-message-id");if(mt){let Be=q.getMessages().find(Je=>Je.id===mt);if(Be!=null&&Be.rawContent)try{let Je=JSON.parse(Be.rawContent);U=(Ve=Je==null?void 0:Je.props)==null?void 0:Ve.markdown,X=((lt=Je==null?void 0:Je.props)==null?void 0:lt.title)||X}catch{}}}if(!U)return;let _=new Blob([U],{type:"text/markdown"}),Te=URL.createObjectURL(_),me=document.createElement("a");me.href=Te,me.download=`${X}.md`,me.click(),URL.revokeObjectURL(Te)}),ye.addEventListener("click",c=>{var $,U,X;let y=c.target.closest("[data-open-artifact]");if(!y)return;let C=y.getAttribute("data-open-artifact");!C||((X=(U=($=n.features)==null?void 0:$.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:X.call(U,{type:"open",artifactId:C}))===!0||(c.preventDefault(),c.stopPropagation(),Z=!1,q.selectArtifact(C),on())}),ye.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let kt=ke.composerOverlay,qt=(c,g,y)=>{var X,_,Te,me;let C=g.trim();if(!C||!se.current)return;let D=(X=c.getAttribute("data-tool-call-id"))!=null?X:"",$=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:D,answer:C,answers:y.structured,values:(_=y.values)!=null?_:y.source==="multi"?C.split(", "):[C],isFreeText:$,source:y.source},bubbles:!0,composed:!0})),Lo(kt,D);let U=se.current.getMessages().find(re=>{var be;return((be=re.toolCall)==null?void 0:be.id)===D});(Te=U==null?void 0:U.agentMetadata)!=null&&Te.awaitingLocalTool?se.current.resolveAskUserQuestion(U,(me=y.structured)!=null?me:C):se.current.sendMessage(C)},Bt=c=>{var D;let g=se.current;if(!g)return;let y=(D=c.getAttribute("data-tool-call-id"))!=null?D:"",C=g.getMessages().find($=>{var U;return((U=$.toolCall)==null?void 0:U.id)===y});C&&g.persistAskUserQuestionProgress(C,{answers:fl(c,C),currentIndex:An(c)})},ar=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),xr=c=>{var D,$,U;if((($=(D=n.features)==null?void 0:D.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=An(c),y=Ia(c);if(g>=y-1)return;let C=(U=se.current)==null?void 0:U.getMessages().find(X=>{var _;return((_=X.toolCall)==null?void 0:_.id)===c.getAttribute("data-tool-call-id")});C&&(ml(c,C,n,g+1),Bt(c))};kt.addEventListener("click",c=>{var $,U,X,_,Te,me,re,be,Me,Ve,lt,tt,ft,mt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let C=y.closest("[data-persona-ask-sheet-for]");if(!C)return;let D=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),D==="dismiss"){let We=($=C.getAttribute("data-tool-call-id"))!=null?$:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Lo(kt,We);let Be=(U=se.current)==null?void 0:U.getMessages().find(Je=>{var W;return((W=Je.toolCall)==null?void 0:W.id)===We});(X=Be==null?void 0:Be.agentMetadata)!=null&&X.awaitingLocalTool&&((_=se.current)==null||_.markAskUserQuestionResolved(Be),(Te=se.current)==null||Te.resolveAskUserQuestion(Be,"(dismissed)"));return}if(D==="pick"){let We=y.getAttribute("data-option-label");if(!We)return;let Be=C.getAttribute("data-multi-select")==="true",Je=Mo(C);if(Je&&Be){let W=aa(C)[An(C)],Re=new Set(Array.isArray(W)?W:[]);Re.has(We)?Re.delete(We):Re.add(We),Po(C,Array.from(Re)),Bt(C);return}if(Je){Po(C,We),Bt(C),xr(C);return}if(Be){let W=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",W?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!W);let Re=C.querySelector('[data-ask-user-action="submit-multi"]');Re&&(Re.disabled=Sp(C).length===0);return}qt(C,We,{source:"pick",values:[We]});return}if(D==="submit-multi"){let We=Sp(C);if(We.length===0)return;qt(C,We.join(", "),{source:"multi",values:We});return}if(D==="open-free-text"){let We=C.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Be=We.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus()}return}if(D==="focus-free-text"){let We=C.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(D==="submit-free-text"){let We=C.querySelector('[data-ask-free-text-input="true"]'),Be=(me=We==null?void 0:We.value)!=null?me:"";if(!Be.trim())return;if(Mo(C)){Po(C,Be.trim()),Bt(C),xr(C);return}qt(C,Be,{source:"free-text"});return}if(D==="next"||D==="back"){if(!se.current)return;let We=(re=C.getAttribute("data-tool-call-id"))!=null?re:"",Be=se.current.getMessages().find(Qe=>{var Ae;return((Ae=Qe.toolCall)==null?void 0:Ae.id)===We});if(!Be)return;let Je=C.querySelector('[data-ask-free-text-input="true"]'),W=(Me=(be=Je==null?void 0:Je.value)==null?void 0:be.trim())!=null?Me:"";if(W){let Qe=aa(C)[An(C)];(typeof Qe!="string"||Qe!==W)&&Po(C,W)}let Re=D==="next"?1:-1,Ne=An(C)+Re;ml(C,Be,n,Ne),Bt(C);return}if(D==="submit-all"){if(!se.current)return;let We=(Ve=C.getAttribute("data-tool-call-id"))!=null?Ve:"",Be=se.current.getMessages().find(Qe=>{var Ae;return((Ae=Qe.toolCall)==null?void 0:Ae.id)===We});if(!Be)return;let Je=C.querySelector('[data-ask-free-text-input="true"]'),W=(tt=(lt=Je==null?void 0:Je.value)==null?void 0:lt.trim())!=null?tt:"";W&&Po(C,W);let Re=fl(C,Be);se.current.persistAskUserQuestionProgress(Be,{answers:Re,currentIndex:An(C)});let Ne=ar(Re);qt(C,Ne||"(submitted)",{source:"submit-all",structured:Re});return}if(D==="skip"){if(!se.current)return;let We=(ft=C.getAttribute("data-tool-call-id"))!=null?ft:"",Be=se.current.getMessages().find(Ae=>{var Dt;return((Dt=Ae.toolCall)==null?void 0:Dt.id)===We});if(!Be)return;let Je=Mo(C),W=An(C),Re=Ia(C),Ne=W>=Re-1;if(!Je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Lo(kt,We),(mt=Be.agentMetadata)!=null&&mt.awaitingLocalTool&&(se.current.markAskUserQuestionResolved(Be),se.current.resolveAskUserQuestion(Be,"(dismissed)"));return}Po(C,"");let Qe=C.querySelector('[data-ask-free-text-input="true"]');if(Qe&&(Qe.value=""),Ne){let Ae=fl(C,Be),Dt=ar(Ae);qt(C,Dt||"(skipped)",{source:"submit-all",structured:Ae});return}ml(C,Be,n,W+1),Bt(C);return}}),kt.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 C=y.closest("[data-persona-ask-sheet-for]");if(!C)return;c.preventDefault();let D=y.value;if(D.trim()){if(Mo(C)){Po(C,D.trim()),Bt(C),xr(C);return}qt(C,D,{source:"free-text"})}});let Nr=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=kt.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let C=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"]')[C-1];$&&(c.preventDefault(),$.click())};document.addEventListener("keydown",Nr);let Er=null,ot=null,wr=null,_r=null,po=()=>{};function jn(){_r==null||_r(),_r=null}let uo=()=>{var U;if(!Er||!ot)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){ot.style.removeProperty("position"),ot.style.removeProperty("left"),ot.style.removeProperty("top"),ot.style.removeProperty("bottom"),ot.style.removeProperty("width"),ot.style.removeProperty("z-index");return}let C=Er.firstElementChild;if(!C||C===ot)return;let D=10;ot.style.position="absolute",ot.style.top="0",ot.style.bottom="0",ot.style.width=`${D}px`,ot.style.zIndex="5";let $=C.offsetWidth-D/2;ot.style.left=`${Math.max(0,$)}px`},Fn=()=>{},on=()=>{var y,C,D,$,U;if(!wt||!Sn(n))return;gl(e,n),hl(e,n),Fn();let c=($=(D=(C=(y=n.features)==null?void 0:y.artifacts)==null?void 0:C.layout)==null?void 0:D.narrowHostMaxWidth)!=null?$:520,g=G.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),wt.update(M),Z?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(U=wt.backdrop)==null||U.classList.add("persona-hidden")):M.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),po()};if(Sn(n)){G.style.position="relative";let c=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ae),wt=Lh(n,{onSelect:y=>{var C;return(C=se.current)==null?void 0:C.selectArtifact(y)},onDismiss:()=>{Z=!0,on()}}),wt.element.classList.add("persona-hidden"),Er=g,g.appendChild(c),g.appendChild(wt.element),wt.backdrop&&G.appendChild(wt.backdrop),G.appendChild(g),po=()=>{var C,D,$,U;if(!Er||!wt)return;if(!((($=(D=(C=n.features)==null?void 0:C.artifacts)==null?void 0:D.layout)==null?void 0:$.resizable)===!0)){wr==null||wr(),wr=null,jn(),ot&&(ot.remove(),ot=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!ot){let X=x("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");X.setAttribute("role","separator"),X.setAttribute("aria-orientation","vertical"),X.setAttribute("aria-label","Resize artifacts panel"),X.tabIndex=0;let _=e.ownerDocument,Te=(U=_.defaultView)!=null?U:window,me=re=>{var ft,mt;if(!wt||re.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;re.preventDefault(),jn();let be=re.clientX,Me=wt.element.getBoundingClientRect().width,Ve=(mt=(ft=n.features)==null?void 0:ft.artifacts)==null?void 0:mt.layout,lt=We=>{let Be=Er.getBoundingClientRect().width,Je=e.classList.contains("persona-artifact-appearance-seamless"),W=Je?0:Hh(Er,Te),Re=Je?0:X.getBoundingClientRect().width||6,Ne=Me-(We.clientX-be),Qe=Bh(Ne,Be,W,Re,Ve==null?void 0:Ve.resizableMinWidth,Ve==null?void 0:Ve.resizableMaxWidth);wt.element.style.width=`${Qe}px`,wt.element.style.maxWidth="none",uo()},tt=()=>{_.removeEventListener("pointermove",lt),_.removeEventListener("pointerup",tt),_.removeEventListener("pointercancel",tt),_r=null;try{X.releasePointerCapture(re.pointerId)}catch{}};_r=tt,_.addEventListener("pointermove",lt),_.addEventListener("pointerup",tt),_.addEventListener("pointercancel",tt);try{X.setPointerCapture(re.pointerId)}catch{}};X.addEventListener("pointerdown",me),ot=X,Er.insertBefore(X,wt.element),wr=()=>{X.removeEventListener("pointerdown",me)}}if(ot){let X=M.artifacts.length>0&&!Z;ot.classList.toggle("persona-hidden",!X),uo()}},Fn=()=>{var Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be,Je,W;if(!T||!wt||((me=(Te=n.launcher)==null?void 0:Te.sidebarMode)!=null?me:!1)||hr(n)&&vn(n).reveal==="emerge")return;let C=(re=e.ownerDocument.defaultView)!=null?re:window,D=(Me=(be=n.launcher)==null?void 0:be.mobileFullscreen)!=null?Me:!0,$=(lt=(Ve=n.launcher)==null?void 0:Ve.mobileBreakpoint)!=null?lt:640;if(D&&C.innerWidth<=$||!Rh(n,T))return;let U=(mt=(ft=(tt=n.launcher)==null?void 0:tt.width)!=null?ft:n.launcherWidth)!=null?mt:mn,X=(W=(Je=(Be=(We=n.features)==null?void 0:We.artifacts)==null?void 0:Be.layout)==null?void 0:Je.expandedPanelWidth)!=null?W:"min(720px, calc(100vw - 24px))";M.artifacts.length>0&&!Z?(G.style.width=X,G.style.maxWidth=X):(G.style.width=U,G.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Ie=new ResizeObserver(()=>{on()}),Ie.observe(G))}else G.appendChild(ae),O()&&we&&(ke.peekBanner&&we.appendChild(ke.peekBanner),we.appendChild(qe));e.appendChild(Y),we&&e.appendChild(we);let Mn=()=>{var Qe,Ae,Dt,pt,cr,Lr,Ft,Ur,Pr,st,gt,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo,Et,Zr,Zn,zr,en,zt,Zt;if(O()){G.style.width="100%",G.style.maxWidth="100%";let Vt=(Ae=(Qe=n.launcher)==null?void 0:Qe.composerBar)!=null?Ae:{},nr=Y.dataset.state==="expanded",tn=(Dt=Vt.expandedSize)!=null?Dt:"anchored";if(!(nr&&tn!=="fullscreen")){ae.style.background="",ae.style.border="",ae.style.borderRadius="",ae.style.overflow="",ae.style.boxShadow="";return}let gr=(cr=(pt=n.theme)==null?void 0:pt.components)==null?void 0:cr.panel,$n=Sa(n),eo=($o,oi)=>{var Ya;return $o==null||$o===""?oi:(Ya=va($n,$o))!=null?Ya:$o},ti="1px solid var(--persona-border)",ri="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ni="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ae.style.background="var(--persona-surface, #ffffff)",ae.style.border=eo(gr==null?void 0:gr.border,ti),ae.style.borderRadius=eo(gr==null?void 0:gr.borderRadius,ni),ae.style.boxShadow=eo(gr==null?void 0:gr.shadow,ri),ae.style.overflow="hidden";return}let c=hr(n),g=(Ft=(Lr=n.launcher)==null?void 0:Lr.sidebarMode)!=null?Ft:!1,y=c||g||((Pr=(Ur=n.launcher)==null?void 0:Ur.fullHeight)!=null?Pr:!1),C=((st=n.launcher)==null?void 0:st.enabled)===!1,D=(qr=(gt=n.theme)==null?void 0:gt.components)==null?void 0:qr.panel,$=Sa(n),U=(Vt,nr)=>{var tn;return Vt==null||Vt===""?nr:(tn=va($,Vt))!=null?tn:Vt},X=(Br=e.ownerDocument.defaultView)!=null?Br:window,_=(Fo=(Oo=n.launcher)==null?void 0:Oo.mobileFullscreen)!=null?Fo:!0,Te=(ma=(No=n.launcher)==null?void 0:No.mobileBreakpoint)!=null?ma:640,me=X.innerWidth<=Te,re=_&&me&&T,be=(rr=(ga=n.launcher)==null?void 0:ga.position)!=null?rr:"bottom-left",Me=be==="bottom-left"||be==="top-left",Ve=(wo=(_o=n.launcher)==null?void 0:_o.zIndex)!=null?wo:Or,lt=g||re?"none":"1px solid var(--persona-border)",tt=re?"none":g?Me?"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&&!re&&(tt="none",lt="none");let ft=g||re?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",mt=U(D==null?void 0:D.border,lt),We=U(D==null?void 0:D.shadow,tt),Be=U(D==null?void 0:D.borderRadius,ft),Je=ve.scrollTop;e.style.cssText="",Y.style.cssText="",G.style.cssText="",ae.style.cssText="",ve.style.cssText="",qe.style.cssText="";let W=()=>{var nr;if(Je<=0)return;((nr=ve.ownerDocument.defaultView)!=null?nr:window).requestAnimationFrame(()=>{if(ve.scrollTop===Je)return;let tn=ve.scrollHeight-ve.clientHeight;tn<=0||(ve.scrollTop=Math.min(Je,tn))})};if(re){Y.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Y.style.cssText=`
|
|
70
|
+
`,M.addEventListener("click",()=>{p=v,T.forEach((B,W)=>{let R=W<v;B.classList.toggle("selected",R),B.setAttribute("aria-checked",W===v-1?"true":"false")})}),T.push(M),k.appendChild(M)}f.appendChild(k);let S=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=a,S.rows=3,S.setAttribute("aria-label","Additional comments"),v.appendChild(S),f.appendChild(v)}let E=document.createElement("div");E.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=i,b.addEventListener("click",()=>{t==null||t(),u.remove()});let y=document.createElement("button");return y.type="button",y.className="persona-feedback-btn persona-feedback-btn-submit",y.textContent=s,y.addEventListener("click",async()=>{if(p===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}y.disabled=!0,y.textContent="Submitting...";try{let v=(S==null?void 0:S.value.trim())||void 0;await r(p,v),u.remove()}catch(v){y.disabled=!1,y.textContent=s,console.error("[CSAT Feedback] Failed to submit:",v)}}),E.appendChild(b),E.appendChild(y),f.appendChild(E),u.appendChild(f),u}function Al(e){let{onSubmit:r,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"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,C.appendChild(A);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=o,C.appendChild(k),m.appendChild(C);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=l;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=u,S.appendChild(E),S.appendChild(b);let y=document.createElement("div");y.className="persona-feedback-numbers";let v=[];for(let H=0;H<=10;H++){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 ${H} out of 10`),j.textContent=String(H),j.dataset.rating=String(H),H<=6?j.classList.add("persona-feedback-detractor"):H<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{f=H,v.forEach((oe,ue)=>{oe.classList.toggle("selected",ue===H),oe.setAttribute("aria-checked",ue===H?"true":"false")})}),v.push(j),y.appendChild(j)}T.appendChild(S),T.appendChild(y),m.appendChild(T);let M=null;if(d){let H=document.createElement("div");H.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"),H.appendChild(M),m.appendChild(H)}let B=document.createElement("div");B.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=i,W.addEventListener("click",()=>{t==null||t(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=s,R.addEventListener("click",async()=>{if(f===null){y.classList.add("persona-feedback-shake"),setTimeout(()=>y.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let H=(M==null?void 0:M.value.trim())||void 0;await r(f,H),p.remove()}catch(H){R.disabled=!1,R.textContent=s,console.error("[NPS Feedback] Failed to submit:",H)}}),B.appendChild(W),B.appendChild(R),m.appendChild(B),p.appendChild(m),p}var Wa="persona-chat-history",V0=30*1e3,j0={"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 G0(e){var n,o,a;if(!e)return[];let r=[],t=Array.from((n=e.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){r.push(i);continue}let d=(o=j0[i.type])!=null?o:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&r.push(s);return r}function Sl(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function X0(e){var r,t,n,o,a,s,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(n=e.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function J0(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ip=e=>!e||typeof e!="object"?{}:{...e},$h=e=>e.map(r=>({...r,streaming:!1})),Uh=(e,r,t)=>{let n=e!=null&&e.markdown?Xo(e.markdown):null,o=ya(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var l,u,p;let s=(l=a.text)!=null?l:"",i=(u=a.message.rawContent)!=null?u:null;if(r){let f=r.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});f!==null&&(s=f.text,f.persist||(a.message.__skipPersist=!0),f.resubmit&&!a.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...a,text:s,raw:(p=i!=null?i:a.text)!=null?p:""}):n?d=n(s):d=Jo(s),o?o(d):d}};function qh(e){var i,d,l,u;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=Ce(t,n,o,a);if(s&&r.appendChild(s),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,r.appendChild(p)}return r}var Tl=(e,r,t)=>{var Qp,Zp,eu,tu,ru,nu,ou,au,su,iu,lu,du,cu,pu,uu,fu,mu,gu,hu,xu,yu,bu,Cu,wu,vu,Au,Su,Tu,ku,Eu,Mu,Lu,Pu,Iu,Ru,Hu,Bu,Wu,Du,Ou,Fu,Nu,_u,$u,Uu,qu,zu;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=zi(r),o=Bs.getForInstance(n.plugins);n.components&&lo.registerAll(n.components);let a=Dh(),i=n.persistState===!1?null:(Qp=n.storageAdapter)!=null?Qp:xl(),d={},l=null,u=!1,p=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:x,open:w}=g;return w&&(u=!0),x}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 x=g!=null?g:{messages:[],metadata:{}};return p(x)});else{let g=c!=null?c:{messages:[],metadata:{}},x=p(g);x.metadata&&(d=Ip(x.metadata)),(Zp=x.messages)!=null&&Zp.length&&(n={...n,initialMessages:x.messages}),(eu=x.artifacts)!=null&&eu.length&&(n={...n,initialArtifacts:x.artifacts,initialSelectedArtifactId:(tu=x.selectedArtifactId)!=null?tu:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=p({messages:[],metadata:{}});(ru=c.messages)!=null&&ru.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var x;d=(x=c({...d}))!=null?x:{},da()},C=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ws],A=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[sa.message,sa.messageAndClick],k=Ds({parsers:C,handlers:A,getSessionMetadata:f,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let T=(ou=(nu=n.launcher)==null?void 0:nu.enabled)!=null?ou:!0,S=(su=(au=n.launcher)==null?void 0:au.autoExpand)!=null?su:!1,E=(iu=n.autoFocusInput)!=null?iu:!1,b=S,y=T,v=(du=(lu=n.layout)==null?void 0:lu.header)==null?void 0:du.layout,M=!1,B=()=>To(n),W=()=>T||B(),R=B()?!1:T?S:!0,H=!1,j=null,oe=()=>{H=!0,j&&clearTimeout(j),j=setTimeout(()=>{H&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),H=!1)},1e4)},ue=Uh(n,k,oe),De=(pu=(cu=n.features)==null?void 0:cu.showReasoning)!=null?pu:!0,Xe=(fu=(uu=n.features)==null?void 0:uu.showToolCalls)!=null?fu:!0,xe=(gu=(mu=n.features)==null?void 0:mu.showEventStreamToggle)!=null?gu:!1,ge=(xu=(hu=n.features)==null?void 0:hu.scrollToBottom)!=null?xu:{},Ge=`${(bu=typeof n.persistState=="object"?(yu=n.persistState)==null?void 0:yu.keyPrefix:void 0)!=null?bu:"persona-"}event-stream`,Q=xe?new Hs(Ge):null,Se=(vu=(wu=(Cu=n.features)==null?void 0:Cu.eventStream)==null?void 0:wu.maxEvents)!=null?vu:2e3,J=xe?new Rs(Se,Q):null,ce=null,pe=!1,ie=null,Oe=0;Q==null||Q.open().then(()=>J==null?void 0:J.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Pe={onCopy:c=>{var g,x;a.emit("message:copy",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.id,"copy").catch(w=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",w)}),(x=(g=n.messageActions)==null?void 0:g.onCopy)==null||x.call(g,c)},onFeedback:c=>{var g,x;a.emit("message:feedback",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.messageId,c.type).catch(w=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",w)}),(x=(g=n.messageActions)==null?void 0:g.onFeedback)==null||x.call(g,c)}},K=(Au=n.statusIndicator)!=null?Au:{},_e=c=>{var g,x,w,O;return c==="idle"?(g=K.idleText)!=null?g:Dr.idle:c==="connecting"?(x=K.connectingText)!=null?x:Dr.connecting:c==="connected"?(w=K.connectedText)!=null?w:Dr.connected:c==="error"?(O=K.errorText)!=null?O:Dr.error:Dr[c]};function $e(c,g,x,w){if(w==="idle"&&x.idleLink){c.textContent="";let O=document.createElement("a");O.href=x.idleLink,O.target="_blank",O.rel="noopener noreferrer",O.textContent=g,O.style.color="inherit",O.style.textDecoration="none",c.appendChild(O)}else c.textContent=g}let{wrapper:Y,panel:G,pillRoot:we}=ah(n),ke=sh(n,W()),{container:ae,body:ve,messagesWrapper:ye,suggestions:Mt,textarea:ne,sendButton:He,sendButtonWrapper:fr,composerForm:Ot,statusText:Yt,introTitle:Fr,introSubtitle:Ar,closeButton:F,iconHolder:le,headerTitle:Fe,headerSubtitle:Ke,header:Ue,footer:qe,actionsRow:nt,leftActions:Ct,rightActions:Pt}=ke,$t=ke.setSendButtonMode,N=ke.micButton,de=ke.micButtonWrapper,Ee=ke.attachmentButton,ut=ke.attachmentButtonWrapper,Ye=ke.attachmentInput,Ut=ke.attachmentPreviewsContainer;ae.classList.add("persona-relative"),ve.classList.add("persona-relative");let or=12,It=()=>{var c;return(c=ge.label)!=null?c:""},St=()=>{var c;return(c=ge.iconName)!=null?c:"arrow-down"},rt=()=>ge.enabled!==!1,it=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");it.type="button",it.style.display="none",it.setAttribute("data-persona-scroll-to-bottom","true");let tr=h("span","persona-flex persona-items-center"),gn=h("span","");it.append(tr,gn),ae.appendChild(it);let Rr=()=>{let g=qe.style.display==="none"?0:qe.offsetHeight;it.style.bottom=`${g+or}px`};Rr();let Tn=()=>{let c=!!It();it.setAttribute("aria-label",It()||"Jump to latest"),it.title=It(),it.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),tr.innerHTML="";let g=Ce(St(),"14px","currentColor",2);g?(tr.appendChild(g),tr.style.display=""):tr.style.display="none",gn.textContent=It(),gn.style.display=c?"":"none"};Tn();let Tt=null,hn=null,ur=o.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:n,defaultRenderer:()=>{let g=ao({config:n,showClose:W()});return na(ae,g,n),g.header},onClose:()=>Nt(!1,"user")});if(c){let g=ae.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ue=c)}}let Sr=()=>{var g,x,w,O;if(!J)return;if(pe=!0,!ce&&J&&(ce=kh({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Yr(),config:n,plugins:o})),ce&&(ve.style.display="none",(g=qe.parentNode)==null||g.insertBefore(ce.element,qe),ce.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${Kr.actionIconColor}`;let $=(O=(w=(x=n.features)==null?void 0:x.eventStream)==null?void 0:w.classNames)==null?void 0:O.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!pe)return;let $=Date.now();$-Oe>=200&&(ce==null||ce.update(),Oe=$),ie=requestAnimationFrame(c)};Oe=0,ie=requestAnimationFrame(c),Jn(),a.emit("eventStream:opened",{timestamp:Date.now()})},Yr=()=>{var c,g,x;if(pe){if(pe=!1,ce&&ce.element.remove(),ve.style.display="",xt){xt.style.boxShadow="";let w=(x=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:x.toggleButtonActive;w&&w.split(/\s+/).forEach(O=>O&&xt.classList.remove(O))}ie!==null&&(cancelAnimationFrame(ie),ie=null),Jn(),a.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(xe){let c=(Tu=(Su=n.features)==null?void 0:Su.eventStream)==null?void 0:Tu.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=h("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=Kr.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let x=Ce("activity","18px","currentColor",1.5);x&&xt.appendChild(x);let w=ke.clearChatButtonWrapper,O=ke.closeButtonWrapper,$=w||O;$&&$.parentNode===Ue?Ue.insertBefore(xt,$):Ue.appendChild(xt),xt.addEventListener("click",()=>{pe?Yr():Sr()})}let kn=c=>{var w,O,$;let g=n.attachments;if(!(g!=null&&g.enabled))return;let x=c.querySelector(".persona-attachment-previews");if(!x){x=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),x.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(x,U):c.insertBefore(x,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=h("input");U.type="file",U.accept=((w=g.allowedTypes)!=null?w:oo).join(","),U.multiple=((O=g.maxFiles)!=null?O:4)>1,U.style.display="none",U.setAttribute("aria-label",($=g.buttonTooltipText)!=null?$:"Attach files"),c.appendChild(U)}},nn=o.find(c=>c.renderComposer);if(nn!=null&&nn.renderComposer){let c=n.composer,g=nn.renderComposer({config:n,defaultRenderer:()=>ka({config:n}).footer,onSubmit:x=>{var U;if(!q||q.isStreaming())return;let w=x.trim(),O=(U=Tt==null?void 0:Tt.hasAttachments())!=null?U:!1;if(!w&&!O)return;ja();let $;O&&($=[],$.push(...Tt.getContentParts()),w&&$.push(gs(w))),q.sendMessage(w,{contentParts:$}),O&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:x=>{n.composer={...n.composer,selectedModelId:x},n.agent&&(n.agent={...n.agent,model:x})},onVoiceToggle:((ku=n.voiceRecognition)==null?void 0:ku.enabled)===!0?()=>{hn==null||hn()}:void 0});g&&(qe.replaceWith(g),qe=g)}let Tr=c=>{let g=c.querySelector("[data-persona-composer-form]"),x=c.querySelector("[data-persona-composer-input]"),w=c.querySelector("[data-persona-composer-submit]"),O=c.querySelector("[data-persona-composer-mic]"),$=c.querySelector("[data-persona-composer-status]");g&&(Ot=g),x&&(ne=x),w&&(He=w),O&&(N=O,de=O.parentElement),$&&(Yt=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Mt=U);let X=c.querySelector(".persona-attachment-button");X&&(Ee=X,ut=X.parentElement),Ye=c.querySelector('input[type="file"]'),Ut=c.querySelector(".persona-attachment-previews");let _=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(nt=_)};kn(qe),Tr(qe);let kr=(Iu=(Eu=n.layout)==null?void 0:Eu.contentMaxWidth)!=null?Iu:B()?(Pu=(Lu=(Mu=n.launcher)==null?void 0:Mu.composerBar)==null?void 0:Lu.contentMaxWidth)!=null?Pu:"720px":void 0;if(kr&&(ye.style.maxWidth=kr,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%"),kr&&Ot&&!B()&&(Ot.style.maxWidth=kr,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),kr&&Mt&&!B()&&(Mt.style.maxWidth=kr,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),kr&&Ut&&!B()&&(Ut.style.maxWidth=kr,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(Ru=n.attachments)!=null&&Ru.enabled&&Ye&&Ut){Tt=ta.fromConfig(n.attachments),Tt.setPreviewsContainer(Ut),Ye.addEventListener("change",x=>{let w=x.target;Tt==null||Tt.handleFileSelect(w.files),w.value=""});let c=n.attachments.dropOverlay,g=qh(c);ae.appendChild(g)}(()=>{var w,O;let c=(O=(w=n.layout)==null?void 0:w.slots)!=null?O:{},g=$=>{switch($){case"body-top":return ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ye;case"footer-top":return Mt;case"composer":return Ot;case"footer-bottom":return Yt;default:return null}},x=($,U)=>{var X;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Ue.insertBefore(U,Ue.firstChild);else if($==="header-right")Ue.appendChild(U);else{let _=Ue.querySelector(".persona-flex-col");_?(X=_.parentNode)==null||X.insertBefore(U,_.nextSibling):Ue.appendChild(U)}break;case"body-top":{let _=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(U):ve.insertBefore(U,ve.firstChild);break}case"body-bottom":ve.appendChild(U);break;case"footer-top":Mt.replaceWith(U);break;case"footer-bottom":Yt.replaceWith(U);break;default:break}};for(let[$,U]of Object.entries(c))if(U)try{let X=U({config:n,defaultContent:()=>g($)});X&&x($,X)}catch(X){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,X)}})();let En=c=>{let x=c.target.closest('button[data-expand-header="true"]');if(!x)return;let w=x.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!w)return;let O=w.getAttribute("data-message-id");if(!O)return;let $=x.getAttribute("data-bubble-type");$==="reasoning"?(Ma.has(O)?Ma.delete(O):Ma.add(O),ch(O,w)):$==="tool"&&(La.has(O)?La.delete(O):La.add(O),ph(O,w,n)),ln.delete(O)};ye.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),En(c))}),ye.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),En(c))});let xn=new Map;ye.addEventListener("click",c=>{var U;let x=c.target.closest(".persona-message-action-btn[data-action]");if(!x)return;c.preventDefault(),c.stopPropagation();let w=x.closest("[data-actions-for]");if(!w)return;let O=w.getAttribute("data-actions-for");if(!O)return;let $=x.getAttribute("data-action");if($==="copy"){let _=q.getMessages().find(Te=>Te.id===O);if(_&&Pe.onCopy){let Te=_.content||"";navigator.clipboard.writeText(Te).then(()=>{x.classList.add("persona-message-action-success");let me=Ce("check",14,"currentColor",2);me&&(x.innerHTML="",x.appendChild(me)),setTimeout(()=>{x.classList.remove("persona-message-action-success");let re=Ce("copy",14,"currentColor",2);re&&(x.innerHTML="",x.appendChild(re))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),Pe.onCopy(_)}}else if($==="upvote"||$==="downvote"){let _=((U=xn.get(O))!=null?U:null)===$,Te=$==="upvote"?"thumbs-up":"thumbs-down";if(_){xn.delete(O),x.classList.remove("persona-message-action-active");let me=Ce(Te,14,"currentColor",2);me&&(x.innerHTML="",x.appendChild(me))}else{let me=$==="upvote"?"downvote":"upvote",re=w.querySelector(`[data-action="${me}"]`);if(re){re.classList.remove("persona-message-action-active");let tt=Ce(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(re.innerHTML="",re.appendChild(tt))}xn.set(O,$),x.classList.add("persona-message-action-active");let be=Ce(Te,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),x.innerHTML="",x.appendChild(be)),x.classList.remove("persona-message-action-pop"),x.offsetWidth,x.classList.add("persona-message-action-pop");let Ve=q.getMessages().find(lt=>lt.id===O);Ve&&Pe.onFeedback&&Pe.onFeedback({type:$,messageId:Ve.id,message:Ve})}}}),ye.addEventListener("click",c=>{let x=c.target.closest("button[data-approval-action]");if(!x)return;c.preventDefault(),c.stopPropagation();let w=x.closest(".persona-approval-bubble");if(!w)return;let O=w.getAttribute("data-message-id");if(!O)return;let $=x.getAttribute("data-approval-action");if(!$)return;let U=$==="approve"?"approved":"denied",_=q.getMessages().find(me=>me.id===O);if(!(_!=null&&_.approval))return;let Te=w.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),q.resolveApproval(_.approval,U)});let wt=null,Ie=null,L={artifacts:[],selectedId:null},Z=!1,se={current:null};ye.addEventListener("click",c=>{var re,be,Me,Ve,lt;let x=c.target.closest("[data-download-artifact]");if(!x)return;c.preventDefault(),c.stopPropagation();let w=x.getAttribute("data-download-artifact");if(!w||((Me=(be=(re=n.features)==null?void 0:re.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Me.call(be,{type:"download",artifactId:w}))===!0)return;let $=q.getArtifactById(w),U=$==null?void 0:$.markdown,X=($==null?void 0:$.title)||"artifact";if(!U){let tt=x.closest("[data-open-artifact]"),ft=tt==null?void 0:tt.closest("[data-message-id]"),mt=ft==null?void 0:ft.getAttribute("data-message-id");if(mt){let Be=q.getMessages().find(Je=>Je.id===mt);if(Be!=null&&Be.rawContent)try{let Je=JSON.parse(Be.rawContent);U=(Ve=Je==null?void 0:Je.props)==null?void 0:Ve.markdown,X=((lt=Je==null?void 0:Je.props)==null?void 0:lt.title)||X}catch{}}}if(!U)return;let _=new Blob([U],{type:"text/markdown"}),Te=URL.createObjectURL(_),me=document.createElement("a");me.href=Te,me.download=`${X}.md`,me.click(),URL.revokeObjectURL(Te)}),ye.addEventListener("click",c=>{var $,U,X;let x=c.target.closest("[data-open-artifact]");if(!x)return;let w=x.getAttribute("data-open-artifact");!w||((X=(U=($=n.features)==null?void 0:$.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:X.call(U,{type:"open",artifactId:w}))===!0||(c.preventDefault(),c.stopPropagation(),Z=!1,q.selectArtifact(w),on())}),ye.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let kt=ke.composerOverlay,qt=(c,g,x)=>{var X,_,Te,me;let w=g.trim();if(!w||!se.current)return;let O=(X=c.getAttribute("data-tool-call-id"))!=null?X:"",$=x.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:O,answer:w,answers:x.structured,values:(_=x.values)!=null?_:x.source==="multi"?w.split(", "):[w],isFreeText:$,source:x.source},bubbles:!0,composed:!0})),Lo(kt,O);let U=se.current.getMessages().find(re=>{var be;return((be=re.toolCall)==null?void 0:be.id)===O});(Te=U==null?void 0:U.agentMetadata)!=null&&Te.awaitingLocalTool?se.current.resolveAskUserQuestion(U,(me=x.structured)!=null?me:w):se.current.sendMessage(w)},Bt=c=>{var O;let g=se.current;if(!g)return;let x=(O=c.getAttribute("data-tool-call-id"))!=null?O:"",w=g.getMessages().find($=>{var U;return((U=$.toolCall)==null?void 0:U.id)===x});w&&g.persistAskUserQuestionProgress(w,{answers:fl(c,w),currentIndex:An(c)})},ar=c=>Object.entries(c).map(([g,x])=>`${g}: ${Array.isArray(x)?x.join(", "):x}`).join(" | "),xr=c=>{var O,$,U;if((($=(O=n.features)==null?void 0:O.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=An(c),x=Ia(c);if(g>=x-1)return;let w=(U=se.current)==null?void 0:U.getMessages().find(X=>{var _;return((_=X.toolCall)==null?void 0:_.id)===c.getAttribute("data-tool-call-id")});w&&(ml(c,w,n,g+1),Bt(c))};kt.addEventListener("click",c=>{var $,U,X,_,Te,me,re,be,Me,Ve,lt,tt,ft,mt;let x=c.target.closest("[data-ask-user-action]");if(!x)return;let w=x.closest("[data-persona-ask-sheet-for]");if(!w)return;let O=x.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),O==="dismiss"){let We=($=w.getAttribute("data-tool-call-id"))!=null?$:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Lo(kt,We);let Be=(U=se.current)==null?void 0:U.getMessages().find(Je=>{var D;return((D=Je.toolCall)==null?void 0:D.id)===We});(X=Be==null?void 0:Be.agentMetadata)!=null&&X.awaitingLocalTool&&((_=se.current)==null||_.markAskUserQuestionResolved(Be),(Te=se.current)==null||Te.resolveAskUserQuestion(Be,"(dismissed)"));return}if(O==="pick"){let We=x.getAttribute("data-option-label");if(!We)return;let Be=w.getAttribute("data-multi-select")==="true",Je=Mo(w);if(Je&&Be){let D=aa(w)[An(w)],Re=new Set(Array.isArray(D)?D:[]);Re.has(We)?Re.delete(We):Re.add(We),Po(w,Array.from(Re)),Bt(w);return}if(Je){Po(w,We),Bt(w),xr(w);return}if(Be){let D=x.getAttribute("aria-pressed")==="true";x.setAttribute("aria-pressed",D?"false":"true"),x.classList.toggle("persona-ask-pill-selected",!D);let Re=w.querySelector('[data-ask-user-action="submit-multi"]');Re&&(Re.disabled=Sp(w).length===0);return}qt(w,We,{source:"pick",values:[We]});return}if(O==="submit-multi"){let We=Sp(w);if(We.length===0)return;qt(w,We.join(", "),{source:"multi",values:We});return}if(O==="open-free-text"){let We=w.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Be=We.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus()}return}if(O==="focus-free-text"){let We=w.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(O==="submit-free-text"){let We=w.querySelector('[data-ask-free-text-input="true"]'),Be=(me=We==null?void 0:We.value)!=null?me:"";if(!Be.trim())return;if(Mo(w)){Po(w,Be.trim()),Bt(w),xr(w);return}qt(w,Be,{source:"free-text"});return}if(O==="next"||O==="back"){if(!se.current)return;let We=(re=w.getAttribute("data-tool-call-id"))!=null?re:"",Be=se.current.getMessages().find(Qe=>{var Ae;return((Ae=Qe.toolCall)==null?void 0:Ae.id)===We});if(!Be)return;let Je=w.querySelector('[data-ask-free-text-input="true"]'),D=(Me=(be=Je==null?void 0:Je.value)==null?void 0:be.trim())!=null?Me:"";if(D){let Qe=aa(w)[An(w)];(typeof Qe!="string"||Qe!==D)&&Po(w,D)}let Re=O==="next"?1:-1,Ne=An(w)+Re;ml(w,Be,n,Ne),Bt(w);return}if(O==="submit-all"){if(!se.current)return;let We=(Ve=w.getAttribute("data-tool-call-id"))!=null?Ve:"",Be=se.current.getMessages().find(Qe=>{var Ae;return((Ae=Qe.toolCall)==null?void 0:Ae.id)===We});if(!Be)return;let Je=w.querySelector('[data-ask-free-text-input="true"]'),D=(tt=(lt=Je==null?void 0:Je.value)==null?void 0:lt.trim())!=null?tt:"";D&&Po(w,D);let Re=fl(w,Be);se.current.persistAskUserQuestionProgress(Be,{answers:Re,currentIndex:An(w)});let Ne=ar(Re);qt(w,Ne||"(submitted)",{source:"submit-all",structured:Re});return}if(O==="skip"){if(!se.current)return;let We=(ft=w.getAttribute("data-tool-call-id"))!=null?ft:"",Be=se.current.getMessages().find(Ae=>{var Dt;return((Dt=Ae.toolCall)==null?void 0:Dt.id)===We});if(!Be)return;let Je=Mo(w),D=An(w),Re=Ia(w),Ne=D>=Re-1;if(!Je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Lo(kt,We),(mt=Be.agentMetadata)!=null&&mt.awaitingLocalTool&&(se.current.markAskUserQuestionResolved(Be),se.current.resolveAskUserQuestion(Be,"(dismissed)"));return}Po(w,"");let Qe=w.querySelector('[data-ask-free-text-input="true"]');if(Qe&&(Qe.value=""),Ne){let Ae=fl(w,Be),Dt=ar(Ae);qt(w,Dt||"(skipped)",{source:"submit-all",structured:Ae});return}ml(w,Be,n,D+1),Bt(w);return}}),kt.addEventListener("keydown",c=>{var $;if(c.key!=="Enter")return;let x=c.target;if(!(($=x.matches)!=null&&$.call(x,'[data-ask-free-text-input="true"]')))return;let w=x.closest("[data-persona-ask-sheet-for]");if(!w)return;c.preventDefault();let O=x.value;if(O.trim()){if(Mo(w)){Po(w,O.trim()),Bt(w),xr(w);return}qt(w,O,{source:"free-text"})}});let Nr=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 x=kt.querySelector("[data-persona-ask-sheet-for]");if(!x||x.getAttribute("data-ask-layout")!=="rows"||x.getAttribute("data-multi-select")==="true")return;let w=Number(c.key),$=x.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[w-1];$&&(c.preventDefault(),$.click())};document.addEventListener("keydown",Nr);let Er=null,ot=null,wr=null,_r=null,po=()=>{};function jn(){_r==null||_r(),_r=null}let uo=()=>{var U;if(!Er||!ot)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),x=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||x){ot.style.removeProperty("position"),ot.style.removeProperty("left"),ot.style.removeProperty("top"),ot.style.removeProperty("bottom"),ot.style.removeProperty("width"),ot.style.removeProperty("z-index");return}let w=Er.firstElementChild;if(!w||w===ot)return;let O=10;ot.style.position="absolute",ot.style.top="0",ot.style.bottom="0",ot.style.width=`${O}px`,ot.style.zIndex="5";let $=w.offsetWidth-O/2;ot.style.left=`${Math.max(0,$)}px`},Fn=()=>{},on=()=>{var x,w,O,$,U;if(!wt||!Sn(n))return;gl(e,n),hl(e,n),Fn();let c=($=(O=(w=(x=n.features)==null?void 0:x.artifacts)==null?void 0:w.layout)==null?void 0:O.narrowHostMaxWidth)!=null?$:520,g=G.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),wt.update(L),Z?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(U=wt.backdrop)==null||U.classList.add("persona-hidden")):L.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),po()};if(Sn(n)){G.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ae),wt=Lh(n,{onSelect:x=>{var w;return(w=se.current)==null?void 0:w.selectArtifact(x)},onDismiss:()=>{Z=!0,on()}}),wt.element.classList.add("persona-hidden"),Er=g,g.appendChild(c),g.appendChild(wt.element),wt.backdrop&&G.appendChild(wt.backdrop),G.appendChild(g),po=()=>{var w,O,$,U;if(!Er||!wt)return;if(!((($=(O=(w=n.features)==null?void 0:w.artifacts)==null?void 0:O.layout)==null?void 0:$.resizable)===!0)){wr==null||wr(),wr=null,jn(),ot&&(ot.remove(),ot=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!ot){let X=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");X.setAttribute("role","separator"),X.setAttribute("aria-orientation","vertical"),X.setAttribute("aria-label","Resize artifacts panel"),X.tabIndex=0;let _=e.ownerDocument,Te=(U=_.defaultView)!=null?U:window,me=re=>{var ft,mt;if(!wt||re.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;re.preventDefault(),jn();let be=re.clientX,Me=wt.element.getBoundingClientRect().width,Ve=(mt=(ft=n.features)==null?void 0:ft.artifacts)==null?void 0:mt.layout,lt=We=>{let Be=Er.getBoundingClientRect().width,Je=e.classList.contains("persona-artifact-appearance-seamless"),D=Je?0:Hh(Er,Te),Re=Je?0:X.getBoundingClientRect().width||6,Ne=Me-(We.clientX-be),Qe=Bh(Ne,Be,D,Re,Ve==null?void 0:Ve.resizableMinWidth,Ve==null?void 0:Ve.resizableMaxWidth);wt.element.style.width=`${Qe}px`,wt.element.style.maxWidth="none",uo()},tt=()=>{_.removeEventListener("pointermove",lt),_.removeEventListener("pointerup",tt),_.removeEventListener("pointercancel",tt),_r=null;try{X.releasePointerCapture(re.pointerId)}catch{}};_r=tt,_.addEventListener("pointermove",lt),_.addEventListener("pointerup",tt),_.addEventListener("pointercancel",tt);try{X.setPointerCapture(re.pointerId)}catch{}};X.addEventListener("pointerdown",me),ot=X,Er.insertBefore(X,wt.element),wr=()=>{X.removeEventListener("pointerdown",me)}}if(ot){let X=L.artifacts.length>0&&!Z;ot.classList.toggle("persona-hidden",!X),uo()}},Fn=()=>{var Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be,Je,D;if(!T||!wt||((me=(Te=n.launcher)==null?void 0:Te.sidebarMode)!=null?me:!1)||hr(n)&&vn(n).reveal==="emerge")return;let w=(re=e.ownerDocument.defaultView)!=null?re:window,O=(Me=(be=n.launcher)==null?void 0:be.mobileFullscreen)!=null?Me:!0,$=(lt=(Ve=n.launcher)==null?void 0:Ve.mobileBreakpoint)!=null?lt:640;if(O&&w.innerWidth<=$||!Rh(n,T))return;let U=(mt=(ft=(tt=n.launcher)==null?void 0:tt.width)!=null?ft:n.launcherWidth)!=null?mt:mn,X=(D=(Je=(Be=(We=n.features)==null?void 0:We.artifacts)==null?void 0:Be.layout)==null?void 0:Je.expandedPanelWidth)!=null?D:"min(720px, calc(100vw - 24px))";L.artifacts.length>0&&!Z?(G.style.width=X,G.style.maxWidth=X):(G.style.width=U,G.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Ie=new ResizeObserver(()=>{on()}),Ie.observe(G))}else G.appendChild(ae),B()&&we&&(ke.peekBanner&&we.appendChild(ke.peekBanner),we.appendChild(qe));e.appendChild(Y),we&&e.appendChild(we);let Mn=()=>{var Qe,Ae,Dt,pt,cr,Lr,Ft,Ur,Pr,st,gt,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo,Et,Zr,Zn,zr,en,zt,Zt;if(B()){G.style.width="100%",G.style.maxWidth="100%";let Vt=(Ae=(Qe=n.launcher)==null?void 0:Qe.composerBar)!=null?Ae:{},nr=Y.dataset.state==="expanded",tn=(Dt=Vt.expandedSize)!=null?Dt:"anchored";if(!(nr&&tn!=="fullscreen")){ae.style.background="",ae.style.border="",ae.style.borderRadius="",ae.style.overflow="",ae.style.boxShadow="";return}let gr=(cr=(pt=n.theme)==null?void 0:pt.components)==null?void 0:cr.panel,$n=Sa(n),eo=($o,oi)=>{var Ya;return $o==null||$o===""?oi:(Ya=va($n,$o))!=null?Ya:$o},ti="1px solid var(--persona-border)",ri="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ni="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ae.style.background="var(--persona-surface, #ffffff)",ae.style.border=eo(gr==null?void 0:gr.border,ti),ae.style.borderRadius=eo(gr==null?void 0:gr.borderRadius,ni),ae.style.boxShadow=eo(gr==null?void 0:gr.shadow,ri),ae.style.overflow="hidden";return}let c=hr(n),g=(Ft=(Lr=n.launcher)==null?void 0:Lr.sidebarMode)!=null?Ft:!1,x=c||g||((Pr=(Ur=n.launcher)==null?void 0:Ur.fullHeight)!=null?Pr:!1),w=((st=n.launcher)==null?void 0:st.enabled)===!1,O=(qr=(gt=n.theme)==null?void 0:gt.components)==null?void 0:qr.panel,$=Sa(n),U=(Vt,nr)=>{var tn;return Vt==null||Vt===""?nr:(tn=va($,Vt))!=null?tn:Vt},X=(Br=e.ownerDocument.defaultView)!=null?Br:window,_=(Fo=(Oo=n.launcher)==null?void 0:Oo.mobileFullscreen)!=null?Fo:!0,Te=(ma=(No=n.launcher)==null?void 0:No.mobileBreakpoint)!=null?ma:640,me=X.innerWidth<=Te,re=_&&me&&T,be=(rr=(ga=n.launcher)==null?void 0:ga.position)!=null?rr:"bottom-left",Me=be==="bottom-left"||be==="top-left",Ve=(wo=(_o=n.launcher)==null?void 0:_o.zIndex)!=null?wo:Or,lt=g||re?"none":"1px solid var(--persona-border)",tt=re?"none":g?Me?"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&&!re&&(tt="none",lt="none");let ft=g||re?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",mt=U(O==null?void 0:O.border,lt),We=U(O==null?void 0:O.shadow,tt),Be=U(O==null?void 0:O.borderRadius,ft),Je=ve.scrollTop;e.style.cssText="",Y.style.cssText="",G.style.cssText="",ae.style.cssText="",ve.style.cssText="",qe.style.cssText="";let D=()=>{var nr;if(Je<=0)return;((nr=ve.ownerDocument.defaultView)!=null?nr:window).requestAnimationFrame(()=>{if(ve.scrollTop===Je)return;let tn=ve.scrollHeight-ve.clientHeight;tn<=0||(ve.scrollTop=Math.min(Je,tn))})};if(re){Y.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Y.style.cssText=`
|
|
71
71
|
position: fixed !important;
|
|
72
72
|
inset: 0 !important;
|
|
73
73
|
width: 100% !important;
|
|
@@ -103,7 +103,7 @@ Please report this to https://github.com/markedjs/marked.`,r){let o="<p>An error
|
|
|
103
103
|
overflow: hidden !important;
|
|
104
104
|
border-radius: 0 !important;
|
|
105
105
|
border: none !important;
|
|
106
|
-
`,ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",qe.style.flexShrink="0",
|
|
106
|
+
`,ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",qe.style.flexShrink="0",M=!0,D();return}let Re=(Zr=(Et=n==null?void 0:n.launcher)==null?void 0:Et.width)!=null?Zr:n==null?void 0:n.launcherWidth,Ne=Re!=null?Re:mn;if(!g&&!c)w&&x?(G.style.width="100%",G.style.maxWidth="100%"):(G.style.width=Ne,G.style.maxWidth=Ne);else if(c)if(vn(n).reveal==="emerge"){let nr=vn(n).width;G.style.width=nr,G.style.maxWidth=nr}else G.style.width="100%",G.style.maxWidth="100%";if(Fn(),G.style.boxShadow=We,G.style.borderRadius=Be,ae.style.border=mt,ae.style.borderRadius=Be,c&&!re&&(O==null?void 0:O.border)===void 0&&(ae.style.border="none",vn(n).side==="right"?ae.style.borderLeft="1px solid var(--persona-border)":ae.style.borderRight="1px solid var(--persona-border)"),x&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",w&&(e.style.width="100%"),Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.height="100%",w&&(Y.style.overflow="hidden"),G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.height="100%",G.style.overflow="hidden",ae.style.display="flex",ae.style.flexDirection="column",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.maxHeight="100%",ae.style.overflow="hidden",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",qe.style.flexShrink="0"),Y.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!w&&!c&&((Zn=On[be])!=null?Zn:On["bottom-right"]).split(" ").forEach(nr=>Y.classList.add(nr)),g){let Vt=(en=(zr=n.launcher)==null?void 0:zr.sidebarWidth)!=null?en:"420px";Y.style.cssText=`
|
|
107
107
|
position: fixed !important;
|
|
108
108
|
top: 0 !important;
|
|
109
109
|
bottom: 0 !important;
|
|
@@ -144,9 +144,9 @@ Please report this to https://github.com/markedjs/marked.`,r){let o="<p>An error
|
|
|
144
144
|
flex-shrink: 0 !important;
|
|
145
145
|
border-top: none !important;
|
|
146
146
|
padding: 8px 16px 12px 16px !important;
|
|
147
|
-
`}if(!C&&!c){let Vt="max-height: -moz-available !important; max-height: stretch !important;",nr=g?"":"padding-top: 1.25em !important;",tn=g?"":`z-index: ${(Zt=(zt=n.launcher)==null?void 0:zt.zIndex)!=null?Zt:Or} !important;`;Y.style.cssText+=Vt+nr+tn}W()};Mn(),vo(e,n),gl(e,n),hl(e,n);let vt=[];vt.push(()=>{document.removeEventListener("keydown",Nr)});let sr=null,ir=null;vt.push(()=>{sr==null||sr(),sr=null,ir==null||ir(),ir=null}),Ie&&vt.push(()=>{Ie==null||Ie.disconnect(),Ie=null}),vt.push(()=>{wr==null||wr(),wr=null,jn(),ot&&(ot.remove(),ot=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),xe&&vt.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),ce==null||ce.destroy(),ce=null,J==null||J.destroy(),J=null,Q=null});let an=null,fo=()=>{an&&(an(),an=null),n.colorScheme==="auto"&&(an=Gi(()=>{vo(e,n)}))};fo(),vt.push(()=>{an&&(an(),an=null)});let yn=(Hu=n.features)==null?void 0:Hu.streamAnimation;if(yn!=null&&yn.type&&yn.type!=="none"){let c=Ss(yn.type,yn.plugins);c&&(sp(c,e),vt.push(()=>rh(e)))}let Ln=Th(Mt),sn=null,q,he=!1,ln=Kg(),Pn=new Map,Nn=new Map,Oa=0,In=Ji(),Rn=0,Hn=null,Gn=!1,Ro=!1,Ns=4,Fa=24,_s=80,la=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Na=(Wu=(Bu=n.voiceRecognition)==null?void 0:Bu.autoResume)!=null?Wu:!1,bn=c=>{a.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Qr=()=>{f(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},$s=()=>{var C,D;if(((C=n.voiceRecognition)==null?void 0:C.enabled)===!1)return;let c=Ip(d.voiceState),g=!!c.active,y=Number((D=c.timestamp)!=null?D:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<V0&&setTimeout(()=>{var $,U;bt.active||(bt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("restore"),q.isVoiceActive()&&Co()}):Wo("restore"))},1e3)},Us=()=>q?$h(q.getMessages()).filter(c=>!c.__skipPersist):[];function da(c){if(!(i!=null&&i.save))return;let y={messages:c?$h(c):q?Us():[],metadata:d,artifacts:M.artifacts,selectedArtifactId:M.selectedId};try{let C=i.save(y);C instanceof Promise&&C.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let Xn=null,qs=()=>Y.querySelector("#persona-scroll-container")||ve,Ho=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Gn=!1},_a=()=>{Hn!==null&&(cancelAnimationFrame(Hn),Hn=null),Ro=!1,Ho()},Jn=()=>{if(!rt()||pe){it.parentNode&&it.remove(),it.style.display="none";return}it.parentNode!==ae&&ae.appendChild(it),Rr();let c=Cs(ve)>0;it.style.display=In.isFollowing()||!c?"none":""},$a=()=>{In.pause()&&(_a(),Jn())},mo=()=>{In.resume(),Jn()},go=(c=!1)=>{In.isFollowing()&&(!c&&!he||(Hn!==null&&(cancelAnimationFrame(Hn),Hn=null),Ro=!0,Hn=requestAnimationFrame(()=>{Hn=null,Ro=!1,In.isFollowing()&&zs(qs(),c?220:140)})))},zs=(c,g=500)=>{let y=c.scrollTop,C=Cs(c),D=C-y;if(Math.abs(D)<1){Rn=c.scrollTop;return}if(Math.abs(D)>=_s){Ho(),Gn=!0,c.scrollTop=C,Rn=c.scrollTop,Gn=!1;return}Ho();let $=performance.now();Gn=!0;let U=_=>1-Math.pow(1-_,3),X=_=>{if(!In.isFollowing()){Ho();return}let Te=Cs(c);Te!==C&&(C=Te,D=C-y);let me=_-$,re=Math.min(me/g,1),be=U(re),Me=y+D*be;c.scrollTop=Me,Rn=c.scrollTop,re<1?Xn=requestAnimationFrame(X):(c.scrollTop=C,Rn=c.scrollTop,Xn=null,Gn=!1)};Xn=requestAnimationFrame(X)},Vs=c=>{let g=new Map;c.forEach(y=>{let C=la.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!C&&y.role==="assistant"&&a.emit("assistant:message",y),y.role==="assistant"&&(C!=null&&C.streaming)&&y.streaming===!1&&a.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(C?y.approval.status!=="pending"&&a.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):a.emit("approval:requested",{approval:y.approval,message:y}))}),la.clear(),g.forEach((y,C)=>{la.set(C,y)})},Bo=(c,g,y)=>{var tt,ft,mt,We,Be,Je;let C=document.createElement("div"),$=(()=>{var Re;let W=o.find(Ne=>Ne.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Re=n.loadingIndicator)!=null&&Re.render)return n.loadingIndicator.render})(),U=(W,Re)=>Re==null?!1:typeof Re=="string"?(W.textContent=Re,!0):(W.appendChild(Re),!0),X=new Set,_=new Set,Te=o.some(W=>W.renderAskUserQuestion),me=[],re=[],be=n.enableComponentStreaming!==!1;if(g.forEach(W=>{var Ur,Pr,st,gt,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo;X.add(W.id);let Re=Te&&so(W),Ne=!Re&&W.role==="assistant"&&!W.variant&&be&&Cl(W);if(!Ne&&Nn.has(W.id)){let Et=c.querySelector(`#wrapper-${W.id}`);Et==null||Et.removeAttribute("data-preserve-runtime"),Nn.delete(W.id)}let Qe=so(W)?`:${(Ur=W.agentMetadata)!=null&&Ur.askUserQuestionAnswered?"a":"u"}:${(Pr=W.agentMetadata)!=null&&Pr.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ae=Jg(W,Oa)+Qe,Dt=Re||Ne?null:Yg(ln,W.id,Ae);if(Dt){C.appendChild(Dt.cloneNode(!0)),so(W)&&((st=W.toolCall)!=null&&st.id)&&((gt=W.agentMetadata)==null?void 0:gt.awaitingLocalTool)===!0&&!((qr=W.agentMetadata)!=null&&qr.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,n,ke.composerOverlay));return}let pt=null,cr=o.find(Et=>!!(W.variant==="reasoning"&&Et.renderReasoning||W.variant==="tool"&&Et.renderToolCall||W.variant==="approval"&&Et.renderApproval||!W.variant&&Et.renderMessage)),Lr=(Br=n.layout)==null?void 0:Br.messages;if(so(W)&&((Oo=W.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){Pn.delete(W.id);let Et=c.querySelector(`#wrapper-${W.id}`);Et==null||Et.removeAttribute("data-preserve-runtime");return}if(so(W)&&((No=(Fo=n.features)==null?void 0:Fo.askUserQuestion)==null?void 0:No.enabled)!==!1){let Et=o.find(Zr=>typeof Zr.renderAskUserQuestion=="function");if(Et&&se.current){let Zr=Pn.get(W.id),Zn=Zr!==Ae,zr=null;if(Zn){let{payload:Zt,complete:Vt}=io(W),nr=W.id,tn=()=>{var cn;return(cn=se.current)==null?void 0:cn.getMessages().find(gr=>gr.id===nr)};zr=Et.renderAskUserQuestion({message:W,payload:Zt,complete:Vt,resolve:cn=>{var $n;let gr=tn();gr&&(($n=se.current)==null||$n.resolveAskUserQuestion(gr,cn))},dismiss:()=>{var gr,$n,eo;let cn=tn();(gr=cn==null?void 0:cn.agentMetadata)!=null&&gr.awaitingLocalTool&&(($n=se.current)==null||$n.markAskUserQuestionResolved(cn),(eo=se.current)==null||eo.resolveAskUserQuestion(cn,"(dismissed)"))},config:n})}let en=Zr!=null;if(Zn&&zr===null&&!en){((ma=W.agentMetadata)==null?void 0:ma.awaitingLocalTool)===!0&&!((ga=W.agentMetadata)!=null&&ga.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,n,ke.composerOverlay));return}let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-${W.id}`,zt.setAttribute("data-wrapper-id",W.id),zt.setAttribute("data-ask-plugin-stub","true"),zt.setAttribute("data-preserve-runtime","true"),C.appendChild(zt),me.push({messageId:W.id,fingerprint:Ae,bubble:zr});return}else{((rr=W.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((_o=W.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,n,ke.composerOverlay));return}}else if(cr)if(W.variant==="reasoning"&&W.reasoning&&cr.renderReasoning){if(!De)return;pt=cr.renderReasoning({message:W,defaultRenderer:()=>hp(W,n),config:n})}else if(W.variant==="tool"&&W.toolCall&&cr.renderToolCall){if(!Xe)return;pt=cr.renderToolCall({message:W,defaultRenderer:()=>xp(W,n),config:n})}else if(W.variant==="approval"&&W.approval&&cr.renderApproval){if(n.approval===!1)return;pt=cr.renderApproval({message:W,defaultRenderer:()=>Tp(W,n),config:n})}else cr.renderMessage&&(pt=cr.renderMessage({message:W,defaultRenderer:()=>{let Et=Ea(W,y,Lr,n.messageActions,Pe,{loadingIndicatorRenderer:$,widgetConfig:n});return W.role!=="user"&&Mp(Et,W,n,q),Et},config:n}));if(!pt&&Ne){let Et=wl(W);if(Et){let Zr=Nn.get(W.id),Zn=Zr!==Ae,zr=n.wrapComponentDirectiveInBubble!==!1,en=null;if(Zn){let zt=bl(Et,{config:n,message:W,transform:y});if(zt)if(zr){let Zt=document.createElement("div");if(Zt.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(" "),Zt.id=`bubble-${W.id}`,Zt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Vt=document.createElement("div");Vt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Vt.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Zt.appendChild(Vt)}Zt.appendChild(zt),en=Zt}else{let Zt=document.createElement("div");if(Zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Zt.id=`bubble-${W.id}`,Zt.setAttribute("data-message-id",W.id),Zt.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Vt=document.createElement("div");Vt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Vt.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Zt.appendChild(Vt)}Zt.appendChild(zt),en=Zt}}if(en||Zr!=null){let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-${W.id}`,zt.setAttribute("data-wrapper-id",W.id),zt.setAttribute("data-component-directive-stub","true"),zt.setAttribute("data-preserve-runtime","true"),zr||zt.classList.add("persona-w-full"),C.appendChild(zt),re.push({messageId:W.id,fingerprint:Ae,bubble:en});return}}}if(!pt)if(W.variant==="reasoning"&&W.reasoning){if(!De)return;pt=hp(W,n)}else if(W.variant==="tool"&&W.toolCall){if(!Xe)return;pt=xp(W,n)}else if(W.variant==="approval"&&W.approval){if(n.approval===!1)return;pt=Tp(W,n)}else{let Et=(wo=n.layout)==null?void 0:wo.messages;Et!=null&&Et.renderUserMessage&&W.role==="user"?pt=Et.renderUserMessage({message:W,config:n,streaming:!!W.streaming}):Et!=null&&Et.renderAssistantMessage&&W.role==="assistant"?pt=Et.renderAssistantMessage({message:W,config:n,streaming:!!W.streaming}):pt=Ea(W,y,Et,n.messageActions,Pe,{loadingIndicatorRenderer:$,widgetConfig:n}),W.role!=="user"&&pt&&Mp(pt,W,n,q)}let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id=`wrapper-${W.id}`,Ft.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Ft.classList.add("persona-justify-end"),(pt==null?void 0:pt.getAttribute("data-persona-component-directive"))==="true"&&Ft.classList.add("persona-w-full"),Ft.appendChild(pt),Qg(ln,W.id,Ae,Ft),C.appendChild(Ft)}),ke.composerOverlay&&ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Ne=Re.getAttribute("data-persona-ask-sheet-for");Ne&&!_.has(Ne)&&Lo(ke.composerOverlay,Ne)}),(ft=(tt=n.features)==null?void 0:tt.toolCallDisplay)!=null&&ft.grouped){let W=[],Re=[];g.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&Xe){Re.push(Ne);return}Re.length>1&&W.push(Re),Re=[]}),Re.length>1&&W.push(Re),W.forEach((Ne,Qe)=>{var Pr,st;let Ae=Ne.map(gt=>Array.from(C.children).find(qr=>qr instanceof HTMLElement&&qr.getAttribute("data-wrapper-id")===gt.id)).filter(gt=>!!gt);if(Ae.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${Qe}-${Ne[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${Qe}-${Ne[0].id}`);let pt=document.createElement("div");pt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",pt.setAttribute("data-persona-tool-group","true");let cr=document.createElement("div");cr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Lr=`Called ${Ne.length} tools`,Ft=(st=(Pr=n.toolCall)==null?void 0:Pr.renderGroupedSummary)==null?void 0:st.call(Pr,{messages:Ne,toolCalls:Ne.map(gt=>gt.toolCall).filter(gt=>!!gt),defaultSummary:Lr,config:n});U(cr,Ft)||(cr.textContent=Lr);let Ur=document.createElement("div");Ur.className="persona-tool-group-stack persona-flex persona-flex-col",pt.append(cr,Ur),Dt.appendChild(pt),Ae[0].before(Dt),Ae.forEach((gt,qr)=>{let Br=document.createElement("div");Br.className="persona-tool-group-item persona-relative",Br.setAttribute("data-persona-tool-group-item","true"),qr<Ae.length-1&&Br.setAttribute("data-persona-tool-group-connector","true"),Br.appendChild(gt),Ur.appendChild(Br)})})}Zg(ln,X);let Me=g.some(W=>W.role==="assistant"&&W.streaming),Ve=g[g.length-1],lt=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(he&&g.some(W=>W.role==="user")&&!Me&&!lt){let W={config:n,streaming:!0,location:"standalone",defaultRenderer:oa},Re=o.find(Qe=>Qe.renderLoadingIndicator),Ne=null;if(Re!=null&&Re.renderLoadingIndicator&&(Ne=Re.renderLoadingIndicator(W)),Ne===null&&((mt=n.loadingIndicator)!=null&&mt.render)&&(Ne=n.loadingIndicator.render(W)),Ne===null&&(Ne=oa()),Ne){let Qe=document.createElement("div"),Ae=((We=n.loadingIndicator)==null?void 0:We.showBubble)!==!1;Qe.className=Ae?["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(" "),Qe.setAttribute("data-typing-indicator","true"),Qe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Qe.appendChild(Ne);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(Qe),C.appendChild(Dt)}}if(!he&&g.length>0){let W=g[g.length-1],Re={config:n,lastMessage:W,messageCount:g.length},Ne=o.find(Ae=>Ae.renderIdleIndicator),Qe=null;if(Ne!=null&&Ne.renderIdleIndicator&&(Qe=Ne.renderIdleIndicator(Re)),Qe===null&&((Be=n.loadingIndicator)!=null&&Be.renderIdle)&&(Qe=n.loadingIndicator.renderIdle(Re)),Qe){let Ae=document.createElement("div"),Dt=((Je=n.loadingIndicator)==null?void 0:Je.showBubble)!==!1;Ae.className=Dt?["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(" "),Ae.setAttribute("data-idle-indicator","true"),Ae.appendChild(Qe);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-idle-indicator",pt.setAttribute("data-wrapper-id","idle-indicator"),pt.appendChild(Ae),C.appendChild(pt)}}if(Xi(c,C),me.length>0)for(let{messageId:W,fingerprint:Re,bubble:Ne}of me){let Qe=c.querySelector(`#wrapper-${W}`);Qe&&Ne!==null&&(Qe.replaceChildren(Ne),Qe.setAttribute("data-bubble-fp",Re),Pn.set(W,Re))}if(Pn.size>0)for(let W of Pn.keys())X.has(W)||Pn.delete(W);if(re.length>0)for(let{messageId:W,fingerprint:Re,bubble:Ne}of re){let Qe=c.querySelector(`#wrapper-${W}`);Qe&&Ne!==null&&(Qe.replaceChildren(Ne),Qe.setAttribute("data-bubble-fp",Re),Nn.set(W,Re))}if(Nn.size>0)for(let W of Nn.keys())X.has(W)||Nn.delete(W)},ho=null,js=()=>{var y;if(ho)return;let c=C=>{let D=C.composedPath();D.includes(Y)||we&&D.includes(we)||Nt(!1,"user")};ho=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},Ua=()=>{var g;if(!ho)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",ho,!0),ho=null};vt.push(()=>Ua());let xo=null,Gs=()=>{var y;if(xo)return;let c=C=>{C.key==="Escape"&&(C.isComposing||Nt(!1,"user"))};xo=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},qa=()=>{var g;if(!xo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",xo,!0),xo=null};vt.push(()=>qa());let yo=!1,za=new Set,Xs=()=>{var g,y,C,D;let c=(C=(y=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:C.streamAnimation;return c||((D=n.features)==null?void 0:D.streamAnimation)},Kn=()=>{var ft,mt,We,Be;if(!O())return;let c=ke.peekBanner,g=ke.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let y=(ft=q==null?void 0:q.getMessages())!=null?ft:[],C;for(let Je=y.length-1;Je>=0;Je--){let W=y[Je];if(W.role==="assistant"&&W.content){C=W;break}}if(!C){c.classList.remove("persona-pill-peek--visible");return}let D=C.content,$=!!C.streaming,U=Xs(),X=Qi(U),_=X.type!=="none"?Ss(X.type,U==null?void 0:U.plugins):null,Te=((mt=_==null?void 0:_.isAnimating)==null?void 0:mt.call(_,C))===!0,me=_!==null&&($||Te);me&&_&&!za.has(_.name)&&(sp(_,e),za.add(_.name));let re=me&&(_!=null&&_.containerClass)?_.containerClass:null,be=(We=g.dataset.personaPeekStreamClass)!=null?We:null;be&&be!==re&&(g.classList.remove(be),delete g.dataset.personaPeekStreamClass),re&&be!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),me?(g.style.setProperty("--persona-stream-step",`${X.speed}ms`),g.style.setProperty("--persona-stream-duration",`${X.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Me=me?Zi(D,X.buffer,_,C,$):D;if(me&&X.placeholder==="skeleton"&&$&&(!Me||!Me.trim())){let Je=document.createElement("div"),W=ks();W.classList.add("persona-pill-peek__skeleton"),Je.appendChild(W),Xi(g,Je)}else{let Je=Math.max(0,Me.length-100),W=Me.length>100?Me.slice(-100):Me,Re=Jo(W);if(!me||!_){let Ne=Me.length>100?`\u2026${W}`:W;g.textContent!==Ne&&(g.textContent=Ne)}else{let Ne=Re;(_.wrap==="char"||_.wrap==="word")&&(Ne=Ts(Re,_.wrap,`peek-${C.id}`,{skipTags:_.skipTags,startIndex:Je}));let Qe=document.createElement("div");if(Qe.innerHTML=Ne,_.useCaret&&W.length>0){let Ae=el(),Dt=Qe.querySelectorAll(".persona-stream-char, .persona-stream-word"),pt=Dt[Dt.length-1];pt!=null&&pt.parentNode?pt.parentNode.insertBefore(Ae,pt.nextSibling):Qe.appendChild(Ae)}Xi(g,Qe),(Be=_.onAfterRender)==null||Be.call(_,{container:g,bubble:c,messageId:C.id,message:C,speed:X.speed,duration:X.duration})}}let tt=he||yo;c.classList.toggle("persona-pill-peek--visible",tt)};if(O()){let c=ke.peekBanner;if(c){let C=D=>{D.preventDefault(),D.stopPropagation(),Nt(!0,"user")};c.addEventListener("pointerdown",C),vt.push(()=>{c.removeEventListener("pointerdown",C)})}let g=()=>{yo||(yo=!0,Kn())},y=()=>{yo&&(yo=!1,Kn())};G.addEventListener("pointerenter",g),G.addEventListener("pointerleave",y),vt.push(()=>{G.removeEventListener("pointerenter",g),G.removeEventListener("pointerleave",y)}),we&&(we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),vt.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}))}let Js=c=>{var be,Me,Ve,lt,tt,ft,mt,We;let g=(Me=(be=n.launcher)==null?void 0:be.composerBar)!=null?Me:{},y=(Ve=g.expandedSize)!=null?Ve:"anchored",C=(lt=g.bottomOffset)!=null?lt:"16px",D=g.collapsedMaxWidth,$=(tt=g.expandedMaxWidth)!=null?tt:"880px",U=(ft=g.expandedTopOffset)!=null?ft:"5vh",X=(mt=g.modalMaxWidth)!=null?mt:"880px",_=(We=g.modalMaxHeight)!=null?We:"min(90vh, 800px)",Te="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",re=Y.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",we){let Be=we.style;Be.bottom=C,Be.width=D!=null?D:""}if(c&&y!=="fullscreen"){if(y==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=X,re.maxWidth=Te,re.maxHeight=_,re.height=_;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${C} + ${me})`,re.top=U,re.width=$,re.maxWidth=Te}},bo=()=>{var _,Te,me,re,be,Me,Ve,lt;if(!H())return;if(O()){let ft=(me=((Te=(_=n.launcher)==null?void 0:_.composerBar)!=null?Te:{}).expandedSize)!=null?me:"anchored",mt=R?"expanded":"collapsed";Y.dataset.state=mt,Y.dataset.expandedSize=ft,we&&(we.dataset.state=mt,we.dataset.expandedSize=ft),Y.style.removeProperty("display"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Js(R),ae.style.display=R?"flex":"none",Mn(),R?(js(),Gs()):(Ua(),qa()),Kn();return}let c=hr(n),g=(re=e.ownerDocument.defaultView)!=null?re:window,y=(Me=(be=n.launcher)==null?void 0:be.mobileBreakpoint)!=null?Me:640,C=(lt=(Ve=n.launcher)==null?void 0:Ve.mobileFullscreen)!=null?lt:!0,D=g.innerWidth<=y,$=C&&D&&T,U=vn(n).reveal;R?(Y.style.removeProperty("display"),Y.style.display=c?"flex":"",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0"),G.classList.add("persona-scale-100","persona-opacity-100"),I?I.element.style.display="none":V&&(V.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!$?(Y.style.removeProperty("display"),Y.style.display="flex",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.setProperty("display","none","important"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.display="",Y.classList.add("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100"),G.classList.add("persona-scale-95","persona-opacity-0")),I?I.element.style.display=c?"none":"":V&&(V.style.display=c?"none":""))},Nt=(c,g="user")=>{var $,U;if(!H()||R===c)return;let y=R;R=c,bo();let C=(()=>{var Ve,lt,tt,ft,mt,We,Be,Je,W,Re;let X=(lt=(Ve=n.launcher)==null?void 0:Ve.sidebarMode)!=null?lt:!1,_=(tt=e.ownerDocument.defaultView)!=null?tt:window,Te=(mt=(ft=n.launcher)==null?void 0:ft.mobileFullscreen)!=null?mt:!0,me=(Be=(We=n.launcher)==null?void 0:We.mobileBreakpoint)!=null?Be:640,re=_.innerWidth<=me,be=hr(n)&&Te&&re,Me=O()&&((Re=(W=(Je=n.launcher)==null?void 0:Je.composerBar)==null?void 0:W.expandedSize)!=null?Re:"fullscreen")==="fullscreen";return X||Te&&re&&T||be||Me})();if(R&&C){if(!sr){let X=e.getRootNode(),_=X instanceof ShadowRoot?X.host:e.closest(".persona-host");_&&(sr=ip(_,(U=($=n.launcher)==null?void 0:$.zIndex)!=null?U:Or))}ir||(ir=lp(e.ownerDocument))}else R||(sr==null||sr(),sr=null,ir==null||ir(),ir=null);R&&(fe(),go(!0));let D={open:R,source:g,timestamp:Date.now()};R&&!y?a.emit("widget:opened",D):!R&&y&&a.emit("widget:closed",D),a.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:bt.active,streaming:q.isStreaming()})},ca=c=>{$t(c?"stop":"send"),N&&(N.disabled=c),Ln.buttons.forEach(g=>{g.disabled=c}),qe.dataset.personaComposerStreaming=c?"true":"false",qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},pa=()=>{bt.active||ne&&ne.focus()};a.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>pa(),200)});let Va=()=>{var y,C,D,$,U,X,_,Te,me,re,be;Fr.textContent=(C=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?C:"Hello \u{1F44B}",Ar.textContent=($=(D=n.copy)==null?void 0:D.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ne.placeholder=(X=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?X:"How can I help...";let c=ve.querySelector("[data-persona-intro-card]");if(c){let Me=((_=n.copy)==null?void 0:_.showWelcomeCard)!==!1;c.style.display=Me?"":"none",Me?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((me=(Te=n.sendButton)==null?void 0:Te.useIcon)!=null&&me)&&!(q!=null&&q.isStreaming())&&(He.textContent=(be=(re=n.copy)==null?void 0:re.sendButtonLabel)!=null?be:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.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 _n=null,Ks=()=>{_n==null&&(_n=setInterval(()=>{let c=ye.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(_n),_n=null;return}let g=Date.now();c.forEach(y=>{let C=Number(y.getAttribute("data-tool-elapsed"));C&&(y.textContent=yi(g-C))})},100))};if(q=new wa(n,{onMessagesChanged(c){Bo(ye,c,ue),Ks(),q&&(c.some(D=>D.role==="user")?Ln.render([],q,ne,c):Ln.render(n.suggestionChips,q,ne,c,n.suggestionChipsConfig)),go(!he),Vs(c);let g=[...c].reverse().find(C=>C.role==="user"),y=bt.lastUserMessageId;g&&g.id!==y&&(bt.lastUserMessageId=g.id,a.emit("user:message",g)),bt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),da(c),Kn()},onStatusChanged(c){var C;let g=(C=n.statusIndicator)!=null?C:{};$e(Yt,(D=>{var $,U,X,_;return D==="idle"?($=g.idleText)!=null?$:Dr.idle:D==="connecting"?(U=g.connectingText)!=null?U:Dr.connecting:D==="connected"?(X=g.connectedText)!=null?X:Dr.connected:D==="error"?(_=g.errorText)!=null?_:Dr.error:Dr[D]})(c),g,c)},onStreamingChanged(c){he=c,ca(c),q&&Bo(ye,q.getMessages(),ue),c||go(!0),Kn()},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":Wn(),Qs();break;case"speaking":Wn(),Zs();break;default:c==="idle"&&q.isBargeInActive()?(Wn(),Co(),N==null||N.setAttribute("aria-label","End voice session")):(bt.active=!1,Wn(),bn("system"),Qr());break}},onArtifactsState(c){M=c,on(),da()}}),se.current=q,((Ou=(Du=n.voiceRecognition)==null?void 0:Du.provider)==null?void 0:Ou.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)}),(J||n.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var y;(y=n.onSSEEvent)==null||y.call(n,c,g),J==null||J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,y,C;c&&(c.metadata&&(d=Ip(c.metadata),k.syncFromMetadata()),(g=c.messages)!=null&&g.length&&q.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&q.hydrateArtifacts(c.artifacts,(C=c.selectedArtifactId)!=null?C:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ja=()=>{var g,y,C;!O()||R||!((C=(y=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||C)||Nt(!0,"auto")},Ga=c=>{var D;if(c.preventDefault(),q.isStreaming()){q.cancel();return}let g=ne.value.trim(),y=(D=Tt==null?void 0:Tt.hasAttachments())!=null?D:!1;if(!g&&!y)return;ja();let C;y&&(C=[],C.push(...Tt.getContentParts()),g&&C.push(gs(g))),ne.value="",ne.style.height="auto",q.sendMessage(g,{contentParts:C}),y&&Tt.clearAttachments()},Xa=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),He.click())},Ja=async c=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Tt)return;let g=G0(c.clipboardData);g.length!==0&&(c.preventDefault(),await Tt.handleFiles(g))},$r=null,dn=!1,Yn=null,dt=null,Ka=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Wo=(c="user")=>{var $,U,X,_,Te,me,re;if(dn||q.isStreaming())return;let g=Ka();if(!g)return;$r=new g;let C=(U=(($=n.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;$r.continuous=!0,$r.interimResults=!0,$r.lang="en-US";let D=ne.value;$r.onresult=be=>{let Me="",Ve="";for(let tt=0;tt<be.results.length;tt++){let ft=be.results[tt],mt=ft[0].transcript;ft.isFinal?Me+=mt+" ":Ve=mt}let lt=D+Me+Ve;ne.value=lt,Yn&&clearTimeout(Yn),(Me||Ve)&&(Yn=window.setTimeout(()=>{let tt=ne.value.trim();tt&&$r&&dn&&(Bn(),ne.value="",ne.style.height="auto",q.sendMessage(tt,{viaVoice:!0}))},C))},$r.onerror=be=>{be.error!=="no-speech"&&Bn()},$r.onend=()=>{if(dn){let be=ne.value.trim();be&&be!==D.trim()&&(ne.value="",ne.style.height="auto",q.sendMessage(be,{viaVoice:!0})),Bn()}};try{if($r.start(),dn=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),bn(c),Qr(),N){let be=(X=n.voiceRecognition)!=null?X:{};dt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((re=(me=be.iconSize)!=null?me:(Te=n.sendButton)==null?void 0:Te.size)!=null?re:"40")||24};let Me=be.recordingBackgroundColor,Ve=be.recordingIconColor,lt=be.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=Ve!=null?Ve:"var(--persona-voice-recording-indicator, #ffffff)",Ve){let tt=N.querySelector("svg");tt&&tt.setAttribute("stroke",Ve)}lt&&(N.style.borderColor=lt),N.setAttribute("aria-label","Stop voice recognition")}}catch{Bn("system")}},Bn=(c="user")=>{if(dn){if(dn=!1,Yn&&(clearTimeout(Yn),Yn=null),$r){try{$r.stop()}catch{}$r=null}if(bt.active=!1,bn(c),Qr(),N){if(N.classList.remove("persona-voice-recording"),dt){N.style.backgroundColor=dt.backgroundColor,N.style.color=dt.color,N.style.borderColor=dt.borderColor;let g=N.querySelector("svg");g&&g.setAttribute("stroke",dt.color||"currentColor"),dt=null}N.setAttribute("aria-label","Start voice recognition")}}},Ys=(c,g)=>{var ft,mt,We,Be,Je,W,Re,Ne;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((ft=c==null?void 0:c.provider)==null?void 0:ft.type)==="runtype";if(!(y||C))return null;let $=x("div","persona-send-button-wrapper"),U=x("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 X=(mt=c==null?void 0:c.iconName)!=null?mt:"mic",_=(We=g==null?void 0:g.size)!=null?We:"40px",Te=(Be=c==null?void 0:c.iconSize)!=null?Be:_,me=parseFloat(Te)||24,re=(Je=c==null?void 0:c.backgroundColor)!=null?Je:g==null?void 0:g.backgroundColor,be=(W=c==null?void 0:c.iconColor)!=null?W:g==null?void 0:g.textColor;U.style.width=Te,U.style.height=Te,U.style.minWidth=Te,U.style.minHeight=Te,U.style.fontSize="18px",U.style.lineHeight="1",be?U.style.color=be:U.style.color="var(--persona-text, #111827)";let Ve=Ce(X,me,be||"currentColor",1.5);Ve?U.appendChild(Ve):U.textContent="\u{1F3A4}",re?U.style.backgroundColor=re: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 lt=(Re=c==null?void 0:c.tooltipText)!=null?Re:"Start voice recognition";if(((Ne=c==null?void 0:c.showTooltip)!=null?Ne:!1)&<){let Qe=x("div","persona-send-button-tooltip");Qe.textContent=lt,$.appendChild(Qe)}return{micButton:U,micButtonWrapper:$}},ua=()=>{var g,y,C,D,$;if(!N||dt)return;let c=(g=n.voiceRecognition)!=null?g:{};dt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat(($=(D=c.iconSize)!=null?D:(C=n.sendButton)==null?void 0:C.size)!=null?$:"40")||24}},fa=(c,g)=>{var $,U,X,_,Te;if(!N)return;let y=N.querySelector("svg");y&&y.remove();let C=(Te=dt==null?void 0:dt.iconSize)!=null?Te:parseFloat((_=(X=($=n.voiceRecognition)==null?void 0:$.iconSize)!=null?X:(U=n.sendButton)==null?void 0:U.size)!=null?_:"40")||24,D=Ce(c,C,g,1.5);D&&N.appendChild(D)},Do=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Co=()=>{var D;if(!N)return;ua();let c=(D=n.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,C=c.recordingBorderColor;if(Do(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let $=N.querySelector("svg");$&&$.setAttribute("stroke",y)}C&&(N.style.borderColor=C),N.setAttribute("aria-label","Stop voice recognition")},Qs=()=>{var X,_,Te,me,re,be,Me,Ve;if(!N)return;ua();let c=(X=n.voiceRecognition)!=null?X:{},g=q.getVoiceInterruptionMode(),y=(_=c.processingIconName)!=null?_:"loader",C=(me=(Te=c.processingIconColor)!=null?Te:dt==null?void 0:dt.color)!=null?me:"",D=(be=(re=c.processingBackgroundColor)!=null?re:dt==null?void 0:dt.backgroundColor)!=null?be:"",$=(Ve=(Me=c.processingBorderColor)!=null?Me:dt==null?void 0:dt.borderColor)!=null?Ve:"";Do(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=D,N.style.borderColor=$;let U=C||"currentColor";N.style.color=U,fa(y,U),N.setAttribute("aria-label","Processing voice input"),g==="none"&&(N.style.cursor="default")},Zs=()=>{var Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be;if(!N)return;ua();let c=(Te=n.voiceRecognition)!=null?Te:{},g=q.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",C=(me=c.speakingIconName)!=null?me:y,D=(Ve=c.speakingIconColor)!=null?Ve:g==="barge-in"?(be=(re=c.recordingIconColor)!=null?re:dt==null?void 0:dt.color)!=null?be:"":(Me=dt==null?void 0:dt.color)!=null?Me:"",$=(ft=c.speakingBackgroundColor)!=null?ft:g==="barge-in"?(lt=c.recordingBackgroundColor)!=null?lt:"var(--persona-voice-recording-bg, #ef4444)":(tt=dt==null?void 0:dt.backgroundColor)!=null?tt:"",U=(Be=c.speakingBorderColor)!=null?Be:g==="barge-in"?(mt=c.recordingBorderColor)!=null?mt:"":(We=dt==null?void 0:dt.borderColor)!=null?We:"";Do(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=$,N.style.borderColor=U;let X=D||"currentColor";N.style.color=X,fa(C,X);let _=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",_),g==="none"&&(N.style.cursor="default"),g==="barge-in"&&N.classList.add("persona-voice-recording")},Wn=()=>{var c,g,y;N&&(Do(),dt&&(N.style.backgroundColor=(c=dt.backgroundColor)!=null?c:"",N.style.color=(g=dt.color)!=null?g:"",N.style.borderColor=(y=dt.borderColor)!=null?y:"",fa(dt.iconName,dt.color||"currentColor"),dt=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},Qn=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let y=q.getVoiceStatus(),C=q.getVoiceInterruptionMode();if(C==="none"&&(y==="processing"||y==="speaking"))return;if(C==="cancel"&&(y==="processing"||y==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()});return}q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bt.manuallyDeactivated=!q.isVoiceActive(),Qr(),bn("user"),q.isVoiceActive()?Co():Wn()});return}if(dn){let y=ne.value.trim();bt.manuallyDeactivated=!0,Qr(),Bn("user"),y&&(ne.value="",ne.style.height="auto",q.sendMessage(y))}else bt.manuallyDeactivated=!1,Qr(),Wo("user")};hn=Qn,N&&(N.addEventListener("click",Qn),vt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Wn()):Bn("system"),N&&N.removeEventListener("click",Qn)}));let Ze=a.on("assistant:complete",()=>{Na&&(bt.active||bt.manuallyDeactivated||Na==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!bt.active&&!bt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("auto"),q.isVoiceActive()&&Co()}):Wo("auto"))},600))});vt.push(Ze);let P=a.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});vt.push(P);let z=()=>{Nt(!R,"user")},I=null,V=null;if(T&&!O()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});g&&(V=g)}V||(I=Ms(n,z))}I?e.appendChild(I.element):V&&e.appendChild(V),bo(),Ln.render(n.suggestionChips,q,ne,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming()),go(!0),$s(),E&&(!T||O()?setTimeout(()=>pa(),0):R&&setTimeout(()=>pa(),200));let fe=()=>{var _,Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be,Je,W,Re,Ne,Qe,Ae,Dt,pt,cr;if(O()){Rr(),bo();return}let c=hr(n),g=(Te=(_=n.launcher)==null?void 0:_.sidebarMode)!=null?Te:!1,y=c||g||((re=(me=n.launcher)==null?void 0:me.fullHeight)!=null?re:!1),C=(be=e.ownerDocument.defaultView)!=null?be:window,D=(Ve=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?Ve:!0,$=(tt=(lt=n.launcher)==null?void 0:lt.mobileBreakpoint)!=null?tt:640,U=C.innerWidth<=$,X=D&&U&&T;try{if(X){Mn(),vo(e,n);return}if(L&&(L=!1,Mn(),vo(e,n)),!T&&!c){G.style.height="",G.style.width="";return}if(!g&&!c){let Lr=(mt=(ft=n==null?void 0:n.launcher)==null?void 0:ft.width)!=null?mt:n==null?void 0:n.launcherWidth,Ft=Lr!=null?Lr:mn;G.style.width=Ft,G.style.maxWidth=Ft}if(Fn(),!y){let Lr=C.innerHeight,Ft=64,Ur=(Be=(We=n.launcher)==null?void 0:We.heightOffset)!=null?Be:0,Pr=Math.max(200,Lr-Ft),st=Math.min(640,Pr),gt=Math.max(200,st-Ur);G.style.height=`${gt}px`}}finally{if(Rr(),bo(),R&&T){let Ft=((Je=e.ownerDocument.defaultView)!=null?Je:window).innerWidth<=((Re=(W=n.launcher)==null?void 0:W.mobileBreakpoint)!=null?Re:640),Ur=(Qe=(Ne=n.launcher)==null?void 0:Ne.sidebarMode)!=null?Qe:!1,Pr=(Dt=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Dt:!0,st=hr(n)&&Pr&&Ft,gt=Ur||Pr&&Ft&&T||st;if(gt&&!ir){let qr=e.getRootNode(),Br=qr instanceof ShadowRoot?qr.host:e.closest(".persona-host");Br&&!sr&&(sr=ip(Br,(cr=(pt=n.launcher)==null?void 0:pt.zIndex)!=null?cr:Or)),ir=lp(e.ownerDocument)}else gt||(sr==null||sr(),sr=null,ir==null||ir(),ir=null)}}};fe();let te=(Fu=e.ownerDocument.defaultView)!=null?Fu:window;if(te.addEventListener("resize",fe),vt.push(()=>te.removeEventListener("resize",fe)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Rr()});c.observe(qe),vt.push(()=>c.disconnect())}Rn=ve.scrollTop;let et=ve.scrollHeight,ze=()=>{let c=ve.scrollTop,g=ve.scrollHeight,y=g<et;et=g;let{action:C,nextLastScrollTop:D}=Ki({following:In.isFollowing(),currentScrollTop:c,lastScrollTop:Rn,nearBottom:ws(ve,Fa),userScrollThreshold:Ns,isAutoScrolling:Gn||Ro||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Rn=D,C==="resume"){mo();return}C==="pause"&&$a()};ve.addEventListener("scroll",ze,{passive:!0}),vt.push(()=>ve.removeEventListener("scroll",ze));let ct=c=>{let g=Yi({following:In.isFollowing(),deltaY:c.deltaY,nearBottom:ws(ve,Fa),resumeWhenNearBottom:!0});g==="pause"?$a():g==="resume"&&mo()};ve.addEventListener("wheel",ct,{passive:!0}),vt.push(()=>ve.removeEventListener("wheel",ct)),it.addEventListener("click",()=>{ve.scrollTop=ve.scrollHeight,Rn=ve.scrollTop,mo(),go(!0)}),vt.push(()=>it.remove()),vt.push(()=>{_a()});let at=()=>{F&&(sn&&(F.removeEventListener("click",sn),sn=null),H()?(F.style.display="",sn=()=>{Nt(!1,"user")},F.addEventListener("click",sn)):F.style.display="none")};at(),(()=>{let{clearChatButton:c}=ke;c&&c.addEventListener("click",()=>{q.clearMessages(),ln.clear(),mo(),Lo(ke.composerOverlay);try{localStorage.removeItem(Wa),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wa)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(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},k.syncFromMetadata(),J==null||J.clear(),ce==null||ce.update()})})(),Ot&&Ot.addEventListener("submit",Ga),ne==null||ne.addEventListener("keydown",Xa),ne==null||ne.addEventListener("paste",Ja);let Gt="persona-attachment-drop-active",lr=0,Rt=()=>{lr=0,ae.classList.remove(Gt)},Lt=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&Tt!==null},yr=c=>{!Sl(c.dataTransfer)||!Lt()||(lr++,lr===1&&ae.classList.add(Gt))},Hr=c=>{!Sl(c.dataTransfer)||!Lt()||(lr--,lr<=0&&Rt())},Mr=c=>{!Sl(c.dataTransfer)||!Lt()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},dr=c=>{var y;if(!Sl(c.dataTransfer)||!Lt())return;c.preventDefault(),c.stopPropagation(),Rt();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&Tt.handleFiles(g)},vr=!0;ae.addEventListener("dragenter",yr,vr),ae.addEventListener("dragleave",Hr,vr),e.addEventListener("dragover",Mr,vr),e.addEventListener("drop",dr,vr);let ei=e.ownerDocument,Kp=c=>{Lt()&&c.preventDefault()},Yp=c=>{Lt()&&c.preventDefault()};ei.addEventListener("dragover",Kp),ei.addEventListener("drop",Yp),vt.push(()=>{Ot&&Ot.removeEventListener("submit",Ga),ne==null||ne.removeEventListener("keydown",Xa),ne==null||ne.removeEventListener("paste",Ja)}),vt.push(()=>{ae.removeEventListener("dragenter",yr,vr),ae.removeEventListener("dragleave",Hr,vr),e.removeEventListener("dragover",Mr,vr),e.removeEventListener("drop",dr,vr),ei.removeEventListener("dragover",Kp),ei.removeEventListener("drop",Yp),Rt()}),vt.push(()=>{q.cancel()}),I?vt.push(()=>{I==null||I.destroy()}):V&&vt.push(()=>{V==null||V.remove()});let mr={update(c){var gr,$n,eo,ti,ri,ni,$o,oi,Ya,Vu,ju,Gu,Xu,Ju,Ku,Yu,Qu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,Cf,wf,vf,Af,Sf,Tf,kf,Ef,Mf,Lf,Pf,If,Rf,Hf,Bf,Wf,Df,Of,Ff,Nf,_f,$f,Uf,qf,zf,Vf,jf,Gf,Xf,Jf,Kf,Yf,Qf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,Cm,wm,vm,Am,Sm,Tm,km,Em,Mm,Lm,Pm,Im,Rm,Hm,Bm,Wm,Dm,Om,Fm,Nm,_m,$m;let g=n.toolCall,y=n.messageActions,C=(gr=n.layout)==null?void 0:gr.messages,D=n.colorScheme,$=n.loadingIndicator,U=n.iterationDisplay,X=($n=n.features)==null?void 0:$n.showReasoning,_=(eo=n.features)==null?void 0:eo.showToolCalls,Te=(ti=n.features)==null?void 0:ti.toolCallDisplay,me=(ri=n.features)==null?void 0:ri.reasoningDisplay;n={...n,...c},Mn(),vo(e,n),gl(e,n),hl(e,n),on(),n.colorScheme!==D&&fo();let re=Bs.getForInstance(n.plugins);o.length=0,o.push(...re),T=($o=(ni=n.launcher)==null?void 0:ni.enabled)!=null?$o:!0,A=(Ya=(oi=n.launcher)==null?void 0:oi.autoExpand)!=null?Ya:!1,De=(ju=(Vu=n.features)==null?void 0:Vu.showReasoning)!=null?ju:!0,Xe=(Xu=(Gu=n.features)==null?void 0:Gu.showToolCalls)!=null?Xu:!0,ge=(Ku=(Ju=n.features)==null?void 0:Ju.scrollToBottom)!=null?Ku:{},Tn(),Jn();let be=xe;if(xe=(Qu=(Yu=n.features)==null?void 0:Yu.showEventStreamToggle)!=null?Qu:!1,xe&&!be){if(J||(Q=new Hs(Ge),J=new Rs(Se,Q),Q.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),q.setSSEEventCallback((ee,Ht)=>{var Xt;(Xt=n.onSSEEvent)==null||Xt.call(n,ee,Ht),J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Ht)})})),!xt&&Ue){let ee=(ef=(Zu=n.features)==null?void 0:Zu.eventStream)==null?void 0:ef.classNames,Ht="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"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");xt=x("button",Ht),xt.style.width="28px",xt.style.height="28px",xt.style.color=Kr.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Xt=Ce("activity","18px","currentColor",1.5);Xt&&xt.appendChild(Xt);let ht=ke.clearChatButtonWrapper,Wt=ke.closeButtonWrapper,br=ht||Wt;br&&br.parentNode===Ue?Ue.insertBefore(xt,br):Ue.appendChild(xt),xt.addEventListener("click",()=>{pe?Yr():Sr()})}}else!xe&&be&&(Yr(),xt&&(xt.remove(),xt=null),J==null||J.clear(),Q==null||Q.destroy(),J=null,Q=null);if(((tf=n.launcher)==null?void 0:tf.enabled)===!1&&I&&(I.destroy(),I=null),((rf=n.launcher)==null?void 0:rf.enabled)===!1&&V&&(V.remove(),V=null),((nf=n.launcher)==null?void 0:nf.enabled)!==!1&&!I&&!V){let ee=o.find(Ht=>Ht.renderLauncher);if(ee!=null&&ee.renderLauncher){let Ht=ee.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});Ht&&(V=Ht,e.appendChild(V))}V||(I=Ms(n,z),e.appendChild(I.element))}I&&I.update(n),Fe&&((of=n.launcher)==null?void 0:of.title)!==void 0&&(Fe.textContent=n.launcher.title),Ke&&((af=n.launcher)==null?void 0:af.subtitle)!==void 0&&(Ke.textContent=n.launcher.subtitle);let Me=(sf=n.layout)==null?void 0:sf.header;if((Me==null?void 0:Me.layout)!==S&&Ue){let ee=Me?Ta(n,Me,{showClose:H(),onClose:()=>Nt(!1,"user")}):ao({config:n,showClose:H(),onClose:()=>Nt(!1,"user")});Ue.replaceWith(ee.header),Ue=ee.header,le=ee.iconHolder,Fe=ee.headerTitle,Ke=ee.headerSubtitle,F=ee.closeButton,S=Me==null?void 0:Me.layout}else if(Me&&(le&&(le.style.display=Me.showIcon===!1?"none":""),Fe&&(Fe.style.display=Me.showTitle===!1?"none":""),Ke&&(Ke.style.display=Me.showSubtitle===!1?"none":""),F&&(F.style.display=Me.showCloseButton===!1?"none":""),ke.clearChatButtonWrapper)){let ee=Me.showClearChat;if(ee!==void 0){ke.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ht}=ke;Ht&&!Ht.classList.contains("persona-absolute")&&(ee?Ht.classList.remove("persona-ml-auto"):Ht.classList.add("persona-ml-auto"))}}let lt=((lf=n.layout)==null?void 0:lf.showHeader)!==!1;Ue&&(Ue.style.display=lt?"":"none");let tt=((df=n.layout)==null?void 0:df.showFooter)!==!1;qe&&(qe.style.display=tt?"":"none"),Rr(),Jn(),T!==h?T?Nt(A,"auto"):(R=!0,bo()):A!==b&&Nt(A,"auto"),b=A,h=T,fe(),at();let We=JSON.stringify(c.toolCall)!==JSON.stringify(g),Be=JSON.stringify(n.messageActions)!==JSON.stringify(y),Je=JSON.stringify((cf=n.layout)==null?void 0:cf.messages)!==JSON.stringify(C),W=((pf=n.loadingIndicator)==null?void 0:pf.render)!==($==null?void 0:$.render)||((uf=n.loadingIndicator)==null?void 0:uf.renderIdle)!==($==null?void 0:$.renderIdle)||((ff=n.loadingIndicator)==null?void 0:ff.showBubble)!==($==null?void 0:$.showBubble),Re=n.iterationDisplay!==U,Ne=((gf=(mf=n.features)==null?void 0:mf.showReasoning)!=null?gf:!0)!==(X!=null?X:!0)||((xf=(hf=n.features)==null?void 0:hf.showToolCalls)!=null?xf:!0)!==(_!=null?_:!0)||JSON.stringify((yf=n.features)==null?void 0:yf.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((bf=n.features)==null?void 0:bf.reasoningDisplay)!==JSON.stringify(me);(We||Be||Je||W||Re||Ne)&&q&&(Oa++,Bo(ye,q.getMessages(),ue));let Ae=(Cf=n.launcher)!=null?Cf:{},Dt=(wf=Ae.headerIconHidden)!=null?wf:!1,pt=(Af=(vf=n.layout)==null?void 0:vf.header)==null?void 0:Af.showIcon,cr=Dt||pt===!1,Lr=Ae.headerIconName,Ft=(Sf=Ae.headerIconSize)!=null?Sf:"48px";if(le){let ee=ae.querySelector(".persona-border-b-persona-divider"),Ht=ee==null?void 0:ee.querySelector(".persona-flex-col");if(cr)le.style.display="none",ee&&Ht&&!ee.contains(Ht)&&ee.insertBefore(Ht,ee.firstChild);else{if(le.style.display="",le.style.height=Ft,le.style.width=Ft,ee&&Ht&&(ee.contains(le)?le.nextSibling!==Ht&&(le.remove(),ee.insertBefore(le,Ht)):ee.insertBefore(le,Ht)),Lr){let ht=parseFloat(Ft)||24,Wt=Ce(Lr,ht*.6,"#ffffff",2);Wt?le.replaceChildren(Wt):le.textContent=(Tf=Ae.agentIconText)!=null?Tf:"\u{1F4AC}"}else if(Ae.iconUrl){let ht=le.querySelector("img");if(ht)ht.src=Ae.iconUrl,ht.style.height=Ft,ht.style.width=Ft;else{let Wt=document.createElement("img");Wt.src=Ae.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=Ft,Wt.style.width=Ft,le.replaceChildren(Wt)}}else{let ht=le.querySelector("svg"),Wt=le.querySelector("img");(ht||Wt)&&le.replaceChildren(),le.textContent=(kf=Ae.agentIconText)!=null?kf:"\u{1F4AC}"}let Xt=le.querySelector("img");Xt&&(Xt.style.height=Ft,Xt.style.width=Ft)}}let Ur=(Mf=(Ef=n.layout)==null?void 0:Ef.header)==null?void 0:Mf.showTitle,Pr=(Pf=(Lf=n.layout)==null?void 0:Lf.header)==null?void 0:Pf.showSubtitle;if(Fe&&(Fe.style.display=Ur===!1?"none":""),Ke&&(Ke.style.display=Pr===!1?"none":""),F){((Rf=(If=n.layout)==null?void 0:If.header)==null?void 0:Rf.showCloseButton)===!1?F.style.display="none":F.style.display="";let Ht=(Hf=Ae.closeButtonSize)!=null?Hf:"32px",Xt=(Bf=Ae.closeButtonPlacement)!=null?Bf:"inline";F.style.height=Ht,F.style.width=Ht;let{closeButtonWrapper:ht}=ke,Wt=Xt==="top-right",br=ht==null?void 0:ht.classList.contains("persona-absolute");if(ht&&Wt!==br)if(ht.remove(),Wt)ht.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ae.style.position="relative",ae.appendChild(ht);else{let yt=(Df=(Wf=Ae.clearChat)==null?void 0:Wf.placement)!=null?Df:"inline",Cr=(Ff=(Of=Ae.clearChat)==null?void 0:Of.enabled)!=null?Ff:!0;ht.className=Cr&&yt==="inline"?"":"persona-ml-auto";let rn=ae.querySelector(".persona-border-b-persona-divider");rn&&rn.appendChild(ht)}if(F.style.color=Ae.closeButtonColor||Kr.actionIconColor,Ae.closeButtonBackgroundColor?(F.style.backgroundColor=Ae.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),Ae.closeButtonBorderWidth||Ae.closeButtonBorderColor){let yt=Ae.closeButtonBorderWidth||"0px",Cr=Ae.closeButtonBorderColor||"transparent";F.style.border=`${yt} solid ${Cr}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");Ae.closeButtonBorderRadius?(F.style.borderRadius=Ae.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),Ae.closeButtonPaddingX?(F.style.paddingLeft=Ae.closeButtonPaddingX,F.style.paddingRight=Ae.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),Ae.closeButtonPaddingY?(F.style.paddingTop=Ae.closeButtonPaddingY,F.style.paddingBottom=Ae.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Wr=(Nf=Ae.closeButtonIconName)!=null?Nf:"x",Dn=(_f=Ae.closeButtonIconText)!=null?_f:"\xD7";F.innerHTML="";let Vr=Ce(Wr,"28px","currentColor",1);Vr?F.appendChild(Vr):F.textContent=Dn;let pr=($f=Ae.closeButtonTooltipText)!=null?$f:"Close chat",pn=(Uf=Ae.closeButtonShowTooltip)!=null?Uf:!0;if(F.setAttribute("aria-label",pr),ht&&(ht._cleanupTooltip&&(ht._cleanupTooltip(),delete ht._cleanupTooltip),pn&&pr)){let yt=null,Cr=()=>{if(yt||!F)return;let Uo=F.ownerDocument,Qa=Uo.body;if(!Qa)return;yt=qn(Uo,"div","persona-clear-chat-tooltip"),yt.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",yt.appendChild(Za);let qo=F.getBoundingClientRect();yt.style.position="fixed",yt.style.zIndex=String(Ao),yt.style.left=`${qo.left+qo.width/2}px`,yt.style.top=`${qo.top-8}px`,yt.style.transform="translate(-50%, -100%)",Qa.appendChild(yt)},rn=()=>{yt&&yt.parentNode&&(yt.parentNode.removeChild(yt),yt=null)};ht.addEventListener("mouseenter",Cr),ht.addEventListener("mouseleave",rn),F.addEventListener("focus",Cr),F.addEventListener("blur",rn),ht._cleanupTooltip=()=>{rn(),ht&&(ht.removeEventListener("mouseenter",Cr),ht.removeEventListener("mouseleave",rn)),F&&(F.removeEventListener("focus",Cr),F.removeEventListener("blur",rn))}}}let{clearChatButton:st,clearChatButtonWrapper:gt}=ke;if(st){let ee=(qf=Ae.clearChat)!=null?qf:{},Ht=(zf=ee.enabled)!=null?zf:!0,Xt=(jf=(Vf=n.layout)==null?void 0:Vf.header)==null?void 0:jf.showClearChat,ht=Xt!==void 0?Xt:Ht,Wt=(Gf=ee.placement)!=null?Gf:"inline";if(gt){gt.style.display=ht?"":"none";let{closeButtonWrapper:br}=ke;!O()&&br&&!br.classList.contains("persona-absolute")&&(ht?br.classList.remove("persona-ml-auto"):br.classList.add("persona-ml-auto"));let Wr=Wt==="top-right",Dn=gt.classList.contains("persona-absolute");if(!O()&&Wr!==Dn&&ht){if(gt.remove(),Wr)gt.className="persona-absolute persona-top-4 persona-z-50",gt.style.right="48px",ae.style.position="relative",ae.appendChild(gt);else{gt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gt.style.right="";let pr=ae.querySelector(".persona-border-b-persona-divider"),pn=ke.closeButtonWrapper;pr&&pn&&pn.parentElement===pr?pr.insertBefore(gt,pn):pr&&pr.appendChild(gt)}let Vr=ke.closeButtonWrapper;Vr&&!Vr.classList.contains("persona-absolute")&&(Wr?Vr.classList.add("persona-ml-auto"):Vr.classList.remove("persona-ml-auto"))}}if(ht){if(!O()){let yt=(Xf=ee.size)!=null?Xf:"32px";st.style.height=yt,st.style.width=yt}let br=(Jf=ee.iconName)!=null?Jf:"refresh-cw",Wr=(Kf=ee.iconColor)!=null?Kf:"";st.style.color=Wr||Kr.actionIconColor,st.innerHTML="";let Dn=O()?"14px":"20px",Vr=Ce(br,Dn,"currentColor",2);if(Vr&&st.appendChild(Vr),ee.backgroundColor?(st.style.backgroundColor=ee.backgroundColor,st.classList.remove("hover:persona-bg-gray-100")):(st.style.backgroundColor="",st.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let yt=ee.borderWidth||"0px",Cr=ee.borderColor||"transparent";st.style.border=`${yt} solid ${Cr}`,st.classList.remove("persona-border-none")}else st.style.border="",st.classList.add("persona-border-none");ee.borderRadius?(st.style.borderRadius=ee.borderRadius,st.classList.remove("persona-rounded-full")):(st.style.borderRadius="",st.classList.add("persona-rounded-full")),ee.paddingX?(st.style.paddingLeft=ee.paddingX,st.style.paddingRight=ee.paddingX):(st.style.paddingLeft="",st.style.paddingRight=""),ee.paddingY?(st.style.paddingTop=ee.paddingY,st.style.paddingBottom=ee.paddingY):(st.style.paddingTop="",st.style.paddingBottom="");let pr=(Yf=ee.tooltipText)!=null?Yf:"Clear chat",pn=(Qf=ee.showTooltip)!=null?Qf:!0;if(st.setAttribute("aria-label",pr),gt&&(gt._cleanupTooltip&&(gt._cleanupTooltip(),delete gt._cleanupTooltip),pn&&pr)){let yt=null,Cr=()=>{if(yt||!st)return;let Uo=st.ownerDocument,Qa=Uo.body;if(!Qa)return;yt=qn(Uo,"div","persona-clear-chat-tooltip"),yt.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",yt.appendChild(Za);let qo=st.getBoundingClientRect();yt.style.position="fixed",yt.style.zIndex=String(Ao),yt.style.left=`${qo.left+qo.width/2}px`,yt.style.top=`${qo.top-8}px`,yt.style.transform="translate(-50%, -100%)",Qa.appendChild(yt)},rn=()=>{yt&&yt.parentNode&&(yt.parentNode.removeChild(yt),yt=null)};gt.addEventListener("mouseenter",Cr),gt.addEventListener("mouseleave",rn),st.addEventListener("focus",Cr),st.addEventListener("blur",rn),gt._cleanupTooltip=()=>{rn(),gt&&(gt.removeEventListener("mouseenter",Cr),gt.removeEventListener("mouseleave",rn)),st&&(st.removeEventListener("focus",Cr),st.removeEventListener("blur",rn))}}}}let qr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ws],Br=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[sa.message,sa.messageAndClick];k=Ds({parsers:qr,handlers:Br,getSessionMetadata:m,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),ue=Uh(n,k,oe),q.updateConfig(n),Bo(ye,q.getMessages(),ue),Ln.render(n.suggestionChips,q,ne,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming());let Oo=((Zf=n.voiceRecognition)==null?void 0:Zf.enabled)===!0,Fo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),No=((tm=(em=n.voiceRecognition)==null?void 0:em.provider)==null?void 0:tm.type)==="runtype";if(Oo&&(Fo||No))if(!N||!de){let ee=Ys(n.voiceRecognition,n.sendButton);ee&&(N=ee.micButton,de=ee.micButtonWrapper,Pt.insertBefore(de,fr),N.addEventListener("click",Qn),N.disabled=q.isStreaming())}else{let ee=(rm=n.voiceRecognition)!=null?rm:{},Ht=(nm=n.sendButton)!=null?nm:{},Xt=(om=ee.iconName)!=null?om:"mic",ht=(am=Ht.size)!=null?am:"40px",Wt=(sm=ee.iconSize)!=null?sm:ht,br=parseFloat(Wt)||24;N.style.width=Wt,N.style.height=Wt,N.style.minWidth=Wt,N.style.minHeight=Wt;let Wr=(lm=(im=ee.iconColor)!=null?im:Ht.textColor)!=null?lm:"currentColor";N.innerHTML="";let Dn=Ce(Xt,br,Wr,2);Dn?N.appendChild(Dn):N.textContent="\u{1F3A4}";let Vr=(dm=ee.backgroundColor)!=null?dm:Ht.backgroundColor;Vr?N.style.backgroundColor=Vr:N.style.backgroundColor="",Wr?N.style.color=Wr:N.style.color="var(--persona-text, #111827)",ee.borderWidth?(N.style.borderWidth=ee.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),ee.borderColor?N.style.borderColor=ee.borderColor:N.style.borderColor="",ee.paddingX?(N.style.paddingLeft=ee.paddingX,N.style.paddingRight=ee.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),ee.paddingY?(N.style.paddingTop=ee.paddingY,N.style.paddingBottom=ee.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let pr=de==null?void 0:de.querySelector(".persona-send-button-tooltip"),pn=(cm=ee.tooltipText)!=null?cm:"Start voice recognition";if(((pm=ee.showTooltip)!=null?pm:!1)&&pn)if(pr)pr.textContent=pn,pr.style.display="";else{let Cr=document.createElement("div");Cr.className="persona-send-button-tooltip",Cr.textContent=pn,de==null||de.insertBefore(Cr,N)}else pr&&(pr.style.display="none");de.style.display="",N.disabled=q.isStreaming()}else N&&de&&(de.style.display="none",((fm=(um=n.voiceRecognition)==null?void 0:um.provider)==null?void 0:fm.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():dn&&Bn());if(((mm=n.attachments)==null?void 0:mm.enabled)===!0)if(!ut||!Ee){let ee=(gm=n.attachments)!=null?gm:{},Xt=(xm=((hm=n.sendButton)!=null?hm:{}).size)!=null?xm:"40px";Ut||(Ut=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",Ot.insertBefore(Ut,ne)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((ym=ee.allowedTypes)!=null?ym:oo).join(","),Ye.multiple=((bm=ee.maxFiles)!=null?bm:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),Ot.insertBefore(Ye,ne)),ut=x("div","persona-send-button-wrapper"),Ee=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ee.type="button",Ee.setAttribute("aria-label",(Cm=ee.buttonTooltipText)!=null?Cm:"Attach file");let ht=(wm=ee.buttonIconName)!=null?wm:"paperclip",Wt=Xt,br=parseFloat(Wt)||40,Wr=Math.round(br*.6);Ee.style.width=Wt,Ee.style.height=Wt,Ee.style.minWidth=Wt,Ee.style.minHeight=Wt,Ee.style.fontSize="18px",Ee.style.lineHeight="1",Ee.style.backgroundColor="transparent",Ee.style.color="var(--persona-primary, #111827)",Ee.style.border="none",Ee.style.borderRadius="6px",Ee.style.transition="background-color 0.15s ease",Ee.addEventListener("mouseenter",()=>{Ee.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ee.addEventListener("mouseleave",()=>{Ee.style.backgroundColor="transparent"});let Dn=Ce(ht,Wr,"currentColor",1.5);Dn?Ee.appendChild(Dn):Ee.textContent="\u{1F4CE}",Ee.addEventListener("click",pn=>{pn.preventDefault(),Ye==null||Ye.click()}),ut.appendChild(Ee);let Vr=(vm=ee.buttonTooltipText)!=null?vm:"Attach file",pr=x("div","persona-send-button-tooltip");pr.textContent=Vr,ut.appendChild(pr),Ct.append(ut),!Tt&&Ye&&Ut&&(Tt=ta.fromConfig(ee),Tt.setPreviewsContainer(Ut),Ye.addEventListener("change",async()=>{Tt&&(Ye!=null&&Ye.files)&&(await Tt.handleFileSelect(Ye.files),Ye.value="")})),ae.querySelector(".persona-attachment-drop-overlay")||ae.appendChild(qh(ee.dropOverlay))}else{ut.style.display="";let ee=(Am=n.attachments)!=null?Am:{};Ye&&(Ye.accept=((Sm=ee.allowedTypes)!=null?Sm:oo).join(","),Ye.multiple=((Tm=ee.maxFiles)!=null?Tm:4)>1),Tt&&Tt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ut&&(ut.style.display="none"),Tt&&Tt.clearAttachments(),(km=ae.querySelector(".persona-attachment-drop-overlay"))==null||km.remove();let rr=(Em=n.sendButton)!=null?Em:{},_o=(Mm=rr.useIcon)!=null?Mm:!1,wo=(Lm=rr.iconText)!=null?Lm:"\u2191",Et=rr.iconName,Zr=(Pm=rr.tooltipText)!=null?Pm:"Send message",Zn=(Im=rr.showTooltip)!=null?Im:!1,zr=(Rm=rr.size)!=null?Rm:"40px",en=rr.backgroundColor,zt=rr.textColor;if(_o){if(He.style.width=zr,He.style.height=zr,He.style.minWidth=zr,He.style.minHeight=zr,He.style.fontSize="18px",He.style.lineHeight="1",He.innerHTML="",zt?He.style.color=zt:He.style.color="var(--persona-button-primary-fg, #ffffff)",Et){let ee=parseFloat(zr)||24,Ht=(zt==null?void 0:zt.trim())||"currentColor",Xt=Ce(Et,ee,Ht,2);Xt?He.appendChild(Xt):He.textContent=wo}else He.textContent=wo;He.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",en?(He.style.backgroundColor=en,He.classList.remove("persona-bg-persona-primary")):(He.style.backgroundColor="",He.classList.add("persona-bg-persona-primary"))}else He.textContent=(Bm=(Hm=n.copy)==null?void 0:Hm.sendButtonLabel)!=null?Bm:"Send",He.style.width="",He.style.height="",He.style.minWidth="",He.style.minHeight="",He.style.fontSize="",He.style.lineHeight="",He.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",en?(He.style.backgroundColor=en,He.classList.remove("persona-bg-persona-accent")):He.classList.add("persona-bg-persona-accent"),zt?He.style.color=zt:He.classList.add("persona-text-white");rr.borderWidth?(He.style.borderWidth=rr.borderWidth,He.style.borderStyle="solid"):(He.style.borderWidth="",He.style.borderStyle=""),rr.borderColor?He.style.borderColor=rr.borderColor:He.style.borderColor="",rr.paddingX?(He.style.paddingLeft=rr.paddingX,He.style.paddingRight=rr.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),rr.paddingY?(He.style.paddingTop=rr.paddingY,He.style.paddingBottom=rr.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Zt=fr==null?void 0:fr.querySelector(".persona-send-button-tooltip");if(Zn&&Zr)if(Zt)Zt.textContent=Zr,Zt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=Zr,fr==null||fr.insertBefore(ee,He)}else Zt&&(Zt.style.display="none");let Vt=(Nm=(Wm=n.layout)==null?void 0:Wm.contentMaxWidth)!=null?Nm:O()?(Fm=(Om=(Dm=n.launcher)==null?void 0:Dm.composerBar)==null?void 0:Om.contentMaxWidth)!=null?Fm:"720px":void 0;Vt?(ye.style.maxWidth=Vt,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",Ot&&(Ot.style.maxWidth=Vt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=Vt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(ye.style.maxWidth="",ye.style.marginLeft="",ye.style.marginRight="",ye.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let nr=(_m=n.statusIndicator)!=null?_m:{},tn=($m=nr.visible)!=null?$m:!0;if(Yt.style.display=tn?"":"none",q){let ee=q.getStatus();$e(Yt,(Xt=>{var ht,Wt,br,Wr;return Xt==="idle"?(ht=nr.idleText)!=null?ht:Dr.idle:Xt==="connecting"?(Wt=nr.connectingText)!=null?Wt:Dr.connecting:Xt==="connected"?(br=nr.connectedText)!=null?br:Dr.connected:Xt==="error"?(Wr=nr.errorText)!=null?Wr:Dr.error:Dr[Xt]})(ee),nr,ee)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let cn=nr.align==="left"?"persona-text-left":nr.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(cn)},open(){H()&&Nt(!0,"api")},close(){H()&&Nt(!1,"api")},toggle(){H()&&Nt(!R,"api")},clearChat(){Z=!1,q.clearMessages(),ln.clear(),mo();try{localStorage.removeItem(Wa),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wa)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={},k.syncFromMetadata(),J==null||J.clear(),ce==null||ce.update()},setMessage(c){return!ne||q.isStreaming()?!1:(!R&&H()&&Nt(!0,"system"),ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ne.value.trim();return g?(!R&&H()&&Nt(!0,"system"),ne.value="",ne.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()||(!R&&H()&&Nt(!0,"system"),bt.manuallyDeactivated=!1,Qr(),q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("user"),q.isVoiceActive()&&Co()})),!0):dn?!0:Ka()?(!R&&H()&&Nt(!0,"system"),bt.manuallyDeactivated=!1,Qr(),Wo("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(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()}),!0):!1:dn?(bt.manuallyDeactivated=!0,Qr(),Bn("user"),!0):!1},injectMessage(c){return!R&&H()&&Nt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!R&&H()&&Nt(!0,"system");let g=q.injectAssistantMessage(c);return B&&(B=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!R&&H()&&Nt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!R&&H()&&Nt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!R&&H()&&Nt(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!R&&H()&&Nt(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!R&&H()&&Nt(!0,"system"),q.injectTestEvent(c)},async connectStream(c,g){return q.connectStream(c,g)},__pushEventStreamEvent(c){J&&J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!xe||!J||Sr()},hideEventStream(){pe&&Yr()},isEventStreamVisible(){return pe},showArtifacts(){Sn(n)&&(Z=!1,on(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){Sn(n)&&(Z=!0,on())},upsertArtifact(c){return Sn(n)?(Z=!1,q.upsertArtifact(c)):null},selectArtifact(c){Sn(n)&&q.selectArtifact(c)},clearArtifacts(){Sn(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&&!R&&!O()||!ne?!1:(ne.focus(),!0)},async resolveApproval(c,g){let C=q.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===c});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${c}`);return q.resolveApproval(C.approval,g)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){f(c)},on(c,g){return a.on(c,g)},off(c,g){a.off(c,g)},isOpen(){return H()&&R},isVoiceActive(){return bt.active},getState(){return{open:H()&&R,launcherEnabled:T,voiceActive:bt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!R&&H()&&Nt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let y=vl({onSubmit:async(C,D)=>{var $;q.isClientTokenMode()&&await q.submitCSATFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ye.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&H()&&Nt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let y=Al({onSubmit:async(C,D)=>{var $;q.isClientTokenMode()&&await q.submitNPSFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ye.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(){_n!=null&&(clearInterval(_n),_n=null),vt.forEach(c=>c()),Y.remove(),we==null||we.remove(),I==null||I.destroy(),V==null||V.remove(),sn&&F.removeEventListener("click",sn)}};if((((Nu=t==null?void 0:t.debugTools)!=null?Nu:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:mr,getMessages:mr.getMessages,getStatus:mr.getStatus,getMetadata:mr.getPersistentMetadata,updateMetadata:mr.updatePersistentMetadata,clearHistory:()=>mr.clearChat(),setVoiceActive:y=>y?mr.startVoiceRecognition():mr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,vt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.focusInput()};if(window.addEventListener("persona:focusInput",g),vt.push(()=>{window.removeEventListener("persona:focusInput",g)}),xe){let X=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&mr.showEventStream()},_=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&mr.hideEventStream()};window.addEventListener("persona:showEventStream",X),window.addEventListener("persona:hideEventStream",_),vt.push(()=>{window.removeEventListener("persona:showEventStream",X),window.removeEventListener("persona:hideEventStream",_)})}let y=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.showArtifacts()},C=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.hideArtifacts()},D=X=>{let _=X.detail;_!=null&&_.instanceId&&_.instanceId!==c||_!=null&&_.artifact&&mr.upsertArtifact(_.artifact)},$=X=>{let _=X.detail;_!=null&&_.instanceId&&_.instanceId!==c||typeof(_==null?void 0:_.id)=="string"&&mr.selectArtifact(_.id)},U=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),vt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let Cn=X0(n.persistState);if(Cn&&H()){let c=J0(Cn.storage),g=`${Cn.keyPrefix}widget-open`,y=`${Cn.keyPrefix}widget-voice`,C=`${Cn.keyPrefix}widget-voice-mode`;if(c){let D=((_u=Cn.persist)==null?void 0:_u.openState)&&c.getItem(g)==="true",$=(($u=Cn.persist)==null?void 0:$u.voiceState)&&c.getItem(y)==="true",U=((Uu=Cn.persist)==null?void 0:Uu.voiceState)&&c.getItem(C)==="true";if(D&&setTimeout(()=>{mr.open(),setTimeout(()=>{var X;if($||U)mr.startVoiceRecognition();else if((X=Cn.persist)!=null&&X.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(qu=Cn.persist)!=null&&qu.openState&&(a.on("widget:opened",()=>{c.setItem(g,"true")}),a.on("widget:closed",()=>{c.setItem(g,"false")})),(zu=Cn.persist)!=null&&zu.voiceState&&(a.on("voice:state",X=>{c.setItem(y,X.active?"true":"false")}),a.on("user:message",X=>{c.setItem(C,X.viaVoice?"true":"false")})),Cn.clearOnChatClear){let X=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(C)},_=()=>X();window.addEventListener("persona:clear-chat",_),vt.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&H()&&setTimeout(()=>{mr.open()},0),Kn(),mr};var K0=(e,r)=>{let t=e.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,r*parseFloat(o[1])/100):420},zh=(e,r)=>{var n,o;let t=(o=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?o:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Wp=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Vh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Wp(e)},Rp=e=>{e.style.transition=""},Hp=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Bp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},kl=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Y0=(e,r,t,n,o)=>{o?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},Q0=(e,r,t,n,o,a)=>{let s=a?r:e;o==="left"?s.firstElementChild!==n&&s.replaceChildren(n,t):s.lastElementChild!==n&&s.replaceChildren(t,n)},jh=(e,r,t,n,o,a,s)=>{var w,v,k,T,A,E;let i=vn(a),d=i.reveal==="push";Y0(e,r,t,n,d),Q0(e,r,t,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",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=e.ownerDocument.defaultView,u=(v=(w=a==null?void 0:a.launcher)==null?void 0:w.mobileFullscreen)!=null?v:!0,p=(T=(k=a==null?void 0:a.launcher)==null?void 0:k.mobileBreakpoint)!=null?T:640,m=l!=null?l.innerWidth<=p:!1;if(u&&m&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hp(r),Rp(n),Vh(n),Bp(t),kl(o,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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((E=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?E:Or),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Vh(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Hp(r),Rp(n),Bp(t),kl(o,n);let b=i.animate?"transform 180ms ease":"none",h=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=s?"translateX(0)":h;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=b,n.style.transform=S,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Rp(n),Wp(n),kl(o,n);let b=K0(i.width,e.clientWidth),h=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",L=i.side==="right"?s?`translateX(-${b}px)`:"translateX(0)":s?"translateX(0)":`translateX(-${b}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${h+b}px`,r.style.transition=S,r.style.transform=L,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${h}px`,t.style.maxWidth=`${h}px`,t.style.minWidth=`${h}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Hp(r),Wp(n),Bp(t),kl(o,n);let b=i.reveal==="emerge";b?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let h=s?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",L=!s;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${h}`,n.style.width=h,n.style.maxWidth=h,n.style.minWidth=h,n.style.minHeight="0",n.style.position="relative",n.style.overflow=b||L?"hidden":"visible",n.style.transition=S,b&&(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")}},Z0=(e,r)=>{let t=e.ownerDocument.createElement("div");return zh(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){zh(t,n)},destroy(){t.remove()}}},eC=(e,r)=>{var A,E,b,h;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(E=(A=r==null?void 0:r.launcher)==null?void 0:A.enabled)==null||E?(h=(b=r==null?void 0:r.launcher)==null?void 0:b.autoExpand)!=null?h:!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,e),d.appendChild(e);let m=null,f=()=>{m==null||m.disconnect(),m=null},w=()=>{f(),vn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(m=new ResizeObserver(()=>{jh(s,i,d,l,u,r,p)}),m.observe(s))},v=()=>{jh(s,i,d,l,u,r,p),w()},k=s.ownerDocument.defaultView,T=()=>{v()};return k==null||k.addEventListener("resize",T),vn(r).reveal==="push"?(i.appendChild(d),i.appendChild(l),s.appendChild(i)):(s.appendChild(d),s.appendChild(l)),v(),{mode:"docked",host:u,shell:s,syncWidgetState(S){let L=S.launcherEnabled?S.open:!0;p!==L&&(p=L,v())},updateConfig(S){var L,O;r=S,((O=(L=r==null?void 0:r.launcher)==null?void 0:L.enabled)!=null?O:!0)===!1&&(p=!0),v()},destroy(){k==null||k.removeEventListener("resize",T),f(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}},Os=(e,r)=>hr(r)?eC(e,r):Z0(e,r);var Dp={},tC=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},rC=()=>{try{if(typeof Dp!="undefined"&&Dp.url)return new URL("../widget.css",Dp.url).href}catch{}return null},Gh=(e,r)=>{let t=rC(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=r.head.querySelector("link[data-persona]");if(!o)return;let a=o.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let a=r.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),r.head.appendChild(a)}},Xh=e=>{var k;let r=tC(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,o=e.config,a=Os(r,o),s,i=[],d=(T,A)=>{var S,L;let b=!((L=(S=A==null?void 0:A.launcher)==null?void 0:S.enabled)!=null?L:!0)||hr(A),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),b&&(h.style.height="100%",h.style.display="flex",h.style.flexDirection="column",h.style.flex="1",h.style.minHeight="0"),t){let O=T.attachShadow({mode:"open"});O.appendChild(h),Gh(O,n)}else T.appendChild(h),Gh(T,n);return r.id&&h.setAttribute("data-persona-instance",r.id),h},l=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},p=()=>{let T=d(a.host,o);s=Tl(T,o,{debugTools:e.debugTools}),u()},m=()=>{i.forEach(T=>T()),i=[],s.destroy()};p(),(k=e.onReady)==null||k.call(e);let f=T=>{m(),a.destroy(),a=Os(r,T),o=T,p()},w={update(T){var L,O,H,R,B,j;let A={...o,...T,launcher:{...(L=o==null?void 0:o.launcher)!=null?L:{},...(O=T==null?void 0:T.launcher)!=null?O:{},dock:{...(R=(H=o==null?void 0:o.launcher)==null?void 0:H.dock)!=null?R:{},...(j=(B=T==null?void 0:T.launcher)==null?void 0:B.dock)!=null?j:{}}}},E=hr(o),b=hr(A),h=To(o),S=To(A);if(E!==b||h!==S){f(A);return}o=A,a.updateConfig(o),s.update(T),l()},destroy(){m(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(w,{get(T,A,E){if(A==="host")return a.host;if(A in T)return Reflect.get(T,A,E);let b=s[A];return typeof b=="function"?b.bind(s):b}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Zh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),nC=new Set(["button","a","input","select","textarea","details","summary"]),oC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Op=/\b(product|card|item|listing|result)\b/i,Np=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,aC=3e3,sC=100;function ex(e){let r=typeof e.className=="string"?e.className:"";if(Op.test(r)||e.id&&Op.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Op.test(n.value))return!0}return!1}function tx(e){var r;return Np.test(((r=e.textContent)!=null?r:"").trim())}function rx(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let o=(t=r[n].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function iC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Jh(e){let r=e.match(Np);return r?r[0]:null}function Kh(e){var n,o,a;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((o=r.textContent)!=null&&o.trim())){let s=r.getAttribute("href");return{title:r.textContent.trim(),href:s&&s!=="#"?s:null}}let t=e.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 lC(e){let r=[],t=n=>{let o=n.trim();o&&!r.includes(o)&&r.push(o)};return e.querySelectorAll("button").forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;t((o=n.value)!=null?o:"")}),r.slice(0,6)}var dC="commerce-card",cC="result-card";function Yh(e){return!ex(e)||!tx(e)||!rx(e)&&!iC(e)?0:5200}function Qh(e){var n;return!ex(e)||tx(e)||!rx(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var _p=[{id:dC,scoreElement(e){return Yh(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Np.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,l,u;if(Yh(e)===0)return null;let{title:t,href:n}=Kh(e),o=(u=(l=Jh(((d=e.textContent)!=null?d:"").trim()))!=null?l:Jh(r.text))!=null?u:"",a=lC(e);return[n&&t?`[${t}](${n})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||r.text.trim().slice(0,120),`selector: ${r.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
147
|
+
`}if(!w&&!c){let Vt="max-height: -moz-available !important; max-height: stretch !important;",nr=g?"":"padding-top: 1.25em !important;",tn=g?"":`z-index: ${(Zt=(zt=n.launcher)==null?void 0:zt.zIndex)!=null?Zt:Or} !important;`;Y.style.cssText+=Vt+nr+tn}D()};Mn(),vo(e,n),gl(e,n),hl(e,n);let vt=[];vt.push(()=>{document.removeEventListener("keydown",Nr)});let sr=null,ir=null;vt.push(()=>{sr==null||sr(),sr=null,ir==null||ir(),ir=null}),Ie&&vt.push(()=>{Ie==null||Ie.disconnect(),Ie=null}),vt.push(()=>{wr==null||wr(),wr=null,jn(),ot&&(ot.remove(),ot=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),xe&&vt.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),ce==null||ce.destroy(),ce=null,J==null||J.destroy(),J=null,Q=null});let an=null,fo=()=>{an&&(an(),an=null),n.colorScheme==="auto"&&(an=Gi(()=>{vo(e,n)}))};fo(),vt.push(()=>{an&&(an(),an=null)});let yn=(Hu=n.features)==null?void 0:Hu.streamAnimation;if(yn!=null&&yn.type&&yn.type!=="none"){let c=Ss(yn.type,yn.plugins);c&&(sp(c,e),vt.push(()=>rh(e)))}let Ln=Th(Mt),sn=null,q,he=!1,ln=Kg(),Pn=new Map,Nn=new Map,Oa=0,In=Ji(),Rn=0,Hn=null,Gn=!1,Ro=!1,Ns=4,Fa=24,_s=80,la=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Na=(Wu=(Bu=n.voiceRecognition)==null?void 0:Bu.autoResume)!=null?Wu:!1,bn=c=>{a.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Qr=()=>{m(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},$s=()=>{var w,O;if(((w=n.voiceRecognition)==null?void 0:w.enabled)===!1)return;let c=Ip(d.voiceState),g=!!c.active,x=Number((O=c.timestamp)!=null?O:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-x<V0&&setTimeout(()=>{var $,U;bt.active||(bt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("restore"),q.isVoiceActive()&&Co()}):Wo("restore"))},1e3)},Us=()=>q?$h(q.getMessages()).filter(c=>!c.__skipPersist):[];function da(c){if(!(i!=null&&i.save))return;let x={messages:c?$h(c):q?Us():[],metadata:d,artifacts:L.artifacts,selectedArtifactId:L.selectedId};try{let w=i.save(x);w instanceof Promise&&w.catch(O=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",O)})}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",w)}}let Xn=null,qs=()=>Y.querySelector("#persona-scroll-container")||ve,Ho=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Gn=!1},_a=()=>{Hn!==null&&(cancelAnimationFrame(Hn),Hn=null),Ro=!1,Ho()},Jn=()=>{if(!rt()||pe){it.parentNode&&it.remove(),it.style.display="none";return}it.parentNode!==ae&&ae.appendChild(it),Rr();let c=Cs(ve)>0;it.style.display=In.isFollowing()||!c?"none":""},$a=()=>{In.pause()&&(_a(),Jn())},mo=()=>{In.resume(),Jn()},go=(c=!1)=>{In.isFollowing()&&(!c&&!he||(Hn!==null&&(cancelAnimationFrame(Hn),Hn=null),Ro=!0,Hn=requestAnimationFrame(()=>{Hn=null,Ro=!1,In.isFollowing()&&zs(qs(),c?220:140)})))},zs=(c,g=500)=>{let x=c.scrollTop,w=Cs(c),O=w-x;if(Math.abs(O)<1){Rn=c.scrollTop;return}if(Math.abs(O)>=_s){Ho(),Gn=!0,c.scrollTop=w,Rn=c.scrollTop,Gn=!1;return}Ho();let $=performance.now();Gn=!0;let U=_=>1-Math.pow(1-_,3),X=_=>{if(!In.isFollowing()){Ho();return}let Te=Cs(c);Te!==w&&(w=Te,O=w-x);let me=_-$,re=Math.min(me/g,1),be=U(re),Me=x+O*be;c.scrollTop=Me,Rn=c.scrollTop,re<1?Xn=requestAnimationFrame(X):(c.scrollTop=w,Rn=c.scrollTop,Xn=null,Gn=!1)};Xn=requestAnimationFrame(X)},Vs=c=>{let g=new Map;c.forEach(x=>{let w=la.get(x.id);g.set(x.id,{streaming:x.streaming,role:x.role}),!w&&x.role==="assistant"&&a.emit("assistant:message",x),x.role==="assistant"&&(w!=null&&w.streaming)&&x.streaming===!1&&a.emit("assistant:complete",x),x.variant==="approval"&&x.approval&&(w?x.approval.status!=="pending"&&a.emit("approval:resolved",{approval:x.approval,decision:x.approval.status}):a.emit("approval:requested",{approval:x.approval,message:x}))}),la.clear(),g.forEach((x,w)=>{la.set(w,x)})},Bo=(c,g,x)=>{var tt,ft,mt,We,Be,Je;let w=document.createElement("div"),$=(()=>{var Re;let D=o.find(Ne=>Ne.renderLoadingIndicator);if(D!=null&&D.renderLoadingIndicator)return D.renderLoadingIndicator;if((Re=n.loadingIndicator)!=null&&Re.render)return n.loadingIndicator.render})(),U=(D,Re)=>Re==null?!1:typeof Re=="string"?(D.textContent=Re,!0):(D.appendChild(Re),!0),X=new Set,_=new Set,Te=o.some(D=>D.renderAskUserQuestion),me=[],re=[],be=n.enableComponentStreaming!==!1;if(g.forEach(D=>{var Ur,Pr,st,gt,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo;X.add(D.id);let Re=Te&&so(D),Ne=!Re&&D.role==="assistant"&&!D.variant&&be&&Cl(D);if(!Ne&&Nn.has(D.id)){let Et=c.querySelector(`#wrapper-${D.id}`);Et==null||Et.removeAttribute("data-preserve-runtime"),Nn.delete(D.id)}let Qe=so(D)?`:${(Ur=D.agentMetadata)!=null&&Ur.askUserQuestionAnswered?"a":"u"}:${(Pr=D.agentMetadata)!=null&&Pr.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ae=Jg(D,Oa)+Qe,Dt=Re||Ne?null:Yg(ln,D.id,Ae);if(Dt){w.appendChild(Dt.cloneNode(!0)),so(D)&&((st=D.toolCall)!=null&&st.id)&&((gt=D.agentMetadata)==null?void 0:gt.awaitingLocalTool)===!0&&!((qr=D.agentMetadata)!=null&&qr.askUserQuestionAnswered)&&(_.add(D.toolCall.id),Ra(D,n,ke.composerOverlay));return}let pt=null,cr=o.find(Et=>!!(D.variant==="reasoning"&&Et.renderReasoning||D.variant==="tool"&&Et.renderToolCall||D.variant==="approval"&&Et.renderApproval||!D.variant&&Et.renderMessage)),Lr=(Br=n.layout)==null?void 0:Br.messages;if(so(D)&&((Oo=D.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){Pn.delete(D.id);let Et=c.querySelector(`#wrapper-${D.id}`);Et==null||Et.removeAttribute("data-preserve-runtime");return}if(so(D)&&((No=(Fo=n.features)==null?void 0:Fo.askUserQuestion)==null?void 0:No.enabled)!==!1){let Et=o.find(Zr=>typeof Zr.renderAskUserQuestion=="function");if(Et&&se.current){let Zr=Pn.get(D.id),Zn=Zr!==Ae,zr=null;if(Zn){let{payload:Zt,complete:Vt}=io(D),nr=D.id,tn=()=>{var cn;return(cn=se.current)==null?void 0:cn.getMessages().find(gr=>gr.id===nr)};zr=Et.renderAskUserQuestion({message:D,payload:Zt,complete:Vt,resolve:cn=>{var $n;let gr=tn();gr&&(($n=se.current)==null||$n.resolveAskUserQuestion(gr,cn))},dismiss:()=>{var gr,$n,eo;let cn=tn();(gr=cn==null?void 0:cn.agentMetadata)!=null&&gr.awaitingLocalTool&&(($n=se.current)==null||$n.markAskUserQuestionResolved(cn),(eo=se.current)==null||eo.resolveAskUserQuestion(cn,"(dismissed)"))},config:n})}let en=Zr!=null;if(Zn&&zr===null&&!en){((ma=D.agentMetadata)==null?void 0:ma.awaitingLocalTool)===!0&&!((ga=D.agentMetadata)!=null&&ga.askUserQuestionAnswered)&&(_.add(D.toolCall.id),Ra(D,n,ke.composerOverlay));return}let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-${D.id}`,zt.setAttribute("data-wrapper-id",D.id),zt.setAttribute("data-ask-plugin-stub","true"),zt.setAttribute("data-preserve-runtime","true"),w.appendChild(zt),me.push({messageId:D.id,fingerprint:Ae,bubble:zr});return}else{((rr=D.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((_o=D.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(_.add(D.toolCall.id),Ra(D,n,ke.composerOverlay));return}}else if(cr)if(D.variant==="reasoning"&&D.reasoning&&cr.renderReasoning){if(!De)return;pt=cr.renderReasoning({message:D,defaultRenderer:()=>hp(D,n),config:n})}else if(D.variant==="tool"&&D.toolCall&&cr.renderToolCall){if(!Xe)return;pt=cr.renderToolCall({message:D,defaultRenderer:()=>xp(D,n),config:n})}else if(D.variant==="approval"&&D.approval&&cr.renderApproval){if(n.approval===!1)return;pt=cr.renderApproval({message:D,defaultRenderer:()=>Tp(D,n),config:n})}else cr.renderMessage&&(pt=cr.renderMessage({message:D,defaultRenderer:()=>{let Et=Ea(D,x,Lr,n.messageActions,Pe,{loadingIndicatorRenderer:$,widgetConfig:n});return D.role!=="user"&&Mp(Et,D,n,q),Et},config:n}));if(!pt&&Ne){let Et=wl(D);if(Et){let Zr=Nn.get(D.id),Zn=Zr!==Ae,zr=n.wrapComponentDirectiveInBubble!==!1,en=null;if(Zn){let zt=bl(Et,{config:n,message:D,transform:x});if(zt)if(zr){let Zt=document.createElement("div");if(Zt.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(" "),Zt.id=`bubble-${D.id}`,Zt.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let Vt=document.createElement("div");Vt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Vt.innerHTML=x({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Zt.appendChild(Vt)}Zt.appendChild(zt),en=Zt}else{let Zt=document.createElement("div");if(Zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Zt.id=`bubble-${D.id}`,Zt.setAttribute("data-message-id",D.id),Zt.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let Vt=document.createElement("div");Vt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Vt.innerHTML=x({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Zt.appendChild(Vt)}Zt.appendChild(zt),en=Zt}}if(en||Zr!=null){let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-${D.id}`,zt.setAttribute("data-wrapper-id",D.id),zt.setAttribute("data-component-directive-stub","true"),zt.setAttribute("data-preserve-runtime","true"),zr||zt.classList.add("persona-w-full"),w.appendChild(zt),re.push({messageId:D.id,fingerprint:Ae,bubble:en});return}}}if(!pt)if(D.variant==="reasoning"&&D.reasoning){if(!De)return;pt=hp(D,n)}else if(D.variant==="tool"&&D.toolCall){if(!Xe)return;pt=xp(D,n)}else if(D.variant==="approval"&&D.approval){if(n.approval===!1)return;pt=Tp(D,n)}else{let Et=(wo=n.layout)==null?void 0:wo.messages;Et!=null&&Et.renderUserMessage&&D.role==="user"?pt=Et.renderUserMessage({message:D,config:n,streaming:!!D.streaming}):Et!=null&&Et.renderAssistantMessage&&D.role==="assistant"?pt=Et.renderAssistantMessage({message:D,config:n,streaming:!!D.streaming}):pt=Ea(D,x,Et,n.messageActions,Pe,{loadingIndicatorRenderer:$,widgetConfig:n}),D.role!=="user"&&pt&&Mp(pt,D,n,q)}let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id=`wrapper-${D.id}`,Ft.setAttribute("data-wrapper-id",D.id),D.role==="user"&&Ft.classList.add("persona-justify-end"),(pt==null?void 0:pt.getAttribute("data-persona-component-directive"))==="true"&&Ft.classList.add("persona-w-full"),Ft.appendChild(pt),Qg(ln,D.id,Ae,Ft),w.appendChild(Ft)}),ke.composerOverlay&&ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Ne=Re.getAttribute("data-persona-ask-sheet-for");Ne&&!_.has(Ne)&&Lo(ke.composerOverlay,Ne)}),(ft=(tt=n.features)==null?void 0:tt.toolCallDisplay)!=null&&ft.grouped){let D=[],Re=[];g.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&Xe){Re.push(Ne);return}Re.length>1&&D.push(Re),Re=[]}),Re.length>1&&D.push(Re),D.forEach((Ne,Qe)=>{var Pr,st;let Ae=Ne.map(gt=>Array.from(w.children).find(qr=>qr instanceof HTMLElement&&qr.getAttribute("data-wrapper-id")===gt.id)).filter(gt=>!!gt);if(Ae.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${Qe}-${Ne[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${Qe}-${Ne[0].id}`);let pt=document.createElement("div");pt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",pt.setAttribute("data-persona-tool-group","true");let cr=document.createElement("div");cr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Lr=`Called ${Ne.length} tools`,Ft=(st=(Pr=n.toolCall)==null?void 0:Pr.renderGroupedSummary)==null?void 0:st.call(Pr,{messages:Ne,toolCalls:Ne.map(gt=>gt.toolCall).filter(gt=>!!gt),defaultSummary:Lr,config:n});U(cr,Ft)||(cr.textContent=Lr);let Ur=document.createElement("div");Ur.className="persona-tool-group-stack persona-flex persona-flex-col",pt.append(cr,Ur),Dt.appendChild(pt),Ae[0].before(Dt),Ae.forEach((gt,qr)=>{let Br=document.createElement("div");Br.className="persona-tool-group-item persona-relative",Br.setAttribute("data-persona-tool-group-item","true"),qr<Ae.length-1&&Br.setAttribute("data-persona-tool-group-connector","true"),Br.appendChild(gt),Ur.appendChild(Br)})})}Zg(ln,X);let Me=g.some(D=>D.role==="assistant"&&D.streaming),Ve=g[g.length-1],lt=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(he&&g.some(D=>D.role==="user")&&!Me&&!lt){let D={config:n,streaming:!0,location:"standalone",defaultRenderer:oa},Re=o.find(Qe=>Qe.renderLoadingIndicator),Ne=null;if(Re!=null&&Re.renderLoadingIndicator&&(Ne=Re.renderLoadingIndicator(D)),Ne===null&&((mt=n.loadingIndicator)!=null&&mt.render)&&(Ne=n.loadingIndicator.render(D)),Ne===null&&(Ne=oa()),Ne){let Qe=document.createElement("div"),Ae=((We=n.loadingIndicator)==null?void 0:We.showBubble)!==!1;Qe.className=Ae?["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(" "),Qe.setAttribute("data-typing-indicator","true"),Qe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Qe.appendChild(Ne);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(Qe),w.appendChild(Dt)}}if(!he&&g.length>0){let D=g[g.length-1],Re={config:n,lastMessage:D,messageCount:g.length},Ne=o.find(Ae=>Ae.renderIdleIndicator),Qe=null;if(Ne!=null&&Ne.renderIdleIndicator&&(Qe=Ne.renderIdleIndicator(Re)),Qe===null&&((Be=n.loadingIndicator)!=null&&Be.renderIdle)&&(Qe=n.loadingIndicator.renderIdle(Re)),Qe){let Ae=document.createElement("div"),Dt=((Je=n.loadingIndicator)==null?void 0:Je.showBubble)!==!1;Ae.className=Dt?["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(" "),Ae.setAttribute("data-idle-indicator","true"),Ae.appendChild(Qe);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-idle-indicator",pt.setAttribute("data-wrapper-id","idle-indicator"),pt.appendChild(Ae),w.appendChild(pt)}}if(Xi(c,w),me.length>0)for(let{messageId:D,fingerprint:Re,bubble:Ne}of me){let Qe=c.querySelector(`#wrapper-${D}`);Qe&&Ne!==null&&(Qe.replaceChildren(Ne),Qe.setAttribute("data-bubble-fp",Re),Pn.set(D,Re))}if(Pn.size>0)for(let D of Pn.keys())X.has(D)||Pn.delete(D);if(re.length>0)for(let{messageId:D,fingerprint:Re,bubble:Ne}of re){let Qe=c.querySelector(`#wrapper-${D}`);Qe&&Ne!==null&&(Qe.replaceChildren(Ne),Qe.setAttribute("data-bubble-fp",Re),Nn.set(D,Re))}if(Nn.size>0)for(let D of Nn.keys())X.has(D)||Nn.delete(D)},ho=null,js=()=>{var x;if(ho)return;let c=w=>{let O=w.composedPath();O.includes(Y)||we&&O.includes(we)||Nt(!1,"user")};ho=c,((x=e.ownerDocument)!=null?x:document).addEventListener("pointerdown",c,!0)},Ua=()=>{var g;if(!ho)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",ho,!0),ho=null};vt.push(()=>Ua());let xo=null,Gs=()=>{var x;if(xo)return;let c=w=>{w.key==="Escape"&&(w.isComposing||Nt(!1,"user"))};xo=c,((x=e.ownerDocument)!=null?x:document).addEventListener("keydown",c,!0)},qa=()=>{var g;if(!xo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",xo,!0),xo=null};vt.push(()=>qa());let yo=!1,za=new Set,Xs=()=>{var g,x,w,O;let c=(w=(x=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:x.peek)==null?void 0:w.streamAnimation;return c||((O=n.features)==null?void 0:O.streamAnimation)},Kn=()=>{var ft,mt,We,Be;if(!B())return;let c=ke.peekBanner,g=ke.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let x=(ft=q==null?void 0:q.getMessages())!=null?ft:[],w;for(let Je=x.length-1;Je>=0;Je--){let D=x[Je];if(D.role==="assistant"&&D.content){w=D;break}}if(!w){c.classList.remove("persona-pill-peek--visible");return}let O=w.content,$=!!w.streaming,U=Xs(),X=Qi(U),_=X.type!=="none"?Ss(X.type,U==null?void 0:U.plugins):null,Te=((mt=_==null?void 0:_.isAnimating)==null?void 0:mt.call(_,w))===!0,me=_!==null&&($||Te);me&&_&&!za.has(_.name)&&(sp(_,e),za.add(_.name));let re=me&&(_!=null&&_.containerClass)?_.containerClass:null,be=(We=g.dataset.personaPeekStreamClass)!=null?We:null;be&&be!==re&&(g.classList.remove(be),delete g.dataset.personaPeekStreamClass),re&&be!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),me?(g.style.setProperty("--persona-stream-step",`${X.speed}ms`),g.style.setProperty("--persona-stream-duration",`${X.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Me=me?Zi(O,X.buffer,_,w,$):O;if(me&&X.placeholder==="skeleton"&&$&&(!Me||!Me.trim())){let Je=document.createElement("div"),D=ks();D.classList.add("persona-pill-peek__skeleton"),Je.appendChild(D),Xi(g,Je)}else{let Je=Math.max(0,Me.length-100),D=Me.length>100?Me.slice(-100):Me,Re=Jo(D);if(!me||!_){let Ne=Me.length>100?`\u2026${D}`:D;g.textContent!==Ne&&(g.textContent=Ne)}else{let Ne=Re;(_.wrap==="char"||_.wrap==="word")&&(Ne=Ts(Re,_.wrap,`peek-${w.id}`,{skipTags:_.skipTags,startIndex:Je}));let Qe=document.createElement("div");if(Qe.innerHTML=Ne,_.useCaret&&D.length>0){let Ae=el(),Dt=Qe.querySelectorAll(".persona-stream-char, .persona-stream-word"),pt=Dt[Dt.length-1];pt!=null&&pt.parentNode?pt.parentNode.insertBefore(Ae,pt.nextSibling):Qe.appendChild(Ae)}Xi(g,Qe),(Be=_.onAfterRender)==null||Be.call(_,{container:g,bubble:c,messageId:w.id,message:w,speed:X.speed,duration:X.duration})}}let tt=he||yo;c.classList.toggle("persona-pill-peek--visible",tt)};if(B()){let c=ke.peekBanner;if(c){let w=O=>{O.preventDefault(),O.stopPropagation(),Nt(!0,"user")};c.addEventListener("pointerdown",w),vt.push(()=>{c.removeEventListener("pointerdown",w)})}let g=()=>{yo||(yo=!0,Kn())},x=()=>{yo&&(yo=!1,Kn())};G.addEventListener("pointerenter",g),G.addEventListener("pointerleave",x),vt.push(()=>{G.removeEventListener("pointerenter",g),G.removeEventListener("pointerleave",x)}),we&&(we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",x),vt.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",x)}))}let Js=c=>{var be,Me,Ve,lt,tt,ft,mt,We;let g=(Me=(be=n.launcher)==null?void 0:be.composerBar)!=null?Me:{},x=(Ve=g.expandedSize)!=null?Ve:"anchored",w=(lt=g.bottomOffset)!=null?lt:"16px",O=g.collapsedMaxWidth,$=(tt=g.expandedMaxWidth)!=null?tt:"880px",U=(ft=g.expandedTopOffset)!=null?ft:"5vh",X=(mt=g.modalMaxWidth)!=null?mt:"880px",_=(We=g.modalMaxHeight)!=null?We:"min(90vh, 800px)",Te="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",re=Y.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",we){let Be=we.style;Be.bottom=w,Be.width=O!=null?O:""}if(c&&x!=="fullscreen"){if(x==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=X,re.maxWidth=Te,re.maxHeight=_,re.height=_;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${w} + ${me})`,re.top=U,re.width=$,re.maxWidth=Te}},bo=()=>{var _,Te,me,re,be,Me,Ve,lt;if(!W())return;if(B()){let ft=(me=((Te=(_=n.launcher)==null?void 0:_.composerBar)!=null?Te:{}).expandedSize)!=null?me:"anchored",mt=R?"expanded":"collapsed";Y.dataset.state=mt,Y.dataset.expandedSize=ft,we&&(we.dataset.state=mt,we.dataset.expandedSize=ft),Y.style.removeProperty("display"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Js(R),ae.style.display=R?"flex":"none",Mn(),R?(js(),Gs()):(Ua(),qa()),Kn();return}let c=hr(n),g=(re=e.ownerDocument.defaultView)!=null?re:window,x=(Me=(be=n.launcher)==null?void 0:be.mobileBreakpoint)!=null?Me:640,w=(lt=(Ve=n.launcher)==null?void 0:Ve.mobileFullscreen)!=null?lt:!0,O=g.innerWidth<=x,$=w&&O&&T,U=vn(n).reveal;R?(Y.style.removeProperty("display"),Y.style.display=c?"flex":"",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0"),G.classList.add("persona-scale-100","persona-opacity-100"),I?I.element.style.display="none":V&&(V.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!$?(Y.style.removeProperty("display"),Y.style.display="flex",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.setProperty("display","none","important"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.display="",Y.classList.add("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100"),G.classList.add("persona-scale-95","persona-opacity-0")),I?I.element.style.display=c?"none":"":V&&(V.style.display=c?"none":""))},Nt=(c,g="user")=>{var $,U;if(!W()||R===c)return;let x=R;R=c,bo();let w=(()=>{var Ve,lt,tt,ft,mt,We,Be,Je,D,Re;let X=(lt=(Ve=n.launcher)==null?void 0:Ve.sidebarMode)!=null?lt:!1,_=(tt=e.ownerDocument.defaultView)!=null?tt:window,Te=(mt=(ft=n.launcher)==null?void 0:ft.mobileFullscreen)!=null?mt:!0,me=(Be=(We=n.launcher)==null?void 0:We.mobileBreakpoint)!=null?Be:640,re=_.innerWidth<=me,be=hr(n)&&Te&&re,Me=B()&&((Re=(D=(Je=n.launcher)==null?void 0:Je.composerBar)==null?void 0:D.expandedSize)!=null?Re:"fullscreen")==="fullscreen";return X||Te&&re&&T||be||Me})();if(R&&w){if(!sr){let X=e.getRootNode(),_=X instanceof ShadowRoot?X.host:e.closest(".persona-host");_&&(sr=ip(_,(U=($=n.launcher)==null?void 0:$.zIndex)!=null?U:Or))}ir||(ir=lp(e.ownerDocument))}else R||(sr==null||sr(),sr=null,ir==null||ir(),ir=null);R&&(fe(),go(!0));let O={open:R,source:g,timestamp:Date.now()};R&&!x?a.emit("widget:opened",O):!R&&x&&a.emit("widget:closed",O),a.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:bt.active,streaming:q.isStreaming()})},ca=c=>{$t(c?"stop":"send"),N&&(N.disabled=c),Ln.buttons.forEach(g=>{g.disabled=c}),qe.dataset.personaComposerStreaming=c?"true":"false",qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},pa=()=>{bt.active||ne&&ne.focus()};a.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>pa(),200)});let Va=()=>{var x,w,O,$,U,X,_,Te,me,re,be;Fr.textContent=(w=(x=n.copy)==null?void 0:x.welcomeTitle)!=null?w:"Hello \u{1F44B}",Ar.textContent=($=(O=n.copy)==null?void 0:O.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ne.placeholder=(X=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?X:"How can I help...";let c=ve.querySelector("[data-persona-intro-card]");if(c){let Me=((_=n.copy)==null?void 0:_.showWelcomeCard)!==!1;c.style.display=Me?"":"none",Me?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((me=(Te=n.sendButton)==null?void 0:Te.useIcon)!=null&&me)&&!(q!=null&&q.isStreaming())&&(He.textContent=(be=(re=n.copy)==null?void 0:re.sendButtonLabel)!=null?be:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.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 _n=null,Ks=()=>{_n==null&&(_n=setInterval(()=>{let c=ye.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(_n),_n=null;return}let g=Date.now();c.forEach(x=>{let w=Number(x.getAttribute("data-tool-elapsed"));w&&(x.textContent=yi(g-w))})},100))};if(q=new wa(n,{onMessagesChanged(c){Bo(ye,c,ue),Ks(),q&&(c.some(O=>O.role==="user")?Ln.render([],q,ne,c):Ln.render(n.suggestionChips,q,ne,c,n.suggestionChipsConfig)),go(!he),Vs(c);let g=[...c].reverse().find(w=>w.role==="user"),x=bt.lastUserMessageId;g&&g.id!==x&&(bt.lastUserMessageId=g.id,a.emit("user:message",g)),bt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),da(c),Kn()},onStatusChanged(c){var w;let g=(w=n.statusIndicator)!=null?w:{};$e(Yt,(O=>{var $,U,X,_;return O==="idle"?($=g.idleText)!=null?$:Dr.idle:O==="connecting"?(U=g.connectingText)!=null?U:Dr.connecting:O==="connected"?(X=g.connectedText)!=null?X:Dr.connected:O==="error"?(_=g.errorText)!=null?_:Dr.error:Dr[O]})(c),g,c)},onStreamingChanged(c){he=c,ca(c),q&&Bo(ye,q.getMessages(),ue),c||go(!0),Kn()},onVoiceStatusChanged(c){var g,x;if(((x=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:x.type)==="runtype")switch(c){case"listening":break;case"processing":Wn(),Qs();break;case"speaking":Wn(),Zs();break;default:c==="idle"&&q.isBargeInActive()?(Wn(),Co(),N==null||N.setAttribute("aria-label","End voice session")):(bt.active=!1,Wn(),bn("system"),Qr());break}},onArtifactsState(c){L=c,on(),da()}}),se.current=q,((Ou=(Du=n.voiceRecognition)==null?void 0:Du.provider)==null?void 0:Ou.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)}),(J||n.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var x;(x=n.onSSEEvent)==null||x.call(n,c,g),J==null||J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,x,w;c&&(c.metadata&&(d=Ip(c.metadata),k.syncFromMetadata()),(g=c.messages)!=null&&g.length&&q.hydrateMessages(c.messages),(x=c.artifacts)!=null&&x.length&&q.hydrateArtifacts(c.artifacts,(w=c.selectedArtifactId)!=null?w:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ja=()=>{var g,x,w;!B()||R||!((w=(x=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:x.expandOnSubmit)==null||w)||Nt(!0,"auto")},Ga=c=>{var O;if(c.preventDefault(),q.isStreaming()){q.cancel();return}let g=ne.value.trim(),x=(O=Tt==null?void 0:Tt.hasAttachments())!=null?O:!1;if(!g&&!x)return;ja();let w;x&&(w=[],w.push(...Tt.getContentParts()),g&&w.push(gs(g))),ne.value="",ne.style.height="auto",q.sendMessage(g,{contentParts:w}),x&&Tt.clearAttachments()},Xa=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),He.click())},Ja=async c=>{var x;if(((x=n.attachments)==null?void 0:x.enabled)!==!0||!Tt)return;let g=G0(c.clipboardData);g.length!==0&&(c.preventDefault(),await Tt.handleFiles(g))},$r=null,dn=!1,Yn=null,dt=null,Ka=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Wo=(c="user")=>{var $,U,X,_,Te,me,re;if(dn||q.isStreaming())return;let g=Ka();if(!g)return;$r=new g;let w=(U=(($=n.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;$r.continuous=!0,$r.interimResults=!0,$r.lang="en-US";let O=ne.value;$r.onresult=be=>{let Me="",Ve="";for(let tt=0;tt<be.results.length;tt++){let ft=be.results[tt],mt=ft[0].transcript;ft.isFinal?Me+=mt+" ":Ve=mt}let lt=O+Me+Ve;ne.value=lt,Yn&&clearTimeout(Yn),(Me||Ve)&&(Yn=window.setTimeout(()=>{let tt=ne.value.trim();tt&&$r&&dn&&(Bn(),ne.value="",ne.style.height="auto",q.sendMessage(tt,{viaVoice:!0}))},w))},$r.onerror=be=>{be.error!=="no-speech"&&Bn()},$r.onend=()=>{if(dn){let be=ne.value.trim();be&&be!==O.trim()&&(ne.value="",ne.style.height="auto",q.sendMessage(be,{viaVoice:!0})),Bn()}};try{if($r.start(),dn=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),bn(c),Qr(),N){let be=(X=n.voiceRecognition)!=null?X:{};dt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((re=(me=be.iconSize)!=null?me:(Te=n.sendButton)==null?void 0:Te.size)!=null?re:"40")||24};let Me=be.recordingBackgroundColor,Ve=be.recordingIconColor,lt=be.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=Ve!=null?Ve:"var(--persona-voice-recording-indicator, #ffffff)",Ve){let tt=N.querySelector("svg");tt&&tt.setAttribute("stroke",Ve)}lt&&(N.style.borderColor=lt),N.setAttribute("aria-label","Stop voice recognition")}}catch{Bn("system")}},Bn=(c="user")=>{if(dn){if(dn=!1,Yn&&(clearTimeout(Yn),Yn=null),$r){try{$r.stop()}catch{}$r=null}if(bt.active=!1,bn(c),Qr(),N){if(N.classList.remove("persona-voice-recording"),dt){N.style.backgroundColor=dt.backgroundColor,N.style.color=dt.color,N.style.borderColor=dt.borderColor;let g=N.querySelector("svg");g&&g.setAttribute("stroke",dt.color||"currentColor"),dt=null}N.setAttribute("aria-label","Start voice recognition")}}},Ys=(c,g)=>{var ft,mt,We,Be,Je,D,Re,Ne;let x=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),w=((ft=c==null?void 0:c.provider)==null?void 0:ft.type)==="runtype";if(!(x||w))return null;let $=h("div","persona-send-button-wrapper"),U=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let X=(mt=c==null?void 0:c.iconName)!=null?mt:"mic",_=(We=g==null?void 0:g.size)!=null?We:"40px",Te=(Be=c==null?void 0:c.iconSize)!=null?Be:_,me=parseFloat(Te)||24,re=(Je=c==null?void 0:c.backgroundColor)!=null?Je:g==null?void 0:g.backgroundColor,be=(D=c==null?void 0:c.iconColor)!=null?D:g==null?void 0:g.textColor;U.style.width=Te,U.style.height=Te,U.style.minWidth=Te,U.style.minHeight=Te,U.style.fontSize="18px",U.style.lineHeight="1",be?U.style.color=be:U.style.color="var(--persona-text, #111827)";let Ve=Ce(X,me,be||"currentColor",1.5);Ve?U.appendChild(Ve):U.textContent="\u{1F3A4}",re?U.style.backgroundColor=re: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 lt=(Re=c==null?void 0:c.tooltipText)!=null?Re:"Start voice recognition";if(((Ne=c==null?void 0:c.showTooltip)!=null?Ne:!1)&<){let Qe=h("div","persona-send-button-tooltip");Qe.textContent=lt,$.appendChild(Qe)}return{micButton:U,micButtonWrapper:$}},ua=()=>{var g,x,w,O,$;if(!N||dt)return;let c=(g=n.voiceRecognition)!=null?g:{};dt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(x=c.iconName)!=null?x:"mic",iconSize:parseFloat(($=(O=c.iconSize)!=null?O:(w=n.sendButton)==null?void 0:w.size)!=null?$:"40")||24}},fa=(c,g)=>{var $,U,X,_,Te;if(!N)return;let x=N.querySelector("svg");x&&x.remove();let w=(Te=dt==null?void 0:dt.iconSize)!=null?Te:parseFloat((_=(X=($=n.voiceRecognition)==null?void 0:$.iconSize)!=null?X:(U=n.sendButton)==null?void 0:U.size)!=null?_:"40")||24,O=Ce(c,w,g,1.5);O&&N.appendChild(O)},Do=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Co=()=>{var O;if(!N)return;ua();let c=(O=n.voiceRecognition)!=null?O:{},g=c.recordingBackgroundColor,x=c.recordingIconColor,w=c.recordingBorderColor;if(Do(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=x!=null?x:"var(--persona-voice-recording-indicator, #ffffff)",x){let $=N.querySelector("svg");$&&$.setAttribute("stroke",x)}w&&(N.style.borderColor=w),N.setAttribute("aria-label","Stop voice recognition")},Qs=()=>{var X,_,Te,me,re,be,Me,Ve;if(!N)return;ua();let c=(X=n.voiceRecognition)!=null?X:{},g=q.getVoiceInterruptionMode(),x=(_=c.processingIconName)!=null?_:"loader",w=(me=(Te=c.processingIconColor)!=null?Te:dt==null?void 0:dt.color)!=null?me:"",O=(be=(re=c.processingBackgroundColor)!=null?re:dt==null?void 0:dt.backgroundColor)!=null?be:"",$=(Ve=(Me=c.processingBorderColor)!=null?Me:dt==null?void 0:dt.borderColor)!=null?Ve:"";Do(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=O,N.style.borderColor=$;let U=w||"currentColor";N.style.color=U,fa(x,U),N.setAttribute("aria-label","Processing voice input"),g==="none"&&(N.style.cursor="default")},Zs=()=>{var Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be;if(!N)return;ua();let c=(Te=n.voiceRecognition)!=null?Te:{},g=q.getVoiceInterruptionMode(),x=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",w=(me=c.speakingIconName)!=null?me:x,O=(Ve=c.speakingIconColor)!=null?Ve:g==="barge-in"?(be=(re=c.recordingIconColor)!=null?re:dt==null?void 0:dt.color)!=null?be:"":(Me=dt==null?void 0:dt.color)!=null?Me:"",$=(ft=c.speakingBackgroundColor)!=null?ft:g==="barge-in"?(lt=c.recordingBackgroundColor)!=null?lt:"var(--persona-voice-recording-bg, #ef4444)":(tt=dt==null?void 0:dt.backgroundColor)!=null?tt:"",U=(Be=c.speakingBorderColor)!=null?Be:g==="barge-in"?(mt=c.recordingBorderColor)!=null?mt:"":(We=dt==null?void 0:dt.borderColor)!=null?We:"";Do(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=$,N.style.borderColor=U;let X=O||"currentColor";N.style.color=X,fa(w,X);let _=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",_),g==="none"&&(N.style.cursor="default"),g==="barge-in"&&N.classList.add("persona-voice-recording")},Wn=()=>{var c,g,x;N&&(Do(),dt&&(N.style.backgroundColor=(c=dt.backgroundColor)!=null?c:"",N.style.color=(g=dt.color)!=null?g:"",N.style.borderColor=(x=dt.borderColor)!=null?x:"",fa(dt.iconName,dt.color||"currentColor"),dt=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},Qn=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let x=q.getVoiceStatus(),w=q.getVoiceInterruptionMode();if(w==="none"&&(x==="processing"||x==="speaking"))return;if(w==="cancel"&&(x==="processing"||x==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()});return}q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bt.manuallyDeactivated=!q.isVoiceActive(),Qr(),bn("user"),q.isVoiceActive()?Co():Wn()});return}if(dn){let x=ne.value.trim();bt.manuallyDeactivated=!0,Qr(),Bn("user"),x&&(ne.value="",ne.style.height="auto",q.sendMessage(x))}else bt.manuallyDeactivated=!1,Qr(),Wo("user")};hn=Qn,N&&(N.addEventListener("click",Qn),vt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Wn()):Bn("system"),N&&N.removeEventListener("click",Qn)}));let Ze=a.on("assistant:complete",()=>{Na&&(bt.active||bt.manuallyDeactivated||Na==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!bt.active&&!bt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("auto"),q.isVoiceActive()&&Co()}):Wo("auto"))},600))});vt.push(Ze);let P=a.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});vt.push(P);let z=()=>{Nt(!R,"user")},I=null,V=null;if(T&&!B()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});g&&(V=g)}V||(I=Ms(n,z))}I?e.appendChild(I.element):V&&e.appendChild(V),bo(),Ln.render(n.suggestionChips,q,ne,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming()),go(!0),$s(),E&&(!T||B()?setTimeout(()=>pa(),0):R&&setTimeout(()=>pa(),200));let fe=()=>{var _,Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be,Je,D,Re,Ne,Qe,Ae,Dt,pt,cr;if(B()){Rr(),bo();return}let c=hr(n),g=(Te=(_=n.launcher)==null?void 0:_.sidebarMode)!=null?Te:!1,x=c||g||((re=(me=n.launcher)==null?void 0:me.fullHeight)!=null?re:!1),w=(be=e.ownerDocument.defaultView)!=null?be:window,O=(Ve=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?Ve:!0,$=(tt=(lt=n.launcher)==null?void 0:lt.mobileBreakpoint)!=null?tt:640,U=w.innerWidth<=$,X=O&&U&&T;try{if(X){Mn(),vo(e,n);return}if(M&&(M=!1,Mn(),vo(e,n)),!T&&!c){G.style.height="",G.style.width="";return}if(!g&&!c){let Lr=(mt=(ft=n==null?void 0:n.launcher)==null?void 0:ft.width)!=null?mt:n==null?void 0:n.launcherWidth,Ft=Lr!=null?Lr:mn;G.style.width=Ft,G.style.maxWidth=Ft}if(Fn(),!x){let Lr=w.innerHeight,Ft=64,Ur=(Be=(We=n.launcher)==null?void 0:We.heightOffset)!=null?Be:0,Pr=Math.max(200,Lr-Ft),st=Math.min(640,Pr),gt=Math.max(200,st-Ur);G.style.height=`${gt}px`}}finally{if(Rr(),bo(),R&&T){let Ft=((Je=e.ownerDocument.defaultView)!=null?Je:window).innerWidth<=((Re=(D=n.launcher)==null?void 0:D.mobileBreakpoint)!=null?Re:640),Ur=(Qe=(Ne=n.launcher)==null?void 0:Ne.sidebarMode)!=null?Qe:!1,Pr=(Dt=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Dt:!0,st=hr(n)&&Pr&&Ft,gt=Ur||Pr&&Ft&&T||st;if(gt&&!ir){let qr=e.getRootNode(),Br=qr instanceof ShadowRoot?qr.host:e.closest(".persona-host");Br&&!sr&&(sr=ip(Br,(cr=(pt=n.launcher)==null?void 0:pt.zIndex)!=null?cr:Or)),ir=lp(e.ownerDocument)}else gt||(sr==null||sr(),sr=null,ir==null||ir(),ir=null)}}};fe();let te=(Fu=e.ownerDocument.defaultView)!=null?Fu:window;if(te.addEventListener("resize",fe),vt.push(()=>te.removeEventListener("resize",fe)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Rr()});c.observe(qe),vt.push(()=>c.disconnect())}Rn=ve.scrollTop;let et=ve.scrollHeight,ze=()=>{let c=ve.scrollTop,g=ve.scrollHeight,x=g<et;et=g;let{action:w,nextLastScrollTop:O}=Ki({following:In.isFollowing(),currentScrollTop:c,lastScrollTop:Rn,nearBottom:ws(ve,Fa),userScrollThreshold:Ns,isAutoScrolling:Gn||Ro||x,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Rn=O,w==="resume"){mo();return}w==="pause"&&$a()};ve.addEventListener("scroll",ze,{passive:!0}),vt.push(()=>ve.removeEventListener("scroll",ze));let ct=c=>{let g=Yi({following:In.isFollowing(),deltaY:c.deltaY,nearBottom:ws(ve,Fa),resumeWhenNearBottom:!0});g==="pause"?$a():g==="resume"&&mo()};ve.addEventListener("wheel",ct,{passive:!0}),vt.push(()=>ve.removeEventListener("wheel",ct)),it.addEventListener("click",()=>{ve.scrollTop=ve.scrollHeight,Rn=ve.scrollTop,mo(),go(!0)}),vt.push(()=>it.remove()),vt.push(()=>{_a()});let at=()=>{F&&(sn&&(F.removeEventListener("click",sn),sn=null),W()?(F.style.display="",sn=()=>{Nt(!1,"user")},F.addEventListener("click",sn)):F.style.display="none")};at(),(()=>{let{clearChatButton:c}=ke;c&&c.addEventListener("click",()=>{q.clearMessages(),ln.clear(),mo(),Lo(ke.composerOverlay);try{localStorage.removeItem(Wa),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(x){console.error("[AgentWidget] Failed to clear default localStorage:",x)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wa)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(x){console.error("[AgentWidget] Failed to clear custom localStorage:",x)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let x=i.clear();x instanceof Promise&&x.catch(w=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)}d={},k.syncFromMetadata(),J==null||J.clear(),ce==null||ce.update()})})(),Ot&&Ot.addEventListener("submit",Ga),ne==null||ne.addEventListener("keydown",Xa),ne==null||ne.addEventListener("paste",Ja);let Gt="persona-attachment-drop-active",lr=0,Rt=()=>{lr=0,ae.classList.remove(Gt)},Lt=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&Tt!==null},yr=c=>{!Sl(c.dataTransfer)||!Lt()||(lr++,lr===1&&ae.classList.add(Gt))},Hr=c=>{!Sl(c.dataTransfer)||!Lt()||(lr--,lr<=0&&Rt())},Mr=c=>{!Sl(c.dataTransfer)||!Lt()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},dr=c=>{var x;if(!Sl(c.dataTransfer)||!Lt())return;c.preventDefault(),c.stopPropagation(),Rt();let g=Array.from((x=c.dataTransfer.files)!=null?x:[]);g.length!==0&&Tt.handleFiles(g)},vr=!0;ae.addEventListener("dragenter",yr,vr),ae.addEventListener("dragleave",Hr,vr),e.addEventListener("dragover",Mr,vr),e.addEventListener("drop",dr,vr);let ei=e.ownerDocument,Kp=c=>{Lt()&&c.preventDefault()},Yp=c=>{Lt()&&c.preventDefault()};ei.addEventListener("dragover",Kp),ei.addEventListener("drop",Yp),vt.push(()=>{Ot&&Ot.removeEventListener("submit",Ga),ne==null||ne.removeEventListener("keydown",Xa),ne==null||ne.removeEventListener("paste",Ja)}),vt.push(()=>{ae.removeEventListener("dragenter",yr,vr),ae.removeEventListener("dragleave",Hr,vr),e.removeEventListener("dragover",Mr,vr),e.removeEventListener("drop",dr,vr),ei.removeEventListener("dragover",Kp),ei.removeEventListener("drop",Yp),Rt()}),vt.push(()=>{q.cancel()}),I?vt.push(()=>{I==null||I.destroy()}):V&&vt.push(()=>{V==null||V.remove()});let mr={update(c){var gr,$n,eo,ti,ri,ni,$o,oi,Ya,Vu,ju,Gu,Xu,Ju,Ku,Yu,Qu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,Cf,wf,vf,Af,Sf,Tf,kf,Ef,Mf,Lf,Pf,If,Rf,Hf,Bf,Wf,Df,Of,Ff,Nf,_f,$f,Uf,qf,zf,Vf,jf,Gf,Xf,Jf,Kf,Yf,Qf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,Cm,wm,vm,Am,Sm,Tm,km,Em,Mm,Lm,Pm,Im,Rm,Hm,Bm,Wm,Dm,Om,Fm,Nm,_m,$m;let g=n.toolCall,x=n.messageActions,w=(gr=n.layout)==null?void 0:gr.messages,O=n.colorScheme,$=n.loadingIndicator,U=n.iterationDisplay,X=($n=n.features)==null?void 0:$n.showReasoning,_=(eo=n.features)==null?void 0:eo.showToolCalls,Te=(ti=n.features)==null?void 0:ti.toolCallDisplay,me=(ri=n.features)==null?void 0:ri.reasoningDisplay;n={...n,...c},Mn(),vo(e,n),gl(e,n),hl(e,n),on(),n.colorScheme!==O&&fo();let re=Bs.getForInstance(n.plugins);o.length=0,o.push(...re),T=($o=(ni=n.launcher)==null?void 0:ni.enabled)!=null?$o:!0,S=(Ya=(oi=n.launcher)==null?void 0:oi.autoExpand)!=null?Ya:!1,De=(ju=(Vu=n.features)==null?void 0:Vu.showReasoning)!=null?ju:!0,Xe=(Xu=(Gu=n.features)==null?void 0:Gu.showToolCalls)!=null?Xu:!0,ge=(Ku=(Ju=n.features)==null?void 0:Ju.scrollToBottom)!=null?Ku:{},Tn(),Jn();let be=xe;if(xe=(Qu=(Yu=n.features)==null?void 0:Yu.showEventStreamToggle)!=null?Qu:!1,xe&&!be){if(J||(Q=new Hs(Ge),J=new Rs(Se,Q),Q.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),q.setSSEEventCallback((ee,Ht)=>{var Xt;(Xt=n.onSSEEvent)==null||Xt.call(n,ee,Ht),J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Ht)})})),!xt&&Ue){let ee=(ef=(Zu=n.features)==null?void 0:Zu.eventStream)==null?void 0:ef.classNames,Ht="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"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");xt=h("button",Ht),xt.style.width="28px",xt.style.height="28px",xt.style.color=Kr.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Xt=Ce("activity","18px","currentColor",1.5);Xt&&xt.appendChild(Xt);let ht=ke.clearChatButtonWrapper,Wt=ke.closeButtonWrapper,br=ht||Wt;br&&br.parentNode===Ue?Ue.insertBefore(xt,br):Ue.appendChild(xt),xt.addEventListener("click",()=>{pe?Yr():Sr()})}}else!xe&&be&&(Yr(),xt&&(xt.remove(),xt=null),J==null||J.clear(),Q==null||Q.destroy(),J=null,Q=null);if(((tf=n.launcher)==null?void 0:tf.enabled)===!1&&I&&(I.destroy(),I=null),((rf=n.launcher)==null?void 0:rf.enabled)===!1&&V&&(V.remove(),V=null),((nf=n.launcher)==null?void 0:nf.enabled)!==!1&&!I&&!V){let ee=o.find(Ht=>Ht.renderLauncher);if(ee!=null&&ee.renderLauncher){let Ht=ee.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});Ht&&(V=Ht,e.appendChild(V))}V||(I=Ms(n,z),e.appendChild(I.element))}I&&I.update(n),Fe&&((of=n.launcher)==null?void 0:of.title)!==void 0&&(Fe.textContent=n.launcher.title),Ke&&((af=n.launcher)==null?void 0:af.subtitle)!==void 0&&(Ke.textContent=n.launcher.subtitle);let Me=(sf=n.layout)==null?void 0:sf.header;if((Me==null?void 0:Me.layout)!==v&&Ue){let ee=Me?Ta(n,Me,{showClose:W(),onClose:()=>Nt(!1,"user")}):ao({config:n,showClose:W(),onClose:()=>Nt(!1,"user")});Ue.replaceWith(ee.header),Ue=ee.header,le=ee.iconHolder,Fe=ee.headerTitle,Ke=ee.headerSubtitle,F=ee.closeButton,v=Me==null?void 0:Me.layout}else if(Me&&(le&&(le.style.display=Me.showIcon===!1?"none":""),Fe&&(Fe.style.display=Me.showTitle===!1?"none":""),Ke&&(Ke.style.display=Me.showSubtitle===!1?"none":""),F&&(F.style.display=Me.showCloseButton===!1?"none":""),ke.clearChatButtonWrapper)){let ee=Me.showClearChat;if(ee!==void 0){ke.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ht}=ke;Ht&&!Ht.classList.contains("persona-absolute")&&(ee?Ht.classList.remove("persona-ml-auto"):Ht.classList.add("persona-ml-auto"))}}let lt=((lf=n.layout)==null?void 0:lf.showHeader)!==!1;Ue&&(Ue.style.display=lt?"":"none");let tt=((df=n.layout)==null?void 0:df.showFooter)!==!1;qe&&(qe.style.display=tt?"":"none"),Rr(),Jn(),T!==y?T?Nt(S,"auto"):(R=!0,bo()):S!==b&&Nt(S,"auto"),b=S,y=T,fe(),at();let We=JSON.stringify(c.toolCall)!==JSON.stringify(g),Be=JSON.stringify(n.messageActions)!==JSON.stringify(x),Je=JSON.stringify((cf=n.layout)==null?void 0:cf.messages)!==JSON.stringify(w),D=((pf=n.loadingIndicator)==null?void 0:pf.render)!==($==null?void 0:$.render)||((uf=n.loadingIndicator)==null?void 0:uf.renderIdle)!==($==null?void 0:$.renderIdle)||((ff=n.loadingIndicator)==null?void 0:ff.showBubble)!==($==null?void 0:$.showBubble),Re=n.iterationDisplay!==U,Ne=((gf=(mf=n.features)==null?void 0:mf.showReasoning)!=null?gf:!0)!==(X!=null?X:!0)||((xf=(hf=n.features)==null?void 0:hf.showToolCalls)!=null?xf:!0)!==(_!=null?_:!0)||JSON.stringify((yf=n.features)==null?void 0:yf.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((bf=n.features)==null?void 0:bf.reasoningDisplay)!==JSON.stringify(me);(We||Be||Je||D||Re||Ne)&&q&&(Oa++,Bo(ye,q.getMessages(),ue));let Ae=(Cf=n.launcher)!=null?Cf:{},Dt=(wf=Ae.headerIconHidden)!=null?wf:!1,pt=(Af=(vf=n.layout)==null?void 0:vf.header)==null?void 0:Af.showIcon,cr=Dt||pt===!1,Lr=Ae.headerIconName,Ft=(Sf=Ae.headerIconSize)!=null?Sf:"48px";if(le){let ee=ae.querySelector(".persona-border-b-persona-divider"),Ht=ee==null?void 0:ee.querySelector(".persona-flex-col");if(cr)le.style.display="none",ee&&Ht&&!ee.contains(Ht)&&ee.insertBefore(Ht,ee.firstChild);else{if(le.style.display="",le.style.height=Ft,le.style.width=Ft,ee&&Ht&&(ee.contains(le)?le.nextSibling!==Ht&&(le.remove(),ee.insertBefore(le,Ht)):ee.insertBefore(le,Ht)),Lr){let ht=parseFloat(Ft)||24,Wt=Ce(Lr,ht*.6,"#ffffff",2);Wt?le.replaceChildren(Wt):le.textContent=(Tf=Ae.agentIconText)!=null?Tf:"\u{1F4AC}"}else if(Ae.iconUrl){let ht=le.querySelector("img");if(ht)ht.src=Ae.iconUrl,ht.style.height=Ft,ht.style.width=Ft;else{let Wt=document.createElement("img");Wt.src=Ae.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=Ft,Wt.style.width=Ft,le.replaceChildren(Wt)}}else{let ht=le.querySelector("svg"),Wt=le.querySelector("img");(ht||Wt)&&le.replaceChildren(),le.textContent=(kf=Ae.agentIconText)!=null?kf:"\u{1F4AC}"}let Xt=le.querySelector("img");Xt&&(Xt.style.height=Ft,Xt.style.width=Ft)}}let Ur=(Mf=(Ef=n.layout)==null?void 0:Ef.header)==null?void 0:Mf.showTitle,Pr=(Pf=(Lf=n.layout)==null?void 0:Lf.header)==null?void 0:Pf.showSubtitle;if(Fe&&(Fe.style.display=Ur===!1?"none":""),Ke&&(Ke.style.display=Pr===!1?"none":""),F){((Rf=(If=n.layout)==null?void 0:If.header)==null?void 0:Rf.showCloseButton)===!1?F.style.display="none":F.style.display="";let Ht=(Hf=Ae.closeButtonSize)!=null?Hf:"32px",Xt=(Bf=Ae.closeButtonPlacement)!=null?Bf:"inline";F.style.height=Ht,F.style.width=Ht;let{closeButtonWrapper:ht}=ke,Wt=Xt==="top-right",br=ht==null?void 0:ht.classList.contains("persona-absolute");if(ht&&Wt!==br)if(ht.remove(),Wt)ht.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ae.style.position="relative",ae.appendChild(ht);else{let yt=(Df=(Wf=Ae.clearChat)==null?void 0:Wf.placement)!=null?Df:"inline",Cr=(Ff=(Of=Ae.clearChat)==null?void 0:Of.enabled)!=null?Ff:!0;ht.className=Cr&&yt==="inline"?"":"persona-ml-auto";let rn=ae.querySelector(".persona-border-b-persona-divider");rn&&rn.appendChild(ht)}if(F.style.color=Ae.closeButtonColor||Kr.actionIconColor,Ae.closeButtonBackgroundColor?(F.style.backgroundColor=Ae.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),Ae.closeButtonBorderWidth||Ae.closeButtonBorderColor){let yt=Ae.closeButtonBorderWidth||"0px",Cr=Ae.closeButtonBorderColor||"transparent";F.style.border=`${yt} solid ${Cr}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");Ae.closeButtonBorderRadius?(F.style.borderRadius=Ae.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),Ae.closeButtonPaddingX?(F.style.paddingLeft=Ae.closeButtonPaddingX,F.style.paddingRight=Ae.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),Ae.closeButtonPaddingY?(F.style.paddingTop=Ae.closeButtonPaddingY,F.style.paddingBottom=Ae.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Wr=(Nf=Ae.closeButtonIconName)!=null?Nf:"x",Dn=(_f=Ae.closeButtonIconText)!=null?_f:"\xD7";F.innerHTML="";let Vr=Ce(Wr,"28px","currentColor",1);Vr?F.appendChild(Vr):F.textContent=Dn;let pr=($f=Ae.closeButtonTooltipText)!=null?$f:"Close chat",pn=(Uf=Ae.closeButtonShowTooltip)!=null?Uf:!0;if(F.setAttribute("aria-label",pr),ht&&(ht._cleanupTooltip&&(ht._cleanupTooltip(),delete ht._cleanupTooltip),pn&&pr)){let yt=null,Cr=()=>{if(yt||!F)return;let Uo=F.ownerDocument,Qa=Uo.body;if(!Qa)return;yt=qn(Uo,"div","persona-clear-chat-tooltip"),yt.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",yt.appendChild(Za);let qo=F.getBoundingClientRect();yt.style.position="fixed",yt.style.zIndex=String(Ao),yt.style.left=`${qo.left+qo.width/2}px`,yt.style.top=`${qo.top-8}px`,yt.style.transform="translate(-50%, -100%)",Qa.appendChild(yt)},rn=()=>{yt&&yt.parentNode&&(yt.parentNode.removeChild(yt),yt=null)};ht.addEventListener("mouseenter",Cr),ht.addEventListener("mouseleave",rn),F.addEventListener("focus",Cr),F.addEventListener("blur",rn),ht._cleanupTooltip=()=>{rn(),ht&&(ht.removeEventListener("mouseenter",Cr),ht.removeEventListener("mouseleave",rn)),F&&(F.removeEventListener("focus",Cr),F.removeEventListener("blur",rn))}}}let{clearChatButton:st,clearChatButtonWrapper:gt}=ke;if(st){let ee=(qf=Ae.clearChat)!=null?qf:{},Ht=(zf=ee.enabled)!=null?zf:!0,Xt=(jf=(Vf=n.layout)==null?void 0:Vf.header)==null?void 0:jf.showClearChat,ht=Xt!==void 0?Xt:Ht,Wt=(Gf=ee.placement)!=null?Gf:"inline";if(gt){gt.style.display=ht?"":"none";let{closeButtonWrapper:br}=ke;!B()&&br&&!br.classList.contains("persona-absolute")&&(ht?br.classList.remove("persona-ml-auto"):br.classList.add("persona-ml-auto"));let Wr=Wt==="top-right",Dn=gt.classList.contains("persona-absolute");if(!B()&&Wr!==Dn&&ht){if(gt.remove(),Wr)gt.className="persona-absolute persona-top-4 persona-z-50",gt.style.right="48px",ae.style.position="relative",ae.appendChild(gt);else{gt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gt.style.right="";let pr=ae.querySelector(".persona-border-b-persona-divider"),pn=ke.closeButtonWrapper;pr&&pn&&pn.parentElement===pr?pr.insertBefore(gt,pn):pr&&pr.appendChild(gt)}let Vr=ke.closeButtonWrapper;Vr&&!Vr.classList.contains("persona-absolute")&&(Wr?Vr.classList.add("persona-ml-auto"):Vr.classList.remove("persona-ml-auto"))}}if(ht){if(!B()){let yt=(Xf=ee.size)!=null?Xf:"32px";st.style.height=yt,st.style.width=yt}let br=(Jf=ee.iconName)!=null?Jf:"refresh-cw",Wr=(Kf=ee.iconColor)!=null?Kf:"";st.style.color=Wr||Kr.actionIconColor,st.innerHTML="";let Dn=B()?"14px":"20px",Vr=Ce(br,Dn,"currentColor",2);if(Vr&&st.appendChild(Vr),ee.backgroundColor?(st.style.backgroundColor=ee.backgroundColor,st.classList.remove("hover:persona-bg-gray-100")):(st.style.backgroundColor="",st.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let yt=ee.borderWidth||"0px",Cr=ee.borderColor||"transparent";st.style.border=`${yt} solid ${Cr}`,st.classList.remove("persona-border-none")}else st.style.border="",st.classList.add("persona-border-none");ee.borderRadius?(st.style.borderRadius=ee.borderRadius,st.classList.remove("persona-rounded-full")):(st.style.borderRadius="",st.classList.add("persona-rounded-full")),ee.paddingX?(st.style.paddingLeft=ee.paddingX,st.style.paddingRight=ee.paddingX):(st.style.paddingLeft="",st.style.paddingRight=""),ee.paddingY?(st.style.paddingTop=ee.paddingY,st.style.paddingBottom=ee.paddingY):(st.style.paddingTop="",st.style.paddingBottom="");let pr=(Yf=ee.tooltipText)!=null?Yf:"Clear chat",pn=(Qf=ee.showTooltip)!=null?Qf:!0;if(st.setAttribute("aria-label",pr),gt&&(gt._cleanupTooltip&&(gt._cleanupTooltip(),delete gt._cleanupTooltip),pn&&pr)){let yt=null,Cr=()=>{if(yt||!st)return;let Uo=st.ownerDocument,Qa=Uo.body;if(!Qa)return;yt=qn(Uo,"div","persona-clear-chat-tooltip"),yt.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",yt.appendChild(Za);let qo=st.getBoundingClientRect();yt.style.position="fixed",yt.style.zIndex=String(Ao),yt.style.left=`${qo.left+qo.width/2}px`,yt.style.top=`${qo.top-8}px`,yt.style.transform="translate(-50%, -100%)",Qa.appendChild(yt)},rn=()=>{yt&&yt.parentNode&&(yt.parentNode.removeChild(yt),yt=null)};gt.addEventListener("mouseenter",Cr),gt.addEventListener("mouseleave",rn),st.addEventListener("focus",Cr),st.addEventListener("blur",rn),gt._cleanupTooltip=()=>{rn(),gt&&(gt.removeEventListener("mouseenter",Cr),gt.removeEventListener("mouseleave",rn)),st&&(st.removeEventListener("focus",Cr),st.removeEventListener("blur",rn))}}}}let qr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ws],Br=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[sa.message,sa.messageAndClick];k=Ds({parsers:qr,handlers:Br,getSessionMetadata:f,updateSessionMetadata:m,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),ue=Uh(n,k,oe),q.updateConfig(n),Bo(ye,q.getMessages(),ue),Ln.render(n.suggestionChips,q,ne,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming());let Oo=((Zf=n.voiceRecognition)==null?void 0:Zf.enabled)===!0,Fo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),No=((tm=(em=n.voiceRecognition)==null?void 0:em.provider)==null?void 0:tm.type)==="runtype";if(Oo&&(Fo||No))if(!N||!de){let ee=Ys(n.voiceRecognition,n.sendButton);ee&&(N=ee.micButton,de=ee.micButtonWrapper,Pt.insertBefore(de,fr),N.addEventListener("click",Qn),N.disabled=q.isStreaming())}else{let ee=(rm=n.voiceRecognition)!=null?rm:{},Ht=(nm=n.sendButton)!=null?nm:{},Xt=(om=ee.iconName)!=null?om:"mic",ht=(am=Ht.size)!=null?am:"40px",Wt=(sm=ee.iconSize)!=null?sm:ht,br=parseFloat(Wt)||24;N.style.width=Wt,N.style.height=Wt,N.style.minWidth=Wt,N.style.minHeight=Wt;let Wr=(lm=(im=ee.iconColor)!=null?im:Ht.textColor)!=null?lm:"currentColor";N.innerHTML="";let Dn=Ce(Xt,br,Wr,2);Dn?N.appendChild(Dn):N.textContent="\u{1F3A4}";let Vr=(dm=ee.backgroundColor)!=null?dm:Ht.backgroundColor;Vr?N.style.backgroundColor=Vr:N.style.backgroundColor="",Wr?N.style.color=Wr:N.style.color="var(--persona-text, #111827)",ee.borderWidth?(N.style.borderWidth=ee.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),ee.borderColor?N.style.borderColor=ee.borderColor:N.style.borderColor="",ee.paddingX?(N.style.paddingLeft=ee.paddingX,N.style.paddingRight=ee.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),ee.paddingY?(N.style.paddingTop=ee.paddingY,N.style.paddingBottom=ee.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let pr=de==null?void 0:de.querySelector(".persona-send-button-tooltip"),pn=(cm=ee.tooltipText)!=null?cm:"Start voice recognition";if(((pm=ee.showTooltip)!=null?pm:!1)&&pn)if(pr)pr.textContent=pn,pr.style.display="";else{let Cr=document.createElement("div");Cr.className="persona-send-button-tooltip",Cr.textContent=pn,de==null||de.insertBefore(Cr,N)}else pr&&(pr.style.display="none");de.style.display="",N.disabled=q.isStreaming()}else N&&de&&(de.style.display="none",((fm=(um=n.voiceRecognition)==null?void 0:um.provider)==null?void 0:fm.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():dn&&Bn());if(((mm=n.attachments)==null?void 0:mm.enabled)===!0)if(!ut||!Ee){let ee=(gm=n.attachments)!=null?gm:{},Xt=(xm=((hm=n.sendButton)!=null?hm:{}).size)!=null?xm:"40px";Ut||(Ut=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",Ot.insertBefore(Ut,ne)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((ym=ee.allowedTypes)!=null?ym:oo).join(","),Ye.multiple=((bm=ee.maxFiles)!=null?bm:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),Ot.insertBefore(Ye,ne)),ut=h("div","persona-send-button-wrapper"),Ee=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ee.type="button",Ee.setAttribute("aria-label",(Cm=ee.buttonTooltipText)!=null?Cm:"Attach file");let ht=(wm=ee.buttonIconName)!=null?wm:"paperclip",Wt=Xt,br=parseFloat(Wt)||40,Wr=Math.round(br*.6);Ee.style.width=Wt,Ee.style.height=Wt,Ee.style.minWidth=Wt,Ee.style.minHeight=Wt,Ee.style.fontSize="18px",Ee.style.lineHeight="1",Ee.style.backgroundColor="transparent",Ee.style.color="var(--persona-primary, #111827)",Ee.style.border="none",Ee.style.borderRadius="6px",Ee.style.transition="background-color 0.15s ease",Ee.addEventListener("mouseenter",()=>{Ee.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ee.addEventListener("mouseleave",()=>{Ee.style.backgroundColor="transparent"});let Dn=Ce(ht,Wr,"currentColor",1.5);Dn?Ee.appendChild(Dn):Ee.textContent="\u{1F4CE}",Ee.addEventListener("click",pn=>{pn.preventDefault(),Ye==null||Ye.click()}),ut.appendChild(Ee);let Vr=(vm=ee.buttonTooltipText)!=null?vm:"Attach file",pr=h("div","persona-send-button-tooltip");pr.textContent=Vr,ut.appendChild(pr),Ct.append(ut),!Tt&&Ye&&Ut&&(Tt=ta.fromConfig(ee),Tt.setPreviewsContainer(Ut),Ye.addEventListener("change",async()=>{Tt&&(Ye!=null&&Ye.files)&&(await Tt.handleFileSelect(Ye.files),Ye.value="")})),ae.querySelector(".persona-attachment-drop-overlay")||ae.appendChild(qh(ee.dropOverlay))}else{ut.style.display="";let ee=(Am=n.attachments)!=null?Am:{};Ye&&(Ye.accept=((Sm=ee.allowedTypes)!=null?Sm:oo).join(","),Ye.multiple=((Tm=ee.maxFiles)!=null?Tm:4)>1),Tt&&Tt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ut&&(ut.style.display="none"),Tt&&Tt.clearAttachments(),(km=ae.querySelector(".persona-attachment-drop-overlay"))==null||km.remove();let rr=(Em=n.sendButton)!=null?Em:{},_o=(Mm=rr.useIcon)!=null?Mm:!1,wo=(Lm=rr.iconText)!=null?Lm:"\u2191",Et=rr.iconName,Zr=(Pm=rr.tooltipText)!=null?Pm:"Send message",Zn=(Im=rr.showTooltip)!=null?Im:!1,zr=(Rm=rr.size)!=null?Rm:"40px",en=rr.backgroundColor,zt=rr.textColor;if(_o){if(He.style.width=zr,He.style.height=zr,He.style.minWidth=zr,He.style.minHeight=zr,He.style.fontSize="18px",He.style.lineHeight="1",He.innerHTML="",zt?He.style.color=zt:He.style.color="var(--persona-button-primary-fg, #ffffff)",Et){let ee=parseFloat(zr)||24,Ht=(zt==null?void 0:zt.trim())||"currentColor",Xt=Ce(Et,ee,Ht,2);Xt?He.appendChild(Xt):He.textContent=wo}else He.textContent=wo;He.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",en?(He.style.backgroundColor=en,He.classList.remove("persona-bg-persona-primary")):(He.style.backgroundColor="",He.classList.add("persona-bg-persona-primary"))}else He.textContent=(Bm=(Hm=n.copy)==null?void 0:Hm.sendButtonLabel)!=null?Bm:"Send",He.style.width="",He.style.height="",He.style.minWidth="",He.style.minHeight="",He.style.fontSize="",He.style.lineHeight="",He.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",en?(He.style.backgroundColor=en,He.classList.remove("persona-bg-persona-accent")):He.classList.add("persona-bg-persona-accent"),zt?He.style.color=zt:He.classList.add("persona-text-white");rr.borderWidth?(He.style.borderWidth=rr.borderWidth,He.style.borderStyle="solid"):(He.style.borderWidth="",He.style.borderStyle=""),rr.borderColor?He.style.borderColor=rr.borderColor:He.style.borderColor="",rr.paddingX?(He.style.paddingLeft=rr.paddingX,He.style.paddingRight=rr.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),rr.paddingY?(He.style.paddingTop=rr.paddingY,He.style.paddingBottom=rr.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Zt=fr==null?void 0:fr.querySelector(".persona-send-button-tooltip");if(Zn&&Zr)if(Zt)Zt.textContent=Zr,Zt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=Zr,fr==null||fr.insertBefore(ee,He)}else Zt&&(Zt.style.display="none");let Vt=(Nm=(Wm=n.layout)==null?void 0:Wm.contentMaxWidth)!=null?Nm:B()?(Fm=(Om=(Dm=n.launcher)==null?void 0:Dm.composerBar)==null?void 0:Om.contentMaxWidth)!=null?Fm:"720px":void 0;Vt?(ye.style.maxWidth=Vt,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",Ot&&(Ot.style.maxWidth=Vt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=Vt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(ye.style.maxWidth="",ye.style.marginLeft="",ye.style.marginRight="",ye.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let nr=(_m=n.statusIndicator)!=null?_m:{},tn=($m=nr.visible)!=null?$m:!0;if(Yt.style.display=tn?"":"none",q){let ee=q.getStatus();$e(Yt,(Xt=>{var ht,Wt,br,Wr;return Xt==="idle"?(ht=nr.idleText)!=null?ht:Dr.idle:Xt==="connecting"?(Wt=nr.connectingText)!=null?Wt:Dr.connecting:Xt==="connected"?(br=nr.connectedText)!=null?br:Dr.connected:Xt==="error"?(Wr=nr.errorText)!=null?Wr:Dr.error:Dr[Xt]})(ee),nr,ee)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let cn=nr.align==="left"?"persona-text-left":nr.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(cn)},open(){W()&&Nt(!0,"api")},close(){W()&&Nt(!1,"api")},toggle(){W()&&Nt(!R,"api")},clearChat(){Z=!1,q.clearMessages(),ln.clear(),mo();try{localStorage.removeItem(Wa),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wa)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(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},k.syncFromMetadata(),J==null||J.clear(),ce==null||ce.update()},setMessage(c){return!ne||q.isStreaming()?!1:(!R&&W()&&Nt(!0,"system"),ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ne.value.trim();return g?(!R&&W()&&Nt(!0,"system"),ne.value="",ne.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,x;return q.isStreaming()?!1:((x=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:x.type)==="runtype"?(q.isVoiceActive()||(!R&&W()&&Nt(!0,"system"),bt.manuallyDeactivated=!1,Qr(),q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("user"),q.isVoiceActive()&&Co()})),!0):dn?!0:Ka()?(!R&&W()&&Nt(!0,"system"),bt.manuallyDeactivated=!1,Qr(),Wo("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(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()}),!0):!1:dn?(bt.manuallyDeactivated=!0,Qr(),Bn("user"),!0):!1},injectMessage(c){return!R&&W()&&Nt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!R&&W()&&Nt(!0,"system");let g=q.injectAssistantMessage(c);return H&&(H=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!R&&W()&&Nt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!R&&W()&&Nt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!R&&W()&&Nt(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!R&&W()&&Nt(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!R&&W()&&Nt(!0,"system"),q.injectTestEvent(c)},async connectStream(c,g){return q.connectStream(c,g)},__pushEventStreamEvent(c){J&&J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!xe||!J||Sr()},hideEventStream(){pe&&Yr()},isEventStreamVisible(){return pe},showArtifacts(){Sn(n)&&(Z=!1,on(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){Sn(n)&&(Z=!0,on())},upsertArtifact(c){return Sn(n)?(Z=!1,q.upsertArtifact(c)):null},selectArtifact(c){Sn(n)&&q.selectArtifact(c)},clearArtifacts(){Sn(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&&!R&&!B()||!ne?!1:(ne.focus(),!0)},async resolveApproval(c,g){let w=q.getMessages().find(O=>{var $;return O.variant==="approval"&&(($=O.approval)==null?void 0:$.id)===c});if(!(w!=null&&w.approval))throw new Error(`Approval not found: ${c}`);return q.resolveApproval(w.approval,g)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return a.on(c,g)},off(c,g){a.off(c,g)},isOpen(){return W()&&R},isVoiceActive(){return bt.active},getState(){return{open:W()&&R,launcherEnabled:T,voiceActive:bt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!R&&W()&&Nt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let x=vl({onSubmit:async(w,O)=>{var $;q.isClientTokenMode()&&await q.submitCSATFeedback(w,O),($=c==null?void 0:c.onSubmit)==null||$.call(c,w,O)},onDismiss:c==null?void 0:c.onDismiss,...c});ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&W()&&Nt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let x=Al({onSubmit:async(w,O)=>{var $;q.isClientTokenMode()&&await q.submitNPSFeedback(w,O),($=c==null?void 0:c.onSubmit)==null||$.call(c,w,O)},onDismiss:c==null?void 0:c.onDismiss,...c});ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return q.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return q.submitNPSFeedback(c,g)},destroy(){_n!=null&&(clearInterval(_n),_n=null),vt.forEach(c=>c()),Y.remove(),we==null||we.remove(),I==null||I.destroy(),V==null||V.remove(),sn&&F.removeEventListener("click",sn)}};if((((Nu=t==null?void 0:t.debugTools)!=null?Nu:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:mr,getMessages:mr.getMessages,getStatus:mr.getStatus,getMetadata:mr.getPersistentMetadata,updateMetadata:mr.updatePersistentMetadata,clearHistory:()=>mr.clearChat(),setVoiceActive:x=>x?mr.startVoiceRecognition():mr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,vt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.focusInput()};if(window.addEventListener("persona:focusInput",g),vt.push(()=>{window.removeEventListener("persona:focusInput",g)}),xe){let X=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&mr.showEventStream()},_=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&mr.hideEventStream()};window.addEventListener("persona:showEventStream",X),window.addEventListener("persona:hideEventStream",_),vt.push(()=>{window.removeEventListener("persona:showEventStream",X),window.removeEventListener("persona:hideEventStream",_)})}let x=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.showArtifacts()},w=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.hideArtifacts()},O=X=>{let _=X.detail;_!=null&&_.instanceId&&_.instanceId!==c||_!=null&&_.artifact&&mr.upsertArtifact(_.artifact)},$=X=>{let _=X.detail;_!=null&&_.instanceId&&_.instanceId!==c||typeof(_==null?void 0:_.id)=="string"&&mr.selectArtifact(_.id)},U=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",O),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),vt.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",O),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let Cn=X0(n.persistState);if(Cn&&W()){let c=J0(Cn.storage),g=`${Cn.keyPrefix}widget-open`,x=`${Cn.keyPrefix}widget-voice`,w=`${Cn.keyPrefix}widget-voice-mode`;if(c){let O=((_u=Cn.persist)==null?void 0:_u.openState)&&c.getItem(g)==="true",$=(($u=Cn.persist)==null?void 0:$u.voiceState)&&c.getItem(x)==="true",U=((Uu=Cn.persist)==null?void 0:Uu.voiceState)&&c.getItem(w)==="true";if(O&&setTimeout(()=>{mr.open(),setTimeout(()=>{var X;if($||U)mr.startVoiceRecognition();else if((X=Cn.persist)!=null&&X.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(qu=Cn.persist)!=null&&qu.openState&&(a.on("widget:opened",()=>{c.setItem(g,"true")}),a.on("widget:closed",()=>{c.setItem(g,"false")})),(zu=Cn.persist)!=null&&zu.voiceState&&(a.on("voice:state",X=>{c.setItem(x,X.active?"true":"false")}),a.on("user:message",X=>{c.setItem(w,X.viaVoice?"true":"false")})),Cn.clearOnChatClear){let X=()=>{c.removeItem(g),c.removeItem(x),c.removeItem(w)},_=()=>X();window.addEventListener("persona:clear-chat",_),vt.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&W()&&setTimeout(()=>{mr.open()},0),Kn(),mr};var K0=(e,r)=>{let t=e.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,r*parseFloat(o[1])/100):420},zh=(e,r)=>{var n,o;let t=(o=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?o:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Wp=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Vh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Wp(e)},Rp=e=>{e.style.transition=""},Hp=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Bp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},kl=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Y0=(e,r,t,n,o)=>{o?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},Q0=(e,r,t,n,o,a)=>{let s=a?r:e;o==="left"?s.firstElementChild!==n&&s.replaceChildren(n,t):s.lastElementChild!==n&&s.replaceChildren(t,n)},jh=(e,r,t,n,o,a,s)=>{var C,A,k,T,S,E;let i=vn(a),d=i.reveal==="push";Y0(e,r,t,n,d),Q0(e,r,t,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",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=e.ownerDocument.defaultView,u=(A=(C=a==null?void 0:a.launcher)==null?void 0:C.mobileFullscreen)!=null?A:!0,p=(T=(k=a==null?void 0:a.launcher)==null?void 0:k.mobileBreakpoint)!=null?T:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hp(r),Rp(n),Vh(n),Bp(t),kl(o,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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((E=(S=a==null?void 0:a.launcher)==null?void 0:S.zIndex)!=null?E:Or),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Vh(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Hp(r),Rp(n),Bp(t),kl(o,n);let b=i.animate?"transform 180ms ease":"none",y=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=s?"translateX(0)":y;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=b,n.style.transform=v,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Rp(n),Wp(n),kl(o,n);let b=K0(i.width,e.clientWidth),y=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",M=i.side==="right"?s?`translateX(-${b}px)`:"translateX(0)":s?"translateX(0)":`translateX(-${b}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${y+b}px`,r.style.transition=v,r.style.transform=M,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${y}px`,t.style.maxWidth=`${y}px`,t.style.minWidth=`${y}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Hp(r),Wp(n),Bp(t),kl(o,n);let b=i.reveal==="emerge";b?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let y=s?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",M=!s;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${y}`,n.style.width=y,n.style.maxWidth=y,n.style.minWidth=y,n.style.minHeight="0",n.style.position="relative",n.style.overflow=b||M?"hidden":"visible",n.style.transition=v,b&&(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")}},Z0=(e,r)=>{let t=e.ownerDocument.createElement("div");return zh(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){zh(t,n)},destroy(){t.remove()}}},eC=(e,r)=>{var S,E,b,y;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(E=(S=r==null?void 0:r.launcher)==null?void 0:S.enabled)==null||E?(y=(b=r==null?void 0:r.launcher)==null?void 0:b.autoExpand)!=null?y:!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,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},C=()=>{m(),vn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{jh(s,i,d,l,u,r,p)}),f.observe(s))},A=()=>{jh(s,i,d,l,u,r,p),C()},k=s.ownerDocument.defaultView,T=()=>{A()};return k==null||k.addEventListener("resize",T),vn(r).reveal==="push"?(i.appendChild(d),i.appendChild(l),s.appendChild(i)):(s.appendChild(d),s.appendChild(l)),A(),{mode:"docked",host:u,shell:s,syncWidgetState(v){let M=v.launcherEnabled?v.open:!0;p!==M&&(p=M,A())},updateConfig(v){var M,B;r=v,((B=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)!=null?B:!0)===!1&&(p=!0),A()},destroy(){k==null||k.removeEventListener("resize",T),m(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}},Os=(e,r)=>hr(r)?eC(e,r):Z0(e,r);var Dp={},tC=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},rC=()=>{try{if(typeof Dp!="undefined"&&Dp.url)return new URL("../widget.css",Dp.url).href}catch{}return null},Gh=(e,r)=>{let t=rC(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=r.head.querySelector("link[data-persona]");if(!o)return;let a=o.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let a=r.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),r.head.appendChild(a)}},Xh=e=>{var k;let r=tC(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,o=e.config,a=Os(r,o),s,i=[],d=(T,S)=>{var v,M;let b=!((M=(v=S==null?void 0:S.launcher)==null?void 0:v.enabled)!=null?M:!0)||hr(S),y=n.createElement("div");if(y.setAttribute("data-persona-root","true"),b&&(y.style.height="100%",y.style.display="flex",y.style.flexDirection="column",y.style.flex="1",y.style.minHeight="0"),t){let B=T.attachShadow({mode:"open"});B.appendChild(y),Gh(B,n)}else T.appendChild(y),Gh(T,n);return r.id&&y.setAttribute("data-persona-instance",r.id),y},l=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},p=()=>{let T=d(a.host,o);s=Tl(T,o,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(T=>T()),i=[],s.destroy()};p(),(k=e.onReady)==null||k.call(e);let m=T=>{f(),a.destroy(),a=Os(r,T),o=T,p()},C={update(T){var M,B,W,R,H,j;let S={...o,...T,launcher:{...(M=o==null?void 0:o.launcher)!=null?M:{},...(B=T==null?void 0:T.launcher)!=null?B:{},dock:{...(R=(W=o==null?void 0:o.launcher)==null?void 0:W.dock)!=null?R:{},...(j=(H=T==null?void 0:T.launcher)==null?void 0:H.dock)!=null?j:{}}}},E=hr(o),b=hr(S),y=To(o),v=To(S);if(E!==b||y!==v){m(S);return}o=S,a.updateConfig(o),s.update(T),l()},destroy(){f(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},A=new Proxy(C,{get(T,S,E){if(S==="host")return a.host;if(S in T)return Reflect.get(T,S,E);let b=s[S];return typeof b=="function"?b.bind(s):b}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=A),A};var Zh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),nC=new Set(["button","a","input","select","textarea","details","summary"]),oC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Op=/\b(product|card|item|listing|result)\b/i,Np=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,aC=3e3,sC=100;function ex(e){let r=typeof e.className=="string"?e.className:"";if(Op.test(r)||e.id&&Op.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Op.test(n.value))return!0}return!1}function tx(e){var r;return Np.test(((r=e.textContent)!=null?r:"").trim())}function rx(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let o=(t=r[n].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function iC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Jh(e){let r=e.match(Np);return r?r[0]:null}function Kh(e){var n,o,a;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((o=r.textContent)!=null&&o.trim())){let s=r.getAttribute("href");return{title:r.textContent.trim(),href:s&&s!=="#"?s:null}}let t=e.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 lC(e){let r=[],t=n=>{let o=n.trim();o&&!r.includes(o)&&r.push(o)};return e.querySelectorAll("button").forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;t((o=n.value)!=null?o:"")}),r.slice(0,6)}var dC="commerce-card",cC="result-card";function Yh(e){return!ex(e)||!tx(e)||!rx(e)&&!iC(e)?0:5200}function Qh(e){var n;return!ex(e)||tx(e)||!rx(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var _p=[{id:dC,scoreElement(e){return Yh(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Np.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,l,u;if(Yh(e)===0)return null;let{title:t,href:n}=Kh(e),o=(u=(l=Jh(((d=e.textContent)!=null?d:"").trim()))!=null?l:Jh(r.text))!=null?u:"",a=lC(e);return[n&&t?`[${t}](${n})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||r.text.trim().slice(0,120),`selector: ${r.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
148
148
|
`)}},{id:cC,scoreElement(e){return Qh(e)},formatSummary(e,r){if(Qh(e)===0)return null;let{title:t,href:n}=Kh(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
|
|
149
|
-
`)}}];function pC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function uC(e){var u,p,m,
|
|
149
|
+
`)}}];function pC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function uC(e){var u,p,f,m,C,A,k,T,S,E,b,y,v;let r=(u=e.options)!=null?u:{},t=(f=(p=r.maxElements)!=null?p:e.maxElements)!=null?f:80,n=(C=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",o=(k=(A=r.maxTextLength)!=null?A:e.maxTextLength)!=null?k:200,a=(S=(T=r.visibleOnly)!=null?T:e.visibleOnly)!=null?S:!0,s=(E=r.root)!=null?E:e.root,i=(b=r.mode)!=null?b:"structured",d=(y=r.maxCandidates)!=null?y:Math.max(500,t*10),l=(v=e.rules)!=null?v:_p;return i==="simple"&&e.rules&&e.rules.length>0?(pC(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:l}}function Fp(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var fC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function mC(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||nC.has(r)||t&&oC.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function nx(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function gC(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let o=e.getAttribute("aria-label");o&&(r["aria-label"]=o);let a=e.getAttribute("type");a&&(r.type=a);let s=e.getAttribute("value");s&&(r.value=s);let i=e.getAttribute("name");i&&(r.name=i);let d=e.getAttribute("role");d&&(r.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(r[u.name]=u.value)}return r}function $p(e){let r=e.tagName.toLowerCase();if(e.id){let o=`#${Fp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of fC){let a=e.getAttribute(o);if(a){let s=`${r}[${o}="${Fp(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let t=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${r}.${t.map(s=>Fp(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let a=e.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(a>=0)return`${r}:nth-of-type(${a+1})`}return r}function hC(e){return e==="static"?sC:aC}function ox(e,r){var o;let t=e.tagName.toLowerCase(),n=((o=e.textContent)!=null?o:"").trim().substring(0,r);return{selector:$p(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:mC(e),attributes:gC(e)}}function xC(e,r,t,n){let o=hC(r.interactivity),a=null;for(let s of t){let i=s.scoreElement(e,r,n);i>0&&(o+=i,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function yC(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function bC(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Zh.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!nx(l)){i=s.nextNode();continue}let p=ox(l,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(k=>k==="role");if(!f&&!m){i=s.nextNode();continue}if(n.has(p.selector)){i=s.nextNode();continue}n.add(p.selector);let{score:C,formattingRule:A}=xC(l,p,e.rules,t);o.push({el:l,domIndex:a,enriched:p,score:C,formattingRule:A}),a+=1}i=s.nextNode()}o.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;yC(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,t);m&&(u=m)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function CC(e,r){let t=[],n=new Set,o=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&t.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let d=a,l=d.tagName.toLowerCase();if(Zh.has(l)){a=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!nx(d)){a=o.nextNode();continue}let u=ox(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){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,e.maxElements)}function ax(e={}){var n;let r=uC(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?CC(r,t):bC(r,t):[]}var El=100;function sx(e,r={}){var a;if(e.length===0)return"No page elements found.";let t=(a=r.mode)!=null?a:"structured",n=[];if(t==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&n.push(`Structured summaries:
|
|
150
150
|
${s.map(i=>`- ${i.split(`
|
|
151
151
|
`).join(`
|
|
152
152
|
`)}`).join(`
|
|
@@ -160,7 +160,7 @@ ${s.join(`
|
|
|
160
160
|
${s.join(`
|
|
161
161
|
`)}`)}return n.join(`
|
|
162
162
|
|
|
163
|
-
`)}var ix={name:"@runtypelabs/persona",version:"3.21.
|
|
163
|
+
`)}var ix={name:"@runtypelabs/persona",version:"3.21.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var ia=ix.version;function co(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function vC(e){if(e)return{getHeaders:co(e.getHeaders),onFeedback:co(e.onFeedback),onCopy:co(e.onCopy),requestMiddleware:co(e.requestMiddleware),actionHandlers:co(e.actionHandlers),actionParsers:co(e.actionParsers),postprocessMessage:co(e.postprocessMessage),contextProviders:co(e.contextProviders),streamParser:co(e.streamParser)}}var lx=`({ text, message }: any) => {
|
|
164
164
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
165
165
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
166
166
|
let cleanJson = jsonSource
|
|
@@ -480,7 +480,7 @@ ${s.join(`
|
|
|
480
480
|
min-height: 300px;
|
|
481
481
|
}
|
|
482
482
|
}
|
|
483
|
-
`;function HC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=RC,document.head.appendChild(e)}function BC(e,r){let t=e.clientWidth-qp*2-bx,n=e.clientHeight-qp*2-bx;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function WC(e,r,t,n,o){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=o==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Cx(e,r){let{items:t,initialIndex:n=0,initialDevice:o="desktop",initialColorScheme:a="light",showZoomControls:s=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");HC();let u=Math.max(0,Math.min(n,t.length-1)),p=o,
|
|
483
|
+
`;function HC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=RC,document.head.appendChild(e)}function BC(e,r){let t=e.clientWidth-qp*2-bx,n=e.clientHeight-qp*2-bx;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function WC(e,r,t,n,o){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=o==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Cx(e,r){let{items:t,initialIndex:n=0,initialDevice:o="desktop",initialColorScheme:a="light",showZoomControls:s=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");HC();let u=Math.max(0,Math.min(n,t.length-1)),p=o,f=a,m=null,C=1,A=!1,k=h("div","persona-dc-root"),T=h("div","persona-dc-toolbar"),S=h("div","persona-dc-toolbar-lead"),E=h("div","persona-dc-toolbar-trail"),b=Qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Oe(-1)}),y=h("div");y.style.position="relative";let v=h("button","persona-dc-title-btn");v.type="button",v.setAttribute("aria-expanded","false"),v.setAttribute("aria-haspopup","listbox");let M=h("span","persona-dc-title-text"),B=h("span","persona-dc-title-chevron"),W=Ce("chevron-down",12,"currentColor",2);W&&B.appendChild(W),v.append(M,B);let R=h("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let H=!1;function j(){R.innerHTML="";for(let Y=0;Y<t.length;Y++){let G=t[Y],we=h("button","persona-dc-dropdown-item");we.type="button",we.setAttribute("role","option"),we.setAttribute("aria-current",Y===u?"true":"false");let ke=h("span");if(ke.textContent=G.title,we.appendChild(ke),G.description){let ae=h("span","persona-dc-dropdown-desc");ae.textContent=G.description,we.appendChild(ae)}we.addEventListener("click",()=>{ue(),Pe(Y)}),R.appendChild(we)}}function oe(){H=!H,R.style.display=H?"":"none",v.setAttribute("aria-expanded",H?"true":"false"),H&&j()}function ue(){H&&(H=!1,R.style.display="none",v.setAttribute("aria-expanded","false"))}v.addEventListener("click",Y=>{Y.stopPropagation(),oe()});let De=()=>ue();document.addEventListener("click",De),y.append(v,R);let Xe=Qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Oe(1)}),xe=h("span","persona-dc-counter");S.append(b,y,Xe,xe);let ge=null;i&&(ge=Ps({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:Y=>{p=Y,J.dataset.device=p,m=null,K()}}),E.appendChild(ge.element));let Le=null;if(s){let Y=h("div","persona-dc-zoom-controls"),G=Qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ae=m!=null?m:C;m=Math.max(xx,ae-hx),K()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{m=1,K()});let we=Qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ae=m!=null?m:C;m=Math.min(yx,ae+hx),K()}}),ke=Qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,K()}});Y.append(G,Le,we,ke),E.appendChild(Y)}if(d){let Y=h("div","persona-dc-separator");E.appendChild(Y);let G=Ps({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:we=>{f=we,J.dataset.colorScheme=f,pe()}});E.appendChild(G.element)}let Ge=h("div","persona-dc-separator");E.appendChild(Ge);let Q=Qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});E.appendChild(Q),T.append(S,E);let Se=h("div","persona-dc-stage"),J=h("div","persona-dc-iframe-wrapper");J.dataset.device=p,J.dataset.colorScheme=f;let ce=h("iframe","persona-dc-iframe");ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ce.setAttribute("loading","lazy"),ce.title=t[u].title,J.appendChild(ce),Se.appendChild(J),k.append(T,Se),e.appendChild(k);function pe(){var Y;try{let G=(Y=ce.contentDocument)==null?void 0:Y.body;if(!G)return;f==="dark"?G.classList.add("theme-dark"):G.classList.remove("theme-dark")}catch{}}ce.addEventListener("load",()=>pe());function ie(){let Y=t[u];M.textContent=Y.title,xe.textContent=`${u+1} / ${t.length}`,ce.title=Y.title}function Oe(Y){let G=((u+Y)%t.length+t.length)%t.length;Pe(G)}function Pe(Y){Y<0||Y>=t.length||(u=Y,ce.src=t[u].url,ie(),l==null||l(u,t[u]))}function K(){var we;if(A)return;let Y=(we=gx[p])!=null?we:gx.desktop;C=BC(Se,Y);let G=Math.max(xx,Math.min(yx,m!=null?m:C));WC(J,ce,Y,G,p),Le&&(Le.textContent=`${Math.round(G*100)}%`)}let _e=new ResizeObserver(()=>K());_e.observe(Se),ie(),ce.src=t[u].url,requestAnimationFrame(()=>K());function $e(){A||(A=!0,_e.disconnect(),document.removeEventListener("click",De),k.remove())}return{element:k,goTo:Pe,next:()=>Oe(1),prev:()=>Oe(-1),getIndex:()=>u,setDevice(Y){p=Y,J.dataset.device=Y,ge==null||ge.setSelected(Y),m=null,K()},setColorScheme(Y){f=Y,J.dataset.colorScheme=Y},setZoom(Y){m=Y,K()},destroy:$e}}function wx(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function vx(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Ax(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:zn(e.colors.primary,.95),100:zn(e.colors.primary,.9),200:zn(e.colors.primary,.8),300:zn(e.colors.primary,.7),400:zn(e.colors.primary,.6),500:e.colors.primary,600:zn(e.colors.primary,.8),700:zn(e.colors.primary,.7),800:zn(e.colors.primary,.6),900:zn(e.colors.primary,.5),950:zn(e.colors.primary,.45)}}),{...r,palette:t}}}}function Sx(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Tx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function zn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),a=Math.round(t+(255-t)*(1-r)),s=Math.round(n+(255-n)*(1-r)),i=Math.round(o+(255-o)*(1-r));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function kx(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var DC={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"}}},Ex={components:{panel:{borderRadius:"0",shadow:"none"}}},zp={id:"shop",label:"Shopping Assistant",config:{theme:DC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:mn},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?"]}},Vp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ex}},jp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ex}},Gp={shop:zp,minimal:Vp,fullscreen:jp};function Mx(e){return Gp[e]}var OC=`
|
|
484
484
|
@keyframes persona-stream-wipe {
|
|
485
485
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
486
486
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|