@runtypelabs/persona 3.19.0 → 3.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -1
- package/dist/index.cjs +27 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +103 -3
- package/dist/index.d.ts +103 -3
- package/dist/index.global.js +65 -65
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +27 -27
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +80 -11
- package/dist/theme-editor.d.cts +73 -0
- package/dist/theme-editor.d.ts +73 -0
- package/dist/theme-editor.js +80 -11
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/session.test.ts +123 -0
- package/src/session.ts +58 -4
- package/src/types.ts +75 -0
- package/src/ui.ts +18 -0
- package/src/utils/component-middleware.test.ts +134 -0
- package/src/utils/component-middleware.ts +44 -13
package/dist/index.global.js
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[
|
|
3
|
-
`).map(a=>{let
|
|
4
|
-
`)}var ha=class{constructor(r){er(this,"options");er(this,"rules");er(this,"lexer");this.options=r||
|
|
5
|
-
`)}}}fences(r){let t=this.rules.block.fences.exec(r);if(t){let
|
|
6
|
-
$1`);
|
|
7
|
-
`);let a=this.lexer.state.top;this.lexer.state.top=!0;let
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var Wx=Object.create;var es=Object.defineProperty;var Dx=Object.getOwnPropertyDescriptor;var Ox=Object.getOwnPropertyNames;var Fx=Object.getPrototypeOf,Nx=Object.prototype.hasOwnProperty;var _m=e=>{throw TypeError(e)};var _x=(e,r,t)=>r in e?es(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var $m=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),$x=(e,r)=>{for(var t in r)es(e,t,{get:r[t],enumerable:!0})},Um=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Ox(r))!Nx.call(e,a)&&a!==t&&es(e,a,{get:()=>r[a],enumerable:!(n=Dx(r,a))||n.enumerable});return e};var Bl=(e,r,t)=>(t=e!=null?Wx(Fx(e)):{},Um(r||!e||!e.__esModule?es(t,"default",{value:e,enumerable:!0}):t,e)),Ux=e=>Um(es({},"__esModule",{value:!0}),e);var er=(e,r,t)=>_x(e,typeof r!="symbol"?r+"":r,t),qx=(e,r,t)=>r.has(e)||_m("Cannot "+t);var qm=(e,r,t)=>r.has(e)?_m("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t);var ai=(e,r,t)=>(qx(e,r,"access private method"),t);var Zl=$m(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.Allow=ze.ALL=ze.COLLECTION=ze.ATOM=ze.SPECIAL=ze.INF=ze._INFINITY=ze.INFINITY=ze.NAN=ze.BOOL=ze.NULL=ze.OBJ=ze.ARR=ze.NUM=ze.STR=void 0;ze.STR=1;ze.NUM=2;ze.ARR=4;ze.OBJ=8;ze.NULL=16;ze.BOOL=32;ze.NAN=64;ze.INFINITY=128;ze._INFINITY=256;ze.INF=ze.INFINITY|ze._INFINITY;ze.SPECIAL=ze.NULL|ze.BOOL|ze.INF|ze.NAN;ze.ATOM=ze.STR|ze.NUM|ze.SPECIAL;ze.COLLECTION=ze.ARR|ze.OBJ;ze.ALL=ze.ATOM|ze.COLLECTION;ze.Allow={STR:ze.STR,NUM:ze.NUM,ARR:ze.ARR,OBJ:ze.OBJ,NULL:ze.NULL,BOOL:ze.BOOL,NAN:ze.NAN,INFINITY:ze.INFINITY,_INFINITY:ze._INFINITY,INF:ze.INF,SPECIAL:ze.SPECIAL,ATOM:ze.ATOM,COLLECTION:ze.COLLECTION,ALL:ze.ALL};ze.default=ze.Allow});var hi=$m(Ir=>{"use strict";var Jy=Ir&&Ir.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var a=Object.getOwnPropertyDescriptor(r,t);(!a||("get"in a?!r.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,a)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),Ky=Ir&&Ir.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&Jy(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}});Ky(Zl(),Ir);var mi=class extends Error{};Ir.PartialJSON=mi;var gi=class extends Error{};Ir.MalformedJSON=gi;function Sg(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 Yy(e.trim(),r)}Ir.parseJSON=Sg;var Yy=(e,r)=>{let t=e.length,n=0,a=m=>{throw new mi(`${m} at position ${n}`)},o=m=>{throw new gi(`${m} at position ${n}`)},s=()=>(p(),n>=t&&a("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 m=n,f=!1;for(n++;n<t&&(e[n]!=='"'||f&&e[n-1]==="\\");)f=e[n]==="\\"?!f:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(m,++n-Number(f)))}catch(w){o(String(w))}else if(Jr.Allow.STR&r)try{return JSON.parse(e.substring(m,n-Number(f))+'"')}catch{return JSON.parse(e.substring(m,e.lastIndexOf("\\"))+'"')}a("Unterminated string literal")},d=()=>{n++,p();let m={};try{for(;e[n]!=="}";){if(p(),n>=t&&Jr.Allow.OBJ&r)return m;let f=i();p(),n++;try{let w=s();m[f]=w}catch(w){if(Jr.Allow.OBJ&r)return m;throw w}p(),e[n]===","&&n++}}catch{if(Jr.Allow.OBJ&r)return m;a("Expected '}' at end of object")}return n++,m},l=()=>{n++;let m=[];try{for(;e[n]!=="]";)m.push(s()),p(),e[n]===","&&n++}catch{if(Jr.Allow.ARR&r)return m;a("Expected ']' at end of array")}return n++,m},u=()=>{if(n===0){e==="-"&&o("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Jr.Allow.NUM&r)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}o(String(f))}}let m=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==t&&!(Jr.Allow.NUM&r)&&a("Unterminated number literal");try{return JSON.parse(e.substring(m,n))}catch{e.substring(m,n)==="-"&&a("Not sure what '-' is");try{return JSON.parse(e.substring(m,e.lastIndexOf("e")))}catch(w){o(String(w))}}},p=()=>{for(;n<t&&`
|
|
2
|
+
\r `.includes(e[n]);)n++};return s()},Qy=Sg;Ir.parse=Qy});var jC={};$x(jC,{ASK_USER_QUESTION_TOOL_NAME:()=>xp,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:()=>Vp,PRESET_FULLSCREEN:()=>zp,PRESET_MINIMAL:()=>qp,PRESET_SHOP:()=>Up,THEME_ZONES:()=>zg,VERSION:()=>ia,accessibilityPlugin:()=>yx,animationsPlugin:()=>bx,applyThemeVariables:()=>vo,attachHeaderToContainer:()=>na,brandPlugin:()=>Cx,buildComposer:()=>ka,buildDefaultHeader:()=>dp,buildHeader:()=>ao,buildHeaderWithLayout:()=>Ta,buildMinimalHeader:()=>cp,collectEnrichedPageContext:()=>rx,componentRegistry:()=>lo,createActionManager:()=>Ds,createAgentExperience:()=>Tl,createAskUserQuestionBubble:()=>wh,createBestAvailableVoiceProvider:()=>Ii,createBubbleWithLayout:()=>sh,createCSATFeedback:()=>vl,createComboButton:()=>ol,createComponentMiddleware:()=>Dh,createComponentStreamParser:()=>yl,createDefaultSanitizer:()=>Ql,createDemoCarousel:()=>xx,createDirectivePostprocessor:()=>dg,createDropdownMenu:()=>ko,createFlexibleJsonStreamParser:()=>Eg,createIconButton:()=>Qt,createImagePart:()=>Bg,createJsonStreamParser:()=>Ai,createLabelButton:()=>Ls,createLocalStorageAdapter:()=>xl,createMarkdownProcessor:()=>is,createMarkdownProcessorFromConfig:()=>Xo,createMessageActions:()=>fp,createNPSFeedback:()=>Al,createPlainTextParser:()=>wi,createPlugin:()=>Ax,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:()=>Fp,detectColorScheme:()=>bs,directivePostprocessor:()=>cg,ensureAskUserQuestionSheet:()=>Ra,escapeHtml:()=>Jo,extractComponentDirectiveFromMessage:()=>wl,fileToImagePart:()=>Wg,formatEnrichedContext:()=>nx,generateAssistantMessageId:()=>Qo,generateCodeSnippet:()=>cx,generateMessageId:()=>Lg,generateStableSelector:()=>Np,generateUserMessageId:()=>Ca,getActiveTheme:()=>Sa,getColorScheme:()=>tp,getDisplayText:()=>Ig,getHeaderLayout:()=>pp,getImageParts:()=>Hg,getPreset:()=>Tx,hasComponentDirective:()=>Cl,hasImages:()=>Rg,headerLayouts:()=>al,highContrastPlugin:()=>vx,initAgentWidget:()=>Vh,isAskUserQuestionMessage:()=>so,isComponentDirectiveType:()=>Wh,isDockedMountMode:()=>hr,isVoiceSupported:()=>xs,listRegisteredStreamAnimations:()=>ap,markdownPostprocessor:()=>ql,mergeWithDefaults:()=>zi,normalizeContent:()=>Pg,parseAskUserQuestionPayload:()=>io,pluginRegistry:()=>Bs,reducedMotionPlugin:()=>wx,registerStreamAnimationPlugin:()=>ra,removeAskUserQuestionSheet:()=>Lo,renderComponentDirective:()=>bl,renderLoadingIndicatorWithFallback:()=>up,renderLucideIcon:()=>Ce,resolveDockConfig:()=>vn,resolveSanitizer:()=>ya,resolveTokens:()=>Vi,themeToCssVariables:()=>ji,unregisterStreamAnimationPlugin:()=>op,validateImageFile:()=>Dg,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 Jm(e){Go=e}var Km=/[&<>"']/,zx=new RegExp(Km.source,"g"),Ym=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Vx=new RegExp(Ym.source,"g"),jx={"&":"&","<":"<",">":">",'"':""","'":"'"},zm=e=>jx[e];function un(e,r){if(r){if(Km.test(e))return e.replace(zx,zm)}else if(Ym.test(e))return e.replace(Vx,zm);return e}var Gx=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Xx(e){return e.replace(Gx,(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 Jx=/(^|[^\[])\^/g;function Kt(e,r){let t=typeof e=="string"?e:e.source;r=r||"";let n={replace:(a,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(Jx,"$1"),t=t.replace(a,s),n},getRegex:()=>new RegExp(t,r)};return n}function Vm(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch{return null}return e}var rs={exec:()=>null};function jm(e,r){let t=e.replace(/\|/g,(o,s,i)=>{let d=!1,l=s;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=t.split(/ \|/),a=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(;a<n.length;a++)n[a]=n[a].trim().replace(/\\\|/g,"|");return n}function si(e,r,t){let n=e.length;if(n===0)return"";let a=0;for(;a<n;){let o=e.charAt(n-a-1);if(o===r&&!t)a++;else if(o!==r&&t)a++;else break}return e.slice(0,n-a)}function Kx(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 Gm(e,r,t,n){let a=r.href,o=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:a,title:o,text:s,tokens:n.inlineTokens(s)};return n.state.inLink=!1,i}return{type:"image",raw:t,href:a,title:o,text:un(s)}}function Yx(e,r){let t=e.match(/^(\s+)(?:```)/);if(t===null)return r;let n=t[1];return r.split(`
|
|
3
|
+
`).map(a=>{let o=a.match(/^\s+/);if(o===null)return a;let[s]=o;return s.length>=n.length?a.slice(n.length):a}).join(`
|
|
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
|
+
`)}}}fences(r){let t=this.rules.block.fences.exec(r);if(t){let n=t[0],a=Yx(n,t[3]||"");return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:a}}}heading(r){let t=this.rules.block.heading.exec(r);if(t){let n=t[2].trim();if(/#$/.test(n)){let a=si(n,"#");(this.options.pedantic||!a||/ $/.test(a))&&(n=a.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
|
+
$1`);n=si(n.replace(/^ *>[ \t]?/gm,""),`
|
|
7
|
+
`);let a=this.lexer.state.top;this.lexer.state.top=!0;let o=this.lexer.blockTokens(n);return this.lexer.state.top=a,{type:"blockquote",raw:t[0],tokens:o,text:n}}}list(r){let t=this.rules.block.list.exec(r);if(t){let n=t[1].trim(),a=n.length>1,o={type:"list",raw:"",ordered:a,start:a?+n.slice(0,-1):"",loose:!1,items:[]};n=a?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=a?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
8
|
`,1)[0].replace(/^\t+/,T=>" ".repeat(3*T.length)),m=r.split(`
|
|
9
9
|
`,1)[0],f=0;this.options.pedantic?(f=2,d=p.trimStart()):(f=t[2].search(/[^ ]/),f=f>4?1:f,d=p.slice(f),f+=t[1].length);let w=!1;if(!p&&/^ *$/.test(m)&&(i+=m+`
|
|
10
10
|
`,r=r.substring(m.length+1),u=!0),!u){let T=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),A=new RegExp(`^ {0,${Math.min(3,f-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),E=new RegExp(`^ {0,${Math.min(3,f-1)}}(?:\`\`\`|~~~)`),b=new RegExp(`^ {0,${Math.min(3,f-1)}}#`);for(;r;){let h=r.split(`
|
|
11
11
|
`,1)[0];if(m=h,this.options.pedantic&&(m=m.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),E.test(m)||b.test(m)||T.test(m)||A.test(r))break;if(m.search(/[^ ]/)>=f||!m.trim())d+=`
|
|
12
12
|
`+m.slice(f);else{if(w||p.search(/[^ ]/)>=4||E.test(p)||b.test(p)||A.test(p))break;d+=`
|
|
13
13
|
`+m}!w&&!m.trim()&&(w=!0),i+=h+`
|
|
14
|
-
`,r=r.substring(h.length+1),p=m.slice(f)}}
|
|
15
|
-
`):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(
|
|
16
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:
|
|
17
|
-
]`).replace("lheading",Zm).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},tg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
|
|
18
|
-
`),this.blockTokens(r,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let
|
|
19
|
-
`:t.push(
|
|
20
|
-
`+
|
|
21
|
-
`+
|
|
22
|
-
`+
|
|
23
|
-
`+
|
|
24
|
-
`+
|
|
25
|
-
`+
|
|
26
|
-
`+
|
|
27
|
-
`+
|
|
28
|
-
`,a?'<pre><code class="language-'+
|
|
29
|
-
`:"<pre><code>"+(
|
|
14
|
+
`,r=r.substring(h.length+1),p=m.slice(f)}}o.loose||(l?o.loose=!0:/\n *\n *$/.test(i)&&(l=!0));let v=null,k;this.options.gfm&&(v=/^\[[ xX]\] /.exec(d),v&&(k=v[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),o.items.push({type:"list_item",raw:i,task:!!v,checked:k,loose:!1,text:d,tokens:[]}),o.raw+=i}o.items[o.items.length-1].raw=i.trimEnd(),o.items[o.items.length-1].text=d.trimEnd(),o.raw=o.raw.trimEnd();for(let u=0;u<o.items.length;u++)if(this.lexer.state.top=!1,o.items[u].tokens=this.lexer.blockTokens(o.items[u].text,[]),!o.loose){let p=o.items[u].tokens.filter(f=>f.type==="space"),m=p.length>0&&p.some(f=>/\n.*\n/.test(f.raw));o.loose=m}if(o.loose)for(let u=0;u<o.items.length;u++)o.items[u].loose=!0;return o}}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," "),a=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=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:a,title:o}}}table(r){let t=this.rules.block.table.exec(r);if(!t||!/[:|]/.test(t[2]))return;let n=jm(t[1]),a=t[2].replace(/^\||\| *$/g,"").split("|"),o=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(`
|
|
15
|
+
`):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===a.length){for(let i of a)/^ *-+: *$/.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 o)s.rows.push(jm(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=Kx(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 a=t[2],o="";if(this.options.pedantic){let s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(a);s&&(a=s[1],o=s[3])}else o=t[3]?t[3].slice(1,-1):"";return a=a.trim(),/^</.test(a)&&(this.options.pedantic&&!/>$/.test(n)?a=a.slice(1):a=a.slice(1,-1)),Gm(t,{href:a&&a.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.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 a=(n[2]||n[1]).replace(/\s+/g," "),o=t[a.toLowerCase()];if(!o){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Gm(n,o,n[0],this.lexer)}}emStrong(r,t,n=""){let a=this.rules.inline.emStrongLDelim.exec(r);if(!a||a[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(a[1]||a[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...a[0]].length-1,i,d,l=s,u=0,p=a[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*r.length+s);(a=p.exec(t))!=null;){if(i=a[1]||a[2]||a[3]||a[4]||a[5]||a[6],!i)continue;if(d=[...i].length,a[3]||a[4]){l+=d;continue}else if((a[5]||a[6])&&s%3&&!((s+d)%3)){u+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+u);let m=[...a[0]][0].length,f=r.slice(0,s+a.index+m+d);if(Math.min(s,d)%2){let v=f.slice(1,-1);return{type:"em",raw:f,text:v,tokens:this.lexer.inlineTokens(v)}}let w=f.slice(2,-2);return{type:"strong",raw:f,text:w,tokens:this.lexer.inlineTokens(w)}}}}codespan(r){let t=this.rules.inline.code.exec(r);if(t){let n=t[2].replace(/\n/g," "),a=/[^ ]/.test(n),o=/^ /.test(n)&&/ $/.test(n);return a&&o&&(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,a;return t[2]==="@"?(n=un(t[1]),a="mailto:"+n):(n=un(t[1]),a=n),{type:"link",raw:t[0],text:n,href:a,tokens:[{type:"text",raw:n,text:n}]}}}url(r){var n,a;let t;if(t=this.rules.inline.url.exec(r)){let o,s;if(t[2]==="@")o=un(t[0]),s="mailto:"+o;else{let i;do i=t[0],t[0]=(a=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?a:"";while(i!==t[0]);o=un(t[0]),t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}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}}}},Qx=/^(?: *(?:\n|$))+/,Zx=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,ey=/^ {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+|$)/,ty=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Qm=/(?:[*+-]|\d{1,9}[.)])/,Zm=Kt(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Qm).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]+)*)/,ry=/^[^\n]+/,Nl=/(?!\s*\])(?:\\.|[^\[\]\\])+/,ny=Kt(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",Nl).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),oy=Kt(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Qm).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]*?(?:-->|$))/,ay=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(),eg=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(),sy=Kt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",eg).getRegex(),$l={blockquote:sy,code:Zx,def:ny,fences:ey,heading:ty,hr:as,html:ay,lheading:Zm,list:oy,newline:Qx,paragraph:eg,table:rs,text:ry},Xm=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(),iy={...$l,table:Xm,paragraph:Kt(Fl).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Xm).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()},ly={...$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
|
+
]`).replace("lheading",Zm).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},tg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,dy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,rg=/^( {2,}|\\)\n(?!\s*$)/,cy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ss="\\p{P}\\p{S}",py=Kt(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,ss).getRegex(),uy=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,fy=Kt(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,ss).getRegex(),my=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(),gy=Kt("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,ss).getRegex(),hy=Kt(/\\([punct])/,"gu").replace(/punct/g,ss).getRegex(),xy=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(),yy=Kt(_l).replace("(?:-->|$)","-->").getRegex(),by=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",yy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),li=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Cy=Kt(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",li).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ng=Kt(/^!?\[(label)\]\[(ref)\]/).replace("label",li).replace("ref",Nl).getRegex(),og=Kt(/^!?\[(ref)\](?:\[\])?/).replace("ref",Nl).getRegex(),wy=Kt("reflink|nolink(?!\\()","g").replace("reflink",ng).replace("nolink",og).getRegex(),Ul={_backpedal:rs,anyPunctuation:hy,autolink:xy,blockSkip:uy,br:rg,code:dy,del:rs,emStrongLDelim:fy,emStrongRDelimAst:my,emStrongRDelimUnd:gy,escape:tg,link:Cy,nolink:og,punctuation:py,reflink:ng,reflinkSearch:wy,tag:by,text:cy,url:rs},vy={...Ul,link:Kt(/^!?\[(label)\]\((.*?)\)/).replace("label",li).getRegex(),reflink:Kt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",li).getRegex()},Wl={...Ul,escape:Kt(tg).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.!#$%&'*+\/=?_`{\|}~-]+@)))/},Ay={...Wl,br:Kt(rg).replace("{2,}","*").getRegex(),text:Kt(Wl.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ii={normal:$l,gfm:iy,pedantic:ly},ts={normal:Ul,gfm:Wl,breaks:Ay,pedantic:vy},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
|
+
`),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,a,o,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
|
+
`:t.push(n);continue}if(n=this.tokenizer.code(r)){r=r.substring(n.raw.length),a=t[t.length-1],a&&(a.type==="paragraph"||a.type==="text")?(a.raw+=`
|
|
20
|
+
`+n.raw,a.text+=`
|
|
21
|
+
`+n.text,this.inlineQueue[this.inlineQueue.length-1].src=a.text):t.push(n);continue}if(n=this.tokenizer.fences(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.heading(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.hr(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.blockquote(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.list(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.html(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.def(r)){r=r.substring(n.raw.length),a=t[t.length-1],a&&(a.type==="paragraph"||a.type==="text")?(a.raw+=`
|
|
22
|
+
`+n.raw,a.text+=`
|
|
23
|
+
`+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=a.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.lheading(r)){r=r.substring(n.raw.length),t.push(n);continue}if(o=r,this.options.extensions&&this.options.extensions.startBlock){let i=1/0,d=r.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},d),typeof l=="number"&&l>=0&&(i=Math.min(i,l))}),i<1/0&&i>=0&&(o=r.substring(0,i+1))}if(this.state.top&&(n=this.tokenizer.paragraph(o))){a=t[t.length-1],s&&a.type==="paragraph"?(a.raw+=`
|
|
24
|
+
`+n.raw,a.text+=`
|
|
25
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=a.text):t.push(n),s=o.length!==r.length,r=r.substring(n.raw.length);continue}if(n=this.tokenizer.text(r)){r=r.substring(n.raw.length),a=t[t.length-1],a&&a.type==="text"?(a.raw+=`
|
|
26
|
+
`+n.raw,a.text+=`
|
|
27
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=a.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,a,o,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),a=t[t.length-1],a&&n.type==="text"&&a.type==="text"?(a.raw+=n.raw,a.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),a=t[t.length-1],a&&n.type==="text"&&a.type==="text"?(a.raw+=n.raw,a.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(o=r,this.options.extensions&&this.options.extensions.startInline){let u=1/0,p=r.slice(1),m;this.options.extensions.startInline.forEach(f=>{m=f.call({lexer:this},p),typeof m=="number"&&m>=0&&(u=Math.min(u,m))}),u<1/0&&u>=0&&(o=r.substring(0,u+1))}if(n=this.tokenizer.inlineText(o)){r=r.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,a=t[t.length-1],a&&a.type==="text"?(a.raw+=n.raw,a.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 o;let a=(o=(t||"").match(/^\S*/))==null?void 0:o[0];return r=r.replace(/\n$/,"")+`
|
|
28
|
+
`,a?'<pre><code class="language-'+un(a)+'">'+(n?r:un(r,!0))+`</code></pre>
|
|
29
|
+
`:"<pre><code>"+(n?r:un(r,!0))+`</code></pre>
|
|
30
30
|
`}blockquote(r){return`<blockquote>
|
|
31
31
|
${r}</blockquote>
|
|
32
|
-
`}html(r,t){return r}heading(r,t,
|
|
32
|
+
`}html(r,t){return r}heading(r,t,n){return`<h${t}>${r}</h${t}>
|
|
33
33
|
`}hr(){return`<hr>
|
|
34
|
-
`}list(r,t,
|
|
34
|
+
`}list(r,t,n){let a=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+a+o+`>
|
|
35
35
|
`+r+"</"+a+`>
|
|
36
|
-
`}listitem(r,t,
|
|
36
|
+
`}listitem(r,t,n){return`<li>${r}</li>
|
|
37
37
|
`}checkbox(r){return"<input "+(r?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(r){return`<p>${r}</p>
|
|
38
38
|
`}table(r,t){return t&&(t=`<tbody>${t}</tbody>`),`<table>
|
|
39
39
|
<thead>
|
|
@@ -41,18 +41,18 @@ ${r}</blockquote>
|
|
|
41
41
|
`+t+`</table>
|
|
42
42
|
`}tablerow(r){return`<tr>
|
|
43
43
|
${r}</tr>
|
|
44
|
-
`}tablecell(r,t){let
|
|
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,
|
|
46
|
-
`+(s.tokens?this.parseInline(s.tokens):s.text);
|
|
47
|
-
Please report this to https://github.com/markedjs/marked.`,r){let a="<p>An error occurred:</p><pre>"+uo(o.message+"",!0)+"</pre>";return t?Promise.resolve(a):a}if(t)return Promise.reject(o);throw o}};var Vn=new ns;function Jt(e,r){return Vn.parse(e,r)}Jt.options=Jt.setOptions=function(e){return Vn.setOptions(e),Jt.defaults=Vn.defaults,Jm(Jt.defaults),Jt};Jt.getDefaults=Ol;Jt.defaults=Gn;Jt.use=function(...e){return Vn.use(...e),Jt.defaults=Vn.defaults,Jm(Jt.defaults),Jt};Jt.walkTokens=function(e,r){return Vn.walkTokens(e,r)};Jt.parseInline=Vn.parseInline;Jt.Parser=rn;Jt.parser=rn.parse;Jt.Renderer=xa;Jt.TextRenderer=os;Jt.Lexer=tn;Jt.lexer=tn.lex;Jt.Tokenizer=ha;Jt.Hooks=zn;Jt.parse=Jt;var XC=Jt.options,JC=Jt.setOptions,KC=Jt.use,YC=Jt.walkTokens,QC=Jt.parseInline;var ZC=rn.parse,ew=tn.lex;var Ay=e=>{if(e)return e},is=e=>{var a,n;let r=e==null?void 0:e.markedOptions,t=new ns({gfm:(a=r==null?void 0:r.gfm)!=null?a:!0,breaks:(n=r==null?void 0:r.breaks)!=null?n:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),o=Ay(e==null?void 0:e.renderer);return o&&t.use({renderer:o}),s=>t.parse(s)},Xn=e=>e?is({markedOptions:e.options,renderer:e.renderer}):is(),Sy=is(),ql=e=>Sy(e),Jn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ig=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),sg=e=>`%%FORM_PLACEHOLDER_${e}%%`,lg=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,a)=>{try{let n=JSON.parse(a.trim());if(n&&typeof n=="object"&&n.component==="form"&&n.type){let s=sg(r.length);return r.push({token:s,type:String(n.type)}),s}}catch{return o}return o}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,a)=>{let n=sg(r.length);return r.push({token:n,type:a}),n}),t},dg=e=>{let r=Xn(e);return t=>{let o=[],a=lg(t,o),n=r(a);return o.forEach(({token:s,type:i})=>{let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ig(i)}"></div>`;n=n.replace(d,u)}),n}},cg=e=>{let r=[],t=lg(e,r),o=ql(t);return r.forEach(({token:a,type:n})=>{let s=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ig(n)}"></div>`;o=o.replace(s,d)}),o};var{entries:bg,setPrototypeOf:pg,isFrozen:Ty,getPrototypeOf:ky,getOwnPropertyDescriptor:Ey}=Object,{freeze:Gr,seal:wo,create:ui}=Object,{apply:Kl,construct:Yl}=typeof Reflect!="undefined"&&Reflect;Gr||(Gr=function(r){return r});wo||(wo=function(r){return r});Kl||(Kl=function(r,t){for(var o=arguments.length,a=new Array(o>2?o-2:0),n=2;n<o;n++)a[n-2]=arguments[n];return r.apply(t,a)});Yl||(Yl=function(r){for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;a<t;a++)o[a-1]=arguments[a];return new r(...o)});var ci=Xr(Array.prototype.forEach),My=Xr(Array.prototype.lastIndexOf),ug=Xr(Array.prototype.pop),ls=Xr(Array.prototype.push),Ly=Xr(Array.prototype.splice),fi=Xr(String.prototype.toLowerCase),zl=Xr(String.prototype.toString),Vl=Xr(String.prototype.match),ds=Xr(String.prototype.replace),Py=Xr(String.prototype.indexOf),Iy=Xr(String.prototype.trim),fo=Xr(Object.prototype.hasOwnProperty),jr=Xr(RegExp.prototype.test),cs=Ry(TypeError);function Xr(e){return function(r){r instanceof RegExp&&(r.lastIndex=0);for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;a<t;a++)o[a-1]=arguments[a];return Kl(e,r,o)}}function Ry(e){return function(){for(var r=arguments.length,t=new Array(r),o=0;o<r;o++)t[o]=arguments[o];return Yl(e,t)}}function wt(e,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fi;pg&&pg(e,null);let o=r.length;for(;o--;){let a=r[o];if(typeof a=="string"){let n=t(a);n!==a&&(Ty(r)||(r[o]=n),a=n)}e[a]=!0}return e}function Hy(e){for(let r=0;r<e.length;r++)fo(e,r)||(e[r]=null);return e}function Uo(e){let r=ui(null);for(let[t,o]of bg(e))fo(e,t)&&(Array.isArray(o)?r[t]=Hy(o):o&&typeof o=="object"&&o.constructor===Object?r[t]=Uo(o):r[t]=o);return r}function ps(e,r){for(;e!==null;){let o=Ey(e,r);if(o){if(o.get)return Xr(o.get);if(typeof o.value=="function")return Xr(o.value)}e=ky(e)}function t(){return null}return t}var fg=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"]),By=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"]),Wy=Gr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),mg=Gr(["#text"]),gg=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"]),hg=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"]),Dy=wo(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Oy=wo(/<%[\w\W]*|[\w\W]*%>/gm),Fy=wo(/\$\{[\w\W]*/gm),Ny=wo(/^data-[\-\w.\u00B7-\uFFFF]+$/),_y=wo(/^aria-[\-\w]+$/),Cg=wo(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),$y=wo(/^(?:\w+script|data):/i),Uy=wo(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),wg=wo(/^html$/i),qy=wo(/^[a-z][.\w]*(-[.\w]+)+$/i),xg=Object.freeze({__proto__:null,ARIA_ATTR:_y,ATTR_WHITESPACE:Uy,CUSTOM_ELEMENT:qy,DATA_ATTR:Ny,DOCTYPE_NAME:wg,ERB_EXPR:Oy,IS_ALLOWED_URI:Cg,IS_SCRIPT_OR_DATA:$y,MUSTACHE_EXPR:Dy,TMPLIT_EXPR:Fy}),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},zy=function(){return typeof window=="undefined"?null:window},Vy=function(r,t){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let o=null,a="data-tt-policy-suffix";t&&t.hasAttribute(a)&&(o=t.getAttribute(a));let n="dompurify"+(o?"#"+o:"");try{return r.createPolicy(n,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+n+" could not be created."),null}},yg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function vg(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:zy(),r=Me=>vg(Me);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,o=t,a=o.currentScript,{DocumentFragment:n,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 Me=t.createElement("template");Me.content&&Me.content.ownerDocument&&(t=Me.content.ownerDocument)}let b,h="",{implementation:S,createNodeIterator:L,createDocumentFragment:O,getElementsByTagName:H}=t,{importNode:R}=o,B=yg();r.isSupported=typeof bg=="function"&&typeof E=="function"&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:oe,TMPLIT_EXPR:fe,DATA_ATTR:_e,ARIA_ATTR:je,IS_SCRIPT_OR_DATA:ye,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:Pe}=xg,{IS_ALLOWED_URI:Ve}=xg,Q=null,Ae=wt({},[...fg,...jl,...Gl,...Xl,...mg]),J=null,de=wt({},[...gg,...Jl,...hg,...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}})),se=null,Be=null,Ee=Object.seal(ui(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),K=!0,Oe=!0,Fe=!1,Y=!0,G=!1,we=!0,ue=!1,re=!1,he=!1,Je=!1,Ot=!1,ce=!1,$e=!0,fr=!1,Wt="user-content-",Yt=!0,Fr=!1,Ar={},F=null,ie=wt({},["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"]),We=null,Xe=wt({},["audio","video","img","source","image","track"]),Ne=null,Ue=wt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),tt="http://www.w3.org/1998/Math/MathML",yt="http://www.w3.org/2000/svg",Mt="http://www.w3.org/1999/xhtml",_t=Mt,N=!1,le=null,Te=wt({},[tt,yt,Mt],zl),ct=wt({},["mi","mo","mn","ms","mtext"]),Ke=wt({},["annotation-xml"]),$t=wt({},["title","style","font","a","script"]),nr=null,Lt=["application/xhtml+xml","text/html"],vt="text/html",Ze=null,at=null,tr=t.createElement("form"),go=function(M){return M instanceof RegExp||M instanceof Function},Rr=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(at&&at===M)){if((!M||typeof M!="object")&&(M={}),M=Uo(M),nr=Lt.indexOf(M.PARSER_MEDIA_TYPE)===-1?vt:M.PARSER_MEDIA_TYPE,Ze=nr==="application/xhtml+xml"?zl:fi,Q=fo(M,"ALLOWED_TAGS")?wt({},M.ALLOWED_TAGS,Ze):Ae,J=fo(M,"ALLOWED_ATTR")?wt({},M.ALLOWED_ATTR,Ze):de,le=fo(M,"ALLOWED_NAMESPACES")?wt({},M.ALLOWED_NAMESPACES,zl):Te,Ne=fo(M,"ADD_URI_SAFE_ATTR")?wt(Uo(Ue),M.ADD_URI_SAFE_ATTR,Ze):Ue,We=fo(M,"ADD_DATA_URI_TAGS")?wt(Uo(Xe),M.ADD_DATA_URI_TAGS,Ze):Xe,F=fo(M,"FORBID_CONTENTS")?wt({},M.FORBID_CONTENTS,Ze):ie,se=fo(M,"FORBID_TAGS")?wt({},M.FORBID_TAGS,Ze):Uo({}),Be=fo(M,"FORBID_ATTR")?wt({},M.FORBID_ATTR,Ze):Uo({}),Ar=fo(M,"USE_PROFILES")?M.USE_PROFILES:!1,K=M.ALLOW_ARIA_ATTR!==!1,Oe=M.ALLOW_DATA_ATTR!==!1,Fe=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,ue=M.WHOLE_DOCUMENT||!1,Je=M.RETURN_DOM||!1,Ot=M.RETURN_DOM_FRAGMENT||!1,ce=M.RETURN_TRUSTED_TYPE||!1,he=M.FORCE_BODY||!1,$e=M.SANITIZE_DOM!==!1,fr=M.SANITIZE_NAMED_PROPS||!1,Yt=M.KEEP_CONTENT!==!1,Fr=M.IN_PLACE||!1,Ve=M.ALLOWED_URI_REGEXP||Cg,_t=M.NAMESPACE||Mt,ct=M.MATHML_TEXT_INTEGRATION_POINTS||ct,Ke=M.HTML_INTEGRATION_POINTS||Ke,pe=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&go(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(pe.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&go(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&&(Oe=!1),Ot&&(Je=!0),Ar&&(Q=wt({},mg),J=ui(null),Ar.html===!0&&(wt(Q,fg),wt(J,gg)),Ar.svg===!0&&(wt(Q,jl),wt(J,Jl),wt(J,pi)),Ar.svgFilters===!0&&(wt(Q,Gl),wt(J,Jl),wt(J,pi)),Ar.mathMl===!0&&(wt(Q,Xl),wt(J,hg),wt(J,pi))),fo(M,"ADD_TAGS")||(Ee.tagCheck=null),fo(M,"ADD_ATTR")||(Ee.attributeCheck=null),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?Ee.tagCheck=M.ADD_TAGS:(Q===Ae&&(Q=Uo(Q)),wt(Q,M.ADD_TAGS,Ze))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?Ee.attributeCheck=M.ADD_ATTR:(J===de&&(J=Uo(J)),wt(J,M.ADD_ATTR,Ze))),M.ADD_URI_SAFE_ATTR&&wt(Ne,M.ADD_URI_SAFE_ATTR,Ze),M.FORBID_CONTENTS&&(F===ie&&(F=Uo(F)),wt(F,M.FORBID_CONTENTS,Ze)),M.ADD_FORBID_CONTENTS&&(F===ie&&(F=Uo(F)),wt(F,M.ADD_FORBID_CONTENTS,Ze)),Yt&&(Q["#text"]=!0),ue&&wt(Q,["html","head","body"]),Q.table&&(wt(Q,["tbody"]),delete se.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=Vy(f,a)),b!==null&&typeof h=="string"&&(h=b.createHTML(""));Gr&&Gr(M),at=M}},To=wt({},[...jl,...Gl,...By]),At=wt({},[...Xl,...Wy]),ho=function(M){let Z=E(M);(!Z||!Z.tagName)&&(Z={namespaceURI:_t,tagName:"template"});let ne=fi(M.tagName),St=fi(Z.tagName);return le[M.namespaceURI]?M.namespaceURI===yt?Z.namespaceURI===Mt?ne==="svg":Z.namespaceURI===tt?ne==="svg"&&(St==="annotation-xml"||ct[St]):!!To[ne]:M.namespaceURI===tt?Z.namespaceURI===Mt?ne==="math":Z.namespaceURI===yt?ne==="math"&&Ke[St]:!!At[ne]:M.namespaceURI===Mt?Z.namespaceURI===yt&&!Ke[St]||Z.namespaceURI===tt&&!ct[St]?!1:!At[ne]&&($t[ne]||!To[ne]):!!(nr==="application/xhtml+xml"&&le[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(Je||Ot)try{ur(Z)}catch{}else try{Z.setAttribute(M,"")}catch{}},Yr=function(M){let Z=null,ne=null;if(he)M="<remove></remove>"+M;else{let Rt=Vl(M,/^[\r\n\t ]+/);ne=Rt&&Rt[0]}nr==="application/xhtml+xml"&&_t===Mt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");let St=b?b.createHTML(M):M;if(_t===Mt)try{Z=new m().parseFromString(St,nr)}catch{}if(!Z||!Z.documentElement){Z=S.createDocument(_t,"template",null);try{Z.documentElement.innerHTML=N?h:St}catch{}}let Ut=Z.body||Z.documentElement;return M&&ne&&Ut.insertBefore(t.createTextNode(ne),Ut.childNodes[0]||null),_t===Mt?H.call(Z,ue?"html":"body")[0]:ue?Z.documentElement:Ut},gt=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)},ko=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")},oo=function(M){return typeof i=="function"&&M instanceof i};function Tr(Me,M,Z){ci(Me,ne=>{ne.call(r,M,Z,at)})}let kr=function(M){let Z=null;if(Tr(B.beforeSanitizeElements,M,null),ko(M))return ur(M),!0;let ne=Ze(M.nodeName);if(Tr(B.uponSanitizeElement,M,{tagName:ne,allowedTags:Q}),we&&M.hasChildNodes()&&!oo(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(!(Ee.tagCheck instanceof Function&&Ee.tagCheck(ne))&&(!Q[ne]||se[ne])){if(!se[ne]&&Eo(ne)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,ne)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(ne)))return!1;if(Yt&&!F[ne]){let St=E(M)||M.parentNode,Ut=A(M)||M.childNodes;if(Ut&&St){let Rt=Ut.length;for(let ar=Rt-1;ar>=0;--ar){let xr=v(Ut[ar],!0);xr.__removalCount=(M.__removalCount||0)+1,St.insertBefore(xr,T(M))}}}return ur(M),!0}return M instanceof d&&!ho(M)||(ne==="noscript"||ne==="noembed"||ne==="noframes")&&jr(/<\/no(script|embed|frames)/i,M.innerHTML)?(ur(M),!0):(G&&M.nodeType===us.text&&(Z=M.textContent,ci([V,oe,fe],St=>{Z=ds(Z,St," ")}),M.textContent!==Z&&(ls(r.removed,{element:M.cloneNode()}),M.textContent=Z)),Tr(B.afterSanitizeElements,M,null),!1)},Vo=function(M,Z,ne){if(Be[Z]||$e&&(Z==="id"||Z==="name")&&(ne in t||ne in tr))return!1;if(!(Oe&&!Be[Z]&&jr(_e,Z))){if(!(K&&jr(je,Z))){if(!(Ee.attributeCheck instanceof Function&&Ee.attributeCheck(Z,M))){if(!J[Z]||Be[Z]){if(!(Eo(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,ne)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(ne))))return!1}else if(!Ne[Z]){if(!jr(Ve,ds(ne,me,""))){if(!((Z==="src"||Z==="xlink:href"||Z==="href")&&M!=="script"&&Py(ne,"data:")===0&&We[M])){if(!(Fe&&!jr(ye,ds(ne,me,"")))){if(ne)return!1}}}}}}}return!0},Eo=function(M){return M!=="annotation-xml"&&Vl(M,Pe)},xo=function(M){Tr(B.beforeSanitizeAttributes,M,null);let{attributes:Z}=M;if(!Z||ko(M))return;let ne={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J,forceKeepAttr:void 0},St=Z.length;for(;St--;){let Ut=Z[St],{name:Rt,namespaceURI:ar,value:xr}=Ut,Nr=Ze(Rt),Er=xr,rt=Rt==="value"?Er:Iy(Er);if(ne.attrName=Nr,ne.attrValue=rt,ne.keepAttr=!0,ne.forceKeepAttr=void 0,Tr(B.uponSanitizeAttribute,M,ne),rt=ne.attrValue,fr&&(Nr==="id"||Nr==="name")&&(Sr(Rt,M),rt=Wt+rt),we&&jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,rt)){Sr(Rt,M);continue}if(Nr==="attributename"&&Vl(rt,"href")){Sr(Rt,M);continue}if(ne.forceKeepAttr)continue;if(!ne.keepAttr){Sr(Rt,M);continue}if(!Y&&jr(/\/>/i,rt)){Sr(Rt,M);continue}G&&ci([V,oe,fe],_r=>{rt=ds(rt,_r," ")});let wr=Ze(M.nodeName);if(!Vo(wr,Nr,rt)){Sr(Rt,M);continue}if(b&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!ar)switch(f.getAttributeType(wr,Nr)){case"TrustedHTML":{rt=b.createHTML(rt);break}case"TrustedScriptURL":{rt=b.createScriptURL(rt);break}}if(rt!==Er)try{ar?M.setAttributeNS(ar,Rt,rt):M.setAttribute(Rt,rt),ko(M)?ur(M):ug(r.removed)}catch{Sr(Rt,M)}}Tr(B.afterSanitizeAttributes,M,null)},bt=function Me(M){let Z=null,ne=gt(M);for(Tr(B.beforeSanitizeShadowDOM,M,null);Z=ne.nextNode();)Tr(B.uponSanitizeShadowNode,Z,null),kr(Z),xo(Z),Z.content instanceof n&&Me(Z.content);Tr(B.afterSanitizeShadowDOM,M,null)};return r.sanitize=function(Me){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Z=null,ne=null,St=null,Ut=null;if(N=!Me,N&&(Me="<!-->"),typeof Me!="string"&&!oo(Me))if(typeof Me.toString=="function"){if(Me=Me.toString(),typeof Me!="string")throw cs("dirty is not a string, aborting")}else throw cs("toString is not a function");if(!r.isSupported)return Me;if(re||Rr(M),r.removed=[],typeof Me=="string"&&(Fr=!1),Fr){if(Me.nodeName){let xr=Ze(Me.nodeName);if(!Q[xr]||se[xr])throw cs("root node is forbidden and cannot be sanitized in-place")}}else if(Me instanceof i)Z=Yr("<!---->"),ne=Z.ownerDocument.importNode(Me,!0),ne.nodeType===us.element&&ne.nodeName==="BODY"||ne.nodeName==="HTML"?Z=ne:Z.appendChild(ne);else{if(!Je&&!G&&!ue&&Me.indexOf("<")===-1)return b&&ce?b.createHTML(Me):Me;if(Z=Yr(Me),!Z)return Je?null:ce?h:""}Z&&he&&ur(Z.firstChild);let Rt=gt(Fr?Me:Z);for(;St=Rt.nextNode();)kr(St),xo(St),St.content instanceof n&&bt(St.content);if(Fr)return Me;if(Je){if(Ot)for(Ut=O.call(Z.ownerDocument);Z.firstChild;)Ut.appendChild(Z.firstChild);else Ut=Z;return(J.shadowroot||J.shadowrootmode)&&(Ut=R.call(o,Ut,!0)),Ut}let ar=ue?Z.outerHTML:Z.innerHTML;return ue&&Q["!doctype"]&&Z.ownerDocument&&Z.ownerDocument.doctype&&Z.ownerDocument.doctype.name&&jr(wg,Z.ownerDocument.doctype.name)&&(ar="<!DOCTYPE "+Z.ownerDocument.doctype.name+`>
|
|
48
|
-
`+ar),G&&ci([V,
|
|
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)}},
|
|
50
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return
|
|
51
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=r)return e!==null?{text:e,raw:o}:null;let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;let n=t(o);return n!==null&&(e=n),r=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Kn=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=eb();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.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 o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let a=(0,on.parse)(t,on.STR|on.OBJ);a&&typeof a=="object"&&(a.component&&typeof a.component=="string"?e=typeof a.text=="string"?xi(a.text):"":a.type==="init"&&a.form?e="":typeof a.text=="string"&&(e=xi(a.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Eg=e=>{let r=null,t=0,a=e||(n=>{if(!n||typeof n!="object")return null;let s=i=>typeof i=="string"?xi(i):null;if(n.component&&typeof n.component=="string")return typeof n.text=="string"?xi(n.text):"";if(n.type==="init"&&n.form)return"";if(n.action)switch(n.action){case"nav_then_click":return s(n.on_load_text)||s(n.text)||null;case"message":case"message_and_click":case"checkout":return s(n.text)||null;default:return s(n.text)||s(n.display_text)||s(n.message)||null}return s(n.text)||s(n.display_text)||s(n.message)||s(n.content)||null});return{getExtractedText:()=>r,processChunk:n=>{let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(n.length<=t)return r!==null?{text:r,raw:n}:null;try{let i=(0,on.parse)(n,on.STR|on.OBJ),d=a(i);d!==null&&(r=d)}catch{}return t=n.length,{text:r||"",raw:n}},close:()=>{}}},Si=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let o=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[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 n,s,i;let o=(i=(n=t==null?void 0:t.seq)!=null?n:t==null?void 0:t.sequenceIndex)!=null?i:(s=t==null?void 0:t.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(r,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(r,t),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(r,t);return}let a=this.buffer.get(o);a!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${a.payloadType} vs ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(a.payloadType,a.payload)),this.buffer.set(o,{payloadType:r,payload:t,seq:o}),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,o)=>t[0]-o[0]);for(let[t,o]of r)this.buffer.delete(t),this.emitter(o.payloadType,o.payload);r.length>0&&(this.nextExpectedSeq=r[r.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var tb="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com",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 rb(e){switch(e){case"json":return Ai;case"regex-json":return vi;case"xml":return Si;default:return wi}}var Mg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ob(e,r){if(!e)return r;let t=e.trim(),o=r.trim();if(t.length===0)return r;if(o.length===0)return e;let a=Mg(t);if(!Mg(o))return e;if(!a||o===t||o.startsWith(t))return r;let s=Kn(e);return Kn(r)!==null&&s===null?r:e}var Yn=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,o,a;this.apiUrl=(t=r.apiUrl)!=null?t:tb,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(o=r.streamParser)!=null?o:rb(r.parserType),this.contextProviders=(a=r.contextProviders)!=null?a:[],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 o;let t=((o=this.config.apiUrl)==null?void 0:o.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 o=await this.sessionInitPromise;return this.clientSession=o,(t=(r=this.config).onSessionInit)==null||t.call(r,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var n,s;let r=((s=(n=this.config).getStoredSessionId)==null?void 0:s.call(n))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.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 n,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 a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(s=(n=this.config).onSessionExpired)==null||s.call(n),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.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 a,n,s,i;let o=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(n=(a=this.config).onSessionExpired)==null||n.call(a);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:o.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 o=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let a=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",a);let n={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();n={...n,...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:n,body:JSON.stringify(a),signal:o.signal},a)}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:n,body:JSON.stringify(a),signal:o.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 o=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let a=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",a);let n={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();n={...n,...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:n,body:JSON.stringify(a),signal:o.signal},a)}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:n,body:JSON.stringify(a),signal:o.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,o){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var s;let a=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/agents/${r.agentId}/approve`,n={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(n,await this.getHeaders()),fetch(a,{method:"POST",headers:n,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(r,t,o){var i,d;let n=`${((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(n,{method:"POST",headers:s,body:JSON.stringify({executionId:r,toolOutputs:t,streamResponse:(d=o==null?void 0:o.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(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,n)=>{let s=new Date(a.createdAt).getTime(),i=new Date(n.createdAt).getTime();return s-i}).map(a=>{var n,s,i;return{role:a.role,content:(i=(s=(n=a.contentParts)!=null?n:a.llmContent)!=null?s:a.rawContent)!=null?i:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async n=>{try{let s=await n({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(a,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(r){let o={messages:r.slice().filter(td).sort((a,n)=>{let s=new Date(a.createdAt).getTime(),i=new Date(n.createdAt).getTime();return s-i}).map(a=>{var n,s,i;return{role:a.role,content:(i=(s=(n=a.contentParts)!=null?n:a.llmContent)!=null?s:a.rawContent)!=null?i:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async n=>{try{let s=await n({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(a,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object")return a}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(r,t,o,a,n,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:n(),...u!==void 0&&{partId:u}};return o.current=p,a(p),p},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,a(o.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,a(u)}return i.done&&(o.current&&(o.current.streaming=!1,a(o.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,o){var Wt,Yt,Fr,Ar;let a=r.getReader(),n=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=F=>{let ie=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,We=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Xe=F.tools?F.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...F,reasoning:ie,toolCall:We,tools:Xe}},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,ie,We="")=>`${F}::${ie}::${We}`,L=(F,ie)=>`${F}::${ie}::`,O=(F,ie,We,Xe)=>{let Ne=S(F,ie,We),Ue=A.get(Ne);if(Ue)return Ue;let tt=We?`-${We}`:"",yt={id:`nested-${F}-${ie}${tt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...We?{partId:We}:{},agentMetadata:{executionId:Xe,parentToolId:F,parentStepId:ie}};return A.set(Ne,yt),p(yt),yt},H=F=>{if(F==null)return null;try{return String(F)}catch{return null}},R=F=>{var ie,We,Xe,Ne,Ue;return H((Ue=(Ne=(Xe=(We=(ie=F.stepId)!=null?ie:F.step_id)!=null?We:F.step)!=null?Xe:F.parentId)!=null?Ne:F.flowStepId)!=null?Ue:F.flow_step_id)},B=F=>{var ie,We,Xe,Ne,Ue,tt,yt;return H((yt=(tt=(Ue=(Ne=(Xe=(We=(ie=F.callId)!=null?ie:F.call_id)!=null?We:F.requestId)!=null?Xe:F.request_id)!=null?Ne:F.toolCallId)!=null?Ue:F.tool_call_id)!=null?tt:F.stepId)!=null?yt:F.step_id)},V=o,oe=!1,fe=()=>{if(m)return m;let F;return!oe&&V?(F=V,oe=!0):V&&w.current?F=`${V}_${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},_e=(F,ie)=>{b.lastId=ie,F&&b.byStep.set(F,ie)},je=(F,ie)=>{var Ue;let We=(Ue=F.reasoningId)!=null?Ue:F.id,Xe=R(F);if(We){let tt=String(We);return _e(Xe,tt),tt}if(Xe){let tt=b.byStep.get(Xe);if(tt)return b.lastId=tt,tt}if(b.lastId&&!ie)return b.lastId;if(!ie)return null;let Ne=`reason-${l()}`;return _e(Xe,Ne),Ne},ye=F=>{let ie=k.get(F);if(ie)return ie;let We={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,We),p(We),We},me=(F,ie)=>{h.lastId=ie,F&&h.byCall.set(F,ie)},Pe=new Set,Ve=new Map,Q=new Set,Ae=new Map,J=F=>{if(!F)return!1;let ie=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return ie==="emit_artifact_markdown"||ie==="emit_artifact_component"},de=(F,ie)=>{var Ue;let We=(Ue=F.toolId)!=null?Ue:F.id,Xe=B(F);if(We){let tt=String(We);return me(Xe,tt),tt}if(Xe){let tt=h.byCall.get(Xe);if(tt)return h.lastId=tt,tt}if(h.lastId&&!ie)return h.lastId;if(!ie)return null;let Ne=`tool-${l()}`;return me(Xe,Ne),Ne},pe=F=>{let ie=T.get(F);if(ie)return ie;let We={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,We),p(We),We},se=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let ie=Number(F);if(!Number.isNaN(ie)&&Number.isFinite(ie))return ie;let We=Date.parse(F);if(!Number.isNaN(We))return We}return Date.now()},Be=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Ee=new Map,K=new Map,Oe=new Map,Fe=new Map,Y=null,G=(F,ie,We)=>{var yt;let Xe=Oe.get(F);Xe||(Xe=[],Oe.set(F,Xe));let Ne=0,Ue=Xe.length;for(;Ne<Ue;){let Mt=Ne+Ue>>>1;Xe[Mt].seq<ie?Ne=Mt+1:Ue=Mt}((yt=Xe[Ne])==null?void 0:yt.seq)===ie?Xe[Ne]={seq:ie,text:We}:Xe.splice(Ne,0,{seq:ie,text:We});let tt="";for(let Mt=0;Mt<Xe.length;Mt++)tt+=Xe[Mt].text;return tt},we=(F,ie)=>{let We=Be(ie),Xe=K.get(F.id),Ne=ob(Xe,We);F.rawContent=Ne;let Ue=Ee.get(F.id),tt=le=>{var ct;let Te=(ct=F.content)!=null?ct:"";le.trim()!==""&&(Te.trim().length===0||le.startsWith(Te)||le.trimStart().startsWith(Te.trim()))&&(F.content=le)},yt=()=>{var le;if(Ue){let Te=(le=Ue.close)==null?void 0:le.call(Ue);Te instanceof Promise&&Te.catch(()=>{})}Ee.delete(F.id),K.delete(F.id),F.streaming=!1,p(F)};if(!Ue){tt(We),yt();return}let Mt=Kn(Ne);if(Mt!==null&&Mt.trim()!==""){tt(Mt),yt();return}let _t=le=>{var Ke;let Te=typeof le=="string"?le:(Ke=le==null?void 0:le.text)!=null?Ke:null;if(Te!==null&&Te.trim()!=="")return Te;let ct=Ue.getExtractedText();return ct!==null&&ct.trim()!==""?ct:We},N;try{N=Ue.processChunk(Ne)}catch{tt(We),yt();return}if(N instanceof Promise){N.then(le=>{tt(_t(le)),yt()}).catch(()=>{tt(We),yt()});return}tt(_t(N)),yt()},ue=[],re=!1,he,Je=()=>{re||(re=!0,queueMicrotask(()=>{re=!1,he()}))},Ot=new Ti((F,ie)=>{ue.push({payloadType:F,payload:ie}),Je()}),ce=null,$e=new Map,fr=(Wt=this.config.iterationDisplay)!=null?Wt:"separate";for(he=()=>{var F,ie,We,Xe,Ne,Ue,tt,yt,Mt,_t,N,le,Te,ct,Ke,$t,nr,Lt,vt,Ze,at,tr,go,Rr,To,At,ho,ur,Sr,Yr,gt,ko,oo,Tr,kr,Vo,Eo,xo,bt,Me,M,Z,ne,St,Ut,Rt,ar,xr,Nr,Er,rt,wr,_r,pn,jo,un,Fo,no,Mo,Ct,sr,ir,ao,fn,yo,Lo,so,q,xe,io,Po,No,Oa,Io,Ro,Ho,Go,Rn,Ns,Fa,_s,la,xt,Na,bo,Qr,$s,Us,da,Xo,qs,Hn,_a,Jo,$a,mn,gn,zs,Vs,Hl,Bn,hn,js,Ua,xn,Gs,qa,yn,za,Xs,Ko,Js,bn,qt,ca,pa,Va,_o,Ks,ja,Ga,Xa,Ja,$r,lo,Yo,lt,Ka,Wn,Bo,Ys,ua,fa,Dn,Cn,Qs,Zs,Wo;for(let Qo=0;Qo<ue.length;Qo++){let et=ue[Qo].payloadType,P=ue[Qo].payload;if(et==="reason_start"){let z=(F=je(P,!0))!=null?F:`reason-${l()}`,I=ye(z);I.reasoning=(ie=I.reasoning)!=null?ie:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Xe=I.reasoning.startedAt)!=null?Xe:se((We=P.startedAt)!=null?We:P.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(et==="reason_delta"||et==="reason_chunk"){let z=(Ue=(Ne=je(P,!1))!=null?Ne:je(P,!0))!=null?Ue:`reason-${l()}`,I=ye(z);I.reasoning=(tt=I.reasoning)!=null?tt:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Mt=I.reasoning.startedAt)!=null?Mt:se((yt=P.startedAt)!=null?yt:P.timestamp);let j=(le=(N=(_t=P.reasoningText)!=null?_t:P.text)!=null?N:P.delta)!=null?le:"";if(j&&P.hidden!==!0){let He=typeof P.sequenceIndex=="number"?P.sequenceIndex:void 0;if(He!==void 0){let ae=G(z,He,String(j));I.reasoning.chunks=[ae]}else I.reasoning.chunks.push(String(j))}if(I.reasoning.status=P.done?"complete":"streaming",P.done){I.reasoning.completedAt=se((Te=P.completedAt)!=null?Te:P.timestamp);let He=(ct=I.reasoning.startedAt)!=null?ct:Date.now();I.reasoning.durationMs=Math.max(0,((Ke=I.reasoning.completedAt)!=null?Ke:Date.now())-He)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(et==="reason_complete"){let z=(nr=($t=je(P,!1))!=null?$t:je(P,!0))!=null?nr:`reason-${l()}`,I=k.get(z);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=se((Lt=P.completedAt)!=null?Lt:P.timestamp);let He=(vt=I.reasoning.startedAt)!=null?vt:Date.now();I.reasoning.durationMs=Math.max(0,((Ze=I.reasoning.completedAt)!=null?Ze:Date.now())-He),I.streaming=!1,p(I)}let j=R(P);j&&b.byStep.delete(j)}else if(et==="tool_start"){let z=(at=de(P,!0))!=null?at:`tool-${l()}`,I=(tr=P.toolName)!=null?tr:P.name;if(J(I)){Pe.add(z);continue}let j=pe(z),He=(go=j.toolCall)!=null?go:{id:z,status:"pending"};He.name=I!=null?I:He.name,He.status="running",P.args!==void 0?He.args=P.args:P.parameters!==void 0&&(He.args=P.parameters),He.startedAt=(To=He.startedAt)!=null?To:se((Rr=P.startedAt)!=null?Rr:P.timestamp),He.completedAt=void 0,He.durationMs=void 0,j.toolCall=He,j.streaming=!0;let ae=P.agentContext;(ae||P.executionId)&&(j.agentMetadata={executionId:(At=ae==null?void 0:ae.executionId)!=null?At:P.executionId,iteration:(ho=ae==null?void 0:ae.iteration)!=null?ho:P.iteration}),p(j)}else if(et==="tool_chunk"||et==="tool_delta"){let z=(Sr=(ur=de(P,!1))!=null?ur:de(P,!0))!=null?Sr:`tool-${l()}`;if(Pe.has(z))continue;let I=pe(z),j=(Yr=I.toolCall)!=null?Yr:{id:z,status:"running"};j.startedAt=(ko=j.startedAt)!=null?ko:se((gt=P.startedAt)!=null?gt:P.timestamp);let He=(kr=(Tr=(oo=P.text)!=null?oo:P.delta)!=null?Tr:P.message)!=null?kr:"";He&&(j.chunks=(Vo=j.chunks)!=null?Vo:[],j.chunks.push(String(He))),j.status="running",I.toolCall=j,I.streaming=!0;let ae=P.agentContext;(ae||P.executionId)&&(I.agentMetadata=(bt=I.agentMetadata)!=null?bt:{executionId:(Eo=ae==null?void 0:ae.executionId)!=null?Eo:P.executionId,iteration:(xo=ae==null?void 0:ae.iteration)!=null?xo:P.iteration}),p(I)}else if(et==="tool_complete"){let z=(M=(Me=de(P,!1))!=null?Me:de(P,!0))!=null?M:`tool-${l()}`;if(Pe.has(z)){Pe.delete(z);continue}let I=pe(z),j=(Z=I.toolCall)!=null?Z:{id:z,status:"running"};j.status="complete",P.result!==void 0&&(j.result=P.result),typeof P.duration=="number"&&(j.duration=P.duration),j.completedAt=se((ne=P.completedAt)!=null?ne:P.timestamp);let He=(St=P.duration)!=null?St:P.executionTime;if(typeof He=="number")j.durationMs=He;else{let ot=(Ut=j.startedAt)!=null?Ut:Date.now();j.durationMs=Math.max(0,((Rt=j.completedAt)!=null?Rt:Date.now())-ot)}I.toolCall=j,I.streaming=!1;let ae=P.agentContext;(ae||P.executionId)&&(I.agentMetadata=(Nr=I.agentMetadata)!=null?Nr:{executionId:(ar=ae==null?void 0:ae.executionId)!=null?ar:P.executionId,iteration:(xr=ae==null?void 0:ae.iteration)!=null?xr:P.iteration}),p(I);let st=B(P);st&&h.byCall.delete(st)}else if(et==="step_await"&&P.awaitReason==="local_tool_required"&&P.toolName){let z=(Er=P.toolId)!=null?Er:`local-${l()}`,I=pe(z),j=(rt=I.toolCall)!=null?rt:{id:z,status:"pending"};j.name=P.toolName,j.args=P.parameters,j.status="complete",j.chunks=(wr=j.chunks)!=null?wr:[],j.startedAt=(pn=j.startedAt)!=null?pn:se((_r=P.startedAt)!=null?_r:P.timestamp),j.completedAt=(jo=j.completedAt)!=null?jo:j.startedAt,I.toolCall=j,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:(Fo=P.executionId)!=null?Fo:(un=I.agentMetadata)==null?void 0:un.executionId,awaitingLocalTool:!0},p(I)}else if(et==="text_start"){if((no=P.toolContext)!=null&&no.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(et==="text_end"){if((Mo=P.toolContext)!=null&&Mo.toolId)continue;let z=m;z&&(z.streaming=!1,p(z),Y=z,m=null,v=!0)}else if(et==="step_chunk"||et==="step_delta"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let j=P.toolContext;if(j!=null&&j.toolId){let ot=String((sr=(Ct=P.id)!=null?Ct:j.stepId)!=null?sr:`step-${l()}`),Ft=P.partId!==void 0&&P.partId!==null?String(P.partId):"",kt=`${j.toolId}::${ot}`,Nt=E.get(kt);if(Ft!==""&&Nt!==void 0&&Nt!==""&&Nt!==Ft){let Pt=A.get(S(j.toolId,ot,Nt));Pt&&Pt.streaming!==!1&&(Pt.streaming=!1,p(Pt))}Ft!==""&&E.set(kt,Ft);let Gt=O(j.toolId,ot,Ft,j.executionId),lr=(yo=(fn=(ao=(ir=P.text)!=null?ir:P.delta)!=null?ao:P.content)!=null?fn:P.chunk)!=null?yo:"";lr&&(Gt.content+=String(lr),Gt.streaming=!0,p(Gt)),P.isComplete&&(Gt.streaming=!1,p(Gt));continue}let He=P.partId;if(He!==void 0&&w.current!==null&&He!==w.current){let ot=m;ot&&(ot.streaming=!1,p(ot),Y=ot,m=null,v=!0)}He!==void 0&&(w.current=He);let ae=He!==void 0&&(Lo=Fe.get(He))!=null?Lo:fe();He!==void 0&&(ae.partId||(ae.partId=He),Fe.set(He,ae));let st=(io=(xe=(q=(so=P.text)!=null?so:P.delta)!=null?q:P.content)!=null?xe:P.chunk)!=null?io:"";if(st){let ot=typeof P.seq=="number"?P.seq:void 0,Ft=He!=null?He:ae.id,kt=ot!==void 0?G(Ft,ot,String(st)):((Po=K.get(ae.id))!=null?Po:"")+st;ae.rawContent=kt,Ee.has(ae.id)||Ee.set(ae.id,this.createStreamParser());let Nt=Ee.get(ae.id),Gt=kt.trim().startsWith("{")||kt.trim().startsWith("[");if(Gt&&K.set(ae.id,kt),Nt.__isPlainTextParser===!0){ae.content=ot!==void 0?kt:ae.content+st,K.delete(ae.id),Ee.delete(ae.id),ae.rawContent=void 0,p(ae);continue}let Pt=Nt.processChunk(kt);if(Pt instanceof Promise)Pt.then(Et=>{var Hr;let yr=typeof Et=="string"?Et:(Hr=Et==null?void 0:Et.text)!=null?Hr:null;if(yr!==null&&yr.trim()!=="")ae.content=yr,p(ae);else if(!Gt&&!kt.trim().startsWith("<")){let Mr=m,dr=Mr&&Mr.id===ae.id?Mr:ae;dr.id===ae.id&&(dr.content=ot!==void 0?kt:dr.content+st,K.delete(dr.id),Ee.delete(dr.id),dr.rawContent=void 0,p(dr))}}).catch(()=>{ae.content=ot!==void 0?kt:ae.content+st,K.delete(ae.id),Ee.delete(ae.id),ae.rawContent=void 0,p(ae)});else{let Et=typeof Pt=="string"?Pt:(No=Pt==null?void 0:Pt.text)!=null?No:null;Et!==null&&Et.trim()!==""?(ae.content=Et,p(ae)):!Gt&&!kt.trim().startsWith("<")&&(ae.content=ot!==void 0?kt:ae.content+st,K.delete(ae.id),Ee.delete(ae.id),ae.rawContent=void 0,p(ae))}}if(P.isComplete){let ot=(Io=(Oa=P.result)==null?void 0:Oa.response)!=null?Io:ae.content;if(ot){let Ft=K.get(ae.id),kt=Ft!=null?Ft:Be(ot);ae.rawContent=kt;let Nt=Ee.get(ae.id),Gt=null,lr=!1;if(Nt&&(Gt=Nt.getExtractedText(),Gt===null&&(Gt=Kn(kt)),Gt===null)){let Pt=Nt.processChunk(kt);Pt instanceof Promise?(lr=!0,Pt.then(Et=>{var Hr;let yr=typeof Et=="string"?Et:(Hr=Et==null?void 0:Et.text)!=null?Hr:null;if(yr!==null){let Mr=m;Mr&&Mr.id===ae.id&&(Mr.content=yr,Mr.streaming=!1,Ee.delete(Mr.id),K.delete(Mr.id),p(Mr))}})):Gt=typeof Pt=="string"?Pt:(Ro=Pt==null?void 0:Pt.text)!=null?Ro:null}if(!lr){Gt!==null&&Gt.trim()!==""?ae.content=Gt:K.has(ae.id)||(ae.content=Be(ot));let Pt=Ee.get(ae.id);if(Pt){let Et=(Ho=Pt.close)==null?void 0:Ho.call(Pt);Et instanceof Promise&&Et.catch(()=>{}),Ee.delete(ae.id)}K.delete(ae.id),ae.streaming=!1,p(ae)}}}}else if(et==="step_complete"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let j=P.toolContext;if(j!=null&&j.toolId){let ot=String((Rn=(Go=P.id)!=null?Go:j.stepId)!=null?Rn:"");if(ot){let Ft=L(j.toolId,ot);for(let[kt,Nt]of A)kt.startsWith(Ft)&&Nt.streaming!==!1&&(Nt.streaming=!1,p(Nt));E.delete(`${j.toolId}::${ot}`)}continue}let He=P.stopReason;if(v){if(m!==null){let kt=m;He&&(kt.stopReason=He),Ee.delete(kt.id),K.delete(kt.id),kt.streaming!==!1&&(kt.streaming=!1,p(kt))}let ot=(Ns=P.result)==null?void 0:Ns.response,Ft=Y;Ft&&(He&&(Ft.stopReason=He),ot!=null?we(Ft,ot):(Ee.delete(Ft.id),K.delete(Ft.id))),Y=null;continue}let ae=(Fa=P.result)==null?void 0:Fa.response,st=fe();if(He&&(st.stopReason=He),ae!=null){let ot=Ee.get(st.id),Ft=!1,kt=!1;if(ot){let Nt=ot.getExtractedText(),Gt=K.get(st.id),lr=Gt!=null?Gt:Be(ae);if(st.rawContent=lr,Nt!==null&&Nt.trim()!=="")st.content=Nt,Ft=!0;else{let Pt=Kn(lr);if(Pt!==null)st.content=Pt,Ft=!0;else{let Et=ot.processChunk(lr);if(Et instanceof Promise)kt=!0,Et.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===st.id&&(dr.content=Hr,dr.streaming=!1,Ee.delete(dr.id),K.delete(dr.id),p(dr))}else{let dr=ot.getExtractedText(),vr=m;vr&&vr.id===st.id&&(dr!==null&&dr.trim()!==""?vr.content=dr:K.has(vr.id)||(vr.content=Be(ae)),vr.streaming=!1,Ee.delete(vr.id),K.delete(vr.id),p(vr))}});else{let yr=typeof Et=="string"?Et:(_s=Et==null?void 0:Et.text)!=null?_s:null;if(yr!==null&&yr.trim()!=="")st.content=yr,Ft=!0;else{let Hr=ot.getExtractedText();Hr!==null&&Hr.trim()!==""&&(st.content=Hr,Ft=!0)}}}}}if(!kt){if(!st.rawContent){let Nt=K.get(st.id);st.rawContent=Nt!=null?Nt:Be(ae)}if(!Ft&&!K.has(st.id)&&(st.content=Be(ae)),ot){let Nt=(la=ot.close)==null?void 0:la.call(ot);Nt instanceof Promise&&Nt.catch(()=>{})}Ee.delete(st.id),K.delete(st.id),st.streaming=!1,p(st)}}else Ee.delete(st.id),K.delete(st.id),st.streaming=!1,p(st)}else if(et==="flow_complete"){let z=(xt=P.result)==null?void 0:xt.response;if(v){if(m!==null){let I=m;Ee.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(z!=null){let I=fe(),j=K.get(I.id),He=j!=null?j:Be(z);I.rawContent=He;let ae=Be(z),st=Ee.get(I.id);if(st){let kt=Kn(He);if(kt!==null)ae=kt;else{let Nt=st.processChunk(He);Nt instanceof Promise&&Nt.then(lr=>{var Et;let Pt=typeof lr=="string"?lr:(Et=lr==null?void 0:lr.text)!=null?Et:null;Pt!==null&&(I.content=Pt,I.streaming=!1,p(I))});let Gt=st.getExtractedText();Gt!==null&&(ae=Gt)}}Ee.delete(I.id),K.delete(I.id);let ot=ae!==I.content,Ft=I.streaming!==!1;ot&&(I.content=ae),I.streaming=!1,(ot||Ft)&&p(I)}else if(m!==null){let I=m;Ee.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}t({type:"status",status:"idle"})}else if(et==="agent_start")ce={executionId:P.executionId,agentId:(Na=P.agentId)!=null?Na:"virtual",agentName:(bo=P.agentName)!=null?bo:"",status:"running",currentIteration:0,maxTurns:(Qr=P.maxTurns)!=null?Qr:1,startedAt:se(P.startedAt)};else if(et==="agent_iteration_start"){if(ce&&(ce.currentIteration=P.iteration),fr==="separate"&&P.iteration>1){let z=m;z&&(z.streaming=!1,p(z),$e.set(P.iteration-1,z),m=null)}}else if(et!=="agent_turn_start"){if(et==="agent_turn_delta"){if(P.contentType==="text"){let z=fe();z.content+=($s=P.delta)!=null?$s:"",z.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId,agentName:ce==null?void 0:ce.agentName},p(z)}else if(P.contentType==="thinking"){let z=(Us=P.turnId)!=null?Us:`agent-think-${P.iteration}`,I=ye(z);I.reasoning=(da=I.reasoning)!=null?da:{id:z,status:"streaming",chunks:[]},I.reasoning.chunks.push((Xo=P.delta)!=null?Xo:""),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=(Hn=I.toolCall.chunks)!=null?Hn:[],I.toolCall.chunks.push((_a=P.delta)!=null?_a:""),p(I))}}}else if(et==="agent_turn_complete"){let z=P.turnId;if(z){let j=k.get(z);if(j!=null&&j.reasoning){j.reasoning.status="complete",j.reasoning.completedAt=se(P.completedAt);let He=(Jo=j.reasoning.startedAt)!=null?Jo:Date.now();j.reasoning.durationMs=Math.max(0,(($a=j.reasoning.completedAt)!=null?$a:Date.now())-He),j.streaming=!1,p(j)}}let I=P.stopReason;if(I&&m!==null){let j=P.turnId;(!j||((mn=m.agentMetadata)==null?void 0:mn.turnId)===j)&&(m.stopReason=I,p(m))}}else if(et==="agent_tool_start"){let z=(gn=P.toolCallId)!=null?gn:`agent-tool-${l()}`;me(B(P),z);let I=pe(z),j=(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};j.name=(Hl=(Vs=P.toolName)!=null?Vs:P.name)!=null?Hl:j.name,j.status="running",P.parameters!==void 0&&(j.args=P.parameters),j.startedAt=se((Bn=P.startedAt)!=null?Bn:P.timestamp),I.toolCall=j,I.streaming=!0,I.agentMetadata={executionId:P.executionId,iteration:P.iteration},p(I)}else if(et==="agent_tool_delta"){let z=(hn=P.toolCallId)!=null?hn: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((xn=P.delta)!=null?xn:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(et==="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=se((yn=P.completedAt)!=null?yn:P.timestamp),I.streaming=!1,p(I);let j=B(P);j&&h.byCall.delete(j)}}}else if(et!=="agent_iteration_complete"){if(et==="agent_reflection"||et==="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(et==="agent_complete"){ce&&(ce.status=P.success?"complete":"error",ce.completedAt=se(P.completedAt),ce.stopReason=P.stopReason);let z=m;z&&(z.streaming=!1,p(z)),t({type:"status",status:"idle"})}else if(et==="agent_error"){let z=typeof P.error=="string"?P.error:(Js=(Ko=P.error)==null?void 0:Ko.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(et!=="agent_ping"){if(et==="agent_approval_start"){let z=(bn=P.approvalId)!=null?bn:`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:(qt=ce==null?void 0:ce.agentId)!=null?qt:"virtual",executionId:(pa=(ca=P.executionId)!=null?ca:ce==null?void 0:ce.executionId)!=null?pa:"",toolName:(Va=P.toolName)!=null?Va:"",toolType:P.toolType,description:(Ks=P.description)!=null?Ks:`Execute ${(_o=P.toolName)!=null?_o:"tool"}`,parameters:P.parameters}};p(I)}else if(et==="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=ce==null?void 0:ce.agentId)!=null?Ga:"virtual",executionId:(Ja=(Xa=P.executionId)!=null?Xa:ce==null?void 0:ce.executionId)!=null?Ja:"",toolName:($r=P.toolName)!=null?$r:"",toolType:P.toolType,description:(Yo=P.description)!=null?Yo:`Execute ${(lo=P.toolName)!=null?lo:"tool"}`,parameters:P.parameters}};p(I)}else if(et==="agent_approval_complete"){let z=P.approvalId;if(z){let j={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(lt=P.decision)!=null?lt:"approved",agentId:(Ka=ce==null?void 0:ce.agentId)!=null?Ka:"virtual",executionId:(Bo=(Wn=P.executionId)!=null?Wn:ce==null?void 0:ce.executionId)!=null?Bo:"",toolName:(Ys=P.toolName)!=null?Ys:"",description:(ua=P.description)!=null?ua:"",resolvedAt:Date.now()}};p(j)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let z=P.artifactType,I=String(P.id),j=typeof P.title=="string"?P.title:void 0;if(t({type:"artifact_start",id:I,artifactType:z,title:j,component:typeof P.component=="string"?P.component:void 0}),Ae.set(I,{markdown:"",title:j}),!Q.has(I)){Q.add(I);let He={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:j,artifactType:z,status:"streaming"}})};Ve.set(I,He),p(He)}}else if(et==="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 j=Ae.get(z);j&&(j.markdown+=I)}else if(et==="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(et==="artifact_complete"){let z=String(P.id);t({type:"artifact_complete",id:z});let I=Ve.get(z);if(I){I.streaming=!1;try{let j=JSON.parse((Dn=I.rawContent)!=null?Dn:"{}");if(j.props){j.props.status="complete";let He=Ae.get(z);He!=null&&He.markdown&&(j.props.markdown=He.markdown)}I.rawContent=JSON.stringify(j)}catch{}Ae.delete(z),p(I),Ve.delete(z)}}}else if(et==="transcript_insert"){let z=P.message;if(!z||typeof z!="object")continue;let I=String((Cn=z.id)!=null?Cn:`msg-${l()}`),j=z.role,ae={id:I,role:j==="user"?"user":j==="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(ae),ae.rawContent)try{let st=JSON.parse(ae.rawContent),ot=(Qs=st==null?void 0:st.props)==null?void 0:Qs.artifactId;typeof ot=="string"&&Q.add(ot)}catch{}m=null,f.current=null,Ee.delete(I),K.delete(I)}else if(et==="error"||et==="step_error"||et==="dispatch_error"||et==="flow_error"){let z=null;if(P.error instanceof Error)z=P.error;else if(et==="dispatch_error"){let I=(Zs=P.message)!=null?Zs:P.error;I!=null&&I!==""&&(z=new Error(String(I)))}else if(et==="step_error"||et==="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((Wo=I.message)!=null?Wo:I)))}else et==="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"})}}}}}}ue.length=0};;){let{done:F,value:ie}=await a.read();if(F)break;s+=n.decode(ie,{stream:!0});let We=s.split(`
|
|
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 a=Vm(r);if(a===null)return n;r=a;let o='<a href="'+r+'"';return t&&(o+=' title="'+t+'"'),o+=">"+n+"</a>",o}image(r,t,n){let a=Vm(r);if(a===null)return n;r=a;let o=`<img src="${r}" alt="${n}"`;return t&&(o+=` title="${t}"`),o+=">",o}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 a=0;a<r.length;a++){let o=r[a];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[o.type]){let s=o,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(o.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let s=o;n+=this.renderer.heading(this.parseInline(s.tokens),s.depth,Xx(this.parseInline(s.tokens,this.textRenderer)));continue}case"code":{let s=o;n+=this.renderer.code(s.text,s.lang,!!s.escaped);continue}case"table":{let s=o,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 m=0;m<p.length;m++)d+=this.renderer.tablecell(this.parseInline(p[m].tokens),{header:!1,align:s.align[m]});l+=this.renderer.tablerow(d)}n+=this.renderer.table(i,l);continue}case"blockquote":{let s=o,i=this.parse(s.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let s=o,i=s.ordered,d=s.start,l=s.loose,u="";for(let p=0;p<s.items.length;p++){let m=s.items[p],f=m.checked,w=m.task,v="";if(m.task){let k=this.renderer.checkbox(!!f);l?m.tokens.length>0&&m.tokens[0].type==="paragraph"?(m.tokens[0].text=k+" "+m.tokens[0].text,m.tokens[0].tokens&&m.tokens[0].tokens.length>0&&m.tokens[0].tokens[0].type==="text"&&(m.tokens[0].tokens[0].text=k+" "+m.tokens[0].tokens[0].text)):m.tokens.unshift({type:"text",text:k+" "}):v+=k+" "}v+=this.parse(m.tokens,l),u+=this.renderer.listitem(v,w,!!f)}n+=this.renderer.list(u,i,d);continue}case"html":{let s=o;n+=this.renderer.html(s.text,s.block);continue}case"paragraph":{let s=o;n+=this.renderer.paragraph(this.parseInline(s.tokens));continue}case"text":{let s=o,i=s.tokens?this.parseInline(s.tokens):s.text;for(;a+1<r.length&&r[a+1].type==="text";)s=r[++a],i+=`
|
|
46
|
+
`+(s.tokens?this.parseInline(s.tokens):s.text);n+=t?this.renderer.paragraph(i):i;continue}default:{let s='Token with "'+o.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 a=0;a<r.length;a++){let o=r[a];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[o.type]){let s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){n+=s||"";continue}}switch(o.type){case"escape":{let s=o;n+=t.text(s.text);break}case"html":{let s=o;n+=t.html(s.text);break}case"link":{let s=o;n+=t.link(s.href,s.title,this.parseInline(s.tokens,t));break}case"image":{let s=o;n+=t.image(s.href,s.title,s.text);break}case"strong":{let s=o;n+=t.strong(this.parseInline(s.tokens,t));break}case"em":{let s=o;n+=t.em(this.parseInline(s.tokens,t));break}case"codespan":{let s=o;n+=t.codespan(s.text);break}case"br":{n+=t.br();break}case"del":{let s=o;n+=t.del(this.parseInline(s.tokens,t));break}case"text":{let s=o;n+=t.text(s.text);break}default:{let s='Token with "'+o.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,ag,os=class{constructor(...r){qm(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 a,o;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;(o=(a=this.defaults.extensions)==null?void 0:a.childTokens)!=null&&o[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 a={...n};if(a.async=this.defaults.async||a.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let d=o.renderer.apply(this,i);return d===!1&&(d=s.apply(this,i)),d}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[o.level];s?s.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),a.extensions=t),n.renderer){let o=this.defaults.renderer||new xa(this.defaults);for(let s in n.renderer){if(!(s in o))throw new Error(`renderer '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.renderer[i],l=o[i];o[i]=(...u)=>{let p=d.apply(o,u);return p===!1&&(p=l.apply(o,u)),p||""}}a.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new ha(this.defaults);for(let s in n.tokenizer){if(!(s in o))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,d=n.tokenizer[i],l=o[i];o[i]=(...u)=>{let p=d.apply(o,u);return p===!1&&(p=l.apply(o,u)),p}}a.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new zo;for(let s in n.hooks){if(!(s in o))throw new Error(`hook '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.hooks[i],l=o[i];zo.passThroughHooks.has(s)?o[i]=u=>{if(this.defaults.async)return Promise.resolve(d.call(o,u)).then(m=>l.call(o,m));let p=d.call(o,u);return l.call(o,p)}:o[i]=(...u)=>{let p=d.apply(o,u);return p===!1&&(p=l.apply(o,u)),p}}a.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,s=n.walkTokens;a.walkTokens=function(i){let d=[];return d.push(s.call(this,i)),o&&(d=d.concat(o.call(this,i))),d}}this.defaults={...this.defaults,...a}}),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,a)=>{let o={...a},s={...this.defaults,...o};this.defaults.async===!0&&o.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,ag).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)}}},ag=function(r,t){return n=>{if(n.message+=`
|
|
47
|
+
Please report this to https://github.com/markedjs/marked.`,r){let a="<p>An error occurred:</p><pre>"+un(n.message+"",!0)+"</pre>";return t?Promise.resolve(a):a}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,Jm(Jt.defaults),Jt};Jt.getDefaults=Ol;Jt.defaults=Go;Jt.use=function(...e){return Vo.use(...e),Jt.defaults=Vo.defaults,Jm(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 JC=Jt.options,KC=Jt.setOptions,YC=Jt.use,QC=Jt.walkTokens,ZC=Jt.parseInline;var ew=ro.parse,tw=to.lex;var Sy=e=>{if(e)return e},is=e=>{var a,o;let r=e==null?void 0:e.markedOptions,t=new os({gfm:(a=r==null?void 0:r.gfm)!=null?a:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=Sy(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(),Ty=is(),ql=e=>Ty(e),Jo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ig=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),sg=e=>`%%FORM_PLACEHOLDER_${e}%%`,lg=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,a)=>{try{let o=JSON.parse(a.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let s=sg(r.length);return r.push({token:s,type:String(o.type)}),s}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,a)=>{let o=sg(r.length);return r.push({token:o,type:a}),o}),t},dg=e=>{let r=Xo(e);return t=>{let n=[],a=lg(t,n),o=r(a);return n.forEach(({token:s,type:i})=>{let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ig(i)}"></div>`;o=o.replace(d,u)}),o}},cg=e=>{let r=[],t=lg(e,r),n=ql(t);return r.forEach(({token:a,type:o})=>{let s=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ig(o)}"></div>`;n=n.replace(s,d)}),n};var{entries:bg,setPrototypeOf:pg,isFrozen:ky,getPrototypeOf:Ey,getOwnPropertyDescriptor:My}=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,a=new Array(n>2?n-2:0),o=2;o<n;o++)a[o-2]=arguments[o];return r.apply(t,a)});Yl||(Yl=function(r){for(var t=arguments.length,n=new Array(t>1?t-1:0),a=1;a<t;a++)n[a-1]=arguments[a];return new r(...n)});var ci=Xr(Array.prototype.forEach),Ly=Xr(Array.prototype.lastIndexOf),ug=Xr(Array.prototype.pop),ls=Xr(Array.prototype.push),Py=Xr(Array.prototype.splice),fi=Xr(String.prototype.toLowerCase),zl=Xr(String.prototype.toString),Vl=Xr(String.prototype.match),ds=Xr(String.prototype.replace),Iy=Xr(String.prototype.indexOf),Ry=Xr(String.prototype.trim),fn=Xr(Object.prototype.hasOwnProperty),jr=Xr(RegExp.prototype.test),cs=Hy(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),a=1;a<t;a++)n[a-1]=arguments[a];return Kl(e,r,n)}}function Hy(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 wt(e,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fi;pg&&pg(e,null);let n=r.length;for(;n--;){let a=r[n];if(typeof a=="string"){let o=t(a);o!==a&&(ky(r)||(r[n]=o),a=o)}e[a]=!0}return e}function By(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 bg(e))fn(e,t)&&(Array.isArray(n)?r[t]=By(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=My(e,r);if(n){if(n.get)return Xr(n.get);if(typeof n.value=="function")return Xr(n.value)}e=Ey(e)}function t(){return null}return t}var fg=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"]),Wy=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"]),Dy=Gr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),mg=Gr(["#text"]),gg=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"]),hg=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"]),Oy=wn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Fy=wn(/<%[\w\W]*|[\w\W]*%>/gm),Ny=wn(/\$\{[\w\W]*/gm),_y=wn(/^data-[\-\w.\u00B7-\uFFFF]+$/),$y=wn(/^aria-[\-\w]+$/),Cg=wn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Uy=wn(/^(?:\w+script|data):/i),qy=wn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),wg=wn(/^html$/i),zy=wn(/^[a-z][.\w]*(-[.\w]+)+$/i),xg=Object.freeze({__proto__:null,ARIA_ATTR:$y,ATTR_WHITESPACE:qy,CUSTOM_ELEMENT:zy,DATA_ATTR:_y,DOCTYPE_NAME:wg,ERB_EXPR:Fy,IS_ALLOWED_URI:Cg,IS_SCRIPT_OR_DATA:Uy,MUSTACHE_EXPR:Oy,TMPLIT_EXPR:Ny}),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},Vy=function(){return typeof window=="undefined"?null:window},jy=function(r,t){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let n=null,a="data-tt-policy-suffix";t&&t.hasAttribute(a)&&(n=t.getAttribute(a));let o="dompurify"+(n?"#"+n:"");try{return r.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},yg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function vg(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Vy(),r=Me=>vg(Me);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,a=n.currentScript,{DocumentFragment:o,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 Me=t.createElement("template");Me.content&&Me.content.ownerDocument&&(t=Me.content.ownerDocument)}let b,h="",{implementation:S,createNodeIterator:L,createDocumentFragment:O,getElementsByTagName:H}=t,{importNode:R}=n,B=yg();r.isSupported=typeof bg=="function"&&typeof E=="function"&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:ne,TMPLIT_EXPR:fe,DATA_ATTR:_e,ARIA_ATTR:je,IS_SCRIPT_OR_DATA:ye,ATTR_WHITESPACE:me,CUSTOM_ELEMENT:Pe}=xg,{IS_ALLOWED_URI:Ve}=xg,Q=null,Ae=wt({},[...fg,...jl,...Gl,...Xl,...mg]),J=null,de=wt({},[...gg,...Jl,...hg,...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}})),se=null,Be=null,Ee=Object.seal(ui(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),K=!0,Oe=!0,Fe=!1,Y=!0,G=!1,we=!0,ue=!1,re=!1,he=!1,Je=!1,Ot=!1,ce=!1,$e=!0,fr=!1,Wt="user-content-",Yt=!0,Fr=!1,Ar={},F=null,ie=wt({},["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"]),We=null,Xe=wt({},["audio","video","img","source","image","track"]),Ne=null,Ue=wt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),tt="http://www.w3.org/1998/Math/MathML",yt="http://www.w3.org/2000/svg",Mt="http://www.w3.org/1999/xhtml",$t=Mt,N=!1,le=null,Te=wt({},[tt,yt,Mt],zl),ct=wt({},["mi","mo","mn","ms","mtext"]),Ke=wt({},["annotation-xml"]),Ut=wt({},["title","style","font","a","script"]),or=null,Lt=["application/xhtml+xml","text/html"],vt="text/html",Ze=null,at=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(!(at&&at===M)){if((!M||typeof M!="object")&&(M={}),M=Un(M),or=Lt.indexOf(M.PARSER_MEDIA_TYPE)===-1?vt:M.PARSER_MEDIA_TYPE,Ze=or==="application/xhtml+xml"?zl:fi,Q=fn(M,"ALLOWED_TAGS")?wt({},M.ALLOWED_TAGS,Ze):Ae,J=fn(M,"ALLOWED_ATTR")?wt({},M.ALLOWED_ATTR,Ze):de,le=fn(M,"ALLOWED_NAMESPACES")?wt({},M.ALLOWED_NAMESPACES,zl):Te,Ne=fn(M,"ADD_URI_SAFE_ATTR")?wt(Un(Ue),M.ADD_URI_SAFE_ATTR,Ze):Ue,We=fn(M,"ADD_DATA_URI_TAGS")?wt(Un(Xe),M.ADD_DATA_URI_TAGS,Ze):Xe,F=fn(M,"FORBID_CONTENTS")?wt({},M.FORBID_CONTENTS,Ze):ie,se=fn(M,"FORBID_TAGS")?wt({},M.FORBID_TAGS,Ze):Un({}),Be=fn(M,"FORBID_ATTR")?wt({},M.FORBID_ATTR,Ze):Un({}),Ar=fn(M,"USE_PROFILES")?M.USE_PROFILES:!1,K=M.ALLOW_ARIA_ATTR!==!1,Oe=M.ALLOW_DATA_ATTR!==!1,Fe=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,ue=M.WHOLE_DOCUMENT||!1,Je=M.RETURN_DOM||!1,Ot=M.RETURN_DOM_FRAGMENT||!1,ce=M.RETURN_TRUSTED_TYPE||!1,he=M.FORCE_BODY||!1,$e=M.SANITIZE_DOM!==!1,fr=M.SANITIZE_NAMED_PROPS||!1,Yt=M.KEEP_CONTENT!==!1,Fr=M.IN_PLACE||!1,Ve=M.ALLOWED_URI_REGEXP||Cg,$t=M.NAMESPACE||Mt,ct=M.MATHML_TEXT_INTEGRATION_POINTS||ct,Ke=M.HTML_INTEGRATION_POINTS||Ke,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&&(Oe=!1),Ot&&(Je=!0),Ar&&(Q=wt({},mg),J=ui(null),Ar.html===!0&&(wt(Q,fg),wt(J,gg)),Ar.svg===!0&&(wt(Q,jl),wt(J,Jl),wt(J,pi)),Ar.svgFilters===!0&&(wt(Q,Gl),wt(J,Jl),wt(J,pi)),Ar.mathMl===!0&&(wt(Q,Xl),wt(J,hg),wt(J,pi))),fn(M,"ADD_TAGS")||(Ee.tagCheck=null),fn(M,"ADD_ATTR")||(Ee.attributeCheck=null),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?Ee.tagCheck=M.ADD_TAGS:(Q===Ae&&(Q=Un(Q)),wt(Q,M.ADD_TAGS,Ze))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?Ee.attributeCheck=M.ADD_ATTR:(J===de&&(J=Un(J)),wt(J,M.ADD_ATTR,Ze))),M.ADD_URI_SAFE_ATTR&&wt(Ne,M.ADD_URI_SAFE_ATTR,Ze),M.FORBID_CONTENTS&&(F===ie&&(F=Un(F)),wt(F,M.FORBID_CONTENTS,Ze)),M.ADD_FORBID_CONTENTS&&(F===ie&&(F=Un(F)),wt(F,M.ADD_FORBID_CONTENTS,Ze)),Yt&&(Q["#text"]=!0),ue&&wt(Q,["html","head","body"]),Q.table&&(wt(Q,["tbody"]),delete se.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,a)),b!==null&&typeof h=="string"&&(h=b.createHTML(""));Gr&&Gr(M),at=M}},Tn=wt({},[...jl,...Gl,...Wy]),At=wt({},[...Xl,...Dy]),hn=function(M){let Z=E(M);(!Z||!Z.tagName)&&(Z={namespaceURI:$t,tagName:"template"});let oe=fi(M.tagName),St=fi(Z.tagName);return le[M.namespaceURI]?M.namespaceURI===yt?Z.namespaceURI===Mt?oe==="svg":Z.namespaceURI===tt?oe==="svg"&&(St==="annotation-xml"||ct[St]):!!Tn[oe]:M.namespaceURI===tt?Z.namespaceURI===Mt?oe==="math":Z.namespaceURI===yt?oe==="math"&&Ke[St]:!!At[oe]:M.namespaceURI===Mt?Z.namespaceURI===yt&&!Ke[St]||Z.namespaceURI===tt&&!ct[St]?!1:!At[oe]&&(Ut[oe]||!Tn[oe]):!!(or==="application/xhtml+xml"&&le[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(Je||Ot)try{ur(Z)}catch{}else try{Z.setAttribute(M,"")}catch{}},Yr=function(M){let Z=null,oe=null;if(he)M="<remove></remove>"+M;else{let Rt=Vl(M,/^[\r\n\t ]+/);oe=Rt&&Rt[0]}or==="application/xhtml+xml"&&$t===Mt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");let St=b?b.createHTML(M):M;if($t===Mt)try{Z=new m().parseFromString(St,or)}catch{}if(!Z||!Z.documentElement){Z=S.createDocument($t,"template",null);try{Z.documentElement.innerHTML=N?h:St}catch{}}let qt=Z.body||Z.documentElement;return M&&oe&&qt.insertBefore(t.createTextNode(oe),qt.childNodes[0]||null),$t===Mt?H.call(Z,ue?"html":"body")[0]:ue?Z.documentElement:qt},gt=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(Me,M,Z){ci(Me,oe=>{oe.call(r,M,Z,at)})}let kr=function(M){let Z=null;if(Tr(B.beforeSanitizeElements,M,null),kn(M))return ur(M),!0;let oe=Ze(M.nodeName);if(Tr(B.uponSanitizeElement,M,{tagName:oe,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(!(Ee.tagCheck instanceof Function&&Ee.tagCheck(oe))&&(!Q[oe]||se[oe])){if(!se[oe]&&En(oe)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,oe)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(oe)))return!1;if(Yt&&!F[oe]){let St=E(M)||M.parentNode,qt=A(M)||M.childNodes;if(qt&&St){let Rt=qt.length;for(let ar=Rt-1;ar>=0;--ar){let xr=v(qt[ar],!0);xr.__removalCount=(M.__removalCount||0)+1,St.insertBefore(xr,T(M))}}}return ur(M),!0}return M instanceof d&&!hn(M)||(oe==="noscript"||oe==="noembed"||oe==="noframes")&&jr(/<\/no(script|embed|frames)/i,M.innerHTML)?(ur(M),!0):(G&&M.nodeType===us.text&&(Z=M.textContent,ci([V,ne,fe],St=>{Z=ds(Z,St," ")}),M.textContent!==Z&&(ls(r.removed,{element:M.cloneNode()}),M.textContent=Z)),Tr(B.afterSanitizeElements,M,null),!1)},Vn=function(M,Z,oe){if(Be[Z]||$e&&(Z==="id"||Z==="name")&&(oe in t||oe in tr))return!1;if(!(Oe&&!Be[Z]&&jr(_e,Z))){if(!(K&&jr(je,Z))){if(!(Ee.attributeCheck instanceof Function&&Ee.attributeCheck(Z,M))){if(!J[Z]||Be[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,oe)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(oe))))return!1}else if(!Ne[Z]){if(!jr(Ve,ds(oe,me,""))){if(!((Z==="src"||Z==="xlink:href"||Z==="href")&&M!=="script"&&Iy(oe,"data:")===0&&We[M])){if(!(Fe&&!jr(ye,ds(oe,me,"")))){if(oe)return!1}}}}}}}return!0},En=function(M){return M!=="annotation-xml"&&Vl(M,Pe)},xn=function(M){Tr(B.beforeSanitizeAttributes,M,null);let{attributes:Z}=M;if(!Z||kn(M))return;let oe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J,forceKeepAttr:void 0},St=Z.length;for(;St--;){let qt=Z[St],{name:Rt,namespaceURI:ar,value:xr}=qt,Nr=Ze(Rt),Er=xr,rt=Rt==="value"?Er:Ry(Er);if(oe.attrName=Nr,oe.attrValue=rt,oe.keepAttr=!0,oe.forceKeepAttr=void 0,Tr(B.uponSanitizeAttribute,M,oe),rt=oe.attrValue,fr&&(Nr==="id"||Nr==="name")&&(Sr(Rt,M),rt=Wt+rt),we&&jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,rt)){Sr(Rt,M);continue}if(Nr==="attributename"&&Vl(rt,"href")){Sr(Rt,M);continue}if(oe.forceKeepAttr)continue;if(!oe.keepAttr){Sr(Rt,M);continue}if(!Y&&jr(/\/>/i,rt)){Sr(Rt,M);continue}G&&ci([V,ne,fe],_r=>{rt=ds(rt,_r," ")});let wr=Ze(M.nodeName);if(!Vn(wr,Nr,rt)){Sr(Rt,M);continue}if(b&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!ar)switch(f.getAttributeType(wr,Nr)){case"TrustedHTML":{rt=b.createHTML(rt);break}case"TrustedScriptURL":{rt=b.createScriptURL(rt);break}}if(rt!==Er)try{ar?M.setAttributeNS(ar,Rt,rt):M.setAttribute(Rt,rt),kn(M)?ur(M):ug(r.removed)}catch{Sr(Rt,M)}}Tr(B.afterSanitizeAttributes,M,null)},bt=function Me(M){let Z=null,oe=gt(M);for(Tr(B.beforeSanitizeShadowDOM,M,null);Z=oe.nextNode();)Tr(B.uponSanitizeShadowNode,Z,null),kr(Z),xn(Z),Z.content instanceof o&&Me(Z.content);Tr(B.afterSanitizeShadowDOM,M,null)};return r.sanitize=function(Me){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Z=null,oe=null,St=null,qt=null;if(N=!Me,N&&(Me="<!-->"),typeof Me!="string"&&!nn(Me))if(typeof Me.toString=="function"){if(Me=Me.toString(),typeof Me!="string")throw cs("dirty is not a string, aborting")}else throw cs("toString is not a function");if(!r.isSupported)return Me;if(re||Rr(M),r.removed=[],typeof Me=="string"&&(Fr=!1),Fr){if(Me.nodeName){let xr=Ze(Me.nodeName);if(!Q[xr]||se[xr])throw cs("root node is forbidden and cannot be sanitized in-place")}}else if(Me instanceof i)Z=Yr("<!---->"),oe=Z.ownerDocument.importNode(Me,!0),oe.nodeType===us.element&&oe.nodeName==="BODY"||oe.nodeName==="HTML"?Z=oe:Z.appendChild(oe);else{if(!Je&&!G&&!ue&&Me.indexOf("<")===-1)return b&&ce?b.createHTML(Me):Me;if(Z=Yr(Me),!Z)return Je?null:ce?h:""}Z&&he&&ur(Z.firstChild);let Rt=gt(Fr?Me:Z);for(;St=Rt.nextNode();)kr(St),xn(St),St.content instanceof o&&bt(St.content);if(Fr)return Me;if(Je){if(Ot)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=ue?Z.outerHTML:Z.innerHTML;return ue&&Q["!doctype"]&&Z.ownerDocument&&Z.ownerDocument.doctype&&Z.ownerDocument.doctype.name&&jr(wg,Z.ownerDocument.doctype.name)&&(ar="<!DOCTYPE "+Z.ownerDocument.doctype.name+`>
|
|
48
|
+
`+ar),G&&ci([V,ne,fe],xr=>{ar=ds(ar,xr," ")}),b&&ce?b.createHTML(ar):ar},r.setConfig=function(){let Me=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rr(Me),re=!0},r.clearConfig=function(){at=null,re=!1},r.isValidAttribute=function(Me,M,Z){at||Rr({});let oe=Ze(Me),St=Ze(M);return Vn(oe,St,Z)},r.addHook=function(Me,M){typeof M=="function"&&ls(B[Me],M)},r.removeHook=function(Me,M){if(M!==void 0){let Z=Ly(B[Me],M);return Z===-1?void 0:Py(B[Me],Z,1)[0]}return ug(B[Me])},r.removeHooks=function(Me){B[Me]=[]},r.removeAllHooks=function(){B=yg()},r}var Ag=vg();var Gy={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"]},Xy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ql=()=>{let e=Ag(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:")&&!Xy.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Gy)},ya=e=>e===!1?null:typeof e=="function"?e:Ql();var no=Bl(hi(),1),xi=e=>e.replace(/\\n/g,`
|
|
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)}},Zy=e=>{var s,i;let r=(s=e.completedAt)!=null?s:Date.now(),t=(i=e.startedAt)!=null?i:r,a=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return a<.1?"Thought for <0.1 seconds":`Thought for ${a>=10?Math.round(a).toString():a.toFixed(1).replace(/\.0$/,"")} seconds`},Tg=e=>e.status==="complete"?Zy(e):e.status==="pending"?"Waiting":"",eb=e=>{var a,o,s;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((a=e.completedAt)!=null?a:Date.now())-((s=(o=e.startedAt)!=null?o: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 kg=e=>e.status==="complete"?eb(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,a;let r=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((a=(n=e.startedAt)!=null?n:e.completedAt)!=null?a:Date.now()));return yi(r)},bi=e=>{var t,n,a;let r=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((a=(n=e.startedAt)!=null?n:e.completedAt)!=null?a:Date.now()));return yi(r)},ed=(e,r,t)=>{var o;if(!r)return t;let n=((o=e.name)==null?void 0:o.trim())||"tool",a=ms(e);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,a)},Ci=(e,r)=>{let t=e.replace(/\{toolName\}/g,r),n=[],a=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,s;for(;(s=a.exec(t))!==null;)s.index>o&&fs(n,t.slice(o,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"]),o=s.index+s[0].length;return o<t.length&&fs(n,t.slice(o),[]),n},fs=(e,r,t)=>{let n=r.split("{duration}");for(let a=0;a<n.length;a++)n[a]&&e.push({text:n[a],styles:t}),a<n.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},tb=()=>{let e=null,r=0,t=n=>{let a=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.match(a);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
50
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[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 a=n.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),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=tb();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 a=(0,no.parse)(t,no.STR|no.OBJ);a&&typeof a=="object"&&(a.component&&typeof a.component=="string"?e=typeof a.text=="string"?xi(a.text):"":a.type==="init"&&a.form?e="":typeof a.text=="string"&&(e=xi(a.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Eg=e=>{let r=null,t=0,a=e||(o=>{if(!o||typeof o!="object")return null;let s=i=>typeof i=="string"?xi(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xi(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return s(o.on_load_text)||s(o.text)||null;case"message":case"message_and_click":case"checkout":return s(o.text)||null;default:return s(o.text)||s(o.display_text)||s(o.message)||null}return s(o.text)||s(o.display_text)||s(o.message)||s(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let s=o.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,no.parse)(o,no.STR|no.OBJ),d=a(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},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 o,s,i;let n=(i=(o=t==null?void 0:t.seq)!=null?o: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 a=this.buffer.get(n);a!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${a.payloadType} vs ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(a.payloadType,a.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 rb="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com",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 nb(e){switch(e){case"json":return Ai;case"regex-json":return vi;case"xml":return Si;default:return wi}}var Mg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ob(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 a=Mg(t);if(!Mg(n))return e;if(!a||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,a;this.apiUrl=(t=r.apiUrl)!=null?t:rb,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:nb(r.parserType),this.contextProviders=(a=r.contextProviders)!=null?a:[],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 o,s;let r=((s=(o=this.config).getStoredSessionId)==null?void 0:s.call(o))||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 a=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.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 o,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 a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o),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 a,o,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,(o=(a=this.config).onSessionExpired)==null||o.call(a);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 a=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",a);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(a),signal:n.signal},a)}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:o,body:JSON.stringify(a),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 a=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",a);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(a),signal:n.signal},a)}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:o,body:JSON.stringify(a),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 a=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(a,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(r,t,n){var i,d;let o=`${((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(o,{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(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,o)=>{let s=new Date(a.createdAt).getTime(),i=new Date(o.createdAt).getTime();return s-i}).map(a=>{var o,s,i;return{role:a.role,content:(i=(s=(o=a.contentParts)!=null?o:a.llmContent)!=null?s:a.rawContent)!=null?i:a.content,createdAt:a.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async o=>{try{let s=await o({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(a,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(a).length&&(n.context=a)}return n}async buildPayload(r){let n={messages:r.slice().filter(td).sort((a,o)=>{let s=new Date(a.createdAt).getTime(),i=new Date(o.createdAt).getTime();return s-i}).map(a=>{var o,s,i;return{role:a.role,content:(i=(s=(o=a.contentParts)!=null?o:a.llmContent)!=null?s:a.rawContent)!=null?i:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async o=>{try{let s=await o({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(a,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(a).length&&(n.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...n},config:this.config});if(a&&typeof a=="object")return a}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return n}async handleCustomSSEEvent(r,t,n,a,o,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:o(),...u!==void 0&&{partId:u}};return n.current=p,a(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,a(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,a(u)}return i.done&&(n.current&&(n.current.streaming=!1,a(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 Wt,Yt,Fr,Ar;let a=r.getReader(),o=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=F=>{let ie=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,We=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Xe=F.tools?F.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...F,reasoning:ie,toolCall:We,tools:Xe}},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,ie,We="")=>`${F}::${ie}::${We}`,L=(F,ie)=>`${F}::${ie}::`,O=(F,ie,We,Xe)=>{let Ne=S(F,ie,We),Ue=A.get(Ne);if(Ue)return Ue;let tt=We?`-${We}`:"",yt={id:`nested-${F}-${ie}${tt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...We?{partId:We}:{},agentMetadata:{executionId:Xe,parentToolId:F,parentStepId:ie}};return A.set(Ne,yt),p(yt),yt},H=F=>{if(F==null)return null;try{return String(F)}catch{return null}},R=F=>{var ie,We,Xe,Ne,Ue;return H((Ue=(Ne=(Xe=(We=(ie=F.stepId)!=null?ie:F.step_id)!=null?We:F.step)!=null?Xe:F.parentId)!=null?Ne:F.flowStepId)!=null?Ue:F.flow_step_id)},B=F=>{var ie,We,Xe,Ne,Ue,tt,yt;return H((yt=(tt=(Ue=(Ne=(Xe=(We=(ie=F.callId)!=null?ie:F.call_id)!=null?We:F.requestId)!=null?Xe:F.request_id)!=null?Ne:F.toolCallId)!=null?Ue:F.tool_call_id)!=null?tt:F.stepId)!=null?yt:F.step_id)},V=n,ne=!1,fe=()=>{if(m)return m;let F;return!ne&&V?(F=V,ne=!0):V&&w.current?F=`${V}_${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},_e=(F,ie)=>{b.lastId=ie,F&&b.byStep.set(F,ie)},je=(F,ie)=>{var Ue;let We=(Ue=F.reasoningId)!=null?Ue:F.id,Xe=R(F);if(We){let tt=String(We);return _e(Xe,tt),tt}if(Xe){let tt=b.byStep.get(Xe);if(tt)return b.lastId=tt,tt}if(b.lastId&&!ie)return b.lastId;if(!ie)return null;let Ne=`reason-${l()}`;return _e(Xe,Ne),Ne},ye=F=>{let ie=k.get(F);if(ie)return ie;let We={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,We),p(We),We},me=(F,ie)=>{h.lastId=ie,F&&h.byCall.set(F,ie)},Pe=new Set,Ve=new Map,Q=new Set,Ae=new Map,J=F=>{if(!F)return!1;let ie=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return ie==="emit_artifact_markdown"||ie==="emit_artifact_component"},de=(F,ie)=>{var Ue;let We=(Ue=F.toolId)!=null?Ue:F.id,Xe=B(F);if(We){let tt=String(We);return me(Xe,tt),tt}if(Xe){let tt=h.byCall.get(Xe);if(tt)return h.lastId=tt,tt}if(h.lastId&&!ie)return h.lastId;if(!ie)return null;let Ne=`tool-${l()}`;return me(Xe,Ne),Ne},pe=F=>{let ie=T.get(F);if(ie)return ie;let We={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,We),p(We),We},se=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let ie=Number(F);if(!Number.isNaN(ie)&&Number.isFinite(ie))return ie;let We=Date.parse(F);if(!Number.isNaN(We))return We}return Date.now()},Be=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Ee=new Map,K=new Map,Oe=new Map,Fe=new Map,Y=null,G=(F,ie,We)=>{var yt;let Xe=Oe.get(F);Xe||(Xe=[],Oe.set(F,Xe));let Ne=0,Ue=Xe.length;for(;Ne<Ue;){let Mt=Ne+Ue>>>1;Xe[Mt].seq<ie?Ne=Mt+1:Ue=Mt}((yt=Xe[Ne])==null?void 0:yt.seq)===ie?Xe[Ne]={seq:ie,text:We}:Xe.splice(Ne,0,{seq:ie,text:We});let tt="";for(let Mt=0;Mt<Xe.length;Mt++)tt+=Xe[Mt].text;return tt},we=(F,ie)=>{let We=Be(ie),Xe=K.get(F.id),Ne=ob(Xe,We);F.rawContent=Ne;let Ue=Ee.get(F.id),tt=le=>{var ct;let Te=(ct=F.content)!=null?ct:"";le.trim()!==""&&(Te.trim().length===0||le.startsWith(Te)||le.trimStart().startsWith(Te.trim()))&&(F.content=le)},yt=()=>{var le;if(Ue){let Te=(le=Ue.close)==null?void 0:le.call(Ue);Te instanceof Promise&&Te.catch(()=>{})}Ee.delete(F.id),K.delete(F.id),F.streaming=!1,p(F)};if(!Ue){tt(We),yt();return}let Mt=Ko(Ne);if(Mt!==null&&Mt.trim()!==""){tt(Mt),yt();return}let $t=le=>{var Ke;let Te=typeof le=="string"?le:(Ke=le==null?void 0:le.text)!=null?Ke:null;if(Te!==null&&Te.trim()!=="")return Te;let ct=Ue.getExtractedText();return ct!==null&&ct.trim()!==""?ct:We},N;try{N=Ue.processChunk(Ne)}catch{tt(We),yt();return}if(N instanceof Promise){N.then(le=>{tt($t(le)),yt()}).catch(()=>{tt(We),yt()});return}tt($t(N)),yt()},ue=[],re=!1,he,Je=()=>{re||(re=!0,queueMicrotask(()=>{re=!1,he()}))},Ot=new Ti((F,ie)=>{ue.push({payloadType:F,payload:ie}),Je()}),ce=null,$e=new Map,fr=(Wt=this.config.iterationDisplay)!=null?Wt:"separate";for(he=()=>{var F,ie,We,Xe,Ne,Ue,tt,yt,Mt,$t,N,le,Te,ct,Ke,Ut,or,Lt,vt,Ze,at,tr,gn,Rr,Tn,At,hn,ur,Sr,Yr,gt,kn,nn,Tr,kr,Vn,En,xn,bt,Me,M,Z,oe,St,qt,Rt,ar,xr,Nr,Er,rt,wr,_r,po,jn,uo,Fn,on,Mn,Ct,sr,ir,an,fo,yn,Ln,sn,q,xe,ln,Pn,Nn,Oa,In,Rn,Hn,Gn,Ro,Ns,Fa,_s,la,xt,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,Ft,ca,pa,Va,_n,Ks,ja,Ga,Xa,Ja,$r,dn,Yn,lt,Ka,Wo,Bn,Ys,ua,fa,Do,Co,Qs,Zs,Wn;for(let Qn=0;Qn<ue.length;Qn++){let et=ue[Qn].payloadType,P=ue[Qn].payload;if(et==="reason_start"){let z=(F=je(P,!0))!=null?F:`reason-${l()}`,I=ye(z);I.reasoning=(ie=I.reasoning)!=null?ie:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Xe=I.reasoning.startedAt)!=null?Xe:se((We=P.startedAt)!=null?We:P.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(et==="reason_delta"||et==="reason_chunk"){let z=(Ue=(Ne=je(P,!1))!=null?Ne:je(P,!0))!=null?Ue:`reason-${l()}`,I=ye(z);I.reasoning=(tt=I.reasoning)!=null?tt:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Mt=I.reasoning.startedAt)!=null?Mt:se((yt=P.startedAt)!=null?yt:P.timestamp);let j=(le=(N=($t=P.reasoningText)!=null?$t:P.text)!=null?N:P.delta)!=null?le:"";if(j&&P.hidden!==!0){let He=typeof P.sequenceIndex=="number"?P.sequenceIndex:void 0;if(He!==void 0){let ae=G(z,He,String(j));I.reasoning.chunks=[ae]}else I.reasoning.chunks.push(String(j))}if(I.reasoning.status=P.done?"complete":"streaming",P.done){I.reasoning.completedAt=se((Te=P.completedAt)!=null?Te:P.timestamp);let He=(ct=I.reasoning.startedAt)!=null?ct:Date.now();I.reasoning.durationMs=Math.max(0,((Ke=I.reasoning.completedAt)!=null?Ke:Date.now())-He)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(et==="reason_complete"){let z=(or=(Ut=je(P,!1))!=null?Ut:je(P,!0))!=null?or:`reason-${l()}`,I=k.get(z);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=se((Lt=P.completedAt)!=null?Lt:P.timestamp);let He=(vt=I.reasoning.startedAt)!=null?vt:Date.now();I.reasoning.durationMs=Math.max(0,((Ze=I.reasoning.completedAt)!=null?Ze:Date.now())-He),I.streaming=!1,p(I)}let j=R(P);j&&b.byStep.delete(j)}else if(et==="tool_start"){let z=(at=de(P,!0))!=null?at:`tool-${l()}`,I=(tr=P.toolName)!=null?tr:P.name;if(J(I)){Pe.add(z);continue}let j=pe(z),He=(gn=j.toolCall)!=null?gn:{id:z,status:"pending"};He.name=I!=null?I:He.name,He.status="running",P.args!==void 0?He.args=P.args:P.parameters!==void 0&&(He.args=P.parameters),He.startedAt=(Tn=He.startedAt)!=null?Tn:se((Rr=P.startedAt)!=null?Rr:P.timestamp),He.completedAt=void 0,He.durationMs=void 0,j.toolCall=He,j.streaming=!0;let ae=P.agentContext;(ae||P.executionId)&&(j.agentMetadata={executionId:(At=ae==null?void 0:ae.executionId)!=null?At:P.executionId,iteration:(hn=ae==null?void 0:ae.iteration)!=null?hn:P.iteration}),p(j)}else if(et==="tool_chunk"||et==="tool_delta"){let z=(Sr=(ur=de(P,!1))!=null?ur:de(P,!0))!=null?Sr:`tool-${l()}`;if(Pe.has(z))continue;let I=pe(z),j=(Yr=I.toolCall)!=null?Yr:{id:z,status:"running"};j.startedAt=(kn=j.startedAt)!=null?kn:se((gt=P.startedAt)!=null?gt:P.timestamp);let He=(kr=(Tr=(nn=P.text)!=null?nn:P.delta)!=null?Tr:P.message)!=null?kr:"";He&&(j.chunks=(Vn=j.chunks)!=null?Vn:[],j.chunks.push(String(He))),j.status="running",I.toolCall=j,I.streaming=!0;let ae=P.agentContext;(ae||P.executionId)&&(I.agentMetadata=(bt=I.agentMetadata)!=null?bt:{executionId:(En=ae==null?void 0:ae.executionId)!=null?En:P.executionId,iteration:(xn=ae==null?void 0:ae.iteration)!=null?xn:P.iteration}),p(I)}else if(et==="tool_complete"){let z=(M=(Me=de(P,!1))!=null?Me:de(P,!0))!=null?M:`tool-${l()}`;if(Pe.has(z)){Pe.delete(z);continue}let I=pe(z),j=(Z=I.toolCall)!=null?Z:{id:z,status:"running"};j.status="complete",P.result!==void 0&&(j.result=P.result),typeof P.duration=="number"&&(j.duration=P.duration),j.completedAt=se((oe=P.completedAt)!=null?oe:P.timestamp);let He=(St=P.duration)!=null?St:P.executionTime;if(typeof He=="number")j.durationMs=He;else{let nt=(qt=j.startedAt)!=null?qt:Date.now();j.durationMs=Math.max(0,((Rt=j.completedAt)!=null?Rt:Date.now())-nt)}I.toolCall=j,I.streaming=!1;let ae=P.agentContext;(ae||P.executionId)&&(I.agentMetadata=(Nr=I.agentMetadata)!=null?Nr:{executionId:(ar=ae==null?void 0:ae.executionId)!=null?ar:P.executionId,iteration:(xr=ae==null?void 0:ae.iteration)!=null?xr:P.iteration}),p(I);let st=B(P);st&&h.byCall.delete(st)}else if(et==="step_await"&&P.awaitReason==="local_tool_required"&&P.toolName){let z=(Er=P.toolId)!=null?Er:`local-${l()}`,I=pe(z),j=(rt=I.toolCall)!=null?rt:{id:z,status:"pending"};j.name=P.toolName,j.args=P.parameters,j.status="complete",j.chunks=(wr=j.chunks)!=null?wr:[],j.startedAt=(po=j.startedAt)!=null?po:se((_r=P.startedAt)!=null?_r:P.timestamp),j.completedAt=(jn=j.completedAt)!=null?jn:j.startedAt,I.toolCall=j,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(et==="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(et==="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(et==="step_chunk"||et==="step_delta"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let j=P.toolContext;if(j!=null&&j.toolId){let nt=String((sr=(Ct=P.id)!=null?Ct:j.stepId)!=null?sr:`step-${l()}`),Nt=P.partId!==void 0&&P.partId!==null?String(P.partId):"",kt=`${j.toolId}::${nt}`,_t=E.get(kt);if(Nt!==""&&_t!==void 0&&_t!==""&&_t!==Nt){let Pt=A.get(S(j.toolId,nt,_t));Pt&&Pt.streaming!==!1&&(Pt.streaming=!1,p(Pt))}Nt!==""&&E.set(kt,Nt);let Gt=O(j.toolId,nt,Nt,j.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 He=P.partId;if(He!==void 0&&w.current!==null&&He!==w.current){let nt=m;nt&&(nt.streaming=!1,p(nt),Y=nt,m=null,v=!0)}He!==void 0&&(w.current=He);let ae=He!==void 0&&(Ln=Fe.get(He))!=null?Ln:fe();He!==void 0&&(ae.partId||(ae.partId=He),Fe.set(He,ae));let st=(ln=(xe=(q=(sn=P.text)!=null?sn:P.delta)!=null?q:P.content)!=null?xe:P.chunk)!=null?ln:"";if(st){let nt=typeof P.seq=="number"?P.seq:void 0,Nt=He!=null?He:ae.id,kt=nt!==void 0?G(Nt,nt,String(st)):((Pn=K.get(ae.id))!=null?Pn:"")+st;ae.rawContent=kt,Ee.has(ae.id)||Ee.set(ae.id,this.createStreamParser());let _t=Ee.get(ae.id),Gt=kt.trim().startsWith("{")||kt.trim().startsWith("[");if(Gt&&K.set(ae.id,kt),_t.__isPlainTextParser===!0){ae.content=nt!==void 0?kt:ae.content+st,K.delete(ae.id),Ee.delete(ae.id),ae.rawContent=void 0,p(ae);continue}let Pt=_t.processChunk(kt);if(Pt instanceof Promise)Pt.then(Et=>{var Hr;let yr=typeof Et=="string"?Et:(Hr=Et==null?void 0:Et.text)!=null?Hr:null;if(yr!==null&&yr.trim()!=="")ae.content=yr,p(ae);else if(!Gt&&!kt.trim().startsWith("<")){let Mr=m,dr=Mr&&Mr.id===ae.id?Mr:ae;dr.id===ae.id&&(dr.content=nt!==void 0?kt:dr.content+st,K.delete(dr.id),Ee.delete(dr.id),dr.rawContent=void 0,p(dr))}}).catch(()=>{ae.content=nt!==void 0?kt:ae.content+st,K.delete(ae.id),Ee.delete(ae.id),ae.rawContent=void 0,p(ae)});else{let Et=typeof Pt=="string"?Pt:(Nn=Pt==null?void 0:Pt.text)!=null?Nn:null;Et!==null&&Et.trim()!==""?(ae.content=Et,p(ae)):!Gt&&!kt.trim().startsWith("<")&&(ae.content=nt!==void 0?kt:ae.content+st,K.delete(ae.id),Ee.delete(ae.id),ae.rawContent=void 0,p(ae))}}if(P.isComplete){let nt=(In=(Oa=P.result)==null?void 0:Oa.response)!=null?In:ae.content;if(nt){let Nt=K.get(ae.id),kt=Nt!=null?Nt:Be(nt);ae.rawContent=kt;let _t=Ee.get(ae.id),Gt=null,lr=!1;if(_t&&(Gt=_t.getExtractedText(),Gt===null&&(Gt=Ko(kt)),Gt===null)){let Pt=_t.processChunk(kt);Pt instanceof Promise?(lr=!0,Pt.then(Et=>{var Hr;let yr=typeof Et=="string"?Et:(Hr=Et==null?void 0:Et.text)!=null?Hr:null;if(yr!==null){let Mr=m;Mr&&Mr.id===ae.id&&(Mr.content=yr,Mr.streaming=!1,Ee.delete(Mr.id),K.delete(Mr.id),p(Mr))}})):Gt=typeof Pt=="string"?Pt:(Rn=Pt==null?void 0:Pt.text)!=null?Rn:null}if(!lr){Gt!==null&&Gt.trim()!==""?ae.content=Gt:K.has(ae.id)||(ae.content=Be(nt));let Pt=Ee.get(ae.id);if(Pt){let Et=(Hn=Pt.close)==null?void 0:Hn.call(Pt);Et instanceof Promise&&Et.catch(()=>{}),Ee.delete(ae.id)}K.delete(ae.id),ae.streaming=!1,p(ae)}}}}else if(et==="step_complete"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let j=P.toolContext;if(j!=null&&j.toolId){let nt=String((Ro=(Gn=P.id)!=null?Gn:j.stepId)!=null?Ro:"");if(nt){let Nt=L(j.toolId,nt);for(let[kt,_t]of A)kt.startsWith(Nt)&&_t.streaming!==!1&&(_t.streaming=!1,p(_t));E.delete(`${j.toolId}::${nt}`)}continue}let He=P.stopReason;if(v){if(m!==null){let kt=m;He&&(kt.stopReason=He),Ee.delete(kt.id),K.delete(kt.id),kt.streaming!==!1&&(kt.streaming=!1,p(kt))}let nt=(Ns=P.result)==null?void 0:Ns.response,Nt=Y;Nt&&(He&&(Nt.stopReason=He),nt!=null?we(Nt,nt):(Ee.delete(Nt.id),K.delete(Nt.id))),Y=null;continue}let ae=(Fa=P.result)==null?void 0:Fa.response,st=fe();if(He&&(st.stopReason=He),ae!=null){let nt=Ee.get(st.id),Nt=!1,kt=!1;if(nt){let _t=nt.getExtractedText(),Gt=K.get(st.id),lr=Gt!=null?Gt:Be(ae);if(st.rawContent=lr,_t!==null&&_t.trim()!=="")st.content=_t,Nt=!0;else{let Pt=Ko(lr);if(Pt!==null)st.content=Pt,Nt=!0;else{let Et=nt.processChunk(lr);if(Et instanceof Promise)kt=!0,Et.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===st.id&&(dr.content=Hr,dr.streaming=!1,Ee.delete(dr.id),K.delete(dr.id),p(dr))}else{let dr=nt.getExtractedText(),vr=m;vr&&vr.id===st.id&&(dr!==null&&dr.trim()!==""?vr.content=dr:K.has(vr.id)||(vr.content=Be(ae)),vr.streaming=!1,Ee.delete(vr.id),K.delete(vr.id),p(vr))}});else{let yr=typeof Et=="string"?Et:(_s=Et==null?void 0:Et.text)!=null?_s:null;if(yr!==null&&yr.trim()!=="")st.content=yr,Nt=!0;else{let Hr=nt.getExtractedText();Hr!==null&&Hr.trim()!==""&&(st.content=Hr,Nt=!0)}}}}}if(!kt){if(!st.rawContent){let _t=K.get(st.id);st.rawContent=_t!=null?_t:Be(ae)}if(!Nt&&!K.has(st.id)&&(st.content=Be(ae)),nt){let _t=(la=nt.close)==null?void 0:la.call(nt);_t instanceof Promise&&_t.catch(()=>{})}Ee.delete(st.id),K.delete(st.id),st.streaming=!1,p(st)}}else Ee.delete(st.id),K.delete(st.id),st.streaming=!1,p(st)}else if(et==="flow_complete"){let z=(xt=P.result)==null?void 0:xt.response;if(v){if(m!==null){let I=m;Ee.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(z!=null){let I=fe(),j=K.get(I.id),He=j!=null?j:Be(z);I.rawContent=He;let ae=Be(z),st=Ee.get(I.id);if(st){let kt=Ko(He);if(kt!==null)ae=kt;else{let _t=st.processChunk(He);_t instanceof Promise&&_t.then(lr=>{var Et;let Pt=typeof lr=="string"?lr:(Et=lr==null?void 0:lr.text)!=null?Et:null;Pt!==null&&(I.content=Pt,I.streaming=!1,p(I))});let Gt=st.getExtractedText();Gt!==null&&(ae=Gt)}}Ee.delete(I.id),K.delete(I.id);let nt=ae!==I.content,Nt=I.streaming!==!1;nt&&(I.content=ae),I.streaming=!1,(nt||Nt)&&p(I)}else if(m!==null){let I=m;Ee.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}t({type:"status",status:"idle"})}else if(et==="agent_start")ce={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:se(P.startedAt)};else if(et==="agent_iteration_start"){if(ce&&(ce.currentIteration=P.iteration),fr==="separate"&&P.iteration>1){let z=m;z&&(z.streaming=!1,p(z),$e.set(P.iteration-1,z),m=null)}}else if(et!=="agent_turn_start"){if(et==="agent_turn_delta"){if(P.contentType==="text"){let z=fe();z.content+=($s=P.delta)!=null?$s:"",z.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId,agentName:ce==null?void 0:ce.agentName},p(z)}else if(P.contentType==="thinking"){let z=(Us=P.turnId)!=null?Us:`agent-think-${P.iteration}`,I=ye(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(et==="agent_turn_complete"){let z=P.turnId;if(z){let j=k.get(z);if(j!=null&&j.reasoning){j.reasoning.status="complete",j.reasoning.completedAt=se(P.completedAt);let He=(Jn=j.reasoning.startedAt)!=null?Jn:Date.now();j.reasoning.durationMs=Math.max(0,(($a=j.reasoning.completedAt)!=null?$a:Date.now())-He),j.streaming=!1,p(j)}}let I=P.stopReason;if(I&&m!==null){let j=P.turnId;(!j||((mo=m.agentMetadata)==null?void 0:mo.turnId)===j)&&(m.stopReason=I,p(m))}}else if(et==="agent_tool_start"){let z=(go=P.toolCallId)!=null?go:`agent-tool-${l()}`;me(B(P),z);let I=pe(z),j=(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};j.name=(Hl=(Vs=P.toolName)!=null?Vs:P.name)!=null?Hl:j.name,j.status="running",P.parameters!==void 0&&(j.args=P.parameters),j.startedAt=se((Bo=P.startedAt)!=null?Bo:P.timestamp),I.toolCall=j,I.streaming=!0,I.agentMetadata={executionId:P.executionId,iteration:P.iteration},p(I)}else if(et==="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(et==="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=se((yo=P.completedAt)!=null?yo:P.timestamp),I.streaming=!1,p(I);let j=B(P);j&&h.byCall.delete(j)}}}else if(et!=="agent_iteration_complete"){if(et==="agent_reflection"||et==="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(et==="agent_complete"){ce&&(ce.status=P.success?"complete":"error",ce.completedAt=se(P.completedAt),ce.stopReason=P.stopReason);let z=m;z&&(z.streaming=!1,p(z)),t({type:"status",status:"idle"})}else if(et==="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(et!=="agent_ping"){if(et==="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:(Ft=ce==null?void 0:ce.agentId)!=null?Ft:"virtual",executionId:(pa=(ca=P.executionId)!=null?ca:ce==null?void 0:ce.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(et==="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=ce==null?void 0:ce.agentId)!=null?Ga:"virtual",executionId:(Ja=(Xa=P.executionId)!=null?Xa:ce==null?void 0:ce.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(et==="agent_approval_complete"){let z=P.approvalId;if(z){let j={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(lt=P.decision)!=null?lt:"approved",agentId:(Ka=ce==null?void 0:ce.agentId)!=null?Ka:"virtual",executionId:(Bn=(Wo=P.executionId)!=null?Wo:ce==null?void 0:ce.executionId)!=null?Bn:"",toolName:(Ys=P.toolName)!=null?Ys:"",description:(ua=P.description)!=null?ua:"",resolvedAt:Date.now()}};p(j)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let z=P.artifactType,I=String(P.id),j=typeof P.title=="string"?P.title:void 0;if(t({type:"artifact_start",id:I,artifactType:z,title:j,component:typeof P.component=="string"?P.component:void 0}),Ae.set(I,{markdown:"",title:j}),!Q.has(I)){Q.add(I);let He={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:j,artifactType:z,status:"streaming"}})};Ve.set(I,He),p(He)}}else if(et==="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 j=Ae.get(z);j&&(j.markdown+=I)}else if(et==="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(et==="artifact_complete"){let z=String(P.id);t({type:"artifact_complete",id:z});let I=Ve.get(z);if(I){I.streaming=!1;try{let j=JSON.parse((Do=I.rawContent)!=null?Do:"{}");if(j.props){j.props.status="complete";let He=Ae.get(z);He!=null&&He.markdown&&(j.props.markdown=He.markdown)}I.rawContent=JSON.stringify(j)}catch{}Ae.delete(z),p(I),Ve.delete(z)}}}else if(et==="transcript_insert"){let z=P.message;if(!z||typeof z!="object")continue;let I=String((Co=z.id)!=null?Co:`msg-${l()}`),j=z.role,ae={id:I,role:j==="user"?"user":j==="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(ae),ae.rawContent)try{let st=JSON.parse(ae.rawContent),nt=(Qs=st==null?void 0:st.props)==null?void 0:Qs.artifactId;typeof nt=="string"&&Q.add(nt)}catch{}m=null,f.current=null,Ee.delete(I),K.delete(I)}else if(et==="error"||et==="step_error"||et==="dispatch_error"||et==="flow_error"){let z=null;if(P.error instanceof Error)z=P.error;else if(et==="dispatch_error"){let I=(Zs=P.message)!=null?Zs:P.error;I!=null&&I!==""&&(z=new Error(String(I)))}else if(et==="step_error"||et==="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 et==="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"})}}}}}}ue.length=0};;){let{done:F,value:ie}=await a.read();if(F)break;s+=o.decode(ie,{stream:!0});let We=s.split(`
|
|
52
52
|
|
|
53
53
|
`);s=(Yt=We.pop())!=null?Yt:"";for(let Xe of We){let Ne=Xe.split(`
|
|
54
|
-
`),Ue="message",tt="";for(let _t of Ne)_t.startsWith("event:")?Ue=_t.replace("event:","").trim():_t.startsWith("data:")&&(tt+=_t.replace("data:","").trim());if(!tt)continue;let yt;try{yt=JSON.parse(tt)}catch(_t){t({type:"error",error:_t instanceof Error?_t:new Error("Failed to parse chat stream payload")});continue}let Mt=Ue!=="message"?Ue:(Fr=yt.type)!=null?Fr:"message";if((Ar=this.onSSEEvent)==null||Ar.call(this,Mt,yt),this.parseSSEEvent){f.current=m;let _t=await this.handleCustomSSEEvent(yt,t,f,p,l,w);if(f.current&&f.current!==m&&(m=f.current),_t)continue}Ot.push(Mt,yt),he()}}Ot.flushPending(),he(),Ot.destroy()}};function Lg(){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 Qn(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ei="[Image]";function Pg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ig(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Rg(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Hg(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function gs(e){return{type:"text",text:e}}function Bg(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 Wg(e){return new Promise((r,t)=>{let o=new FileReader;o.onload=()=>{let a=o.result;r({type:"image",image:a,mimeType:e.type,alt:e.name})},o.onerror=()=>t(new Error("Failed to read file")),o.readAsDataURL(e)})}function Dg(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 Og=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],nb=["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"],nn=[...Og,...nb];function ab(e){return Og.includes(e)||e.startsWith("image/")}function Mi(e){return ab(e.type)}async function Fg(e){return new Promise((r,t)=>{let o=new FileReader;o.onload=()=>{let a=o.result;Mi(e)?r({type:"image",image:a,mimeType:e.type,alt:e.name}):r({type:"file",data:a,mimeType:e.type,filename:e.name})},o.onerror=()=>t(new Error("Failed to read file")),o.readAsDataURL(e)})}function Ng(e,r=nn,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 sb(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function _g(e,r){let t=sb(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 o=t.AudioContext||t.webkitAudioContext;this.ctx=new o({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 o=this.ensureContext(),a=this.pcmToFloat32(t),n=o.createBuffer(1,a.length,this.sampleRate);n.getChannelData(0).set(a);let s=o.createBufferSource();s.buffer=n,s.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=n.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),o=new Float32Array(t),a=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let n=0;n<t;n++){let s=a.getInt16(n*2,!0);o[n]=s/32768}return o}};var Pi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,o,a,n){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);(o==="silence"?d<a.threshold:d>=a.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=a.duration&&(this.fired=!0,n()):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,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let a=this.w;if(!a||!a.location)throw new Error("Window object or location not available");let n=a.location.protocol==="https:"?"wss:":"ws:",s=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(o=this.config)==null?void 0:o.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=`${n}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${n}//${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(a){throw this.ws=null,this.errorCallbacks.forEach(n=>n(a)),this.statusCallbacks.forEach(n=>n("error")),a}}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(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,o;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(a=>a({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(a=>a("speaking")),this.playAudio(r.response.audio).catch(a=>this.errorCallbacks.forEach(n=>n(a instanceof Error?a:new Error(String(a)))))):(o=r.response.audio)!=null&&o.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(a=>a("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(a=>a(new Error(r.error))),this.statusCallbacks.forEach(a=>a("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,o,a;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 n=this.w;this.audioContext||(this.audioContext=new(n.AudioContext||n.webkitAudioContext));let s=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.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(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}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 n,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,o=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:o,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(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(r),a=this.getFormatFromMimeType(r.type),n=this.generateRequestId();this.currentRequestId=n,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:a,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:n}))}catch(o){this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,o)=>{let a=new FileReader;a.onload=()=>{let s=a.result.split(",")[1];t(s)},a.onerror=o,a.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),o=new Uint8Array(t.length);for(let l=0;l<t.length;l++)o[l]=t.charCodeAt(l);let a=r.format||"mp3",n=a==="mp3"?"audio/mpeg":`audio/${a}`,s=new Blob([o],{type:n}),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 Zn=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 o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,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=a=>{var i;let n=Array.from(a.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=a.results[a.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:n,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=a=>{this.errorCallbacks.forEach(n=>n(new Error(a.error))),this.statusCallbacks.forEach(n=>n("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(a=>a("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(a=>a("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}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(!Zn.isSupported())throw new Error("Browser speech recognition not supported");return new Zn(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(Zn.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,o,a,n,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:(o=r.message.agentMetadata.agentName)!=null?o:"",status:"running",currentIteration:(a=r.message.agentMetadata.iteration)!=null?a: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,((n=this.agentExecution)==null?void 0:n.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 o,a;this.messages=[...(o=r.initialMessages)!=null?o:[]].map(n=>{var s;return{...n,sequence:(s=n.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yn(r);for(let n of(a=r.initialArtifacts)!=null?a:[])this.artifacts.set(n.id,{...n,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,o;return(o=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?o:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,o,a;try{let n=r||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=ea(n);let s=(t=this.config.voiceRecognition)!=null?t:{},i=(o=s.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(a=s.processingErrorText)!=null?a:"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(n){console.error("Failed to setup voice:",n)}}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,o,a,n,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:((o=r.runtype)==null?void 0:o.agentId)||"",clientToken:((a=r.runtype)==null?void 0:a.clientToken)||"",host:(n=r.runtype)==null?void 0:n.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 o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(t=(r=this.callbacks).onError)==null||t.call(r,o instanceof Error?o:new Error(String(o))),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 Yn(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:o,llmContent:a,contentParts:n,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u}=r,m={id:s!=null?s:t==="user"?Ca():t==="assistant"?Qn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...a!==void 0&&{llmContent:a},...n!==void 0&&{contentParts:n},...u!==void 0&&{voiceProcessing:u}};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 o of r){let{role:a,content:n,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1}=o,f={id:d!=null?d:a==="user"?Ca():a==="assistant"?Qn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:a,content:n,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}};t.push(f)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var l,u,p,m,f;let o=r.trim();if(!o&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let a=Ca(),n=Qn(),s={id:a,role:"user",content:o||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:n},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:n,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 a,n,s,i,d;if(this.streaming)return;(a=this.abortController)==null||a.abort();let r=Qn();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let o=[...this.messages];try{await this.client.dispatch({messages:o,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=(n=this.callbacks).onError)==null||s.call(n,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(r,t){var a,n,s;if(this.streaming)return;(a=this.abortController)==null||a.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&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=(n=this.callbacks).onError)==null||s.call(n,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,l,u;let o=`approval-${r.id}`,a={...r,status:t,resolvedAt:Date.now()},n={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:a};this.upsertMessage(n);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 o=this.messages.find(a=>a.id===r.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(r,t){let o=this.messages.find(a=>a.id===r.id);o&&this.upsertMessage({...o,agentMetadata:{...o.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 o=this.messages.find(h=>h.id===r.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let a=(p=r.agentMetadata)==null?void 0:p.executionId,n=(m=r.toolCall)==null?void 0:m.name;if(!a||!n){(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(a,{[n]: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 a;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let n={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}let o={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(a=r.props)!=null?a:{}};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}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,o;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 a=this.artifacts.get(r.id);(a==null?void 0:a.artifactType)==="markdown"&&(a.markdown=((o=a.markdown)!=null?o:"")+r.artDelta);break}case"artifact_update":{let a=this.artifacts.get(r.id);(a==null?void 0:a.artifactType)==="component"&&(a.props={...a.props,...r.props},r.component&&(a.component=r.component));break}case"artifact_complete":{let a=this.artifacts.get(r.id);a&&(a.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(o=>{var a;return{...o,streaming:!1,sequence:(a=o.sequence)!=null?a:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(r,t=null){this.artifacts.clear();for(let o of r)this.artifacts.set(o.id,{...o,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 o=[...this.messages].reverse().find(n=>n.role==="assistant"&&n.content&&!n.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let a=o.content;a.trim()&&this.speak(a,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let a=new SpeechSynthesisUtterance(r),n=o.getVoices();if(t.voice){let s=n.find(i=>i.name===t.voice);s&&(a.voice=s)}else n.length>0&&(a.voice=t.pickVoice?t.pickVoice(n):e.pickBestVoice(n));t.rate!==void 0&&(a.rate=t.rate),t.pitch!==void 0&&(a.pitch=t.pitch),setTimeout(()=>o.speak(a),50)}static pickBestVoice(r){var o;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 a of t){let n=r.find(s=>s.name===a);if(n)return n}return(o=r.find(a=>a.lang.startsWith("en")))!=null?o: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),o=this.messages.findIndex(a=>a.id===t.id);if(o===-1){this.appendMessage(t);return}this.messages=this.messages.map((a,n)=>{var i;if(n!==o)return a;let s={...a,...t};return((i=a.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...a.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:a.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,o)=>{var d,l;let a=new Date(t.createdAt).getTime(),n=new Date(o.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(n)&&a!==n)return a-n;let s=(d=t.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return s!==i?s-i:t.id.localeCompare(o.id)})}};var x=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},qo=(e,r,t)=>{let o=e.createElement(r);return t&&(o.className=t),o};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 od=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var nd=[["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 oc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var nc=[["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 ib={activity:rd,"arrow-down":od,"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":nd,"arrow-right":ad,"external-link":Ld,ellipsis:Wi,"ellipsis-vertical":Bi,menu:oc,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":nc,"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",o=2)=>{let a=ib[e];return a?lb(a,r,t,o):(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 lb(e,r,t,o){if(!Array.isArray(e))return null;let a=document.createElementNS("http://www.w3.org/2000/svg","svg");return a.setAttribute("width",String(r)),a.setAttribute("height",String(r)),a.setAttribute("viewBox","0 0 24 24"),a.setAttribute("fill","none"),a.setAttribute("stroke",t),a.setAttribute("stroke-width",String(o)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),a.setAttribute("aria-hidden","true"),e.forEach(n=>{if(!Array.isArray(n)||n.length<2)return;let s=n[0],i=n[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))}),a.appendChild(d)}),a}var Ui={allowedTypes:nn,maxFileSize:10*1024*1024,maxFiles:4};function db(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cb(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,o,a;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ui.allowedTypes,maxFileSize:(o=r.maxFileSize)!=null?o:Ui.maxFileSize,maxFiles:(a=r.maxFiles)!=null?a: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,o,a,n,s,i,d;if(r.length){for(let l of r){if(this.attachments.length>=this.config.maxFiles){(o=(t=this.config).onFileRejected)==null||o.call(t,l,"count");continue}let u=Ng(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(a=u.error)!=null&&a.includes("type")?"type":"size";(s=(n=this.config).onFileRejected)==null||s.call(n,l,p);continue}try{let p=await Fg(l),m=Mi(l)?URL.createObjectURL(l):null,f={id:db(),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 n,s,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let o=this.attachments[t];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(t,1);let a=(n=this.previewsContainer)==null?void 0:n.querySelector(`[data-attachment-id="${r}"]`);a&&a.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var r,t;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.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),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",r.id),o.style.width="48px",o.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",o.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=cb(r.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=x("span");l.textContent=_g(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),o.appendChild(s)}let a=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");a.type="button",a.setAttribute("aria-label","Remove attachment"),a.style.position="absolute",a.style.top="-4px",a.style.right="-4px",a.style.width="18px",a.style.height="18px",a.style.borderRadius="50%",a.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",a.style.border="none",a.style.cursor="pointer",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center",a.style.padding="0";let n=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);n?a.appendChild(n):(a.textContent="\xD7",a.style.color="var(--persona-text-inverse, #ffffff)",a.style.fontSize="14px",a.style.lineHeight="1"),a.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(r.id)}),o.appendChild(a),this.previewsContainer.appendChild(o)}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 $g=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[o,a]of Object.entries(r)){let n=t[o];$g(n)&&$g(a)?t[o]=ys(n,a):t[o]=a}return t}var mo="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:mo,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 Ug(e,r){if(!(!e&&!r))return e?r?ys(e,r):e:r}function zi(e){var r,t,o,a,n,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h;return e?{...jt,...e,theme:Ug(jt.theme,e.theme),darkTheme:Ug(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:{...(o=jt.launcher)==null?void 0:o.clearChat,...(a=e.launcher)==null?void 0:a.clearChat}},copy:{...jt.copy,...e.copy},sendButton:{...jt.sendButton,...e.sendButton},statusIndicator:{...jt.statusIndicator,...e.statusIndicator},voiceRecognition:{...jt.voiceRecognition,...e.voiceRecognition},features:(()=>{var me,Pe,Ve,Q,Ae,J,de,pe;let S=(me=jt.features)==null?void 0:me.artifacts,L=(Pe=e.features)==null?void 0:Pe.artifacts,O=(Ve=jt.features)==null?void 0:Ve.scrollToBottom,H=(Q=e.features)==null?void 0:Q.scrollToBottom,R=(Ae=jt.features)==null?void 0:Ae.streamAnimation,B=(J=e.features)==null?void 0:J.streamAnimation,V=(de=jt.features)==null?void 0:de.askUserQuestion,oe=(pe=e.features)==null?void 0:pe.askUserQuestion,fe=S===void 0&&L===void 0?void 0:{...S,...L,layout:{...S==null?void 0:S.layout,...L==null?void 0:L.layout}},_e=O===void 0&&H===void 0?void 0:{...O,...H},je=R===void 0&&B===void 0?void 0:{...R,...B},ye=V===void 0&&oe===void 0?void 0:{...V,...oe,styles:{...V==null?void 0:V.styles,...oe==null?void 0:oe.styles}};return{...jt.features,...e.features,..._e!==void 0?{scrollToBottom:_e}:{},...fe!==void 0?{artifacts:fe}:{},...je!==void 0?{streamAnimation:je}:{},...ye!==void 0?{askUserQuestion:ye}:{}}})(),suggestionChips:(n=e.suggestionChips)!=null?n: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:mo,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("."),o=e;for(let a of t){if(o==null)return;o=o[a]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?va(e,o):o}function Vi(e){let r={};function t(o,a){for(let[n,s]of Object.entries(o)){let i=`${a}.${n}`;if(typeof s=="string"){let d=va(e,s);d!==void 0&&(r[i]={path:i,value:d,type:a.includes("color")?"color":a.includes("spacing")?"spacing":a.includes("typography")?"typography":a.includes("shadow")?"shadow":a.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 qg(e,r){let t={...e};for(let[o,a]of Object.entries(r)){let n=t[o];n&&typeof n=="object"&&!Array.isArray(n)&&a&&typeof a=="object"&&!Array.isArray(a)?t[o]=qg(n,a):t[o]=a}return t}function pb(e,r){return r?qg(e,r):e}function Aa(e,r={}){var a,n,s,i,d,l,u,p,m,f,w,v,k;let t={palette:Yc,semantic:Qc,components:Zc},o={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(a=e==null?void 0:e.palette)==null?void 0:a.colors},spacing:{...t.palette.spacing,...(n=e==null?void 0:e.palette)==null?void 0:n.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:pb(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let T=ep(o);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)o=T.transform(o);return o}function ji(e){var v,k,T,A,E,b,h,S,L,O,H,R,B,V,oe,fe,_e,je,ye,me,Pe,Ve,Q,Ae,J,de,pe,se,Be,Ee,K,Oe,Fe,Y,G,we,ue,re,he,Je,Ot,ce,$e,fr,Wt,Yt,Fr,Ar,F,ie,We,Xe,Ne,Ue,tt,yt,Mt,_t,N,le,Te,ct,Ke,$t,nr,Lt,vt,Ze,at,tr,go,Rr,To,At,ho,ur,Sr,Yr,gt,ko,oo,Tr,kr,Vo,Eo,xo,bt,Me,M,Z,ne,St,Ut,Rt,ar,xr,Nr,Er,rt,wr,_r,pn,jo,un,Fo,no,Mo,Ct,sr,ir,ao,fn,yo,Lo,so,q;let r=Vi(e),t={};for(let[xe,io]of Object.entries(r)){let Po=xe.replace(/\./g,"-");t[`--persona-${Po}`]=io.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"]=(V=t["--persona-components-voice-processing-icon"])!=null?V: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"]=(fe=t["--persona-components-approval-requested-background"])!=null?fe:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(_e=t["--persona-components-approval-requested-border"])!=null?_e:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(je=t["--persona-components-approval-requested-text"])!=null?je:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ye=t["--persona-components-approval-approve-background"])!=null?ye:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(me=t["--persona-components-approval-deny-background"])!=null?me:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Pe=t["--persona-components-attachment-image-background"])!=null?Pe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Ve=t["--persona-components-attachment-image-border"])!=null?Ve: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"]=(Ae=t["--persona-semantic-typography-fontSize"])!=null?Ae: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"]=(de=t["--persona-semantic-typography-lineHeight"])!=null?de: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"]=(se=t["--persona-palette-radius-md"])!=null?se:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(Ee=t["--persona-palette-radius-xl"])!=null?Ee:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=(Fe=(Oe=t["--persona-components-launcher-borderRadius"])!=null?Oe:t["--persona-palette-radius-full"])!=null?Fe:"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"]=(ue=t["--persona-components-button-primary-background"])!=null?ue:t["--persona-primary"],t["--persona-button-primary-fg"]=(re=t["--persona-components-button-primary-foreground"])!=null?re:t["--persona-text-inverse"],t["--persona-button-radius"]=(Je=(he=t["--persona-components-button-primary-borderRadius"])!=null?he:t["--persona-palette-radius-full"])!=null?Je:"9999px",t["--persona-panel-radius"]=(ce=(Ot=t["--persona-components-panel-borderRadius"])!=null?Ot:t["--persona-radius-xl"])!=null?ce:"0.75rem",t["--persona-panel-border"]=($e=t["--persona-components-panel-border"])!=null?$e:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Wt=(fr=t["--persona-components-panel-shadow"])!=null?fr:t["--persona-palette-shadows-xl"])!=null?Wt:"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"]=(We=(ie=t["--persona-components-message-assistant-borderRadius"])!=null?ie:t["--persona-radius-lg"])!=null?We:"0.5rem",t["--persona-header-bg"]=(Xe=t["--persona-components-header-background"])!=null?Xe:t["--persona-surface"],t["--persona-header-border"]=(Ne=t["--persona-components-header-border"])!=null?Ne:t["--persona-divider"],t["--persona-header-icon-bg"]=(Ue=t["--persona-components-header-iconBackground"])!=null?Ue:t["--persona-primary"],t["--persona-header-icon-fg"]=(tt=t["--persona-components-header-iconForeground"])!=null?tt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(yt=t["--persona-components-header-titleForeground"])!=null?yt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Mt=t["--persona-components-header-subtitleForeground"])!=null?Mt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(_t=t["--persona-components-header-actionIconForeground"])!=null?_t:t["--persona-muted"];let o=(N=e.components)==null?void 0:N.header;o!=null&&o.shadow&&(t["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(t["--persona-header-border-bottom"]=o.borderBottom);let a=(le=e.components)==null?void 0:le.introCard;t["--persona-intro-card-bg"]=(Te=t["--persona-components-introCard-background"])!=null?Te:t["--persona-surface"],t["--persona-intro-card-radius"]=(ct=t["--persona-components-introCard-borderRadius"])!=null?ct:"1rem",t["--persona-intro-card-padding"]=(Ke=t["--persona-components-introCard-padding"])!=null?Ke:"1.5rem",t["--persona-intro-card-shadow"]=(nr=($t=a==null?void 0:a.shadow)!=null?$t:t["--persona-components-introCard-shadow"])!=null?nr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Lt=t["--persona-components-input-background"])!=null?Lt:t["--persona-surface"],t["--persona-input-placeholder"]=(vt=t["--persona-components-input-placeholder"])!=null?vt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Ze=t["--persona-components-message-user-background"])!=null?Ze:t["--persona-accent"],t["--persona-message-user-text"]=(at=t["--persona-components-message-user-text"])!=null?at: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"]=(go=t["--persona-components-message-assistant-background"])!=null?go: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"]=(To=t["--persona-components-message-assistant-border"])!=null?To:t["--persona-border"],t["--persona-message-assistant-shadow"]=(At=t["--persona-components-message-assistant-shadow"])!=null?At:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(ho=t["--persona-components-scrollToBottom-background"])!=null?ho: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"]=(gt=t["--persona-components-scrollToBottom-border"])!=null?gt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(ko=t["--persona-components-scrollToBottom-size"])!=null?ko:"40px",t["--persona-scroll-to-bottom-radius"]=(kr=(Tr=(oo=t["--persona-components-scrollToBottom-borderRadius"])!=null?oo:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?kr:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Eo=(Vo=t["--persona-components-scrollToBottom-shadow"])!=null?Vo:t["--persona-palette-shadows-sm"])!=null?Eo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(xo=t["--persona-components-scrollToBottom-padding"])!=null?xo:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(bt=t["--persona-components-scrollToBottom-gap"])!=null?bt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(M=(Me=t["--persona-components-scrollToBottom-fontSize"])!=null?Me: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"]=(ne=t["--persona-components-toolBubble-shadow"])!=null?ne:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(St=t["--persona-components-reasoningBubble-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Ut=t["--persona-components-composer-shadow"])!=null?Ut:"none",t["--persona-md-inline-code-bg"]=(Rt=t["--persona-components-markdown-inlineCode-background"])!=null?Rt: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 n=t["--persona-components-markdown-heading-h1-fontSize"];n&&(t["--persona-md-h1-size"]=n);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"]=(rt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?rt: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"]=(pn=t["--persona-components-markdown-table-borderColor"])!=null?pn:t["--persona-border"],t["--persona-md-hr-color"]=(jo=t["--persona-components-markdown-hr-color"])!=null?jo:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(un=t["--persona-components-markdown-blockquote-borderColor"])!=null?un:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Fo=t["--persona-components-markdown-blockquote-background"])!=null?Fo:"transparent",t["--persona-md-blockquote-text-color"]=(no=t["--persona-components-markdown-blockquote-textColor"])!=null?no:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Mo=t["--persona-components-collapsibleWidget-container"])!=null?Mo:t["--persona-surface"],t["--cw-surface"]=(Ct=t["--persona-components-collapsibleWidget-surface"])!=null?Ct: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 xe=w.toolbar;xe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,t["--persona-dropdown-bg"]=(ao=t["--persona-dropdown-bg"])!=null?ao:xe.copyMenuBackground),xe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,t["--persona-dropdown-border"]=(fn=t["--persona-dropdown-border"])!=null?fn:xe.copyMenuBorder),xe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,t["--persona-dropdown-shadow"]=(yo=t["--persona-dropdown-shadow"])!=null?yo:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Lo=t["--persona-dropdown-radius"])!=null?Lo:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(so=t["--persona-dropdown-item-hover-bg"])!=null?so:xe.copyMenuItemHoverBackground),xe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(w!=null&&w.tab){let xe=w.tab;xe.background&&(t["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(t["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(t["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(t["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(t["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(t["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(w!=null&&w.pane){let xe=w.pane;if(xe.toolbarBackground){let io=(q=va(e,xe.toolbarBackground))!=null?q:xe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=io}}return t}var zg={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 ub={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"}}},Vg=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"},fb=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=>fb(e),mb=e=>Aa(e),gb=e=>{var t;let r=Aa(void 0,{validate:!1});return Aa({...e,palette:{...r.palette,colors:{...ub.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Sa=e=>{let r=tp(e),t=Vg(e==null?void 0:e.theme),o=Vg(e==null?void 0:e.darkTheme);return r==="dark"?gb(ys(t!=null?t:{},o!=null?o:{})):mb(t)},hb=e=>ji(e),vn=(e,r)=>{var n;let t=Sa(r),o=hb(t);for(let[s,i]of Object.entries(o))e.style.setProperty(s,i);let a=(n=r==null?void 0:r.toolCall)==null?void 0:n.shadow;a!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",a.trim()===""?"none":a)},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)"),o=()=>e(bs());t.addEventListener?(t.addEventListener("change",o),r.push(()=>t.removeEventListener("change",o))):t.addListener&&(t.addListener(o),r.push(()=>t.removeListener(o)))}return()=>{r.forEach(t=>t())}};var jg=(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=a(k,()=>i(k,m,v,A=>A.morphStyle==="innerHTML"?(n(A,m,v),Array.from(m.childNodes)):o(A,m,v)));return k.pantry.remove(),T}function o(m,f,w){let v=p(f);return n(m,v,w,f,f.nextSibling),Array.from(v.childNodes)}function a(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 n=(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 V=T(h,B,L,b);s(V,H,b),L=V.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,V=O.nextSibling,oe=0,fe=H;for(;fe&&fe!=R;){if(S(fe,O)){if(h(L,fe,O))return fe;B===null&&(L.idMap.has(fe)||(B=fe))}if(B===null&&V&&S(fe,V)&&(oe++,V=V.nextSibling,oe>=2&&(B=void 0)),L.activeElementAndParents.includes(fe))break;fe=fe.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 V of R)if(B.has(V))return!0;return!1}function S(L,O){var B,V,oe;let H=L,R=O;return H.nodeType===R.nodeType&&H.tagName===R.tagName&&(!((B=H.getAttribute)!=null&&B.call(H,"id"))||((V=H.getAttribute)==null?void 0:V.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)||n(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:o=!0}=t;jg.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(a,n){var s,i;if(a instanceof HTMLElement&&o){if(a.classList.contains("persona-animate-typing")||a.hasAttribute("data-preserve-runtime"))return!1;if(a.hasAttribute("data-preserve-animation")){if(n instanceof HTMLElement&&!n.hasAttribute("data-preserve-animation"))return;if(n instanceof HTMLElement&&n.hasAttribute("data-preserve-animation")){let d=(s=a.textContent)!=null?s:"",l=(i=n.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function Gg(e,r){var t,o,a,n,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h,S,L,O,H,R,B,V,oe,fe,_e;return[e.id,e.role,(o=(t=e.content)==null?void 0:t.length)!=null?o:0,(n=(a=e.content)==null?void 0:a.slice(-32))!=null?n:"",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,(V=(B=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:B.length)!=null?V:0,(fe=(oe=e.contentParts)==null?void 0:oe.length)!=null?fe:0,(_e=e.stopReason)!=null?_e:"",r].join("\0")}function Xg(){return new Map}function Jg(e,r,t){let o=e.get(r);return o&&o.fingerprint===t?o.wrapper:null}function Kg(e,r,t,o){e.set(r,{fingerprint:t,wrapper:o})}function Yg(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:o,nearBottom:a,userScrollThreshold:n,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-o;return s||Math.abs(u)<n?{action:"none",delta:u,nextLastScrollTop:t}:!r&&a&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:r&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:r&&d&&!a?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Yi(e){let{following:r,deltaY:t,nearBottom:o=!1,resumeWhenNearBottom:a=!1}=e;return r&&t<0?"pause":!r&&a&&t>0&&o?"resume":"none"}var Dr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Or=1e5,An=Or+1;var vs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},xb=["pre","code","a","script","style"],Qi=e=>{var r,t,o,a,n;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:(o=e==null?void 0:e.speed)!=null?o:vs.speed,duration:(a=e==null?void 0:e.duration)!=null?a:vs.duration,buffer:(n=e==null?void 0:e.buffer)!=null?n:vs.buffer}},Zg=[{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 Zg)As.set(e.name,e);var ra=e=>{As.set(e.name,e)},np=e=>{Zg.some(r=>r.name===e)||As.delete(e)},ap=()=>Array.from(As.keys()),Ss=(e,r)=>{var t,o;return e==="none"?null:r&&Object.prototype.hasOwnProperty.call(r,e)?(t=r[e])!=null?t:null:(o=As.get(e))!=null?o:null},Zi=(e,r,t,o,a)=>{if(!a)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,o);if(!e)return e;if(r==="word"){let n=e.search(/\s(?=\S*$)/);return n<0?"":e.slice(0,n)}if(r==="line"){let n=e.lastIndexOf(`
|
|
55
|
-
`);return
|
|
54
|
+
`),Ue="message",tt="";for(let $t of Ne)$t.startsWith("event:")?Ue=$t.replace("event:","").trim():$t.startsWith("data:")&&(tt+=$t.replace("data:","").trim());if(!tt)continue;let yt;try{yt=JSON.parse(tt)}catch($t){t({type:"error",error:$t instanceof Error?$t:new Error("Failed to parse chat stream payload")});continue}let Mt=Ue!=="message"?Ue:(Fr=yt.type)!=null?Fr:"message";if((Ar=this.onSSEEvent)==null||Ar.call(this,Mt,yt),this.parseSSEEvent){f.current=m;let $t=await this.handleCustomSSEEvent(yt,t,f,p,l,w);if(f.current&&f.current!==m&&(m=f.current),$t)continue}Ot.push(Mt,yt),he()}}Ot.flushPending(),he(),Ot.destroy()}};function Lg(){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 Pg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ig(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Rg(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Hg(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function gs(e){return{type:"text",text:e}}function Bg(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 Wg(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let a=n.result;r({type:"image",image:a,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Dg(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 Og=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ab=["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=[...Og,...ab];function sb(e){return Og.includes(e)||e.startsWith("image/")}function Mi(e){return sb(e.type)}async function Fg(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let a=n.result;Mi(e)?r({type:"image",image:a,mimeType:e.type,alt:e.name}):r({type:"file",data:a,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Ng(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 ib(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function _g(e,r){let t=ib(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(),a=this.pcmToFloat32(t),o=n.createBuffer(1,a.length,this.sampleRate);o.getChannelData(0).set(a);let s=n.createBufferSource();s.buffer=o,s.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=o.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),a=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let s=a.getInt16(o*2,!0);n[o]=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,a,o){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<a.threshold:d>=a.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=a.duration&&(this.fired=!0,o()):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 a=this.w;if(!a||!a.location)throw new Error("Window object or location not available");let o=a.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=`${o}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${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(a){throw this.ws=null,this.errorCallbacks.forEach(o=>o(a)),this.statusCallbacks.forEach(o=>o("error")),a}}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(a=>a({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(a=>a("speaking")),this.playAudio(r.response.audio).catch(a=>this.errorCallbacks.forEach(o=>o(a instanceof Error?a:new Error(String(a)))))):(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(a=>a("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(a=>a(new Error(r.error))),this.statusCallbacks.forEach(a=>a("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,a;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 o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let s=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(a=(n=this.config)==null?void 0:n.silenceThreshold)!=null?a:.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(o){throw this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}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 o,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=(o=this.config)==null?void 0:o.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),a=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:a,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(a=>a(n)),this.statusCallbacks.forEach(a=>a("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let a=new FileReader;a.onload=()=>{let s=a.result.split(",")[1];t(s)},a.onerror=n,a.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 a=r.format||"mp3",o=a==="mp3"?"audio/mpeg":`audio/${a}`,s=new Blob([n],{type:o}),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=a=>{var i;let o=Array.from(a.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=a.results[a.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=a=>{this.errorCallbacks.forEach(o=>o(new Error(a.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(a=>a("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(a=>a("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(a=>a(n)),this.statusCallbacks.forEach(a=>a("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,a,o,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:(a=r.message.agentMetadata.iteration)!=null?a: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,((o=this.agentExecution)==null?void 0:o.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,a;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yo(r);for(let o of(a=r.initialArtifacts)!=null?a:[])this.artifacts.set(o.id,{...o,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,a;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ea(o);let s=(t=this.config.voiceRecognition)!=null?t:{},i=(n=s.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(a=s.processingErrorText)!=null?a:"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(o){console.error("Failed to setup voice:",o)}}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,a,o,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:((a=r.runtype)==null?void 0:a.clientToken)||"",host:(o=r.runtype)==null?void 0:o.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:a,contentParts:o,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,...a!==void 0&&{llmContent:a},...o!==void 0&&{contentParts:o},...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:a,content:o,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:m,rawContent:f}=n,v={id:d!=null?d:a==="user"?Ca():a==="assistant"?Qo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:a,content:o,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:a="",llmContent:o,id:s,createdAt:i,sequence:d}=r,l={text:a,component:t,props:n};return this.injectMessage({role:"assistant",content:a,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...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 a=Ca(),o=Qo(),s={id:a,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:o},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:o,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 a,o,s,i,d;if(this.streaming)return;(a=this.abortController)==null||a.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=(o=this.callbacks).onError)==null||s.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(r,t){var a,o,s;if(this.streaming)return;(a=this.abortController)==null||a.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=(o=this.callbacks).onError)==null||s.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,l,u;let n=`approval-${r.id}`,a={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:a};this.upsertMessage(o);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(a=>a.id===r.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(r,t){let n=this.messages.find(a=>a.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 a=(p=r.agentMetadata)==null?void 0:p.executionId,o=(m=r.toolCall)==null?void 0:m.name;if(!a||!o){(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(a,{[o]: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 a;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(a=r.props)!=null?a:{}};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 a=this.artifacts.get(r.id);(a==null?void 0:a.artifactType)==="markdown"&&(a.markdown=((n=a.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let a=this.artifacts.get(r.id);(a==null?void 0:a.artifactType)==="component"&&(a.props={...a.props,...r.props},r.component&&(a.component=r.component));break}case"artifact_complete":{let a=this.artifacts.get(r.id);a&&(a.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 a;return{...n,streaming:!1,sequence:(a=n.sequence)!=null?a: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(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let a=n.content;a.trim()&&this.speak(a,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let a=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let s=o.find(i=>i.name===t.voice);s&&(a.voice=s)}else o.length>0&&(a.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(a.rate=t.rate),t.pitch!==void 0&&(a.pitch=t.pitch),setTimeout(()=>n.speak(a),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 a of t){let o=r.find(s=>s.name===a);if(o)return o}return(n=r.find(a=>a.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(a=>a.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((a,o)=>{var i;if(o!==n)return a;let s={...a,...t};return((i=a.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...a.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:a.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 a=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(o)&&a!==o)return a-o;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 lb={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 a=lb[e];return a?db(a,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 db(e,r,t,n){if(!Array.isArray(e))return null;let a=document.createElementNS("http://www.w3.org/2000/svg","svg");return a.setAttribute("width",String(r)),a.setAttribute("height",String(r)),a.setAttribute("viewBox","0 0 24 24"),a.setAttribute("fill","none"),a.setAttribute("stroke",t),a.setAttribute("stroke-width",String(n)),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),a.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let s=o[0],i=o[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))}),a.appendChild(d)}),a}var Ui={allowedTypes:oo,maxFileSize:10*1024*1024,maxFiles:4};function cb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function pb(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,a;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ui.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Ui.maxFileSize,maxFiles:(a=r.maxFiles)!=null?a: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,a,o,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=Ng(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(a=u.error)!=null&&a.includes("type")?"type":"size";(s=(o=this.config).onFileRejected)==null||s.call(o,l,p);continue}try{let p=await Fg(l),m=Mi(l)?URL.createObjectURL(l):null,f={id:cb(),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 o,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 a=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);a&&a.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=pb(r.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=x("span");l.textContent=_g(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 a=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");a.type="button",a.setAttribute("aria-label","Remove attachment"),a.style.position="absolute",a.style.top="-4px",a.style.right="-4px",a.style.width="18px",a.style.height="18px",a.style.borderRadius="50%",a.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",a.style.border="none",a.style.cursor="pointer",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center",a.style.padding="0";let o=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);o?a.appendChild(o):(a.textContent="\xD7",a.style.color="var(--persona-text-inverse, #ffffff)",a.style.fontSize="14px",a.style.lineHeight="1"),a.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(a),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 $g=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,a]of Object.entries(r)){let o=t[n];$g(o)&&$g(a)?t[n]=ys(o,a):t[n]=a}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 Ug(e,r){if(!(!e&&!r))return e?r?ys(e,r):e:r}function zi(e){var r,t,n,a,o,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h;return e?{...jt,...e,theme:Ug(jt.theme,e.theme),darkTheme:Ug(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,...(a=e.launcher)==null?void 0:a.clearChat}},copy:{...jt.copy,...e.copy},sendButton:{...jt.sendButton,...e.sendButton},statusIndicator:{...jt.statusIndicator,...e.statusIndicator},voiceRecognition:{...jt.voiceRecognition,...e.voiceRecognition},features:(()=>{var me,Pe,Ve,Q,Ae,J,de,pe;let S=(me=jt.features)==null?void 0:me.artifacts,L=(Pe=e.features)==null?void 0:Pe.artifacts,O=(Ve=jt.features)==null?void 0:Ve.scrollToBottom,H=(Q=e.features)==null?void 0:Q.scrollToBottom,R=(Ae=jt.features)==null?void 0:Ae.streamAnimation,B=(J=e.features)==null?void 0:J.streamAnimation,V=(de=jt.features)==null?void 0:de.askUserQuestion,ne=(pe=e.features)==null?void 0:pe.askUserQuestion,fe=S===void 0&&L===void 0?void 0:{...S,...L,layout:{...S==null?void 0:S.layout,...L==null?void 0:L.layout}},_e=O===void 0&&H===void 0?void 0:{...O,...H},je=R===void 0&&B===void 0?void 0:{...R,...B},ye=V===void 0&&ne===void 0?void 0:{...V,...ne,styles:{...V==null?void 0:V.styles,...ne==null?void 0:ne.styles}};return{...jt.features,...e.features,..._e!==void 0?{scrollToBottom:_e}:{},...fe!==void 0?{artifacts:fe}:{},...je!==void 0?{streamAnimation:je}:{},...ye!==void 0?{askUserQuestion:ye}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o: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 a of t){if(n==null)return;n=n[a]}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,a){for(let[o,s]of Object.entries(n)){let i=`${a}.${o}`;if(typeof s=="string"){let d=va(e,s);d!==void 0&&(r[i]={path:i,value:d,type:a.includes("color")?"color":a.includes("spacing")?"spacing":a.includes("typography")?"typography":a.includes("shadow")?"shadow":a.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 qg(e,r){let t={...e};for(let[n,a]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&a&&typeof a=="object"&&!Array.isArray(a)?t[n]=qg(o,a):t[n]=a}return t}function ub(e,r){return r?qg(e,r):e}function Aa(e,r={}){var a,o,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,...(a=e==null?void 0:e.palette)==null?void 0:a.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.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:ub(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,V,ne,fe,_e,je,ye,me,Pe,Ve,Q,Ae,J,de,pe,se,Be,Ee,K,Oe,Fe,Y,G,we,ue,re,he,Je,Ot,ce,$e,fr,Wt,Yt,Fr,Ar,F,ie,We,Xe,Ne,Ue,tt,yt,Mt,$t,N,le,Te,ct,Ke,Ut,or,Lt,vt,Ze,at,tr,gn,Rr,Tn,At,hn,ur,Sr,Yr,gt,kn,nn,Tr,kr,Vn,En,xn,bt,Me,M,Z,oe,St,qt,Rt,ar,xr,Nr,Er,rt,wr,_r,po,jn,uo,Fn,on,Mn,Ct,sr,ir,an,fo,yn,Ln,sn,q;let r=Vi(e),t={};for(let[xe,ln]of Object.entries(r)){let Pn=xe.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"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(fe=t["--persona-components-approval-requested-background"])!=null?fe:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(_e=t["--persona-components-approval-requested-border"])!=null?_e:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(je=t["--persona-components-approval-requested-text"])!=null?je:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ye=t["--persona-components-approval-approve-background"])!=null?ye:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(me=t["--persona-components-approval-deny-background"])!=null?me:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Pe=t["--persona-components-attachment-image-background"])!=null?Pe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Ve=t["--persona-components-attachment-image-border"])!=null?Ve: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"]=(Ae=t["--persona-semantic-typography-fontSize"])!=null?Ae: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"]=(de=t["--persona-semantic-typography-lineHeight"])!=null?de: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"]=(se=t["--persona-palette-radius-md"])!=null?se:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(Ee=t["--persona-palette-radius-xl"])!=null?Ee:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=(Fe=(Oe=t["--persona-components-launcher-borderRadius"])!=null?Oe:t["--persona-palette-radius-full"])!=null?Fe:"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"]=(ue=t["--persona-components-button-primary-background"])!=null?ue:t["--persona-primary"],t["--persona-button-primary-fg"]=(re=t["--persona-components-button-primary-foreground"])!=null?re:t["--persona-text-inverse"],t["--persona-button-radius"]=(Je=(he=t["--persona-components-button-primary-borderRadius"])!=null?he:t["--persona-palette-radius-full"])!=null?Je:"9999px",t["--persona-panel-radius"]=(ce=(Ot=t["--persona-components-panel-borderRadius"])!=null?Ot:t["--persona-radius-xl"])!=null?ce:"0.75rem",t["--persona-panel-border"]=($e=t["--persona-components-panel-border"])!=null?$e:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Wt=(fr=t["--persona-components-panel-shadow"])!=null?fr:t["--persona-palette-shadows-xl"])!=null?Wt:"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"]=(We=(ie=t["--persona-components-message-assistant-borderRadius"])!=null?ie:t["--persona-radius-lg"])!=null?We:"0.5rem",t["--persona-header-bg"]=(Xe=t["--persona-components-header-background"])!=null?Xe:t["--persona-surface"],t["--persona-header-border"]=(Ne=t["--persona-components-header-border"])!=null?Ne:t["--persona-divider"],t["--persona-header-icon-bg"]=(Ue=t["--persona-components-header-iconBackground"])!=null?Ue:t["--persona-primary"],t["--persona-header-icon-fg"]=(tt=t["--persona-components-header-iconForeground"])!=null?tt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(yt=t["--persona-components-header-titleForeground"])!=null?yt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Mt=t["--persona-components-header-subtitleForeground"])!=null?Mt: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 a=(le=e.components)==null?void 0:le.introCard;t["--persona-intro-card-bg"]=(Te=t["--persona-components-introCard-background"])!=null?Te:t["--persona-surface"],t["--persona-intro-card-radius"]=(ct=t["--persona-components-introCard-borderRadius"])!=null?ct:"1rem",t["--persona-intro-card-padding"]=(Ke=t["--persona-components-introCard-padding"])!=null?Ke:"1.5rem",t["--persona-intro-card-shadow"]=(or=(Ut=a==null?void 0:a.shadow)!=null?Ut:t["--persona-components-introCard-shadow"])!=null?or:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Lt=t["--persona-components-input-background"])!=null?Lt:t["--persona-surface"],t["--persona-input-placeholder"]=(vt=t["--persona-components-input-placeholder"])!=null?vt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Ze=t["--persona-components-message-user-background"])!=null?Ze:t["--persona-accent"],t["--persona-message-user-text"]=(at=t["--persona-components-message-user-text"])!=null?at: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"]=(At=t["--persona-components-message-assistant-shadow"])!=null?At:"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"]=(gt=t["--persona-components-scrollToBottom-border"])!=null?gt: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"]=(bt=t["--persona-components-scrollToBottom-gap"])!=null?bt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(M=(Me=t["--persona-components-scrollToBottom-fontSize"])!=null?Me: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"]=(oe=t["--persona-components-toolBubble-shadow"])!=null?oe:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(St=t["--persona-components-reasoningBubble-shadow"])!=null?St:"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"]=(Rt=t["--persona-components-markdown-inlineCode-background"])!=null?Rt: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 o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);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"]=(rt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?rt: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"]=(Ct=t["--persona-components-collapsibleWidget-surface"])!=null?Ct: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 xe=w.toolbar;xe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,t["--persona-dropdown-bg"]=(an=t["--persona-dropdown-bg"])!=null?an:xe.copyMenuBackground),xe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,t["--persona-dropdown-border"]=(fo=t["--persona-dropdown-border"])!=null?fo:xe.copyMenuBorder),xe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,t["--persona-dropdown-shadow"]=(yn=t["--persona-dropdown-shadow"])!=null?yn:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Ln=t["--persona-dropdown-radius"])!=null?Ln:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(sn=t["--persona-dropdown-item-hover-bg"])!=null?sn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(w!=null&&w.tab){let xe=w.tab;xe.background&&(t["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(t["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(t["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(t["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(t["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(t["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(w!=null&&w.pane){let xe=w.pane;if(xe.toolbarBackground){let ln=(q=va(e,xe.toolbarBackground))!=null?q:xe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=ln}}return t}var zg={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 fb={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"}}},Vg=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"},mb=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=>mb(e),gb=e=>Aa(e),hb=e=>{var t;let r=Aa(void 0,{validate:!1});return Aa({...e,palette:{...r.palette,colors:{...fb.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Sa=e=>{let r=tp(e),t=Vg(e==null?void 0:e.theme),n=Vg(e==null?void 0:e.darkTheme);return r==="dark"?hb(ys(t!=null?t:{},n!=null?n:{})):gb(t)},xb=e=>ji(e),vo=(e,r)=>{var o;let t=Sa(r),n=xb(t);for(let[s,i]of Object.entries(n))e.style.setProperty(s,i);let a=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;a!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",a.trim()===""?"none":a)},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 jg=(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=a(k,()=>i(k,m,v,A=>A.morphStyle==="innerHTML"?(o(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 o(m,v,w,f,f.nextSibling),Array.from(v.childNodes)}function a(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 o=(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 V=T(h,B,L,b);s(V,H,b),L=V.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,V=O.nextSibling,ne=0,fe=H;for(;fe&&fe!=R;){if(S(fe,O)){if(h(L,fe,O))return fe;B===null&&(L.idMap.has(fe)||(B=fe))}if(B===null&&V&&S(fe,V)&&(ne++,V=V.nextSibling,ne>=2&&(B=void 0)),L.activeElementAndParents.includes(fe))break;fe=fe.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 V of R)if(B.has(V))return!0;return!1}function S(L,O){var B,V,ne;let H=L,R=O;return H.nodeType===R.nodeType&&H.tagName===R.tagName&&(!((B=H.getAttribute)!=null&&B.call(H,"id"))||((V=H.getAttribute)==null?void 0:V.call(H,"id"))===((ne=R.getAttribute)==null?void 0:ne.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)||o(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;jg.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(a,o){var s,i;if(a instanceof HTMLElement&&n){if(a.classList.contains("persona-animate-typing")||a.hasAttribute("data-preserve-runtime"))return!1;if(a.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(s=a.textContent)!=null?s:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function Gg(e,r){var t,n,a,o,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h,S,L,O,H,R,B,V,ne,fe,_e;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(a=e.content)==null?void 0:a.slice(-32))!=null?o:"",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,(V=(B=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:B.length)!=null?V:0,(fe=(ne=e.contentParts)==null?void 0:ne.length)!=null?fe:0,(_e=e.stopReason)!=null?_e:"",r].join("\0")}function Xg(){return new Map}function Jg(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Kg(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Yg(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:a,userScrollThreshold:o,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-n;return s||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!r&&a&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:r&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:r&&d&&!a?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Yi(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:a=!1}=e;return r&&t<0?"pause":!r&&a&&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"},yb=["pre","code","a","script","style"],Qi=e=>{var r,t,n,a,o;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:(a=e==null?void 0:e.duration)!=null?a:vs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:vs.buffer}},Zg=[{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 Zg)As.set(e.name,e);var ra=e=>{As.set(e.name,e)},op=e=>{Zg.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,a)=>{if(!a)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,n);if(!e)return e;if(r==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(r==="line"){let o=e.lastIndexOf(`
|
|
55
|
+
`);return o<0?"":e.slice(0,o)}return e},bb=(e,r,t,n)=>{let a=e.createElement("span");return a.className="persona-stream-char",a.id=`stream-c-${t}-${n}`,a.style.setProperty("--char-index",String(n)),a.textContent=r,a},Cb=(e,r,t,n)=>{let a=e.createElement("span");return a.className="persona-stream-word",a.id=`stream-w-${t}-${n}`,a.style.setProperty("--word-index",String(n)),a.textContent=r,a},rp=/\s/,wb=(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},vb=(e,r,t)=>{var d;let n=e.ownerDocument,a=e.parentNode;if(!n||!a)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let s=n.createDocumentFragment(),i=0;for(;i<o.length;)if(rp.test(o[i])){let l=i;for(;l<o.length&&rp.test(o[l]);)l+=1;s.appendChild(n.createTextNode(o.slice(i,l))),i=l}else{let l=n.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!rp.test(o[u]);)l.appendChild(bb(n,o[u],r,t.value)),t.value+=1,u+=1;s.appendChild(l),i=u}a.replaceChild(s,e)},Ab=(e,r,t)=>{var d;let n=e.ownerDocument,a=e.parentNode;if(!n||!a)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let s=n.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(n.createTextNode(l)):(s.appendChild(Cb(n,l,r,t.value)),t.value+=1));a.replaceChild(s,e)},Ts=(e,r,t,n)=>{var p,m;if(!e||typeof document=="undefined")return e;let a=document.createElement("div");a.innerHTML=e;let o=new Set(((p=n==null?void 0:n.skipTags)!=null?p:yb).map(f=>f.toLowerCase())),s=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,null),i=[],d=s.nextNode();for(;d;)wb(d,o)||i.push(d),d=s.nextNode();let l={value:(m=n==null?void 0:n.startIndex)!=null?m:0},u=r==="char"?vb:Ab;for(let f of i)u(f,t,l);return a.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},Qg=new WeakMap,Sb=(e,r)=>{var o;if(!e.styles)return;let t=Qg.get(r);if(t||(t=new Set,Qg.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 a=(r instanceof ShadowRoot?r.ownerDocument:(o=r.ownerDocument)!=null?o:document).createElement("style");a.setAttribute("data-persona-animation",e.name),a.textContent=e.styles,r.appendChild(a)},np=new WeakMap,Tb=(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)},eh=e=>{let r=np.get(e);if(r){for(let t of r.values())typeof t=="function"&&t();r.clear()}},sp=(e,r)=>{Sb(e,r),Tb(e,r)};function ip(e,r=Or){let t=e.style.position,n=e.style.zIndex,a=e.style.isolation,o=getComputedStyle(e),s=o.position==="static"||o.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=a}}var Es=0,So=null;function lp(e=document){var t;if(Es++,Es===1){let n=e.body,o=((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:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}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 a=e.body,o=(n=e.defaultView)!=null?n:window;a.style.overflow=So.originalOverflow,a.style.position=So.originalPosition,a.style.top=So.originalTop,a.style.width=So.originalWidth,o.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,a,o,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:(a=r==null?void 0:r.width)!=null?a:tl.width,animate:(o=r==null?void 0:r.animate)!=null?o: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=x("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 a="<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 o=n=>{var E,b,h,S,L,O,H,R,B,V,oe,fe,_e,je;let s=(E=n.launcher)!=null?E:{},i=hr(n),d=t.querySelector("[data-role='launcher-title']");if(d){let ye=(b=s.title)!=null?b:"Chat Assistant";d.textContent=ye,d.setAttribute("title",ye)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let ye=(h=s.subtitle)!=null?h:"Get answers fast";l.textContent=ye,l.setAttribute("title",ye)}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 ye=(S=s.agentIconSize)!=null?S:"40px";if(p.style.height=ye,p.style.width=ye,p.innerHTML="",s.agentIconName){let me=parseFloat(ye)||24,Pe=Ce(s.agentIconName,me*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(p.appendChild(Pe),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 ye=(H=s.agentIconSize)!=null?H:"40px";m.style.height=ye,m.style.width=ye,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 ye=(R=s.callToActionIconSize)!=null?R:"32px";f.style.height=ye,f.style.width=ye,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 me=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,me=(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 Pe=parseFloat(ye)||24,Ve=Math.max(Pe-me,8),Q=Ce(s.callToActionIconName,Ve,"currentColor",2);Q?f.appendChild(Q):f.textContent=(B=s.callToActionIconText)!=null?B:"\u2197"}else f.textContent=(V=s.callToActionIconText)!=null?V:"\u2197"}let w=s.position&&Oo[s.position]?Oo[s.position]:Oo["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=(fe=s.border)!=null?fe:T,t.style.boxShadow=(_e=s.shadow)!=null?_e: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=(je=s.collapsedMaxWidth)!=null?je:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},a=()=>{t.removeEventListener("click",r),t.remove()};return e&&o(e),{element:t,update:o,destroy:a}};var Tb="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:o=Tb,buttonSize:a,iconSize:n="28px"}=r,s=(v=e==null?void 0:e.launcher)!=null?v:{},i=(k=a!=null?a:s.closeButtonSize)!=null?k:"32px",d=x("div",o),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,n,"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=qo(O,"div","persona-clear-chat-tooltip"),h.textContent=u;let R=qo(O,"div");R.className="persona-clear-chat-tooltip-arrow",h.appendChild(R);let B=l.getBoundingClientRect();h.style.position="fixed",h.style.zIndex=String(An),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}},kb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ol=(e,r={})=>{var h,S,L,O,H,R,B,V,oe,fe,_e,je,ye;let{wrapperClassName:t=kb,buttonSize:o,iconSize:a="20px"}=r,s=(S=((h=e==null?void 0:e.launcher)!=null?h:{}).clearChat)!=null?S:{},i=(L=o!=null?o: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=(V=s.borderColor)!=null?V:"",f=(oe=s.borderRadius)!=null?oe:"",w=(fe=s.paddingX)!=null?fe:"",v=(_e=s.paddingY)!=null?_e:"",k=(je=s.tooltipText)!=null?je:"Clear chat",T=(ye=s.showTooltip)!=null?ye:!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,a,"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 me=p||"0px",Pe=m||"transparent";E.style.border=`${me} solid ${Pe}`,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 me=null,Pe=()=>{if(me)return;let Q=E.ownerDocument,Ae=Q.body;if(!Ae)return;me=qo(Q,"div","persona-clear-chat-tooltip"),me.textContent=k;let J=qo(Q,"div");J.className="persona-clear-chat-tooltip-arrow",me.appendChild(J);let de=E.getBoundingClientRect();me.style.position="fixed",me.style.zIndex=String(An),me.style.left=`${de.left+de.width/2}px`,me.style.top=`${de.top-8}px`,me.style.transform="translate(-50%, -100%)",Ae.appendChild(me)},Ve=()=>{me&&me.parentNode&&(me.parentNode.removeChild(me),me=null)};A.addEventListener("mouseenter",Pe),A.addEventListener("mouseleave",Ve),E.addEventListener("focus",Pe),E.addEventListener("blur",Ve),A._cleanupTooltip=()=>{Ve(),A.removeEventListener("mouseenter",Pe),A.removeEventListener("mouseleave",Ve),E.removeEventListener("focus",Pe),E.removeEventListener("blur",Ve)}}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))"},an=e=>{var h,S,L,O,H,R,B,V,oe,fe,_e,je,ye,me,Pe,Ve;let{config:r,showClose:t=!0}=e,o=x("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let a=(h=r==null?void 0:r.launcher)!=null?h:{},n=(S=a.headerIconSize)!=null?S:"48px",s=(L=a.closeButtonPlacement)!=null?L:"inline",i=(O=a.headerIconHidden)!=null?O:!1,d=a.headerIconName,l=x("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=n,l.style.width=n,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(n)||24,Ae=Ce(d,Q*.6,"currentColor",1);Ae?l.replaceChildren(Ae):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=n,Q.style.width=n,l.replaceChildren(Q)}else l.textContent=(oe=(V=r==null?void 0:r.launcher)==null?void 0:V.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=(_e=(fe=r==null?void 0:r.launcher)==null?void 0:fe.title)!=null?_e:"Chat Assistant";let m=x("span","persona-text-xs");m.style.color=Kr.subtitleColor,m.textContent=(ye=(je=r==null?void 0:r.launcher)==null?void 0:je.subtitle)!=null?ye:"Here to help you get answers fast",u.append(p,m),i?o.append(u):o.append(l,u);let f=(me=a.clearChat)!=null?me:{},w=(Pe=f.enabled)!=null?Pe:!0,v=(Ve=f.placement)!=null?Ve:"inline",k=null,T=null;if(w){let Ae=ol(r,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=Ae.button,T=Ae.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&o.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"&&o.appendChild(b),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:m,closeButton:E,closeButtonWrapper:b,clearChatButton:k,clearChatButtonWrapper:T}},oa=(e,r,t)=>{var s,i,d,l;let o=(s=t==null?void 0:t.launcher)!=null?s:{},a=(i=o.closeButtonPlacement)!=null?i:"inline",n=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(r.header),a==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&n==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function kn(e){let{items:r,onSelect:t,anchor:o,position:a="bottom-left",portal:n}=e,s=x("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),n?(s.style.position="fixed",s.style.zIndex=String(An)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",a==="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(!n)return;let f=o.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,a==="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)&&!o.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 n&&n.appendChild(s),{element:s,show:l,hide:u,toggle:p,destroy:m}}function Qt(e){let{icon:r,label:t,size:o,strokeWidth:a,className:n,onClick:s,aria:i}=e,d=x("button","persona-icon-btn"+(n?" "+n:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Ce(r,o!=null?o:16,"currentColor",a!=null?a: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:o="default",size:a="sm",iconSize:n,className:s,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+a,s&&(l+=" "+s);let u=x("button",l);if(u.type="button",u.setAttribute("aria-label",t),r){let m=Ce(r,n!=null?n: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:o,className:a}=e,n=x("div","persona-toggle-group"+(a?" "+a:""));n.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(),o(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(),o(u.id)})),p.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:p}),n.appendChild(p)}function l(u){s=u,d()}return{element:n,setSelected:l}}function nl(e){var f,w;let{label:r,icon:t="chevron-down",menuItems:o,onSelect:a,position:n="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=kn({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),a(v)},anchor:l,position:n,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 o;let r=an({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(t){let a=r.headerTitle.parentElement;a&&(a.style.cursor="pointer",a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.addEventListener("click",()=>t()),a.addEventListener("keydown",n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),t())}))}return r};function Eb(e,r,t){var o,a,n;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",(a=(o=s.ariaLabel)!=null?o:s.label)!=null?a:s.id),s.icon){let d=Ce(s.icon,14,"currentColor",2);d&&i.appendChild(d)}else s.label&&(i.textContent=s.label);if((n=s.menuItems)!=null&&n.length){let d=x("div","persona-relative");d.appendChild(i);let l=kn({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:o,layoutHeaderConfig:a,onHeaderAction:n}=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=a==null?void 0:a.titleMenu,l,u;if(d)l=nl({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),Eb(l,a==null?void 0:a.trailingActions,(S=a==null?void 0:a.onAction)!=null?S:n),a!=null&&a.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=a.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||V()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let B=a==null?void 0:a.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 V,oe;l.style.backgroundColor=(V=B.background)!=null?V:"",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",o&&f.addEventListener("click",o),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 o=(s=r==null?void 0:r.layout)!=null?s:"default",n=pp(o)({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&&(n.iconHolder.style.display="none"),r.showTitle===!1&&(n.headerTitle.style.display="none"),r.showSubtitle===!1&&(n.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(n.closeButton.style.display="none"),r.showClearChat===!1&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n};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,o=20;r.style.maxHeight=`${t*o}px`,r.style.overflowY="auto";let a=()=>{let d=parseFloat(r.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*o},n=()=>{r.addEventListener("input",()=>{r.style.height="auto";let d=Math.min(r.scrollHeight,a());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:n}},il=e=>{var h,S,L,O,H,R,B,V,oe,fe,_e,je;let r=(h=e==null?void 0:e.sendButton)!=null?h:{},t=(S=r.useIcon)!=null?S:!1,o=(L=r.iconText)!=null?L:"\u2191",a=r.iconName,n=(O=r.stopIconName)!=null?O:"square",s=(H=r.tooltipText)!=null?H:"Send message",i=(R=r.stopTooltipText)!=null?R:"Stop generating",d=(V=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?V:"Send",l=(fe=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?fe:"Stop",u=(_e=r.showTooltip)!=null?_e:!1,p=(je=r.size)!=null?je:"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 ye=parseFloat(p)||24,me=(f==null?void 0:f.trim())||"currentColor";a?(k=Ce(a,ye,me,2),k?v.appendChild(k):v.textContent=o):v.textContent=o,T=Ce(n,ye,me,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:ye=>{if(ye===E)return;E=ye;let me=ye==="stop"?i:s;if(v.setAttribute("aria-label",me),A&&(A.textContent=me),t){if(k&&T){let Pe=ye==="stop"?T:k,Ve=ye==="stop"?k:T;Ve.parentNode===v?v.replaceChild(Pe,Ve):v.appendChild(Pe)}}else v.textContent=ye==="stop"?l:d}}},ll=e=>{var A,E,b,h,S,L,O,H,R,B,V,oe;let r=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(r.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),a=((E=r.provider)==null?void 0:E.type)==="runtype";if(!(o||a))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=(V=r.tooltipText)!=null?V:"Start voice recognition";if(((oe=r.showTooltip)!=null?oe:!1)&&k){let fe=x("div","persona-send-button-tooltip");fe.textContent=k,i.appendChild(fe)}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",o=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let a=x("input");a.type="file",a.accept=((T=r.allowedTypes)!=null?T:nn).join(","),a.multiple=((A=r.maxFiles)!=null?A:4)>1,a.style.display="none",a.setAttribute("aria-label","Attach files");let n=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(),a.click()}),n.appendChild(s);let m=(h=r.buttonTooltipText)!=null?h:"Attach file",f=x("div","persona-send-button-tooltip");return f.textContent=m,n.appendChild(f),{button:s,wrapper:n,input:a,previewsContainer:o}},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",o=x("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let a=(i=r.visible)!=null?i:!0;o.style.display=a?"":"none";let n=(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=n,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=n;return o},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 o=pl(),a=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");a.setAttribute("data-persona-composer-form",""),a.style.outline="none";let{textarea:n,attachAutoResize:s}=sl(r);s();let i=il(r),d=ll(r),l=dl(r),u=cl(r);l&&(l.previewsContainer.style.gap="8px",a.append(l.previewsContainer,l.input)),a.append(n);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),a.append(p),a.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)&&n.focus()}),t.append(o,a,u),{footer:t,suggestions:o,composerForm:a,textarea:n,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 th=()=>{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 o=x("span","persona-pill-peek__text"),a=x("span","persona-pill-peek__caret"),n=Ce("chevron-up",16,"currentColor",1.5);return n&&a.appendChild(n),e.append(r,o,a),{root:e,textNode:o}},rh=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 o=pl();o.style.display="none";let a=cl(r);a.style.display="none";let{textarea:n,attachAutoResize:s}=sl(r);n.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)&&n.focus()}),l&&u.append(l.input),u.append(p,n,m),l&&t.append(l.previewsContainer),t.append(u,o,a);let f=u;return{footer:t,suggestions:o,composerForm:u,textarea:n,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:a,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 oh=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(Tn(e)){let B=(f=(m=e==null?void 0:e.launcher)==null?void 0:m.composerBar)!=null?f:{},V=x("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(w=B.expandedSize)!=null?w:"anchored",V.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%",V.appendChild(oe);let fe=x("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(T=B.expandedSize)!=null?T:"anchored",fe.style.zIndex=String((E=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?E:Or),{wrapper:V,panel:oe,pillRoot:fe}}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"),V=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(V),{wrapper:B,panel:V}}if(!r){let B=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=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,V.style.width="100%",B.appendChild(V),{wrapper:B,panel:V}}let a=(S=e==null?void 0:e.launcher)!=null?S:{},n=a.position&&Oo[a.position]?Oo[a.position]:Oo["bottom-right"],s=x("div",`persona-widget-wrapper persona-fixed ${n} 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:mo;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},Mb=(e,r)=>{var b,h,S,L,O,H,R,B,V;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:o,wrapper:a}=rl(e,{showClose:r,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});a.style.position="absolute",a.style.top="8px",a.style.right="8px",a.style.zIndex="10";let n=(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(n){let oe=ol(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%"),((V=e==null?void 0:e.copy)==null?void 0:V.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=rh({config:e}),{root:A,textNode:E}=th();return t.append(d,a,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:o,closeButtonWrapper:a,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}},nh=(e,r=!0)=>{var k,T,A,E,b,h,S,L,O;if(Tn(e))return Mb(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 o=(k=e==null?void 0:e.layout)==null?void 0:k.header,a=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,n=o?Ta(e,o,{showClose:r}):an({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;a?oa(t,n,e):(n.header.style.display="none",oa(t,n,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:n.closeButton,closeButtonWrapper:n.closeButtonWrapper,clearChatButton:n.clearChatButton,clearChatButtonWrapper:n.clearChatButtonWrapper,iconHolder:n.iconHolder,headerTitle:n.headerTitle,headerSubtitle:n.headerSubtitle,header:n.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 Lb=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}},Pb=(e,r)=>{if(!e)return null;let t=Lb(e);if(t===null)return null;let o=r==null?void 0:r[e],a=o!==void 0?o:t;return a||null},Ib=(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},Rb=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Hb=320,Bb=320,Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Db=(e,r,t)=>{if(e.length===0)return null;try{let o=x("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),r&&(o.style.marginBottom="8px");let a=0,n=!1,s=()=>{n||(n=!0,o.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=`${Hb}px`,l.style.maxHeight=`${Bb}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;a+=1,l.addEventListener("error",()=>{u||(u=!0,a=Math.max(0,a-1),l.remove(),a===0&&s())}),l.addEventListener("load",()=>{u=!0}),Rb(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,a=Math.max(0,a-1),l.remove())}),a===0?(s(),null):o}catch{return t==null||t(),null}},na=()=>{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 o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let a=document.createElement("span");return a.className="persona-sr-only",a.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(o),e.appendChild(a),e},up=(e,r,t)=>{let o={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:na};if(r){let a=r(o);if(a!==null)return a}return na()},Ob=(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"),o=r==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let a=x("img");a.src=o,a.alt=r==="user"?"User":"Assistant",a.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(a)}else t.textContent=o,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},ah=(e,r)=>{let t=x("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return r.format?t.textContent=r.format(o):t.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Fb=(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},fp=(e,r,t)=>{var f,w,v,k,T,A;let o=(f=r.showCopy)!=null?f:!0,a=(w=r.showUpvote)!=null?w:!0,n=(v=r.showDownvote)!=null?v:!0;if(!o&&!a&&!n){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 o&&p.appendChild(m("copy","Copy message","copy")),a&&p.appendChild(m("thumbs-up","Upvote","upvote")),n&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Ea=(e,r,t,o,a,n)=>{var me,Pe,Ve,Q,Ae,J,de,pe,se,Be,Ee,K,Oe,Fe,Y,G,we;let s=t!=null?t:{},i=(me=s.layout)!=null?me:"bubble",d=s.avatar,l=s.timestamp,u=(Pe=d==null?void 0:d.show)!=null?Pe:!1,p=(Ve=l==null?void 0:l.show)!=null?Ve:!1,m=(Q=d==null?void 0:d.position)!=null?Q:"left",f=(Ae=l==null?void 0:l.position)!=null?Ae:"below",w=Fb(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=Wb(e),T=(de=(J=e.content)==null?void 0:J.trim())!=null?de:"",E=k.length>0&&T===Ei,b=Qi((se=(pe=n==null?void 0:n.widgetConfig)==null?void 0:pe.features)==null?void 0:se.streamAnimation),h=(K=(Ee=(Be=n==null?void 0:n.widgetConfig)==null?void 0:Be.features)==null?void 0:Ee.streamAnimation)==null?void 0:K.plugins,S=e.role==="assistant"&&b.type!=="none"?Ss(b.type,h):null,L=e.role==="assistant"&&((Oe=S==null?void 0:S.isAnimating)==null?void 0:Oe.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((Fe=e.content)!=null?Fe:"",b.buffer,S,e,!!e.streaming):(Y=e.content)!=null?Y:"",B=r({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=B;O&&(S==null?void 0:S.wrap)==="char"?V=Ts(B,"char",e.id,{skipTags:S.skipTags}):O&&(S==null?void 0:S.wrap)==="word"&&(V=Ts(B,"word",e.id,{skipTags:S.skipTags}));let oe=null;if(E?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",H.appendChild(oe)):H.innerHTML=V,O&&(S!=null&&S.useCaret)&&!E&&T){let ue=el(),re=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),he=re[re.length-1];if(he!=null&&he.parentNode)he.parentNode.insertBefore(ue,he.nextSibling);else{let Je=H.lastElementChild;Je?Je.appendChild(ue):H.appendChild(ue)}}if(p&&f==="inline"&&e.createdAt){let ue=ah(e,l);ue.classList.add("persona-ml-2","persona-inline"),H.appendChild(ue)}if(k.length>0){let ue=Db(k,!E&&!!T,()=>{E&&oe&&(oe.style.display="")});ue?v.appendChild(ue):E&&oe&&(oe.style.display="")}if(v.appendChild(H),p&&f==="below"&&e.createdAt){let ue=ah(e,l);ue.classList.add("persona-mt-1"),v.appendChild(ue)}let fe=e.role==="assistant"?Pb(e.stopReason,(we=(G=n==null?void 0:n.widgetConfig)==null?void 0:G.copy)==null?void 0:we.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ue=!!(R&&R.trim()),re=b.placeholder==="skeleton",he=re&&b.buffer==="line"&&ue;if(ue)he&&v.appendChild(ks());else if(re)v.appendChild(ks());else{let Je=up("inline",n==null?void 0:n.loadingIndicatorRenderer,n==null?void 0:n.widgetConfig);Je&&v.appendChild(Je)}}if(fe&&e.stopReason&&!e.streaming&&(T||(H.style.display="none"),v.appendChild(Ib(e.stopReason,fe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let ue=fp(e,o,a);v.appendChild(ue)}if(!u||e.role==="system")return v;let je=x("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ye=Ob(d,e.role);return m==="right"||m==="left"&&e.role==="user"?je.append(v,ye):je.append(ye,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),je},sh=(e,r,t,o,a,n)=>{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,o,a,n)};var Ma=new Set,Nb=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),_b=(e,r)=>{var o,a;let t=(a=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?a:"";return t?t.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,r).join(`
|
|
64
|
-
`):""},ih=(e,r)=>{let t=Ma.has(e),
|
|
63
|
+
`,t.addEventListener("click",r);let n=o=>{var E,b,h,S,L,O,H,R,B,V,ne,fe,_e,je;let s=(E=o.launcher)!=null?E:{},i=hr(o),d=t.querySelector("[data-role='launcher-title']");if(d){let ye=(b=s.title)!=null?b:"Chat Assistant";d.textContent=ye,d.setAttribute("title",ye)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let ye=(h=s.subtitle)!=null?h:"Get answers fast";l.textContent=ye,l.setAttribute("title",ye)}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 ye=(S=s.agentIconSize)!=null?S:"40px";if(p.style.height=ye,p.style.width=ye,p.innerHTML="",s.agentIconName){let me=parseFloat(ye)||24,Pe=Ce(s.agentIconName,me*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(p.appendChild(Pe),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 ye=(H=s.agentIconSize)!=null?H:"40px";m.style.height=ye,m.style.width=ye,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 ye=(R=s.callToActionIconSize)!=null?R:"32px";f.style.height=ye,f.style.width=ye,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 me=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,me=(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 Pe=parseFloat(ye)||24,Ve=Math.max(Pe-me,8),Q=Ce(s.callToActionIconName,Ve,"currentColor",2);Q?f.appendChild(Q):f.textContent=(B=s.callToActionIconText)!=null?B:"\u2197"}else f.textContent=(V=s.callToActionIconText)!=null?V:"\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((ne=s.zIndex)!=null?ne: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=(fe=s.border)!=null?fe:T,t.style.boxShadow=(_e=s.shadow)!=null?_e: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=(je=s.collapsedMaxWidth)!=null?je:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},a=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:a}};var kb="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=kb,buttonSize:a,iconSize:o="28px"}=r,s=(v=e==null?void 0:e.launcher)!=null?v:{},i=(k=a!=null?a: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,o,"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}},Eb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",nl=(e,r={})=>{var h,S,L,O,H,R,B,V,ne,fe,_e,je,ye;let{wrapperClassName:t=Eb,buttonSize:n,iconSize:a="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=(V=s.borderColor)!=null?V:"",f=(ne=s.borderRadius)!=null?ne:"",w=(fe=s.paddingX)!=null?fe:"",v=(_e=s.paddingY)!=null?_e:"",k=(je=s.tooltipText)!=null?je:"Clear chat",T=(ye=s.showTooltip)!=null?ye:!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,a,"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 me=p||"0px",Pe=m||"transparent";E.style.border=`${me} solid ${Pe}`,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 me=null,Pe=()=>{if(me)return;let Q=E.ownerDocument,Ae=Q.body;if(!Ae)return;me=qn(Q,"div","persona-clear-chat-tooltip"),me.textContent=k;let J=qn(Q,"div");J.className="persona-clear-chat-tooltip-arrow",me.appendChild(J);let de=E.getBoundingClientRect();me.style.position="fixed",me.style.zIndex=String(Ao),me.style.left=`${de.left+de.width/2}px`,me.style.top=`${de.top-8}px`,me.style.transform="translate(-50%, -100%)",Ae.appendChild(me)},Ve=()=>{me&&me.parentNode&&(me.parentNode.removeChild(me),me=null)};A.addEventListener("mouseenter",Pe),A.addEventListener("mouseleave",Ve),E.addEventListener("focus",Pe),E.addEventListener("blur",Ve),A._cleanupTooltip=()=>{Ve(),A.removeEventListener("mouseenter",Pe),A.removeEventListener("mouseleave",Ve),E.removeEventListener("focus",Pe),E.removeEventListener("blur",Ve)}}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,V,ne,fe,_e,je,ye,me,Pe,Ve;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 a=(h=r==null?void 0:r.launcher)!=null?h:{},o=(S=a.headerIconSize)!=null?S:"48px",s=(L=a.closeButtonPlacement)!=null?L:"inline",i=(O=a.headerIconHidden)!=null?O:!1,d=a.headerIconName,l=x("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,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(o)||24,Ae=Ce(d,Q*.6,"currentColor",1);Ae?l.replaceChildren(Ae):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=o,Q.style.width=o,l.replaceChildren(Q)}else l.textContent=(ne=(V=r==null?void 0:r.launcher)==null?void 0:V.agentIconText)!=null?ne:"\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=(_e=(fe=r==null?void 0:r.launcher)==null?void 0:fe.title)!=null?_e:"Chat Assistant";let m=x("span","persona-text-xs");m.style.color=Kr.subtitleColor,m.textContent=(ye=(je=r==null?void 0:r.launcher)==null?void 0:je.subtitle)!=null?ye:"Here to help you get answers fast",u.append(p,m),i?n.append(u):n.append(l,u);let f=(me=a.clearChat)!=null?me:{},w=(Pe=f.enabled)!=null?Pe:!0,v=(Ve=f.placement)!=null?Ve:"inline",k=null,T=null;if(w){let Ae=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=Ae.button,T=Ae.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:{},a=(i=n.closeButtonPlacement)!=null?i:"inline",o=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(r.header),a==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function ko(e){let{items:r,onSelect:t,anchor:n,position:a="bottom-left",portal:o}=e,s=x("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),o?(s.style.position="fixed",s.style.zIndex=String(Ao)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",a==="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(!o)return;let f=n.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,a==="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 o&&o.appendChild(s),{element:s,show:l,hide:u,toggle:p,destroy:m}}function Qt(e){let{icon:r,label:t,size:n,strokeWidth:a,className:o,onClick:s,aria:i}=e,d=x("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Ce(r,n!=null?n:16,"currentColor",a!=null?a: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:a="sm",iconSize:o,className:s,onClick:i,aria:d}=e,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+a,s&&(l+=" "+s);let u=x("button",l);if(u.type="button",u.setAttribute("aria-label",t),r){let m=Ce(r,o!=null?o: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:a}=e,o=x("div","persona-toggle-group"+(a?" "+a:""));o.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}),o.appendChild(p)}function l(u){s=u,d()}return{element:o,setSelected:l}}function ol(e){var f,w;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:a,position:o="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"),a(v)},anchor:l,position:o,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 a=r.headerTitle.parentElement;a&&(a.style.cursor="pointer",a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.addEventListener("click",()=>t()),a.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function Mb(e,r,t){var n,a,o;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",(a=(n=s.ariaLabel)!=null?n:s.label)!=null?a:s.id),s.icon){let d=Ce(s.icon,14,"currentColor",2);d&&i.appendChild(d)}else s.label&&(i.textContent=s.label);if((o=s.menuItems)!=null&&o.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:a,onHeaderAction:o}=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=a==null?void 0:a.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),Mb(l,a==null?void 0:a.trailingActions,(S=a==null?void 0:a.onAction)!=null?S:o),a!=null&&a.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=a.onTitleClick;l.addEventListener("click",ne=>{ne.target.closest("button")||V()}),l.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let B=a==null?void 0:a.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 V,ne;l.style.backgroundColor=(V=B.background)!=null?V:"",l.style.borderColor=(ne=B.border)!=null?ne:""}),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",o=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&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};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 a=()=>{let d=parseFloat(r.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*n},o=()=>{r.addEventListener("input",()=>{r.style.height="auto";let d=Math.min(r.scrollHeight,a());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:o}},il=e=>{var h,S,L,O,H,R,B,V,ne,fe,_e,je;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",a=r.iconName,o=(O=r.stopIconName)!=null?O:"square",s=(H=r.tooltipText)!=null?H:"Send message",i=(R=r.stopTooltipText)!=null?R:"Stop generating",d=(V=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?V:"Send",l=(fe=(ne=e==null?void 0:e.copy)==null?void 0:ne.stopButtonLabel)!=null?fe:"Stop",u=(_e=r.showTooltip)!=null?_e:!1,p=(je=r.size)!=null?je:"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 ye=parseFloat(p)||24,me=(f==null?void 0:f.trim())||"currentColor";a?(k=Ce(a,ye,me,2),k?v.appendChild(k):v.textContent=n):v.textContent=n,T=Ce(o,ye,me,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:ye=>{if(ye===E)return;E=ye;let me=ye==="stop"?i:s;if(v.setAttribute("aria-label",me),A&&(A.textContent=me),t){if(k&&T){let Pe=ye==="stop"?T:k,Ve=ye==="stop"?k:T;Ve.parentNode===v?v.replaceChild(Pe,Ve):v.appendChild(Pe)}}else v.textContent=ye==="stop"?l:d}}},ll=e=>{var A,E,b,h,S,L,O,H,R,B,V,ne;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"),a=((E=r.provider)==null?void 0:E.type)==="runtype";if(!(n||a))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=(V=r.tooltipText)!=null?V:"Start voice recognition";if(((ne=r.showTooltip)!=null?ne:!1)&&k){let fe=x("div","persona-send-button-tooltip");fe.textContent=k,i.appendChild(fe)}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 a=x("input");a.type="file",a.accept=((T=r.allowedTypes)!=null?T:oo).join(","),a.multiple=((A=r.maxFiles)!=null?A:4)>1,a.style.display="none",a.setAttribute("aria-label","Attach files");let o=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(),a.click()}),o.appendChild(s);let m=(h=r.buttonTooltipText)!=null?h:"Attach file",f=x("div","persona-send-button-tooltip");return f.textContent=m,o.appendChild(f),{button:s,wrapper:o,input:a,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 a=(i=r.visible)!=null?i:!0;n.style.display=a?"":"none";let o=(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=o,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=o;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(),a=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");a.setAttribute("data-persona-composer-form",""),a.style.outline="none";let{textarea:o,attachAutoResize:s}=sl(r);s();let i=il(r),d=ll(r),l=dl(r),u=cl(r);l&&(l.previewsContainer.style.gap="8px",a.append(l.previewsContainer,l.input)),a.append(o);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),a.append(p),a.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)&&o.focus()}),t.append(n,a,u),{footer:t,suggestions:n,composerForm:a,textarea:o,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 th=()=>{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"),a=x("span","persona-pill-peek__caret"),o=Ce("chevron-up",16,"currentColor",1.5);return o&&a.appendChild(o),e.append(r,n,a),{root:e,textNode:n}},rh=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 a=cl(r);a.style.display="none";let{textarea:o,attachAutoResize:s}=sl(r);o.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)&&o.focus()}),l&&u.append(l.input),u.append(p,o,m),l&&t.append(l.previewsContainer),t.append(u,n,a);let f=u;return{footer:t,suggestions:n,composerForm:u,textarea:o,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:a,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 nh=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:{},V=x("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(w=B.expandedSize)!=null?w:"anchored",V.style.zIndex=String((k=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?k:Or);let ne=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let fe=x("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(T=B.expandedSize)!=null?T:"anchored",fe.style.zIndex=String((E=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?E:Or),{wrapper:V,panel:ne,pillRoot:fe}}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"),V=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(V),{wrapper:B,panel:V}}if(!r){let B=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(h=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?h:"100%";return B.style.width=ne,V.style.width="100%",B.appendChild(V),{wrapper:B,panel:V}}let a=(S=e==null?void 0:e.launcher)!=null?S:{},o=a.position&&On[a.position]?On[a.position]:On["bottom-right"],s=x("div",`persona-widget-wrapper persona-fixed ${o} 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}},Lb=(e,r)=>{var b,h,S,L,O,H,R,B,V;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:a}=rl(e,{showClose:r,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});a.style.position="absolute",a.style.top="8px",a.style.right="8px",a.style.zIndex="10";let o=(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(o){let ne=nl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=ne.button,i=ne.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%"),((V=e==null?void 0:e.copy)==null?void 0:V.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=rh({config:e}),{root:A,textNode:E}=th();return t.append(d,a,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:a,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}},oh=(e,r=!0)=>{var k,T,A,E,b,h,S,L,O;if(To(e))return Lb(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,a=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,o=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;a?na(t,o,e):(o.header.style.display="none",na(t,o,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:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.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 Pb=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}},Ib=(e,r)=>{if(!e)return null;let t=Pb(e);if(t===null)return null;let n=r==null?void 0:r[e],a=n!==void 0?n:t;return a||null},Rb=(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},Hb=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Bb=320,Wb=320,Db=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Ob=(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 a=0,o=!1,s=()=>{o||(o=!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=`${Bb}px`,l.style.maxHeight=`${Wb}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;a+=1,l.addEventListener("error",()=>{u||(u=!0,a=Math.max(0,a-1),l.remove(),a===0&&s())}),l.addEventListener("load",()=>{u=!0}),Hb(i.image)?(l.src=i.image,n.appendChild(l)):(u=!0,a=Math.max(0,a-1),l.remove())}),a===0?(s(),null):n}catch{return t==null||t(),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 a=document.createElement("span");return a.className="persona-sr-only",a.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(a),e},up=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:oa};if(r){let a=r(n);if(a!==null)return a}return oa()},Fb=(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 a=x("img");a.src=n,a.alt=r==="user"?"User":"Assistant",a.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(a)}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},ah=(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},Nb=(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},fp=(e,r,t)=>{var f,w,v,k,T,A;let n=(f=r.showCopy)!=null?f:!0,a=(w=r.showUpvote)!=null?w:!0,o=(v=r.showDownvote)!=null?v:!0;if(!n&&!a&&!o){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")),a&&p.appendChild(m("thumbs-up","Upvote","upvote")),o&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Ea=(e,r,t,n,a,o)=>{var me,Pe,Ve,Q,Ae,J,de,pe,se,Be,Ee,K,Oe,Fe,Y,G,we;let s=t!=null?t:{},i=(me=s.layout)!=null?me:"bubble",d=s.avatar,l=s.timestamp,u=(Pe=d==null?void 0:d.show)!=null?Pe:!1,p=(Ve=l==null?void 0:l.show)!=null?Ve:!1,m=(Q=d==null?void 0:d.position)!=null?Q:"left",f=(Ae=l==null?void 0:l.position)!=null?Ae:"below",w=Nb(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=Db(e),T=(de=(J=e.content)==null?void 0:J.trim())!=null?de:"",E=k.length>0&&T===Ei,b=Qi((se=(pe=o==null?void 0:o.widgetConfig)==null?void 0:pe.features)==null?void 0:se.streamAnimation),h=(K=(Ee=(Be=o==null?void 0:o.widgetConfig)==null?void 0:Be.features)==null?void 0:Ee.streamAnimation)==null?void 0:K.plugins,S=e.role==="assistant"&&b.type!=="none"?Ss(b.type,h):null,L=e.role==="assistant"&&((Oe=S==null?void 0:S.isAnimating)==null?void 0:Oe.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((Fe=e.content)!=null?Fe:"",b.buffer,S,e,!!e.streaming):(Y=e.content)!=null?Y:"",B=r({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=B;O&&(S==null?void 0:S.wrap)==="char"?V=Ts(B,"char",e.id,{skipTags:S.skipTags}):O&&(S==null?void 0:S.wrap)==="word"&&(V=Ts(B,"word",e.id,{skipTags:S.skipTags}));let ne=null;if(E?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",H.appendChild(ne)):H.innerHTML=V,O&&(S!=null&&S.useCaret)&&!E&&T){let ue=el(),re=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),he=re[re.length-1];if(he!=null&&he.parentNode)he.parentNode.insertBefore(ue,he.nextSibling);else{let Je=H.lastElementChild;Je?Je.appendChild(ue):H.appendChild(ue)}}if(p&&f==="inline"&&e.createdAt){let ue=ah(e,l);ue.classList.add("persona-ml-2","persona-inline"),H.appendChild(ue)}if(k.length>0){let ue=Ob(k,!E&&!!T,()=>{E&&ne&&(ne.style.display="")});ue?v.appendChild(ue):E&&ne&&(ne.style.display="")}if(v.appendChild(H),p&&f==="below"&&e.createdAt){let ue=ah(e,l);ue.classList.add("persona-mt-1"),v.appendChild(ue)}let fe=e.role==="assistant"?Ib(e.stopReason,(we=(G=o==null?void 0:o.widgetConfig)==null?void 0:G.copy)==null?void 0:we.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ue=!!(R&&R.trim()),re=b.placeholder==="skeleton",he=re&&b.buffer==="line"&&ue;if(ue)he&&v.appendChild(ks());else if(re)v.appendChild(ks());else{let Je=up("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Je&&v.appendChild(Je)}}if(fe&&e.stopReason&&!e.streaming&&(T||(H.style.display="none"),v.appendChild(Rb(e.stopReason,fe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let ue=fp(e,n,a);v.appendChild(ue)}if(!u||e.role==="system")return v;let je=x("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ye=Fb(d,e.role);return m==="right"||m==="left"&&e.role==="user"?je.append(v,ye):je.append(ye,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),je},sh=(e,r,t,n,a,o)=>{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,a,o)};var Ma=new Set,_b=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),$b=(e,r)=>{var n,a;let t=(a=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?a:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
|
|
64
|
+
`):""},ih=(e,r)=>{let t=Ma.has(e),n=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!a)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"}a.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},mp=(e,r)=>{var _e,je,ye,me,Pe,Ve,Q,Ae,J,de,pe;let t=e.reasoning,n=x("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 a=(je=(_e=r==null?void 0:r.features)==null?void 0:_e.reasoningDisplay)!=null?je:{},o=a.expandable!==!1,s=o&&Ma.has(e.id),i=t.status!=="complete",d=$b(e,(ye=a.previewMaxLines)!=null?ye:3),l=x("button",o?"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",o&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=x("div","persona-flex persona-flex-col persona-text-left"),p=x("span","persona-text-xs persona-text-persona-primary"),m="Thinking...",f=(me=r==null?void 0:r.reasoning)!=null?me:{},w=String((Pe=t.startedAt)!=null?Pe:Date.now()),v=()=>{let se=x("span","");return se.setAttribute("data-tool-elapsed",w),se.textContent=bi(t),se},k=(Ve=f.renderCollapsedSummary)==null?void 0:Ve.call(f,{message:e,reasoning:t,defaultSummary:m,previewText:d,isActive:i,config:r!=null?r:{},elapsed:bi(t),createElapsedElement:v});typeof k=="string"&&k.trim()?(p.textContent=k,u.appendChild(p)):k instanceof HTMLElement?u.appendChild(k):(p.textContent=m,u.appendChild(p));let T=x("span","persona-text-xs persona-text-persona-primary");T.textContent=Tg(t),u.appendChild(T);let A=(Q=a.loadingAnimation)!=null?Q:"none",E=f.activeTextTemplate,b=f.completeTextTemplate,h=i?E:b,S=k instanceof HTMLElement,L=(se,Be,Ee)=>{let K=Ee;for(let Oe of Be){let Fe=x("span","persona-tool-char");Fe.style.setProperty("--char-index",String(K)),Fe.textContent=Oe===" "?"\xA0":Oe,se.appendChild(Fe),K++}return K},O=(se,Be)=>{p.textContent="";let Ee=Ci(se,""),K=0;for(let Oe of Ee){let Fe=Oe.styles.length>0?(()=>{let Y=x("span",Oe.styles.map(G=>`persona-tool-text-${G}`).join(" "));return p.appendChild(Y),Y})():p;if(Oe.isDuration&&i)Fe.appendChild(v());else{let Y=Oe.isDuration?bi(t):Oe.text;Be?K=L(Fe,Y,K):Fe.appendChild(document.createTextNode(Y))}}};if(!S&&h)if(T.style.display="none",p.style.display="",i&&A!=="none"){let se=(Ae=f.loadingAnimationDuration)!=null?Ae:2e3;p.setAttribute("data-preserve-animation","true"),A==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${se}ms`),O(h,!1)):(p.classList.add(`persona-tool-loading-${A}`),p.style.setProperty("--persona-tool-anim-duration",`${se}ms`),A==="shimmer-color"&&(f.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),O(h,!0))}else O(h,!1);else if(!S&&i&&A!=="none"){p.style.display="";let se=(J=f.loadingAnimationDuration)!=null?J:2e3;if(p.setAttribute("data-preserve-animation","true"),A==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${se}ms`);else{p.classList.add(`persona-tool-loading-${A}`),p.style.setProperty("--persona-tool-anim-duration",`${se}ms`),A==="shimmer-color"&&(f.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Be=p.textContent||m;p.textContent="",L(p,Be,0)}t.status==="complete"&&(p.style.display="none")}else S||(t.status==="complete"?p.style.display="none":p.style.display="");let H=null;if(o){H=x("div","persona-flex persona-items-center");let Be=Ce(s?"chevron-up":"chevron-down",16,"currentColor",2);Be?H.appendChild(Be):H.textContent=s?"Hide":"Show";let Ee=x("div","persona-flex persona-items-center persona-ml-auto");Ee.append(H),l.append(u,Ee)}else l.append(u);let R=x("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&&a.activePreview&&d){let se=(pe=(de=r==null?void 0:r.reasoning)==null?void 0:de.renderCollapsedPreview)==null?void 0:pe.call(de,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:r!=null?r:{}});_b(R,se)||(R.textContent=d),R.style.display=""}if(!s&&i&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!o)return n.append(l,R),n;let B=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");B.style.display=s?"":"none";let V=t.chunks.join(""),ne=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),B.appendChild(ne),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),H){H.innerHTML="";let Be=Ce(s?"chevron-up":"chevron-down",16,"currentColor",2);Be?H.appendChild(Be):H.textContent=s?"Hide":"Show"}B.style.display=s?"":"none",R.style.display=s?"none":R.textContent||R.childNodes.length?"":"none"})(),n.append(l,R,B),n};var La=new Set,Ub=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),qb=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
|
|
65
65
|
`);let a=ba(t.args).trim();return a?a.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,o=(u=r==null?void 0:r.features)==null?void 0:u.toolCallDisplay,a=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",n=Ub(e,(m=o==null?void 0:o.previewMaxLines)!=null?m:3),s=t?kg(t):"";if(!t)return{summary:s,previewText:n,isActive:!1};let i=t.status!=="complete",d=(f=r==null?void 0:r.toolCall)!=null?f:{},l=s;return a==="tool-name"?l=((w=t.name)==null?void 0:w.trim())||s:a==="tool-preview"&&n&&(l=n),i&&d.activeTextTemplate?l=ed(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ed(t,d.completeTextTemplate,l)),{summary:l,previewText:n,isActive:i}},lh=(e,r,t)=>{var u;let o=La.has(e),a=(u=t==null?void 0:t.toolCall)!=null?u:{},n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!n||!s)return;n.setAttribute("aria-expanded",o?"true":"false");let d=n.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=a.toggleTextColor||a.headerTextColor||"currentColor",m=Ce(o?"chevron-up":"chevron-down",16,p,2);m?l.appendChild(m):l.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},gp=(e,r)=>{var V,oe,fe,_e,je,ye,me,Pe,Ve;let t=e.toolCall,o=(V=r==null?void 0:r.toolCall)!=null?V:{},a=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(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),o.backgroundColor&&(a.style.backgroundColor=o.backgroundColor),o.borderColor&&(a.style.borderColor=o.borderColor),o.borderWidth&&(a.style.borderWidth=o.borderWidth),o.borderRadius&&(a.style.borderRadius=o.borderRadius),!t)return a;let n=(fe=(oe=r==null?void 0:r.features)==null?void 0:oe.toolCallDisplay)!=null?fe:{},s=n.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"),o.headerBackgroundColor&&(p.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(p.style.paddingLeft=o.headerPaddingX,p.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(p.style.paddingTop=o.headerPaddingY,p.style.paddingBottom=o.headerPaddingY);let m=x("div","persona-flex persona-flex-col persona-text-left"),f=x("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let w=String((_e=t.startedAt)!=null?_e:Date.now()),v=()=>{let Q=x("span","");return Q.setAttribute("data-tool-elapsed",w),Q.textContent=ms(t),Q},k=(ye=o.renderCollapsedSummary)==null?void 0:ye.call(o,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(je=n.collapsedMode)!=null?je:"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=(me=n.loadingAnimation)!=null?me:"none",A=o.activeTextTemplate,E=o.completeTextTemplate,b=u?A:E,h=k instanceof HTMLElement,S=(Q,Ae,J)=>{let de=J;for(let pe of Ae){let se=x("span","persona-tool-char");se.style.setProperty("--char-index",String(de)),se.textContent=pe===" "?"\xA0":pe,Q.appendChild(se),de++}return de},L=(Q,Ae)=>{var se;f.textContent="";let J=((se=t.name)==null?void 0:se.trim())||"tool",de=Ci(Q,J),pe=0;for(let Be of de){let Ee=Be.styles.length>0?(()=>{let K=x("span",Be.styles.map(Oe=>`persona-tool-text-${Oe}`).join(" "));return f.appendChild(K),K})():f;if(Be.isDuration&&u)Ee.appendChild(v());else{let K=Be.isDuration?ms(t):Be.text;Ae?pe=S(Ee,K,pe):Ee.appendChild(document.createTextNode(K))}}};if(!h)if(u&&T!=="none"){let Q=(Pe=o.loadingAnimationDuration)!=null?Pe: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"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),b)L(b,!0);else{let Ae=f.textContent||d;f.textContent="",S(f,Ae,0)}}else b&&L(b,!1);let O=null;if(s){O=x("div","persona-flex persona-items-center");let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Ae=Ce(i?"chevron-up":"chevron-down",16,Q,2);Ae?O.appendChild(Ae):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&&n.activePreview&&l){let Q=(Ve=o.renderCollapsedPreview)==null?void 0:Ve.call(o,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:r!=null?r:{}});$b(H,Q)||(H.textContent=l),H.style.display=""}if(!i&&u&&n.activeMinHeight&&(a.style.minHeight=n.activeMinHeight),!s)return a.append(p,H),a;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",o.contentBackgroundColor&&(R.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(R.style.color=o.contentTextColor),o.contentPaddingX&&(R.style.paddingLeft=o.contentPaddingX,R.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(R.style.paddingTop=o.contentPaddingY,R.style.paddingBottom=o.contentPaddingY),t.name){let Q=x("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Q.style.color=o.contentTextColor:o.headerTextColor&&(Q.style.color=o.headerTextColor),Q.textContent=t.name,R.appendChild(Q)}if(t.args!==void 0){let Q=x("div","persona-space-y-1"),Ae=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ae.style.color=o.labelTextColor),Ae.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",o.codeBlockBackgroundColor&&(J.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(J.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(J.style.color=o.codeBlockTextColor),J.textContent=ba(t.args),Q.append(Ae,J),R.appendChild(Q)}if(t.chunks&&t.chunks.length){let Q=x("div","persona-space-y-1"),Ae=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ae.style.color=o.labelTextColor),Ae.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",o.codeBlockBackgroundColor&&(J.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(J.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(J.style.color=o.codeBlockTextColor),J.textContent=t.chunks.join(""),Q.append(Ae,J),R.appendChild(Q)}if(t.status==="complete"&&t.result!==void 0){let Q=x("div","persona-space-y-1"),Ae=x("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ae.style.color=o.labelTextColor),Ae.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",o.codeBlockBackgroundColor&&(J.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(J.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(J.style.color=o.codeBlockTextColor),J.textContent=ba(t.result),Q.append(Ae,J),R.appendChild(Q)}if(t.status==="complete"&&typeof t.duration=="number"){let Q=x("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Q.style.color=o.contentTextColor),Q.textContent=`Duration: ${t.duration}ms`,R.appendChild(Q)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Ae=Ce(i?"chevron-up":"chevron-down",16,Q,2);Ae?O.appendChild(Ae):O.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),a.append(p,H,R),a};var En=Bl(hi(),1);var xp="ask_user_question",hp=8,Pa="data-persona-ask-sheet-for",zb="Other",Vb="Other\u2026",ch="Type your own answer here",ph="Send",jb="Next",Gb="Back",Xb="Submit all",Jb="Skip",Kb=3,yp="data-ask-current-index",bp="data-ask-question-count",uh="data-ask-answers",Cp="data-ask-grouped",fh="data-ask-layout",Yb=e=>e.layout==="pills"?"pills":"rows",Qb=e=>e.getAttribute(fh)==="pills"?"pills":"rows",dh=!1,mh=e=>e.replace(/["\\]/g,"\\$&"),sn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xp,ul=e=>{var r,t;return(t=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion)!=null?t:{}},ln=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 o=r.chunks;if(!o||o.length===0)return{payload:null,complete:t};try{let a=o.join(""),n=(0,En.parse)(a,En.STR|En.OBJ|En.ARR);if(n&&typeof n=="object")return{payload:n,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>hp&&!dh&&(dh=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${r.length} questions; truncating to ${hp}.`)),r.slice(0,hp)},Zb=e=>{var r;return(r=Is(e)[0])!=null?r:null},e0=(e,r)=>{var t;return(t=Is(e)[r])!=null?t:null},gh=(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))},hh=(e,r,t)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),r){let a=x("span","persona-ask-row-check");o.appendChild(a)}else{let a=x("span","persona-ask-row-badge");a.textContent=String(t+1),o.appendChild(a)}return o},t0=(e,r,t,o)=>{let n=x("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(n.type="button",n.setAttribute("role",o?"checkbox":"button"),n.setAttribute("aria-pressed","false"),n.setAttribute("data-ask-user-action","pick"),n.setAttribute("data-option-index",String(r)),n.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)}n.appendChild(s);let d=hh(t,o,r);d&&n.appendChild(d)}else n.textContent=e.label,e.description&&(n.title=e.description);return n},r0=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},o0=(e,r,t,o)=>{var u,p,m;let n=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");n.setAttribute("role","group"),n.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<Kb;f++)n.appendChild(r0(o));return n}if(d.forEach((f,w)=>{n.appendChild(t0(f,w,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let f=o==="rows"?zb:Vb;if(o==="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:ch,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=hh(o,s,d.length);T&&w.appendChild(T),n.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,n.appendChild(w)}}return n},xh=(e,r)=>{var n,s;let o=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");o.setAttribute("data-ask-free-text-row","true");let a=document.createElement("input");if(a.type="text",a.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",a.placeholder=(n=e.freeTextPlaceholder)!=null?n:ch,a.setAttribute("data-ask-free-text-input","true"),o.appendChild(a),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:ph,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},n0=e=>{var o;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=(o=e.submitLabel)!=null?o:ph,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,r.appendChild(t),r},a0=(e,r,t)=>{var l,u,p,m;let o=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let a=x("button","persona-ask-nav-back persona-pointer-events-auto");a.type="button",a.textContent=(l=t.backLabel)!=null?l:Gb,a.setAttribute("data-ask-user-action","back"),a.disabled=e===0,o.appendChild(a);let n=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:Jb,s.setAttribute("data-ask-user-action","skip"),n.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:Xb:(m=t.nextLabel)!=null?m:jb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,n.appendChild(i),o.appendChild(n),o},aa=e=>{let r=e.getAttribute(uh);if(!r)return{};try{let t=JSON.parse(r);return t&&typeof t=="object"?t:{}}catch{return{}}},yh=(e,r)=>{e.setAttribute(uh,JSON.stringify(r))},Ao=e=>{var t;let r=Number((t=e.getAttribute(yp))!=null?t:"0");return Number.isFinite(r)?Math.max(0,Math.floor(r)):0},s0=(e,r)=>{e.setAttribute(yp,String(Math.max(0,Math.floor(r))))},Ia=e=>{var t;let r=Number((t=e.getAttribute(bp))!=null?t:"1");return Number.isFinite(r)?Math.max(1,Math.floor(r)):1},Mn=e=>e.getAttribute(Cp)==="true",i0=(e,r)=>{var a;let t=(a=e.agentMetadata)==null?void 0:a.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let o={};return r.forEach((n,s)=>{let i=typeof(n==null?void 0:n.question)=="string"?n.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(o[s]=d)}}),o},l0=(e,r)=>{var o;let t=(o=e.agentMetadata)==null?void 0:o.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}=ln(r),o=Is(t),a=aa(e),n={},s=new Set;return o.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(a,d)&&(n[l]=a[d]))}),n},bh=e=>{let r=aa(e),t=Ao(e),o=r[t],a=new Set;typeof o=="string"?a.add(o):Array.isArray(o)&&o.forEach(d=>a.add(d));let n=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');n.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=a.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(n).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 o=="string"&&o.length>0&&!s.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Ch=e=>{if(!Mn(e))return;let r=aa(e),t=Ao(e),o=r[t],a=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,n=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');n&&(n.disabled=!a);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}},wp=(e,r,t)=>{let o=ul(t),a=Qb(e),{payload:n,complete:s}=ln(r),i=Mn(e),d=Ao(e),l=Ia(e),u=i?e0(n,d):Zb(n),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=o0(u,o,s,a);v.replaceWith(A)}if(a!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(xh(o,a))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(n0(o)):(!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=a0(d,l,o);T?T.replaceWith(A):e.appendChild(A)}else T&&T.remove();bh(e),Ch(e)},d0=(e,r,t)=>{let o=ul(r),a=Yb(o),n=e.toolCall.id,s=Is(t),i=Math.max(1,s.length),d=i>1,l=i0(e,s),u=d?l0(e,i):0,p=x("div",["persona-ask-sheet",`persona-ask-sheet--${a}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Pa,n),p.setAttribute("data-tool-call-id",n),p.setAttribute("data-message-id",e.id),p.setAttribute(bp,String(i)),p.setAttribute(yp,String(u)),p.setAttribute(Cp,d?"true":"false"),p.setAttribute(fh,a),yh(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),gh(p,o);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",a==="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),a!=="rows"&&p.appendChild(xh(o,a)),wp(p,e,r),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},c0=(e,r,t)=>{let{payload:o}=ln(r),a=Math.max(1,Is(o).length);a>Ia(e)&&(e.setAttribute(bp,String(a)),a>1&&!Mn(e)&&e.setAttribute(Cp,"true")),wp(e,r,t)},wh=(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 o=ul(r);gh(t,o);let a=x("span","persona-ask-stub-label"),{complete:n}=ln(e);return a.textContent=n?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(a),t},Ra=(e,r,t)=>{if(!t||!sn(e)||ul(r).enabled===!1)return;let a=e.toolCall.id;t.querySelectorAll(`[${Pa}]`).forEach(l=>{l.getAttribute(Pa)!==a&&l.remove()});let s=t.querySelector(`[${Pa}="${mh(a)}"]`);if(s){c0(s,e,r);return}let{payload:i}=ln(e),d=d0(e,r,i);t.appendChild(d)},Ln=(e,r)=>{if(!e)return;let t=r?`[${Pa}="${mh(r)}"]`:`[${Pa}]`;e.querySelectorAll(t).forEach(a=>{a.classList.add("persona-ask-sheet-leave");let n=Number.parseInt(getComputedStyle(a).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>a.remove(),Number.isFinite(n)?n:180)})},vp=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),Pn=(e,r)=>{let t=aa(e),o=Ao(e);typeof r=="string"&&r.length===0||Array.isArray(r)&&r.length===0?delete t[o]:t[o]=r,yh(e,t),bh(e),Ch(e)},ml=(e,r,t,o)=>{let a=Ia(e),n=Math.max(0,Math.min(a-1,o));s0(e,n),wp(e,r,t)};var Ap=(e,r)=>{var v,k,T,A,E,b,h,S,L,O,H,R;let t=e.approval,o=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,a=(t==null?void 0:t.status)==="pending",n=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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.style.backgroundColor=(v=o==null?void 0:o.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",n.style.borderColor=(k=o==null?void 0:o.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return n;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=o==null?void 0:o.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(o!=null&&o.titleColor&&(f.style.color=o.titleColor),f.textContent=(A=o==null?void 0:o.title)!=null?A:"Approval Required",m.appendChild(f),!a){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(o!=null&&o.descriptionColor&&(w.style.color=o.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");o!=null&&o.parameterBackgroundColor&&(B.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(B.style.color=o.parameterTextColor),B.style.fontSize="0.75rem",B.style.lineHeight="1rem",B.textContent=ba(t.parameters),p.appendChild(B)}if(a){let B=x("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let V=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");V.type="button",V.style.backgroundColor=(E=o==null?void 0:o.approveButtonColor)!=null?E:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(b=o==null?void 0:o.approveButtonTextColor)!=null?b:"#ffffff",V.setAttribute("data-approval-action","approve");let oe=Ce("shield-check",14,(h=o==null?void 0:o.approveButtonTextColor)!=null?h:"#ffffff",2);oe&&(oe.style.marginRight="4px",V.appendChild(oe));let fe=document.createTextNode((S=o==null?void 0:o.approveLabel)!=null?S:"Approve");V.appendChild(fe);let _e=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");_e.type="button",_e.style.backgroundColor=(L=o==null?void 0:o.denyButtonColor)!=null?L:"transparent",_e.style.color=(O=o==null?void 0:o.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",_e.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,_e.setAttribute("data-approval-action","deny");let je=Ce("shield-x",14,(H=o==null?void 0:o.denyButtonTextColor)!=null?H:"var(--persona-feedback-error, #dc2626)",2);je&&(je.style.marginRight="4px",_e.appendChild(je));let ye=document.createTextNode((R=o==null?void 0:o.denyLabel)!=null?R:"Deny");_e.appendChild(ye),B.append(V,_e),p.appendChild(B)}return s.append(i,p),n.appendChild(s),n};var vh=e=>{let r=[];return{buttons:r,render:(o,a,n,s,i)=>{if(e.innerHTML="",r.length=0,!o||!o.length||(s!=null?s:a?a.getMessages():[]).some(f=>f.role==="user"))return;let u=document.createDocumentFragment(),p=a?a.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'}};o.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",()=>{!a||a.isStreaming()||(n.value="",a.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 o of t)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.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 o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let a=o.result;a.objectStoreNames.contains(this.storeName)||a.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,r()},o.onerror=()=>{t(o.error)}}catch(o){t(o)}})}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 o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let a of r)o.put(a)}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(o){t(o)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let n=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();n.onsuccess=()=>{r(n.result)},n.onerror=()=>{t(n.error)}}catch(o){t(o)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(o){t(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(o){t(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let a of r)o.put(a)}catch{}}};function Ha(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var p0={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)"}},u0={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},f0=["flowName","stepName","reasoningText","text","name","tool","toolName"],m0=100;function g0(e,r){let t={...p0,...r};if(t[e])return t[e];for(let o of Object.keys(t))if(o.endsWith("_")&&e.startsWith(o))return t[o];return u0}function h0(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function x0(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),o=String(r.getMinutes()).padStart(2,"0"),a=String(r.getSeconds()).padStart(2,"0"),n=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${o}:${a}.${n}`}function y0(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let o of r){let a=o.split("."),n=t;for(let s of a)if(n&&typeof n=="object"&&n!==null)n=n[s];else{n=void 0;break}if(typeof n=="string"&&n.trim())return n.trim()}}catch{}return null}function b0(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),t()})}function C0(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 w0(e,r,t){let o,a;try{a=JSON.parse(e.payload),o=JSON.stringify(a,null,2)}catch{a=e.payload,o=e.payload}let n=r.find(i=>i.renderEventStreamPayload);if(n!=null&&n.renderEventStreamPayload&&t){let i=n.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>s(),parsedPayload:a});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=o,i.appendChild(d),i}}function Sp(e,r,t,o,a,n,s,i){var m;let d=a.has(e.id),l=x("div","persona-border-b persona-border-persona-divider persona-text-xs");Ha(l,(m=o.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:()=>n(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(p()),l;function p(){var V,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=(V=o.timestampFormat)!=null?V:"relative";T.textContent=A==="relative"?h0(e.timestamp,t):x0(e.timestamp);let E=null;o.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=g0(e.type,o.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=o.descriptionFields)!=null?oe:f0,L=y0(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 fe=>{fe.stopPropagation(),await b0(C0(e)),R.innerHTML="";let _e=Ce("check","12px","currentColor",1.5);_e&&R.appendChild(_e),setTimeout(()=>{R.innerHTML="";let je=Ce("clipboard","12px","currentColor",1.5);je&&R.appendChild(je)},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(w0(e,s,i)),f}}function Ah(e){var f,w,v,k,T;let{buffer:r,getFullHistory:t,onClose:o,config:a,plugins:n=[]}=e,s=(f=a==null?void 0:a.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=a==null?void 0:a.features)==null?void 0:k.eventStream)!=null?T:{},p=n.find(A=>A.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&a){let A=p.renderEventStreamView({config:a,events:r.getAll(),defaultRenderer:()=>m().element,onClose:o});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(),V=0,oe=0,fe=!1,_e=null,je=!1,ye=0,me=new Set,Pe=new Map,Ve="",Q="",Ae=null,J,de,pe,se,Be;function Ee(){let N=x("div","persona-flex persona-flex-col persona-flex-shrink-0"),le=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(le,A==null?void 0:A.headerBar);let Te=x("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Te.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 ct=x("div","persona-flex-1");de=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 Ke=x("option","");Ke.value="",Ke.textContent="All events",de.appendChild(Ke),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 nr=Ce("clipboard-copy","12px","currentColor",1.5);nr&&pe.appendChild(nr);let Lt=x("span","persona-text-xs");Lt.textContent="Copy All",pe.appendChild(Lt),le.appendChild(Te),le.appendChild(J),le.appendChild(ct),le.appendChild(de),le.appendChild(pe);let vt=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ha(vt,A==null?void 0:A.searchBar);let Ze=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),at=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");Ze&&at.appendChild(Ze),se=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(se,A==null?void 0:A.searchInput),se.type="text",se.placeholder="Search event payloads...",Be=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"),Be.type="button",Be.style.display="none";let tr=Ce("x","12px","currentColor",2);return tr&&Be.appendChild(tr),vt.appendChild(at),vt.appendChild(se),vt.appendChild(Be),N.appendChild(le),N.appendChild(vt),N}let K,Oe=n.find(N=>N.renderEventStreamToolbar);if(Oe!=null&&Oe.renderEventStreamToolbar&&a){let N=Oe.renderEventStreamToolbar({config:a,defaultRenderer:()=>Ee(),eventCount:r.getSize(),filteredCount:0,onFilterChange:le=>{h=le,$e(),Yt()},onSearchChange:le=>{S=le,$e(),Yt()}});K=N!=null?N:Ee()}else K=Ee();let Fe=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");Fe.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 ue=Ce(d,"14px","currentColor",2);ue&&we.appendChild(ue);let re=x("span","");re.textContent=l,we.appendChild(re);let he=x("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");he.style.display="none",Y.appendChild(G),Y.appendChild(he),Y.appendChild(we),E.setAttribute("tabindex","0"),E.appendChild(K),E.appendChild(Fe),E.appendChild(Y);function Je(){let N=r.getAll(),le={};for(let Lt of N)le[Lt.type]=(le[Lt.type]||0)+1;let Te=Object.keys(le).sort(),ct=Te.length!==O.length||!Te.every((Lt,vt)=>Lt===O[vt]),Ke=!ct&&Te.some(Lt=>le[Lt]!==H[Lt]),$t=N.length!==Object.values(H).reduce((Lt,vt)=>Lt+vt,0);if(!ct&&!Ke&&!$t||(O=Te,H=le,!de))return;let nr=de.value;if(de.options[0].textContent="All events",ct){for(;de.options.length>1;)de.remove(1);for(let Lt of Te){let vt=x("option","");vt.value=Lt,vt.textContent=`${Lt} (${le[Lt]||0})`,de.appendChild(vt)}nr&&Te.includes(nr)?de.value=nr:nr&&(de.value="",h="")}else for(let Lt=1;Lt<de.options.length;Lt++){let vt=de.options[Lt];vt.textContent=`${vt.value} (${le[vt.value]||0})`}}function Ot(){let N=r.getAll();if(h&&(N=N.filter(le=>le.type===h)),S){let le=S.toLowerCase();N=N.filter(Te=>Te.type.toLowerCase().includes(le)||Te.payload.toLowerCase().includes(le))}return N}function ce(){return h!==""||S!==""}function $e(){R=0,V=0,B.resume(),we.style.display="none"}function fr(N){me.has(N)?me.delete(N):me.add(N),Ae=N;let le=G.scrollTop,Te=B.isFollowing();je=!0,B.pause(),Yt(),G.scrollTop=le,Te&&B.resume(),je=!1}function Wt(){return ws(G,50)}function Yt(){oe=Date.now(),fe=!1,Je();let N=r.getEvictedCount();N>0?(Fe.textContent=`${N.toLocaleString()} older events truncated`,Fe.style.display=""):Fe.style.display="none",b=Ot();let le=b.length,Te=r.getSize()>0;J&&(J.textContent=String(r.getSize())),le===0&&Te&&ce()?(he.textContent=S?`No events matching '${S}'`:"No events matching filter",he.style.display="",G.style.display="none"):(he.style.display="none",G.style.display=""),pe&&(pe.title=ce()?`Copy Filtered (${le})`:"Copy All"),i&&!B.isFollowing()&&le>R&&(V+=le-R,re.textContent=l?`${l}${V>0?` (${V})`:""}`:"",we.style.display=""),R=le;let ct=r.getAll(),Ke=ct.length>0?ct[0].timestamp:0,$t=new Set(b.map(vt=>vt.id));for(let vt of me)$t.has(vt)||me.delete(vt);let nr=h!==Ve||S!==Q,Lt=Pe.size===0&&b.length>0;if(nr||Lt||b.length===0){G.innerHTML="",Pe.clear();let vt=document.createDocumentFragment();for(let Ze=0;Ze<b.length;Ze++){let at=Sp(b[Ze],Ze,Ke,u,me,fr,n,a);Pe.set(b[Ze].id,at),vt.appendChild(at)}G.appendChild(vt),Ve=h,Q=S,Ae=null}else{if(Ae!==null){let Ze=Pe.get(Ae);if(Ze&&Ze.parentNode===G){let at=b.findIndex(tr=>tr.id===Ae);if(at>=0){let tr=Sp(b[at],at,Ke,u,me,fr,n,a);G.insertBefore(tr,Ze),Ze.remove(),Pe.set(Ae,tr)}}Ae=null}let vt=new Set(b.map(Ze=>Ze.id));for(let[Ze,at]of Pe)vt.has(Ze)||(at.remove(),Pe.delete(Ze));for(let Ze=0;Ze<b.length;Ze++){let at=b[Ze];if(!Pe.has(at.id)){let tr=Sp(at,Ze,Ke,u,me,fr,n,a);Pe.set(at.id,tr),G.appendChild(tr)}}}B.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Fr(){if(Date.now()-oe>=m0){_e!==null&&(cancelAnimationFrame(_e),_e=null),Yt();return}fe||(fe=!0,_e=requestAnimationFrame(()=>{_e=null,Yt()}))}let Ar=(N,le)=>{if(!pe)return;pe.innerHTML="";let Te=Ce(N,"12px","currentColor",1.5);Te&&pe.appendChild(Te);let ct=x("span","persona-text-xs");ct.textContent="Copy All",pe.appendChild(ct),setTimeout(()=>{pe.innerHTML="";let Ke=Ce("clipboard-copy","12px","currentColor",1.5);Ke&&pe.appendChild(Ke);let $t=x("span","persona-text-xs");$t.textContent="Copy All",pe.appendChild($t),pe.disabled=!1},le)},F=async()=>{if(pe){pe.disabled=!0;try{let N;ce()?N=b:t?(N=await t(),N.length===0&&(N=r.getAll())):N=r.getAll();let le=N.map(Te=>{try{return JSON.parse(Te.payload)}catch{return Te.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),Ar("check",1500)}catch{Ar("x",1500)}}},ie=()=>{de&&(h=de.value,$e(),Yt())},We=()=>{!se||!Be||(Be.style.display=se.value?"":"none",L&&clearTimeout(L),L=setTimeout(()=>{S=se.value,$e(),Yt()},150))},Xe=()=>{!se||!Be||(se.value="",S="",Be.style.display="none",L&&clearTimeout(L),$e(),Yt())},Ne=()=>{if(je)return;let N=G.scrollTop,{action:le,nextLastScrollTop:Te}=Ki({following:B.isFollowing(),currentScrollTop:N,lastScrollTop:ye,nearBottom:Wt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=Te,le==="resume"?(B.resume(),V=0,we.style.display="none"):le==="pause"&&(B.pause(),i&&(re.textContent=l,we.style.display=""))},Ue=N=>{let le=Yi({following:B.isFollowing(),deltaY:N.deltaY,nearBottom:Wt(),resumeWhenNearBottom:!0});le==="pause"?(B.pause(),i&&(re.textContent=l,we.style.display="")):le==="resume"&&(B.resume(),V=0,we.style.display="none")},tt=()=>{i&&(G.scrollTop=G.scrollHeight,B.resume(),V=0,we.style.display="none")},yt=N=>{let le=N.target;if(!le||le.closest("button"))return;let Te=le.closest("[data-event-id]");if(!Te)return;let ct=Te.getAttribute("data-event-id");ct&&fr(ct)},Mt=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),se==null||se.focus(),se==null||se.select();return}N.key==="Escape"&&(se&&document.activeElement===se?(Xe(),se.blur(),E.focus()):o&&o())};pe&&pe.addEventListener("click",F),de&&de.addEventListener("change",ie),se&&se.addEventListener("input",We),Be&&Be.addEventListener("click",Xe),G.addEventListener("scroll",Ne),G.addEventListener("wheel",Ue,{passive:!0}),G.addEventListener("click",yt),we.addEventListener("click",tt),E.addEventListener("keydown",Mt);function _t(){L&&clearTimeout(L),_e!==null&&(cancelAnimationFrame(_e),_e=null),fe=!1,Pe.clear(),pe&&pe.removeEventListener("click",F),de&&de.removeEventListener("change",ie),se&&se.removeEventListener("input",We),Be&&Be.removeEventListener("click",Xe),G.removeEventListener("scroll",Ne),G.removeEventListener("wheel",Ue),G.removeEventListener("click",yt),we.removeEventListener("click",tt),E.removeEventListener("keydown",Mt)}return{element:E,update:Fr,destroy:_t}}}function Sh(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",a=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`),o&&i.setAttribute("data-open-artifact",o);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)",a==="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),a==="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",o),i.append(m)}return i}var Th=(e,r)=>{var o,a,n;let t=(n=(a=(o=r==null?void 0:r.config)==null?void 0:o.features)==null?void 0:a.artifacts)==null?void 0:n.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:()=>Sh(e,r)});if(u)return u}return Sh(e,r)};var Tp=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,o])=>{this.register(t,o)})}},dn=new Tp;dn.register("PersonaArtifactCard",Th);function v0(e){var a;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 o=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((a=e.props)!=null?a:{},null,2),r.appendChild(t),r.appendChild(o),r}function kh(e,r){var pe,se,Be,Ee;let t=(se=(pe=e.features)==null?void 0:pe.artifacts)==null?void 0:se.layout,a=((Be=t==null?void 0:t.toolbarPreset)!=null?Be:"default")==="document",n=(Ee=t==null?void 0:t.panePadding)==null?void 0:Ee.trim(),s=e.markdown?Xn(e.markdown):null,i=ya(e.sanitize),d=K=>{let Oe=s?s(K):Jn(K);return i?i(Oe):Oe},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"),a&&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"),a&&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=a?Qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Qt({icon:"eye",label:"Rendered view"}),A=a?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(a&&(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 a&&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)):a?H=Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=Qt({icon:"copy",label:"Copy"});let V=a?Qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"refresh-cw",label:"Refresh"}),oe=a?Qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"x",label:"Close"}),fe=()=>{var G,we,ue;let K=(G=Ve.find(re=>re.id===Q))!=null?G:Ve[Ve.length-1],Oe=(we=K==null?void 0:K.id)!=null?we:null,Fe=(K==null?void 0:K.artifactType)==="markdown"&&(ue=K.markdown)!=null?ue:"",Y=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Fe,jsonPayload:Y,id:Oe}},_e=async()=>{var G;let{markdown:K,jsonPayload:Oe}=fe(),Fe=(G=Ve.find(we=>we.id===Q))!=null?G:Ve[Ve.length-1],Y=(Fe==null?void 0:Fe.artifactType)==="markdown"?K:Fe?Oe:"";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:Oe,jsonPayload:Fe,id:Y}=fe();try{await K({actionId:"primary",artifactId:Y,markdown:Oe,jsonPayload:Fe})}catch{}return}await _e()}),R&&(S!=null&&S.length)){let K=()=>{var Fe;return(Fe=p.closest("[data-persona-root]"))!=null?Fe:document.body},Oe=()=>{B=kn({items:S.map(Fe=>({id:Fe.id,label:Fe.label})),onSelect:async Fe=>{let{markdown:Y,jsonPayload:G,id:we}=fe(),ue=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ue?await ue({actionId:Fe,artifactId:we,markdown:Y,jsonPayload:G}):Fe==="markdown"||Fe==="md"?await navigator.clipboard.writeText(Y):Fe==="json"||Fe==="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?Oe():requestAnimationFrame(Oe),R.addEventListener("click",Fe=>{Fe.stopPropagation(),B==null||B.toggle()})}V.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 je=()=>{a&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),A.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",je(),J()}),A.addEventListener("click",()=>{v="source",je(),J()});let ye=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");a?(m.replaceChildren(),k.append(T,A),O?E.append(O,V,oe):E.append(H,V,oe),m.append(k,ye,E),je()):(m.appendChild(f),m.appendChild(w)),n&&(m.style.paddingLeft=n,m.style.paddingRight=n);let me=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"),Pe=x("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");n&&(me.style.paddingLeft=n,me.style.paddingRight=n,Pe.style.padding=n),p.appendChild(m),p.appendChild(me),p.appendChild(Pe);let Ve=[],Q=null,Ae=!1,J=()=>{var Y,G,we,ue;let K=a&&Ve.length<=1;me.classList.toggle("persona-hidden",K),me.replaceChildren();for(let re of Ve){let he=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");he.type="button",he.textContent=re.title||re.id.slice(0,8),re.id===Q&&he.classList.add("persona-bg-persona-container","persona-border-persona-border"),he.addEventListener("click",()=>r.onSelect(re.id)),me.appendChild(he)}Pe.replaceChildren();let Oe=Q&&Ve.find(re=>re.id===Q)||Ve[Ve.length-1];if(!Oe)return;if(a){let re=Oe.artifactType==="markdown"?"MD":(Y=Oe.component)!=null?Y:"Component",Je=(Oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ye.textContent=`${Je} \xB7 ${re}`}else f.textContent="Artifacts";if(Oe.artifactType==="markdown"){if(a&&v==="source"){let he=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");he.textContent=(G=Oe.markdown)!=null?G:"",Pe.appendChild(he);return}let re=x("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");re.innerHTML=d((we=Oe.markdown)!=null?we:""),Pe.appendChild(re);return}let Fe=Oe.component?dn.get(Oe.component):void 0;if(Fe){let he={message:{id:Oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Je=Fe((ue=Oe.props)!=null?ue:{},he);if(Je){Pe.appendChild(Je);return}}catch{}}Pe.appendChild(v0(Oe))},de=()=>{var Oe;let K=Ve.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Fe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,G=((Oe=Fe==null?void 0:Fe.classList.contains("persona-artifact-narrow-host"))!=null?Oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&G&&Ae?(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 Oe,Fe,Y;Ve=K.artifacts,Q=(Y=(Fe=K.selectedId)!=null?Fe:(Oe=K.artifacts[K.artifacts.length-1])==null?void 0:Oe.id)!=null?Y:null,Ve.length>0&&(Ae=!0),J(),de()},setMobileOpen(K){Ae=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):de()}}}function So(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 Eh(e,r){var n,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"),!So(r))return;let t=(s=(n=r.features)==null?void 0:n.artifacts)==null?void 0:s.layout,o=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),a=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):a&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",a))}function A0(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(!So(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"),A0(e),Eh(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 o=(f=t==null?void 0:t.paneBackground)==null?void 0:f.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let a=(w=t==null?void 0:t.panePadding)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let n=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();n?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",n):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"),Eh(e,r)}var Mh=["panel","seamless"];function hl(e,r){var i,d,l,u,p,m;for(let f of Mh)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"),!So(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",a=Mh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${a}`);let n=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();n&&e.style.setProperty("--persona-artifact-pane-radius",n);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())||n;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Lh(e,r){var t,o,a;return!r||!So(e)?!1:((a=(o=(t=e.features)==null?void 0:t.artifacts)==null?void 0:o.layout)==null?void 0:a.expandLauncherPanelWhenOpen)!==!1}function S0(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 T0(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 k0(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function E0(e,r,t,o){let a=e-o-2*r-t;return Math.max(0,a)}function Ph(e,r){var s;let o=(s=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",a=/^([\d.]+)px$/i.exec(o);if(a)return Number(a[1]);let n=/^([\d.]+)/.exec(o);return n?Number(n[1]):8}function Ih(e,r,t,o,a,n){let s=S0(a,200),i=E0(r,t,o,200);i=Math.max(s,i);let d=T0(n);return d!==null&&(i=Math.min(i,d)),k0(e,s,i)}var Rh={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"}},kp=(e,r,t,o)=>{let a=e.querySelectorAll("[data-tv-form]");a.length&&a.forEach(n=>{var w,v,k;if(n.dataset.enhanced==="true")return;let s=(w=n.dataset.tvForm)!=null?w:"init";n.dataset.enhanced="true";let i=(v=Rh[s])!=null?v:Rh.init;n.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),n.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 o.sendMessage(String(O.nextPrompt))}catch(L){m.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ep=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 o;let t=this.plugins.get(r);t&&((o=t.onUnregister)==null||o.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var o,a;return((o=t.priority)!=null?o:0)-((a=r.priority)!=null?a:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let o=new Set(r.map(n=>n.id));return[...t.filter(n=>!o.has(n.id)),...r].sort((n,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=n.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 Ep;var Hh=()=>{let e=new Map,r=(a,n)=>(e.has(a)||e.set(a,new Set),e.get(a).add(n),()=>t(a,n)),t=(a,n)=>{var s;(s=e.get(a))==null||s.delete(n)};return{on:r,off:t,emit:(a,n)=>{var s;(s=e.get(a))==null||s.forEach(i=>{try{i(n)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var M0=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},L0=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let o=0;for(let a=t;a<r.length;a+=1){let n=r[a];if(n==="{"&&(o+=1),n==="}"&&(o-=1,o===0))return r.slice(t,a+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=M0(e),t=L0(r);if(!t)return null;let o=JSON.parse(t);if(!o||typeof o!="object"||!o.action)return null;let{action:a,...n}=o;return{type:String(a),payload:n,raw:o}}catch{return null}},Mp=e=>typeof e=="string"?e:e==null?"":String(e),sa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Mp(e.payload.text)},messageAndClick:(e,r)=>{var a;if(e.type!=="message_and_click")return;let t=e.payload,o=Mp(t.element);if(o&&((a=r.document)!=null&&a.querySelector)){let n=r.document.querySelector(o);n?setTimeout(()=>{n.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Mp(t.text)}}},Bh=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ds=e=>{let r=new Set(Bh(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Bh(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let n=Array.from(r);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!=="assistant"||!n.text||r.has(n.message.id))return null;let s=typeof n.raw=="string"&&n.raw||typeof n.message.rawContent=="string"&&n.message.rawContent||typeof n.text=="string"&&n.text||null;!s&&typeof n.text=="string"&&n.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:n.message}))||null,null):null;if(!i)return null;r.add(n.message.id),o();let d={action:i,message:n.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:n.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 P0=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}},I0=e=>e.map(r=>({...r,streaming:!1})),R0=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?P0(t.getItem(e)):null},save:t=>{let o=r();if(o)try{let a={...t,messages:t.messages?I0(t.messages):void 0,artifacts:t.artifacts?R0(t.artifacts):void 0};o.setItem(e,JSON.stringify(a))}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",a)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ba=Bl(hi(),1);function H0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function B0(e,r){if(!H0(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 o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(t.length<=r)return e;try{let a=(0,Ba.parse)(t,Ba.STR|Ba.OBJ),n=B0(a,t);n&&(e=n)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Wh(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:o,onPropsUpdate:a}=r,n=dn.get(e.component);if(!n)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:t,updateProps:i=>{a&&a(i)}};try{return n(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Dh(){let e=yl();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Cl(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function wl(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var W0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vl(e){let{onSubmit:r,onDismiss:t,title:o="How satisfied are you?",subtitle:a="Please rate your experience",commentPlaceholder:n="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=W0}=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=o,f.appendChild(w);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=a,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
|
+
`):""},zb=(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,a=(p=n==null?void 0:n.collapsedMode)!=null?p:"tool-call",o=qb(e,(m=n==null?void 0:n.previewMaxLines)!=null?m:3),s=t?kg(t):"";if(!t)return{summary:s,previewText:o,isActive:!1};let i=t.status!=="complete",d=(f=r==null?void 0:r.toolCall)!=null?f:{},l=s;return a==="tool-name"?l=((w=t.name)==null?void 0:w.trim())||s:a==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=ed(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ed(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},lh=(e,r,t)=>{var u;let n=La.has(e),a=(u=t==null?void 0:t.toolCall)!=null?u:{},o=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!s)return;o.setAttribute("aria-expanded",n?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=a.toggleTextColor||a.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")},gp=(e,r)=>{var V,ne,fe,_e,je,ye,me,Pe,Ve;let t=e.toolCall,n=(V=r==null?void 0:r.toolCall)!=null?V:{},a=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(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),n.backgroundColor&&(a.style.backgroundColor=n.backgroundColor),n.borderColor&&(a.style.borderColor=n.borderColor),n.borderWidth&&(a.style.borderWidth=n.borderWidth),n.borderRadius&&(a.style.borderRadius=n.borderRadius),!t)return a;let o=(fe=(ne=r==null?void 0:r.features)==null?void 0:ne.toolCallDisplay)!=null?fe:{},s=o.expandable!==!1,i=s&&La.has(e.id),{summary:d,previewText:l,isActive:u}=zb(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((_e=t.startedAt)!=null?_e:Date.now()),v=()=>{let Q=x("span","");return Q.setAttribute("data-tool-elapsed",w),Q.textContent=ms(t),Q},k=(ye=n.renderCollapsedSummary)==null?void 0:ye.call(n,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(je=o.collapsedMode)!=null?je:"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=(me=o.loadingAnimation)!=null?me:"none",A=n.activeTextTemplate,E=n.completeTextTemplate,b=u?A:E,h=k instanceof HTMLElement,S=(Q,Ae,J)=>{let de=J;for(let pe of Ae){let se=x("span","persona-tool-char");se.style.setProperty("--char-index",String(de)),se.textContent=pe===" "?"\xA0":pe,Q.appendChild(se),de++}return de},L=(Q,Ae)=>{var se;f.textContent="";let J=((se=t.name)==null?void 0:se.trim())||"tool",de=Ci(Q,J),pe=0;for(let Be of de){let Ee=Be.styles.length>0?(()=>{let K=x("span",Be.styles.map(Oe=>`persona-tool-text-${Oe}`).join(" "));return f.appendChild(K),K})():f;if(Be.isDuration&&u)Ee.appendChild(v());else{let K=Be.isDuration?ms(t):Be.text;Ae?pe=S(Ee,K,pe):Ee.appendChild(document.createTextNode(K))}}};if(!h)if(u&&T!=="none"){let Q=(Pe=n.loadingAnimationDuration)!=null?Pe: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 Ae=f.textContent||d;f.textContent="",S(f,Ae,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",Ae=Ce(i?"chevron-up":"chevron-down",16,Q,2);Ae?O.appendChild(Ae):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&&o.activePreview&&l){let Q=(Ve=n.renderCollapsedPreview)==null?void 0:Ve.call(n,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:r!=null?r:{}});Ub(H,Q)||(H.textContent=l),H.style.display=""}if(!i&&u&&o.activeMinHeight&&(a.style.minHeight=o.activeMinHeight),!s)return a.append(p,H),a;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"),Ae=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ae.style.color=n.labelTextColor),Ae.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(Ae,J),R.appendChild(Q)}if(t.chunks&&t.chunks.length){let Q=x("div","persona-space-y-1"),Ae=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ae.style.color=n.labelTextColor),Ae.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(Ae,J),R.appendChild(Q)}if(t.status==="complete"&&t.result!==void 0){let Q=x("div","persona-space-y-1"),Ae=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Ae.style.color=n.labelTextColor),Ae.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(Ae,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",Ae=Ce(i?"chevron-up":"chevron-down",16,Q,2);Ae?O.appendChild(Ae):O.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),a.append(p,H,R),a};var Eo=Bl(hi(),1);var xp="ask_user_question",hp=8,Pa="data-persona-ask-sheet-for",Vb="Other",jb="Other\u2026",ch="Type your own answer here",ph="Send",Gb="Next",Xb="Back",Jb="Submit all",Kb="Skip",Yb=3,yp="data-ask-current-index",bp="data-ask-question-count",uh="data-ask-answers",Cp="data-ask-grouped",fh="data-ask-layout",Qb=e=>e.layout==="pills"?"pills":"rows",Zb=e=>e.getAttribute(fh)==="pills"?"pills":"rows",dh=!1,mh=e=>e.replace(/["\\]/g,"\\$&"),so=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xp,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 a=n.join(""),o=(0,Eo.parse)(a,Eo.STR|Eo.OBJ|Eo.ARR);if(o&&typeof o=="object")return{payload:o,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>hp&&!dh&&(dh=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${r.length} questions; truncating to ${hp}.`)),r.slice(0,hp)},e0=e=>{var r;return(r=Is(e)[0])!=null?r:null},t0=(e,r)=>{var t;return(t=Is(e)[r])!=null?t:null},gh=(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))},hh=(e,r,t)=>{if(e!=="rows")return null;let n=x("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),r){let a=x("span","persona-ask-row-check");n.appendChild(a)}else{let a=x("span","persona-ask-row-badge");a.textContent=String(t+1),n.appendChild(a)}return n},r0=(e,r,t,n)=>{let o=x("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",n?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(r)),o.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)}o.appendChild(s);let d=hh(t,n,r);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},n0=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},o0=(e,r,t,n)=>{var u,p,m;let o=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");o.setAttribute("role","group"),o.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<Yb;f++)o.appendChild(n0(n));return o}if(d.forEach((f,w)=>{o.appendChild(r0(f,w,n,s))}),(e==null?void 0:e.allowFreeText)!==!1){let f=n==="rows"?Vb:jb;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:ch,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=hh(n,s,d.length);T&&w.appendChild(T),o.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,o.appendChild(w)}}return o},xh=(e,r)=>{var o,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 a=document.createElement("input");if(a.type="text",a.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",a.placeholder=(o=e.freeTextPlaceholder)!=null?o:ch,a.setAttribute("data-ask-free-text-input","true"),n.appendChild(a),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:ph,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},a0=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:ph,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,r.appendChild(t),r},s0=(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 a=x("button","persona-ask-nav-back persona-pointer-events-auto");a.type="button",a.textContent=(l=t.backLabel)!=null?l:Xb,a.setAttribute("data-ask-user-action","back"),a.disabled=e===0,n.appendChild(a);let o=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:Kb,s.setAttribute("data-ask-user-action","skip"),o.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:Jb:(m=t.nextLabel)!=null?m:Gb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),n.appendChild(o),n},aa=e=>{let r=e.getAttribute(uh);if(!r)return{};try{let t=JSON.parse(r);return t&&typeof t=="object"?t:{}}catch{return{}}},yh=(e,r)=>{e.setAttribute(uh,JSON.stringify(r))},An=e=>{var t;let r=Number((t=e.getAttribute(yp))!=null?t:"0");return Number.isFinite(r)?Math.max(0,Math.floor(r)):0},i0=(e,r)=>{e.setAttribute(yp,String(Math.max(0,Math.floor(r))))},Ia=e=>{var t;let r=Number((t=e.getAttribute(bp))!=null?t:"1");return Number.isFinite(r)?Math.max(1,Math.floor(r)):1},Mo=e=>e.getAttribute(Cp)==="true",l0=(e,r)=>{var a;let t=(a=e.agentMetadata)==null?void 0:a.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let n={};return r.forEach((o,s)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(n[s]=d)}}),n},d0=(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),a=aa(e),o={},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(a,d)&&(o[l]=a[d]))}),o},bh=e=>{let r=aa(e),t=An(e),n=r[t],a=new Set;typeof n=="string"?a.add(n):Array.isArray(n)&&n.forEach(d=>a.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=a.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(o).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=""},Ch=e=>{if(!Mo(e))return;let r=aa(e),t=An(e),n=r[t],a=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!a);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}},wp=(e,r,t)=>{let n=ul(t),a=Zb(e),{payload:o,complete:s}=io(r),i=Mo(e),d=An(e),l=Ia(e),u=i?t0(o,d):e0(o),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=o0(u,n,s,a);v.replaceWith(A)}if(a!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(xh(n,a))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(a0(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=s0(d,l,n);T?T.replaceWith(A):e.appendChild(A)}else T&&T.remove();bh(e),Ch(e)},c0=(e,r,t)=>{let n=ul(r),a=Qb(n),o=e.toolCall.id,s=Is(t),i=Math.max(1,s.length),d=i>1,l=l0(e,s),u=d?d0(e,i):0,p=x("div",["persona-ask-sheet",`persona-ask-sheet--${a}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Pa,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(bp,String(i)),p.setAttribute(yp,String(u)),p.setAttribute(Cp,d?"true":"false"),p.setAttribute(fh,a),yh(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`),gh(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",a==="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),a!=="rows"&&p.appendChild(xh(n,a)),wp(p,e,r),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},p0=(e,r,t)=>{let{payload:n}=io(r),a=Math.max(1,Is(n).length);a>Ia(e)&&(e.setAttribute(bp,String(a)),a>1&&!Mo(e)&&e.setAttribute(Cp,"true")),wp(e,r,t)},wh=(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);gh(t,n);let a=x("span","persona-ask-stub-label"),{complete:o}=io(e);return a.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(a),t},Ra=(e,r,t)=>{if(!t||!so(e)||ul(r).enabled===!1)return;let a=e.toolCall.id;t.querySelectorAll(`[${Pa}]`).forEach(l=>{l.getAttribute(Pa)!==a&&l.remove()});let s=t.querySelector(`[${Pa}="${mh(a)}"]`);if(s){p0(s,e,r);return}let{payload:i}=io(e),d=c0(e,r,i);t.appendChild(d)},Lo=(e,r)=>{if(!e)return;let t=r?`[${Pa}="${mh(r)}"]`:`[${Pa}]`;e.querySelectorAll(t).forEach(a=>{a.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(a).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>a.remove(),Number.isFinite(o)?o:180)})},vp=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,yh(e,t),bh(e),Ch(e)},ml=(e,r,t,n)=>{let a=Ia(e),o=Math.max(0,Math.min(a-1,n));i0(e,o),wp(e,r,t)};var Ap=(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,a=(t==null?void 0:t.status)==="pending",o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(v=n==null?void 0:n.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(k=n==null?void 0:n.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return o;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),!a){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(a){let B=x("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let V=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");V.type="button",V.style.backgroundColor=(E=n==null?void 0:n.approveButtonColor)!=null?E:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(b=n==null?void 0:n.approveButtonTextColor)!=null?b:"#ffffff",V.setAttribute("data-approval-action","approve");let ne=Ce("shield-check",14,(h=n==null?void 0:n.approveButtonTextColor)!=null?h:"#ffffff",2);ne&&(ne.style.marginRight="4px",V.appendChild(ne));let fe=document.createTextNode((S=n==null?void 0:n.approveLabel)!=null?S:"Approve");V.appendChild(fe);let _e=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");_e.type="button",_e.style.backgroundColor=(L=n==null?void 0:n.denyButtonColor)!=null?L:"transparent",_e.style.color=(O=n==null?void 0:n.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",_e.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,_e.setAttribute("data-approval-action","deny");let je=Ce("shield-x",14,(H=n==null?void 0:n.denyButtonTextColor)!=null?H:"var(--persona-feedback-error, #dc2626)",2);je&&(je.style.marginRight="4px",_e.appendChild(je));let ye=document.createTextNode((R=n==null?void 0:n.denyLabel)!=null?R:"Deny");_e.appendChild(ye),B.append(V,_e),p.appendChild(B)}return s.append(i,p),o.appendChild(s),o};var vh=e=>{let r=[];return{buttons:r,render:(n,a,o,s,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(s!=null?s:a?a.getMessages():[]).some(f=>f.role==="user"))return;let u=document.createDocumentFragment(),p=a?a.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",()=>{!a||a.isStreaming()||(o.value="",a.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 a=n.result;a.objectStoreNames.contains(this.storeName)||a.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 a of r)n.put(a)}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 o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.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 a of r)n.put(a)}catch{}}};function Ha(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var u0={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)"}},f0={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},m0=["flowName","stepName","reasoningText","text","name","tool","toolName"],g0=100;function h0(e,r){let t={...u0,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return f0}function x0(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function y0(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),a=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${a}.${o}`}function b0(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let a=n.split("."),o=t;for(let s of a)if(o&&typeof o=="object"&&o!==null)o=o[s];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function C0(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 w0(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 v0(e,r,t){let n,a;try{a=JSON.parse(e.payload),n=JSON.stringify(a,null,2)}catch{a=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>s(),parsedPayload:a});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 Sp(e,r,t,n,a,o,s,i){var m;let d=a.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:()=>o(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(p()),l;function p(){var V,ne;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=(V=n.timestampFormat)!=null?V:"relative";T.textContent=A==="relative"?x0(e.timestamp,t):y0(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=h0(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=(ne=n.descriptionFields)!=null?ne:m0,L=b0(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 fe=>{fe.stopPropagation(),await C0(w0(e)),R.innerHTML="";let _e=Ce("check","12px","currentColor",1.5);_e&&R.appendChild(_e),setTimeout(()=>{R.innerHTML="";let je=Ce("clipboard","12px","currentColor",1.5);je&&R.appendChild(je)},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(v0(e,s,i)),f}}function Ah(e){var f,w,v,k,T;let{buffer:r,getFullHistory:t,onClose:n,config:a,plugins:o=[]}=e,s=(f=a==null?void 0:a.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=a==null?void 0:a.features)==null?void 0:k.eventStream)!=null?T:{},p=o.find(A=>A.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&a){let A=p.renderEventStreamView({config:a,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(),V=0,ne=0,fe=!1,_e=null,je=!1,ye=0,me=new Set,Pe=new Map,Ve="",Q="",Ae=null,J,de,pe,se,Be;function Ee(){let N=x("div","persona-flex persona-flex-col persona-flex-shrink-0"),le=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(le,A==null?void 0:A.headerBar);let Te=x("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Te.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 ct=x("div","persona-flex-1");de=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 Ke=x("option","");Ke.value="",Ke.textContent="All events",de.appendChild(Ke),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 Lt=x("span","persona-text-xs");Lt.textContent="Copy All",pe.appendChild(Lt),le.appendChild(Te),le.appendChild(J),le.appendChild(ct),le.appendChild(de),le.appendChild(pe);let vt=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ha(vt,A==null?void 0:A.searchBar);let Ze=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),at=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");Ze&&at.appendChild(Ze),se=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(se,A==null?void 0:A.searchInput),se.type="text",se.placeholder="Search event payloads...",Be=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"),Be.type="button",Be.style.display="none";let tr=Ce("x","12px","currentColor",2);return tr&&Be.appendChild(tr),vt.appendChild(at),vt.appendChild(se),vt.appendChild(Be),N.appendChild(le),N.appendChild(vt),N}let K,Oe=o.find(N=>N.renderEventStreamToolbar);if(Oe!=null&&Oe.renderEventStreamToolbar&&a){let N=Oe.renderEventStreamToolbar({config:a,defaultRenderer:()=>Ee(),eventCount:r.getSize(),filteredCount:0,onFilterChange:le=>{h=le,$e(),Yt()},onSearchChange:le=>{S=le,$e(),Yt()}});K=N!=null?N:Ee()}else K=Ee();let Fe=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");Fe.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 ue=Ce(d,"14px","currentColor",2);ue&&we.appendChild(ue);let re=x("span","");re.textContent=l,we.appendChild(re);let he=x("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");he.style.display="none",Y.appendChild(G),Y.appendChild(he),Y.appendChild(we),E.setAttribute("tabindex","0"),E.appendChild(K),E.appendChild(Fe),E.appendChild(Y);function Je(){let N=r.getAll(),le={};for(let Lt of N)le[Lt.type]=(le[Lt.type]||0)+1;let Te=Object.keys(le).sort(),ct=Te.length!==O.length||!Te.every((Lt,vt)=>Lt===O[vt]),Ke=!ct&&Te.some(Lt=>le[Lt]!==H[Lt]),Ut=N.length!==Object.values(H).reduce((Lt,vt)=>Lt+vt,0);if(!ct&&!Ke&&!Ut||(O=Te,H=le,!de))return;let or=de.value;if(de.options[0].textContent="All events",ct){for(;de.options.length>1;)de.remove(1);for(let Lt of Te){let vt=x("option","");vt.value=Lt,vt.textContent=`${Lt} (${le[Lt]||0})`,de.appendChild(vt)}or&&Te.includes(or)?de.value=or:or&&(de.value="",h="")}else for(let Lt=1;Lt<de.options.length;Lt++){let vt=de.options[Lt];vt.textContent=`${vt.value} (${le[vt.value]||0})`}}function Ot(){let N=r.getAll();if(h&&(N=N.filter(le=>le.type===h)),S){let le=S.toLowerCase();N=N.filter(Te=>Te.type.toLowerCase().includes(le)||Te.payload.toLowerCase().includes(le))}return N}function ce(){return h!==""||S!==""}function $e(){R=0,V=0,B.resume(),we.style.display="none"}function fr(N){me.has(N)?me.delete(N):me.add(N),Ae=N;let le=G.scrollTop,Te=B.isFollowing();je=!0,B.pause(),Yt(),G.scrollTop=le,Te&&B.resume(),je=!1}function Wt(){return ws(G,50)}function Yt(){ne=Date.now(),fe=!1,Je();let N=r.getEvictedCount();N>0?(Fe.textContent=`${N.toLocaleString()} older events truncated`,Fe.style.display=""):Fe.style.display="none",b=Ot();let le=b.length,Te=r.getSize()>0;J&&(J.textContent=String(r.getSize())),le===0&&Te&&ce()?(he.textContent=S?`No events matching '${S}'`:"No events matching filter",he.style.display="",G.style.display="none"):(he.style.display="none",G.style.display=""),pe&&(pe.title=ce()?`Copy Filtered (${le})`:"Copy All"),i&&!B.isFollowing()&&le>R&&(V+=le-R,re.textContent=l?`${l}${V>0?` (${V})`:""}`:"",we.style.display=""),R=le;let ct=r.getAll(),Ke=ct.length>0?ct[0].timestamp:0,Ut=new Set(b.map(vt=>vt.id));for(let vt of me)Ut.has(vt)||me.delete(vt);let or=h!==Ve||S!==Q,Lt=Pe.size===0&&b.length>0;if(or||Lt||b.length===0){G.innerHTML="",Pe.clear();let vt=document.createDocumentFragment();for(let Ze=0;Ze<b.length;Ze++){let at=Sp(b[Ze],Ze,Ke,u,me,fr,o,a);Pe.set(b[Ze].id,at),vt.appendChild(at)}G.appendChild(vt),Ve=h,Q=S,Ae=null}else{if(Ae!==null){let Ze=Pe.get(Ae);if(Ze&&Ze.parentNode===G){let at=b.findIndex(tr=>tr.id===Ae);if(at>=0){let tr=Sp(b[at],at,Ke,u,me,fr,o,a);G.insertBefore(tr,Ze),Ze.remove(),Pe.set(Ae,tr)}}Ae=null}let vt=new Set(b.map(Ze=>Ze.id));for(let[Ze,at]of Pe)vt.has(Ze)||(at.remove(),Pe.delete(Ze));for(let Ze=0;Ze<b.length;Ze++){let at=b[Ze];if(!Pe.has(at.id)){let tr=Sp(at,Ze,Ke,u,me,fr,o,a);Pe.set(at.id,tr),G.appendChild(tr)}}}B.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Fr(){if(Date.now()-ne>=g0){_e!==null&&(cancelAnimationFrame(_e),_e=null),Yt();return}fe||(fe=!0,_e=requestAnimationFrame(()=>{_e=null,Yt()}))}let Ar=(N,le)=>{if(!pe)return;pe.innerHTML="";let Te=Ce(N,"12px","currentColor",1.5);Te&&pe.appendChild(Te);let ct=x("span","persona-text-xs");ct.textContent="Copy All",pe.appendChild(ct),setTimeout(()=>{pe.innerHTML="";let Ke=Ce("clipboard-copy","12px","currentColor",1.5);Ke&&pe.appendChild(Ke);let Ut=x("span","persona-text-xs");Ut.textContent="Copy All",pe.appendChild(Ut),pe.disabled=!1},le)},F=async()=>{if(pe){pe.disabled=!0;try{let N;ce()?N=b:t?(N=await t(),N.length===0&&(N=r.getAll())):N=r.getAll();let le=N.map(Te=>{try{return JSON.parse(Te.payload)}catch{return Te.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),Ar("check",1500)}catch{Ar("x",1500)}}},ie=()=>{de&&(h=de.value,$e(),Yt())},We=()=>{!se||!Be||(Be.style.display=se.value?"":"none",L&&clearTimeout(L),L=setTimeout(()=>{S=se.value,$e(),Yt()},150))},Xe=()=>{!se||!Be||(se.value="",S="",Be.style.display="none",L&&clearTimeout(L),$e(),Yt())},Ne=()=>{if(je)return;let N=G.scrollTop,{action:le,nextLastScrollTop:Te}=Ki({following:B.isFollowing(),currentScrollTop:N,lastScrollTop:ye,nearBottom:Wt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=Te,le==="resume"?(B.resume(),V=0,we.style.display="none"):le==="pause"&&(B.pause(),i&&(re.textContent=l,we.style.display=""))},Ue=N=>{let le=Yi({following:B.isFollowing(),deltaY:N.deltaY,nearBottom:Wt(),resumeWhenNearBottom:!0});le==="pause"?(B.pause(),i&&(re.textContent=l,we.style.display="")):le==="resume"&&(B.resume(),V=0,we.style.display="none")},tt=()=>{i&&(G.scrollTop=G.scrollHeight,B.resume(),V=0,we.style.display="none")},yt=N=>{let le=N.target;if(!le||le.closest("button"))return;let Te=le.closest("[data-event-id]");if(!Te)return;let ct=Te.getAttribute("data-event-id");ct&&fr(ct)},Mt=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),se==null||se.focus(),se==null||se.select();return}N.key==="Escape"&&(se&&document.activeElement===se?(Xe(),se.blur(),E.focus()):n&&n())};pe&&pe.addEventListener("click",F),de&&de.addEventListener("change",ie),se&&se.addEventListener("input",We),Be&&Be.addEventListener("click",Xe),G.addEventListener("scroll",Ne),G.addEventListener("wheel",Ue,{passive:!0}),G.addEventListener("click",yt),we.addEventListener("click",tt),E.addEventListener("keydown",Mt);function $t(){L&&clearTimeout(L),_e!==null&&(cancelAnimationFrame(_e),_e=null),fe=!1,Pe.clear(),pe&&pe.removeEventListener("click",F),de&&de.removeEventListener("change",ie),se&&se.removeEventListener("input",We),Be&&Be.removeEventListener("click",Xe),G.removeEventListener("scroll",Ne),G.removeEventListener("wheel",Ue),G.removeEventListener("click",yt),we.removeEventListener("click",tt),E.removeEventListener("keydown",Mt)}return{element:E,update:Fr,destroy:$t}}}function Sh(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",a=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)",a==="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),a==="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 Th=(e,r)=>{var n,a,o;let t=(o=(a=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:a.artifacts)==null?void 0:o.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:()=>Sh(e,r)});if(u)return u}return Sh(e,r)};var Tp=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 Tp;lo.register("PersonaArtifactCard",Th);function A0(e){var a;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((a=e.props)!=null?a:{},null,2),r.appendChild(t),r.appendChild(n),r}function kh(e,r){var pe,se,Be,Ee;let t=(se=(pe=e.features)==null?void 0:pe.artifacts)==null?void 0:se.layout,a=((Be=t==null?void 0:t.toolbarPreset)!=null?Be:"default")==="document",o=(Ee=t==null?void 0:t.panePadding)==null?void 0:Ee.trim(),s=e.markdown?Xo(e.markdown):null,i=ya(e.sanitize),d=K=>{let Oe=s?s(K):Jo(K);return i?i(Oe):Oe},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"),a&&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"),a&&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=a?Qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Qt({icon:"eye",label:"Rendered view"}),A=a?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(a&&(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 a&&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)):a?H=Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=Qt({icon:"copy",label:"Copy"});let V=a?Qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"refresh-cw",label:"Refresh"}),ne=a?Qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"x",label:"Close"}),fe=()=>{var G,we,ue;let K=(G=Ve.find(re=>re.id===Q))!=null?G:Ve[Ve.length-1],Oe=(we=K==null?void 0:K.id)!=null?we:null,Fe=(K==null?void 0:K.artifactType)==="markdown"&&(ue=K.markdown)!=null?ue:"",Y=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Fe,jsonPayload:Y,id:Oe}},_e=async()=>{var G;let{markdown:K,jsonPayload:Oe}=fe(),Fe=(G=Ve.find(we=>we.id===Q))!=null?G:Ve[Ve.length-1],Y=(Fe==null?void 0:Fe.artifactType)==="markdown"?K:Fe?Oe:"";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:Oe,jsonPayload:Fe,id:Y}=fe();try{await K({actionId:"primary",artifactId:Y,markdown:Oe,jsonPayload:Fe})}catch{}return}await _e()}),R&&(S!=null&&S.length)){let K=()=>{var Fe;return(Fe=p.closest("[data-persona-root]"))!=null?Fe:document.body},Oe=()=>{B=ko({items:S.map(Fe=>({id:Fe.id,label:Fe.label})),onSelect:async Fe=>{let{markdown:Y,jsonPayload:G,id:we}=fe(),ue=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ue?await ue({actionId:Fe,artifactId:we,markdown:Y,jsonPayload:G}):Fe==="markdown"||Fe==="md"?await navigator.clipboard.writeText(Y):Fe==="json"||Fe==="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?Oe():requestAnimationFrame(Oe),R.addEventListener("click",Fe=>{Fe.stopPropagation(),B==null||B.toggle()})}V.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}J()}),ne.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let je=()=>{a&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),A.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",je(),J()}),A.addEventListener("click",()=>{v="source",je(),J()});let ye=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");a?(m.replaceChildren(),k.append(T,A),O?E.append(O,V,ne):E.append(H,V,ne),m.append(k,ye,E),je()):(m.appendChild(f),m.appendChild(w)),o&&(m.style.paddingLeft=o,m.style.paddingRight=o);let me=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"),Pe=x("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(me.style.paddingLeft=o,me.style.paddingRight=o,Pe.style.padding=o),p.appendChild(m),p.appendChild(me),p.appendChild(Pe);let Ve=[],Q=null,Ae=!1,J=()=>{var Y,G,we,ue;let K=a&&Ve.length<=1;me.classList.toggle("persona-hidden",K),me.replaceChildren();for(let re of Ve){let he=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");he.type="button",he.textContent=re.title||re.id.slice(0,8),re.id===Q&&he.classList.add("persona-bg-persona-container","persona-border-persona-border"),he.addEventListener("click",()=>r.onSelect(re.id)),me.appendChild(he)}Pe.replaceChildren();let Oe=Q&&Ve.find(re=>re.id===Q)||Ve[Ve.length-1];if(!Oe)return;if(a){let re=Oe.artifactType==="markdown"?"MD":(Y=Oe.component)!=null?Y:"Component",Je=(Oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ye.textContent=`${Je} \xB7 ${re}`}else f.textContent="Artifacts";if(Oe.artifactType==="markdown"){if(a&&v==="source"){let he=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");he.textContent=(G=Oe.markdown)!=null?G:"",Pe.appendChild(he);return}let re=x("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");re.innerHTML=d((we=Oe.markdown)!=null?we:""),Pe.appendChild(re);return}let Fe=Oe.component?lo.get(Oe.component):void 0;if(Fe){let he={message:{id:Oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Je=Fe((ue=Oe.props)!=null?ue:{},he);if(Je){Pe.appendChild(Je);return}}catch{}}Pe.appendChild(A0(Oe))},de=()=>{var Oe;let K=Ve.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Fe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,G=((Oe=Fe==null?void 0:Fe.classList.contains("persona-artifact-narrow-host"))!=null?Oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&G&&Ae?(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 Oe,Fe,Y;Ve=K.artifacts,Q=(Y=(Fe=K.selectedId)!=null?Fe:(Oe=K.artifacts[K.artifacts.length-1])==null?void 0:Oe.id)!=null?Y:null,Ve.length>0&&(Ae=!0),J(),de()},setMobileOpen(K){Ae=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):de()}}}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 Eh(e,r){var o,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=(o=r.features)==null?void 0:o.artifacts)==null?void 0:s.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),a=(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)):a&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",a))}function S0(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"),S0(e),Eh(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 a=(w=t==null?void 0:t.panePadding)==null?void 0:w.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):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"),Eh(e,r)}var Mh=["panel","seamless"];function hl(e,r){var i,d,l,u,p,m;for(let f of Mh)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",a=Mh.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${a}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);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())||o;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Lh(e,r){var t,n,a;return!r||!Sn(e)?!1:((a=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:a.expandLauncherPanelWhenOpen)!==!1}function T0(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 k0(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 E0(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function M0(e,r,t,n){let a=e-n-2*r-t;return Math.max(0,a)}function Ph(e,r){var s;let n=(s=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",a=/^([\d.]+)px$/i.exec(n);if(a)return Number(a[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function Ih(e,r,t,n,a,o){let s=T0(a,200),i=M0(r,t,n,200);i=Math.max(s,i);let d=k0(o);return d!==null&&(i=Math.min(i,d)),E0(e,s,i)}var Rh={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"}},kp=(e,r,t,n)=>{let a=e.querySelectorAll("[data-tv-form]");a.length&&a.forEach(o=>{var w,v,k;if(o.dataset.enhanced==="true")return;let s=(w=o.dataset.tvForm)!=null?w:"init";o.dataset.enhanced="true";let i=(v=Rh[s])!=null?v:Rh.init;o.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),o.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 Ep=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,a;return((n=t.priority)!=null?n:0)-((a=r.priority)!=null?a:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=o.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 Ep;var Hh=()=>{let e=new Map,r=(a,o)=>(e.has(a)||e.set(a,new Set),e.get(a).add(o),()=>t(a,o)),t=(a,o)=>{var s;(s=e.get(a))==null||s.delete(o)};return{on:r,off:t,emit:(a,o)=>{var s;(s=e.get(a))==null||s.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var L0=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},P0=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let a=t;a<r.length;a+=1){let o=r[a];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,a+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=L0(e),t=P0(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:a,...o}=n;return{type:String(a),payload:o,raw:n}}catch{return null}},Mp=e=>typeof e=="string"?e:e==null?"":String(e),sa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Mp(e.payload.text)},messageAndClick:(e,r)=>{var a;if(e.type!=="message_and_click")return;let t=e.payload,n=Mp(t.element);if(n&&((a=r.document)!=null&&a.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Mp(t.text)}}},Bh=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ds=e=>{let r=new Set(Bh(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Bh(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let s=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!s&&typeof o.text=="string"&&o.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:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.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:o.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 I0=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}},R0=e=>e.map(r=>({...r,streaming:!1})),H0=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?I0(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let a={...t,messages:t.messages?R0(t.messages):void 0,artifacts:t.artifacts?H0(t.artifacts):void 0};n.setItem(e,JSON.stringify(a))}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",a)}},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 B0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function W0(e,r){if(!B0(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 a=(0,Ba.parse)(t,Ba.STR|Ba.OBJ),o=W0(a,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Wh(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:a}=r,o=lo.get(e.component);if(!o)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=>{a&&a(i)}};try{return o(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Dh(){let e=yl();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Oh(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=Oh(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=Oh(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 D0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vl(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:a="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=D0}=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=a,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=`
|
|
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=n,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:o="How likely are you to recommend us?",subtitle:a="On a scale of 0 to 10",commentPlaceholder:n="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=o,w.appendChild(v);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=a,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 V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${B} out of 10`),V.textContent=String(B),V.dataset.rating=String(B),B<=6?V.classList.add("persona-feedback-detractor"):B<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{m=B,S.forEach((oe,fe)=>{oe.classList.toggle("selected",fe===B),oe.setAttribute("aria-checked",fe===B?"true":"false")})}),S.push(V),h.appendChild(V)}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=n,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",D0=30*1e3,O0={"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 F0(e){var o,a,n;if(!e)return[];let r=[],t=Array.from((o=e.items)!=null?o:[]);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=(a=O0[i.type])!=null?a:"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((n=e.files)!=null?n:[]))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 N0(e){var r,t,o,a,n,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:(a=(o=e.persist)==null?void 0:o.openState)!=null?a:!0,voiceState:(s=(n=e.persist)==null?void 0:n.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 _0(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Lp=e=>!e||typeof e!="object"?{}:{...e},Oh=e=>e.map(r=>({...r,streaming:!1})),Fh=(e,r,t)=>{let o=e!=null&&e.markdown?Xn(e.markdown):null,a=ya(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&a&&(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."),n=>{var l,u,p;let s=(l=n.text)!=null?l:"",i=(u=n.message.rawContent)!=null?u:null;if(r){let m=r.process({text:s,raw:i!=null?i:s,message:n.message,streaming:n.streaming});m!==null&&(s=m.text,m.persist||(n.message.__skipPersist=!0),m.resubmit&&!n.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...n,text:s,raw:(p=i!=null?i:n.text)!=null?p:""}):o?d=o(s):d=Jn(s),a?a(d):d}};function Nh(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",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",a=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",n=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=Ce(t,o,a,n);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 Kp,Yp,Qp,Zp,eu,tu,ru,ou,nu,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;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 o=zi(r),a=Bs.getForInstance(o.plugins);o.components&&dn.registerAll(o.components);let n=Hh(),i=o.persistState===!1?null:(Kp=o.storageAdapter)!=null?Kp:xl(),d={},l=null,u=!1,p=c=>{if(o.onStateLoaded)try{let g=o.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=Lp(y.metadata)),(Yp=y.messages)!=null&&Yp.length&&(o={...o,initialMessages:y.messages}),(Qp=y.artifacts)!=null&&Qp.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Zp=y.selectedArtifactId)!=null?Zp:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=p({messages:[],metadata:{}});(eu=c.messages)!=null&&eu.length&&(o={...o,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=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ws],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[sa.message,sa.messageAndClick],k=Ds({parsers:w,handlers:v,getSessionMetadata:m,updateSessionMetadata:f,emit:n.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let T=(ru=(tu=o.launcher)==null?void 0:tu.enabled)!=null?ru:!0,A=(nu=(ou=o.launcher)==null?void 0:ou.autoExpand)!=null?nu:!1,E=(au=o.autoFocusInput)!=null?au:!1,b=A,h=T,S=(iu=(su=o.layout)==null?void 0:su.header)==null?void 0:iu.layout,L=!1,O=()=>Tn(o),H=()=>T||O(),R=O()?!1:T?A:!0,B=!1,V=null,oe=()=>{B=!0,V&&clearTimeout(V),V=setTimeout(()=>{B&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),B=!1)},1e4)},fe=Fh(o,k,oe),_e=(du=(lu=o.features)==null?void 0:lu.showReasoning)!=null?du:!0,je=(pu=(cu=o.features)==null?void 0:cu.showToolCalls)!=null?pu:!0,ye=(fu=(uu=o.features)==null?void 0:uu.showEventStreamToggle)!=null?fu:!1,me=(gu=(mu=o.features)==null?void 0:mu.scrollToBottom)!=null?gu:{},Ve=`${(xu=typeof o.persistState=="object"?(hu=o.persistState)==null?void 0:hu.keyPrefix:void 0)!=null?xu:"persona-"}event-stream`,Q=ye?new Hs(Ve):null,Ae=(Cu=(bu=(yu=o.features)==null?void 0:yu.eventStream)==null?void 0:bu.maxEvents)!=null?Cu:2e3,J=ye?new Rs(Ae,Q):null,de=null,pe=!1,se=null,Be=0;Q==null||Q.open().then(()=>J==null?void 0:J.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Ee={onCopy:c=>{var g,y;n.emit("message:copy",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.id,"copy").catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(y=(g=o.messageActions)==null?void 0:g.onCopy)==null||y.call(g,c)},onFeedback:c=>{var g,y;n.emit("message:feedback",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.messageId,c.type).catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(y=(g=o.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},K=(wu=o.statusIndicator)!=null?wu:{},Oe=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 Fe(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}=oh(o),ue=nh(o,H()),{container:re,body:he,messagesWrapper:Je,suggestions:Ot,textarea:ce,sendButton:$e,sendButtonWrapper:fr,composerForm:Wt,statusText:Yt,introTitle:Fr,introSubtitle:Ar,closeButton:F,iconHolder:ie,headerTitle:We,headerSubtitle:Xe,header:Ne,footer:Ue,actionsRow:tt,leftActions:yt,rightActions:Mt}=ue,_t=ue.setSendButtonMode,N=ue.micButton,le=ue.micButtonWrapper,Te=ue.attachmentButton,ct=ue.attachmentButtonWrapper,Ke=ue.attachmentInput,$t=ue.attachmentPreviewsContainer;re.classList.add("persona-relative"),he.classList.add("persona-relative");let nr=12,Lt=()=>{var c;return(c=me.label)!=null?c:""},vt=()=>{var c;return(c=me.iconName)!=null?c:"arrow-down"},Ze=()=>me.enabled!==!1,at=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");at.type="button",at.style.display="none",at.setAttribute("data-persona-scroll-to-bottom","true");let tr=x("span","persona-flex persona-items-center"),go=x("span","");at.append(tr,go),re.appendChild(at);let Rr=()=>{let g=Ue.style.display==="none"?0:Ue.offsetHeight;at.style.bottom=`${g+nr}px`};Rr();let To=()=>{let c=!!Lt();at.setAttribute("aria-label",Lt()||"Jump to latest"),at.title=Lt(),at.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),tr.innerHTML="";let g=Ce(vt(),"14px","currentColor",2);g?(tr.appendChild(g),tr.style.display=""):tr.style.display="none",go.textContent=Lt(),go.style.display=c?"":"none"};To();let At=null,ho=null,ur=a.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:o,defaultRenderer:()=>{let g=an({config:o,showClose:H()});return oa(re,g,o),g.header},onClose:()=>qt(!1,"user")});if(c){let g=re.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ne=c)}}let Sr=()=>{var g,y,C,D;if(!J)return;if(pe=!0,!de&&J&&(de=Ah({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Yr(),config:o,plugins:a})),de&&(he.style.display="none",(g=Ue.parentNode)==null||g.insertBefore(de.element,Ue),de.update()),gt){gt.style.boxShadow=`inset 0 0 0 1.5px ${Kr.actionIconColor}`;let $=(D=(C=(y=o.features)==null?void 0:y.eventStream)==null?void 0:C.classNames)==null?void 0:D.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&>.classList.add(U))}let c=()=>{if(!pe)return;let $=Date.now();$-Be>=200&&(de==null||de.update(),Be=$),se=requestAnimationFrame(c)};Be=0,se=requestAnimationFrame(c),Jo(),n.emit("eventStream:opened",{timestamp:Date.now()})},Yr=()=>{var c,g,y;if(pe){if(pe=!1,de&&de.element.remove(),he.style.display="",gt){gt.style.boxShadow="";let C=(y=(g=(c=o.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;C&&C.split(/\s+/).forEach(D=>D&>.classList.remove(D))}se!==null&&(cancelAnimationFrame(se),se=null),Jo(),n.emit("eventStream:closed",{timestamp:Date.now()})}},gt=null;if(ye){let c=(Au=(vu=o.features)==null?void 0:vu.eventStream)==null?void 0:Au.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:"");gt=x("button",g),gt.style.width="28px",gt.style.height="28px",gt.style.color=Kr.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let y=Ce("activity","18px","currentColor",1.5);y&>.appendChild(y);let C=ue.clearChatButtonWrapper,D=ue.closeButtonWrapper,$=C||D;$&&$.parentNode===Ne?Ne.insertBefore(gt,$):Ne.appendChild(gt),gt.addEventListener("click",()=>{pe?Yr():Sr()})}let ko=c=>{var C,D,$;let g=o.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:nn).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)}},oo=a.find(c=>c.renderComposer);if(oo!=null&&oo.renderComposer){let c=o.composer,g=oo.renderComposer({config:o,defaultRenderer:()=>ka({config:o}).footer,onSubmit:y=>{var U;if(!q||q.isStreaming())return;let C=y.trim(),D=(U=At==null?void 0:At.hasAttachments())!=null?U:!1;if(!C&&!D)return;ja();let $;D&&($=[],$.push(...At.getContentParts()),C&&$.push(gs(C))),q.sendMessage(C,{contentParts:$}),D&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:((Su=o.voiceRecognition)==null?void 0:Su.enabled)===!0?()=>{ho==null||ho()}:void 0});g&&(Ue.replaceWith(g),Ue=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&&(Wt=g),y&&(ce=y),C&&($e=C),D&&(N=D,le=D.parentElement),$&&(Yt=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Ot=U);let X=c.querySelector(".persona-attachment-button");X&&(Te=X,ct=X.parentElement),Ke=c.querySelector('input[type="file"]'),$t=c.querySelector(".persona-attachment-previews");let _=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(tt=_)};ko(Ue),Tr(Ue);let kr=(Lu=(Tu=o.layout)==null?void 0:Tu.contentMaxWidth)!=null?Lu:O()?(Mu=(Eu=(ku=o.launcher)==null?void 0:ku.composerBar)==null?void 0:Eu.contentMaxWidth)!=null?Mu:"720px":void 0;if(kr&&(Je.style.maxWidth=kr,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%"),kr&&Wt&&!O()&&(Wt.style.maxWidth=kr,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),kr&&Ot&&!O()&&(Ot.style.maxWidth=kr,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),kr&&$t&&!O()&&($t.style.maxWidth=kr,$t.style.marginLeft="auto",$t.style.marginRight="auto"),(Pu=o.attachments)!=null&&Pu.enabled&&Ke&&$t){At=ta.fromConfig(o.attachments),At.setPreviewsContainer($t),Ke.addEventListener("change",y=>{let C=y.target;At==null||At.handleFileSelect(C.files),C.value=""});let c=o.attachments.dropOverlay,g=Nh(c);re.appendChild(g)}(()=>{var C,D;let c=(D=(C=o.layout)==null?void 0:C.slots)!=null?D:{},g=$=>{switch($){case"body-top":return re.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Je;case"footer-top":return Ot;case"composer":return Wt;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")Ne.insertBefore(U,Ne.firstChild);else if($==="header-right")Ne.appendChild(U);else{let _=Ne.querySelector(".persona-flex-col");_?(X=_.parentNode)==null||X.insertBefore(U,_.nextSibling):Ne.appendChild(U)}break;case"body-top":{let _=he.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(U):he.insertBefore(U,he.firstChild);break}case"body-bottom":he.appendChild(U);break;case"footer-top":Ot.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:o,defaultContent:()=>g($)});X&&y($,X)}catch(X){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,X)}})();let Eo=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),ih(D,C)):$==="tool"&&(La.has(D)?La.delete(D):La.add(D),lh(D,C,o)),io.delete(D)};Je.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Eo(c))}),Je.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Eo(c))});let xo=new Map;Je.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(Se=>Se.id===D);if(_&&Ee.onCopy){let Se=_.content||"";navigator.clipboard.writeText(Se).then(()=>{y.classList.add("persona-message-action-success");let ge=Ce("check",14,"currentColor",2);ge&&(y.innerHTML="",y.appendChild(ge)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let te=Ce("copy",14,"currentColor",2);te&&(y.innerHTML="",y.appendChild(te))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),Ee.onCopy(_)}}else if($==="upvote"||$==="downvote"){let _=((U=xo.get(D))!=null?U:null)===$,Se=$==="upvote"?"thumbs-up":"thumbs-down";if(_){xo.delete(D),y.classList.remove("persona-message-action-active");let ge=Ce(Se,14,"currentColor",2);ge&&(y.innerHTML="",y.appendChild(ge))}else{let ge=$==="upvote"?"downvote":"upvote",te=C.querySelector(`[data-action="${ge}"]`);if(te){te.classList.remove("persona-message-action-active");let Qe=Ce(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Qe&&(te.innerHTML="",te.appendChild(Qe))}xo.set(D,$),y.classList.add("persona-message-action-active");let be=Ce(Se,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 qe=q.getMessages().find(it=>it.id===D);qe&&Ee.onFeedback&&Ee.onFeedback({type:$,messageId:qe.id,message:qe})}}}),Je.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(ge=>ge.id===D);if(!(_!=null&&_.approval))return;let Se=C.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),q.resolveApproval(_.approval,U)});let bt=null,Me=null,M={artifacts:[],selectedId:null},Z=!1,ne={current:null};Je.addEventListener("click",c=>{var te,be,ke,qe,it;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.getAttribute("data-download-artifact");if(!C||((ke=(be=(te=o.features)==null?void 0:te.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:ke.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 Qe=y.closest("[data-open-artifact]"),pt=Qe==null?void 0:Qe.closest("[data-message-id]"),ut=pt==null?void 0:pt.getAttribute("data-message-id");if(ut){let Ie=q.getMessages().find(Ge=>Ge.id===ut);if(Ie!=null&&Ie.rawContent)try{let Ge=JSON.parse(Ie.rawContent);U=(qe=Ge==null?void 0:Ge.props)==null?void 0:qe.markdown,X=((it=Ge==null?void 0:Ge.props)==null?void 0:it.title)||X}catch{}}}if(!U)return;let _=new Blob([U],{type:"text/markdown"}),Se=URL.createObjectURL(_),ge=document.createElement("a");ge.href=Se,ge.download=`${X}.md`,ge.click(),URL.revokeObjectURL(Se)}),Je.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=($=o.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),no())}),Je.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let St=ue.composerOverlay,Ut=(c,g,y)=>{var X,_,Se,ge;let C=g.trim();if(!C||!ne.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})),Ln(St,D);let U=ne.current.getMessages().find(te=>{var be;return((be=te.toolCall)==null?void 0:be.id)===D});(Se=U==null?void 0:U.agentMetadata)!=null&&Se.awaitingLocalTool?ne.current.resolveAskUserQuestion(U,(ge=y.structured)!=null?ge:C):ne.current.sendMessage(C)},Rt=c=>{var D;let g=ne.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:Ao(c)})},ar=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),xr=c=>{var D,$,U;if((($=(D=o.features)==null?void 0:D.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=Ao(c),y=Ia(c);if(g>=y-1)return;let C=(U=ne.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,o,g+1),Rt(c))};St.addEventListener("click",c=>{var $,U,X,_,Se,ge,te,be,ke,qe,it,Qe,pt,ut;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 Re=($=C.getAttribute("data-tool-call-id"))!=null?$:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Ln(St,Re);let Ie=(U=ne.current)==null?void 0:U.getMessages().find(Ge=>{var W;return((W=Ge.toolCall)==null?void 0:W.id)===Re});(X=Ie==null?void 0:Ie.agentMetadata)!=null&&X.awaitingLocalTool&&((_=ne.current)==null||_.markAskUserQuestionResolved(Ie),(Se=ne.current)==null||Se.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(D==="pick"){let Re=y.getAttribute("data-option-label");if(!Re)return;let Ie=C.getAttribute("data-multi-select")==="true",Ge=Mn(C);if(Ge&&Ie){let W=aa(C)[Ao(C)],Le=new Set(Array.isArray(W)?W:[]);Le.has(Re)?Le.delete(Re):Le.add(Re),Pn(C,Array.from(Le)),Rt(C);return}if(Ge){Pn(C,Re),Rt(C),xr(C);return}if(Ie){let W=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",W?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!W);let Le=C.querySelector('[data-ask-user-action="submit-multi"]');Le&&(Le.disabled=vp(C).length===0);return}Ut(C,Re,{source:"pick",values:[Re]});return}if(D==="submit-multi"){let Re=vp(C);if(Re.length===0)return;Ut(C,Re.join(", "),{source:"multi",values:Re});return}if(D==="open-free-text"){let Re=C.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Ie=Re.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(D==="focus-free-text"){let Re=C.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(D==="submit-free-text"){let Re=C.querySelector('[data-ask-free-text-input="true"]'),Ie=(ge=Re==null?void 0:Re.value)!=null?ge:"";if(!Ie.trim())return;if(Mn(C)){Pn(C,Ie.trim()),Rt(C),xr(C);return}Ut(C,Ie,{source:"free-text"});return}if(D==="next"||D==="back"){if(!ne.current)return;let Re=(te=C.getAttribute("data-tool-call-id"))!=null?te:"",Ie=ne.current.getMessages().find(Ye=>{var ve;return((ve=Ye.toolCall)==null?void 0:ve.id)===Re});if(!Ie)return;let Ge=C.querySelector('[data-ask-free-text-input="true"]'),W=(ke=(be=Ge==null?void 0:Ge.value)==null?void 0:be.trim())!=null?ke:"";if(W){let Ye=aa(C)[Ao(C)];(typeof Ye!="string"||Ye!==W)&&Pn(C,W)}let Le=D==="next"?1:-1,De=Ao(C)+Le;ml(C,Ie,o,De),Rt(C);return}if(D==="submit-all"){if(!ne.current)return;let Re=(qe=C.getAttribute("data-tool-call-id"))!=null?qe:"",Ie=ne.current.getMessages().find(Ye=>{var ve;return((ve=Ye.toolCall)==null?void 0:ve.id)===Re});if(!Ie)return;let Ge=C.querySelector('[data-ask-free-text-input="true"]'),W=(Qe=(it=Ge==null?void 0:Ge.value)==null?void 0:it.trim())!=null?Qe:"";W&&Pn(C,W);let Le=fl(C,Ie);ne.current.persistAskUserQuestionProgress(Ie,{answers:Le,currentIndex:Ao(C)});let De=ar(Le);Ut(C,De||"(submitted)",{source:"submit-all",structured:Le});return}if(D==="skip"){if(!ne.current)return;let Re=(pt=C.getAttribute("data-tool-call-id"))!=null?pt:"",Ie=ne.current.getMessages().find(ve=>{var Bt;return((Bt=ve.toolCall)==null?void 0:Bt.id)===Re});if(!Ie)return;let Ge=Mn(C),W=Ao(C),Le=Ia(C),De=W>=Le-1;if(!Ge){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Ln(St,Re),(ut=Ie.agentMetadata)!=null&&ut.awaitingLocalTool&&(ne.current.markAskUserQuestionResolved(Ie),ne.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}Pn(C,"");let Ye=C.querySelector('[data-ask-free-text-input="true"]');if(Ye&&(Ye.value=""),De){let ve=fl(C,Ie),Bt=ar(ve);Ut(C,Bt||"(skipped)",{source:"submit-all",structured:ve});return}ml(C,Ie,o,W+1),Rt(C);return}}),St.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(Mn(C)){Pn(C,D.trim()),Rt(C),xr(C);return}Ut(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=St.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,rt=null,wr=null,_r=null,pn=()=>{};function jo(){_r==null||_r(),_r=null}let un=()=>{var U;if(!Er||!rt)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){rt.style.removeProperty("position"),rt.style.removeProperty("left"),rt.style.removeProperty("top"),rt.style.removeProperty("bottom"),rt.style.removeProperty("width"),rt.style.removeProperty("z-index");return}let C=Er.firstElementChild;if(!C||C===rt)return;let D=10;rt.style.position="absolute",rt.style.top="0",rt.style.bottom="0",rt.style.width=`${D}px`,rt.style.zIndex="5";let $=C.offsetWidth-D/2;rt.style.left=`${Math.max(0,$)}px`},Fo=()=>{},no=()=>{var y,C,D,$,U;if(!bt||!So(o))return;gl(e,o),hl(e,o),Fo();let c=($=(D=(C=(y=o.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),bt.update(M),Z?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(U=bt.backdrop)==null||U.classList.add("persona-hidden")):M.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),pn()};if(So(o)){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(re),bt=kh(o,{onSelect:y=>{var C;return(C=ne.current)==null?void 0:C.selectArtifact(y)},onDismiss:()=>{Z=!0,no()}}),bt.element.classList.add("persona-hidden"),Er=g,g.appendChild(c),g.appendChild(bt.element),bt.backdrop&&G.appendChild(bt.backdrop),G.appendChild(g),pn=()=>{var C,D,$,U;if(!Er||!bt)return;if(!((($=(D=(C=o.features)==null?void 0:C.artifacts)==null?void 0:D.layout)==null?void 0:$.resizable)===!0)){wr==null||wr(),wr=null,jo(),rt&&(rt.remove(),rt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!rt){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,Se=(U=_.defaultView)!=null?U:window,ge=te=>{var pt,ut;if(!bt||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;te.preventDefault(),jo();let be=te.clientX,ke=bt.element.getBoundingClientRect().width,qe=(ut=(pt=o.features)==null?void 0:pt.artifacts)==null?void 0:ut.layout,it=Re=>{let Ie=Er.getBoundingClientRect().width,Ge=e.classList.contains("persona-artifact-appearance-seamless"),W=Ge?0:Ph(Er,Se),Le=Ge?0:X.getBoundingClientRect().width||6,De=ke-(Re.clientX-be),Ye=Ih(De,Ie,W,Le,qe==null?void 0:qe.resizableMinWidth,qe==null?void 0:qe.resizableMaxWidth);bt.element.style.width=`${Ye}px`,bt.element.style.maxWidth="none",un()},Qe=()=>{_.removeEventListener("pointermove",it),_.removeEventListener("pointerup",Qe),_.removeEventListener("pointercancel",Qe),_r=null;try{X.releasePointerCapture(te.pointerId)}catch{}};_r=Qe,_.addEventListener("pointermove",it),_.addEventListener("pointerup",Qe),_.addEventListener("pointercancel",Qe);try{X.setPointerCapture(te.pointerId)}catch{}};X.addEventListener("pointerdown",ge),rt=X,Er.insertBefore(X,bt.element),wr=()=>{X.removeEventListener("pointerdown",ge)}}if(rt){let X=M.artifacts.length>0&&!Z;rt.classList.toggle("persona-hidden",!X),un()}},Fo=()=>{var Se,ge,te,be,ke,qe,it,Qe,pt,ut,Re,Ie,Ge,W;if(!T||!bt||((ge=(Se=o.launcher)==null?void 0:Se.sidebarMode)!=null?ge:!1)||hr(o)&&vo(o).reveal==="emerge")return;let C=(te=e.ownerDocument.defaultView)!=null?te:window,D=(ke=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?ke:!0,$=(it=(qe=o.launcher)==null?void 0:qe.mobileBreakpoint)!=null?it:640;if(D&&C.innerWidth<=$||!Lh(o,T))return;let U=(ut=(pt=(Qe=o.launcher)==null?void 0:Qe.width)!=null?pt:o.launcherWidth)!=null?ut:mo,X=(W=(Ge=(Ie=(Re=o.features)==null?void 0:Re.artifacts)==null?void 0:Ie.layout)==null?void 0:Ge.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"&&(Me=new ResizeObserver(()=>{no()}),Me.observe(G))}else G.appendChild(re),O()&&we&&(ue.peekBanner&&we.appendChild(ue.peekBanner),we.appendChild(Ue));e.appendChild(Y),we&&e.appendChild(we);let Mo=()=>{var Ye,ve,Bt,dt,cr,Lr,Dt,Ur,Pr,nt,ft,qr,Br,On,Fn,Nn,ma,ga,rr,_n,wn,Tt,Zr,Zo,zr,eo,zt,Zt;if(O()){G.style.width="100%",G.style.maxWidth="100%";let Vt=(ve=(Ye=o.launcher)==null?void 0:Ye.composerBar)!=null?ve:{},or=Y.dataset.state==="expanded",to=(Bt=Vt.expandedSize)!=null?Bt:"anchored";if(!(or&&to!=="fullscreen")){re.style.background="",re.style.border="",re.style.borderRadius="",re.style.overflow="",re.style.boxShadow="";return}let gr=(cr=(dt=o.theme)==null?void 0:dt.components)==null?void 0:cr.panel,$o=Sa(o),en=($n,ni)=>{var Ya;return $n==null||$n===""?ni:(Ya=va($o,$n))!=null?Ya:$n},ti="1px solid var(--persona-border)",ri="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",oi="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";re.style.background="var(--persona-surface, #ffffff)",re.style.border=en(gr==null?void 0:gr.border,ti),re.style.borderRadius=en(gr==null?void 0:gr.borderRadius,oi),re.style.boxShadow=en(gr==null?void 0:gr.shadow,ri),re.style.overflow="hidden";return}let c=hr(o),g=(Dt=(Lr=o.launcher)==null?void 0:Lr.sidebarMode)!=null?Dt:!1,y=c||g||((Pr=(Ur=o.launcher)==null?void 0:Ur.fullHeight)!=null?Pr:!1),C=((nt=o.launcher)==null?void 0:nt.enabled)===!1,D=(qr=(ft=o.theme)==null?void 0:ft.components)==null?void 0:qr.panel,$=Sa(o),U=(Vt,or)=>{var to;return Vt==null||Vt===""?or:(to=va($,Vt))!=null?to:Vt},X=(Br=e.ownerDocument.defaultView)!=null?Br:window,_=(Fn=(On=o.launcher)==null?void 0:On.mobileFullscreen)!=null?Fn:!0,Se=(ma=(Nn=o.launcher)==null?void 0:Nn.mobileBreakpoint)!=null?ma:640,ge=X.innerWidth<=Se,te=_&&ge&&T,be=(rr=(ga=o.launcher)==null?void 0:ga.position)!=null?rr:"bottom-left",ke=be==="bottom-left"||be==="top-left",qe=(wn=(_n=o.launcher)==null?void 0:_n.zIndex)!=null?wn:Or,it=g||te?"none":"1px solid var(--persona-border)",Qe=te?"none":g?ke?"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&&!te&&(Qe="none",it="none");let pt=g||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ut=U(D==null?void 0:D.border,it),Re=U(D==null?void 0:D.shadow,Qe),Ie=U(D==null?void 0:D.borderRadius,pt),Ge=he.scrollTop;e.style.cssText="",Y.style.cssText="",G.style.cssText="",re.style.cssText="",he.style.cssText="",Ue.style.cssText="";let W=()=>{var or;if(Ge<=0)return;((or=he.ownerDocument.defaultView)!=null?or:window).requestAnimationFrame(()=>{if(he.scrollTop===Ge)return;let to=he.scrollHeight-he.clientHeight;to<=0||(he.scrollTop=Math.min(Ge,to))})};if(te){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
|
+
`,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=o,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:a="On a scale of 0 to 10",commentPlaceholder:o="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=a,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 V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${B} out of 10`),V.textContent=String(B),V.dataset.rating=String(B),B<=6?V.classList.add("persona-feedback-detractor"):B<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{m=B,S.forEach((ne,fe)=>{ne.classList.toggle("selected",fe===B),ne.setAttribute("aria-checked",fe===B?"true":"false")})}),S.push(V),h.appendChild(V)}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=o,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",O0=30*1e3,F0={"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 N0(e){var n,a,o;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=(a=F0[i.type])!=null?a:"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((o=e.files)!=null?o:[]))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 _0(e){var r,t,n,a,o,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:(a=(n=e.persist)==null?void 0:n.openState)!=null?a:!0,voiceState:(s=(o=e.persist)==null?void 0:o.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 $0(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Lp=e=>!e||typeof e!="object"?{}:{...e},Fh=e=>e.map(r=>({...r,streaming:!1})),Nh=(e,r,t)=>{let n=e!=null&&e.markdown?Xo(e.markdown):null,a=ya(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&a&&(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."),o=>{var l,u,p;let s=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(r){let m=r.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});m!==null&&(s=m.text,m.persist||(o.message.__skipPersist=!0),m.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:s,raw:(p=i!=null?i:o.text)!=null?p:""}):n?d=n(s):d=Jo(s),a?a(d):d}};function _h(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",a=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=Ce(t,n,a,o);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 Kp,Yp,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;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),a=Bs.getForInstance(n.plugins);n.components&&lo.registerAll(n.components);let o=Hh(),i=n.persistState===!1?null:(Kp=n.storageAdapter)!=null?Kp: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=Lp(y.metadata)),(Yp=y.messages)!=null&&Yp.length&&(n={...n,initialMessages:y.messages}),(Qp=y.artifacts)!=null&&Qp.length&&(n={...n,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Zp=y.selectedArtifactId)!=null?Zp: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:{}});(eu=c.messages)!=null&&eu.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:o.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let T=(ru=(tu=n.launcher)==null?void 0:tu.enabled)!=null?ru:!0,A=(ou=(nu=n.launcher)==null?void 0:nu.autoExpand)!=null?ou:!1,E=(au=n.autoFocusInput)!=null?au:!1,b=A,h=T,S=(iu=(su=n.layout)==null?void 0:su.header)==null?void 0:iu.layout,L=!1,O=()=>To(n),H=()=>T||O(),R=O()?!1:T?A:!0,B=!1,V=null,ne=()=>{B=!0,V&&clearTimeout(V),V=setTimeout(()=>{B&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),B=!1)},1e4)},fe=Nh(n,k,ne),_e=(du=(lu=n.features)==null?void 0:lu.showReasoning)!=null?du:!0,je=(pu=(cu=n.features)==null?void 0:cu.showToolCalls)!=null?pu:!0,ye=(fu=(uu=n.features)==null?void 0:uu.showEventStreamToggle)!=null?fu:!1,me=(gu=(mu=n.features)==null?void 0:mu.scrollToBottom)!=null?gu:{},Ve=`${(xu=typeof n.persistState=="object"?(hu=n.persistState)==null?void 0:hu.keyPrefix:void 0)!=null?xu:"persona-"}event-stream`,Q=ye?new Hs(Ve):null,Ae=(Cu=(bu=(yu=n.features)==null?void 0:yu.eventStream)==null?void 0:bu.maxEvents)!=null?Cu:2e3,J=ye?new Rs(Ae,Q):null,de=null,pe=!1,se=null,Be=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 Ee={onCopy:c=>{var g,y;o.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;o.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=(wu=n.statusIndicator)!=null?wu:{},Oe=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 Fe(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}=nh(n),ue=oh(n,H()),{container:re,body:he,messagesWrapper:Je,suggestions:Ot,textarea:ce,sendButton:$e,sendButtonWrapper:fr,composerForm:Wt,statusText:Yt,introTitle:Fr,introSubtitle:Ar,closeButton:F,iconHolder:ie,headerTitle:We,headerSubtitle:Xe,header:Ne,footer:Ue,actionsRow:tt,leftActions:yt,rightActions:Mt}=ue,$t=ue.setSendButtonMode,N=ue.micButton,le=ue.micButtonWrapper,Te=ue.attachmentButton,ct=ue.attachmentButtonWrapper,Ke=ue.attachmentInput,Ut=ue.attachmentPreviewsContainer;re.classList.add("persona-relative"),he.classList.add("persona-relative");let or=12,Lt=()=>{var c;return(c=me.label)!=null?c:""},vt=()=>{var c;return(c=me.iconName)!=null?c:"arrow-down"},Ze=()=>me.enabled!==!1,at=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");at.type="button",at.style.display="none",at.setAttribute("data-persona-scroll-to-bottom","true");let tr=x("span","persona-flex persona-items-center"),gn=x("span","");at.append(tr,gn),re.appendChild(at);let Rr=()=>{let g=Ue.style.display==="none"?0:Ue.offsetHeight;at.style.bottom=`${g+or}px`};Rr();let Tn=()=>{let c=!!Lt();at.setAttribute("aria-label",Lt()||"Jump to latest"),at.title=Lt(),at.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),tr.innerHTML="";let g=Ce(vt(),"14px","currentColor",2);g?(tr.appendChild(g),tr.style.display=""):tr.style.display="none",gn.textContent=Lt(),gn.style.display=c?"":"none"};Tn();let At=null,hn=null,ur=a.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(re,g,n),g.header},onClose:()=>Ft(!1,"user")});if(c){let g=re.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ne=c)}}let Sr=()=>{var g,y,C,D;if(!J)return;if(pe=!0,!de&&J&&(de=Ah({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Yr(),config:n,plugins:a})),de&&(he.style.display="none",(g=Ue.parentNode)==null||g.insertBefore(de.element,Ue),de.update()),gt){gt.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&>.classList.add(U))}let c=()=>{if(!pe)return;let $=Date.now();$-Be>=200&&(de==null||de.update(),Be=$),se=requestAnimationFrame(c)};Be=0,se=requestAnimationFrame(c),Jn(),o.emit("eventStream:opened",{timestamp:Date.now()})},Yr=()=>{var c,g,y;if(pe){if(pe=!1,de&&de.element.remove(),he.style.display="",gt){gt.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&>.classList.remove(D))}se!==null&&(cancelAnimationFrame(se),se=null),Jn(),o.emit("eventStream:closed",{timestamp:Date.now()})}},gt=null;if(ye){let c=(Au=(vu=n.features)==null?void 0:vu.eventStream)==null?void 0:Au.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:"");gt=x("button",g),gt.style.width="28px",gt.style.height="28px",gt.style.color=Kr.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let y=Ce("activity","18px","currentColor",1.5);y&>.appendChild(y);let C=ue.clearChatButtonWrapper,D=ue.closeButtonWrapper,$=C||D;$&&$.parentNode===Ne?Ne.insertBefore(gt,$):Ne.appendChild(gt),gt.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=a.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=At==null?void 0:At.hasAttachments())!=null?U:!1;if(!C&&!D)return;ja();let $;D&&($=[],$.push(...At.getContentParts()),C&&$.push(gs(C))),q.sendMessage(C,{contentParts:$}),D&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.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:((Su=n.voiceRecognition)==null?void 0:Su.enabled)===!0?()=>{hn==null||hn()}:void 0});g&&(Ue.replaceWith(g),Ue=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&&(Wt=g),y&&(ce=y),C&&($e=C),D&&(N=D,le=D.parentElement),$&&(Yt=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Ot=U);let X=c.querySelector(".persona-attachment-button");X&&(Te=X,ct=X.parentElement),Ke=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");_&&(tt=_)};kn(Ue),Tr(Ue);let kr=(Lu=(Tu=n.layout)==null?void 0:Tu.contentMaxWidth)!=null?Lu:O()?(Mu=(Eu=(ku=n.launcher)==null?void 0:ku.composerBar)==null?void 0:Eu.contentMaxWidth)!=null?Mu:"720px":void 0;if(kr&&(Je.style.maxWidth=kr,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%"),kr&&Wt&&!O()&&(Wt.style.maxWidth=kr,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),kr&&Ot&&!O()&&(Ot.style.maxWidth=kr,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),kr&&Ut&&!O()&&(Ut.style.maxWidth=kr,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(Pu=n.attachments)!=null&&Pu.enabled&&Ke&&Ut){At=ta.fromConfig(n.attachments),At.setPreviewsContainer(Ut),Ke.addEventListener("change",y=>{let C=y.target;At==null||At.handleFileSelect(C.files),C.value=""});let c=n.attachments.dropOverlay,g=_h(c);re.appendChild(g)}(()=>{var C,D;let c=(D=(C=n.layout)==null?void 0:C.slots)!=null?D:{},g=$=>{switch($){case"body-top":return re.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Je;case"footer-top":return Ot;case"composer":return Wt;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")Ne.insertBefore(U,Ne.firstChild);else if($==="header-right")Ne.appendChild(U);else{let _=Ne.querySelector(".persona-flex-col");_?(X=_.parentNode)==null||X.insertBefore(U,_.nextSibling):Ne.appendChild(U)}break;case"body-top":{let _=he.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(U):he.insertBefore(U,he.firstChild);break}case"body-bottom":he.appendChild(U);break;case"footer-top":Ot.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),ih(D,C)):$==="tool"&&(La.has(D)?La.delete(D):La.add(D),lh(D,C,n)),ln.delete(D)};Je.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),En(c))}),Je.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;Je.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(Se=>Se.id===D);if(_&&Ee.onCopy){let Se=_.content||"";navigator.clipboard.writeText(Se).then(()=>{y.classList.add("persona-message-action-success");let ge=Ce("check",14,"currentColor",2);ge&&(y.innerHTML="",y.appendChild(ge)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let te=Ce("copy",14,"currentColor",2);te&&(y.innerHTML="",y.appendChild(te))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),Ee.onCopy(_)}}else if($==="upvote"||$==="downvote"){let _=((U=xn.get(D))!=null?U:null)===$,Se=$==="upvote"?"thumbs-up":"thumbs-down";if(_){xn.delete(D),y.classList.remove("persona-message-action-active");let ge=Ce(Se,14,"currentColor",2);ge&&(y.innerHTML="",y.appendChild(ge))}else{let ge=$==="upvote"?"downvote":"upvote",te=C.querySelector(`[data-action="${ge}"]`);if(te){te.classList.remove("persona-message-action-active");let Qe=Ce(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Qe&&(te.innerHTML="",te.appendChild(Qe))}xn.set(D,$),y.classList.add("persona-message-action-active");let be=Ce(Se,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 qe=q.getMessages().find(it=>it.id===D);qe&&Ee.onFeedback&&Ee.onFeedback({type:$,messageId:qe.id,message:qe})}}}),Je.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(ge=>ge.id===D);if(!(_!=null&&_.approval))return;let Se=C.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),q.resolveApproval(_.approval,U)});let bt=null,Me=null,M={artifacts:[],selectedId:null},Z=!1,oe={current:null};Je.addEventListener("click",c=>{var te,be,ke,qe,it;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.getAttribute("data-download-artifact");if(!C||((ke=(be=(te=n.features)==null?void 0:te.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:ke.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 Qe=y.closest("[data-open-artifact]"),pt=Qe==null?void 0:Qe.closest("[data-message-id]"),ut=pt==null?void 0:pt.getAttribute("data-message-id");if(ut){let Ie=q.getMessages().find(Ge=>Ge.id===ut);if(Ie!=null&&Ie.rawContent)try{let Ge=JSON.parse(Ie.rawContent);U=(qe=Ge==null?void 0:Ge.props)==null?void 0:qe.markdown,X=((it=Ge==null?void 0:Ge.props)==null?void 0:it.title)||X}catch{}}}if(!U)return;let _=new Blob([U],{type:"text/markdown"}),Se=URL.createObjectURL(_),ge=document.createElement("a");ge.href=Se,ge.download=`${X}.md`,ge.click(),URL.revokeObjectURL(Se)}),Je.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())}),Je.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let St=ue.composerOverlay,qt=(c,g,y)=>{var X,_,Se,ge;let C=g.trim();if(!C||!oe.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(St,D);let U=oe.current.getMessages().find(te=>{var be;return((be=te.toolCall)==null?void 0:be.id)===D});(Se=U==null?void 0:U.agentMetadata)!=null&&Se.awaitingLocalTool?oe.current.resolveAskUserQuestion(U,(ge=y.structured)!=null?ge:C):oe.current.sendMessage(C)},Rt=c=>{var D;let g=oe.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=oe.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),Rt(c))};St.addEventListener("click",c=>{var $,U,X,_,Se,ge,te,be,ke,qe,it,Qe,pt,ut;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 Re=($=C.getAttribute("data-tool-call-id"))!=null?$:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Lo(St,Re);let Ie=(U=oe.current)==null?void 0:U.getMessages().find(Ge=>{var W;return((W=Ge.toolCall)==null?void 0:W.id)===Re});(X=Ie==null?void 0:Ie.agentMetadata)!=null&&X.awaitingLocalTool&&((_=oe.current)==null||_.markAskUserQuestionResolved(Ie),(Se=oe.current)==null||Se.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(D==="pick"){let Re=y.getAttribute("data-option-label");if(!Re)return;let Ie=C.getAttribute("data-multi-select")==="true",Ge=Mo(C);if(Ge&&Ie){let W=aa(C)[An(C)],Le=new Set(Array.isArray(W)?W:[]);Le.has(Re)?Le.delete(Re):Le.add(Re),Po(C,Array.from(Le)),Rt(C);return}if(Ge){Po(C,Re),Rt(C),xr(C);return}if(Ie){let W=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",W?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!W);let Le=C.querySelector('[data-ask-user-action="submit-multi"]');Le&&(Le.disabled=vp(C).length===0);return}qt(C,Re,{source:"pick",values:[Re]});return}if(D==="submit-multi"){let Re=vp(C);if(Re.length===0)return;qt(C,Re.join(", "),{source:"multi",values:Re});return}if(D==="open-free-text"){let Re=C.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Ie=Re.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(D==="focus-free-text"){let Re=C.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(D==="submit-free-text"){let Re=C.querySelector('[data-ask-free-text-input="true"]'),Ie=(ge=Re==null?void 0:Re.value)!=null?ge:"";if(!Ie.trim())return;if(Mo(C)){Po(C,Ie.trim()),Rt(C),xr(C);return}qt(C,Ie,{source:"free-text"});return}if(D==="next"||D==="back"){if(!oe.current)return;let Re=(te=C.getAttribute("data-tool-call-id"))!=null?te:"",Ie=oe.current.getMessages().find(Ye=>{var ve;return((ve=Ye.toolCall)==null?void 0:ve.id)===Re});if(!Ie)return;let Ge=C.querySelector('[data-ask-free-text-input="true"]'),W=(ke=(be=Ge==null?void 0:Ge.value)==null?void 0:be.trim())!=null?ke:"";if(W){let Ye=aa(C)[An(C)];(typeof Ye!="string"||Ye!==W)&&Po(C,W)}let Le=D==="next"?1:-1,De=An(C)+Le;ml(C,Ie,n,De),Rt(C);return}if(D==="submit-all"){if(!oe.current)return;let Re=(qe=C.getAttribute("data-tool-call-id"))!=null?qe:"",Ie=oe.current.getMessages().find(Ye=>{var ve;return((ve=Ye.toolCall)==null?void 0:ve.id)===Re});if(!Ie)return;let Ge=C.querySelector('[data-ask-free-text-input="true"]'),W=(Qe=(it=Ge==null?void 0:Ge.value)==null?void 0:it.trim())!=null?Qe:"";W&&Po(C,W);let Le=fl(C,Ie);oe.current.persistAskUserQuestionProgress(Ie,{answers:Le,currentIndex:An(C)});let De=ar(Le);qt(C,De||"(submitted)",{source:"submit-all",structured:Le});return}if(D==="skip"){if(!oe.current)return;let Re=(pt=C.getAttribute("data-tool-call-id"))!=null?pt:"",Ie=oe.current.getMessages().find(ve=>{var Bt;return((Bt=ve.toolCall)==null?void 0:Bt.id)===Re});if(!Ie)return;let Ge=Mo(C),W=An(C),Le=Ia(C),De=W>=Le-1;if(!Ge){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Lo(St,Re),(ut=Ie.agentMetadata)!=null&&ut.awaitingLocalTool&&(oe.current.markAskUserQuestionResolved(Ie),oe.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}Po(C,"");let Ye=C.querySelector('[data-ask-free-text-input="true"]');if(Ye&&(Ye.value=""),De){let ve=fl(C,Ie),Bt=ar(ve);qt(C,Bt||"(skipped)",{source:"submit-all",structured:ve});return}ml(C,Ie,n,W+1),Rt(C);return}}),St.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()),Rt(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=St.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,rt=null,wr=null,_r=null,po=()=>{};function jn(){_r==null||_r(),_r=null}let uo=()=>{var U;if(!Er||!rt)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){rt.style.removeProperty("position"),rt.style.removeProperty("left"),rt.style.removeProperty("top"),rt.style.removeProperty("bottom"),rt.style.removeProperty("width"),rt.style.removeProperty("z-index");return}let C=Er.firstElementChild;if(!C||C===rt)return;let D=10;rt.style.position="absolute",rt.style.top="0",rt.style.bottom="0",rt.style.width=`${D}px`,rt.style.zIndex="5";let $=C.offsetWidth-D/2;rt.style.left=`${Math.max(0,$)}px`},Fn=()=>{},on=()=>{var y,C,D,$,U;if(!bt||!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),bt.update(M),Z?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(U=bt.backdrop)==null||U.classList.add("persona-hidden")):M.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.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(re),bt=kh(n,{onSelect:y=>{var C;return(C=oe.current)==null?void 0:C.selectArtifact(y)},onDismiss:()=>{Z=!0,on()}}),bt.element.classList.add("persona-hidden"),Er=g,g.appendChild(c),g.appendChild(bt.element),bt.backdrop&&G.appendChild(bt.backdrop),G.appendChild(g),po=()=>{var C,D,$,U;if(!Er||!bt)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(),rt&&(rt.remove(),rt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!rt){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,Se=(U=_.defaultView)!=null?U:window,ge=te=>{var pt,ut;if(!bt||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;te.preventDefault(),jn();let be=te.clientX,ke=bt.element.getBoundingClientRect().width,qe=(ut=(pt=n.features)==null?void 0:pt.artifacts)==null?void 0:ut.layout,it=Re=>{let Ie=Er.getBoundingClientRect().width,Ge=e.classList.contains("persona-artifact-appearance-seamless"),W=Ge?0:Ph(Er,Se),Le=Ge?0:X.getBoundingClientRect().width||6,De=ke-(Re.clientX-be),Ye=Ih(De,Ie,W,Le,qe==null?void 0:qe.resizableMinWidth,qe==null?void 0:qe.resizableMaxWidth);bt.element.style.width=`${Ye}px`,bt.element.style.maxWidth="none",uo()},Qe=()=>{_.removeEventListener("pointermove",it),_.removeEventListener("pointerup",Qe),_.removeEventListener("pointercancel",Qe),_r=null;try{X.releasePointerCapture(te.pointerId)}catch{}};_r=Qe,_.addEventListener("pointermove",it),_.addEventListener("pointerup",Qe),_.addEventListener("pointercancel",Qe);try{X.setPointerCapture(te.pointerId)}catch{}};X.addEventListener("pointerdown",ge),rt=X,Er.insertBefore(X,bt.element),wr=()=>{X.removeEventListener("pointerdown",ge)}}if(rt){let X=M.artifacts.length>0&&!Z;rt.classList.toggle("persona-hidden",!X),uo()}},Fn=()=>{var Se,ge,te,be,ke,qe,it,Qe,pt,ut,Re,Ie,Ge,W;if(!T||!bt||((ge=(Se=n.launcher)==null?void 0:Se.sidebarMode)!=null?ge:!1)||hr(n)&&vn(n).reveal==="emerge")return;let C=(te=e.ownerDocument.defaultView)!=null?te:window,D=(ke=(be=n.launcher)==null?void 0:be.mobileFullscreen)!=null?ke:!0,$=(it=(qe=n.launcher)==null?void 0:qe.mobileBreakpoint)!=null?it:640;if(D&&C.innerWidth<=$||!Lh(n,T))return;let U=(ut=(pt=(Qe=n.launcher)==null?void 0:Qe.width)!=null?pt:n.launcherWidth)!=null?ut:mn,X=(W=(Ge=(Ie=(Re=n.features)==null?void 0:Re.artifacts)==null?void 0:Ie.layout)==null?void 0:Ge.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"&&(Me=new ResizeObserver(()=>{on()}),Me.observe(G))}else G.appendChild(re),O()&&we&&(ue.peekBanner&&we.appendChild(ue.peekBanner),we.appendChild(Ue));e.appendChild(Y),we&&e.appendChild(we);let Mn=()=>{var Ye,ve,Bt,dt,cr,Lr,Dt,Ur,Pr,ot,ft,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo,Tt,Zr,Zn,zr,en,zt,Zt;if(O()){G.style.width="100%",G.style.maxWidth="100%";let Vt=(ve=(Ye=n.launcher)==null?void 0:Ye.composerBar)!=null?ve:{},nr=Y.dataset.state==="expanded",tn=(Bt=Vt.expandedSize)!=null?Bt:"anchored";if(!(nr&&tn!=="fullscreen")){re.style.background="",re.style.border="",re.style.borderRadius="",re.style.overflow="",re.style.boxShadow="";return}let gr=(cr=(dt=n.theme)==null?void 0:dt.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))";re.style.background="var(--persona-surface, #ffffff)",re.style.border=eo(gr==null?void 0:gr.border,ti),re.style.borderRadius=eo(gr==null?void 0:gr.borderRadius,ni),re.style.boxShadow=eo(gr==null?void 0:gr.shadow,ri),re.style.overflow="hidden";return}let c=hr(n),g=(Dt=(Lr=n.launcher)==null?void 0:Lr.sidebarMode)!=null?Dt:!1,y=c||g||((Pr=(Ur=n.launcher)==null?void 0:Ur.fullHeight)!=null?Pr:!1),C=((ot=n.launcher)==null?void 0:ot.enabled)===!1,D=(qr=(ft=n.theme)==null?void 0:ft.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,Se=(ma=(No=n.launcher)==null?void 0:No.mobileBreakpoint)!=null?ma:640,ge=X.innerWidth<=Se,te=_&&ge&&T,be=(rr=(ga=n.launcher)==null?void 0:ga.position)!=null?rr:"bottom-left",ke=be==="bottom-left"||be==="top-left",qe=(wo=(_o=n.launcher)==null?void 0:_o.zIndex)!=null?wo:Or,it=g||te?"none":"1px solid var(--persona-border)",Qe=te?"none":g?ke?"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&&!te&&(Qe="none",it="none");let pt=g||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ut=U(D==null?void 0:D.border,it),Re=U(D==null?void 0:D.shadow,Qe),Ie=U(D==null?void 0:D.borderRadius,pt),Ge=he.scrollTop;e.style.cssText="",Y.style.cssText="",G.style.cssText="",re.style.cssText="",he.style.cssText="",Ue.style.cssText="";let W=()=>{var nr;if(Ge<=0)return;((nr=he.ownerDocument.defaultView)!=null?nr:window).requestAnimationFrame(()=>{if(he.scrollTop===Ge)return;let tn=he.scrollHeight-he.clientHeight;tn<=0||(he.scrollTop=Math.min(Ge,tn))})};if(te){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 a="<p>An error
|
|
|
103
103
|
overflow: hidden !important;
|
|
104
104
|
border-radius: 0 !important;
|
|
105
105
|
border: none !important;
|
|
106
|
-
`,he.style.flex="1 1 0%",he.style.minHeight="0",he.style.overflowY="auto",Ue.style.flexShrink="0",L=!0,W();return}let Le=(Zr=(Tt=
|
|
106
|
+
`,he.style.flex="1 1 0%",he.style.minHeight="0",he.style.overflowY="auto",Ue.style.flexShrink="0",L=!0,W();return}let Le=(Zr=(Tt=n==null?void 0:n.launcher)==null?void 0:Tt.width)!=null?Zr:n==null?void 0:n.launcherWidth,De=Le!=null?Le:mn;if(!g&&!c)C&&y?(G.style.width="100%",G.style.maxWidth="100%"):(G.style.width=De,G.style.maxWidth=De);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=Re,G.style.borderRadius=Ie,re.style.border=ut,re.style.borderRadius=Ie,c&&!te&&(D==null?void 0:D.border)===void 0&&(re.style.border="none",vn(n).side==="right"?re.style.borderLeft="1px solid var(--persona-border)":re.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",C&&(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%",C&&(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",re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.overflow="hidden",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.overflowY="auto",Ue.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&&!C&&!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,23 +144,23 @@ Please report this to https://github.com/markedjs/marked.`,r){let a="<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;",or=g?"":"padding-top: 1.25em !important;",to=g?"":`z-index: ${(Zt=(zt=o.launcher)==null?void 0:zt.zIndex)!=null?Zt:Or} !important;`;Y.style.cssText+=Vt+or+to}W()};Mo(),vn(e,o),gl(e,o),hl(e,o);let Ct=[];Ct.push(()=>{document.removeEventListener("keydown",Nr)});let sr=null,ir=null;Ct.push(()=>{sr==null||sr(),sr=null,ir==null||ir(),ir=null}),Me&&Ct.push(()=>{Me==null||Me.disconnect(),Me=null}),Ct.push(()=>{wr==null||wr(),wr=null,jo(),rt&&(rt.remove(),rt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),ye&&Ct.push(()=>{se!==null&&(cancelAnimationFrame(se),se=null),de==null||de.destroy(),de=null,J==null||J.destroy(),J=null,Q=null});let ao=null,fn=()=>{ao&&(ao(),ao=null),o.colorScheme==="auto"&&(ao=Gi(()=>{vn(e,o)}))};fn(),Ct.push(()=>{ao&&(ao(),ao=null)});let yo=(Iu=o.features)==null?void 0:Iu.streamAnimation;if(yo!=null&&yo.type&&yo.type!=="none"){let c=Ss(yo.type,yo.plugins);c&&(sp(c,e),Ct.push(()=>eh(e)))}let Lo=vh(Ot),so=null,q,xe=!1,io=Xg(),Po=new Map,No=new Map,Oa=0,Io=Ji(),Ro=0,Ho=null,Go=!1,Rn=!1,Ns=4,Fa=24,_s=80,la=new Map,xt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Na=(Hu=(Ru=o.voiceRecognition)==null?void 0:Ru.autoResume)!=null?Hu:!1,bo=c=>{n.emit("voice:state",{active:xt.active,source:c,timestamp:Date.now()})},Qr=()=>{f(c=>({...c,voiceState:{active:xt.active,timestamp:Date.now(),manuallyDeactivated:xt.manuallyDeactivated}}))},$s=()=>{var C,D;if(((C=o.voiceRecognition)==null?void 0:C.enabled)===!1)return;let c=Lp(d.voiceState),g=!!c.active,y=Number((D=c.timestamp)!=null?D:0);xt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<D0&&setTimeout(()=>{var $,U;xt.active||(xt.manuallyDeactivated=!1,((U=($=o.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),bo("restore"),q.isVoiceActive()&&Cn()}):Wn("restore"))},1e3)},Us=()=>q?Oh(q.getMessages()).filter(c=>!c.__skipPersist):[];function da(c){if(!(i!=null&&i.save))return;let y={messages:c?Oh(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 Xo=null,qs=()=>Y.querySelector("#persona-scroll-container")||he,Hn=()=>{Xo!==null&&(cancelAnimationFrame(Xo),Xo=null),Go=!1},_a=()=>{Ho!==null&&(cancelAnimationFrame(Ho),Ho=null),Rn=!1,Hn()},Jo=()=>{if(!Ze()||pe){at.parentNode&&at.remove(),at.style.display="none";return}at.parentNode!==re&&re.appendChild(at),Rr();let c=Cs(he)>0;at.style.display=Io.isFollowing()||!c?"none":""},$a=()=>{Io.pause()&&(_a(),Jo())},mn=()=>{Io.resume(),Jo()},gn=(c=!1)=>{Io.isFollowing()&&(!c&&!xe||(Ho!==null&&(cancelAnimationFrame(Ho),Ho=null),Rn=!0,Ho=requestAnimationFrame(()=>{Ho=null,Rn=!1,Io.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){Ro=c.scrollTop;return}if(Math.abs(D)>=_s){Hn(),Go=!0,c.scrollTop=C,Ro=c.scrollTop,Go=!1;return}Hn();let $=performance.now();Go=!0;let U=_=>1-Math.pow(1-_,3),X=_=>{if(!Io.isFollowing()){Hn();return}let Se=Cs(c);Se!==C&&(C=Se,D=C-y);let ge=_-$,te=Math.min(ge/g,1),be=U(te),ke=y+D*be;c.scrollTop=ke,Ro=c.scrollTop,te<1?Xo=requestAnimationFrame(X):(c.scrollTop=C,Ro=c.scrollTop,Xo=null,Go=!1)};Xo=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"&&n.emit("assistant:message",y),y.role==="assistant"&&(C!=null&&C.streaming)&&y.streaming===!1&&n.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(C?y.approval.status!=="pending"&&n.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):n.emit("approval:requested",{approval:y.approval,message:y}))}),la.clear(),g.forEach((y,C)=>{la.set(C,y)})},Bn=(c,g,y)=>{var Qe,pt,ut,Re,Ie,Ge;let C=document.createElement("div"),$=(()=>{var Le;let W=a.find(De=>De.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Le=o.loadingIndicator)!=null&&Le.render)return o.loadingIndicator.render})(),U=(W,Le)=>Le==null?!1:typeof Le=="string"?(W.textContent=Le,!0):(W.appendChild(Le),!0),X=new Set,_=new Set,Se=a.some(W=>W.renderAskUserQuestion),ge=[],te=[],be=o.enableComponentStreaming!==!1;if(g.forEach(W=>{var Ur,Pr,nt,ft,qr,Br,On,Fn,Nn,ma,ga,rr,_n,wn;X.add(W.id);let Le=Se&&sn(W),De=!Le&&W.role==="assistant"&&!W.variant&&be&&Cl(W);if(!De&&No.has(W.id)){let Tt=c.querySelector(`#wrapper-${W.id}`);Tt==null||Tt.removeAttribute("data-preserve-runtime"),No.delete(W.id)}let Ye=sn(W)?`:${(Ur=W.agentMetadata)!=null&&Ur.askUserQuestionAnswered?"a":"u"}:${(Pr=W.agentMetadata)!=null&&Pr.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",ve=Gg(W,Oa)+Ye,Bt=Le||De?null:Jg(io,W.id,ve);if(Bt){C.appendChild(Bt.cloneNode(!0)),sn(W)&&((nt=W.toolCall)!=null&&nt.id)&&((ft=W.agentMetadata)==null?void 0:ft.awaitingLocalTool)===!0&&!((qr=W.agentMetadata)!=null&&qr.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,o,ue.composerOverlay));return}let dt=null,cr=a.find(Tt=>!!(W.variant==="reasoning"&&Tt.renderReasoning||W.variant==="tool"&&Tt.renderToolCall||W.variant==="approval"&&Tt.renderApproval||!W.variant&&Tt.renderMessage)),Lr=(Br=o.layout)==null?void 0:Br.messages;if(sn(W)&&((On=W.agentMetadata)==null?void 0:On.askUserQuestionAnswered)===!0){Po.delete(W.id);let Tt=c.querySelector(`#wrapper-${W.id}`);Tt==null||Tt.removeAttribute("data-preserve-runtime");return}if(sn(W)&&((Nn=(Fn=o.features)==null?void 0:Fn.askUserQuestion)==null?void 0:Nn.enabled)!==!1){let Tt=a.find(Zr=>typeof Zr.renderAskUserQuestion=="function");if(Tt&&ne.current){let Zr=Po.get(W.id),Zo=Zr!==ve,zr=null;if(Zo){let{payload:Zt,complete:Vt}=ln(W),or=W.id,to=()=>{var co;return(co=ne.current)==null?void 0:co.getMessages().find(gr=>gr.id===or)};zr=Tt.renderAskUserQuestion({message:W,payload:Zt,complete:Vt,resolve:co=>{var $o;let gr=to();gr&&(($o=ne.current)==null||$o.resolveAskUserQuestion(gr,co))},dismiss:()=>{var gr,$o,en;let co=to();(gr=co==null?void 0:co.agentMetadata)!=null&&gr.awaitingLocalTool&&(($o=ne.current)==null||$o.markAskUserQuestionResolved(co),(en=ne.current)==null||en.resolveAskUserQuestion(co,"(dismissed)"))},config:o})}let eo=Zr!=null;if(Zo&&zr===null&&!eo){((ma=W.agentMetadata)==null?void 0:ma.awaitingLocalTool)===!0&&!((ga=W.agentMetadata)!=null&&ga.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,o,ue.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),ge.push({messageId:W.id,fingerprint:ve,bubble:zr});return}else{((rr=W.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((_n=W.agentMetadata)!=null&&_n.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,o,ue.composerOverlay));return}}else if(cr)if(W.variant==="reasoning"&&W.reasoning&&cr.renderReasoning){if(!_e)return;dt=cr.renderReasoning({message:W,defaultRenderer:()=>mp(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&cr.renderToolCall){if(!je)return;dt=cr.renderToolCall({message:W,defaultRenderer:()=>gp(W,o),config:o})}else if(W.variant==="approval"&&W.approval&&cr.renderApproval){if(o.approval===!1)return;dt=cr.renderApproval({message:W,defaultRenderer:()=>Ap(W,o),config:o})}else cr.renderMessage&&(dt=cr.renderMessage({message:W,defaultRenderer:()=>{let Tt=Ea(W,y,Lr,o.messageActions,Ee,{loadingIndicatorRenderer:$,widgetConfig:o});return W.role!=="user"&&kp(Tt,W,o,q),Tt},config:o}));if(!dt&&De){let Tt=wl(W);if(Tt){let Zr=No.get(W.id),Zo=Zr!==ve,zr=o.wrapComponentDirectiveInBubble!==!1,eo=null;if(Zo){let zt=bl(Tt,{config:o,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),eo=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),eo=Zt}}if(eo||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),te.push({messageId:W.id,fingerprint:ve,bubble:eo});return}}}if(!dt)if(W.variant==="reasoning"&&W.reasoning){if(!_e)return;dt=mp(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!je)return;dt=gp(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;dt=Ap(W,o)}else{let Tt=(wn=o.layout)==null?void 0:wn.messages;Tt!=null&&Tt.renderUserMessage&&W.role==="user"?dt=Tt.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):Tt!=null&&Tt.renderAssistantMessage&&W.role==="assistant"?dt=Tt.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):dt=Ea(W,y,Tt,o.messageActions,Ee,{loadingIndicatorRenderer:$,widgetConfig:o}),W.role!=="user"&&dt&&kp(dt,W,o,q)}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${W.id}`,Dt.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Dt.classList.add("persona-justify-end"),(dt==null?void 0:dt.getAttribute("data-persona-component-directive"))==="true"&&Dt.classList.add("persona-w-full"),Dt.appendChild(dt),Kg(io,W.id,ve,Dt),C.appendChild(Dt)}),ue.composerOverlay&&ue.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let De=Le.getAttribute("data-persona-ask-sheet-for");De&&!_.has(De)&&Ln(ue.composerOverlay,De)}),(pt=(Qe=o.features)==null?void 0:Qe.toolCallDisplay)!=null&&pt.grouped){let W=[],Le=[];g.forEach(De=>{if(De.variant==="tool"&&De.toolCall&&je){Le.push(De);return}Le.length>1&&W.push(Le),Le=[]}),Le.length>1&&W.push(Le),W.forEach((De,Ye)=>{var Pr,nt;let ve=De.map(ft=>Array.from(C.children).find(qr=>qr instanceof HTMLElement&&qr.getAttribute("data-wrapper-id")===ft.id)).filter(ft=>!!ft);if(ve.length<2)return;let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-tool-group-${Ye}-${De[0].id}`,Bt.setAttribute("data-wrapper-id",`tool-group-${Ye}-${De[0].id}`);let dt=document.createElement("div");dt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",dt.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 ${De.length} tools`,Dt=(nt=(Pr=o.toolCall)==null?void 0:Pr.renderGroupedSummary)==null?void 0:nt.call(Pr,{messages:De,toolCalls:De.map(ft=>ft.toolCall).filter(ft=>!!ft),defaultSummary:Lr,config:o});U(cr,Dt)||(cr.textContent=Lr);let Ur=document.createElement("div");Ur.className="persona-tool-group-stack persona-flex persona-flex-col",dt.append(cr,Ur),Bt.appendChild(dt),ve[0].before(Bt),ve.forEach((ft,qr)=>{let Br=document.createElement("div");Br.className="persona-tool-group-item persona-relative",Br.setAttribute("data-persona-tool-group-item","true"),qr<ve.length-1&&Br.setAttribute("data-persona-tool-group-connector","true"),Br.appendChild(ft),Ur.appendChild(Br)})})}Yg(io,X);let ke=g.some(W=>W.role==="assistant"&&W.streaming),qe=g[g.length-1],it=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(xe&&g.some(W=>W.role==="user")&&!ke&&!it){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:na},Le=a.find(Ye=>Ye.renderLoadingIndicator),De=null;if(Le!=null&&Le.renderLoadingIndicator&&(De=Le.renderLoadingIndicator(W)),De===null&&((ut=o.loadingIndicator)!=null&&ut.render)&&(De=o.loadingIndicator.render(W)),De===null&&(De=na()),De){let Ye=document.createElement("div"),ve=((Re=o.loadingIndicator)==null?void 0:Re.showBubble)!==!1;Ye.className=ve?["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(" "),Ye.setAttribute("data-typing-indicator","true"),Ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ye.appendChild(De);let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id="wrapper-typing-indicator",Bt.setAttribute("data-wrapper-id","typing-indicator"),Bt.appendChild(Ye),C.appendChild(Bt)}}if(!xe&&g.length>0){let W=g[g.length-1],Le={config:o,lastMessage:W,messageCount:g.length},De=a.find(ve=>ve.renderIdleIndicator),Ye=null;if(De!=null&&De.renderIdleIndicator&&(Ye=De.renderIdleIndicator(Le)),Ye===null&&((Ie=o.loadingIndicator)!=null&&Ie.renderIdle)&&(Ye=o.loadingIndicator.renderIdle(Le)),Ye){let ve=document.createElement("div"),Bt=((Ge=o.loadingIndicator)==null?void 0:Ge.showBubble)!==!1;ve.className=Bt?["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(" "),ve.setAttribute("data-idle-indicator","true"),ve.appendChild(Ye);let dt=document.createElement("div");dt.className="persona-flex",dt.id="wrapper-idle-indicator",dt.setAttribute("data-wrapper-id","idle-indicator"),dt.appendChild(ve),C.appendChild(dt)}}if(Xi(c,C),ge.length>0)for(let{messageId:W,fingerprint:Le,bubble:De}of ge){let Ye=c.querySelector(`#wrapper-${W}`);Ye&&De!==null&&(Ye.replaceChildren(De),Ye.setAttribute("data-bubble-fp",Le),Po.set(W,Le))}if(Po.size>0)for(let W of Po.keys())X.has(W)||Po.delete(W);if(te.length>0)for(let{messageId:W,fingerprint:Le,bubble:De}of te){let Ye=c.querySelector(`#wrapper-${W}`);Ye&&De!==null&&(Ye.replaceChildren(De),Ye.setAttribute("data-bubble-fp",Le),No.set(W,Le))}if(No.size>0)for(let W of No.keys())X.has(W)||No.delete(W)},hn=null,js=()=>{var y;if(hn)return;let c=C=>{let D=C.composedPath();D.includes(Y)||we&&D.includes(we)||qt(!1,"user")};hn=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},Ua=()=>{var g;if(!hn)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",hn,!0),hn=null};Ct.push(()=>Ua());let xn=null,Gs=()=>{var y;if(xn)return;let c=C=>{C.key==="Escape"&&(C.isComposing||qt(!1,"user"))};xn=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},qa=()=>{var g;if(!xn)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",xn,!0),xn=null};Ct.push(()=>qa());let yn=!1,za=new Set,Xs=()=>{var g,y,C,D;let c=(C=(y=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:C.streamAnimation;return c||((D=o.features)==null?void 0:D.streamAnimation)},Ko=()=>{var pt,ut,Re,Ie;if(!O())return;let c=ue.peekBanner,g=ue.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let y=(pt=q==null?void 0:q.getMessages())!=null?pt:[],C;for(let Ge=y.length-1;Ge>=0;Ge--){let W=y[Ge];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,Se=((ut=_==null?void 0:_.isAnimating)==null?void 0:ut.call(_,C))===!0,ge=_!==null&&($||Se);ge&&_&&!za.has(_.name)&&(sp(_,e),za.add(_.name));let te=ge&&(_!=null&&_.containerClass)?_.containerClass:null,be=(Re=g.dataset.personaPeekStreamClass)!=null?Re:null;be&&be!==te&&(g.classList.remove(be),delete g.dataset.personaPeekStreamClass),te&&be!==te&&(g.classList.add(te),g.dataset.personaPeekStreamClass=te),ge?(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 ke=ge?Zi(D,X.buffer,_,C,$):D;if(ge&&X.placeholder==="skeleton"&&$&&(!ke||!ke.trim())){let Ge=document.createElement("div"),W=ks();W.classList.add("persona-pill-peek__skeleton"),Ge.appendChild(W),Xi(g,Ge)}else{let Ge=Math.max(0,ke.length-100),W=ke.length>100?ke.slice(-100):ke,Le=Jn(W);if(!ge||!_){let De=ke.length>100?`\u2026${W}`:W;g.textContent!==De&&(g.textContent=De)}else{let De=Le;(_.wrap==="char"||_.wrap==="word")&&(De=Ts(Le,_.wrap,`peek-${C.id}`,{skipTags:_.skipTags,startIndex:Ge}));let Ye=document.createElement("div");if(Ye.innerHTML=De,_.useCaret&&W.length>0){let ve=el(),Bt=Ye.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=Bt[Bt.length-1];dt!=null&&dt.parentNode?dt.parentNode.insertBefore(ve,dt.nextSibling):Ye.appendChild(ve)}Xi(g,Ye),(Ie=_.onAfterRender)==null||Ie.call(_,{container:g,bubble:c,messageId:C.id,message:C,speed:X.speed,duration:X.duration})}}let Qe=xe||yn;c.classList.toggle("persona-pill-peek--visible",Qe)};if(O()){let c=ue.peekBanner;if(c){let C=D=>{D.preventDefault(),D.stopPropagation(),qt(!0,"user")};c.addEventListener("pointerdown",C),Ct.push(()=>{c.removeEventListener("pointerdown",C)})}let g=()=>{yn||(yn=!0,Ko())},y=()=>{yn&&(yn=!1,Ko())};G.addEventListener("pointerenter",g),G.addEventListener("pointerleave",y),Ct.push(()=>{G.removeEventListener("pointerenter",g),G.removeEventListener("pointerleave",y)}),we&&(we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),Ct.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}))}let Js=c=>{var be,ke,qe,it,Qe,pt,ut,Re;let g=(ke=(be=o.launcher)==null?void 0:be.composerBar)!=null?ke:{},y=(qe=g.expandedSize)!=null?qe:"anchored",C=(it=g.bottomOffset)!=null?it:"16px",D=g.collapsedMaxWidth,$=(Qe=g.expandedMaxWidth)!=null?Qe:"880px",U=(pt=g.expandedTopOffset)!=null?pt:"5vh",X=(ut=g.modalMaxWidth)!=null?ut:"880px",_=(Re=g.modalMaxHeight)!=null?Re:"min(90vh, 800px)",Se="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",te=Y.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",we){let Ie=we.style;Ie.bottom=C,Ie.width=D!=null?D:""}if(c&&y!=="fullscreen"){if(y==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=X,te.maxWidth=Se,te.maxHeight=_,te.height=_;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${C} + ${ge})`,te.top=U,te.width=$,te.maxWidth=Se}},bn=()=>{var _,Se,ge,te,be,ke,qe,it;if(!H())return;if(O()){let pt=(ge=((Se=(_=o.launcher)==null?void 0:_.composerBar)!=null?Se:{}).expandedSize)!=null?ge:"anchored",ut=R?"expanded":"collapsed";Y.dataset.state=ut,Y.dataset.expandedSize=pt,we&&(we.dataset.state=ut,we.dataset.expandedSize=pt),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),re.style.display=R?"flex":"none",Mo(),R?(js(),Gs()):(Ua(),qa()),Ko();return}let c=hr(o),g=(te=e.ownerDocument.defaultView)!=null?te:window,y=(ke=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?ke:640,C=(it=(qe=o.launcher)==null?void 0:qe.mobileFullscreen)!=null?it:!0,D=g.innerWidth<=y,$=C&&D&&T,U=vo(o).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":j&&(j.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":"":j&&(j.style.display=c?"none":""))},qt=(c,g="user")=>{var $,U;if(!H()||R===c)return;let y=R;R=c,bn();let C=(()=>{var qe,it,Qe,pt,ut,Re,Ie,Ge,W,Le;let X=(it=(qe=o.launcher)==null?void 0:qe.sidebarMode)!=null?it:!1,_=(Qe=e.ownerDocument.defaultView)!=null?Qe:window,Se=(ut=(pt=o.launcher)==null?void 0:pt.mobileFullscreen)!=null?ut:!0,ge=(Ie=(Re=o.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Ie:640,te=_.innerWidth<=ge,be=hr(o)&&Se&&te,ke=O()&&((Le=(W=(Ge=o.launcher)==null?void 0:Ge.composerBar)==null?void 0:W.expandedSize)!=null?Le:"fullscreen")==="fullscreen";return X||Se&&te&&T||be||ke})();if(R&&C){if(!sr){let X=e.getRootNode(),_=X instanceof ShadowRoot?X.host:e.closest(".persona-host");_&&(sr=ip(_,(U=($=o.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&&(He(),gn(!0));let D={open:R,source:g,timestamp:Date.now()};R&&!y?n.emit("widget:opened",D):!R&&y&&n.emit("widget:closed",D),n.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:xt.active,streaming:q.isStreaming()})},ca=c=>{_t(c?"stop":"send"),N&&(N.disabled=c),Lo.buttons.forEach(g=>{g.disabled=c}),Ue.dataset.personaComposerStreaming=c?"true":"false",Ue.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=()=>{xt.active||ce&&ce.focus()};n.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>pa(),200)});let Va=()=>{var y,C,D,$,U,X,_,Se,ge,te,be;Fr.textContent=(C=(y=o.copy)==null?void 0:y.welcomeTitle)!=null?C:"Hello \u{1F44B}",Ar.textContent=($=(D=o.copy)==null?void 0:D.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ce.placeholder=(X=(U=o.copy)==null?void 0:U.inputPlaceholder)!=null?X:"How can I help...";let c=he.querySelector("[data-persona-intro-card]");if(c){let ke=((_=o.copy)==null?void 0:_.showWelcomeCard)!==!1;c.style.display=ke?"":"none",ke?(he.classList.remove("persona-gap-3"),he.classList.add("persona-gap-6")):(he.classList.remove("persona-gap-6"),he.classList.add("persona-gap-3"))}!((ge=(Se=o.sendButton)==null?void 0:Se.useIcon)!=null&&ge)&&!(q!=null&&q.isStreaming())&&($e.textContent=(be=(te=o.copy)==null?void 0:te.sendButtonLabel)!=null?be:"Send"),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{f(g=>({...g,sessionId:c}))}});let _o=null,Ks=()=>{_o==null&&(_o=setInterval(()=>{let c=Je.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(_o),_o=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(o,{onMessagesChanged(c){Bn(Je,c,fe),Ks(),q&&(c.some(D=>D.role==="user")?Lo.render([],q,ce,c):Lo.render(o.suggestionChips,q,ce,c,o.suggestionChipsConfig)),gn(!xe),Vs(c);let g=[...c].reverse().find(C=>C.role==="user"),y=xt.lastUserMessageId;g&&g.id!==y&&(xt.lastUserMessageId=g.id,n.emit("user:message",g)),xt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),da(c),Ko()},onStatusChanged(c){var C;let g=(C=o.statusIndicator)!=null?C:{};Fe(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){xe=c,ca(c),q&&Bn(Je,q.getMessages(),fe),c||gn(!0),Ko()},onVoiceStatusChanged(c){var g,y;if(((y=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":Wo(),Qs();break;case"speaking":Wo(),Zs();break;default:c==="idle"&&q.isBargeInActive()?(Wo(),Cn(),N==null||N.setAttribute("aria-label","End voice session")):(xt.active=!1,Wo(),bo("system"),Qr());break}},onArtifactsState(c){M=c,no(),da()}}),ne.current=q,((Wu=(Bu=o.voiceRecognition)==null?void 0:Bu.provider)==null?void 0:Wu.type)==="runtype")try{q.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&q.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(J||o.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var y;(y=o.onSSEEvent)==null||y.call(o,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=Lp(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=o.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||C)||qt(!0,"auto")},Ga=c=>{var D;if(c.preventDefault(),q.isStreaming()){q.cancel();return}let g=ce.value.trim(),y=(D=At==null?void 0:At.hasAttachments())!=null?D:!1;if(!g&&!y)return;ja();let C;y&&(C=[],C.push(...At.getContentParts()),g&&C.push(gs(g))),ce.value="",ce.style.height="auto",q.sendMessage(g,{contentParts:C}),y&&At.clearAttachments()},Xa=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),$e.click())},Ja=async c=>{var y;if(((y=o.attachments)==null?void 0:y.enabled)!==!0||!At)return;let g=F0(c.clipboardData);g.length!==0&&(c.preventDefault(),await At.handleFiles(g))},$r=null,lo=!1,Yo=null,lt=null,Ka=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Wn=(c="user")=>{var $,U,X,_,Se,ge,te;if(lo||q.isStreaming())return;let g=Ka();if(!g)return;$r=new g;let C=(U=(($=o.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;$r.continuous=!0,$r.interimResults=!0,$r.lang="en-US";let D=ce.value;$r.onresult=be=>{let ke="",qe="";for(let Qe=0;Qe<be.results.length;Qe++){let pt=be.results[Qe],ut=pt[0].transcript;pt.isFinal?ke+=ut+" ":qe=ut}let it=D+ke+qe;ce.value=it,Yo&&clearTimeout(Yo),(ke||qe)&&(Yo=window.setTimeout(()=>{let Qe=ce.value.trim();Qe&&$r&&lo&&(Bo(),ce.value="",ce.style.height="auto",q.sendMessage(Qe,{viaVoice:!0}))},C))},$r.onerror=be=>{be.error!=="no-speech"&&Bo()},$r.onend=()=>{if(lo){let be=ce.value.trim();be&&be!==D.trim()&&(ce.value="",ce.style.height="auto",q.sendMessage(be,{viaVoice:!0})),Bo()}};try{if($r.start(),lo=!0,xt.active=!0,c!=="system"&&(xt.manuallyDeactivated=!1),bo(c),Qr(),N){let be=(X=o.voiceRecognition)!=null?X:{};lt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((te=(ge=be.iconSize)!=null?ge:(Se=o.sendButton)==null?void 0:Se.size)!=null?te:"40")||24};let ke=be.recordingBackgroundColor,qe=be.recordingIconColor,it=be.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=ke!=null?ke:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=qe!=null?qe:"var(--persona-voice-recording-indicator, #ffffff)",qe){let Qe=N.querySelector("svg");Qe&&Qe.setAttribute("stroke",qe)}it&&(N.style.borderColor=it),N.setAttribute("aria-label","Stop voice recognition")}}catch{Bo("system")}},Bo=(c="user")=>{if(lo){if(lo=!1,Yo&&(clearTimeout(Yo),Yo=null),$r){try{$r.stop()}catch{}$r=null}if(xt.active=!1,bo(c),Qr(),N){if(N.classList.remove("persona-voice-recording"),lt){N.style.backgroundColor=lt.backgroundColor,N.style.color=lt.color,N.style.borderColor=lt.borderColor;let g=N.querySelector("svg");g&&g.setAttribute("stroke",lt.color||"currentColor"),lt=null}N.setAttribute("aria-label","Start voice recognition")}}},Ys=(c,g)=>{var pt,ut,Re,Ie,Ge,W,Le,De;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((pt=c==null?void 0:c.provider)==null?void 0:pt.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=(ut=c==null?void 0:c.iconName)!=null?ut:"mic",_=(Re=g==null?void 0:g.size)!=null?Re:"40px",Se=(Ie=c==null?void 0:c.iconSize)!=null?Ie:_,ge=parseFloat(Se)||24,te=(Ge=c==null?void 0:c.backgroundColor)!=null?Ge: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=Se,U.style.height=Se,U.style.minWidth=Se,U.style.minHeight=Se,U.style.fontSize="18px",U.style.lineHeight="1",be?U.style.color=be:U.style.color="var(--persona-text, #111827)";let qe=Ce(X,ge,be||"currentColor",1.5);qe?U.appendChild(qe):U.textContent="\u{1F3A4}",te?U.style.backgroundColor=te: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 it=(Le=c==null?void 0:c.tooltipText)!=null?Le:"Start voice recognition";if(((De=c==null?void 0:c.showTooltip)!=null?De:!1)&&it){let Ye=x("div","persona-send-button-tooltip");Ye.textContent=it,$.appendChild(Ye)}return{micButton:U,micButtonWrapper:$}},ua=()=>{var g,y,C,D,$;if(!N||lt)return;let c=(g=o.voiceRecognition)!=null?g:{};lt={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=o.sendButton)==null?void 0:C.size)!=null?$:"40")||24}},fa=(c,g)=>{var $,U,X,_,Se;if(!N)return;let y=N.querySelector("svg");y&&y.remove();let C=(Se=lt==null?void 0:lt.iconSize)!=null?Se:parseFloat((_=(X=($=o.voiceRecognition)==null?void 0:$.iconSize)!=null?X:(U=o.sendButton)==null?void 0:U.size)!=null?_:"40")||24,D=Ce(c,C,g,1.5);D&&N.appendChild(D)},Dn=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Cn=()=>{var D;if(!N)return;ua();let c=(D=o.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,C=c.recordingBorderColor;if(Dn(),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,_,Se,ge,te,be,ke,qe;if(!N)return;ua();let c=(X=o.voiceRecognition)!=null?X:{},g=q.getVoiceInterruptionMode(),y=(_=c.processingIconName)!=null?_:"loader",C=(ge=(Se=c.processingIconColor)!=null?Se:lt==null?void 0:lt.color)!=null?ge:"",D=(be=(te=c.processingBackgroundColor)!=null?te:lt==null?void 0:lt.backgroundColor)!=null?be:"",$=(qe=(ke=c.processingBorderColor)!=null?ke:lt==null?void 0:lt.borderColor)!=null?qe:"";Dn(),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 Se,ge,te,be,ke,qe,it,Qe,pt,ut,Re,Ie;if(!N)return;ua();let c=(Se=o.voiceRecognition)!=null?Se:{},g=q.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",C=(ge=c.speakingIconName)!=null?ge:y,D=(qe=c.speakingIconColor)!=null?qe:g==="barge-in"?(be=(te=c.recordingIconColor)!=null?te:lt==null?void 0:lt.color)!=null?be:"":(ke=lt==null?void 0:lt.color)!=null?ke:"",$=(pt=c.speakingBackgroundColor)!=null?pt:g==="barge-in"?(it=c.recordingBackgroundColor)!=null?it:"var(--persona-voice-recording-bg, #ef4444)":(Qe=lt==null?void 0:lt.backgroundColor)!=null?Qe:"",U=(Ie=c.speakingBorderColor)!=null?Ie:g==="barge-in"?(ut=c.recordingBorderColor)!=null?ut:"":(Re=lt==null?void 0:lt.borderColor)!=null?Re:"";Dn(),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")},Wo=()=>{var c,g,y;N&&(Dn(),lt&&(N.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",N.style.color=(g=lt.color)!=null?g:"",N.style.borderColor=(y=lt.borderColor)!=null?y:"",fa(lt.iconName,lt.color||"currentColor"),lt=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},Qo=()=>{var c,g;if(((g=(c=o.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(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Qr(),bo("user"),Wo()});return}q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),xt.manuallyDeactivated=!q.isVoiceActive(),Qr(),bo("user"),q.isVoiceActive()?Cn():Wo()});return}if(lo){let y=ce.value.trim();xt.manuallyDeactivated=!0,Qr(),Bo("user"),y&&(ce.value="",ce.style.height="auto",q.sendMessage(y))}else xt.manuallyDeactivated=!1,Qr(),Wn("user")};ho=Qo,N&&(N.addEventListener("click",Qo),Ct.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Wo()):Bo("system"),N&&N.removeEventListener("click",Qo)}));let et=n.on("assistant:complete",()=>{Na&&(xt.active||xt.manuallyDeactivated||Na==="assistant"&&!xt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!xt.active&&!xt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),bo("auto"),q.isVoiceActive()&&Cn()}):Wn("auto"))},600))});Ct.push(et);let P=n.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});Ct.push(P);let z=()=>{qt(!R,"user")},I=null,j=null;if(T&&!O()){let c=a.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>Ms(o,z).element,onToggle:z});g&&(j=g)}j||(I=Ms(o,z))}I?e.appendChild(I.element):j&&e.appendChild(j),bn(),Lo.render(o.suggestionChips,q,ce,void 0,o.suggestionChipsConfig),Va(),ca(q.isStreaming()),gn(!0),$s(),E&&(!T||O()?setTimeout(()=>pa(),0):R&&setTimeout(()=>pa(),200));let He=()=>{var _,Se,ge,te,be,ke,qe,it,Qe,pt,ut,Re,Ie,Ge,W,Le,De,Ye,ve,Bt,dt,cr;if(O()){Rr(),bn();return}let c=hr(o),g=(Se=(_=o.launcher)==null?void 0:_.sidebarMode)!=null?Se:!1,y=c||g||((te=(ge=o.launcher)==null?void 0:ge.fullHeight)!=null?te:!1),C=(be=e.ownerDocument.defaultView)!=null?be:window,D=(qe=(ke=o.launcher)==null?void 0:ke.mobileFullscreen)!=null?qe:!0,$=(Qe=(it=o.launcher)==null?void 0:it.mobileBreakpoint)!=null?Qe:640,U=C.innerWidth<=$,X=D&&U&&T;try{if(X){Mo(),vn(e,o);return}if(L&&(L=!1,Mo(),vn(e,o)),!T&&!c){G.style.height="",G.style.width="";return}if(!g&&!c){let Lr=(ut=(pt=o==null?void 0:o.launcher)==null?void 0:pt.width)!=null?ut:o==null?void 0:o.launcherWidth,Dt=Lr!=null?Lr:mo;G.style.width=Dt,G.style.maxWidth=Dt}if(Fo(),!y){let Lr=C.innerHeight,Dt=64,Ur=(Ie=(Re=o.launcher)==null?void 0:Re.heightOffset)!=null?Ie:0,Pr=Math.max(200,Lr-Dt),nt=Math.min(640,Pr),ft=Math.max(200,nt-Ur);G.style.height=`${ft}px`}}finally{if(Rr(),bn(),R&&T){let Dt=((Ge=e.ownerDocument.defaultView)!=null?Ge:window).innerWidth<=((Le=(W=o.launcher)==null?void 0:W.mobileBreakpoint)!=null?Le:640),Ur=(Ye=(De=o.launcher)==null?void 0:De.sidebarMode)!=null?Ye:!1,Pr=(Bt=(ve=o.launcher)==null?void 0:ve.mobileFullscreen)!=null?Bt:!0,nt=hr(o)&&Pr&&Dt,ft=Ur||Pr&&Dt&&T||nt;if(ft&&!ir){let qr=e.getRootNode(),Br=qr instanceof ShadowRoot?qr.host:e.closest(".persona-host");Br&&!sr&&(sr=ip(Br,(cr=(dt=o.launcher)==null?void 0:dt.zIndex)!=null?cr:Or)),ir=lp(e.ownerDocument)}else ft||(sr==null||sr(),sr=null,ir==null||ir(),ir=null)}}};He();let ae=(Du=e.ownerDocument.defaultView)!=null?Du:window;if(ae.addEventListener("resize",He),Ct.push(()=>ae.removeEventListener("resize",He)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Rr()});c.observe(Ue),Ct.push(()=>c.disconnect())}Ro=he.scrollTop;let st=he.scrollHeight,ot=()=>{let c=he.scrollTop,g=he.scrollHeight,y=g<st;st=g;let{action:C,nextLastScrollTop:D}=Ki({following:Io.isFollowing(),currentScrollTop:c,lastScrollTop:Ro,nearBottom:ws(he,Fa),userScrollThreshold:Ns,isAutoScrolling:Go||Rn||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Ro=D,C==="resume"){mn();return}C==="pause"&&$a()};he.addEventListener("scroll",ot,{passive:!0}),Ct.push(()=>he.removeEventListener("scroll",ot));let Ft=c=>{let g=Yi({following:Io.isFollowing(),deltaY:c.deltaY,nearBottom:ws(he,Fa),resumeWhenNearBottom:!0});g==="pause"?$a():g==="resume"&&mn()};he.addEventListener("wheel",Ft,{passive:!0}),Ct.push(()=>he.removeEventListener("wheel",Ft)),at.addEventListener("click",()=>{he.scrollTop=he.scrollHeight,Ro=he.scrollTop,mn(),gn(!0)}),Ct.push(()=>at.remove()),Ct.push(()=>{_a()});let kt=()=>{F&&(so&&(F.removeEventListener("click",so),so=null),H()?(F.style.display="",so=()=>{qt(!1,"user")},F.addEventListener("click",so)):F.style.display="none")};kt(),(()=>{let{clearChatButton:c}=ue;c&&c.addEventListener("click",()=>{q.clearMessages(),io.clear(),mn(),Ln(ue.composerOverlay);try{localStorage.removeItem(Wa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Wa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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(),de==null||de.update()})})(),Wt&&Wt.addEventListener("submit",Ga),ce==null||ce.addEventListener("keydown",Xa),ce==null||ce.addEventListener("paste",Ja);let Gt="persona-attachment-drop-active",lr=0,Pt=()=>{lr=0,re.classList.remove(Gt)},Et=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&At!==null},yr=c=>{!Sl(c.dataTransfer)||!Et()||(lr++,lr===1&&re.classList.add(Gt))},Hr=c=>{!Sl(c.dataTransfer)||!Et()||(lr--,lr<=0&&Pt())},Mr=c=>{!Sl(c.dataTransfer)||!Et()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},dr=c=>{var y;if(!Sl(c.dataTransfer)||!Et())return;c.preventDefault(),c.stopPropagation(),Pt();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&At.handleFiles(g)},vr=!0;re.addEventListener("dragenter",yr,vr),re.addEventListener("dragleave",Hr,vr),e.addEventListener("dragover",Mr,vr),e.addEventListener("drop",dr,vr);let ei=e.ownerDocument,Xp=c=>{Et()&&c.preventDefault()},Jp=c=>{Et()&&c.preventDefault()};ei.addEventListener("dragover",Xp),ei.addEventListener("drop",Jp),Ct.push(()=>{Wt&&Wt.removeEventListener("submit",Ga),ce==null||ce.removeEventListener("keydown",Xa),ce==null||ce.removeEventListener("paste",Ja)}),Ct.push(()=>{re.removeEventListener("dragenter",yr,vr),re.removeEventListener("dragleave",Hr,vr),e.removeEventListener("dragover",Mr,vr),e.removeEventListener("drop",dr,vr),ei.removeEventListener("dragover",Xp),ei.removeEventListener("drop",Jp),Pt()}),Ct.push(()=>{q.cancel()}),I?Ct.push(()=>{I==null||I.destroy()}):j&&Ct.push(()=>{j==null||j.remove()});let mr={update(c){var gr,$o,en,ti,ri,oi,$n,ni,Ya,qu,zu,Vu,ju,Gu,Xu,Ju,Ku,Yu,Qu,Zu,ef,tf,rf,of,nf,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,om,nm,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;let g=o.toolCall,y=o.messageActions,C=(gr=o.layout)==null?void 0:gr.messages,D=o.colorScheme,$=o.loadingIndicator,U=o.iterationDisplay,X=($o=o.features)==null?void 0:$o.showReasoning,_=(en=o.features)==null?void 0:en.showToolCalls,Se=(ti=o.features)==null?void 0:ti.toolCallDisplay,ge=(ri=o.features)==null?void 0:ri.reasoningDisplay;o={...o,...c},Mo(),vn(e,o),gl(e,o),hl(e,o),no(),o.colorScheme!==D&&fn();let te=Bs.getForInstance(o.plugins);a.length=0,a.push(...te),T=($n=(oi=o.launcher)==null?void 0:oi.enabled)!=null?$n:!0,A=(Ya=(ni=o.launcher)==null?void 0:ni.autoExpand)!=null?Ya:!1,_e=(zu=(qu=o.features)==null?void 0:qu.showReasoning)!=null?zu:!0,je=(ju=(Vu=o.features)==null?void 0:Vu.showToolCalls)!=null?ju:!0,me=(Xu=(Gu=o.features)==null?void 0:Gu.scrollToBottom)!=null?Xu:{},To(),Jo();let be=ye;if(ye=(Ku=(Ju=o.features)==null?void 0:Ju.showEventStreamToggle)!=null?Ku:!1,ye&&!be){if(J||(Q=new Hs(Ve),J=new Rs(Ae,Q),Q.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),q.setSSEEventCallback((ee,It)=>{var Xt;(Xt=o.onSSEEvent)==null||Xt.call(o,ee,It),J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(It)})})),!gt&&Ne){let ee=(Qu=(Yu=o.features)==null?void 0:Yu.eventStream)==null?void 0:Qu.classNames,It="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:"");gt=x("button",It),gt.style.width="28px",gt.style.height="28px",gt.style.color=Kr.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let Xt=Ce("activity","18px","currentColor",1.5);Xt&>.appendChild(Xt);let mt=ue.clearChatButtonWrapper,Ht=ue.closeButtonWrapper,br=mt||Ht;br&&br.parentNode===Ne?Ne.insertBefore(gt,br):Ne.appendChild(gt),gt.addEventListener("click",()=>{pe?Yr():Sr()})}}else!ye&&be&&(Yr(),gt&&(gt.remove(),gt=null),J==null||J.clear(),Q==null||Q.destroy(),J=null,Q=null);if(((Zu=o.launcher)==null?void 0:Zu.enabled)===!1&&I&&(I.destroy(),I=null),((ef=o.launcher)==null?void 0:ef.enabled)===!1&&j&&(j.remove(),j=null),((tf=o.launcher)==null?void 0:tf.enabled)!==!1&&!I&&!j){let ee=a.find(It=>It.renderLauncher);if(ee!=null&&ee.renderLauncher){let It=ee.renderLauncher({config:o,defaultRenderer:()=>Ms(o,z).element,onToggle:z});It&&(j=It,e.appendChild(j))}j||(I=Ms(o,z),e.appendChild(I.element))}I&&I.update(o),We&&((rf=o.launcher)==null?void 0:rf.title)!==void 0&&(We.textContent=o.launcher.title),Xe&&((of=o.launcher)==null?void 0:of.subtitle)!==void 0&&(Xe.textContent=o.launcher.subtitle);let ke=(nf=o.layout)==null?void 0:nf.header;if((ke==null?void 0:ke.layout)!==S&&Ne){let ee=ke?Ta(o,ke,{showClose:H(),onClose:()=>qt(!1,"user")}):an({config:o,showClose:H(),onClose:()=>qt(!1,"user")});Ne.replaceWith(ee.header),Ne=ee.header,ie=ee.iconHolder,We=ee.headerTitle,Xe=ee.headerSubtitle,F=ee.closeButton,S=ke==null?void 0:ke.layout}else if(ke&&(ie&&(ie.style.display=ke.showIcon===!1?"none":""),We&&(We.style.display=ke.showTitle===!1?"none":""),Xe&&(Xe.style.display=ke.showSubtitle===!1?"none":""),F&&(F.style.display=ke.showCloseButton===!1?"none":""),ue.clearChatButtonWrapper)){let ee=ke.showClearChat;if(ee!==void 0){ue.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:It}=ue;It&&!It.classList.contains("persona-absolute")&&(ee?It.classList.remove("persona-ml-auto"):It.classList.add("persona-ml-auto"))}}let it=((af=o.layout)==null?void 0:af.showHeader)!==!1;Ne&&(Ne.style.display=it?"":"none");let Qe=((sf=o.layout)==null?void 0:sf.showFooter)!==!1;Ue&&(Ue.style.display=Qe?"":"none"),Rr(),Jo(),T!==h?T?qt(A,"auto"):(R=!0,bn()):A!==b&&qt(A,"auto"),b=A,h=T,He(),kt();let Re=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ie=JSON.stringify(o.messageActions)!==JSON.stringify(y),Ge=JSON.stringify((lf=o.layout)==null?void 0:lf.messages)!==JSON.stringify(C),W=((df=o.loadingIndicator)==null?void 0:df.render)!==($==null?void 0:$.render)||((cf=o.loadingIndicator)==null?void 0:cf.renderIdle)!==($==null?void 0:$.renderIdle)||((pf=o.loadingIndicator)==null?void 0:pf.showBubble)!==($==null?void 0:$.showBubble),Le=o.iterationDisplay!==U,De=((ff=(uf=o.features)==null?void 0:uf.showReasoning)!=null?ff:!0)!==(X!=null?X:!0)||((gf=(mf=o.features)==null?void 0:mf.showToolCalls)!=null?gf:!0)!==(_!=null?_:!0)||JSON.stringify((hf=o.features)==null?void 0:hf.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((xf=o.features)==null?void 0:xf.reasoningDisplay)!==JSON.stringify(ge);(Re||Ie||Ge||W||Le||De)&&q&&(Oa++,Bn(Je,q.getMessages(),fe));let ve=(yf=o.launcher)!=null?yf:{},Bt=(bf=ve.headerIconHidden)!=null?bf:!1,dt=(wf=(Cf=o.layout)==null?void 0:Cf.header)==null?void 0:wf.showIcon,cr=Bt||dt===!1,Lr=ve.headerIconName,Dt=(vf=ve.headerIconSize)!=null?vf:"48px";if(ie){let ee=re.querySelector(".persona-border-b-persona-divider"),It=ee==null?void 0:ee.querySelector(".persona-flex-col");if(cr)ie.style.display="none",ee&&It&&!ee.contains(It)&&ee.insertBefore(It,ee.firstChild);else{if(ie.style.display="",ie.style.height=Dt,ie.style.width=Dt,ee&&It&&(ee.contains(ie)?ie.nextSibling!==It&&(ie.remove(),ee.insertBefore(ie,It)):ee.insertBefore(ie,It)),Lr){let mt=parseFloat(Dt)||24,Ht=Ce(Lr,mt*.6,"#ffffff",2);Ht?ie.replaceChildren(Ht):ie.textContent=(Af=ve.agentIconText)!=null?Af:"\u{1F4AC}"}else if(ve.iconUrl){let mt=ie.querySelector("img");if(mt)mt.src=ve.iconUrl,mt.style.height=Dt,mt.style.width=Dt;else{let Ht=document.createElement("img");Ht.src=ve.iconUrl,Ht.alt="",Ht.className="persona-rounded-xl persona-object-cover",Ht.style.height=Dt,Ht.style.width=Dt,ie.replaceChildren(Ht)}}else{let mt=ie.querySelector("svg"),Ht=ie.querySelector("img");(mt||Ht)&&ie.replaceChildren(),ie.textContent=(Sf=ve.agentIconText)!=null?Sf:"\u{1F4AC}"}let Xt=ie.querySelector("img");Xt&&(Xt.style.height=Dt,Xt.style.width=Dt)}}let Ur=(kf=(Tf=o.layout)==null?void 0:Tf.header)==null?void 0:kf.showTitle,Pr=(Mf=(Ef=o.layout)==null?void 0:Ef.header)==null?void 0:Mf.showSubtitle;if(We&&(We.style.display=Ur===!1?"none":""),Xe&&(Xe.style.display=Pr===!1?"none":""),F){((Pf=(Lf=o.layout)==null?void 0:Lf.header)==null?void 0:Pf.showCloseButton)===!1?F.style.display="none":F.style.display="";let It=(If=ve.closeButtonSize)!=null?If:"32px",Xt=(Rf=ve.closeButtonPlacement)!=null?Rf:"inline";F.style.height=It,F.style.width=It;let{closeButtonWrapper:mt}=ue,Ht=Xt==="top-right",br=mt==null?void 0:mt.classList.contains("persona-absolute");if(mt&&Ht!==br)if(mt.remove(),Ht)mt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",re.style.position="relative",re.appendChild(mt);else{let ht=(Bf=(Hf=ve.clearChat)==null?void 0:Hf.placement)!=null?Bf:"inline",Cr=(Df=(Wf=ve.clearChat)==null?void 0:Wf.enabled)!=null?Df:!0;mt.className=Cr&&ht==="inline"?"":"persona-ml-auto";let ro=re.querySelector(".persona-border-b-persona-divider");ro&&ro.appendChild(mt)}if(F.style.color=ve.closeButtonColor||Kr.actionIconColor,ve.closeButtonBackgroundColor?(F.style.backgroundColor=ve.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ht=ve.closeButtonBorderWidth||"0px",Cr=ve.closeButtonBorderColor||"transparent";F.style.border=`${ht} solid ${Cr}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");ve.closeButtonBorderRadius?(F.style.borderRadius=ve.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(F.style.paddingLeft=ve.closeButtonPaddingX,F.style.paddingRight=ve.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),ve.closeButtonPaddingY?(F.style.paddingTop=ve.closeButtonPaddingY,F.style.paddingBottom=ve.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Wr=(Of=ve.closeButtonIconName)!=null?Of:"x",Do=(Ff=ve.closeButtonIconText)!=null?Ff:"\xD7";F.innerHTML="";let Vr=Ce(Wr,"28px","currentColor",1);Vr?F.appendChild(Vr):F.textContent=Do;let pr=(Nf=ve.closeButtonTooltipText)!=null?Nf:"Close chat",po=(_f=ve.closeButtonShowTooltip)!=null?_f:!0;if(F.setAttribute("aria-label",pr),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),po&&pr)){let ht=null,Cr=()=>{if(ht||!F)return;let Un=F.ownerDocument,Qa=Un.body;if(!Qa)return;ht=qo(Un,"div","persona-clear-chat-tooltip"),ht.textContent=pr;let Za=qo(Un,"div");Za.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Za);let qn=F.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(An),ht.style.left=`${qn.left+qn.width/2}px`,ht.style.top=`${qn.top-8}px`,ht.style.transform="translate(-50%, -100%)",Qa.appendChild(ht)},ro=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};mt.addEventListener("mouseenter",Cr),mt.addEventListener("mouseleave",ro),F.addEventListener("focus",Cr),F.addEventListener("blur",ro),mt._cleanupTooltip=()=>{ro(),mt&&(mt.removeEventListener("mouseenter",Cr),mt.removeEventListener("mouseleave",ro)),F&&(F.removeEventListener("focus",Cr),F.removeEventListener("blur",ro))}}}let{clearChatButton:nt,clearChatButtonWrapper:ft}=ue;if(nt){let ee=($f=ve.clearChat)!=null?$f:{},It=(Uf=ee.enabled)!=null?Uf:!0,Xt=(zf=(qf=o.layout)==null?void 0:qf.header)==null?void 0:zf.showClearChat,mt=Xt!==void 0?Xt:It,Ht=(Vf=ee.placement)!=null?Vf:"inline";if(ft){ft.style.display=mt?"":"none";let{closeButtonWrapper:br}=ue;!O()&&br&&!br.classList.contains("persona-absolute")&&(mt?br.classList.remove("persona-ml-auto"):br.classList.add("persona-ml-auto"));let Wr=Ht==="top-right",Do=ft.classList.contains("persona-absolute");if(!O()&&Wr!==Do&&mt){if(ft.remove(),Wr)ft.className="persona-absolute persona-top-4 persona-z-50",ft.style.right="48px",re.style.position="relative",re.appendChild(ft);else{ft.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ft.style.right="";let pr=re.querySelector(".persona-border-b-persona-divider"),po=ue.closeButtonWrapper;pr&&po&&po.parentElement===pr?pr.insertBefore(ft,po):pr&&pr.appendChild(ft)}let Vr=ue.closeButtonWrapper;Vr&&!Vr.classList.contains("persona-absolute")&&(Wr?Vr.classList.add("persona-ml-auto"):Vr.classList.remove("persona-ml-auto"))}}if(mt){if(!O()){let ht=(jf=ee.size)!=null?jf:"32px";nt.style.height=ht,nt.style.width=ht}let br=(Gf=ee.iconName)!=null?Gf:"refresh-cw",Wr=(Xf=ee.iconColor)!=null?Xf:"";nt.style.color=Wr||Kr.actionIconColor,nt.innerHTML="";let Do=O()?"14px":"20px",Vr=Ce(br,Do,"currentColor",2);if(Vr&&nt.appendChild(Vr),ee.backgroundColor?(nt.style.backgroundColor=ee.backgroundColor,nt.classList.remove("hover:persona-bg-gray-100")):(nt.style.backgroundColor="",nt.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let ht=ee.borderWidth||"0px",Cr=ee.borderColor||"transparent";nt.style.border=`${ht} solid ${Cr}`,nt.classList.remove("persona-border-none")}else nt.style.border="",nt.classList.add("persona-border-none");ee.borderRadius?(nt.style.borderRadius=ee.borderRadius,nt.classList.remove("persona-rounded-full")):(nt.style.borderRadius="",nt.classList.add("persona-rounded-full")),ee.paddingX?(nt.style.paddingLeft=ee.paddingX,nt.style.paddingRight=ee.paddingX):(nt.style.paddingLeft="",nt.style.paddingRight=""),ee.paddingY?(nt.style.paddingTop=ee.paddingY,nt.style.paddingBottom=ee.paddingY):(nt.style.paddingTop="",nt.style.paddingBottom="");let pr=(Jf=ee.tooltipText)!=null?Jf:"Clear chat",po=(Kf=ee.showTooltip)!=null?Kf:!0;if(nt.setAttribute("aria-label",pr),ft&&(ft._cleanupTooltip&&(ft._cleanupTooltip(),delete ft._cleanupTooltip),po&&pr)){let ht=null,Cr=()=>{if(ht||!nt)return;let Un=nt.ownerDocument,Qa=Un.body;if(!Qa)return;ht=qo(Un,"div","persona-clear-chat-tooltip"),ht.textContent=pr;let Za=qo(Un,"div");Za.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Za);let qn=nt.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(An),ht.style.left=`${qn.left+qn.width/2}px`,ht.style.top=`${qn.top-8}px`,ht.style.transform="translate(-50%, -100%)",Qa.appendChild(ht)},ro=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ft.addEventListener("mouseenter",Cr),ft.addEventListener("mouseleave",ro),nt.addEventListener("focus",Cr),nt.addEventListener("blur",ro),ft._cleanupTooltip=()=>{ro(),ft&&(ft.removeEventListener("mouseenter",Cr),ft.removeEventListener("mouseleave",ro)),nt&&(nt.removeEventListener("focus",Cr),nt.removeEventListener("blur",ro))}}}}let qr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ws],Br=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[sa.message,sa.messageAndClick];k=Ds({parsers:qr,handlers:Br,getSessionMetadata:m,updateSessionMetadata:f,emit:n.emit,documentRef:typeof document!="undefined"?document:null}),fe=Fh(o,k,oe),q.updateConfig(o),Bn(Je,q.getMessages(),fe),Lo.render(o.suggestionChips,q,ce,void 0,o.suggestionChipsConfig),Va(),ca(q.isStreaming());let On=((Yf=o.voiceRecognition)==null?void 0:Yf.enabled)===!0,Fn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Nn=((Zf=(Qf=o.voiceRecognition)==null?void 0:Qf.provider)==null?void 0:Zf.type)==="runtype";if(On&&(Fn||Nn))if(!N||!le){let ee=Ys(o.voiceRecognition,o.sendButton);ee&&(N=ee.micButton,le=ee.micButtonWrapper,Mt.insertBefore(le,fr),N.addEventListener("click",Qo),N.disabled=q.isStreaming())}else{let ee=(em=o.voiceRecognition)!=null?em:{},It=(tm=o.sendButton)!=null?tm:{},Xt=(rm=ee.iconName)!=null?rm:"mic",mt=(om=It.size)!=null?om:"40px",Ht=(nm=ee.iconSize)!=null?nm:mt,br=parseFloat(Ht)||24;N.style.width=Ht,N.style.height=Ht,N.style.minWidth=Ht,N.style.minHeight=Ht;let Wr=(sm=(am=ee.iconColor)!=null?am:It.textColor)!=null?sm:"currentColor";N.innerHTML="";let Do=Ce(Xt,br,Wr,2);Do?N.appendChild(Do):N.textContent="\u{1F3A4}";let Vr=(im=ee.backgroundColor)!=null?im:It.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=le==null?void 0:le.querySelector(".persona-send-button-tooltip"),po=(lm=ee.tooltipText)!=null?lm:"Start voice recognition";if(((dm=ee.showTooltip)!=null?dm:!1)&&po)if(pr)pr.textContent=po,pr.style.display="";else{let Cr=document.createElement("div");Cr.className="persona-send-button-tooltip",Cr.textContent=po,le==null||le.insertBefore(Cr,N)}else pr&&(pr.style.display="none");le.style.display="",N.disabled=q.isStreaming()}else N&&le&&(le.style.display="none",((pm=(cm=o.voiceRecognition)==null?void 0:cm.provider)==null?void 0:pm.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():lo&&Bo());if(((um=o.attachments)==null?void 0:um.enabled)===!0)if(!ct||!Te){let ee=(fm=o.attachments)!=null?fm:{},Xt=(gm=((mm=o.sendButton)!=null?mm:{}).size)!=null?gm:"40px";$t||($t=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),$t.style.display="none",Wt.insertBefore($t,ce)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((hm=ee.allowedTypes)!=null?hm:nn).join(","),Ke.multiple=((xm=ee.maxFiles)!=null?xm:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Wt.insertBefore(Ke,ce)),ct=x("div","persona-send-button-wrapper"),Te=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Te.type="button",Te.setAttribute("aria-label",(ym=ee.buttonTooltipText)!=null?ym:"Attach file");let mt=(bm=ee.buttonIconName)!=null?bm:"paperclip",Ht=Xt,br=parseFloat(Ht)||40,Wr=Math.round(br*.6);Te.style.width=Ht,Te.style.height=Ht,Te.style.minWidth=Ht,Te.style.minHeight=Ht,Te.style.fontSize="18px",Te.style.lineHeight="1",Te.style.backgroundColor="transparent",Te.style.color="var(--persona-primary, #111827)",Te.style.border="none",Te.style.borderRadius="6px",Te.style.transition="background-color 0.15s ease",Te.addEventListener("mouseenter",()=>{Te.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Te.addEventListener("mouseleave",()=>{Te.style.backgroundColor="transparent"});let Do=Ce(mt,Wr,"currentColor",1.5);Do?Te.appendChild(Do):Te.textContent="\u{1F4CE}",Te.addEventListener("click",po=>{po.preventDefault(),Ke==null||Ke.click()}),ct.appendChild(Te);let Vr=(Cm=ee.buttonTooltipText)!=null?Cm:"Attach file",pr=x("div","persona-send-button-tooltip");pr.textContent=Vr,ct.appendChild(pr),yt.append(ct),!At&&Ke&&$t&&(At=ta.fromConfig(ee),At.setPreviewsContainer($t),Ke.addEventListener("change",async()=>{At&&(Ke!=null&&Ke.files)&&(await At.handleFileSelect(Ke.files),Ke.value="")})),re.querySelector(".persona-attachment-drop-overlay")||re.appendChild(Nh(ee.dropOverlay))}else{ct.style.display="";let ee=(wm=o.attachments)!=null?wm:{};Ke&&(Ke.accept=((vm=ee.allowedTypes)!=null?vm:nn).join(","),Ke.multiple=((Am=ee.maxFiles)!=null?Am:4)>1),At&&At.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ct&&(ct.style.display="none"),At&&At.clearAttachments(),(Sm=re.querySelector(".persona-attachment-drop-overlay"))==null||Sm.remove();let rr=(Tm=o.sendButton)!=null?Tm:{},_n=(km=rr.useIcon)!=null?km:!1,wn=(Em=rr.iconText)!=null?Em:"\u2191",Tt=rr.iconName,Zr=(Mm=rr.tooltipText)!=null?Mm:"Send message",Zo=(Lm=rr.showTooltip)!=null?Lm:!1,zr=(Pm=rr.size)!=null?Pm:"40px",eo=rr.backgroundColor,zt=rr.textColor;if(_n){if($e.style.width=zr,$e.style.height=zr,$e.style.minWidth=zr,$e.style.minHeight=zr,$e.style.fontSize="18px",$e.style.lineHeight="1",$e.innerHTML="",zt?$e.style.color=zt:$e.style.color="var(--persona-button-primary-fg, #ffffff)",Tt){let ee=parseFloat(zr)||24,It=(zt==null?void 0:zt.trim())||"currentColor",Xt=Ce(Tt,ee,It,2);Xt?$e.appendChild(Xt):$e.textContent=wn}else $e.textContent=wn;$e.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",eo?($e.style.backgroundColor=eo,$e.classList.remove("persona-bg-persona-primary")):($e.style.backgroundColor="",$e.classList.add("persona-bg-persona-primary"))}else $e.textContent=(Rm=(Im=o.copy)==null?void 0:Im.sendButtonLabel)!=null?Rm:"Send",$e.style.width="",$e.style.height="",$e.style.minWidth="",$e.style.minHeight="",$e.style.fontSize="",$e.style.lineHeight="",$e.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",eo?($e.style.backgroundColor=eo,$e.classList.remove("persona-bg-persona-accent")):$e.classList.add("persona-bg-persona-accent"),zt?$e.style.color=zt:$e.classList.add("persona-text-white");rr.borderWidth?($e.style.borderWidth=rr.borderWidth,$e.style.borderStyle="solid"):($e.style.borderWidth="",$e.style.borderStyle=""),rr.borderColor?$e.style.borderColor=rr.borderColor:$e.style.borderColor="",rr.paddingX?($e.style.paddingLeft=rr.paddingX,$e.style.paddingRight=rr.paddingX):($e.style.paddingLeft="",$e.style.paddingRight=""),rr.paddingY?($e.style.paddingTop=rr.paddingY,$e.style.paddingBottom=rr.paddingY):($e.style.paddingTop="",$e.style.paddingBottom="");let Zt=fr==null?void 0:fr.querySelector(".persona-send-button-tooltip");if(Zo&&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,$e)}else Zt&&(Zt.style.display="none");let Vt=(Om=(Hm=o.layout)==null?void 0:Hm.contentMaxWidth)!=null?Om:O()?(Dm=(Wm=(Bm=o.launcher)==null?void 0:Bm.composerBar)==null?void 0:Wm.contentMaxWidth)!=null?Dm:"720px":void 0;Vt?(Je.style.maxWidth=Vt,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%",Wt&&(Wt.style.maxWidth=Vt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Ot&&(Ot.style.maxWidth=Vt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto")):(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight="",Je.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""));let or=(Fm=o.statusIndicator)!=null?Fm:{},to=(Nm=or.visible)!=null?Nm:!0;if(Yt.style.display=to?"":"none",q){let ee=q.getStatus();Fe(Yt,(Xt=>{var mt,Ht,br,Wr;return Xt==="idle"?(mt=or.idleText)!=null?mt:Dr.idle:Xt==="connecting"?(Ht=or.connectingText)!=null?Ht:Dr.connecting:Xt==="connected"?(br=or.connectedText)!=null?br:Dr.connected:Xt==="error"?(Wr=or.errorText)!=null?Wr:Dr.error:Dr[Xt]})(ee),or,ee)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let co=or.align==="left"?"persona-text-left":or.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(co)},open(){H()&&qt(!0,"api")},close(){H()&&qt(!1,"api")},toggle(){H()&&qt(!R,"api")},clearChat(){Z=!1,q.clearMessages(),io.clear(),mn();try{localStorage.removeItem(Wa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Wa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.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(),de==null||de.update()},setMessage(c){return!ce||q.isStreaming()?!1:(!R&&H()&&qt(!0,"system"),ce.value=c,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ce.value.trim();return g?(!R&&H()&&qt(!0,"system"),ce.value="",ce.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return q.isStreaming()?!1:((y=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(q.isVoiceActive()||(!R&&H()&&qt(!0,"system"),xt.manuallyDeactivated=!1,Qr(),q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),bo("user"),q.isVoiceActive()&&Cn()})),!0):lo?!0:Ka()?(!R&&H()&&qt(!0,"system"),xt.manuallyDeactivated=!1,Qr(),Wn("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Qr(),bo("user"),Wo()}),!0):!1:lo?(xt.manuallyDeactivated=!0,Qr(),Bo("user"),!0):!1},injectMessage(c){return!R&&H()&&qt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!R&&H()&&qt(!0,"system");let g=q.injectAssistantMessage(c);return B&&(B=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!R&&H()&&qt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!R&&H()&&qt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!R&&H()&&qt(!0,"system"),q.injectMessageBatch(c)},injectTestMessage(c){!R&&H()&&qt(!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(){!ye||!J||Sr()},hideEventStream(){pe&&Yr()},isEventStreamVisible(){return pe},showArtifacts(){So(o)&&(Z=!1,no(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){So(o)&&(Z=!0,no())},upsertArtifact(c){return So(o)?(Z=!1,q.upsertArtifact(c)):null},selectArtifact(c){So(o)&&q.selectArtifact(c)},clearArtifacts(){So(o)&&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()||!ce?!1:(ce.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 n.on(c,g)},off(c,g){n.off(c,g)},isOpen(){return H()&&R},isVoiceActive(){return xt.active},getState(){return{open:H()&&R,launcherEnabled:T,voiceActive:xt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!R&&H()&&qt(!0,"system");let g=Je.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});Je.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&H()&&qt(!0,"system");let g=Je.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});Je.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(){_o!=null&&(clearInterval(_o),_o=null),Ct.forEach(c=>c()),Y.remove(),we==null||we.remove(),I==null||I.destroy(),j==null||j.remove(),so&&F.removeEventListener("click",so)}};if((((Ou=t==null?void 0:t.debugTools)!=null?Ou:!1)||!!o.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,Ct.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),Ct.push(()=>{window.removeEventListener("persona:focusInput",g)}),ye){let X=Se=>{let ge=Se.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&mr.showEventStream()},_=Se=>{let ge=Se.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&mr.hideEventStream()};window.addEventListener("persona:showEventStream",X),window.addEventListener("persona:hideEventStream",_),Ct.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),Ct.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 Co=N0(o.persistState);if(Co&&H()){let c=_0(Co.storage),g=`${Co.keyPrefix}widget-open`,y=`${Co.keyPrefix}widget-voice`,C=`${Co.keyPrefix}widget-voice-mode`;if(c){let D=((Fu=Co.persist)==null?void 0:Fu.openState)&&c.getItem(g)==="true",$=((Nu=Co.persist)==null?void 0:Nu.voiceState)&&c.getItem(y)==="true",U=((_u=Co.persist)==null?void 0:_u.voiceState)&&c.getItem(C)==="true";if(D&&setTimeout(()=>{mr.open(),setTimeout(()=>{var X;if($||U)mr.startVoiceRecognition();else if((X=Co.persist)!=null&&X.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),($u=Co.persist)!=null&&$u.openState&&(n.on("widget:opened",()=>{c.setItem(g,"true")}),n.on("widget:closed",()=>{c.setItem(g,"false")})),(Uu=Co.persist)!=null&&Uu.voiceState&&(n.on("voice:state",X=>{c.setItem(y,X.active?"true":"false")}),n.on("user:message",X=>{c.setItem(C,X.viaVoice?"true":"false")})),Co.clearOnChatClear){let X=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(C)},_=()=>X();window.addEventListener("persona:clear-chat",_),Ct.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&H()&&setTimeout(()=>{mr.open()},0),Ko(),mr};var $0=(e,r)=>{let t=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(o)return Math.max(0,parseFloat(o[1]));let a=/^(\d+(?:\.\d+)?)%$/i.exec(t);return a?Math.max(0,r*parseFloat(a[1])/100):420},_h=(e,r)=>{var o,a;let t=(a=(o=r==null?void 0:r.launcher)==null?void 0:o.enabled)!=null?a:!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"},Hp=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=""},$h=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Hp(e)},Pp=e=>{e.style.transition=""},Ip=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=""},Rp=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=""},U0=(e,r,t,o,a)=>{a?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,o),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(o))},q0=(e,r,t,o,a,n)=>{let s=n?r:e;a==="left"?s.firstElementChild!==o&&s.replaceChildren(o,t):s.lastElementChild!==o&&s.replaceChildren(t,o)},Uh=(e,r,t,o,a,n,s)=>{var w,v,k,T,A,E;let i=vo(n),d=i.reveal==="push";U0(e,r,t,o,d),q0(e,r,t,o,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",a.className="persona-host",a.style.height="100%",a.style.minHeight="0",a.style.display="flex",a.style.flexDirection="column",a.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(v=(w=n==null?void 0:n.launcher)==null?void 0:w.mobileFullscreen)!=null?v:!0,p=(T=(k=n==null?void 0:n.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"),Ip(r),Pp(o),$h(o),Rp(t),kl(a,o),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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((E=(A=n==null?void 0:n.launcher)==null?void 0:A.zIndex)!=null?E:Or),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.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"),$h(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ip(r),Pp(o),Rp(t),kl(a,o);let b=i.animate?"transform 180ms ease":"none",h=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=s?"translateX(0)":h;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=b,o.style.transform=S,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",Pp(o),Hp(o),kl(a,o);let b=$0(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`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ip(r),Hp(o),Rp(t),kl(a,o);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;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${h}`,o.style.width=h,o.style.maxWidth=h,o.style.minWidth=h,o.style.minHeight="0",o.style.position="relative",o.style.overflow=b||L?"hidden":"visible",o.style.transition=S,b&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",a.style.width=i.width,a.style.minWidth=i.width,a.style.maxWidth=i.width,a.style.boxSizing="border-box")}},z0=(e,r)=>{let t=e.ownerDocument.createElement("div");return _h(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(o){_h(t,o)},destroy(){t.remove()}}},V0=(e,r)=>{var A,E,b,h;let{ownerDocument:t}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let a=e.tagName.toUpperCase();if(a==="BODY"||a==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let n=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),o.insertBefore(s,e),d.appendChild(e);let m=null,f=()=>{m==null||m.disconnect(),m=null},w=()=>{f(),vo(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(m=new ResizeObserver(()=>{Uh(s,i,d,l,u,r,p)}),m.observe(s))},v=()=>{Uh(s,i,d,l,u,r,p),w()},k=s.ownerDocument.defaultView,T=()=>{v()};return k==null||k.addEventListener("resize",T),vo(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(),o.isConnected&&(n&&n.parentNode===o?o.insertBefore(e,n):o.appendChild(e)),s.remove()}}},Os=(e,r)=>hr(r)?V0(e,r):z0(e,r);var Bp={},j0=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},G0=()=>{try{if(typeof Bp!="undefined"&&Bp.url)return new URL("../widget.css",Bp.url).href}catch{}return null},qh=(e,r)=>{let t=G0(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let a=r.head.querySelector("link[data-persona]");if(!a)return;let n=a.cloneNode(!0);e.insertBefore(n,e.firstChild)};if(e instanceof ShadowRoot)if(t){let a=r.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),e.insertBefore(a,e.firstChild)}else o();else if(!r.head.querySelector("link[data-persona]")&&t){let n=r.createElement("link");n.rel="stylesheet",n.href=t,n.setAttribute("data-persona","true"),r.head.appendChild(n)}},zh=e=>{var k;let r=j0(e.target),t=e.useShadowDom===!0,o=r.ownerDocument,a=e.config,n=Os(r,a),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=o.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),qh(O,o)}else T.appendChild(h),qh(T,o);return r.id&&h.setAttribute("data-persona-instance",r.id),h},l=()=>{n.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},p=()=>{let T=d(n.host,a);s=Tl(T,a,{debugTools:e.debugTools}),u()},m=()=>{i.forEach(T=>T()),i=[],s.destroy()};p(),(k=e.onReady)==null||k.call(e);let f=T=>{m(),n.destroy(),n=Os(r,T),a=T,p()},w={update(T){var L,O,H,R,B,V;let A={...a,...T,launcher:{...(L=a==null?void 0:a.launcher)!=null?L:{},...(O=T==null?void 0:T.launcher)!=null?O:{},dock:{...(R=(H=a==null?void 0:a.launcher)==null?void 0:H.dock)!=null?R:{},...(V=(B=T==null?void 0:T.launcher)==null?void 0:B.dock)!=null?V:{}}}},E=hr(a),b=hr(A),h=Tn(a),S=Tn(A);if(E!==b||h!==S){f(A);return}a=A,n.updateConfig(a),s.update(T),l()},destroy(){m(),n.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(w,{get(T,A,E){if(A==="host")return n.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 Jh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),X0=new Set(["button","a","input","select","textarea","details","summary"]),J0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Wp=/\b(product|card|item|listing|result)\b/i,Op=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,K0=3e3,Y0=100;function Kh(e){let r=typeof e.className=="string"?e.className:"";if(Wp.test(r)||e.id&&Wp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let o=e.attributes[t];if(o.name.startsWith("data-")&&Wp.test(o.value))return!0}return!1}function Yh(e){var r;return Op.test(((r=e.textContent)!=null?r:"").trim())}function Qh(e){var t;let r=e.querySelectorAll("a[href]");for(let o=0;o<r.length;o++){let a=(t=r[o].getAttribute("href"))!=null?t:"";if(a&&a!=="#"&&!a.toLowerCase().startsWith("javascript:"))return!0}return!1}function Q0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Vh(e){let r=e.match(Op);return r?r[0]:null}function jh(e){var o,a,n;let r=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(r&&((a=r.textContent)!=null&&a.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(n=t==null?void 0:t.textContent)!=null&&n.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Z0(e){let r=[],t=o=>{let a=o.trim();a&&!r.includes(a)&&r.push(a)};return e.querySelectorAll("button").forEach(o=>{var a;return t((a=o.textContent)!=null?a:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var a;return t((a=o.textContent)!=null?a:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var a;t((a=o.value)!=null?a:"")}),r.slice(0,6)}var eC="commerce-card",tC="result-card";function Gh(e){return!Kh(e)||!Yh(e)||!Qh(e)&&!Q0(e)?0:5200}function Xh(e){var o;return!Kh(e)||Yh(e)||!Qh(e)||((o=e.textContent)!=null?o:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Fp=[{id:eC,scoreElement(e){return Gh(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let o=t.text.trim();return!!(o.length===0||Op.test(o)&&o.length<32)}return!0},formatSummary(e,r){var d,l,u;if(Gh(e)===0)return null;let{title:t,href:o}=jh(e),a=(u=(l=Vh(((d=e.textContent)!=null?d:"").trim()))!=null?l:Vh(r.text))!=null?u:"",n=Z0(e);return[o&&t?`[${t}](${o})${a?` \u2014 ${a}`:""}`:t?`${t}${a?` \u2014 ${a}`:""}`:a||r.text.trim().slice(0,120),`selector: ${r.selector}`,n.length?`actions: ${n.join(", ")}`:""].filter(Boolean).join(`
|
|
148
|
-
`)}},{id:
|
|
149
|
-
`)}}];function
|
|
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 Ct=[];Ct.push(()=>{document.removeEventListener("keydown",Nr)});let sr=null,ir=null;Ct.push(()=>{sr==null||sr(),sr=null,ir==null||ir(),ir=null}),Me&&Ct.push(()=>{Me==null||Me.disconnect(),Me=null}),Ct.push(()=>{wr==null||wr(),wr=null,jn(),rt&&(rt.remove(),rt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),ye&&Ct.push(()=>{se!==null&&(cancelAnimationFrame(se),se=null),de==null||de.destroy(),de=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(),Ct.push(()=>{an&&(an(),an=null)});let yn=(Iu=n.features)==null?void 0:Iu.streamAnimation;if(yn!=null&&yn.type&&yn.type!=="none"){let c=Ss(yn.type,yn.plugins);c&&(sp(c,e),Ct.push(()=>eh(e)))}let Ln=vh(Ot),sn=null,q,xe=!1,ln=Xg(),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,xt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Na=(Hu=(Ru=n.voiceRecognition)==null?void 0:Ru.autoResume)!=null?Hu:!1,bn=c=>{o.emit("voice:state",{active:xt.active,source:c,timestamp:Date.now()})},Qr=()=>{f(c=>({...c,voiceState:{active:xt.active,timestamp:Date.now(),manuallyDeactivated:xt.manuallyDeactivated}}))},$s=()=>{var C,D;if(((C=n.voiceRecognition)==null?void 0:C.enabled)===!1)return;let c=Lp(d.voiceState),g=!!c.active,y=Number((D=c.timestamp)!=null?D:0);xt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<O0&&setTimeout(()=>{var $,U;xt.active||(xt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),bn("restore"),q.isVoiceActive()&&Co()}):Wo("restore"))},1e3)},Us=()=>q?Fh(q.getMessages()).filter(c=>!c.__skipPersist):[];function da(c){if(!(i!=null&&i.save))return;let y={messages:c?Fh(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")||he,Ho=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Gn=!1},_a=()=>{Hn!==null&&(cancelAnimationFrame(Hn),Hn=null),Ro=!1,Ho()},Jn=()=>{if(!Ze()||pe){at.parentNode&&at.remove(),at.style.display="none";return}at.parentNode!==re&&re.appendChild(at),Rr();let c=Cs(he)>0;at.style.display=In.isFollowing()||!c?"none":""},$a=()=>{In.pause()&&(_a(),Jn())},mo=()=>{In.resume(),Jn()},go=(c=!1)=>{In.isFollowing()&&(!c&&!xe||(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 Se=Cs(c);Se!==C&&(C=Se,D=C-y);let ge=_-$,te=Math.min(ge/g,1),be=U(te),ke=y+D*be;c.scrollTop=ke,Rn=c.scrollTop,te<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"&&o.emit("assistant:message",y),y.role==="assistant"&&(C!=null&&C.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(C?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),la.clear(),g.forEach((y,C)=>{la.set(C,y)})},Bo=(c,g,y)=>{var Qe,pt,ut,Re,Ie,Ge;let C=document.createElement("div"),$=(()=>{var Le;let W=a.find(De=>De.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Le=n.loadingIndicator)!=null&&Le.render)return n.loadingIndicator.render})(),U=(W,Le)=>Le==null?!1:typeof Le=="string"?(W.textContent=Le,!0):(W.appendChild(Le),!0),X=new Set,_=new Set,Se=a.some(W=>W.renderAskUserQuestion),ge=[],te=[],be=n.enableComponentStreaming!==!1;if(g.forEach(W=>{var Ur,Pr,ot,ft,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo;X.add(W.id);let Le=Se&&so(W),De=!Le&&W.role==="assistant"&&!W.variant&&be&&Cl(W);if(!De&&Nn.has(W.id)){let Tt=c.querySelector(`#wrapper-${W.id}`);Tt==null||Tt.removeAttribute("data-preserve-runtime"),Nn.delete(W.id)}let Ye=so(W)?`:${(Ur=W.agentMetadata)!=null&&Ur.askUserQuestionAnswered?"a":"u"}:${(Pr=W.agentMetadata)!=null&&Pr.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",ve=Gg(W,Oa)+Ye,Bt=Le||De?null:Jg(ln,W.id,ve);if(Bt){C.appendChild(Bt.cloneNode(!0)),so(W)&&((ot=W.toolCall)!=null&&ot.id)&&((ft=W.agentMetadata)==null?void 0:ft.awaitingLocalTool)===!0&&!((qr=W.agentMetadata)!=null&&qr.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,n,ue.composerOverlay));return}let dt=null,cr=a.find(Tt=>!!(W.variant==="reasoning"&&Tt.renderReasoning||W.variant==="tool"&&Tt.renderToolCall||W.variant==="approval"&&Tt.renderApproval||!W.variant&&Tt.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 Tt=c.querySelector(`#wrapper-${W.id}`);Tt==null||Tt.removeAttribute("data-preserve-runtime");return}if(so(W)&&((No=(Fo=n.features)==null?void 0:Fo.askUserQuestion)==null?void 0:No.enabled)!==!1){let Tt=a.find(Zr=>typeof Zr.renderAskUserQuestion=="function");if(Tt&&oe.current){let Zr=Pn.get(W.id),Zn=Zr!==ve,zr=null;if(Zn){let{payload:Zt,complete:Vt}=io(W),nr=W.id,tn=()=>{var cn;return(cn=oe.current)==null?void 0:cn.getMessages().find(gr=>gr.id===nr)};zr=Tt.renderAskUserQuestion({message:W,payload:Zt,complete:Vt,resolve:cn=>{var $n;let gr=tn();gr&&(($n=oe.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=oe.current)==null||$n.markAskUserQuestionResolved(cn),(eo=oe.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,ue.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),ge.push({messageId:W.id,fingerprint:ve,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,ue.composerOverlay));return}}else if(cr)if(W.variant==="reasoning"&&W.reasoning&&cr.renderReasoning){if(!_e)return;dt=cr.renderReasoning({message:W,defaultRenderer:()=>mp(W,n),config:n})}else if(W.variant==="tool"&&W.toolCall&&cr.renderToolCall){if(!je)return;dt=cr.renderToolCall({message:W,defaultRenderer:()=>gp(W,n),config:n})}else if(W.variant==="approval"&&W.approval&&cr.renderApproval){if(n.approval===!1)return;dt=cr.renderApproval({message:W,defaultRenderer:()=>Ap(W,n),config:n})}else cr.renderMessage&&(dt=cr.renderMessage({message:W,defaultRenderer:()=>{let Tt=Ea(W,y,Lr,n.messageActions,Ee,{loadingIndicatorRenderer:$,widgetConfig:n});return W.role!=="user"&&kp(Tt,W,n,q),Tt},config:n}));if(!dt&&De){let Tt=wl(W);if(Tt){let Zr=Nn.get(W.id),Zn=Zr!==ve,zr=n.wrapComponentDirectiveInBubble!==!1,en=null;if(Zn){let zt=bl(Tt,{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),te.push({messageId:W.id,fingerprint:ve,bubble:en});return}}}if(!dt)if(W.variant==="reasoning"&&W.reasoning){if(!_e)return;dt=mp(W,n)}else if(W.variant==="tool"&&W.toolCall){if(!je)return;dt=gp(W,n)}else if(W.variant==="approval"&&W.approval){if(n.approval===!1)return;dt=Ap(W,n)}else{let Tt=(wo=n.layout)==null?void 0:wo.messages;Tt!=null&&Tt.renderUserMessage&&W.role==="user"?dt=Tt.renderUserMessage({message:W,config:n,streaming:!!W.streaming}):Tt!=null&&Tt.renderAssistantMessage&&W.role==="assistant"?dt=Tt.renderAssistantMessage({message:W,config:n,streaming:!!W.streaming}):dt=Ea(W,y,Tt,n.messageActions,Ee,{loadingIndicatorRenderer:$,widgetConfig:n}),W.role!=="user"&&dt&&kp(dt,W,n,q)}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${W.id}`,Dt.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Dt.classList.add("persona-justify-end"),(dt==null?void 0:dt.getAttribute("data-persona-component-directive"))==="true"&&Dt.classList.add("persona-w-full"),Dt.appendChild(dt),Kg(ln,W.id,ve,Dt),C.appendChild(Dt)}),ue.composerOverlay&&ue.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let De=Le.getAttribute("data-persona-ask-sheet-for");De&&!_.has(De)&&Lo(ue.composerOverlay,De)}),(pt=(Qe=n.features)==null?void 0:Qe.toolCallDisplay)!=null&&pt.grouped){let W=[],Le=[];g.forEach(De=>{if(De.variant==="tool"&&De.toolCall&&je){Le.push(De);return}Le.length>1&&W.push(Le),Le=[]}),Le.length>1&&W.push(Le),W.forEach((De,Ye)=>{var Pr,ot;let ve=De.map(ft=>Array.from(C.children).find(qr=>qr instanceof HTMLElement&&qr.getAttribute("data-wrapper-id")===ft.id)).filter(ft=>!!ft);if(ve.length<2)return;let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-tool-group-${Ye}-${De[0].id}`,Bt.setAttribute("data-wrapper-id",`tool-group-${Ye}-${De[0].id}`);let dt=document.createElement("div");dt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",dt.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 ${De.length} tools`,Dt=(ot=(Pr=n.toolCall)==null?void 0:Pr.renderGroupedSummary)==null?void 0:ot.call(Pr,{messages:De,toolCalls:De.map(ft=>ft.toolCall).filter(ft=>!!ft),defaultSummary:Lr,config:n});U(cr,Dt)||(cr.textContent=Lr);let Ur=document.createElement("div");Ur.className="persona-tool-group-stack persona-flex persona-flex-col",dt.append(cr,Ur),Bt.appendChild(dt),ve[0].before(Bt),ve.forEach((ft,qr)=>{let Br=document.createElement("div");Br.className="persona-tool-group-item persona-relative",Br.setAttribute("data-persona-tool-group-item","true"),qr<ve.length-1&&Br.setAttribute("data-persona-tool-group-connector","true"),Br.appendChild(ft),Ur.appendChild(Br)})})}Yg(ln,X);let ke=g.some(W=>W.role==="assistant"&&W.streaming),qe=g[g.length-1],it=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(xe&&g.some(W=>W.role==="user")&&!ke&&!it){let W={config:n,streaming:!0,location:"standalone",defaultRenderer:oa},Le=a.find(Ye=>Ye.renderLoadingIndicator),De=null;if(Le!=null&&Le.renderLoadingIndicator&&(De=Le.renderLoadingIndicator(W)),De===null&&((ut=n.loadingIndicator)!=null&&ut.render)&&(De=n.loadingIndicator.render(W)),De===null&&(De=oa()),De){let Ye=document.createElement("div"),ve=((Re=n.loadingIndicator)==null?void 0:Re.showBubble)!==!1;Ye.className=ve?["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(" "),Ye.setAttribute("data-typing-indicator","true"),Ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ye.appendChild(De);let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id="wrapper-typing-indicator",Bt.setAttribute("data-wrapper-id","typing-indicator"),Bt.appendChild(Ye),C.appendChild(Bt)}}if(!xe&&g.length>0){let W=g[g.length-1],Le={config:n,lastMessage:W,messageCount:g.length},De=a.find(ve=>ve.renderIdleIndicator),Ye=null;if(De!=null&&De.renderIdleIndicator&&(Ye=De.renderIdleIndicator(Le)),Ye===null&&((Ie=n.loadingIndicator)!=null&&Ie.renderIdle)&&(Ye=n.loadingIndicator.renderIdle(Le)),Ye){let ve=document.createElement("div"),Bt=((Ge=n.loadingIndicator)==null?void 0:Ge.showBubble)!==!1;ve.className=Bt?["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(" "),ve.setAttribute("data-idle-indicator","true"),ve.appendChild(Ye);let dt=document.createElement("div");dt.className="persona-flex",dt.id="wrapper-idle-indicator",dt.setAttribute("data-wrapper-id","idle-indicator"),dt.appendChild(ve),C.appendChild(dt)}}if(Xi(c,C),ge.length>0)for(let{messageId:W,fingerprint:Le,bubble:De}of ge){let Ye=c.querySelector(`#wrapper-${W}`);Ye&&De!==null&&(Ye.replaceChildren(De),Ye.setAttribute("data-bubble-fp",Le),Pn.set(W,Le))}if(Pn.size>0)for(let W of Pn.keys())X.has(W)||Pn.delete(W);if(te.length>0)for(let{messageId:W,fingerprint:Le,bubble:De}of te){let Ye=c.querySelector(`#wrapper-${W}`);Ye&&De!==null&&(Ye.replaceChildren(De),Ye.setAttribute("data-bubble-fp",Le),Nn.set(W,Le))}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)||Ft(!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};Ct.push(()=>Ua());let xo=null,Gs=()=>{var y;if(xo)return;let c=C=>{C.key==="Escape"&&(C.isComposing||Ft(!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};Ct.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 pt,ut,Re,Ie;if(!O())return;let c=ue.peekBanner,g=ue.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let y=(pt=q==null?void 0:q.getMessages())!=null?pt:[],C;for(let Ge=y.length-1;Ge>=0;Ge--){let W=y[Ge];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,Se=((ut=_==null?void 0:_.isAnimating)==null?void 0:ut.call(_,C))===!0,ge=_!==null&&($||Se);ge&&_&&!za.has(_.name)&&(sp(_,e),za.add(_.name));let te=ge&&(_!=null&&_.containerClass)?_.containerClass:null,be=(Re=g.dataset.personaPeekStreamClass)!=null?Re:null;be&&be!==te&&(g.classList.remove(be),delete g.dataset.personaPeekStreamClass),te&&be!==te&&(g.classList.add(te),g.dataset.personaPeekStreamClass=te),ge?(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 ke=ge?Zi(D,X.buffer,_,C,$):D;if(ge&&X.placeholder==="skeleton"&&$&&(!ke||!ke.trim())){let Ge=document.createElement("div"),W=ks();W.classList.add("persona-pill-peek__skeleton"),Ge.appendChild(W),Xi(g,Ge)}else{let Ge=Math.max(0,ke.length-100),W=ke.length>100?ke.slice(-100):ke,Le=Jo(W);if(!ge||!_){let De=ke.length>100?`\u2026${W}`:W;g.textContent!==De&&(g.textContent=De)}else{let De=Le;(_.wrap==="char"||_.wrap==="word")&&(De=Ts(Le,_.wrap,`peek-${C.id}`,{skipTags:_.skipTags,startIndex:Ge}));let Ye=document.createElement("div");if(Ye.innerHTML=De,_.useCaret&&W.length>0){let ve=el(),Bt=Ye.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=Bt[Bt.length-1];dt!=null&&dt.parentNode?dt.parentNode.insertBefore(ve,dt.nextSibling):Ye.appendChild(ve)}Xi(g,Ye),(Ie=_.onAfterRender)==null||Ie.call(_,{container:g,bubble:c,messageId:C.id,message:C,speed:X.speed,duration:X.duration})}}let Qe=xe||yo;c.classList.toggle("persona-pill-peek--visible",Qe)};if(O()){let c=ue.peekBanner;if(c){let C=D=>{D.preventDefault(),D.stopPropagation(),Ft(!0,"user")};c.addEventListener("pointerdown",C),Ct.push(()=>{c.removeEventListener("pointerdown",C)})}let g=()=>{yo||(yo=!0,Kn())},y=()=>{yo&&(yo=!1,Kn())};G.addEventListener("pointerenter",g),G.addEventListener("pointerleave",y),Ct.push(()=>{G.removeEventListener("pointerenter",g),G.removeEventListener("pointerleave",y)}),we&&(we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),Ct.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}))}let Js=c=>{var be,ke,qe,it,Qe,pt,ut,Re;let g=(ke=(be=n.launcher)==null?void 0:be.composerBar)!=null?ke:{},y=(qe=g.expandedSize)!=null?qe:"anchored",C=(it=g.bottomOffset)!=null?it:"16px",D=g.collapsedMaxWidth,$=(Qe=g.expandedMaxWidth)!=null?Qe:"880px",U=(pt=g.expandedTopOffset)!=null?pt:"5vh",X=(ut=g.modalMaxWidth)!=null?ut:"880px",_=(Re=g.modalMaxHeight)!=null?Re:"min(90vh, 800px)",Se="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",te=Y.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",we){let Ie=we.style;Ie.bottom=C,Ie.width=D!=null?D:""}if(c&&y!=="fullscreen"){if(y==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=X,te.maxWidth=Se,te.maxHeight=_,te.height=_;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${C} + ${ge})`,te.top=U,te.width=$,te.maxWidth=Se}},bo=()=>{var _,Se,ge,te,be,ke,qe,it;if(!H())return;if(O()){let pt=(ge=((Se=(_=n.launcher)==null?void 0:_.composerBar)!=null?Se:{}).expandedSize)!=null?ge:"anchored",ut=R?"expanded":"collapsed";Y.dataset.state=ut,Y.dataset.expandedSize=pt,we&&(we.dataset.state=ut,we.dataset.expandedSize=pt),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),re.style.display=R?"flex":"none",Mn(),R?(js(),Gs()):(Ua(),qa()),Kn();return}let c=hr(n),g=(te=e.ownerDocument.defaultView)!=null?te:window,y=(ke=(be=n.launcher)==null?void 0:be.mobileBreakpoint)!=null?ke:640,C=(it=(qe=n.launcher)==null?void 0:qe.mobileFullscreen)!=null?it:!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":j&&(j.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":"":j&&(j.style.display=c?"none":""))},Ft=(c,g="user")=>{var $,U;if(!H()||R===c)return;let y=R;R=c,bo();let C=(()=>{var qe,it,Qe,pt,ut,Re,Ie,Ge,W,Le;let X=(it=(qe=n.launcher)==null?void 0:qe.sidebarMode)!=null?it:!1,_=(Qe=e.ownerDocument.defaultView)!=null?Qe:window,Se=(ut=(pt=n.launcher)==null?void 0:pt.mobileFullscreen)!=null?ut:!0,ge=(Ie=(Re=n.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Ie:640,te=_.innerWidth<=ge,be=hr(n)&&Se&&te,ke=O()&&((Le=(W=(Ge=n.launcher)==null?void 0:Ge.composerBar)==null?void 0:W.expandedSize)!=null?Le:"fullscreen")==="fullscreen";return X||Se&&te&&T||be||ke})();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&&(He(),go(!0));let D={open:R,source:g,timestamp:Date.now()};R&&!y?o.emit("widget:opened",D):!R&&y&&o.emit("widget:closed",D),o.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:xt.active,streaming:q.isStreaming()})},ca=c=>{$t(c?"stop":"send"),N&&(N.disabled=c),Ln.buttons.forEach(g=>{g.disabled=c}),Ue.dataset.personaComposerStreaming=c?"true":"false",Ue.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=()=>{xt.active||ce&&ce.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>pa(),200)});let Va=()=>{var y,C,D,$,U,X,_,Se,ge,te,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.",ce.placeholder=(X=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?X:"How can I help...";let c=he.querySelector("[data-persona-intro-card]");if(c){let ke=((_=n.copy)==null?void 0:_.showWelcomeCard)!==!1;c.style.display=ke?"":"none",ke?(he.classList.remove("persona-gap-3"),he.classList.add("persona-gap-6")):(he.classList.remove("persona-gap-6"),he.classList.add("persona-gap-3"))}!((ge=(Se=n.sendButton)==null?void 0:Se.useIcon)!=null&&ge)&&!(q!=null&&q.isStreaming())&&($e.textContent=(be=(te=n.copy)==null?void 0:te.sendButtonLabel)!=null?be:"Send"),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.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=Je.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(Je,c,fe),Ks(),q&&(c.some(D=>D.role==="user")?Ln.render([],q,ce,c):Ln.render(n.suggestionChips,q,ce,c,n.suggestionChipsConfig)),go(!xe),Vs(c);let g=[...c].reverse().find(C=>C.role==="user"),y=xt.lastUserMessageId;g&&g.id!==y&&(xt.lastUserMessageId=g.id,o.emit("user:message",g)),xt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),da(c),Kn()},onStatusChanged(c){var C;let g=(C=n.statusIndicator)!=null?C:{};Fe(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){xe=c,ca(c),q&&Bo(Je,q.getMessages(),fe),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")):(xt.active=!1,Wn(),bn("system"),Qr());break}},onArtifactsState(c){M=c,on(),da()}}),oe.current=q,((Wu=(Bu=n.voiceRecognition)==null?void 0:Bu.provider)==null?void 0:Wu.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=Lp(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)||Ft(!0,"auto")},Ga=c=>{var D;if(c.preventDefault(),q.isStreaming()){q.cancel();return}let g=ce.value.trim(),y=(D=At==null?void 0:At.hasAttachments())!=null?D:!1;if(!g&&!y)return;ja();let C;y&&(C=[],C.push(...At.getContentParts()),g&&C.push(gs(g))),ce.value="",ce.style.height="auto",q.sendMessage(g,{contentParts:C}),y&&At.clearAttachments()},Xa=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),$e.click())},Ja=async c=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!At)return;let g=N0(c.clipboardData);g.length!==0&&(c.preventDefault(),await At.handleFiles(g))},$r=null,dn=!1,Yn=null,lt=null,Ka=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Wo=(c="user")=>{var $,U,X,_,Se,ge,te;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=ce.value;$r.onresult=be=>{let ke="",qe="";for(let Qe=0;Qe<be.results.length;Qe++){let pt=be.results[Qe],ut=pt[0].transcript;pt.isFinal?ke+=ut+" ":qe=ut}let it=D+ke+qe;ce.value=it,Yn&&clearTimeout(Yn),(ke||qe)&&(Yn=window.setTimeout(()=>{let Qe=ce.value.trim();Qe&&$r&&dn&&(Bn(),ce.value="",ce.style.height="auto",q.sendMessage(Qe,{viaVoice:!0}))},C))},$r.onerror=be=>{be.error!=="no-speech"&&Bn()},$r.onend=()=>{if(dn){let be=ce.value.trim();be&&be!==D.trim()&&(ce.value="",ce.style.height="auto",q.sendMessage(be,{viaVoice:!0})),Bn()}};try{if($r.start(),dn=!0,xt.active=!0,c!=="system"&&(xt.manuallyDeactivated=!1),bn(c),Qr(),N){let be=(X=n.voiceRecognition)!=null?X:{};lt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((te=(ge=be.iconSize)!=null?ge:(Se=n.sendButton)==null?void 0:Se.size)!=null?te:"40")||24};let ke=be.recordingBackgroundColor,qe=be.recordingIconColor,it=be.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=ke!=null?ke:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=qe!=null?qe:"var(--persona-voice-recording-indicator, #ffffff)",qe){let Qe=N.querySelector("svg");Qe&&Qe.setAttribute("stroke",qe)}it&&(N.style.borderColor=it),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(xt.active=!1,bn(c),Qr(),N){if(N.classList.remove("persona-voice-recording"),lt){N.style.backgroundColor=lt.backgroundColor,N.style.color=lt.color,N.style.borderColor=lt.borderColor;let g=N.querySelector("svg");g&&g.setAttribute("stroke",lt.color||"currentColor"),lt=null}N.setAttribute("aria-label","Start voice recognition")}}},Ys=(c,g)=>{var pt,ut,Re,Ie,Ge,W,Le,De;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((pt=c==null?void 0:c.provider)==null?void 0:pt.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=(ut=c==null?void 0:c.iconName)!=null?ut:"mic",_=(Re=g==null?void 0:g.size)!=null?Re:"40px",Se=(Ie=c==null?void 0:c.iconSize)!=null?Ie:_,ge=parseFloat(Se)||24,te=(Ge=c==null?void 0:c.backgroundColor)!=null?Ge: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=Se,U.style.height=Se,U.style.minWidth=Se,U.style.minHeight=Se,U.style.fontSize="18px",U.style.lineHeight="1",be?U.style.color=be:U.style.color="var(--persona-text, #111827)";let qe=Ce(X,ge,be||"currentColor",1.5);qe?U.appendChild(qe):U.textContent="\u{1F3A4}",te?U.style.backgroundColor=te: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 it=(Le=c==null?void 0:c.tooltipText)!=null?Le:"Start voice recognition";if(((De=c==null?void 0:c.showTooltip)!=null?De:!1)&&it){let Ye=x("div","persona-send-button-tooltip");Ye.textContent=it,$.appendChild(Ye)}return{micButton:U,micButtonWrapper:$}},ua=()=>{var g,y,C,D,$;if(!N||lt)return;let c=(g=n.voiceRecognition)!=null?g:{};lt={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,_,Se;if(!N)return;let y=N.querySelector("svg");y&&y.remove();let C=(Se=lt==null?void 0:lt.iconSize)!=null?Se: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,_,Se,ge,te,be,ke,qe;if(!N)return;ua();let c=(X=n.voiceRecognition)!=null?X:{},g=q.getVoiceInterruptionMode(),y=(_=c.processingIconName)!=null?_:"loader",C=(ge=(Se=c.processingIconColor)!=null?Se:lt==null?void 0:lt.color)!=null?ge:"",D=(be=(te=c.processingBackgroundColor)!=null?te:lt==null?void 0:lt.backgroundColor)!=null?be:"",$=(qe=(ke=c.processingBorderColor)!=null?ke:lt==null?void 0:lt.borderColor)!=null?qe:"";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 Se,ge,te,be,ke,qe,it,Qe,pt,ut,Re,Ie;if(!N)return;ua();let c=(Se=n.voiceRecognition)!=null?Se:{},g=q.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",C=(ge=c.speakingIconName)!=null?ge:y,D=(qe=c.speakingIconColor)!=null?qe:g==="barge-in"?(be=(te=c.recordingIconColor)!=null?te:lt==null?void 0:lt.color)!=null?be:"":(ke=lt==null?void 0:lt.color)!=null?ke:"",$=(pt=c.speakingBackgroundColor)!=null?pt:g==="barge-in"?(it=c.recordingBackgroundColor)!=null?it:"var(--persona-voice-recording-bg, #ef4444)":(Qe=lt==null?void 0:lt.backgroundColor)!=null?Qe:"",U=(Ie=c.speakingBorderColor)!=null?Ie:g==="barge-in"?(ut=c.recordingBorderColor)!=null?ut:"":(Re=lt==null?void 0:lt.borderColor)!=null?Re:"";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(),lt&&(N.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",N.style.color=(g=lt.color)!=null?g:"",N.style.borderColor=(y=lt.borderColor)!=null?y:"",fa(lt.iconName,lt.color||"currentColor"),lt=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(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()});return}q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),xt.manuallyDeactivated=!q.isVoiceActive(),Qr(),bn("user"),q.isVoiceActive()?Co():Wn()});return}if(dn){let y=ce.value.trim();xt.manuallyDeactivated=!0,Qr(),Bn("user"),y&&(ce.value="",ce.style.height="auto",q.sendMessage(y))}else xt.manuallyDeactivated=!1,Qr(),Wo("user")};hn=Qn,N&&(N.addEventListener("click",Qn),Ct.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 et=o.on("assistant:complete",()=>{Na&&(xt.active||xt.manuallyDeactivated||Na==="assistant"&&!xt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!xt.active&&!xt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),bn("auto"),q.isVoiceActive()&&Co()}):Wo("auto"))},600))});Ct.push(et);let P=o.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});Ct.push(P);let z=()=>{Ft(!R,"user")},I=null,j=null;if(T&&!O()){let c=a.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});g&&(j=g)}j||(I=Ms(n,z))}I?e.appendChild(I.element):j&&e.appendChild(j),bo(),Ln.render(n.suggestionChips,q,ce,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming()),go(!0),$s(),E&&(!T||O()?setTimeout(()=>pa(),0):R&&setTimeout(()=>pa(),200));let He=()=>{var _,Se,ge,te,be,ke,qe,it,Qe,pt,ut,Re,Ie,Ge,W,Le,De,Ye,ve,Bt,dt,cr;if(O()){Rr(),bo();return}let c=hr(n),g=(Se=(_=n.launcher)==null?void 0:_.sidebarMode)!=null?Se:!1,y=c||g||((te=(ge=n.launcher)==null?void 0:ge.fullHeight)!=null?te:!1),C=(be=e.ownerDocument.defaultView)!=null?be:window,D=(qe=(ke=n.launcher)==null?void 0:ke.mobileFullscreen)!=null?qe:!0,$=(Qe=(it=n.launcher)==null?void 0:it.mobileBreakpoint)!=null?Qe: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=(ut=(pt=n==null?void 0:n.launcher)==null?void 0:pt.width)!=null?ut:n==null?void 0:n.launcherWidth,Dt=Lr!=null?Lr:mn;G.style.width=Dt,G.style.maxWidth=Dt}if(Fn(),!y){let Lr=C.innerHeight,Dt=64,Ur=(Ie=(Re=n.launcher)==null?void 0:Re.heightOffset)!=null?Ie:0,Pr=Math.max(200,Lr-Dt),ot=Math.min(640,Pr),ft=Math.max(200,ot-Ur);G.style.height=`${ft}px`}}finally{if(Rr(),bo(),R&&T){let Dt=((Ge=e.ownerDocument.defaultView)!=null?Ge:window).innerWidth<=((Le=(W=n.launcher)==null?void 0:W.mobileBreakpoint)!=null?Le:640),Ur=(Ye=(De=n.launcher)==null?void 0:De.sidebarMode)!=null?Ye:!1,Pr=(Bt=(ve=n.launcher)==null?void 0:ve.mobileFullscreen)!=null?Bt:!0,ot=hr(n)&&Pr&&Dt,ft=Ur||Pr&&Dt&&T||ot;if(ft&&!ir){let qr=e.getRootNode(),Br=qr instanceof ShadowRoot?qr.host:e.closest(".persona-host");Br&&!sr&&(sr=ip(Br,(cr=(dt=n.launcher)==null?void 0:dt.zIndex)!=null?cr:Or)),ir=lp(e.ownerDocument)}else ft||(sr==null||sr(),sr=null,ir==null||ir(),ir=null)}}};He();let ae=(Du=e.ownerDocument.defaultView)!=null?Du:window;if(ae.addEventListener("resize",He),Ct.push(()=>ae.removeEventListener("resize",He)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Rr()});c.observe(Ue),Ct.push(()=>c.disconnect())}Rn=he.scrollTop;let st=he.scrollHeight,nt=()=>{let c=he.scrollTop,g=he.scrollHeight,y=g<st;st=g;let{action:C,nextLastScrollTop:D}=Ki({following:In.isFollowing(),currentScrollTop:c,lastScrollTop:Rn,nearBottom:ws(he,Fa),userScrollThreshold:Ns,isAutoScrolling:Gn||Ro||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Rn=D,C==="resume"){mo();return}C==="pause"&&$a()};he.addEventListener("scroll",nt,{passive:!0}),Ct.push(()=>he.removeEventListener("scroll",nt));let Nt=c=>{let g=Yi({following:In.isFollowing(),deltaY:c.deltaY,nearBottom:ws(he,Fa),resumeWhenNearBottom:!0});g==="pause"?$a():g==="resume"&&mo()};he.addEventListener("wheel",Nt,{passive:!0}),Ct.push(()=>he.removeEventListener("wheel",Nt)),at.addEventListener("click",()=>{he.scrollTop=he.scrollHeight,Rn=he.scrollTop,mo(),go(!0)}),Ct.push(()=>at.remove()),Ct.push(()=>{_a()});let kt=()=>{F&&(sn&&(F.removeEventListener("click",sn),sn=null),H()?(F.style.display="",sn=()=>{Ft(!1,"user")},F.addEventListener("click",sn)):F.style.display="none")};kt(),(()=>{let{clearChatButton:c}=ue;c&&c.addEventListener("click",()=>{q.clearMessages(),ln.clear(),mo(),Lo(ue.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(),de==null||de.update()})})(),Wt&&Wt.addEventListener("submit",Ga),ce==null||ce.addEventListener("keydown",Xa),ce==null||ce.addEventListener("paste",Ja);let Gt="persona-attachment-drop-active",lr=0,Pt=()=>{lr=0,re.classList.remove(Gt)},Et=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&At!==null},yr=c=>{!Sl(c.dataTransfer)||!Et()||(lr++,lr===1&&re.classList.add(Gt))},Hr=c=>{!Sl(c.dataTransfer)||!Et()||(lr--,lr<=0&&Pt())},Mr=c=>{!Sl(c.dataTransfer)||!Et()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},dr=c=>{var y;if(!Sl(c.dataTransfer)||!Et())return;c.preventDefault(),c.stopPropagation(),Pt();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&At.handleFiles(g)},vr=!0;re.addEventListener("dragenter",yr,vr),re.addEventListener("dragleave",Hr,vr),e.addEventListener("dragover",Mr,vr),e.addEventListener("drop",dr,vr);let ei=e.ownerDocument,Xp=c=>{Et()&&c.preventDefault()},Jp=c=>{Et()&&c.preventDefault()};ei.addEventListener("dragover",Xp),ei.addEventListener("drop",Jp),Ct.push(()=>{Wt&&Wt.removeEventListener("submit",Ga),ce==null||ce.removeEventListener("keydown",Xa),ce==null||ce.removeEventListener("paste",Ja)}),Ct.push(()=>{re.removeEventListener("dragenter",yr,vr),re.removeEventListener("dragleave",Hr,vr),e.removeEventListener("dragover",Mr,vr),e.removeEventListener("drop",dr,vr),ei.removeEventListener("dragover",Xp),ei.removeEventListener("drop",Jp),Pt()}),Ct.push(()=>{q.cancel()}),I?Ct.push(()=>{I==null||I.destroy()}):j&&Ct.push(()=>{j==null||j.remove()});let mr={update(c){var gr,$n,eo,ti,ri,ni,$o,oi,Ya,qu,zu,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;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,Se=(ti=n.features)==null?void 0:ti.toolCallDisplay,ge=(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 te=Bs.getForInstance(n.plugins);a.length=0,a.push(...te),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,_e=(zu=(qu=n.features)==null?void 0:qu.showReasoning)!=null?zu:!0,je=(ju=(Vu=n.features)==null?void 0:Vu.showToolCalls)!=null?ju:!0,me=(Xu=(Gu=n.features)==null?void 0:Gu.scrollToBottom)!=null?Xu:{},Tn(),Jn();let be=ye;if(ye=(Ku=(Ju=n.features)==null?void 0:Ju.showEventStreamToggle)!=null?Ku:!1,ye&&!be){if(J||(Q=new Hs(Ve),J=new Rs(Ae,Q),Q.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),q.setSSEEventCallback((ee,It)=>{var Xt;(Xt=n.onSSEEvent)==null||Xt.call(n,ee,It),J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(It)})})),!gt&&Ne){let ee=(Qu=(Yu=n.features)==null?void 0:Yu.eventStream)==null?void 0:Qu.classNames,It="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:"");gt=x("button",It),gt.style.width="28px",gt.style.height="28px",gt.style.color=Kr.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let Xt=Ce("activity","18px","currentColor",1.5);Xt&>.appendChild(Xt);let mt=ue.clearChatButtonWrapper,Ht=ue.closeButtonWrapper,br=mt||Ht;br&&br.parentNode===Ne?Ne.insertBefore(gt,br):Ne.appendChild(gt),gt.addEventListener("click",()=>{pe?Yr():Sr()})}}else!ye&&be&&(Yr(),gt&&(gt.remove(),gt=null),J==null||J.clear(),Q==null||Q.destroy(),J=null,Q=null);if(((Zu=n.launcher)==null?void 0:Zu.enabled)===!1&&I&&(I.destroy(),I=null),((ef=n.launcher)==null?void 0:ef.enabled)===!1&&j&&(j.remove(),j=null),((tf=n.launcher)==null?void 0:tf.enabled)!==!1&&!I&&!j){let ee=a.find(It=>It.renderLauncher);if(ee!=null&&ee.renderLauncher){let It=ee.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});It&&(j=It,e.appendChild(j))}j||(I=Ms(n,z),e.appendChild(I.element))}I&&I.update(n),We&&((rf=n.launcher)==null?void 0:rf.title)!==void 0&&(We.textContent=n.launcher.title),Xe&&((nf=n.launcher)==null?void 0:nf.subtitle)!==void 0&&(Xe.textContent=n.launcher.subtitle);let ke=(of=n.layout)==null?void 0:of.header;if((ke==null?void 0:ke.layout)!==S&&Ne){let ee=ke?Ta(n,ke,{showClose:H(),onClose:()=>Ft(!1,"user")}):ao({config:n,showClose:H(),onClose:()=>Ft(!1,"user")});Ne.replaceWith(ee.header),Ne=ee.header,ie=ee.iconHolder,We=ee.headerTitle,Xe=ee.headerSubtitle,F=ee.closeButton,S=ke==null?void 0:ke.layout}else if(ke&&(ie&&(ie.style.display=ke.showIcon===!1?"none":""),We&&(We.style.display=ke.showTitle===!1?"none":""),Xe&&(Xe.style.display=ke.showSubtitle===!1?"none":""),F&&(F.style.display=ke.showCloseButton===!1?"none":""),ue.clearChatButtonWrapper)){let ee=ke.showClearChat;if(ee!==void 0){ue.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:It}=ue;It&&!It.classList.contains("persona-absolute")&&(ee?It.classList.remove("persona-ml-auto"):It.classList.add("persona-ml-auto"))}}let it=((af=n.layout)==null?void 0:af.showHeader)!==!1;Ne&&(Ne.style.display=it?"":"none");let Qe=((sf=n.layout)==null?void 0:sf.showFooter)!==!1;Ue&&(Ue.style.display=Qe?"":"none"),Rr(),Jn(),T!==h?T?Ft(A,"auto"):(R=!0,bo()):A!==b&&Ft(A,"auto"),b=A,h=T,He(),kt();let Re=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ie=JSON.stringify(n.messageActions)!==JSON.stringify(y),Ge=JSON.stringify((lf=n.layout)==null?void 0:lf.messages)!==JSON.stringify(C),W=((df=n.loadingIndicator)==null?void 0:df.render)!==($==null?void 0:$.render)||((cf=n.loadingIndicator)==null?void 0:cf.renderIdle)!==($==null?void 0:$.renderIdle)||((pf=n.loadingIndicator)==null?void 0:pf.showBubble)!==($==null?void 0:$.showBubble),Le=n.iterationDisplay!==U,De=((ff=(uf=n.features)==null?void 0:uf.showReasoning)!=null?ff:!0)!==(X!=null?X:!0)||((gf=(mf=n.features)==null?void 0:mf.showToolCalls)!=null?gf:!0)!==(_!=null?_:!0)||JSON.stringify((hf=n.features)==null?void 0:hf.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((xf=n.features)==null?void 0:xf.reasoningDisplay)!==JSON.stringify(ge);(Re||Ie||Ge||W||Le||De)&&q&&(Oa++,Bo(Je,q.getMessages(),fe));let ve=(yf=n.launcher)!=null?yf:{},Bt=(bf=ve.headerIconHidden)!=null?bf:!1,dt=(wf=(Cf=n.layout)==null?void 0:Cf.header)==null?void 0:wf.showIcon,cr=Bt||dt===!1,Lr=ve.headerIconName,Dt=(vf=ve.headerIconSize)!=null?vf:"48px";if(ie){let ee=re.querySelector(".persona-border-b-persona-divider"),It=ee==null?void 0:ee.querySelector(".persona-flex-col");if(cr)ie.style.display="none",ee&&It&&!ee.contains(It)&&ee.insertBefore(It,ee.firstChild);else{if(ie.style.display="",ie.style.height=Dt,ie.style.width=Dt,ee&&It&&(ee.contains(ie)?ie.nextSibling!==It&&(ie.remove(),ee.insertBefore(ie,It)):ee.insertBefore(ie,It)),Lr){let mt=parseFloat(Dt)||24,Ht=Ce(Lr,mt*.6,"#ffffff",2);Ht?ie.replaceChildren(Ht):ie.textContent=(Af=ve.agentIconText)!=null?Af:"\u{1F4AC}"}else if(ve.iconUrl){let mt=ie.querySelector("img");if(mt)mt.src=ve.iconUrl,mt.style.height=Dt,mt.style.width=Dt;else{let Ht=document.createElement("img");Ht.src=ve.iconUrl,Ht.alt="",Ht.className="persona-rounded-xl persona-object-cover",Ht.style.height=Dt,Ht.style.width=Dt,ie.replaceChildren(Ht)}}else{let mt=ie.querySelector("svg"),Ht=ie.querySelector("img");(mt||Ht)&&ie.replaceChildren(),ie.textContent=(Sf=ve.agentIconText)!=null?Sf:"\u{1F4AC}"}let Xt=ie.querySelector("img");Xt&&(Xt.style.height=Dt,Xt.style.width=Dt)}}let Ur=(kf=(Tf=n.layout)==null?void 0:Tf.header)==null?void 0:kf.showTitle,Pr=(Mf=(Ef=n.layout)==null?void 0:Ef.header)==null?void 0:Mf.showSubtitle;if(We&&(We.style.display=Ur===!1?"none":""),Xe&&(Xe.style.display=Pr===!1?"none":""),F){((Pf=(Lf=n.layout)==null?void 0:Lf.header)==null?void 0:Pf.showCloseButton)===!1?F.style.display="none":F.style.display="";let It=(If=ve.closeButtonSize)!=null?If:"32px",Xt=(Rf=ve.closeButtonPlacement)!=null?Rf:"inline";F.style.height=It,F.style.width=It;let{closeButtonWrapper:mt}=ue,Ht=Xt==="top-right",br=mt==null?void 0:mt.classList.contains("persona-absolute");if(mt&&Ht!==br)if(mt.remove(),Ht)mt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",re.style.position="relative",re.appendChild(mt);else{let ht=(Bf=(Hf=ve.clearChat)==null?void 0:Hf.placement)!=null?Bf:"inline",Cr=(Df=(Wf=ve.clearChat)==null?void 0:Wf.enabled)!=null?Df:!0;mt.className=Cr&&ht==="inline"?"":"persona-ml-auto";let rn=re.querySelector(".persona-border-b-persona-divider");rn&&rn.appendChild(mt)}if(F.style.color=ve.closeButtonColor||Kr.actionIconColor,ve.closeButtonBackgroundColor?(F.style.backgroundColor=ve.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ht=ve.closeButtonBorderWidth||"0px",Cr=ve.closeButtonBorderColor||"transparent";F.style.border=`${ht} solid ${Cr}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");ve.closeButtonBorderRadius?(F.style.borderRadius=ve.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(F.style.paddingLeft=ve.closeButtonPaddingX,F.style.paddingRight=ve.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),ve.closeButtonPaddingY?(F.style.paddingTop=ve.closeButtonPaddingY,F.style.paddingBottom=ve.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Wr=(Of=ve.closeButtonIconName)!=null?Of:"x",Dn=(Ff=ve.closeButtonIconText)!=null?Ff:"\xD7";F.innerHTML="";let Vr=Ce(Wr,"28px","currentColor",1);Vr?F.appendChild(Vr):F.textContent=Dn;let pr=(Nf=ve.closeButtonTooltipText)!=null?Nf:"Close chat",pn=(_f=ve.closeButtonShowTooltip)!=null?_f:!0;if(F.setAttribute("aria-label",pr),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),pn&&pr)){let ht=null,Cr=()=>{if(ht||!F)return;let Uo=F.ownerDocument,Qa=Uo.body;if(!Qa)return;ht=qn(Uo,"div","persona-clear-chat-tooltip"),ht.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Za);let qo=F.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(Ao),ht.style.left=`${qo.left+qo.width/2}px`,ht.style.top=`${qo.top-8}px`,ht.style.transform="translate(-50%, -100%)",Qa.appendChild(ht)},rn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};mt.addEventListener("mouseenter",Cr),mt.addEventListener("mouseleave",rn),F.addEventListener("focus",Cr),F.addEventListener("blur",rn),mt._cleanupTooltip=()=>{rn(),mt&&(mt.removeEventListener("mouseenter",Cr),mt.removeEventListener("mouseleave",rn)),F&&(F.removeEventListener("focus",Cr),F.removeEventListener("blur",rn))}}}let{clearChatButton:ot,clearChatButtonWrapper:ft}=ue;if(ot){let ee=($f=ve.clearChat)!=null?$f:{},It=(Uf=ee.enabled)!=null?Uf:!0,Xt=(zf=(qf=n.layout)==null?void 0:qf.header)==null?void 0:zf.showClearChat,mt=Xt!==void 0?Xt:It,Ht=(Vf=ee.placement)!=null?Vf:"inline";if(ft){ft.style.display=mt?"":"none";let{closeButtonWrapper:br}=ue;!O()&&br&&!br.classList.contains("persona-absolute")&&(mt?br.classList.remove("persona-ml-auto"):br.classList.add("persona-ml-auto"));let Wr=Ht==="top-right",Dn=ft.classList.contains("persona-absolute");if(!O()&&Wr!==Dn&&mt){if(ft.remove(),Wr)ft.className="persona-absolute persona-top-4 persona-z-50",ft.style.right="48px",re.style.position="relative",re.appendChild(ft);else{ft.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ft.style.right="";let pr=re.querySelector(".persona-border-b-persona-divider"),pn=ue.closeButtonWrapper;pr&&pn&&pn.parentElement===pr?pr.insertBefore(ft,pn):pr&&pr.appendChild(ft)}let Vr=ue.closeButtonWrapper;Vr&&!Vr.classList.contains("persona-absolute")&&(Wr?Vr.classList.add("persona-ml-auto"):Vr.classList.remove("persona-ml-auto"))}}if(mt){if(!O()){let ht=(jf=ee.size)!=null?jf:"32px";ot.style.height=ht,ot.style.width=ht}let br=(Gf=ee.iconName)!=null?Gf:"refresh-cw",Wr=(Xf=ee.iconColor)!=null?Xf:"";ot.style.color=Wr||Kr.actionIconColor,ot.innerHTML="";let Dn=O()?"14px":"20px",Vr=Ce(br,Dn,"currentColor",2);if(Vr&&ot.appendChild(Vr),ee.backgroundColor?(ot.style.backgroundColor=ee.backgroundColor,ot.classList.remove("hover:persona-bg-gray-100")):(ot.style.backgroundColor="",ot.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let ht=ee.borderWidth||"0px",Cr=ee.borderColor||"transparent";ot.style.border=`${ht} solid ${Cr}`,ot.classList.remove("persona-border-none")}else ot.style.border="",ot.classList.add("persona-border-none");ee.borderRadius?(ot.style.borderRadius=ee.borderRadius,ot.classList.remove("persona-rounded-full")):(ot.style.borderRadius="",ot.classList.add("persona-rounded-full")),ee.paddingX?(ot.style.paddingLeft=ee.paddingX,ot.style.paddingRight=ee.paddingX):(ot.style.paddingLeft="",ot.style.paddingRight=""),ee.paddingY?(ot.style.paddingTop=ee.paddingY,ot.style.paddingBottom=ee.paddingY):(ot.style.paddingTop="",ot.style.paddingBottom="");let pr=(Jf=ee.tooltipText)!=null?Jf:"Clear chat",pn=(Kf=ee.showTooltip)!=null?Kf:!0;if(ot.setAttribute("aria-label",pr),ft&&(ft._cleanupTooltip&&(ft._cleanupTooltip(),delete ft._cleanupTooltip),pn&&pr)){let ht=null,Cr=()=>{if(ht||!ot)return;let Uo=ot.ownerDocument,Qa=Uo.body;if(!Qa)return;ht=qn(Uo,"div","persona-clear-chat-tooltip"),ht.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Za);let qo=ot.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(Ao),ht.style.left=`${qo.left+qo.width/2}px`,ht.style.top=`${qo.top-8}px`,ht.style.transform="translate(-50%, -100%)",Qa.appendChild(ht)},rn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ft.addEventListener("mouseenter",Cr),ft.addEventListener("mouseleave",rn),ot.addEventListener("focus",Cr),ot.addEventListener("blur",rn),ft._cleanupTooltip=()=>{rn(),ft&&(ft.removeEventListener("mouseenter",Cr),ft.removeEventListener("mouseleave",rn)),ot&&(ot.removeEventListener("focus",Cr),ot.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:o.emit,documentRef:typeof document!="undefined"?document:null}),fe=Nh(n,k,ne),q.updateConfig(n),Bo(Je,q.getMessages(),fe),Ln.render(n.suggestionChips,q,ce,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming());let Oo=((Yf=n.voiceRecognition)==null?void 0:Yf.enabled)===!0,Fo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),No=((Zf=(Qf=n.voiceRecognition)==null?void 0:Qf.provider)==null?void 0:Zf.type)==="runtype";if(Oo&&(Fo||No))if(!N||!le){let ee=Ys(n.voiceRecognition,n.sendButton);ee&&(N=ee.micButton,le=ee.micButtonWrapper,Mt.insertBefore(le,fr),N.addEventListener("click",Qn),N.disabled=q.isStreaming())}else{let ee=(em=n.voiceRecognition)!=null?em:{},It=(tm=n.sendButton)!=null?tm:{},Xt=(rm=ee.iconName)!=null?rm:"mic",mt=(nm=It.size)!=null?nm:"40px",Ht=(om=ee.iconSize)!=null?om:mt,br=parseFloat(Ht)||24;N.style.width=Ht,N.style.height=Ht,N.style.minWidth=Ht,N.style.minHeight=Ht;let Wr=(sm=(am=ee.iconColor)!=null?am:It.textColor)!=null?sm:"currentColor";N.innerHTML="";let Dn=Ce(Xt,br,Wr,2);Dn?N.appendChild(Dn):N.textContent="\u{1F3A4}";let Vr=(im=ee.backgroundColor)!=null?im:It.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=le==null?void 0:le.querySelector(".persona-send-button-tooltip"),pn=(lm=ee.tooltipText)!=null?lm:"Start voice recognition";if(((dm=ee.showTooltip)!=null?dm:!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,le==null||le.insertBefore(Cr,N)}else pr&&(pr.style.display="none");le.style.display="",N.disabled=q.isStreaming()}else N&&le&&(le.style.display="none",((pm=(cm=n.voiceRecognition)==null?void 0:cm.provider)==null?void 0:pm.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():dn&&Bn());if(((um=n.attachments)==null?void 0:um.enabled)===!0)if(!ct||!Te){let ee=(fm=n.attachments)!=null?fm:{},Xt=(gm=((mm=n.sendButton)!=null?mm:{}).size)!=null?gm:"40px";Ut||(Ut=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",Wt.insertBefore(Ut,ce)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((hm=ee.allowedTypes)!=null?hm:oo).join(","),Ke.multiple=((xm=ee.maxFiles)!=null?xm:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Wt.insertBefore(Ke,ce)),ct=x("div","persona-send-button-wrapper"),Te=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Te.type="button",Te.setAttribute("aria-label",(ym=ee.buttonTooltipText)!=null?ym:"Attach file");let mt=(bm=ee.buttonIconName)!=null?bm:"paperclip",Ht=Xt,br=parseFloat(Ht)||40,Wr=Math.round(br*.6);Te.style.width=Ht,Te.style.height=Ht,Te.style.minWidth=Ht,Te.style.minHeight=Ht,Te.style.fontSize="18px",Te.style.lineHeight="1",Te.style.backgroundColor="transparent",Te.style.color="var(--persona-primary, #111827)",Te.style.border="none",Te.style.borderRadius="6px",Te.style.transition="background-color 0.15s ease",Te.addEventListener("mouseenter",()=>{Te.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Te.addEventListener("mouseleave",()=>{Te.style.backgroundColor="transparent"});let Dn=Ce(mt,Wr,"currentColor",1.5);Dn?Te.appendChild(Dn):Te.textContent="\u{1F4CE}",Te.addEventListener("click",pn=>{pn.preventDefault(),Ke==null||Ke.click()}),ct.appendChild(Te);let Vr=(Cm=ee.buttonTooltipText)!=null?Cm:"Attach file",pr=x("div","persona-send-button-tooltip");pr.textContent=Vr,ct.appendChild(pr),yt.append(ct),!At&&Ke&&Ut&&(At=ta.fromConfig(ee),At.setPreviewsContainer(Ut),Ke.addEventListener("change",async()=>{At&&(Ke!=null&&Ke.files)&&(await At.handleFileSelect(Ke.files),Ke.value="")})),re.querySelector(".persona-attachment-drop-overlay")||re.appendChild(_h(ee.dropOverlay))}else{ct.style.display="";let ee=(wm=n.attachments)!=null?wm:{};Ke&&(Ke.accept=((vm=ee.allowedTypes)!=null?vm:oo).join(","),Ke.multiple=((Am=ee.maxFiles)!=null?Am:4)>1),At&&At.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ct&&(ct.style.display="none"),At&&At.clearAttachments(),(Sm=re.querySelector(".persona-attachment-drop-overlay"))==null||Sm.remove();let rr=(Tm=n.sendButton)!=null?Tm:{},_o=(km=rr.useIcon)!=null?km:!1,wo=(Em=rr.iconText)!=null?Em:"\u2191",Tt=rr.iconName,Zr=(Mm=rr.tooltipText)!=null?Mm:"Send message",Zn=(Lm=rr.showTooltip)!=null?Lm:!1,zr=(Pm=rr.size)!=null?Pm:"40px",en=rr.backgroundColor,zt=rr.textColor;if(_o){if($e.style.width=zr,$e.style.height=zr,$e.style.minWidth=zr,$e.style.minHeight=zr,$e.style.fontSize="18px",$e.style.lineHeight="1",$e.innerHTML="",zt?$e.style.color=zt:$e.style.color="var(--persona-button-primary-fg, #ffffff)",Tt){let ee=parseFloat(zr)||24,It=(zt==null?void 0:zt.trim())||"currentColor",Xt=Ce(Tt,ee,It,2);Xt?$e.appendChild(Xt):$e.textContent=wo}else $e.textContent=wo;$e.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",en?($e.style.backgroundColor=en,$e.classList.remove("persona-bg-persona-primary")):($e.style.backgroundColor="",$e.classList.add("persona-bg-persona-primary"))}else $e.textContent=(Rm=(Im=n.copy)==null?void 0:Im.sendButtonLabel)!=null?Rm:"Send",$e.style.width="",$e.style.height="",$e.style.minWidth="",$e.style.minHeight="",$e.style.fontSize="",$e.style.lineHeight="",$e.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?($e.style.backgroundColor=en,$e.classList.remove("persona-bg-persona-accent")):$e.classList.add("persona-bg-persona-accent"),zt?$e.style.color=zt:$e.classList.add("persona-text-white");rr.borderWidth?($e.style.borderWidth=rr.borderWidth,$e.style.borderStyle="solid"):($e.style.borderWidth="",$e.style.borderStyle=""),rr.borderColor?$e.style.borderColor=rr.borderColor:$e.style.borderColor="",rr.paddingX?($e.style.paddingLeft=rr.paddingX,$e.style.paddingRight=rr.paddingX):($e.style.paddingLeft="",$e.style.paddingRight=""),rr.paddingY?($e.style.paddingTop=rr.paddingY,$e.style.paddingBottom=rr.paddingY):($e.style.paddingTop="",$e.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,$e)}else Zt&&(Zt.style.display="none");let Vt=(Om=(Hm=n.layout)==null?void 0:Hm.contentMaxWidth)!=null?Om:O()?(Dm=(Wm=(Bm=n.launcher)==null?void 0:Bm.composerBar)==null?void 0:Wm.contentMaxWidth)!=null?Dm:"720px":void 0;Vt?(Je.style.maxWidth=Vt,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%",Wt&&(Wt.style.maxWidth=Vt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Ot&&(Ot.style.maxWidth=Vt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto")):(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight="",Je.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""));let nr=(Fm=n.statusIndicator)!=null?Fm:{},tn=(Nm=nr.visible)!=null?Nm:!0;if(Yt.style.display=tn?"":"none",q){let ee=q.getStatus();Fe(Yt,(Xt=>{var mt,Ht,br,Wr;return Xt==="idle"?(mt=nr.idleText)!=null?mt:Dr.idle:Xt==="connecting"?(Ht=nr.connectingText)!=null?Ht: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()&&Ft(!0,"api")},close(){H()&&Ft(!1,"api")},toggle(){H()&&Ft(!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(),de==null||de.update()},setMessage(c){return!ce||q.isStreaming()?!1:(!R&&H()&&Ft(!0,"system"),ce.value=c,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ce.value.trim();return g?(!R&&H()&&Ft(!0,"system"),ce.value="",ce.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()&&Ft(!0,"system"),xt.manuallyDeactivated=!1,Qr(),q.toggleVoice().then(()=>{xt.active=q.isVoiceActive(),bn("user"),q.isVoiceActive()&&Co()})),!0):dn?!0:Ka()?(!R&&H()&&Ft(!0,"system"),xt.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(()=>{xt.active=!1,xt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()}),!0):!1:dn?(xt.manuallyDeactivated=!0,Qr(),Bn("user"),!0):!1},injectMessage(c){return!R&&H()&&Ft(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!R&&H()&&Ft(!0,"system");let g=q.injectAssistantMessage(c);return B&&(B=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!R&&H()&&Ft(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!R&&H()&&Ft(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!R&&H()&&Ft(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!R&&H()&&Ft(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!R&&H()&&Ft(!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(){!ye||!J||Sr()},hideEventStream(){pe&&Yr()},isEventStreamVisible(){return pe},showArtifacts(){Sn(n)&&(Z=!1,on(),bt==null||bt.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()||!ce?!1:(ce.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 o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return H()&&R},isVoiceActive(){return xt.active},getState(){return{open:H()&&R,launcherEnabled:T,voiceActive:xt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!R&&H()&&Ft(!0,"system");let g=Je.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});Je.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&H()&&Ft(!0,"system");let g=Je.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});Je.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),Ct.forEach(c=>c()),Y.remove(),we==null||we.remove(),I==null||I.destroy(),j==null||j.remove(),sn&&F.removeEventListener("click",sn)}};if((((Ou=t==null?void 0:t.debugTools)!=null?Ou:!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,Ct.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),Ct.push(()=>{window.removeEventListener("persona:focusInput",g)}),ye){let X=Se=>{let ge=Se.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&mr.showEventStream()},_=Se=>{let ge=Se.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&mr.hideEventStream()};window.addEventListener("persona:showEventStream",X),window.addEventListener("persona:hideEventStream",_),Ct.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),Ct.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=_0(n.persistState);if(Cn&&H()){let c=$0(Cn.storage),g=`${Cn.keyPrefix}widget-open`,y=`${Cn.keyPrefix}widget-voice`,C=`${Cn.keyPrefix}widget-voice-mode`;if(c){let D=((Fu=Cn.persist)==null?void 0:Fu.openState)&&c.getItem(g)==="true",$=((Nu=Cn.persist)==null?void 0:Nu.voiceState)&&c.getItem(y)==="true",U=((_u=Cn.persist)==null?void 0:_u.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),($u=Cn.persist)!=null&&$u.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(Uu=Cn.persist)!=null&&Uu.voiceState&&(o.on("voice:state",X=>{c.setItem(y,X.active?"true":"false")}),o.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",_),Ct.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&H()&&setTimeout(()=>{mr.open()},0),Kn(),mr};var U0=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let a=/^(\d+(?:\.\d+)?)%$/i.exec(t);return a?Math.max(0,r*parseFloat(a[1])/100):420},$h=(e,r)=>{var n,a;let t=(a=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?a:!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"},Hp=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=""},Uh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Hp(e)},Pp=e=>{e.style.transition=""},Ip=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=""},Rp=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=""},q0=(e,r,t,n,a)=>{a?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},z0=(e,r,t,n,a,o)=>{let s=o?r:e;a==="left"?s.firstElementChild!==n&&s.replaceChildren(n,t):s.lastElementChild!==n&&s.replaceChildren(t,n)},qh=(e,r,t,n,a,o,s)=>{var w,v,k,T,A,E;let i=vn(o),d=i.reveal==="push";q0(e,r,t,n,d),z0(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",a.className="persona-host",a.style.height="100%",a.style.minHeight="0",a.style.display="flex",a.style.flexDirection="column",a.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(v=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileFullscreen)!=null?v:!0,p=(T=(k=o==null?void 0:o.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"),Ip(r),Pp(n),Uh(n),Rp(t),kl(a,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=o==null?void 0:o.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"),Uh(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ip(r),Pp(n),Rp(t),kl(a,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",Pp(n),Hp(n),kl(a,n);let b=U0(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="",Ip(r),Hp(n),Rp(t),kl(a,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",a.style.width=i.width,a.style.minWidth=i.width,a.style.maxWidth=i.width,a.style.boxSizing="border-box")}},V0=(e,r)=>{let t=e.ownerDocument.createElement("div");return $h(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){$h(t,n)},destroy(){t.remove()}}},j0=(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 a=e.tagName.toUpperCase();if(a==="BODY"||a==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=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(()=>{qh(s,i,d,l,u,r,p)}),m.observe(s))},v=()=>{qh(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&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),s.remove()}}},Os=(e,r)=>hr(r)?j0(e,r):V0(e,r);var Bp={},G0=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},X0=()=>{try{if(typeof Bp!="undefined"&&Bp.url)return new URL("../widget.css",Bp.url).href}catch{}return null},zh=(e,r)=>{let t=X0(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let a=r.head.querySelector("link[data-persona]");if(!a)return;let o=a.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let a=r.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),e.insertBefore(a,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},Vh=e=>{var k;let r=G0(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,a=e.config,o=Os(r,a),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),zh(O,n)}else T.appendChild(h),zh(T,n);return r.id&&h.setAttribute("data-persona-instance",r.id),h},l=()=>{o.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},p=()=>{let T=d(o.host,a);s=Tl(T,a,{debugTools:e.debugTools}),u()},m=()=>{i.forEach(T=>T()),i=[],s.destroy()};p(),(k=e.onReady)==null||k.call(e);let f=T=>{m(),o.destroy(),o=Os(r,T),a=T,p()},w={update(T){var L,O,H,R,B,V;let A={...a,...T,launcher:{...(L=a==null?void 0:a.launcher)!=null?L:{},...(O=T==null?void 0:T.launcher)!=null?O:{},dock:{...(R=(H=a==null?void 0:a.launcher)==null?void 0:H.dock)!=null?R:{},...(V=(B=T==null?void 0:T.launcher)==null?void 0:B.dock)!=null?V:{}}}},E=hr(a),b=hr(A),h=To(a),S=To(A);if(E!==b||h!==S){f(A);return}a=A,o.updateConfig(a),s.update(T),l()},destroy(){m(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(w,{get(T,A,E){if(A==="host")return o.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 Kh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),J0=new Set(["button","a","input","select","textarea","details","summary"]),K0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Wp=/\b(product|card|item|listing|result)\b/i,Op=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Y0=3e3,Q0=100;function Yh(e){let r=typeof e.className=="string"?e.className:"";if(Wp.test(r)||e.id&&Wp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Wp.test(n.value))return!0}return!1}function Qh(e){var r;return Op.test(((r=e.textContent)!=null?r:"").trim())}function Zh(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let a=(t=r[n].getAttribute("href"))!=null?t:"";if(a&&a!=="#"&&!a.toLowerCase().startsWith("javascript:"))return!0}return!1}function Z0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function jh(e){let r=e.match(Op);return r?r[0]:null}function Gh(e){var n,a,o;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&&((a=r.textContent)!=null&&a.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(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function eC(e){let r=[],t=n=>{let a=n.trim();a&&!r.includes(a)&&r.push(a)};return e.querySelectorAll("button").forEach(n=>{var a;return t((a=n.textContent)!=null?a:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var a;return t((a=n.textContent)!=null?a:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var a;t((a=n.value)!=null?a:"")}),r.slice(0,6)}var tC="commerce-card",rC="result-card";function Xh(e){return!Yh(e)||!Qh(e)||!Zh(e)&&!Z0(e)?0:5200}function Jh(e){var n;return!Yh(e)||Qh(e)||!Zh(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 Fp=[{id:tC,scoreElement(e){return Xh(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||Op.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,l,u;if(Xh(e)===0)return null;let{title:t,href:n}=Gh(e),a=(u=(l=jh(((d=e.textContent)!=null?d:"").trim()))!=null?l:jh(r.text))!=null?u:"",o=eC(e);return[n&&t?`[${t}](${n})${a?` \u2014 ${a}`:""}`:t?`${t}${a?` \u2014 ${a}`:""}`:a||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
148
|
+
`)}},{id:rC,scoreElement(e){return Jh(e)},formatSummary(e,r){if(Jh(e)===0)return null;let{title:t,href:n}=Gh(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
|
|
149
|
+
`)}}];function nC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function oC(e){var u,p,m,f,w,v,k,T,A,E,b,h,S;let r=(u=e.options)!=null?u:{},t=(m=(p=r.maxElements)!=null?p:e.maxElements)!=null?m:80,n=(w=(f=r.excludeSelector)!=null?f:e.excludeSelector)!=null?w:".persona-host",a=(k=(v=r.maxTextLength)!=null?v:e.maxTextLength)!=null?k:200,o=(A=(T=r.visibleOnly)!=null?T:e.visibleOnly)!=null?A:!0,s=(E=r.root)!=null?E:e.root,i=(b=r.mode)!=null?b:"structured",d=(h=r.maxCandidates)!=null?h:Math.max(500,t*10),l=(S=e.rules)!=null?S:Fp;return i==="simple"&&e.rules&&e.rules.length>0?(nC(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:a,visibleOnly:o,root:s,rules:l}}function Dp(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var aC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function sC(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"||J0.has(r)||t&&K0.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function ex(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 iC(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let a=e.getAttribute("aria-label");a&&(r["aria-label"]=a);let o=e.getAttribute("type");o&&(r.type=o);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 Np(e){let r=e.tagName.toLowerCase();if(e.id){let a=`#${Dp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}for(let a of aC){let o=e.getAttribute(a);if(o){let s=`${r}[${a}="${Dp(o)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let t=Array.from(e.classList).filter(a=>a&&!a.startsWith("persona-")).slice(0,3);if(t.length>0){let a=`${r}.${t.map(s=>Dp(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let d=`${a}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function lC(e){return e==="static"?Q0:Y0}function tx(e,r){var a;let t=e.tagName.toLowerCase(),n=((a=e.textContent)!=null?a:"").trim().substring(0,r);return{selector:Np(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:sC(e),attributes:iC(e)}}function dC(e,r,t,n){let a=lC(r.interactivity),o=null;for(let s of t){let i=s.scoreElement(e,r,n);i>0&&(a+=i,s.formatSummary&&!o&&(o=s))}return{score:a,formattingRule:o}}function cC(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 pC(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,a=[],o=0,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&a.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Kh.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!ex(l)){i=s.nextNode();continue}let p=tx(l,e.maxTextLength),m=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(k=>k==="role");if(!m&&!f){i=s.nextNode();continue}if(n.has(p.selector)){i=s.nextNode();continue}n.add(p.selector);let{score:w,formattingRule:v}=dC(l,p,e.rules,t);a.push({el:l,domIndex:o,enriched:p,score:w,formattingRule:v}),o+=1}i=s.nextNode()}a.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,m=u.enriched.interactivity==="static"?1:0;return p!==m?p-m:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of a){if(d.length>=e.maxElements)break;cC(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,m=u.enriched.interactivity==="static"?1:0;return p!==m?p-m:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var m;let u;if((m=l.formattingRule)!=null&&m.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,t);f&&(u=f)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function uC(e,r){let t=[],n=new Set,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=a.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(Kh.has(l)){o=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=a.nextNode();continue}}catch{}if(e.visibleOnly&&!ex(d)){o=a.nextNode();continue}let u=tx(d,e.maxTextLength),p=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(f=>f==="role");if(!p&&!m){o=a.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}o=a.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 rx(e={}){var n;let r=oC(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?uC(r,t):pC(r,t):[]}var El=100;function nx(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"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(`
|
|
153
|
-
`)}`)}let a={clickable:[],navigable:[],input:[],static:[]};for(let s of e)t==="structured"&&s.formattedSummary||a[s.interactivity].push(s);if(a.clickable.length>0){let s=a.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,El)}" (clickable)`);
|
|
153
|
+
`)}`)}let a={clickable:[],navigable:[],input:[],static:[]};for(let s of e)t==="structured"&&s.formattedSummary||a[s.interactivity].push(s);if(a.clickable.length>0){let s=a.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,El)}" (clickable)`);n.push(`Interactive elements:
|
|
154
154
|
${s.join(`
|
|
155
|
-
`)}`)}if(a.navigable.length>0){let s=a.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,El)}" (navigable)`);
|
|
155
|
+
`)}`)}if(a.navigable.length>0){let s=a.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,El)}" (navigable)`);n.push(`Navigation links:
|
|
156
156
|
${s.join(`
|
|
157
|
-
`)}`)}if(a.input.length>0){let s=a.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,El)}" (input)`);
|
|
157
|
+
`)}`)}if(a.input.length>0){let s=a.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,El)}" (input)`);n.push(`Form inputs:
|
|
158
158
|
${s.join(`
|
|
159
|
-
`)}`)}if(a.static.length>0){let s=a.static.map(i=>`- ${i.selector}: "${i.text.substring(0,El)}"`);
|
|
159
|
+
`)}`)}if(a.static.length>0){let s=a.static.map(i=>`- ${i.selector}: "${i.text.substring(0,El)}"`);n.push(`Content:
|
|
160
160
|
${s.join(`
|
|
161
|
-
`)}`)}return
|
|
161
|
+
`)}`)}return n.join(`
|
|
162
162
|
|
|
163
|
-
`)}var ox={name:"@runtypelabs/persona",version:"3.
|
|
163
|
+
`)}var ox={name:"@runtypelabs/persona",version:"3.20.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./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=ox.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 mC(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 ax=`({ 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
|
|
@@ -173,7 +173,7 @@ ${s.join(`
|
|
|
173
173
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
174
174
|
} catch (e) { return null; }
|
|
175
175
|
return null;
|
|
176
|
-
}`,
|
|
176
|
+
}`,sx=`function(ctx) {
|
|
177
177
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
178
178
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
179
179
|
var cleanJson = jsonSource
|
|
@@ -186,7 +186,7 @@ ${s.join(`
|
|
|
186
186
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
187
187
|
} catch (e) { return null; }
|
|
188
188
|
return null;
|
|
189
|
-
}`,
|
|
189
|
+
}`,ix=`(action: any, context: any) => {
|
|
190
190
|
if (action.type !== 'nav_then_click') return;
|
|
191
191
|
const payload = action.payload || action.raw || {};
|
|
192
192
|
const url = payload?.page;
|
|
@@ -203,7 +203,7 @@ ${s.join(`
|
|
|
203
203
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
204
204
|
window.location.href = targetUrl;
|
|
205
205
|
return { handled: true, displayText: text };
|
|
206
|
-
}`,
|
|
206
|
+
}`,lx=`function(action, context) {
|
|
207
207
|
if (action.type !== 'nav_then_click') return;
|
|
208
208
|
var payload = action.payload || action.raw || {};
|
|
209
209
|
var url = payload.page;
|
|
@@ -220,26 +220,26 @@ ${s.join(`
|
|
|
220
220
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
221
221
|
window.location.href = targetUrl;
|
|
222
222
|
return { handled: true, displayText: text };
|
|
223
|
-
}`,
|
|
223
|
+
}`,gC=`(parsed: any) => {
|
|
224
224
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
225
225
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
226
226
|
if (parsed.action === 'message') return parsed.text || '';
|
|
227
227
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
228
228
|
return parsed.text || null;
|
|
229
|
-
}`,
|
|
229
|
+
}`,hC=`function(parsed) {
|
|
230
230
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
231
231
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
232
232
|
if (parsed.action === 'message') return parsed.text || '';
|
|
233
233
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
234
234
|
return parsed.text || null;
|
|
235
|
-
}`;function
|
|
236
|
-
`)}function
|
|
237
|
-
`)}function bC(e,r){let t=r==null?void 0:r.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&In(o,"theme",e.theme," "),e.launcher&&In(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,n])=>{o.push(` ${a}: "${n}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,n])=>{typeof n=="string"?o.push(` ${a}: "${n}",`):typeof n=="boolean"&&o.push(` ${a}: ${n},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,n])=>{typeof n=="string"?o.push(` ${a}: "${n}",`):typeof n=="boolean"?o.push(` ${a}: ${n},`):typeof n=="number"&&o.push(` ${a}: ${n},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,n])=>{typeof n=="string"?o.push(` ${a}: "${n}",`):typeof n=="boolean"&&o.push(` ${a}: ${n},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,n])=>{o.push(` ${a}: ${n},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ll(e," ")),o.push(...Pl(e," ",t)),o.push(...Il(e," ")),o.push(...Rl(e," ")),t!=null&&t.getHeaders&&o.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&o.push(` contextProviders: ${t.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?o.push(` streamParser: ${t.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${mC}),`)),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${nx}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${nx}`),o.push(" ],")),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${t.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${sx}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${sx}`),o.push(" ],")),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
|
|
238
|
-
`)}function
|
|
239
|
-
`)}function
|
|
235
|
+
}`;function xC(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function Ml(e){var r,t;return(t=(r=e.parserType)!=null?r:xC(e.streamParser))!=null?t:"plain"}function Ll(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,a])=>{typeof a=="string"&&t.push(`${r} ${n}: "${a}",`)}),t.push(`${r}},`)),t}function Pl(e,r,t){let n=[],a=e.messageActions&&Object.entries(e.messageActions).some(([s,i])=>s!=="onFeedback"&&s!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(a||o)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([s,i])=>{s==="onFeedback"||s==="onCopy"||(typeof i=="string"?n.push(`${r} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${s}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function Il(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(n||a)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,s])=>{typeof s=="string"?t.push(`${r} ${o}: "${s}",`):typeof s=="boolean"&&t.push(`${r} ${o}: ${s},`)}),t.push(`${r} },`)),a&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function Rl(e,r){let t=[];if(e.layout){let n=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),a=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(n||a)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,s])=>{o!=="render"&&(typeof s=="string"?t.push(`${r} ${o}: "${s}",`):typeof s=="boolean"&&t.push(`${r} ${o}: ${s},`))}),t.push(`${r} },`)),a&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,s])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof s=="object"&&s!==null?(t.push(`${r} avatar: {`),Object.entries(s).forEach(([i,d])=>{typeof d=="string"?t.push(`${r} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${r} ${i}: ${d},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof s=="object"&&s!==null?Object.entries(s).some(([d])=>d!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(s).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${r} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${r} ${d}: ${l},`))}),t.push(`${r} },`)):typeof s=="string"?t.push(`${r} ${o}: "${s}",`):typeof s=="boolean"&&t.push(`${r} ${o}: ${s},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function _p(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function dx(e,r,t){Object.entries(r).forEach(([n,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${t}${n}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${t}${n}: {`),dx(e,a,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(a)},`)}})}function Io(e,r,t,n){t&&(e.push(`${n}${r}: {`),dx(e,t,`${n} `),e.push(`${n}},`))}function cx(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let a=t?{...t,hooks:mC(t.hooks)}:void 0;return r==="esm"?yC(n,a):r==="script-installer"?wC(n,a):r==="script-advanced"?AC(n,a):r==="react-component"?bC(n,a):r==="react-advanced"?CC(n,a):vC(n,a)}function yC(e,r){let t=r==null?void 0:r.hooks,n=Ml(e),a=n!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),a&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Io(o,"theme",e.theme," "),e.launcher&&Io(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([s,i])=>{o.push(` ${s}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"?o.push(` ${s}: ${i},`):typeof i=="number"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([s,i])=>{o.push(` ${s}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{o.push(` "${s}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ll(e," ")),o.push(...Pl(e," ",t)),o.push(...Il(e," ")),o.push(...Rl(e," ")),o.push(..._p(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
236
|
+
`)}function bC(e,r){let t=r==null?void 0:r.hooks,n=Ml(e),a=n!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),a&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Io(o,"theme",e.theme," "),e.launcher&&Io(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([s,i])=>{o.push(` ${s}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"?o.push(` ${s}: ${i},`):typeof i=="number"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([s,i])=>{o.push(` ${s}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{o.push(` "${s}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ll(e," ")),o.push(...Pl(e," ",t)),o.push(...Il(e," ")),o.push(...Rl(e," ")),o.push(..._p(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
|
|
237
|
+
`)}function CC(e,r){let t=r==null?void 0:r.hooks,n=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Io(n,"theme",e.theme," "),e.launcher&&Io(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([a,o])=>{n.push(` ${a}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,o])=>{typeof o=="string"?n.push(` ${a}: "${o}",`):typeof o=="boolean"&&n.push(` ${a}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,o])=>{typeof o=="string"?n.push(` ${a}: "${o}",`):typeof o=="boolean"?n.push(` ${a}: ${o},`):typeof o=="number"&&n.push(` ${a}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,o])=>{typeof o=="string"?n.push(` ${a}: "${o}",`):typeof o=="boolean"&&n.push(` ${a}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([a,o])=>{n.push(` ${a}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{n.push(` "${a}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...Ll(e," ")),n.push(...Pl(e," ",t)),n.push(...Il(e," ")),n.push(...Rl(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${gC}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${ax}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${ax}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${ix}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${ix}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
|
|
238
|
+
`)}function px(e){var a;let r=Ml(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((a=e.suggestionChips)==null?void 0:a.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([s,i])=>{typeof i=="string"&&(o[s]=i)}),Object.keys(o).length>0&&(n.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([s,i])=>{s!=="onFeedback"&&s!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[s]=i)}),Object.keys(o).length>0&&(n.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(s[i]=d)}),Object.keys(s).length>0&&(o.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)s.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(s.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(s[i]=d)}),Object.keys(s).length>0&&(o.messages=s)}Object.keys(o).length>0&&(n.layout=o)}return n}function wC(e,r){let t=px(e),n=r!=null&&r.windowKey?{config:t,windowKey:r.windowKey}:t,a=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ia}/dist/install.global.js" data-config='${a}'></script>`}function vC(e,r){let t=r==null?void 0:r.hooks,n=Ml(e),a=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ia}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ia}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),a&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Io(o,"theme",e.theme," "),e.launcher&&Io(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([s,i])=>{o.push(` ${s}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"?o.push(` ${s}: ${i},`):typeof i=="number"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,i])=>{typeof i=="string"?o.push(` ${s}: "${i}",`):typeof i=="boolean"&&o.push(` ${s}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([s,i])=>{o.push(` ${s}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{o.push(` "${s}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ll(e," ")),o.push(...Pl(e," ",t)),o.push(...Il(e," ")),o.push(...Rl(e," ")),o.push(..._p(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
239
|
+
`)}function AC(e,r){let t=r==null?void 0:r.hooks,n=px(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
|
|
240
240
|
`).map((s,i)=>i===0?s:" "+s).join(`
|
|
241
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ia}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(
|
|
242
|
-
`)}var
|
|
241
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ia}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${hC});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${sx}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${sx}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${lx}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${lx}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...r!=null&&r.windowKey?[` windowKey: '${r.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
|
|
242
|
+
`)}var ux={desktop:{w:1280,h:800},mobile:{w:390,h:844}},fx=.1,mx=.15,gx=1.5,$p=24,hx=40,SC=`
|
|
243
243
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
244
244
|
.persona-dc-root {
|
|
245
245
|
display: flex;
|
|
@@ -480,7 +480,7 @@ ${s.join(`
|
|
|
480
480
|
min-height: 300px;
|
|
481
481
|
}
|
|
482
482
|
}
|
|
483
|
-
`;function
|
|
483
|
+
`;function TC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=SC,document.head.appendChild(e)}function kC(e,r){let t=e.clientWidth-$p*2-hx,n=e.clientHeight-$p*2-hx;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function EC(e,r,t,n,a){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=a==="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 xx(e,r){let{items:t,initialIndex:n=0,initialDevice:a="desktop",initialColorScheme:o="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");TC();let u=Math.max(0,Math.min(n,t.length-1)),p=a,m=o,f=null,w=1,v=!1,k=x("div","persona-dc-root"),T=x("div","persona-dc-toolbar"),A=x("div","persona-dc-toolbar-lead"),E=x("div","persona-dc-toolbar-trail"),b=Qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Be(-1)}),h=x("div");h.style.position="relative";let S=x("button","persona-dc-title-btn");S.type="button",S.setAttribute("aria-expanded","false"),S.setAttribute("aria-haspopup","listbox");let L=x("span","persona-dc-title-text"),O=x("span","persona-dc-title-chevron"),H=Ce("chevron-down",12,"currentColor",2);H&&O.appendChild(H),S.append(L,O);let R=x("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let B=!1;function V(){R.innerHTML="";for(let Y=0;Y<t.length;Y++){let G=t[Y],we=x("button","persona-dc-dropdown-item");we.type="button",we.setAttribute("role","option"),we.setAttribute("aria-current",Y===u?"true":"false");let ue=x("span");if(ue.textContent=G.title,we.appendChild(ue),G.description){let re=x("span","persona-dc-dropdown-desc");re.textContent=G.description,we.appendChild(re)}we.addEventListener("click",()=>{fe(),Ee(Y)}),R.appendChild(we)}}function ne(){B=!B,R.style.display=B?"":"none",S.setAttribute("aria-expanded",B?"true":"false"),B&&V()}function fe(){B&&(B=!1,R.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",Y=>{Y.stopPropagation(),ne()});let _e=()=>fe();document.addEventListener("click",_e),h.append(S,R);let je=Qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Be(1)}),ye=x("span","persona-dc-counter");A.append(b,h,je,ye);let me=null;i&&(me=Ps({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:Y=>{p=Y,J.dataset.device=p,f=null,K()}}),E.appendChild(me.element));let Pe=null;if(s){let Y=x("div","persona-dc-zoom-controls"),G=Qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let re=f!=null?f:w;f=Math.max(mx,re-fx),K()}});Pe=x("span","persona-dc-zoom-level"),Pe.title="Reset to 100%",Pe.style.cursor="pointer",Pe.addEventListener("click",()=>{f=1,K()});let we=Qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let re=f!=null?f:w;f=Math.min(gx,re+fx),K()}}),ue=Qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,K()}});Y.append(G,Pe,we,ue),E.appendChild(Y)}if(d){let Y=x("div","persona-dc-separator");E.appendChild(Y);let G=Ps({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:m,onSelect:we=>{m=we,J.dataset.colorScheme=m,pe()}});E.appendChild(G.element)}let Ve=x("div","persona-dc-separator");E.appendChild(Ve);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(A,E);let Ae=x("div","persona-dc-stage"),J=x("div","persona-dc-iframe-wrapper");J.dataset.device=p,J.dataset.colorScheme=m;let de=x("iframe","persona-dc-iframe");de.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),de.setAttribute("loading","lazy"),de.title=t[u].title,J.appendChild(de),Ae.appendChild(J),k.append(T,Ae),e.appendChild(k);function pe(){var Y;try{let G=(Y=de.contentDocument)==null?void 0:Y.body;if(!G)return;m==="dark"?G.classList.add("theme-dark"):G.classList.remove("theme-dark")}catch{}}de.addEventListener("load",()=>pe());function se(){let Y=t[u];L.textContent=Y.title,ye.textContent=`${u+1} / ${t.length}`,de.title=Y.title}function Be(Y){let G=((u+Y)%t.length+t.length)%t.length;Ee(G)}function Ee(Y){Y<0||Y>=t.length||(u=Y,de.src=t[u].url,se(),l==null||l(u,t[u]))}function K(){var we;if(v)return;let Y=(we=ux[p])!=null?we:ux.desktop;w=kC(Ae,Y);let G=Math.max(mx,Math.min(gx,f!=null?f:w));EC(J,de,Y,G,p),Pe&&(Pe.textContent=`${Math.round(G*100)}%`)}let Oe=new ResizeObserver(()=>K());Oe.observe(Ae),se(),de.src=t[u].url,requestAnimationFrame(()=>K());function Fe(){v||(v=!0,Oe.disconnect(),document.removeEventListener("click",_e),k.remove())}return{element:k,goTo:Ee,next:()=>Be(1),prev:()=>Be(-1),getIndex:()=>u,setDevice(Y){p=Y,J.dataset.device=Y,me==null||me.setSelected(Y),f=null,K()},setColorScheme(Y){m=Y,J.dataset.colorScheme=Y},setZoom(Y){f=Y,K()},destroy:Fe}}function yx(){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 bx(){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 Cx(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 wx(){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 vx(){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),a=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),s=Math.round(n+(255-n)*(1-r)),i=Math.round(a+(255-a)*(1-r));return`#${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Ax(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var MC={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"}}},Sx={components:{panel:{borderRadius:"0",shadow:"none"}}},Up={id:"shop",label:"Shopping Assistant",config:{theme:MC,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?"]}},qp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Sx}},zp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Sx}},Vp={shop:Up,minimal:qp,fullscreen:zp};function Tx(e){return Vp[e]}var LC=`
|
|
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; }
|
|
@@ -516,7 +516,7 @@ ${s.join(`
|
|
|
516
516
|
mask-image: none !important;
|
|
517
517
|
}
|
|
518
518
|
}
|
|
519
|
-
`.trim(),
|
|
519
|
+
`.trim(),PC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:LC};ra(PC);var IC=`
|
|
520
520
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
521
521
|
animation: persona-stream-glyph-cycle-fade
|
|
522
522
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -534,7 +534,7 @@ ${s.join(`
|
|
|
534
534
|
opacity: 1 !important;
|
|
535
535
|
}
|
|
536
536
|
}
|
|
537
|
-
`.trim(),Fs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",
|
|
537
|
+
`.trim(),Fs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",RC=10,HC=120,jp=120,BC=.4,WC=50,DC=e=>{var n;if(!e)return jp;let t=((n=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return t?parseFloat(t[1]):jp},Hx=e=>{let r=e.closest(".persona-stream-glyph-cycle"),t=DC(r);return HC*t/jp},Gp=e=>{let r=Fs[Math.floor(Math.random()*Fs.length)];return e&&r===e&&(r=Fs[(Fs.indexOf(r)+1)%Fs.length]),r},OC=e=>{let r=e.closest(".persona-stream-glyph-cycle");if(!r)return;let t=r.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),n=!1;for(let a of Array.from(t)){if(a===e){n=!0;continue}n&&Math.random()<BC&&(a.textContent=Gp())}},kx=new WeakMap,Ex=25,Mx=.5,FC=6,Lx=.25,Px=new WeakMap,Ix=new WeakMap,NC=(e,r)=>{var a;if(!e)return Ex*Mx;let t=Px.get(e);Px.set(e,r);let n=(a=Ix.get(e))!=null?a:Ex;if(t!==void 0){let o=r-t;o>1&&(n=n*(1-Lx)+o*Lx,Ix.set(e,n))}return Math.max(FC,n*Mx)},Da=new Map,_C=e=>{var t;let r=e.closest("[data-message-id]");return(t=r==null?void 0:r.dataset.messageId)!=null?t:null},$C=e=>{var r;e&&Da.set(e,((r=Da.get(e))!=null?r:0)+1)},UC=e=>{var t;if(!e)return;let r=(t=Da.get(e))!=null?t:0;r<=1?Da.delete(e):Da.set(e,r-1)},Bx=e=>{var l;if(e.dataset.glyphCycleScheduled==="true")return;let r=(l=e.textContent)!=null?l:"";if(!r||/\s/.test(r))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=r,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Gp();let t=_C(e);t&&(e.dataset.glyphCycleMessageId=t),$C(t);let n=e.closest(".persona-stream-glyph-cycle"),a=Date.now(),o=NC(n,a),s=Hx(e),i=RC*s,d=a+i;if(n){let u=kx.get(n);u!==void 0&&(d=Math.max(d,u)),kx.set(n,d+o)}qC(e,r,d)},qC=(e,r,t)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let n=Hx(e),a=(s=e.textContent)!=null?s:void 0,o=()=>{var d;if(!e.isConnected)return;if(Date.now()>=t){e.textContent=r,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,UC((d=e.dataset.glyphCycleMessageId)!=null?d:null),delete e.dataset.glyphCycleMessageId;return}let i=Gp(a);e.textContent=i,a=i,OC(e),setTimeout(o,n)};setTimeout(o,n)},Rx=e=>{var t;let r=(t=e.querySelectorAll)==null?void 0:t.call(e,".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(r)for(let n of Array.from(r))Bx(n)},zC=e=>e.nodeType===1,VC={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:IC,bufferContent(e){if(e.length<WC)return"";let r=0,t=-1,n=0;for(;n<e.length;){if(e[n]==="*"&&e[n+1]==="*"){r+=1,n+=2;continue}/\s/.test(e[n])&&r%2===0&&(t=n),n+=1}return t<0?"":e.slice(0,t)},isAnimating(e){var r;return((r=Da.get(e.id))!=null?r:0)>0},onAttach(e){Rx(e);let r=new MutationObserver(t=>{for(let n of t)for(let a of Array.from(n.addedNodes))zC(a)&&(a.classList.contains("persona-stream-char")&&a.closest(".persona-stream-glyph-cycle")?Bx(a):Rx(a))});return r.observe(e,{childList:!0,subtree:!0}),()=>r.disconnect()}};ra(VC);return Ux(jC);})();
|
|
538
538
|
/*! Bundled license information:
|
|
539
539
|
|
|
540
540
|
dompurify/dist/purify.es.mjs:
|