@runtypelabs/persona 3.20.0 → 3.21.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/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-cwY5HaFD.d.cts → types-CWPIj66R.d.cts} +19 -1
- package/dist/animations/{types-cwY5HaFD.d.ts → types-CWPIj66R.d.ts} +19 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/index.cjs +46 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -1
- package/dist/index.d.ts +19 -1
- package/dist/index.global.js +72 -72
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +46 -46
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +260 -0
- package/dist/theme-editor.d.cts +19 -1
- package/dist/theme-editor.d.ts +19 -1
- package/dist/theme-editor.js +260 -0
- package/package.json +1 -1
- package/src/client.test.ts +521 -0
- package/src/client.ts +150 -1
- package/src/components/message-bubble.test.ts +192 -0
- package/src/components/message-bubble.ts +200 -0
- package/src/types.ts +27 -2
package/dist/index.global.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[n]);)n++};return s()},
|
|
3
|
-
`).map(
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var Fx=Object.create;var es=Object.defineProperty;var Nx=Object.getOwnPropertyDescriptor;var _x=Object.getOwnPropertyNames;var $x=Object.getPrototypeOf,Ux=Object.prototype.hasOwnProperty;var Um=e=>{throw TypeError(e)};var qx=(e,r,t)=>r in e?es(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var qm=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),zx=(e,r)=>{for(var t in r)es(e,t,{get:r[t],enumerable:!0})},zm=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of _x(r))!Ux.call(e,o)&&o!==t&&es(e,o,{get:()=>r[o],enumerable:!(n=Nx(r,o))||n.enumerable});return e};var Bl=(e,r,t)=>(t=e!=null?Fx($x(e)):{},zm(r||!e||!e.__esModule?es(t,"default",{value:e,enumerable:!0}):t,e)),Vx=e=>zm(es({},"__esModule",{value:!0}),e);var er=(e,r,t)=>qx(e,typeof r!="symbol"?r+"":r,t),jx=(e,r,t)=>r.has(e)||Um("Cannot "+t);var Vm=(e,r,t)=>r.has(e)?Um("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t);var ai=(e,r,t)=>(jx(e,r,"access private method"),t);var Zl=qm(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.Allow=je.ALL=je.COLLECTION=je.ATOM=je.SPECIAL=je.INF=je._INFINITY=je.INFINITY=je.NAN=je.BOOL=je.NULL=je.OBJ=je.ARR=je.NUM=je.STR=void 0;je.STR=1;je.NUM=2;je.ARR=4;je.OBJ=8;je.NULL=16;je.BOOL=32;je.NAN=64;je.INFINITY=128;je._INFINITY=256;je.INF=je.INFINITY|je._INFINITY;je.SPECIAL=je.NULL|je.BOOL|je.INF|je.NAN;je.ATOM=je.STR|je.NUM|je.SPECIAL;je.COLLECTION=je.ARR|je.OBJ;je.ALL=je.ATOM|je.COLLECTION;je.Allow={STR:je.STR,NUM:je.NUM,ARR:je.ARR,OBJ:je.OBJ,NULL:je.NULL,BOOL:je.BOOL,NAN:je.NAN,INFINITY:je.INFINITY,_INFINITY:je._INFINITY,INF:je.INF,SPECIAL:je.SPECIAL,ATOM:je.ATOM,COLLECTION:je.COLLECTION,ALL:je.ALL};je.default=je.Allow});var hi=qm(Ir=>{"use strict";var Qy=Ir&&Ir.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(r,t);(!o||("get"in o?!r.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,o)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),Zy=Ir&&Ir.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&Qy(r,e,t)};Object.defineProperty(Ir,"__esModule",{value:!0});Ir.Allow=Ir.MalformedJSON=Ir.PartialJSON=Ir.parseJSON=Ir.parse=void 0;var Jr=Zl();Object.defineProperty(Ir,"Allow",{enumerable:!0,get:function(){return Jr.Allow}});Zy(Zl(),Ir);var mi=class extends Error{};Ir.PartialJSON=mi;var gi=class extends Error{};Ir.MalformedJSON=gi;function kg(e,r=Jr.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return eb(e.trim(),r)}Ir.parseJSON=kg;var eb=(e,r)=>{let t=e.length,n=0,o=m=>{throw new mi(`${m} at position ${n}`)},a=m=>{throw new gi(`${m} at position ${n}`)},s=()=>(p(),n>=t&&o("Unexpected end of input"),e[n]==='"'?i():e[n]==="{"?d():e[n]==="["?l():e.substring(n,n+4)==="null"||Jr.Allow.NULL&r&&t-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||Jr.Allow.BOOL&r&&t-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||Jr.Allow.BOOL&r&&t-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||Jr.Allow.INFINITY&r&&t-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||Jr.Allow._INFINITY&r&&1<t-n&&t-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||Jr.Allow.NAN&r&&t-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),i=()=>{let 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){a(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("\\"))+'"')}o("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;o("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;o("Expected ']' at end of array")}return n++,m},u=()=>{if(n===0){e==="-"&&a("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{}a(String(f))}}let m=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==t&&!(Jr.Allow.NUM&r)&&o("Unterminated number literal");try{return JSON.parse(e.substring(m,n))}catch{e.substring(m,n)==="-"&&o("Not sure what '-' is");try{return JSON.parse(e.substring(m,e.lastIndexOf("e")))}catch(w){a(String(w))}}},p=()=>{for(;n<t&&`
|
|
2
|
+
\r `.includes(e[n]);)n++};return s()},tb=kg;Ir.parse=tb});var ew={};zx(ew,{ASK_USER_QUESTION_TOOL_NAME:()=>bp,AgentWidgetClient:()=>Yo,AgentWidgetSession:()=>wa,AttachmentManager:()=>ta,DEFAULT_COMPONENTS:()=>Zc,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>qi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>mn,DEFAULT_PALETTE:()=>Yc,DEFAULT_SEMANTIC:()=>Qc,DEFAULT_WIDGET_CONFIG:()=>jt,PRESETS:()=>Gp,PRESET_FULLSCREEN:()=>jp,PRESET_MINIMAL:()=>Vp,PRESET_SHOP:()=>zp,THEME_ZONES:()=>jg,VERSION:()=>ia,accessibilityPlugin:()=>wx,animationsPlugin:()=>vx,applyThemeVariables:()=>vo,attachHeaderToContainer:()=>na,brandPlugin:()=>Ax,buildComposer:()=>ka,buildDefaultHeader:()=>dp,buildHeader:()=>ao,buildHeaderWithLayout:()=>Ta,buildMinimalHeader:()=>cp,collectEnrichedPageContext:()=>ax,componentRegistry:()=>lo,createActionManager:()=>Ds,createAgentExperience:()=>Tl,createAskUserQuestionBubble:()=>Sh,createBestAvailableVoiceProvider:()=>Ii,createBubbleWithLayout:()=>dh,createCSATFeedback:()=>vl,createComboButton:()=>ol,createComponentMiddleware:()=>Nh,createComponentStreamParser:()=>yl,createDefaultSanitizer:()=>Ql,createDemoCarousel:()=>Cx,createDirectivePostprocessor:()=>pg,createDropdownMenu:()=>ko,createFlexibleJsonStreamParser:()=>Lg,createIconButton:()=>Qt,createImagePart:()=>Dg,createJsonStreamParser:()=>Ai,createLabelButton:()=>Ls,createLocalStorageAdapter:()=>xl,createMarkdownProcessor:()=>is,createMarkdownProcessorFromConfig:()=>Xo,createMessageActions:()=>gp,createNPSFeedback:()=>Al,createPlainTextParser:()=>wi,createPlugin:()=>kx,createRegexJsonParser:()=>vi,createStandardBubble:()=>Ea,createTextPart:()=>gs,createTheme:()=>Aa,createThemeObserver:()=>Gi,createToggleGroup:()=>Ps,createTypingIndicator:()=>oa,createVoiceProvider:()=>ea,createWidgetHostLayout:()=>Os,createXmlParser:()=>Si,defaultActionHandlers:()=>sa,defaultJsonActionParser:()=>Ws,defaultParseRules:()=>_p,detectColorScheme:()=>bs,directivePostprocessor:()=>ug,ensureAskUserQuestionSheet:()=>Ra,escapeHtml:()=>Jo,extractComponentDirectiveFromMessage:()=>wl,fileToImagePart:()=>Og,formatEnrichedContext:()=>sx,generateAssistantMessageId:()=>Qo,generateCodeSnippet:()=>fx,generateMessageId:()=>Ig,generateStableSelector:()=>$p,generateUserMessageId:()=>Ca,getActiveTheme:()=>Sa,getColorScheme:()=>tp,getDisplayText:()=>Hg,getHeaderLayout:()=>pp,getImageParts:()=>Wg,getPreset:()=>Mx,hasComponentDirective:()=>Cl,hasImages:()=>Bg,headerLayouts:()=>al,highContrastPlugin:()=>Tx,initAgentWidget:()=>Xh,isAskUserQuestionMessage:()=>so,isComponentDirectiveType:()=>Fh,isDockedMountMode:()=>hr,isVoiceSupported:()=>xs,listRegisteredStreamAnimations:()=>ap,markdownPostprocessor:()=>ql,mergeWithDefaults:()=>zi,normalizeContent:()=>Rg,parseAskUserQuestionPayload:()=>io,pluginRegistry:()=>Bs,reducedMotionPlugin:()=>Sx,registerStreamAnimationPlugin:()=>ra,removeAskUserQuestionSheet:()=>Lo,renderComponentDirective:()=>bl,renderLoadingIndicatorWithFallback:()=>mp,renderLucideIcon:()=>Ce,resolveDockConfig:()=>vn,resolveSanitizer:()=>ya,resolveTokens:()=>Vi,themeToCssVariables:()=>ji,unregisterStreamAnimationPlugin:()=>op,validateImageFile:()=>Fg,validateTheme:()=>ep});function Ol(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Go=Ol();function Ym(e){Go=e}var Qm=/[&<>"']/,Gx=new RegExp(Qm.source,"g"),Zm=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Xx=new RegExp(Zm.source,"g"),Jx={"&":"&","<":"<",">":">",'"':""","'":"'"},jm=e=>Jx[e];function un(e,r){if(r){if(Qm.test(e))return e.replace(Gx,jm)}else if(Zm.test(e))return e.replace(Xx,jm);return e}var Kx=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Yx(e){return e.replace(Kx,(r,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}var Qx=/(^|[^\[])\^/g;function Kt(e,r){let t=typeof e=="string"?e:e.source;r=r||"";let n={replace:(o,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(Qx,"$1"),t=t.replace(o,s),n},getRegex:()=>new RegExp(t,r)};return n}function Gm(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch{return null}return e}var rs={exec:()=>null};function Xm(e,r){let t=e.replace(/\|/g,(a,s,i)=>{let d=!1,l=s;for(;--l>=0&&i[l]==="\\";)d=!d;return d?"|":" |"}),n=t.split(/ \|/),o=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),r)if(n.length>r)n.splice(r);else for(;n.length<r;)n.push("");for(;o<n.length;o++)n[o]=n[o].trim().replace(/\\\|/g,"|");return n}function si(e,r,t){let n=e.length;if(n===0)return"";let o=0;for(;o<n;){let a=e.charAt(n-o-1);if(a===r&&!t)o++;else if(a!==r&&t)o++;else break}return e.slice(0,n-o)}function Zx(e,r){if(e.indexOf(r[1])===-1)return-1;let t=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===r[0])t++;else if(e[n]===r[1]&&(t--,t<0))return n;return-1}function Jm(e,r,t,n){let o=r.href,a=r.title?un(r.title):null,s=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){n.state.inLink=!0;let i={type:"link",raw:t,href:o,title:a,text:s,tokens:n.inlineTokens(s)};return n.state.inLink=!1,i}return{type:"image",raw:t,href:o,title:a,text:un(s)}}function ey(e,r){let t=e.match(/^(\s+)(?:```)/);if(t===null)return r;let n=t[1];return r.split(`
|
|
3
|
+
`).map(o=>{let a=o.match(/^\s+/);if(a===null)return o;let[s]=a;return s.length>=n.length?o.slice(n.length):o}).join(`
|
|
4
4
|
`)}var ha=class{constructor(r){er(this,"options");er(this,"rules");er(this,"lexer");this.options=r||Go}space(r){let t=this.rules.block.newline.exec(r);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(r){let t=this.rules.block.code.exec(r);if(t){let n=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:si(n,`
|
|
5
|
-
`)}}}fences(r){let t=this.rules.block.fences.exec(r);if(t){let n=t[0],
|
|
5
|
+
`)}}}fences(r){let t=this.rules.block.fences.exec(r);if(t){let n=t[0],o=ey(n,t[3]||"");return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:o}}}heading(r){let t=this.rules.block.heading.exec(r);if(t){let n=t[2].trim();if(/#$/.test(n)){let o=si(n,"#");(this.options.pedantic||!o||/ $/.test(o))&&(n=o.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(r){let t=this.rules.block.hr.exec(r);if(t)return{type:"hr",raw:t[0]}}blockquote(r){let t=this.rules.block.blockquote.exec(r);if(t){let n=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,`
|
|
6
6
|
$1`);n=si(n.replace(/^ *>[ \t]?/gm,""),`
|
|
7
|
-
`);let
|
|
7
|
+
`);let o=this.lexer.state.top;this.lexer.state.top=!0;let a=this.lexer.blockTokens(n);return this.lexer.state.top=o,{type:"blockquote",raw:t[0],tokens:a,text:n}}}list(r){let t=this.rules.block.list.exec(r);if(t){let n=t[1].trim(),o=n.length>1,a={type:"list",raw:"",ordered:o,start:o?+n.slice(0,-1):"",loose:!1,items:[]};n=o?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=o?n:"[*+-]");let s=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),i="",d="",l=!1;for(;r;){let u=!1;if(!(t=s.exec(r))||this.rules.block.hr.test(r))break;i=t[0],r=r.substring(i.length);let p=t[2].split(`
|
|
8
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(n.length===
|
|
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=
|
|
17
|
-
]`).replace("lheading",
|
|
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,
|
|
19
|
-
`:t.push(n);continue}if(n=this.tokenizer.code(r)){r=r.substring(n.raw.length),
|
|
20
|
-
`+n.raw,
|
|
21
|
-
`+n.text,this.inlineQueue[this.inlineQueue.length-1].src=
|
|
22
|
-
`+n.raw,
|
|
23
|
-
`+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=
|
|
24
|
-
`+n.raw,
|
|
25
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=
|
|
26
|
-
`+n.raw,
|
|
27
|
-
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=
|
|
28
|
-
`,
|
|
14
|
+
`,r=r.substring(h.length+1),p=m.slice(f)}}a.loose||(l?a.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]\] +/,""))),a.items.push({type:"list_item",raw:i,task:!!v,checked:k,loose:!1,text:d,tokens:[]}),a.raw+=i}a.items[a.items.length-1].raw=i.trimEnd(),a.items[a.items.length-1].text=d.trimEnd(),a.raw=a.raw.trimEnd();for(let u=0;u<a.items.length;u++)if(this.lexer.state.top=!1,a.items[u].tokens=this.lexer.blockTokens(a.items[u].text,[]),!a.loose){let p=a.items[u].tokens.filter(f=>f.type==="space"),m=p.length>0&&p.some(f=>/\n.*\n/.test(f.raw));a.loose=m}if(a.loose)for(let u=0;u<a.items.length;u++)a.items[u].loose=!0;return a}}html(r){let t=this.rules.block.html.exec(r);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(r){let t=this.rules.block.def.exec(r);if(t){let n=t[1].toLowerCase().replace(/\s+/g," "),o=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:o,title:a}}}table(r){let t=this.rules.block.table.exec(r);if(!t||!/[:|]/.test(t[2]))return;let n=Xm(t[1]),o=t[2].replace(/^\||\| *$/g,"").split("|"),a=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(`
|
|
15
|
+
`):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===o.length){for(let i of o)/^ *-+: *$/.test(i)?s.align.push("right"):/^ *:-+: *$/.test(i)?s.align.push("center"):/^ *:-+ *$/.test(i)?s.align.push("left"):s.align.push(null);for(let i of n)s.header.push({text:i,tokens:this.lexer.inline(i)});for(let i of a)s.rows.push(Xm(i,s.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return s}}lheading(r){let t=this.rules.block.lheading.exec(r);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(r){let t=this.rules.block.paragraph.exec(r);if(t){let n=t[1].charAt(t[1].length-1)===`
|
|
16
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(r){let t=this.rules.block.text.exec(r);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(r){let t=this.rules.inline.escape.exec(r);if(t)return{type:"escape",raw:t[0],text:un(t[1])}}tag(r){let t=this.rules.inline.tag.exec(r);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(r){let t=this.rules.inline.link.exec(r);if(t){let n=t[2].trim();if(!this.options.pedantic&&/^</.test(n)){if(!/>$/.test(n))return;let s=si(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=Zx(t[2],"()");if(s>-1){let d=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,d).trim(),t[3]=""}}let o=t[2],a="";if(this.options.pedantic){let s=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);s&&(o=s[1],a=s[3])}else a=t[3]?t[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(n)?o=o.slice(1):o=o.slice(1,-1)),Jm(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer)}}reflink(r,t){let n;if((n=this.rules.inline.reflink.exec(r))||(n=this.rules.inline.nolink.exec(r))){let o=(n[2]||n[1]).replace(/\s+/g," "),a=t[o.toLowerCase()];if(!a){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Jm(n,a,n[0],this.lexer)}}emStrong(r,t,n=""){let o=this.rules.inline.emStrongLDelim.exec(r);if(!o||o[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(o[1]||o[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...o[0]].length-1,i,d,l=s,u=0,p=o[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*r.length+s);(o=p.exec(t))!=null;){if(i=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!i)continue;if(d=[...i].length,o[3]||o[4]){l+=d;continue}else if((o[5]||o[6])&&s%3&&!((s+d)%3)){u+=d;continue}if(l-=d,l>0)continue;d=Math.min(d,d+l+u);let m=[...o[0]][0].length,f=r.slice(0,s+o.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," "),o=/[^ ]/.test(n),a=/^ /.test(n)&&/ $/.test(n);return o&&a&&(n=n.substring(1,n.length-1)),n=un(n,!0),{type:"codespan",raw:t[0],text:n}}}br(r){let t=this.rules.inline.br.exec(r);if(t)return{type:"br",raw:t[0]}}del(r){let t=this.rules.inline.del.exec(r);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(r){let t=this.rules.inline.autolink.exec(r);if(t){let n,o;return t[2]==="@"?(n=un(t[1]),o="mailto:"+n):(n=un(t[1]),o=n),{type:"link",raw:t[0],text:n,href:o,tokens:[{type:"text",raw:n,text:n}]}}}url(r){var n,o;let t;if(t=this.rules.inline.url.exec(r)){let a,s;if(t[2]==="@")a=un(t[0]),s="mailto:"+a;else{let i;do i=t[0],t[0]=(o=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?o:"";while(i!==t[0]);a=un(t[0]),t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:a,href:s,tokens:[{type:"text",raw:a,text:a}]}}}inlineText(r){let t=this.rules.inline.text.exec(r);if(t){let n;return this.lexer.state.inRawBlock?n=t[0]:n=un(t[0]),{type:"text",raw:t[0],text:n}}}},ty=/^(?: *(?:\n|$))+/,ry=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,ny=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,as=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,oy=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,eg=/(?:[*+-]|\d{1,9}[.)])/,tg=Kt(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,eg).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),Fl=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ay=/^[^\n]+/,Nl=/(?!\s*\])(?:\\.|[^\[\]\\])+/,sy=Kt(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",Nl).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),iy=Kt(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,eg).getRegex(),di="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",_l=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ly=Kt("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",_l).replace("tag",di).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),rg=Kt(Fl).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",di).getRegex(),dy=Kt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",rg).getRegex(),$l={blockquote:dy,code:ry,def:sy,fences:ny,heading:oy,hr:as,html:ly,lheading:tg,list:iy,newline:ty,paragraph:rg,table:rs,text:ay},Km=Kt("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",di).getRegex(),cy={...$l,table:Km,paragraph:Kt(Fl).replace("hr",as).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Km).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",di).getRegex()},py={...$l,html:Kt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_l).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:rs,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Kt(Fl).replace("hr",as).replace("heading",` *#{1,6} *[^
|
|
17
|
+
]`).replace("lheading",tg).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ng=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,uy=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,og=/^( {2,}|\\)\n(?!\s*$)/,fy=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ss="\\p{P}\\p{S}",my=Kt(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,ss).getRegex(),gy=/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,hy=Kt(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,ss).getRegex(),xy=Kt("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,ss).getRegex(),yy=Kt("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,ss).getRegex(),by=Kt(/\\([punct])/,"gu").replace(/punct/g,ss).getRegex(),Cy=Kt(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),wy=Kt(_l).replace("(?:-->|$)","-->").getRegex(),vy=Kt("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",wy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),li=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ay=Kt(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",li).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ag=Kt(/^!?\[(label)\]\[(ref)\]/).replace("label",li).replace("ref",Nl).getRegex(),sg=Kt(/^!?\[(ref)\](?:\[\])?/).replace("ref",Nl).getRegex(),Sy=Kt("reflink|nolink(?!\\()","g").replace("reflink",ag).replace("nolink",sg).getRegex(),Ul={_backpedal:rs,anyPunctuation:by,autolink:Cy,blockSkip:gy,br:og,code:uy,del:rs,emStrongLDelim:hy,emStrongRDelimAst:xy,emStrongRDelimUnd:yy,escape:ng,link:Ay,nolink:sg,punctuation:my,reflink:ag,reflinkSearch:Sy,tag:vy,text:fy,url:rs},Ty={...Ul,link:Kt(/^!?\[(label)\]\((.*?)\)/).replace("label",li).getRegex(),reflink:Kt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",li).getRegex()},Wl={...Ul,escape:Kt(ng).replace("])","~|])").getRegex(),url:Kt(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},ky={...Wl,br:Kt(og).replace("{2,}","*").getRegex(),text:Kt(Wl.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ii={normal:$l,gfm:cy,pedantic:py},ts={normal:Ul,gfm:Wl,breaks:ky,pedantic:Ty},to=class e{constructor(r){er(this,"tokens");er(this,"options");er(this,"state");er(this,"tokenizer");er(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=r||Go,this.options.tokenizer=this.options.tokenizer||new ha,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={block:ii.normal,inline:ts.normal};this.options.pedantic?(t.block=ii.pedantic,t.inline=ts.pedantic):this.options.gfm&&(t.block=ii.gfm,this.options.breaks?t.inline=ts.breaks:t.inline=ts.gfm),this.tokenizer.rules=t}static get rules(){return{block:ii,inline:ts}}static lex(r,t){return new e(t).lex(r)}static lexInline(r,t){return new e(t).inlineTokens(r)}lex(r){r=r.replace(/\r\n|\r/g,`
|
|
18
|
+
`),this.blockTokens(r,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(r,t=[]){this.options.pedantic?r=r.replace(/\t/g," ").replace(/^ +$/gm,""):r=r.replace(/^( *)(\t+)/gm,(i,d,l)=>d+" ".repeat(l.length));let n,o,a,s;for(;r;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(i=>(n=i.call({lexer:this},r,t))?(r=r.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.space(r)){r=r.substring(n.raw.length),n.raw.length===1&&t.length>0?t[t.length-1].raw+=`
|
|
19
|
+
`:t.push(n);continue}if(n=this.tokenizer.code(r)){r=r.substring(n.raw.length),o=t[t.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
|
|
20
|
+
`+n.raw,o.text+=`
|
|
21
|
+
`+n.text,this.inlineQueue[this.inlineQueue.length-1].src=o.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),o=t[t.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
|
|
22
|
+
`+n.raw,o.text+=`
|
|
23
|
+
`+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=o.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(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(a=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&&(a=r.substring(0,i+1))}if(this.state.top&&(n=this.tokenizer.paragraph(a))){o=t[t.length-1],s&&o.type==="paragraph"?(o.raw+=`
|
|
24
|
+
`+n.raw,o.text+=`
|
|
25
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n),s=a.length!==r.length,r=r.substring(n.raw.length);continue}if(n=this.tokenizer.text(r)){r=r.substring(n.raw.length),o=t[t.length-1],o&&o.type==="text"?(o.raw+=`
|
|
26
|
+
`+n.raw,o.text+=`
|
|
27
|
+
`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):t.push(n);continue}if(r){let i="Infinite loop on byte: "+r.charCodeAt(0);if(this.options.silent){console.error(i);break}else throw new Error(i)}}return this.state.top=!0,t}inline(r,t=[]){return this.inlineQueue.push({src:r,tokens:t}),t}inlineTokens(r,t=[]){let n,o,a,s=r,i,d,l;if(this.tokens.links){let u=Object.keys(this.tokens.links);if(u.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)u.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;r;)if(d||(l=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(n=u.call({lexer:this},r,t))?(r=r.substring(n.raw.length),t.push(n),!0):!1))){if(n=this.tokenizer.escape(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.tag(r)){r=r.substring(n.raw.length),o=t[t.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(n=this.tokenizer.link(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.reflink(r,this.tokens.links)){r=r.substring(n.raw.length),o=t[t.length-1],o&&n.type==="text"&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(n=this.tokenizer.emStrong(r,s,l)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.codespan(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.br(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.del(r)){r=r.substring(n.raw.length),t.push(n);continue}if(n=this.tokenizer.autolink(r)){r=r.substring(n.raw.length),t.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(r))){r=r.substring(n.raw.length),t.push(n);continue}if(a=r,this.options.extensions&&this.options.extensions.startInline){let u=1/0,p=r.slice(1),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&&(a=r.substring(0,u+1))}if(n=this.tokenizer.inlineText(a)){r=r.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(l=n.raw.slice(-1)),d=!0,o=t[t.length-1],o&&o.type==="text"?(o.raw+=n.raw,o.text+=n.text):t.push(n);continue}if(r){let u="Infinite loop on byte: "+r.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}},xa=class{constructor(r){er(this,"options");this.options=r||Go}code(r,t,n){var a;let o=(a=(t||"").match(/^\S*/))==null?void 0:a[0];return r=r.replace(/\n$/,"")+`
|
|
28
|
+
`,o?'<pre><code class="language-'+un(o)+'">'+(n?r:un(r,!0))+`</code></pre>
|
|
29
29
|
`:"<pre><code>"+(n?r:un(r,!0))+`</code></pre>
|
|
30
30
|
`}blockquote(r){return`<blockquote>
|
|
31
31
|
${r}</blockquote>
|
|
32
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,n){let
|
|
35
|
-
`+r+"</"+
|
|
34
|
+
`}list(r,t,n){let o=t?"ol":"ul",a=t&&n!==1?' start="'+n+'"':"";return"<"+o+a+`>
|
|
35
|
+
`+r+"</"+o+`>
|
|
36
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>
|
|
@@ -42,17 +42,17 @@ ${r}</blockquote>
|
|
|
42
42
|
`}tablerow(r){return`<tr>
|
|
43
43
|
${r}</tr>
|
|
44
44
|
`}tablecell(r,t){let n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+r+`</${n}>
|
|
45
|
-
`}strong(r){return`<strong>${r}</strong>`}em(r){return`<em>${r}</em>`}codespan(r){return`<code>${r}</code>`}br(){return"<br>"}del(r){return`<del>${r}</del>`}link(r,t,n){let
|
|
46
|
-
`+(s.tokens?this.parseInline(s.tokens):s.text);n+=t?this.renderer.paragraph(i):i;continue}default:{let s='Token with "'+
|
|
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([
|
|
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 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(`
|
|
45
|
+
`}strong(r){return`<strong>${r}</strong>`}em(r){return`<em>${r}</em>`}codespan(r){return`<code>${r}</code>`}br(){return"<br>"}del(r){return`<del>${r}</del>`}link(r,t,n){let o=Gm(r);if(o===null)return n;r=o;let a='<a href="'+r+'"';return t&&(a+=' title="'+t+'"'),a+=">"+n+"</a>",a}image(r,t,n){let o=Gm(r);if(o===null)return n;r=o;let a=`<img src="${r}" alt="${n}"`;return t&&(a+=` title="${t}"`),a+=">",a}text(r){return r}},ns=class{strong(r){return r}em(r){return r}codespan(r){return r}del(r){return r}html(r){return r}text(r){return r}link(r,t,n){return""+n}image(r,t,n){return""+n}br(){return""}},ro=class e{constructor(r){er(this,"options");er(this,"renderer");er(this,"textRenderer");this.options=r||Go,this.options.renderer=this.options.renderer||new xa,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new ns}static parse(r,t){return new e(t).parse(r)}static parseInline(r,t){return new e(t).parseInline(r)}parse(r,t=!0){let n="";for(let o=0;o<r.length;o++){let a=r[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=a,i=this.options.extensions.renderers[s.type].call({parser:this},s);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(s.type)){n+=i||"";continue}}switch(a.type){case"space":continue;case"hr":{n+=this.renderer.hr();continue}case"heading":{let s=a;n+=this.renderer.heading(this.parseInline(s.tokens),s.depth,Yx(this.parseInline(s.tokens,this.textRenderer)));continue}case"code":{let s=a;n+=this.renderer.code(s.text,s.lang,!!s.escaped);continue}case"table":{let s=a,i="",d="";for(let u=0;u<s.header.length;u++)d+=this.renderer.tablecell(this.parseInline(s.header[u].tokens),{header:!0,align:s.align[u]});i+=this.renderer.tablerow(d);let l="";for(let u=0;u<s.rows.length;u++){let p=s.rows[u];d="";for(let 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=a,i=this.parse(s.tokens);n+=this.renderer.blockquote(i);continue}case"list":{let s=a,i=s.ordered,d=s.start,l=s.loose,u="";for(let p=0;p<s.items.length;p++){let 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=a;n+=this.renderer.html(s.text,s.block);continue}case"paragraph":{let s=a;n+=this.renderer.paragraph(this.parseInline(s.tokens));continue}case"text":{let s=a,i=s.tokens?this.parseInline(s.tokens):s.text;for(;o+1<r.length&&r[o+1].type==="text";)s=r[++o],i+=`
|
|
46
|
+
`+(s.tokens?this.parseInline(s.tokens):s.text);n+=t?this.renderer.paragraph(i):i;continue}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(r,t){t=t||this.renderer;let n="";for(let o=0;o<r.length;o++){let a=r[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){n+=s||"";continue}}switch(a.type){case"escape":{let s=a;n+=t.text(s.text);break}case"html":{let s=a;n+=t.html(s.text);break}case"link":{let s=a;n+=t.link(s.href,s.title,this.parseInline(s.tokens,t));break}case"image":{let s=a;n+=t.image(s.href,s.title,s.text);break}case"strong":{let s=a;n+=t.strong(this.parseInline(s.tokens,t));break}case"em":{let s=a;n+=t.em(this.parseInline(s.tokens,t));break}case"codespan":{let s=a;n+=t.codespan(s.text);break}case"br":{n+=t.br();break}case"del":{let s=a;n+=t.del(this.parseInline(s.tokens,t));break}case"text":{let s=a;n+=t.text(s.text);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},zo=class{constructor(r){er(this,"options");this.options=r||Go}preprocess(r){return r}postprocess(r){return r}processAllTokens(r){return r}};er(zo,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var jo,Dl,ig,os=class{constructor(...r){Vm(this,jo);er(this,"defaults",Ol());er(this,"options",this.setOptions);er(this,"parse",ai(this,jo,Dl).call(this,to.lex,ro.parse));er(this,"parseInline",ai(this,jo,Dl).call(this,to.lexInline,ro.parseInline));er(this,"Parser",ro);er(this,"Renderer",xa);er(this,"TextRenderer",ns);er(this,"Lexer",to);er(this,"Tokenizer",ha);er(this,"Hooks",zo);this.use(...r)}walkTokens(r,t){var o,a;let n=[];for(let s of r)switch(n=n.concat(t.call(this,s)),s.type){case"table":{let i=s;for(let d of i.header)n=n.concat(this.walkTokens(d.tokens,t));for(let d of i.rows)for(let l of d)n=n.concat(this.walkTokens(l.tokens,t));break}case"list":{let i=s;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=s;(a=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&a[i.type]?this.defaults.extensions.childTokens[i.type].forEach(d=>{let l=i[d].flat(1/0);n=n.concat(this.walkTokens(l,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...r){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return r.forEach(n=>{let o={...n};if(o.async=this.defaults.async||o.async||!1,n.extensions&&(n.extensions.forEach(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let s=t.renderers[a.name];s?t.renderers[a.name]=function(...i){let d=a.renderer.apply(this,i);return d===!1&&(d=s.apply(this,i)),d}:t.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[a.level];s?s.unshift(a.tokenizer):t[a.level]=[a.tokenizer],a.start&&(a.level==="block"?t.startBlock?t.startBlock.push(a.start):t.startBlock=[a.start]:a.level==="inline"&&(t.startInline?t.startInline.push(a.start):t.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(t.childTokens[a.name]=a.childTokens)}),o.extensions=t),n.renderer){let a=this.defaults.renderer||new xa(this.defaults);for(let s in n.renderer){if(!(s in a))throw new Error(`renderer '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.renderer[i],l=a[i];a[i]=(...u)=>{let p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p||""}}o.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new ha(this.defaults);for(let s in n.tokenizer){if(!(s in a))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,d=n.tokenizer[i],l=a[i];a[i]=(...u)=>{let p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p}}o.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new zo;for(let s in n.hooks){if(!(s in a))throw new Error(`hook '${s}' does not exist`);if(s==="options")continue;let i=s,d=n.hooks[i],l=a[i];zo.passThroughHooks.has(s)?a[i]=u=>{if(this.defaults.async)return Promise.resolve(d.call(a,u)).then(m=>l.call(a,m));let p=d.call(a,u);return l.call(a,p)}:a[i]=(...u)=>{let p=d.apply(a,u);return p===!1&&(p=l.apply(a,u)),p}}o.hooks=a}if(n.walkTokens){let a=this.defaults.walkTokens,s=n.walkTokens;o.walkTokens=function(i){let d=[];return d.push(s.call(this,i)),a&&(d=d.concat(a.call(this,i))),d}}this.defaults={...this.defaults,...o}}),this}setOptions(r){return this.defaults={...this.defaults,...r},this}lexer(r,t){return to.lex(r,t!=null?t:this.defaults)}parser(r,t){return ro.parse(r,t!=null?t:this.defaults)}};jo=new WeakSet,Dl=function(r,t){return(n,o)=>{let a={...o},s={...this.defaults,...a};this.defaults.async===!0&&a.async===!1&&(s.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),s.async=!0);let i=ai(this,jo,ig).call(this,!!s.silent,!!s.async);if(typeof n=="undefined"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks&&(s.hooks.options=s),s.async)return Promise.resolve(s.hooks?s.hooks.preprocess(n):n).then(d=>r(d,s)).then(d=>s.hooks?s.hooks.processAllTokens(d):d).then(d=>s.walkTokens?Promise.all(this.walkTokens(d,s.walkTokens)).then(()=>d):d).then(d=>t(d,s)).then(d=>s.hooks?s.hooks.postprocess(d):d).catch(i);try{s.hooks&&(n=s.hooks.preprocess(n));let d=r(n,s);s.hooks&&(d=s.hooks.processAllTokens(d)),s.walkTokens&&this.walkTokens(d,s.walkTokens);let l=t(d,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(d){return i(d)}}},ig=function(r,t){return n=>{if(n.message+=`
|
|
47
|
+
Please report this to https://github.com/markedjs/marked.`,r){let o="<p>An error occurred:</p><pre>"+un(n.message+"",!0)+"</pre>";return t?Promise.resolve(o):o}if(t)return Promise.reject(n);throw n}};var Vo=new os;function Jt(e,r){return Vo.parse(e,r)}Jt.options=Jt.setOptions=function(e){return Vo.setOptions(e),Jt.defaults=Vo.defaults,Ym(Jt.defaults),Jt};Jt.getDefaults=Ol;Jt.defaults=Go;Jt.use=function(...e){return Vo.use(...e),Jt.defaults=Vo.defaults,Ym(Jt.defaults),Jt};Jt.walkTokens=function(e,r){return Vo.walkTokens(e,r)};Jt.parseInline=Vo.parseInline;Jt.Parser=ro;Jt.parser=ro.parse;Jt.Renderer=xa;Jt.TextRenderer=ns;Jt.Lexer=to;Jt.lexer=to.lex;Jt.Tokenizer=ha;Jt.Hooks=zo;Jt.parse=Jt;var nw=Jt.options,ow=Jt.setOptions,aw=Jt.use,sw=Jt.walkTokens,iw=Jt.parseInline;var lw=ro.parse,dw=to.lex;var Ey=e=>{if(e)return e},is=e=>{var o,a;let r=e==null?void 0:e.markedOptions,t=new os({gfm:(o=r==null?void 0:r.gfm)!=null?o:!0,breaks:(a=r==null?void 0:r.breaks)!=null?a:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=Ey(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),s=>t.parse(s)},Xo=e=>e?is({markedOptions:e.options,renderer:e.renderer}):is(),My=is(),ql=e=>My(e),Jo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),dg=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),lg=e=>`%%FORM_PLACEHOLDER_${e}%%`,cg=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,o)=>{try{let a=JSON.parse(o.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=lg(r.length);return r.push({token:s,type:String(a.type)}),s}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,o)=>{let a=lg(r.length);return r.push({token:a,type:o}),a}),t},pg=e=>{let r=Xo(e);return t=>{let n=[],o=cg(t,n),a=r(o);return n.forEach(({token:s,type:i})=>{let d=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${dg(i)}"></div>`;a=a.replace(d,u)}),a}},ug=e=>{let r=[],t=cg(e,r),n=ql(t);return r.forEach(({token:o,type:a})=>{let s=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${dg(a)}"></div>`;n=n.replace(s,d)}),n};var{entries:wg,setPrototypeOf:fg,isFrozen:Ly,getPrototypeOf:Py,getOwnPropertyDescriptor:Iy}=Object,{freeze:Gr,seal:wn,create:ui}=Object,{apply:Kl,construct:Yl}=typeof Reflect!="undefined"&&Reflect;Gr||(Gr=function(r){return r});wn||(wn=function(r){return r});Kl||(Kl=function(r,t){for(var n=arguments.length,o=new Array(n>2?n-2:0),a=2;a<n;a++)o[a-2]=arguments[a];return r.apply(t,o)});Yl||(Yl=function(r){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return new r(...n)});var ci=Xr(Array.prototype.forEach),Ry=Xr(Array.prototype.lastIndexOf),mg=Xr(Array.prototype.pop),ls=Xr(Array.prototype.push),Hy=Xr(Array.prototype.splice),fi=Xr(String.prototype.toLowerCase),zl=Xr(String.prototype.toString),Vl=Xr(String.prototype.match),ds=Xr(String.prototype.replace),By=Xr(String.prototype.indexOf),Wy=Xr(String.prototype.trim),fn=Xr(Object.prototype.hasOwnProperty),jr=Xr(RegExp.prototype.test),cs=Dy(TypeError);function Xr(e){return function(r){r instanceof RegExp&&(r.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return Kl(e,r,n)}}function Dy(e){return function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return Yl(e,t)}}function At(e,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fi;fg&&fg(e,null);let n=r.length;for(;n--;){let o=r[n];if(typeof o=="string"){let a=t(o);a!==o&&(Ly(r)||(r[n]=a),o=a)}e[o]=!0}return e}function Oy(e){for(let r=0;r<e.length;r++)fn(e,r)||(e[r]=null);return e}function Un(e){let r=ui(null);for(let[t,n]of wg(e))fn(e,t)&&(Array.isArray(n)?r[t]=Oy(n):n&&typeof n=="object"&&n.constructor===Object?r[t]=Un(n):r[t]=n);return r}function ps(e,r){for(;e!==null;){let n=Iy(e,r);if(n){if(n.get)return Xr(n.get);if(typeof n.value=="function")return Xr(n.value)}e=Py(e)}function t(){return null}return t}var gg=Gr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),jl=Gr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Gl=Gr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Fy=Gr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Xl=Gr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Ny=Gr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),hg=Gr(["#text"]),xg=Gr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Jl=Gr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),yg=Gr(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),pi=Gr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_y=wn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),$y=wn(/<%[\w\W]*|[\w\W]*%>/gm),Uy=wn(/\$\{[\w\W]*/gm),qy=wn(/^data-[\-\w.\u00B7-\uFFFF]+$/),zy=wn(/^aria-[\-\w]+$/),vg=wn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vy=wn(/^(?:\w+script|data):/i),jy=wn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ag=wn(/^html$/i),Gy=wn(/^[a-z][.\w]*(-[.\w]+)+$/i),bg=Object.freeze({__proto__:null,ARIA_ATTR:zy,ATTR_WHITESPACE:jy,CUSTOM_ELEMENT:Gy,DATA_ATTR:qy,DOCTYPE_NAME:Ag,ERB_EXPR:$y,IS_ALLOWED_URI:vg,IS_SCRIPT_OR_DATA:Vy,MUSTACHE_EXPR:_y,TMPLIT_EXPR:Uy}),us={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Xy=function(){return typeof window=="undefined"?null:window},Jy=function(r,t){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let n=null,o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));let a="dompurify"+(n?"#"+n:"");try{return r.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Cg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Sg(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Xy(),r=Ie=>Sg(Ie);if(r.version="3.3.3",r.removed=[],!e||!e.document||e.document.nodeType!==us.document||!e.Element)return r.isSupported=!1,r;let{document:t}=e,n=t,o=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:i,Element:d,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:m,trustedTypes:f}=e,w=d.prototype,v=ps(w,"cloneNode"),k=ps(w,"remove"),T=ps(w,"nextSibling"),A=ps(w,"childNodes"),E=ps(w,"parentNode");if(typeof s=="function"){let Ie=t.createElement("template");Ie.content&&Ie.content.ownerDocument&&(t=Ie.content.ownerDocument)}let b,h="",{implementation:S,createNodeIterator:L,createDocumentFragment:O,getElementsByTagName:H}=t,{importNode:R}=n,B=Cg();r.isSupported=typeof wg=="function"&&typeof E=="function"&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:j,ERB_EXPR:oe,TMPLIT_EXPR:ue,DATA_ATTR:De,ARIA_ATTR:Xe,IS_SCRIPT_OR_DATA:xe,ATTR_WHITESPACE:ge,CUSTOM_ELEMENT:Le}=bg,{IS_ALLOWED_URI:Ge}=bg,Q=null,Se=At({},[...gg,...jl,...Gl,...Xl,...hg]),J=null,ce=At({},[...xg,...Jl,...yg,...pi]),pe=Object.seal(ui(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ie=null,Oe=null,Pe=Object.seal(ui(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),K=!0,_e=!0,$e=!1,Y=!0,G=!1,we=!0,ke=!1,ae=!1,ve=!1,ye=!1,Mt=!1,ne=!1,He=!0,fr=!1,Ot="user-content-",Yt=!0,Fr=!1,Ar={},F=null,le=At({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Fe=null,Ke=At({},["audio","video","img","source","image","track"]),Ue=null,qe=At({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),nt="http://www.w3.org/1998/Math/MathML",Ct="http://www.w3.org/2000/svg",Pt="http://www.w3.org/1999/xhtml",$t=Pt,N=!1,de=null,Ee=At({},[nt,Ct,Pt],zl),ut=At({},["mi","mo","mn","ms","mtext"]),Ye=At({},["annotation-xml"]),Ut=At({},["title","style","font","a","script"]),or=null,It=["application/xhtml+xml","text/html"],St="text/html",rt=null,it=null,tr=t.createElement("form"),gn=function(M){return M instanceof RegExp||M instanceof Function},Rr=function(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(it&&it===M)){if((!M||typeof M!="object")&&(M={}),M=Un(M),or=It.indexOf(M.PARSER_MEDIA_TYPE)===-1?St:M.PARSER_MEDIA_TYPE,rt=or==="application/xhtml+xml"?zl:fi,Q=fn(M,"ALLOWED_TAGS")?At({},M.ALLOWED_TAGS,rt):Se,J=fn(M,"ALLOWED_ATTR")?At({},M.ALLOWED_ATTR,rt):ce,de=fn(M,"ALLOWED_NAMESPACES")?At({},M.ALLOWED_NAMESPACES,zl):Ee,Ue=fn(M,"ADD_URI_SAFE_ATTR")?At(Un(qe),M.ADD_URI_SAFE_ATTR,rt):qe,Fe=fn(M,"ADD_DATA_URI_TAGS")?At(Un(Ke),M.ADD_DATA_URI_TAGS,rt):Ke,F=fn(M,"FORBID_CONTENTS")?At({},M.FORBID_CONTENTS,rt):le,ie=fn(M,"FORBID_TAGS")?At({},M.FORBID_TAGS,rt):Un({}),Oe=fn(M,"FORBID_ATTR")?At({},M.FORBID_ATTR,rt):Un({}),Ar=fn(M,"USE_PROFILES")?M.USE_PROFILES:!1,K=M.ALLOW_ARIA_ATTR!==!1,_e=M.ALLOW_DATA_ATTR!==!1,$e=M.ALLOW_UNKNOWN_PROTOCOLS||!1,Y=M.ALLOW_SELF_CLOSE_IN_ATTR!==!1,G=M.SAFE_FOR_TEMPLATES||!1,we=M.SAFE_FOR_XML!==!1,ke=M.WHOLE_DOCUMENT||!1,ye=M.RETURN_DOM||!1,Mt=M.RETURN_DOM_FRAGMENT||!1,ne=M.RETURN_TRUSTED_TYPE||!1,ve=M.FORCE_BODY||!1,He=M.SANITIZE_DOM!==!1,fr=M.SANITIZE_NAMED_PROPS||!1,Yt=M.KEEP_CONTENT!==!1,Fr=M.IN_PLACE||!1,Ge=M.ALLOWED_URI_REGEXP||vg,$t=M.NAMESPACE||Pt,ut=M.MATHML_TEXT_INTEGRATION_POINTS||ut,Ye=M.HTML_INTEGRATION_POINTS||Ye,pe=M.CUSTOM_ELEMENT_HANDLING||{},M.CUSTOM_ELEMENT_HANDLING&&gn(M.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(pe.tagNameCheck=M.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M.CUSTOM_ELEMENT_HANDLING&&gn(M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(pe.attributeNameCheck=M.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M.CUSTOM_ELEMENT_HANDLING&&typeof M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(pe.allowCustomizedBuiltInElements=M.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(_e=!1),Mt&&(ye=!0),Ar&&(Q=At({},hg),J=ui(null),Ar.html===!0&&(At(Q,gg),At(J,xg)),Ar.svg===!0&&(At(Q,jl),At(J,Jl),At(J,pi)),Ar.svgFilters===!0&&(At(Q,Gl),At(J,Jl),At(J,pi)),Ar.mathMl===!0&&(At(Q,Xl),At(J,yg),At(J,pi))),fn(M,"ADD_TAGS")||(Pe.tagCheck=null),fn(M,"ADD_ATTR")||(Pe.attributeCheck=null),M.ADD_TAGS&&(typeof M.ADD_TAGS=="function"?Pe.tagCheck=M.ADD_TAGS:(Q===Se&&(Q=Un(Q)),At(Q,M.ADD_TAGS,rt))),M.ADD_ATTR&&(typeof M.ADD_ATTR=="function"?Pe.attributeCheck=M.ADD_ATTR:(J===ce&&(J=Un(J)),At(J,M.ADD_ATTR,rt))),M.ADD_URI_SAFE_ATTR&&At(Ue,M.ADD_URI_SAFE_ATTR,rt),M.FORBID_CONTENTS&&(F===le&&(F=Un(F)),At(F,M.FORBID_CONTENTS,rt)),M.ADD_FORBID_CONTENTS&&(F===le&&(F=Un(F)),At(F,M.ADD_FORBID_CONTENTS,rt)),Yt&&(Q["#text"]=!0),ke&&At(Q,["html","head","body"]),Q.table&&(At(Q,["tbody"]),delete ie.tbody),M.TRUSTED_TYPES_POLICY){if(typeof M.TRUSTED_TYPES_POLICY.createHTML!="function")throw cs('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw cs('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=M.TRUSTED_TYPES_POLICY,h=b.createHTML("")}else b===void 0&&(b=Jy(f,o)),b!==null&&typeof h=="string"&&(h=b.createHTML(""));Gr&&Gr(M),it=M}},Tn=At({},[...jl,...Gl,...Fy]),Tt=At({},[...Xl,...Ny]),hn=function(M){let Z=E(M);(!Z||!Z.tagName)&&(Z={namespaceURI:$t,tagName:"template"});let se=fi(M.tagName),kt=fi(Z.tagName);return de[M.namespaceURI]?M.namespaceURI===Ct?Z.namespaceURI===Pt?se==="svg":Z.namespaceURI===nt?se==="svg"&&(kt==="annotation-xml"||ut[kt]):!!Tn[se]:M.namespaceURI===nt?Z.namespaceURI===Pt?se==="math":Z.namespaceURI===Ct?se==="math"&&Ye[kt]:!!Tt[se]:M.namespaceURI===Pt?Z.namespaceURI===Ct&&!Ye[kt]||Z.namespaceURI===nt&&!ut[kt]?!1:!Tt[se]&&(Ut[se]||!Tn[se]):!!(or==="application/xhtml+xml"&&de[M.namespaceURI]):!1},ur=function(M){ls(r.removed,{element:M});try{E(M).removeChild(M)}catch{k(M)}},Sr=function(M,Z){try{ls(r.removed,{attribute:Z.getAttributeNode(M),from:Z})}catch{ls(r.removed,{attribute:null,from:Z})}if(Z.removeAttribute(M),M==="is")if(ye||Mt)try{ur(Z)}catch{}else try{Z.setAttribute(M,"")}catch{}},Yr=function(M){let Z=null,se=null;if(ve)M="<remove></remove>"+M;else{let Bt=Vl(M,/^[\r\n\t ]+/);se=Bt&&Bt[0]}or==="application/xhtml+xml"&&$t===Pt&&(M='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+M+"</body></html>");let kt=b?b.createHTML(M):M;if($t===Pt)try{Z=new m().parseFromString(kt,or)}catch{}if(!Z||!Z.documentElement){Z=S.createDocument($t,"template",null);try{Z.documentElement.innerHTML=N?h:kt}catch{}}let qt=Z.body||Z.documentElement;return M&&se&&qt.insertBefore(t.createTextNode(se),qt.childNodes[0]||null),$t===Pt?H.call(Z,ke?"html":"body")[0]:ke?Z.documentElement:qt},xt=function(M){return L.call(M.ownerDocument||M,M,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},kn=function(M){return M instanceof p&&(typeof M.nodeName!="string"||typeof M.textContent!="string"||typeof M.removeChild!="function"||!(M.attributes instanceof u)||typeof M.removeAttribute!="function"||typeof M.setAttribute!="function"||typeof M.namespaceURI!="string"||typeof M.insertBefore!="function"||typeof M.hasChildNodes!="function")},nn=function(M){return typeof i=="function"&&M instanceof i};function Tr(Ie,M,Z){ci(Ie,se=>{se.call(r,M,Z,it)})}let kr=function(M){let Z=null;if(Tr(B.beforeSanitizeElements,M,null),kn(M))return ur(M),!0;let se=rt(M.nodeName);if(Tr(B.uponSanitizeElement,M,{tagName:se,allowedTags:Q}),we&&M.hasChildNodes()&&!nn(M.firstElementChild)&&jr(/<[/\w!]/g,M.innerHTML)&&jr(/<[/\w!]/g,M.textContent)||M.nodeType===us.progressingInstruction||we&&M.nodeType===us.comment&&jr(/<[/\w]/g,M.data))return ur(M),!0;if(!(Pe.tagCheck instanceof Function&&Pe.tagCheck(se))&&(!Q[se]||ie[se])){if(!ie[se]&&En(se)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,se)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(se)))return!1;if(Yt&&!F[se]){let kt=E(M)||M.parentNode,qt=A(M)||M.childNodes;if(qt&&kt){let Bt=qt.length;for(let ar=Bt-1;ar>=0;--ar){let xr=v(qt[ar],!0);xr.__removalCount=(M.__removalCount||0)+1,kt.insertBefore(xr,T(M))}}}return ur(M),!0}return M instanceof d&&!hn(M)||(se==="noscript"||se==="noembed"||se==="noframes")&&jr(/<\/no(script|embed|frames)/i,M.innerHTML)?(ur(M),!0):(G&&M.nodeType===us.text&&(Z=M.textContent,ci([j,oe,ue],kt=>{Z=ds(Z,kt," ")}),M.textContent!==Z&&(ls(r.removed,{element:M.cloneNode()}),M.textContent=Z)),Tr(B.afterSanitizeElements,M,null),!1)},Vn=function(M,Z,se){if(Oe[Z]||He&&(Z==="id"||Z==="name")&&(se in t||se in tr))return!1;if(!(_e&&!Oe[Z]&&jr(De,Z))){if(!(K&&jr(Xe,Z))){if(!(Pe.attributeCheck instanceof Function&&Pe.attributeCheck(Z,M))){if(!J[Z]||Oe[Z]){if(!(En(M)&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,M)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(M))&&(pe.attributeNameCheck instanceof RegExp&&jr(pe.attributeNameCheck,Z)||pe.attributeNameCheck instanceof Function&&pe.attributeNameCheck(Z,M))||Z==="is"&&pe.allowCustomizedBuiltInElements&&(pe.tagNameCheck instanceof RegExp&&jr(pe.tagNameCheck,se)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(se))))return!1}else if(!Ue[Z]){if(!jr(Ge,ds(se,ge,""))){if(!((Z==="src"||Z==="xlink:href"||Z==="href")&&M!=="script"&&By(se,"data:")===0&&Fe[M])){if(!($e&&!jr(xe,ds(se,ge,"")))){if(se)return!1}}}}}}}return!0},En=function(M){return M!=="annotation-xml"&&Vl(M,Le)},xn=function(M){Tr(B.beforeSanitizeAttributes,M,null);let{attributes:Z}=M;if(!Z||kn(M))return;let se={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J,forceKeepAttr:void 0},kt=Z.length;for(;kt--;){let qt=Z[kt],{name:Bt,namespaceURI:ar,value:xr}=qt,Nr=rt(Bt),Er=xr,ot=Bt==="value"?Er:Wy(Er);if(se.attrName=Nr,se.attrValue=ot,se.keepAttr=!0,se.forceKeepAttr=void 0,Tr(B.uponSanitizeAttribute,M,se),ot=se.attrValue,fr&&(Nr==="id"||Nr==="name")&&(Sr(Bt,M),ot=Ot+ot),we&&jr(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,ot)){Sr(Bt,M);continue}if(Nr==="attributename"&&Vl(ot,"href")){Sr(Bt,M);continue}if(se.forceKeepAttr)continue;if(!se.keepAttr){Sr(Bt,M);continue}if(!Y&&jr(/\/>/i,ot)){Sr(Bt,M);continue}G&&ci([j,oe,ue],_r=>{ot=ds(ot,_r," ")});let wr=rt(M.nodeName);if(!Vn(wr,Nr,ot)){Sr(Bt,M);continue}if(b&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!ar)switch(f.getAttributeType(wr,Nr)){case"TrustedHTML":{ot=b.createHTML(ot);break}case"TrustedScriptURL":{ot=b.createScriptURL(ot);break}}if(ot!==Er)try{ar?M.setAttributeNS(ar,Bt,ot):M.setAttribute(Bt,ot),kn(M)?ur(M):mg(r.removed)}catch{Sr(Bt,M)}}Tr(B.afterSanitizeAttributes,M,null)},wt=function Ie(M){let Z=null,se=xt(M);for(Tr(B.beforeSanitizeShadowDOM,M,null);Z=se.nextNode();)Tr(B.uponSanitizeShadowNode,Z,null),kr(Z),xn(Z),Z.content instanceof a&&Ie(Z.content);Tr(B.afterSanitizeShadowDOM,M,null)};return r.sanitize=function(Ie){let M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Z=null,se=null,kt=null,qt=null;if(N=!Ie,N&&(Ie="<!-->"),typeof Ie!="string"&&!nn(Ie))if(typeof Ie.toString=="function"){if(Ie=Ie.toString(),typeof Ie!="string")throw cs("dirty is not a string, aborting")}else throw cs("toString is not a function");if(!r.isSupported)return Ie;if(ae||Rr(M),r.removed=[],typeof Ie=="string"&&(Fr=!1),Fr){if(Ie.nodeName){let xr=rt(Ie.nodeName);if(!Q[xr]||ie[xr])throw cs("root node is forbidden and cannot be sanitized in-place")}}else if(Ie instanceof i)Z=Yr("<!---->"),se=Z.ownerDocument.importNode(Ie,!0),se.nodeType===us.element&&se.nodeName==="BODY"||se.nodeName==="HTML"?Z=se:Z.appendChild(se);else{if(!ye&&!G&&!ke&&Ie.indexOf("<")===-1)return b&&ne?b.createHTML(Ie):Ie;if(Z=Yr(Ie),!Z)return ye?null:ne?h:""}Z&&ve&&ur(Z.firstChild);let Bt=xt(Fr?Ie:Z);for(;kt=Bt.nextNode();)kr(kt),xn(kt),kt.content instanceof a&&wt(kt.content);if(Fr)return Ie;if(ye){if(Mt)for(qt=O.call(Z.ownerDocument);Z.firstChild;)qt.appendChild(Z.firstChild);else qt=Z;return(J.shadowroot||J.shadowrootmode)&&(qt=R.call(n,qt,!0)),qt}let ar=ke?Z.outerHTML:Z.innerHTML;return ke&&Q["!doctype"]&&Z.ownerDocument&&Z.ownerDocument.doctype&&Z.ownerDocument.doctype.name&&jr(Ag,Z.ownerDocument.doctype.name)&&(ar="<!DOCTYPE "+Z.ownerDocument.doctype.name+`>
|
|
48
|
+
`+ar),G&&ci([j,oe,ue],xr=>{ar=ds(ar,xr," ")}),b&&ne?b.createHTML(ar):ar},r.setConfig=function(){let Ie=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rr(Ie),ae=!0},r.clearConfig=function(){it=null,ae=!1},r.isValidAttribute=function(Ie,M,Z){it||Rr({});let se=rt(Ie),kt=rt(M);return Vn(se,kt,Z)},r.addHook=function(Ie,M){typeof M=="function"&&ls(B[Ie],M)},r.removeHook=function(Ie,M){if(M!==void 0){let Z=Ry(B[Ie],M);return Z===-1?void 0:Hy(B[Ie],Z,1)[0]}return mg(B[Ie])},r.removeHooks=function(Ie){B[Ie]=[]},r.removeAllHooks=function(){B=Cg()},r}var Tg=Sg();var Ky={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Yy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ql=()=>{let e=Tg(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!Yy.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Ky)},ya=e=>e===!1?null:typeof e=="function"?e:Ql();var no=Bl(hi(),1),xi=e=>e.replace(/\\n/g,`
|
|
49
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ba=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},rb=e=>{var s,i;let r=(s=e.completedAt)!=null?s:Date.now(),t=(i=e.startedAt)!=null?i:r,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Eg=e=>e.status==="complete"?rb(e):e.status==="pending"?"Waiting":"",nb=e=>{var o,a,s;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Mg=e=>e.status==="complete"?nb(e):"Using tool...",yi=e=>{let r=e/1e3;return r<.1?"<0.1s":r>=10?`${Math.round(r)}s`:`${r.toFixed(1).replace(/\.0$/,"")}s`},ms=e=>{var t,n,o;let r=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(n=e.startedAt)!=null?n:e.completedAt)!=null?o:Date.now()));return yi(r)},bi=e=>{var t,n,o;let r=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(n=e.startedAt)!=null?n:e.completedAt)!=null?o:Date.now()));return yi(r)},ed=(e,r,t)=>{var a;if(!r)return t;let n=((a=e.name)==null?void 0:a.trim())||"tool",o=ms(e);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Ci=(e,r)=>{let t=e.replace(/\{toolName\}/g,r),n=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=o.exec(t))!==null;)s.index>a&&fs(n,t.slice(a,s.index),[]),s[1]!==void 0?fs(n,s[1],["bold"]):s[2]!==void 0?fs(n,s[2],["italic"]):s[3]!==void 0&&fs(n,s[3],["dim"]),a=s.index+s[0].length;return a<t.length&&fs(n,t.slice(a),[]),n},fs=(e,r,t)=>{let n=r.split("{duration}");for(let o=0;o<n.length;o++)n[o]&&e.push({text:n[o],styles:t}),o<n.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},ob=()=>{let e=null,r=0,t=n=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(o);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
50
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
51
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let a=t(n);return a!==null&&(e=a),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Ko=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},wi=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},vi=()=>{var r;let e=ob();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},Ai=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let o=(0,no.parse)(t,no.STR|no.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?xi(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=xi(o.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Lg=e=>{let r=null,t=0,o=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?xi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?xi(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>r,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return r!==null?{text:r,raw:a}:null;try{let i=(0,no.parse)(a,no.STR|no.OBJ),d=o(i);d!==null&&(r=d)}catch{}return t=a.length,{text:r||"",raw:a}},close:()=>{}}},Si=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var Ti=class{constructor(r,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=r,this.gapTimeoutMs=t}push(r,t){var a,s,i;let n=(i=(a=t==null?void 0:t.seq)!=null?a:t==null?void 0:t.sequenceIndex)!=null?i:(s=t==null?void 0:t.agentContext)==null?void 0:s.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(r,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(r,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(r,t);return}let o=this.buffer.get(n);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${o.payloadType} vs ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(n,{payloadType:r,payload:t,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let r=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(r.payloadType,r.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let r=[...this.buffer.entries()].sort((t,n)=>t[0]-n[0]);for(let[t,n]of r)this.buffer.delete(t),this.emitter(n.payloadType,n.payload);r.length>0&&(this.nextExpectedSeq=r[r.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var ab="https://api.runtype.com/v1/dispatch",ki="https://api.runtype.com";function sb(e){var a,s;let r=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[r];if(n)return`attachment.${n}`;let o=r.indexOf("/");if(o>0){let i=(s=(a=r.slice(o+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var td=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ib(e){switch(e){case"json":return Ai;case"regex-json":return vi;case"xml":return Si;default:return wi}}var Pg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lb(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let o=Pg(t);if(!Pg(n))return e;if(!o||n===t||n.startsWith(t))return r;let s=Ko(e);return Ko(r)!==null&&s===null?r:e}var Yo=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,o;this.apiUrl=(t=r.apiUrl)!=null?t:ab,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:ib(r.parserType),this.contextProviders=(o=r.contextProviders)!=null?o:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let r=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/client/feedback`}async sendFeedback(r){var a,s;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(s=(a=this.config).onSessionExpired)==null||s.call(a),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var o,a,s,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o);let f=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:f}),f}let l=await this.buildPayload(r.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([f])=>f!=="sessionId"&&f!=="session_id")):void 0,p={sessionId:d.sessionId,messages:r.messages.filter(td).map(f=>{var w,v,k;return{id:f.id,role:f.role,content:(k=(v=(w=f.contentParts)!=null?w:f.llmContent)!=null?v:f.rawContent)!=null?k:f.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!m.ok){let f=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(m.status===429){let v=new Error(f.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let w=new Error(f.error||"Failed to send message");throw t({type:"error",error:w}),w}if(!m.body){let f=new Error("No response body received");throw t({type:"error",error:f}),f}t({type:"status",status:"connected"});try{await this.streamResponse(m.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(o),signal:n.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var s;let o=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ki}/v1/agents/${r.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(o,{method:"POST",headers:a,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(r,t,n){var i,d;let a=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||ki}/resume`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(a,{method:"POST",headers:s,body:JSON.stringify({executionId:r,toolOutputs:t,streamResponse:(d=n==null?void 0:n.streamResponse)!=null?d:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(td).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,a)=>{let s=new Date(o.createdAt).getTime(),i=new Date(a.createdAt).getTime();return s-i}).map(o=>{var a,s,i;return{role:o.role,content:(i=(s=(a=o.contentParts)!=null?a:o.llmContent)!=null?s:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async a=>{try{let s=await a({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(o,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(o).length&&(n.context=o)}return n}async buildPayload(r){let n={messages:r.slice().filter(td).sort((o,a)=>{let s=new Date(o.createdAt).getTime(),i=new Date(a.createdAt).getTime();return s-i}).map(o=>{var a,s,i;return{role:o.role,content:(i=(s=(a=o.contentParts)!=null?a:o.llmContent)!=null?s:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async a=>{try{let s=await a({messages:r,config:this.config});s&&typeof s=="object"&&Object.assign(o,s)}catch(s){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",s)}})),Object.keys(o).length&&(n.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...n},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return n}async handleCustomSSEEvent(r,t,n,o,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return n.current=p,o(p),p},l=u=>n.current?n.current:d(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(n.current&&(n.current.streaming=!1,o(n.current)),d(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(n.current&&(n.current.streaming=!1,o(n.current)),s.current=null,t({type:"status",status:"idle"})),i.error&&(s.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var Ot,Yt,Fr,Ar;let o=r.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=F=>{let le=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,Fe=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ke=F.tools?F.tools.map(Ue=>({...Ue,chunks:Ue.chunks?[...Ue.chunks]:void 0})):void 0;return{...F,reasoning:le,toolCall:Fe,tools:Ke}},p=F=>{t({type:"message",message:u(F)})},m=null,f={current:null},w={current:null},v=!1,k=new Map,T=new Map,A=new Map,E=new Map,b={lastId:null,byStep:new Map},h={lastId:null,byCall:new Map},S=(F,le,Fe="")=>`${F}::${le}::${Fe}`,L=(F,le)=>`${F}::${le}::`,O=(F,le,Fe,Ke)=>{let Ue=S(F,le,Fe),qe=A.get(Ue);if(qe)return qe;let nt=Fe?`-${Fe}`:"",Ct={id:`nested-${F}-${le}${nt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Fe?{partId:Fe}:{},agentMetadata:{executionId:Ke,parentToolId:F,parentStepId:le}};return A.set(Ue,Ct),p(Ct),Ct},H=F=>{if(F==null)return null;try{return String(F)}catch{return null}},R=F=>{var le,Fe,Ke,Ue,qe;return H((qe=(Ue=(Ke=(Fe=(le=F.stepId)!=null?le:F.step_id)!=null?Fe:F.step)!=null?Ke:F.parentId)!=null?Ue:F.flowStepId)!=null?qe:F.flow_step_id)},B=F=>{var le,Fe,Ke,Ue,qe,nt,Ct;return H((Ct=(nt=(qe=(Ue=(Ke=(Fe=(le=F.callId)!=null?le:F.call_id)!=null?Fe:F.requestId)!=null?Ke:F.request_id)!=null?Ue:F.toolCallId)!=null?qe:F.tool_call_id)!=null?nt:F.stepId)!=null?Ct:F.step_id)},j=n,oe=!1,ue=()=>{if(m)return m;let F;return!oe&&j?(F=j,oe=!0):j&&w.current?F=`${j}_${w.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(m),m},De=(F,le)=>{b.lastId=le,F&&b.byStep.set(F,le)},Xe=(F,le)=>{var qe;let Fe=(qe=F.reasoningId)!=null?qe:F.id,Ke=R(F);if(Fe){let nt=String(Fe);return De(Ke,nt),nt}if(Ke){let nt=b.byStep.get(Ke);if(nt)return b.lastId=nt,nt}if(b.lastId&&!le)return b.lastId;if(!le)return null;let Ue=`reason-${l()}`;return De(Ke,Ue),Ue},xe=F=>{let le=k.get(F);if(le)return le;let Fe={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return k.set(F,Fe),p(Fe),Fe},ge=(F,le)=>{h.lastId=le,F&&h.byCall.set(F,le)},Le=new Set,Ge=new Map,Q=new Set,Se=new Map,J=F=>{if(!F)return!1;let le=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return le==="emit_artifact_markdown"||le==="emit_artifact_component"},ce=(F,le)=>{var qe;let Fe=(qe=F.toolId)!=null?qe:F.id,Ke=B(F);if(Fe){let nt=String(Fe);return ge(Ke,nt),nt}if(Ke){let nt=h.byCall.get(Ke);if(nt)return h.lastId=nt,nt}if(h.lastId&&!le)return h.lastId;if(!le)return null;let Ue=`tool-${l()}`;return ge(Ke,Ue),Ue},pe=F=>{let le=T.get(F);if(le)return le;let Fe={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return T.set(F,Fe),p(Fe),Fe},ie=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let le=Number(F);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let Fe=Date.parse(F);if(!Number.isNaN(Fe))return Fe}return Date.now()},Oe=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Pe=new Map,K=new Map,_e=new Map,$e=new Map,Y=null,G=(F,le,Fe)=>{var Ct;let Ke=_e.get(F);Ke||(Ke=[],_e.set(F,Ke));let Ue=0,qe=Ke.length;for(;Ue<qe;){let Pt=Ue+qe>>>1;Ke[Pt].seq<le?Ue=Pt+1:qe=Pt}((Ct=Ke[Ue])==null?void 0:Ct.seq)===le?Ke[Ue]={seq:le,text:Fe}:Ke.splice(Ue,0,{seq:le,text:Fe});let nt="";for(let Pt=0;Pt<Ke.length;Pt++)nt+=Ke[Pt].text;return nt},we=(F,le)=>{let Fe=Oe(le),Ke=K.get(F.id),Ue=lb(Ke,Fe);F.rawContent=Ue;let qe=Pe.get(F.id),nt=de=>{var ut;let Ee=(ut=F.content)!=null?ut:"";de.trim()!==""&&(Ee.trim().length===0||de.startsWith(Ee)||de.trimStart().startsWith(Ee.trim()))&&(F.content=de)},Ct=()=>{var de;if(qe){let Ee=(de=qe.close)==null?void 0:de.call(qe);Ee instanceof Promise&&Ee.catch(()=>{})}Pe.delete(F.id),K.delete(F.id),F.streaming=!1,p(F)};if(!qe){nt(Fe),Ct();return}let Pt=Ko(Ue);if(Pt!==null&&Pt.trim()!==""){nt(Pt),Ct();return}let $t=de=>{var Ye;let Ee=typeof de=="string"?de:(Ye=de==null?void 0:de.text)!=null?Ye:null;if(Ee!==null&&Ee.trim()!=="")return Ee;let ut=qe.getExtractedText();return ut!==null&&ut.trim()!==""?ut:Fe},N;try{N=qe.processChunk(Ue)}catch{nt(Fe),Ct();return}if(N instanceof Promise){N.then(de=>{nt($t(de)),Ct()}).catch(()=>{nt(Fe),Ct()});return}nt($t(N)),Ct()},ke=[],ae=!1,ve,ye=()=>{ae||(ae=!0,queueMicrotask(()=>{ae=!1,ve()}))},Mt=new Ti((F,le)=>{ke.push({payloadType:F,payload:le}),ye()}),ne=null,He=new Map,fr=(Ot=this.config.iterationDisplay)!=null?Ot:"separate";for(ve=()=>{var F,le,Fe,Ke,Ue,qe,nt,Ct,Pt,$t,N,de,Ee,ut,Ye,Ut,or,It,St,rt,it,tr,gn,Rr,Tn,Tt,hn,ur,Sr,Yr,xt,kn,nn,Tr,kr,Vn,En,xn,wt,Ie,M,Z,se,kt,qt,Bt,ar,xr,Nr,Er,ot,wr,_r,po,jn,uo,Fn,on,Mn,vt,sr,ir,an,fo,yn,Ln,sn,q,he,ln,Pn,Nn,Oa,In,Rn,Hn,Gn,Ro,Ns,Fa,_s,la,bt,Na,bn,Qr,$s,Us,da,Xn,qs,Ho,_a,Jn,$a,mo,go,zs,Vs,Hl,Bo,ho,js,Ua,xo,Gs,qa,yo,za,Xs,Kn,Js,bo,Nt,ca,pa,Va,_n,Ks,ja,Ga,Xa,Ja,$r,dn,Yn,dt,Ka,Wo,Bn,Ys,ua,fa,Do,Co,Qs,Zs,Wn;for(let Qn=0;Qn<ke.length;Qn++){let Ze=ke[Qn].payloadType,P=ke[Qn].payload;if(Ze==="reason_start"){let z=(F=Xe(P,!0))!=null?F:`reason-${l()}`,I=xe(z);I.reasoning=(le=I.reasoning)!=null?le:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Ke=I.reasoning.startedAt)!=null?Ke:ie((Fe=P.startedAt)!=null?Fe:P.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ze==="reason_delta"||Ze==="reason_chunk"){let z=(qe=(Ue=Xe(P,!1))!=null?Ue:Xe(P,!0))!=null?qe:`reason-${l()}`,I=xe(z);I.reasoning=(nt=I.reasoning)!=null?nt:{id:z,status:"streaming",chunks:[]},I.reasoning.startedAt=(Pt=I.reasoning.startedAt)!=null?Pt:ie((Ct=P.startedAt)!=null?Ct:P.timestamp);let V=(de=(N=($t=P.reasoningText)!=null?$t:P.text)!=null?N:P.delta)!=null?de:"";if(V&&P.hidden!==!0){let fe=typeof P.sequenceIndex=="number"?P.sequenceIndex:void 0;if(fe!==void 0){let te=G(z,fe,String(V));I.reasoning.chunks=[te]}else I.reasoning.chunks.push(String(V))}if(I.reasoning.status=P.done?"complete":"streaming",P.done){I.reasoning.completedAt=ie((Ee=P.completedAt)!=null?Ee:P.timestamp);let fe=(ut=I.reasoning.startedAt)!=null?ut:Date.now();I.reasoning.durationMs=Math.max(0,((Ye=I.reasoning.completedAt)!=null?Ye:Date.now())-fe)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ze==="reason_complete"){let z=(or=(Ut=Xe(P,!1))!=null?Ut:Xe(P,!0))!=null?or:`reason-${l()}`,I=k.get(z);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=ie((It=P.completedAt)!=null?It:P.timestamp);let fe=(St=I.reasoning.startedAt)!=null?St:Date.now();I.reasoning.durationMs=Math.max(0,((rt=I.reasoning.completedAt)!=null?rt:Date.now())-fe),I.streaming=!1,p(I)}let V=R(P);V&&b.byStep.delete(V)}else if(Ze==="tool_start"){let z=(it=ce(P,!0))!=null?it:`tool-${l()}`,I=(tr=P.toolName)!=null?tr:P.name;if(J(I)){Le.add(z);continue}let V=pe(z),fe=(gn=V.toolCall)!=null?gn:{id:z,status:"pending"};fe.name=I!=null?I:fe.name,fe.status="running",P.args!==void 0?fe.args=P.args:P.parameters!==void 0&&(fe.args=P.parameters),fe.startedAt=(Tn=fe.startedAt)!=null?Tn:ie((Rr=P.startedAt)!=null?Rr:P.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,V.toolCall=fe,V.streaming=!0;let te=P.agentContext;(te||P.executionId)&&(V.agentMetadata={executionId:(Tt=te==null?void 0:te.executionId)!=null?Tt:P.executionId,iteration:(hn=te==null?void 0:te.iteration)!=null?hn:P.iteration}),p(V)}else if(Ze==="tool_chunk"||Ze==="tool_delta"){let z=(Sr=(ur=ce(P,!1))!=null?ur:ce(P,!0))!=null?Sr:`tool-${l()}`;if(Le.has(z))continue;let I=pe(z),V=(Yr=I.toolCall)!=null?Yr:{id:z,status:"running"};V.startedAt=(kn=V.startedAt)!=null?kn:ie((xt=P.startedAt)!=null?xt:P.timestamp);let fe=(kr=(Tr=(nn=P.text)!=null?nn:P.delta)!=null?Tr:P.message)!=null?kr:"";fe&&(V.chunks=(Vn=V.chunks)!=null?Vn:[],V.chunks.push(String(fe))),V.status="running",I.toolCall=V,I.streaming=!0;let te=P.agentContext;(te||P.executionId)&&(I.agentMetadata=(wt=I.agentMetadata)!=null?wt:{executionId:(En=te==null?void 0:te.executionId)!=null?En:P.executionId,iteration:(xn=te==null?void 0:te.iteration)!=null?xn:P.iteration}),p(I)}else if(Ze==="tool_complete"){let z=(M=(Ie=ce(P,!1))!=null?Ie:ce(P,!0))!=null?M:`tool-${l()}`;if(Le.has(z)){Le.delete(z);continue}let I=pe(z),V=(Z=I.toolCall)!=null?Z:{id:z,status:"running"};V.status="complete",P.result!==void 0&&(V.result=P.result),typeof P.duration=="number"&&(V.duration=P.duration),V.completedAt=ie((se=P.completedAt)!=null?se:P.timestamp);let fe=(kt=P.duration)!=null?kt:P.executionTime;if(typeof fe=="number")V.durationMs=fe;else{let ze=(qt=V.startedAt)!=null?qt:Date.now();V.durationMs=Math.max(0,((Bt=V.completedAt)!=null?Bt:Date.now())-ze)}I.toolCall=V,I.streaming=!1;let te=P.agentContext;(te||P.executionId)&&(I.agentMetadata=(Nr=I.agentMetadata)!=null?Nr:{executionId:(ar=te==null?void 0:te.executionId)!=null?ar:P.executionId,iteration:(xr=te==null?void 0:te.iteration)!=null?xr:P.iteration}),p(I);let et=B(P);et&&h.byCall.delete(et)}else if(Ze==="step_await"&&P.awaitReason==="local_tool_required"&&P.toolName){let z=(Er=P.toolId)!=null?Er:`local-${l()}`,I=pe(z),V=(ot=I.toolCall)!=null?ot:{id:z,status:"pending"};V.name=P.toolName,V.args=P.parameters,V.status="complete",V.chunks=(wr=V.chunks)!=null?wr:[],V.startedAt=(po=V.startedAt)!=null?po:ie((_r=P.startedAt)!=null?_r:P.timestamp),V.completedAt=(jn=V.completedAt)!=null?jn:V.startedAt,I.toolCall=V,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:(Fn=P.executionId)!=null?Fn:(uo=I.agentMetadata)==null?void 0:uo.executionId,awaitingLocalTool:!0},p(I)}else if(Ze==="text_start"){if((on=P.toolContext)!=null&&on.toolId)continue;let z=P.partId;if(z!==void 0&&w.current!==null&&z!==w.current){let I=m;I&&(I.streaming=!1,p(I),Y=I,m=null,v=!0)}z!==void 0&&(w.current=z)}else if(Ze==="text_end"){if((Mn=P.toolContext)!=null&&Mn.toolId)continue;let z=m;z&&(z.streaming=!1,p(z),Y=z,m=null,v=!0)}else if(Ze==="step_chunk"||Ze==="step_delta"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let V=P.toolContext;if(V!=null&&V.toolId){let ze=String((sr=(vt=P.id)!=null?vt:V.stepId)!=null?sr:`step-${l()}`),ct=P.partId!==void 0&&P.partId!==null?String(P.partId):"",at=`${V.toolId}::${ze}`,_t=E.get(at);if(ct!==""&&_t!==void 0&&_t!==""&&_t!==ct){let Rt=A.get(S(V.toolId,ze,_t));Rt&&Rt.streaming!==!1&&(Rt.streaming=!1,p(Rt))}ct!==""&&E.set(at,ct);let Gt=O(V.toolId,ze,ct,V.executionId),lr=(yn=(fo=(an=(ir=P.text)!=null?ir:P.delta)!=null?an:P.content)!=null?fo:P.chunk)!=null?yn:"";lr&&(Gt.content+=String(lr),Gt.streaming=!0,p(Gt)),P.isComplete&&(Gt.streaming=!1,p(Gt));continue}let fe=P.partId;if(fe!==void 0&&w.current!==null&&fe!==w.current){let ze=m;ze&&(ze.streaming=!1,p(ze),Y=ze,m=null,v=!0)}fe!==void 0&&(w.current=fe);let te=fe!==void 0&&(Ln=$e.get(fe))!=null?Ln:ue();fe!==void 0&&(te.partId||(te.partId=fe),$e.set(fe,te));let et=(ln=(he=(q=(sn=P.text)!=null?sn:P.delta)!=null?q:P.content)!=null?he:P.chunk)!=null?ln:"";if(et){let ze=typeof P.seq=="number"?P.seq:void 0,ct=fe!=null?fe:te.id,at=ze!==void 0?G(ct,ze,String(et)):((Pn=K.get(te.id))!=null?Pn:"")+et;te.rawContent=at,Pe.has(te.id)||Pe.set(te.id,this.createStreamParser());let _t=Pe.get(te.id),Gt=at.trim().startsWith("{")||at.trim().startsWith("[");if(Gt&&K.set(te.id,at),_t.__isPlainTextParser===!0){te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te);continue}let Rt=_t.processChunk(at);if(Rt instanceof Promise)Rt.then(Lt=>{var Hr;let yr=typeof Lt=="string"?Lt:(Hr=Lt==null?void 0:Lt.text)!=null?Hr:null;if(yr!==null&&yr.trim()!=="")te.content=yr,p(te);else if(!Gt&&!at.trim().startsWith("<")){let Mr=m,dr=Mr&&Mr.id===te.id?Mr:te;dr.id===te.id&&(dr.content=ze!==void 0?at:dr.content+et,K.delete(dr.id),Pe.delete(dr.id),dr.rawContent=void 0,p(dr))}}).catch(()=>{te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te)});else{let Lt=typeof Rt=="string"?Rt:(Nn=Rt==null?void 0:Rt.text)!=null?Nn:null;Lt!==null&&Lt.trim()!==""?(te.content=Lt,p(te)):!Gt&&!at.trim().startsWith("<")&&(te.content=ze!==void 0?at:te.content+et,K.delete(te.id),Pe.delete(te.id),te.rawContent=void 0,p(te))}}if(P.isComplete){let ze=(In=(Oa=P.result)==null?void 0:Oa.response)!=null?In:te.content;if(ze){let ct=K.get(te.id),at=ct!=null?ct:Oe(ze);te.rawContent=at;let _t=Pe.get(te.id),Gt=null,lr=!1;if(_t&&(Gt=_t.getExtractedText(),Gt===null&&(Gt=Ko(at)),Gt===null)){let Rt=_t.processChunk(at);Rt instanceof Promise?(lr=!0,Rt.then(Lt=>{var Hr;let yr=typeof Lt=="string"?Lt:(Hr=Lt==null?void 0:Lt.text)!=null?Hr:null;if(yr!==null){let Mr=m;Mr&&Mr.id===te.id&&(Mr.content=yr,Mr.streaming=!1,Pe.delete(Mr.id),K.delete(Mr.id),p(Mr))}})):Gt=typeof Rt=="string"?Rt:(Rn=Rt==null?void 0:Rt.text)!=null?Rn:null}if(!lr){Gt!==null&&Gt.trim()!==""?te.content=Gt:K.has(te.id)||(te.content=Oe(ze));let Rt=Pe.get(te.id);if(Rt){let Lt=(Hn=Rt.close)==null?void 0:Hn.call(Rt);Lt instanceof Promise&&Lt.catch(()=>{}),Pe.delete(te.id)}K.delete(te.id),te.streaming=!1,p(te)}}}}else if(Ze==="step_complete"){let z=P.stepType,I=P.executionType;if(z==="tool"||I==="context")continue;let V=P.toolContext;if(V!=null&&V.toolId){let ze=String((Ro=(Gn=P.id)!=null?Gn:V.stepId)!=null?Ro:"");if(ze){let ct=L(V.toolId,ze);for(let[at,_t]of A)at.startsWith(ct)&&_t.streaming!==!1&&(_t.streaming=!1,p(_t));E.delete(`${V.toolId}::${ze}`)}continue}let fe=P.stopReason;if(v){if(m!==null){let at=m;fe&&(at.stopReason=fe),Pe.delete(at.id),K.delete(at.id),at.streaming!==!1&&(at.streaming=!1,p(at))}let ze=(Ns=P.result)==null?void 0:Ns.response,ct=Y;ct&&(fe&&(ct.stopReason=fe),ze!=null?we(ct,ze):(Pe.delete(ct.id),K.delete(ct.id))),Y=null;continue}let te=(Fa=P.result)==null?void 0:Fa.response,et=ue();if(fe&&(et.stopReason=fe),te!=null){let ze=Pe.get(et.id),ct=!1,at=!1;if(ze){let _t=ze.getExtractedText(),Gt=K.get(et.id),lr=Gt!=null?Gt:Oe(te);if(et.rawContent=lr,_t!==null&&_t.trim()!=="")et.content=_t,ct=!0;else{let Rt=Ko(lr);if(Rt!==null)et.content=Rt,ct=!0;else{let Lt=ze.processChunk(lr);if(Lt instanceof Promise)at=!0,Lt.then(yr=>{var Mr;let Hr=typeof yr=="string"?yr:(Mr=yr==null?void 0:yr.text)!=null?Mr:null;if(Hr!==null&&Hr.trim()!==""){let dr=m;dr&&dr.id===et.id&&(dr.content=Hr,dr.streaming=!1,Pe.delete(dr.id),K.delete(dr.id),p(dr))}else{let dr=ze.getExtractedText(),vr=m;vr&&vr.id===et.id&&(dr!==null&&dr.trim()!==""?vr.content=dr:K.has(vr.id)||(vr.content=Oe(te)),vr.streaming=!1,Pe.delete(vr.id),K.delete(vr.id),p(vr))}});else{let yr=typeof Lt=="string"?Lt:(_s=Lt==null?void 0:Lt.text)!=null?_s:null;if(yr!==null&&yr.trim()!=="")et.content=yr,ct=!0;else{let Hr=ze.getExtractedText();Hr!==null&&Hr.trim()!==""&&(et.content=Hr,ct=!0)}}}}}if(!at){if(!et.rawContent){let _t=K.get(et.id);et.rawContent=_t!=null?_t:Oe(te)}if(!ct&&!K.has(et.id)&&(et.content=Oe(te)),ze){let _t=(la=ze.close)==null?void 0:la.call(ze);_t instanceof Promise&&_t.catch(()=>{})}Pe.delete(et.id),K.delete(et.id),et.streaming=!1,p(et)}}else Pe.delete(et.id),K.delete(et.id),et.streaming=!1,p(et)}else if(Ze==="flow_complete"){let z=(bt=P.result)==null?void 0:bt.response;if(v){if(m!==null){let I=m;Pe.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(z!=null){let I=ue(),V=K.get(I.id),fe=V!=null?V:Oe(z);I.rawContent=fe;let te=Oe(z),et=Pe.get(I.id);if(et){let at=Ko(fe);if(at!==null)te=at;else{let _t=et.processChunk(fe);_t instanceof Promise&&_t.then(lr=>{var Lt;let Rt=typeof lr=="string"?lr:(Lt=lr==null?void 0:lr.text)!=null?Lt:null;Rt!==null&&(I.content=Rt,I.streaming=!1,p(I))});let Gt=et.getExtractedText();Gt!==null&&(te=Gt)}}Pe.delete(I.id),K.delete(I.id);let ze=te!==I.content,ct=I.streaming!==!1;ze&&(I.content=te),I.streaming=!1,(ze||ct)&&p(I)}else if(m!==null){let I=m;Pe.delete(I.id),K.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}t({type:"status",status:"idle"})}else if(Ze==="agent_start")ne={executionId:P.executionId,agentId:(Na=P.agentId)!=null?Na:"virtual",agentName:(bn=P.agentName)!=null?bn:"",status:"running",currentIteration:0,maxTurns:(Qr=P.maxTurns)!=null?Qr:1,startedAt:ie(P.startedAt)};else if(Ze==="agent_iteration_start"){if(ne&&(ne.currentIteration=P.iteration),fr==="separate"&&P.iteration>1){let z=m;z&&(z.streaming=!1,p(z),He.set(P.iteration-1,z),m=null)}}else if(Ze!=="agent_turn_start"){if(Ze==="agent_turn_delta"){if(P.contentType==="text"){let z=ue();z.content+=($s=P.delta)!=null?$s:"",z.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId,agentName:ne==null?void 0:ne.agentName},p(z)}else if(P.contentType==="thinking"){let z=(Us=P.turnId)!=null?Us:`agent-think-${P.iteration}`,I=xe(z);I.reasoning=(da=I.reasoning)!=null?da:{id:z,status:"streaming",chunks:[]},I.reasoning.chunks.push((Xn=P.delta)!=null?Xn:""),I.agentMetadata={executionId:P.executionId,iteration:P.iteration,turnId:P.turnId},p(I)}else if(P.contentType==="tool_input"){let z=(qs=P.toolCallId)!=null?qs:h.lastId;if(z){let I=T.get(z);I!=null&&I.toolCall&&(I.toolCall.chunks=(Ho=I.toolCall.chunks)!=null?Ho:[],I.toolCall.chunks.push((_a=P.delta)!=null?_a:""),p(I))}}}else if(Ze==="agent_turn_complete"){let z=P.turnId;if(z){let V=k.get(z);if(V!=null&&V.reasoning){V.reasoning.status="complete",V.reasoning.completedAt=ie(P.completedAt);let fe=(Jn=V.reasoning.startedAt)!=null?Jn:Date.now();V.reasoning.durationMs=Math.max(0,(($a=V.reasoning.completedAt)!=null?$a:Date.now())-fe),V.streaming=!1,p(V)}}let I=P.stopReason;if(I&&m!==null){let V=P.turnId;(!V||((mo=m.agentMetadata)==null?void 0:mo.turnId)===V)&&(m.stopReason=I,p(m))}}else if(Ze==="agent_tool_start"){let z=(go=P.toolCallId)!=null?go:`agent-tool-${l()}`;ge(B(P),z);let I=pe(z),V=(zs=I.toolCall)!=null?zs:{id:z,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};V.name=(Hl=(Vs=P.toolName)!=null?Vs:P.name)!=null?Hl:V.name,V.status="running",P.parameters!==void 0&&(V.args=P.parameters),V.startedAt=ie((Bo=P.startedAt)!=null?Bo:P.timestamp),I.toolCall=V,I.streaming=!0,I.agentMetadata={executionId:P.executionId,iteration:P.iteration},p(I)}else if(Ze==="agent_tool_delta"){let z=(ho=P.toolCallId)!=null?ho:h.lastId;if(z){let I=(js=T.get(z))!=null?js:pe(z);I.toolCall&&(I.toolCall.chunks=(Ua=I.toolCall.chunks)!=null?Ua:[],I.toolCall.chunks.push((xo=P.delta)!=null?xo:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ze==="agent_tool_complete"){let z=(Gs=P.toolCallId)!=null?Gs:h.lastId;if(z){let I=(qa=T.get(z))!=null?qa:pe(z);if(I.toolCall){I.toolCall.status="complete",P.result!==void 0&&(I.toolCall.result=P.result),typeof P.executionTime=="number"&&(I.toolCall.durationMs=P.executionTime),I.toolCall.completedAt=ie((yo=P.completedAt)!=null?yo:P.timestamp),I.streaming=!1,p(I);let V=B(P);V&&h.byCall.delete(V)}}}else if(Ze==="agent_media"){let z=Array.isArray(P.media)?P.media:[],I=[];for(let V of z){if(!V||typeof V!="object")continue;let fe=V,te=typeof fe.type=="string"?fe.type:void 0,et=typeof fe.mediaType=="string"?fe.mediaType.toLowerCase():"",ze=null,ct="";if(te==="media"){let at=typeof fe.data=="string"?fe.data:void 0;if(!at)continue;ct=et.length>0?et:"application/octet-stream",ze=`data:${ct};base64,${at}`}else if(te==="image-url"){let at=typeof fe.url=="string"?fe.url:void 0;if(!at)continue;ct=et,ze=at}else if(te==="file-url"){let at=typeof fe.url=="string"?fe.url:void 0;if(!at)continue;ct=et,ze=at}else continue;if(ze)if(te==="image-url"||ct.startsWith("image/"))I.push({type:"image",image:ze,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))I.push({type:"audio",audio:ze,mimeType:ct});else if(ct.startsWith("video/"))I.push({type:"video",video:ze,mimeType:ct});else{let at=ct||"application/octet-stream";I.push({type:"file",data:ze,mimeType:at,filename:sb(at)})}}if(I.length>0){let V=l(),fe=P.toolCallId,et={id:`agent-media-${typeof fe=="string"&&fe.length>0?`${fe}-${V}`:String(V)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:V,agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(et);let ze=m;ze&&(ze.streaming=!1,p(ze)),m=null,f.current=null}}else if(Ze!=="agent_iteration_complete"){if(Ze==="agent_reflection"||Ze==="agent_reflect"){let z=`agent-reflection-${P.executionId}-${P.iteration}`,I={id:z,role:"assistant",content:(za=P.reflection)!=null?za:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(Xs=P.reflection)!=null?Xs:""]},agentMetadata:{executionId:P.executionId,iteration:P.iteration}};p(I)}else if(Ze==="agent_complete"){ne&&(ne.status=P.success?"complete":"error",ne.completedAt=ie(P.completedAt),ne.stopReason=P.stopReason);let z=m;z&&(z.streaming=!1,p(z)),t({type:"status",status:"idle"})}else if(Ze==="agent_error"){let z=typeof P.error=="string"?P.error:(Js=(Kn=P.error)==null?void 0:Kn.message)!=null?Js:"Agent execution error";P.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):t({type:"error",error:new Error(z)})}else if(Ze!=="agent_ping"){if(Ze==="agent_approval_start"){let z=(bo=P.approvalId)!=null?bo:`approval-${l()}`,I={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Nt=ne==null?void 0:ne.agentId)!=null?Nt:"virtual",executionId:(pa=(ca=P.executionId)!=null?ca:ne==null?void 0:ne.executionId)!=null?pa:"",toolName:(Va=P.toolName)!=null?Va:"",toolType:P.toolType,description:(Ks=P.description)!=null?Ks:`Execute ${(_n=P.toolName)!=null?_n:"tool"}`,parameters:P.parameters}};p(I)}else if(Ze==="step_await"&&P.awaitReason==="approval_required"){let z=(ja=P.approvalId)!=null?ja:`approval-${l()}`,I={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ga=ne==null?void 0:ne.agentId)!=null?Ga:"virtual",executionId:(Ja=(Xa=P.executionId)!=null?Xa:ne==null?void 0:ne.executionId)!=null?Ja:"",toolName:($r=P.toolName)!=null?$r:"",toolType:P.toolType,description:(Yn=P.description)!=null?Yn:`Execute ${(dn=P.toolName)!=null?dn:"tool"}`,parameters:P.parameters}};p(I)}else if(Ze==="agent_approval_complete"){let z=P.approvalId;if(z){let V={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(dt=P.decision)!=null?dt:"approved",agentId:(Ka=ne==null?void 0:ne.agentId)!=null?Ka:"virtual",executionId:(Bn=(Wo=P.executionId)!=null?Wo:ne==null?void 0:ne.executionId)!=null?Bn:"",toolName:(Ys=P.toolName)!=null?Ys:"",description:(ua=P.description)!=null?ua:"",resolvedAt:Date.now()}};p(V)}}else if(Ze==="artifact_start"||Ze==="artifact_delta"||Ze==="artifact_update"||Ze==="artifact_complete"){if(Ze==="artifact_start"){let z=P.artifactType,I=String(P.id),V=typeof P.title=="string"?P.title:void 0;if(t({type:"artifact_start",id:I,artifactType:z,title:V,component:typeof P.component=="string"?P.component:void 0}),Se.set(I,{markdown:"",title:V}),!Q.has(I)){Q.add(I);let fe={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:V,artifactType:z,status:"streaming"}})};Ge.set(I,fe),p(fe)}}else if(Ze==="artifact_delta"){let z=String(P.id),I=typeof P.delta=="string"?P.delta:String((fa=P.delta)!=null?fa:"");t({type:"artifact_delta",id:z,artDelta:I});let V=Se.get(z);V&&(V.markdown+=I)}else if(Ze==="artifact_update"){let z=P.props&&typeof P.props=="object"&&!Array.isArray(P.props)?P.props:{};t({type:"artifact_update",id:String(P.id),props:z,component:typeof P.component=="string"?P.component:void 0})}else if(Ze==="artifact_complete"){let z=String(P.id);t({type:"artifact_complete",id:z});let I=Ge.get(z);if(I){I.streaming=!1;try{let V=JSON.parse((Do=I.rawContent)!=null?Do:"{}");if(V.props){V.props.status="complete";let fe=Se.get(z);fe!=null&&fe.markdown&&(V.props.markdown=fe.markdown)}I.rawContent=JSON.stringify(V)}catch{}Se.delete(z),p(I),Ge.delete(z)}}}else if(Ze==="transcript_insert"){let z=P.message;if(!z||typeof z!="object")continue;let I=String((Co=z.id)!=null?Co:`msg-${l()}`),V=z.role,te={id:I,role:V==="user"?"user":V==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(p(te),te.rawContent)try{let et=JSON.parse(te.rawContent),ze=(Qs=et==null?void 0:et.props)==null?void 0:Qs.artifactId;typeof ze=="string"&&Q.add(ze)}catch{}m=null,f.current=null,Pe.delete(I),K.delete(I)}else if(Ze==="error"||Ze==="step_error"||Ze==="dispatch_error"||Ze==="flow_error"){let z=null;if(P.error instanceof Error)z=P.error;else if(Ze==="dispatch_error"){let I=(Zs=P.message)!=null?Zs:P.error;I!=null&&I!==""&&(z=new Error(String(I)))}else if(Ze==="step_error"||Ze==="flow_error"){let I=P.error;typeof I=="string"&&I!==""?z=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(z=new Error(String((Wn=I.message)!=null?Wn:I)))}else Ze==="error"&&P.error!=null&&P.error!==""&&(z=new Error(String(P.error)));if(z){t({type:"error",error:z});let I=m;I&&I.streaming&&(I.streaming=!1,p(I)),t({type:"status",status:"idle"})}}}}}}ke.length=0};;){let{done:F,value:le}=await o.read();if(F)break;s+=a.decode(le,{stream:!0});let Fe=s.split(`
|
|
52
52
|
|
|
53
|
-
`);s=(Yt=
|
|
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
|
|
53
|
+
`);s=(Yt=Fe.pop())!=null?Yt:"";for(let Ke of Fe){let Ue=Ke.split(`
|
|
54
|
+
`),qe="message",nt="";for(let $t of Ue)$t.startsWith("event:")?qe=$t.replace("event:","").trim():$t.startsWith("data:")&&(nt+=$t.replace("data:","").trim());if(!nt)continue;let Ct;try{Ct=JSON.parse(nt)}catch($t){t({type:"error",error:$t instanceof Error?$t:new Error("Failed to parse chat stream payload")});continue}let Pt=qe!=="message"?qe:(Fr=Ct.type)!=null?Fr:"message";if((Ar=this.onSSEEvent)==null||Ar.call(this,Pt,Ct),this.parseSSEEvent){f.current=m;let $t=await this.handleCustomSSEEvent(Ct,t,f,p,l,w);if(f.current&&f.current!==m&&(m=f.current),$t)continue}Mt.push(Pt,Ct),ve()}}Mt.flushPending(),ve(),Mt.destroy()}};function Ig(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Ca(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Qo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ei="[Image]";function Rg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Hg(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Bg(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Wg(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function gs(e){return{type:"text",text:e}}function Dg(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Og(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;r({type:"image",image:o,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Fg(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var Ng=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],db=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],oo=[...Ng,...db];function cb(e){return Ng.includes(e)||e.startsWith("image/")}function Mi(e){return cb(e.type)}async function _g(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let o=n.result;Mi(e)?r({type:"image",image:o,mimeType:e.type,alt:e.name}):r({type:"file",data:o,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function $g(e,r=oo,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function pb(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Ug(e,r){let t=pb(r).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var Li=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),o=this.pcmToFloat32(t),a=n.createBuffer(1,o.length,this.sampleRate);a.getChannelData(0).set(o);let s=n.createBufferSource();s.buffer=a,s.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=a.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,s.onended=()=>{let d=this.activeSources.indexOf(s);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),o=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let a=0;a<t;a++){let s=o.getInt16(a*2,!0);n[a]=s/32768}return n}};var Pi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,o,a){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let s=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(s);let i=0;for(let u=0;u<s.length;u++)i+=s[u]*s[u];let d=Math.sqrt(i/s.length);(n==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,a()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var hs=class{constructor(r){this.config=r;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Pi;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let a=o.location.protocol==="https:"?"wss:":"ws:",s=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!s)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${a}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${a}//${s}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,f)=>{if(!this.ws)return f(new Error("WebSocket not created"));let w=!1,v=T=>{w||(w=!0,clearTimeout(k),f(new Error(T)))},k=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(k),m())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",T=>{if(!T.wasClean&&!w){let A=T.code!==1006?` (code ${T.code})`:"";v("WebSocket connection failed"+A+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(r.response.audio).catch(o=>this.errorCallbacks.forEach(a=>a(o instanceof Error?o:new Error(String(o)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(r.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Li(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let a=this.w;this.audioContext||(this.audioContext=new(a.AudioContext||a.webkitAudioContext));let s=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(o=(n=this.config)==null?void 0:n.silenceThreshold)!=null?o:.01;this.vad.start(s,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(a){throw this.errorCallbacks.forEach(s=>s(a)),this.statusCallbacks.forEach(s=>s("error")),a}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var a,s;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(s=(a=this.config)==null?void 0:a.silenceThreshold)!=null?s:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),o=this.getFormatFromMimeType(r.type),a=this.generateRequestId();this.currentRequestId=a,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:a}))}catch(n){this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result.split(",")[1];t(s)},o.onerror=n,o.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let l=0;l<t.length;l++)n[l]=t.charCodeAt(l);let o=r.format||"mp3",a=o==="mp3"?"audio/mpeg":`audio/${o}`,s=new Blob([n],{type:a}),i=URL.createObjectURL(s),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Zo=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let a=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(a=>a(new Error(o.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(o=>o(n)),this.statusCallbacks.forEach(o=>o("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ea(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!Zo.isSupported())throw new Error("Browser speech recognition not supported");return new Zo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ii(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ea({type:"runtype",runtype:e.runtype});if(Zo.isSupported())return ea({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function xs(e){try{return Ii(e),!0}catch{return!1}}var wa=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,o,a,s,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(o=r.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n,o;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Yo(r);for(let a of(o=r.initialArtifacts)!=null?o:[])this.artifacts.set(a.id,{...a,status:"complete"});r.initialSelectedArtifactId!=null&&(this.selectedArtifactId=r.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return xs((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,o;try{let a=r||this.getVoiceConfigFromConfig();if(!a)throw new Error("Voice configuration not provided");this.voiceProvider=ea(a);let s=(t=this.config.voiceRecognition)!=null?t:{},i=(n=s.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(o=s.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,m,f,w,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((m=l.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(f=l.text)!=null&&f.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let k=(v=this.pendingVoiceAssistantMessageId)!=null?v:(w=[...this.messages].reverse().find(T=>T.role==="assistant"))==null?void 0:w.id;k&&this.ttsSpokenMessageIds.add(k)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(a){console.error("Failed to setup voice:",a)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,o,a,s,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((o=r.runtype)==null?void 0:o.clientToken)||"",host:(a=r.runtype)==null?void 0:a.host,voiceId:(s=r.runtype)==null?void 0:s.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=r.browser)==null?void 0:l.language)||"en-US",continuous:(u=r.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Yo(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=r,f={id:s!=null?s:t==="user"?Ca():t==="assistant"?Qo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:o,content:a,llmContent:s,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:m,rawContent:f}=n,v={id:d!=null?d:o==="user"?Ca():o==="assistant"?Qo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};t.push(v)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(r){let{component:t,props:n={},text:o="",llmContent:a,id:s,createdAt:i,sequence:d}=r,l={text:o,component:t,props:n};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(r,t){var l,u,p,m,f;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let o=Ca(),a=Qo(),s={id:o,role:"user",content:n||Ei,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(w){let v=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!v){let k={id:a,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(k)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(w instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,w):(f=(m=this.callbacks).onError)==null||f.call(m,new Error(String(w))))}}async continueConversation(){var o,a,s,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let r=Qo();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(l){let u={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(r,t){var o,a,s;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,l,u;let n=`approval-${r.id}`,o={...r,status:t,resolvedAt:Date.now()},a={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(a);let s=this.config.approval,i=s&&typeof s=="object"?s.onDecision:void 0;try{let p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let m=null;if(p instanceof Response){if(!p.ok){let f=await p.json().catch(()=>null);throw new Error((d=f==null?void 0:f.error)!=null?d:`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(u=(l=this.callbacks).onError)==null||u.call(l,p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(r,t){let n=this.messages.find(o=>o.id===r.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(r,t){let n=this.messages.find(o=>o.id===r.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(r,t){var u,p,m,f,w,v,k,T,A,E,b;let n=this.messages.find(h=>h.id===r.id);if(((u=n==null?void 0:n.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(p=r.agentMetadata)==null?void 0:p.executionId,a=(m=r.toolCall)==null?void 0:m.name;if(!o||!a){(w=(f=this.callbacks).onError)==null||w.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof t=="string"?void 0:t;if(s===void 0&&typeof t=="string"){let h=(v=r.toolCall)==null?void 0:v.args,S=Array.isArray(h==null?void 0:h.questions)?h.questions:[];if(S.length===1){let L=typeof((k=S[0])==null?void 0:k.question)=="string"?S[0].question:"";L&&(s={[L]:t})}}this.markAskUserQuestionResolved(r,s);let i=r.toolCall.id,d=(T=r.toolCall)==null?void 0:T.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let h=typeof t=="string"?t:Object.entries(t).map(([S,L])=>`${S}: ${Array.isArray(L)?L.join(", "):L}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let h=s!=null?s:{};l.forEach((S,L)=>{let O=typeof(S==null?void 0:S.question)=="string"?S.question:"";if(!O)return;let H=h[O],R=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${L}`,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${L}`,role:"user",content:R||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let h=await this.client.resumeFlow(o,{[a]:t});if(!h.ok){let S=await h.json().catch(()=>null);throw new Error((A=S==null?void 0:S.error)!=null?A:`Resume failed: ${h.status}`)}h.body&&await this.connectStream(h.body)}catch(h){(b=(E=this.callbacks).onError)==null||b.call(E,h instanceof Error?h:new Error(String(h)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var o;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let a={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,a),this.selectedArtifactId=t,this.emitArtifactsState(),a}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(o=r.props)!=null?o:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let o=this.artifacts.get(r.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((n=o.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let o=this.artifacts.get(r.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...r.props},r.component&&(o.component=r.component));break}case"artifact_complete":{let o=this.artifacts.get(r.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var o;return{...n,streaming:!1,sequence:(o=n.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(r,t=null){this.artifacts.clear();for(let n of r)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let o=n.content;o.trim()&&this.speak(o,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(r),a=n.getVoices();if(t.voice){let s=a.find(i=>i.name===t.voice);s&&(o.voice=s)}else a.length>0&&(o.voice=t.pickVoice?t.pickVoice(a):e.pickBestVoice(a));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>n.speak(o),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let a=r.find(s=>s.name===o);if(a)return a}return(n=r.find(o=>o.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(o=>o.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,a)=>{var i;if(a!==n)return o;let s={...o,...t};return((i=o.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(s.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var d,l;let o=new Date(t.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(a)&&o!==a)return o-a;let s=(d=t.sequence)!=null?d:0,i=(l=n.sequence)!=null?l:0;return s!==i?s-i:t.id.localeCompare(n.id)})}};var x=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},qn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var rd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var nd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var od=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ad=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var sd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var id=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var ld=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var dd=[["path",{d:"M4.929 4.929 19.07 19.071"}],["circle",{cx:"12",cy:"12",r:"10"}]];var cd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var pd=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}]];var ud=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var fd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var md=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var gd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var hd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var xd=[["path",{d:"M20 6 9 17l-5-5"}]];var yd=[["path",{d:"m6 9 6 6 6-6"}]];var bd=[["path",{d:"m15 18-6-6 6-6"}]];var Cd=[["path",{d:"m9 18 6-6-6-6"}]];var wd=[["path",{d:"m18 15-6-6-6 6"}]];var Ri=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Hi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var vd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var Ad=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Sd=[["path",{d:"M12 6v6l4 2"}],["circle",{cx:"12",cy:"12",r:"10"}]];var Td=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var kd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Ed=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Md=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Bi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Wi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ld=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var Pd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Id=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Rd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var Hd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Bd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Wd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Dd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Od=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Fd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Nd=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var _d=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Di=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var $d=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1"}],["path",{d:"M12 8v13"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"}]];var Ud=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var qd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var zd=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Vd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var jd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Oi=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Gd=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Xd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var Jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Kd=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Yd=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var Fi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Qd=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Zd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var ec=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var tc=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var rc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var nc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var oc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var ac=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var sc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var ic=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var lc=[["path",{d:"M5 12h14"}]];var dc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var cc=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var pc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var uc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var fc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var mc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var gc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var hc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var xc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var yc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var bc=[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"}],["path",{d:"M12 17.5v-11"}]];var Cc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var wc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var vc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var Ac=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Sc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Tc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var kc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Ec=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Mc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Ni=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Lc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Pc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var Ic=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Rc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var _i=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Hc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Bc=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Wc=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var Dc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Oc=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Fc=[["path",{d:"M17 14V2"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}]];var Nc=[["path",{d:"M7 10v12"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}]];var _c=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var $c=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Uc=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var $i=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var qc=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var zc=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Vc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var jc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Gc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Xc=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var Jc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Kc=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var ub={activity:rd,"arrow-down":nd,"arrow-up":id,"arrow-up-right":sd,bot:ud,"chevron-down":yd,"chevron-up":wd,"chevron-right":Cd,"chevron-left":bd,check:xd,clipboard:Ad,"clipboard-copy":vd,copy:Td,file:Wd,"file-code":Rd,"file-spreadsheet":Hd,"file-text":Bd,"image-plus":Gd,loader:Qd,"loader-circle":Fi,mic:sc,paperclip:uc,"refresh-cw":Cc,search:Ac,send:Sc,"shield-alert":Ec,"shield-check":Mc,"shield-x":Ni,square:Hc,"thumbs-down":Fc,"thumbs-up":Nc,upload:zc,"volume-2":jc,x:Jc,user:Vc,mail:ec,phone:hc,calendar:gd,clock:Sd,building:fd,"map-pin":tc,lock:Zd,key:Kd,"credit-card":kd,"at-sign":ld,hash:qd,globe:Ud,link:Yd,"circle-check":Ri,"circle-x":Hi,"triangle-alert":$i,info:Jd,ban:dd,shield:Lc,"arrow-left":od,"arrow-right":ad,"external-link":Ld,ellipsis:Wi,"ellipsis-vertical":Bi,menu:nc,house:Oi,plus:yc,minus:lc,pencil:mc,trash:Uc,"trash-2":$c,save:vc,download:Md,share:kc,funnel:Di,settings:Tc,"rotate-cw":wc,maximize:rc,minimize:ic,"shopping-cart":Ic,"shopping-bag":Pc,package:pc,truck:qc,tag:Oc,gift:$d,receipt:bc,wallet:Xc,store:Wc,"dollar-sign":Ed,percent:gc,play:xc,pause:fc,"volume-x":Gc,camera:hd,image:Xd,film:Od,headphones:zd,"message-circle":oc,"message-square":ac,bell:cd,heart:Vd,star:Bc,eye:Id,"eye-off":Pd,bookmark:pd,"calendar-days":md,history:jd,timer:_c,folder:_d,"folder-open":Nd,files:Dd,sparkles:_i,zap:Kc,sun:Dc,moon:cc,flag:Fd,monitor:dc,smartphone:Rc},Ce=(e,r=24,t="currentColor",n=2)=>{let o=ub[e];return o?fb(o,r,t,n):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function fb(e,r,t,n){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(r)),o.setAttribute("height",String(r)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),o.appendChild(d)}),o}var Ui={allowedTypes:oo,maxFileSize:10*1024*1024,maxFiles:4};function mb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function gb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ta=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,o;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ui.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Ui.maxFileSize,maxFiles:(o=r.maxFiles)!=null?o:Ui.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:Ui.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,o,a,s,i,d;if(r.length){for(let l of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,l,"count");continue}let u=$g(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(o=u.error)!=null&&o.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,p);continue}try{let p=await _g(l),m=Mi(l)?URL.createObjectURL(l):null,f={id:mb(),file:l,previewUrl:m,contentPart:p};this.attachments.push(f),this.renderPreview(f)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var a,s,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let o=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${r}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=Mi(r.file),n=x("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let s=x("img");s.src=r.previewUrl,s.alt=r.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",n.appendChild(s)}else{let s=x("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=gb(r.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&s.appendChild(d);let l=x("span");l.textContent=Ug(r.file.type,r.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",s.appendChild(l),n.appendChild(s)}let o=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let a=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);a?o.appendChild(a):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(o),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ys(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,o]of Object.entries(r)){let a=t[n];qg(a)&&qg(o)?t[n]=ys(a,o):t[n]=o}return t}var mn="min(440px, calc(100vw - 24px))",qi="440px",jt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:mn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function zg(e,r){if(!(!e&&!r))return e?r?ys(e,r):e:r}function zi(e){var r,t,n,o,a,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h;return e?{...jt,...e,theme:zg(jt.theme,e.theme),darkTheme:zg(jt.darkTheme,e.darkTheme),launcher:{...jt.launcher,...e.launcher,dock:{...(r=jt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=jt.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...jt.copy,...e.copy},sendButton:{...jt.sendButton,...e.sendButton},statusIndicator:{...jt.statusIndicator,...e.statusIndicator},voiceRecognition:{...jt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ge,Le,Ge,Q,Se,J,ce,pe;let S=(ge=jt.features)==null?void 0:ge.artifacts,L=(Le=e.features)==null?void 0:Le.artifacts,O=(Ge=jt.features)==null?void 0:Ge.scrollToBottom,H=(Q=e.features)==null?void 0:Q.scrollToBottom,R=(Se=jt.features)==null?void 0:Se.streamAnimation,B=(J=e.features)==null?void 0:J.streamAnimation,j=(ce=jt.features)==null?void 0:ce.askUserQuestion,oe=(pe=e.features)==null?void 0:pe.askUserQuestion,ue=S===void 0&&L===void 0?void 0:{...S,...L,layout:{...S==null?void 0:S.layout,...L==null?void 0:L.layout}},De=O===void 0&&H===void 0?void 0:{...O,...H},Xe=R===void 0&&B===void 0?void 0:{...R,...B},xe=j===void 0&&oe===void 0?void 0:{...j,...oe,styles:{...j==null?void 0:j.styles,...oe==null?void 0:oe.styles}};return{...jt.features,...e.features,...De!==void 0?{scrollToBottom:De}:{},...ue!==void 0?{artifacts:ue}:{},...Xe!==void 0?{streamAnimation:Xe}:{},...xe!==void 0?{askUserQuestion:xe}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:jt.suggestionChips,suggestionChipsConfig:{...jt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...jt.layout,...e.layout,header:{...(s=jt.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=jt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=jt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(f=(m=e.layout)==null?void 0:m.messages)==null?void 0:f.avatar},timestamp:{...(v=(w=jt.layout)==null?void 0:w.messages)==null?void 0:v.timestamp,...(T=(k=e.layout)==null?void 0:k.messages)==null?void 0:T.timestamp}},slots:{...(A=jt.layout)==null?void 0:A.slots,...(E=e.layout)==null?void 0:E.slots}},markdown:{...jt.markdown,...e.markdown,options:{...(b=jt.markdown)==null?void 0:b.options,...(h=e.markdown)==null?void 0:h.options}},messageActions:{...jt.messageActions,...e.messageActions}}:jt}var Yc={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Qc={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Zc={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:mn,maxWidth:qi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function va(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let o of t){if(n==null)return;n=n[o]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?va(e,n):n}function Vi(e){let r={};function t(n,o){for(let[a,s]of Object.entries(n)){let i=`${o}.${a}`;if(typeof s=="string"){let d=va(e,s);d!==void 0&&(r[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&t(s,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function ep(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function Vg(e,r){let t={...e};for(let[n,o]of Object.entries(r)){let a=t[n];a&&typeof a=="object"&&!Array.isArray(a)&&o&&typeof o=="object"&&!Array.isArray(o)?t[n]=Vg(a,o):t[n]=o}return t}function hb(e,r){return r?Vg(e,r):e}function Aa(e,r={}){var o,a,s,i,d,l,u,p,m,f,w,v,k;let t={palette:Yc,semantic:Qc,components:Zc},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...t.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(m=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:m.interactive},feedback:{...t.semantic.colors.feedback,...(w=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:w.feedback}},spacing:{...t.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:hb(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let T=ep(n);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(A=>A.message).join(", ")}`)}if(r.plugins)for(let T of r.plugins)n=T.transform(n);return n}function ji(e){var v,k,T,A,E,b,h,S,L,O,H,R,B,j,oe,ue,De,Xe,xe,ge,Le,Ge,Q,Se,J,ce,pe,ie,Oe,Pe,K,_e,$e,Y,G,we,ke,ae,ve,ye,Mt,ne,He,fr,Ot,Yt,Fr,Ar,F,le,Fe,Ke,Ue,qe,nt,Ct,Pt,$t,N,de,Ee,ut,Ye,Ut,or,It,St,rt,it,tr,gn,Rr,Tn,Tt,hn,ur,Sr,Yr,xt,kn,nn,Tr,kr,Vn,En,xn,wt,Ie,M,Z,se,kt,qt,Bt,ar,xr,Nr,Er,ot,wr,_r,po,jn,uo,Fn,on,Mn,vt,sr,ir,an,fo,yn,Ln,sn,q;let r=Vi(e),t={};for(let[he,ln]of Object.entries(r)){let Pn=he.replace(/\./g,"-");t[`--persona-${Pn}`]=ln.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(k=t["--persona-semantic-colors-secondary"])!=null?k:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(T=t["--persona-semantic-colors-accent"])!=null?T:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(A=t["--persona-semantic-colors-surface"])!=null?A:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(E=t["--persona-semantic-colors-background"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(b=t["--persona-semantic-colors-container"])!=null?b:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(h=t["--persona-semantic-colors-text"])!=null?h:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(S=t["--persona-semantic-colors-text-muted"])!=null?S:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(L=t["--persona-semantic-colors-text-inverse"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(O=t["--persona-semantic-colors-border"])!=null?O:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(H=t["--persona-semantic-colors-divider"])!=null?H:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(B=t["--persona-components-voice-recording-background"])!=null?B:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(j=t["--persona-components-voice-processing-icon"])!=null?j:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ue=t["--persona-components-approval-requested-background"])!=null?ue:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(De=t["--persona-components-approval-requested-border"])!=null?De:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Xe=t["--persona-components-approval-requested-text"])!=null?Xe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(xe=t["--persona-components-approval-approve-background"])!=null?xe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ge=t["--persona-components-approval-deny-background"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Le=t["--persona-components-attachment-image-background"])!=null?Le:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Ge=t["--persona-components-attachment-image-border"])!=null?Ge:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Q=t["--persona-semantic-typography-fontFamily"])!=null?Q:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Se=t["--persona-semantic-typography-fontSize"])!=null?Se:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(J=t["--persona-semantic-typography-fontWeight"])!=null?J:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ce=t["--persona-semantic-typography-lineHeight"])!=null?ce:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(pe=t["--persona-palette-radius-sm"])!=null?pe:"0.125rem",t["--persona-radius-md"]=(ie=t["--persona-palette-radius-md"])!=null?ie:"0.375rem",t["--persona-radius-lg"]=(Oe=t["--persona-palette-radius-lg"])!=null?Oe:"0.5rem",t["--persona-radius-xl"]=(Pe=t["--persona-palette-radius-xl"])!=null?Pe:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=($e=(_e=t["--persona-components-launcher-borderRadius"])!=null?_e:t["--persona-palette-radius-full"])!=null?$e:"9999px",t["--persona-launcher-bg"]=(Y=t["--persona-components-launcher-background"])!=null?Y:t["--persona-primary"],t["--persona-launcher-fg"]=(G=t["--persona-components-launcher-foreground"])!=null?G:t["--persona-text-inverse"],t["--persona-launcher-border"]=(we=t["--persona-components-launcher-border"])!=null?we:t["--persona-border"],t["--persona-button-primary-bg"]=(ke=t["--persona-components-button-primary-background"])!=null?ke:t["--persona-primary"],t["--persona-button-primary-fg"]=(ae=t["--persona-components-button-primary-foreground"])!=null?ae:t["--persona-text-inverse"],t["--persona-button-radius"]=(ye=(ve=t["--persona-components-button-primary-borderRadius"])!=null?ve:t["--persona-palette-radius-full"])!=null?ye:"9999px",t["--persona-panel-radius"]=(ne=(Mt=t["--persona-components-panel-borderRadius"])!=null?Mt:t["--persona-radius-xl"])!=null?ne:"0.75rem",t["--persona-panel-border"]=(He=t["--persona-components-panel-border"])!=null?He:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ot=(fr=t["--persona-components-panel-shadow"])!=null?fr:t["--persona-palette-shadows-xl"])!=null?Ot:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Fr=(Yt=t["--persona-components-input-borderRadius"])!=null?Yt:t["--persona-radius-lg"])!=null?Fr:"0.5rem",t["--persona-message-user-radius"]=(F=(Ar=t["--persona-components-message-user-borderRadius"])!=null?Ar:t["--persona-radius-lg"])!=null?F:"0.5rem",t["--persona-message-assistant-radius"]=(Fe=(le=t["--persona-components-message-assistant-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?Fe:"0.5rem",t["--persona-header-bg"]=(Ke=t["--persona-components-header-background"])!=null?Ke:t["--persona-surface"],t["--persona-header-border"]=(Ue=t["--persona-components-header-border"])!=null?Ue:t["--persona-divider"],t["--persona-header-icon-bg"]=(qe=t["--persona-components-header-iconBackground"])!=null?qe:t["--persona-primary"],t["--persona-header-icon-fg"]=(nt=t["--persona-components-header-iconForeground"])!=null?nt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ct=t["--persona-components-header-titleForeground"])!=null?Ct:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Pt=t["--persona-components-header-subtitleForeground"])!=null?Pt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=($t=t["--persona-components-header-actionIconForeground"])!=null?$t:t["--persona-muted"];let n=(N=e.components)==null?void 0:N.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom);let o=(de=e.components)==null?void 0:de.introCard;t["--persona-intro-card-bg"]=(Ee=t["--persona-components-introCard-background"])!=null?Ee:t["--persona-surface"],t["--persona-intro-card-radius"]=(ut=t["--persona-components-introCard-borderRadius"])!=null?ut:"1rem",t["--persona-intro-card-padding"]=(Ye=t["--persona-components-introCard-padding"])!=null?Ye:"1.5rem",t["--persona-intro-card-shadow"]=(or=(Ut=o==null?void 0:o.shadow)!=null?Ut:t["--persona-components-introCard-shadow"])!=null?or:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(It=t["--persona-components-input-background"])!=null?It:t["--persona-surface"],t["--persona-input-placeholder"]=(St=t["--persona-components-input-placeholder"])!=null?St:t["--persona-text-muted"],t["--persona-message-user-bg"]=(rt=t["--persona-components-message-user-background"])!=null?rt:t["--persona-accent"],t["--persona-message-user-text"]=(it=t["--persona-components-message-user-text"])!=null?it:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(tr=t["--persona-components-message-user-shadow"])!=null?tr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(gn=t["--persona-components-message-assistant-background"])!=null?gn:t["--persona-surface"],t["--persona-message-assistant-text"]=(Rr=t["--persona-components-message-assistant-text"])!=null?Rr:t["--persona-text"],t["--persona-message-assistant-border"]=(Tn=t["--persona-components-message-assistant-border"])!=null?Tn:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Tt=t["--persona-components-message-assistant-shadow"])!=null?Tt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(hn=t["--persona-components-scrollToBottom-background"])!=null?hn:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Yr=(Sr=t["--persona-components-scrollToBottom-foreground"])!=null?Sr:t["--persona-button-primary-fg"])!=null?Yr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(xt=t["--persona-components-scrollToBottom-border"])!=null?xt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(kn=t["--persona-components-scrollToBottom-size"])!=null?kn:"40px",t["--persona-scroll-to-bottom-radius"]=(kr=(Tr=(nn=t["--persona-components-scrollToBottom-borderRadius"])!=null?nn:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?kr:"9999px",t["--persona-scroll-to-bottom-shadow"]=(En=(Vn=t["--persona-components-scrollToBottom-shadow"])!=null?Vn:t["--persona-palette-shadows-sm"])!=null?En:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(xn=t["--persona-components-scrollToBottom-padding"])!=null?xn:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(wt=t["--persona-components-scrollToBottom-gap"])!=null?wt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(M=(Ie=t["--persona-components-scrollToBottom-fontSize"])!=null?Ie:t["--persona-palette-typography-fontSize-sm"])!=null?M:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Z=t["--persona-components-scrollToBottom-iconSize"])!=null?Z:"14px",t["--persona-tool-bubble-shadow"]=(se=t["--persona-components-toolBubble-shadow"])!=null?se:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(kt=t["--persona-components-reasoningBubble-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(qt=t["--persona-components-composer-shadow"])!=null?qt:"none",t["--persona-md-inline-code-bg"]=(Bt=t["--persona-components-markdown-inlineCode-background"])!=null?Bt:t["--persona-container"],t["--persona-md-inline-code-color"]=(ar=t["--persona-components-markdown-inlineCode-foreground"])!=null?ar:t["--persona-text"],t["--persona-md-link-color"]=(Nr=(xr=t["--persona-components-markdown-link-foreground"])!=null?xr:t["--persona-accent"])!=null?Nr:"#0f0f0f";let a=t["--persona-components-markdown-heading-h1-fontSize"];a&&(t["--persona-md-h1-size"]=a);let s=t["--persona-components-markdown-heading-h1-fontWeight"];s&&(t["--persona-md-h1-weight"]=s);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Er=t["--persona-components-markdown-codeBlock-background"])!=null?Er:t["--persona-container"],t["--persona-md-code-block-border-color"]=(ot=t["--persona-components-markdown-codeBlock-borderColor"])!=null?ot:t["--persona-border"],t["--persona-md-code-block-text-color"]=(wr=t["--persona-components-markdown-codeBlock-textColor"])!=null?wr:"inherit",t["--persona-md-table-header-bg"]=(_r=t["--persona-components-markdown-table-headerBackground"])!=null?_r:t["--persona-container"],t["--persona-md-table-border-color"]=(po=t["--persona-components-markdown-table-borderColor"])!=null?po:t["--persona-border"],t["--persona-md-hr-color"]=(jn=t["--persona-components-markdown-hr-color"])!=null?jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(uo=t["--persona-components-markdown-blockquote-borderColor"])!=null?uo:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Fn=t["--persona-components-markdown-blockquote-background"])!=null?Fn:"transparent",t["--persona-md-blockquote-text-color"]=(on=t["--persona-components-markdown-blockquote-textColor"])!=null?on:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Mn=t["--persona-components-collapsibleWidget-container"])!=null?Mn:t["--persona-surface"],t["--cw-surface"]=(vt=t["--persona-components-collapsibleWidget-surface"])!=null?vt:t["--persona-surface"],t["--cw-border"]=(sr=t["--persona-components-collapsibleWidget-border"])!=null?sr:t["--persona-border"],t["--persona-message-border"]=(ir=t["--persona-components-message-border"])!=null?ir:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let m=u==null?void 0:u.labelButton;m&&(m.background&&(t["--persona-label-btn-bg"]=m.background),m.border&&(t["--persona-label-btn-border"]=m.border),m.color&&(t["--persona-label-btn-color"]=m.color),m.padding&&(t["--persona-label-btn-padding"]=m.padding),m.borderRadius&&(t["--persona-label-btn-radius"]=m.borderRadius),m.hoverBackground&&(t["--persona-label-btn-hover-bg"]=m.hoverBackground),m.fontSize&&(t["--persona-label-btn-font-size"]=m.fontSize),m.gap&&(t["--persona-label-btn-gap"]=m.gap));let f=u==null?void 0:u.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let w=u==null?void 0:u.artifact;if(w!=null&&w.toolbar){let he=w.toolbar;he.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,t["--persona-dropdown-bg"]=(an=t["--persona-dropdown-bg"])!=null?an:he.copyMenuBackground),he.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,t["--persona-dropdown-border"]=(fo=t["--persona-dropdown-border"])!=null?fo:he.copyMenuBorder),he.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,t["--persona-dropdown-shadow"]=(yn=t["--persona-dropdown-shadow"])!=null?yn:he.copyMenuShadow),he.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Ln=t["--persona-dropdown-radius"])!=null?Ln:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(sn=t["--persona-dropdown-item-hover-bg"])!=null?sn:he.copyMenuItemHoverBackground),he.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(w!=null&&w.tab){let he=w.tab;he.background&&(t["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(t["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(t["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(t["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(t["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(t["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(t["--persona-artifact-tab-list-padding"]=he.listPadding)}if(w!=null&&w.pane){let he=w.pane;if(he.toolbarBackground){let ln=(q=va(e,he.toolbarBackground))!=null?q:he.toolbarBackground;t["--persona-artifact-toolbar-bg"]=ln}}return t}var jg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var xb={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Gg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bs=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},yb=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":bs()},tp=e=>yb(e),bb=e=>Aa(e),Cb=e=>{var t;let r=Aa(void 0,{validate:!1});return Aa({...e,palette:{...r.palette,colors:{...xb.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Sa=e=>{let r=tp(e),t=Gg(e==null?void 0:e.theme),n=Gg(e==null?void 0:e.darkTheme);return r==="dark"?Cb(ys(t!=null?t:{},n!=null?n:{})):bb(t)},wb=e=>ji(e),vo=(e,r)=>{var a;let t=Sa(r),n=wb(t);for(let[s,i]of Object.entries(n))e.style.setProperty(s,i);let o=(a=r==null?void 0:r.toolCall)==null?void 0:a.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},Gi=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(bs())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(bs());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Xg=(function(){"use strict";let e=()=>{},r={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:m=>m.getAttribute("im-preserve")==="true",shouldReAppend:m=>m.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function t(m,f,w={}){m=u(m);let v=p(f),k=l(m,v,w),T=o(k,()=>i(k,m,v,A=>A.morphStyle==="innerHTML"?(a(A,m,v),Array.from(m.childNodes)):n(A,m,v)));return k.pantry.remove(),T}function n(m,f,w){let v=p(f);return a(m,v,w,f,f.nextSibling),Array.from(v.childNodes)}function o(m,f){var E;if(!m.config.restoreFocus)return f();let w=document.activeElement;if(!(w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement))return f();let{id:v,selectionStart:k,selectionEnd:T}=w,A=f();return v&&v!==((E=document.activeElement)==null?void 0:E.getAttribute("id"))&&(w=m.target.querySelector(`[id="${v}"]`),w==null||w.focus()),w&&!w.selectionEnd&&T&&w.setSelectionRange(k,T),A}let a=(function(){function m(b,h,S,L=null,O=null){h instanceof HTMLTemplateElement&&S instanceof HTMLTemplateElement&&(h=h.content,S=S.content),L||(L=h.firstChild);for(let H of S.childNodes){if(L&&L!=O){let B=w(b,H,L,O);if(B){B!==L&&k(b,L,B),s(B,H,b),L=B.nextSibling;continue}}if(H instanceof Element){let B=H.getAttribute("id");if(b.persistentIds.has(B)){let j=T(h,B,L,b);s(j,H,b),L=j.nextSibling;continue}}let R=f(h,H,L,b);R&&(L=R.nextSibling)}for(;L&&L!=O;){let H=L;L=L.nextSibling,v(b,H)}}function f(b,h,S,L){if(L.callbacks.beforeNodeAdded(h)===!1)return null;if(L.idMap.has(h)){let O=document.createElement(h.tagName);return b.insertBefore(O,S),s(O,h,L),L.callbacks.afterNodeAdded(O),O}else{let O=document.importNode(h,!0);return b.insertBefore(O,S),L.callbacks.afterNodeAdded(O),O}}let w=(function(){function b(L,O,H,R){let B=null,j=O.nextSibling,oe=0,ue=H;for(;ue&&ue!=R;){if(S(ue,O)){if(h(L,ue,O))return ue;B===null&&(L.idMap.has(ue)||(B=ue))}if(B===null&&j&&S(ue,j)&&(oe++,j=j.nextSibling,oe>=2&&(B=void 0)),L.activeElementAndParents.includes(ue))break;ue=ue.nextSibling}return B||null}function h(L,O,H){let R=L.idMap.get(O),B=L.idMap.get(H);if(!B||!R)return!1;for(let j of R)if(B.has(j))return!0;return!1}function S(L,O){var B,j,oe;let H=L,R=O;return H.nodeType===R.nodeType&&H.tagName===R.tagName&&(!((B=H.getAttribute)!=null&&B.call(H,"id"))||((j=H.getAttribute)==null?void 0:j.call(H,"id"))===((oe=R.getAttribute)==null?void 0:oe.call(R,"id")))}return b})();function v(b,h){var S;if(b.idMap.has(h))E(b.pantry,h,null);else{if(b.callbacks.beforeNodeRemoved(h)===!1)return;(S=h.parentNode)==null||S.removeChild(h),b.callbacks.afterNodeRemoved(h)}}function k(b,h,S){let L=h;for(;L&&L!==S;){let O=L;L=L.nextSibling,v(b,O)}return L}function T(b,h,S,L){var H,R;let O=((R=(H=L.target).getAttribute)==null?void 0:R.call(H,"id"))===h&&L.target||L.target.querySelector(`[id="${h}"]`)||L.pantry.querySelector(`[id="${h}"]`);return A(O,L),E(b,O,S),O}function A(b,h){let S=b.getAttribute("id");for(;b=b.parentNode;){let L=h.idMap.get(b);L&&(L.delete(S),L.size||h.idMap.delete(b))}}function E(b,h,S){if(b.moveBefore)try{b.moveBefore(h,S)}catch{b.insertBefore(h,S)}else b.insertBefore(h,S)}return m})(),s=(function(){function m(A,E,b){return b.ignoreActive&&A===document.activeElement?null:(b.callbacks.beforeNodeMorphed(A,E)===!1||(A instanceof HTMLHeadElement&&b.head.ignore||(A instanceof HTMLHeadElement&&b.head.style!=="morph"?d(A,E,b):(f(A,E,b),T(A,b)||a(b,A,E))),b.callbacks.afterNodeMorphed(A,E)),A)}function f(A,E,b){let h=E.nodeType;if(h===1){let S=A,L=E,O=S.attributes,H=L.attributes;for(let R of H)k(R.name,S,"update",b)||S.getAttribute(R.name)!==R.value&&S.setAttribute(R.name,R.value);for(let R=O.length-1;0<=R;R--){let B=O[R];if(B&&!L.hasAttribute(B.name)){if(k(B.name,S,"remove",b))continue;S.removeAttribute(B.name)}}T(S,b)||w(S,L,b)}(h===8||h===3)&&A.nodeValue!==E.nodeValue&&(A.nodeValue=E.nodeValue)}function w(A,E,b){if(A instanceof HTMLInputElement&&E instanceof HTMLInputElement&&E.type!=="file"){let h=E.value,S=A.value;v(A,E,"checked",b),v(A,E,"disabled",b),E.hasAttribute("value")?S!==h&&(k("value",A,"update",b)||(A.setAttribute("value",h),A.value=h)):k("value",A,"remove",b)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&E instanceof HTMLOptionElement)v(A,E,"selected",b);else if(A instanceof HTMLTextAreaElement&&E instanceof HTMLTextAreaElement){let h=E.value,S=A.value;if(k("value",A,"update",b))return;h!==S&&(A.value=h),A.firstChild&&A.firstChild.nodeValue!==h&&(A.firstChild.nodeValue=h)}}function v(A,E,b,h){let S=E[b],L=A[b];if(S!==L){let O=k(b,A,"update",h);O||(A[b]=E[b]),S?O||A.setAttribute(b,""):k(b,A,"remove",h)||A.removeAttribute(b)}}function k(A,E,b,h){return A==="value"&&h.ignoreActiveValue&&E===document.activeElement?!0:h.callbacks.beforeAttributeUpdated(A,E,b)===!1}function T(A,E){return!!E.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return m})();function i(m,f,w,v){if(m.head.block){let k=f.querySelector("head"),T=w.querySelector("head");if(k&&T){let A=d(k,T,m);return Promise.all(A).then(()=>{let E=Object.assign(m,{head:{block:!1,ignore:!0}});return v(E)})}}return v(m)}function d(m,f,w){let v=[],k=[],T=[],A=[],E=new Map;for(let h of f.children)E.set(h.outerHTML,h);for(let h of m.children){let S=E.has(h.outerHTML),L=w.head.shouldReAppend(h),O=w.head.shouldPreserve(h);S||O?L?k.push(h):(E.delete(h.outerHTML),T.push(h)):w.head.style==="append"?L&&(k.push(h),A.push(h)):w.head.shouldRemove(h)!==!1&&k.push(h)}A.push(...E.values());let b=[];for(let h of A){let S=document.createRange().createContextualFragment(h.outerHTML).firstChild;if(w.callbacks.beforeNodeAdded(S)!==!1){if("href"in S&&S.href||"src"in S&&S.src){let L,O=new Promise(function(H){L=H});S.addEventListener("load",function(){L()}),b.push(O)}m.appendChild(S),w.callbacks.afterNodeAdded(S),v.push(S)}}for(let h of k)w.callbacks.beforeNodeRemoved(h)!==!1&&(m.removeChild(h),w.callbacks.afterNodeRemoved(h));return w.head.afterHeadMorphed(m,{added:v,kept:T,removed:k}),b}let l=(function(){function m(b,h,S){let{persistentIds:L,idMap:O}=A(b,h),H=f(S),R=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:b,newContent:h,config:H,morphStyle:R,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:O,persistentIds:L,pantry:w(),activeElementAndParents:v(b),callbacks:H.callbacks,head:H.head}}function f(b){let h=Object.assign({},r);return Object.assign(h,b),h.callbacks=Object.assign({},r.callbacks,b.callbacks),h.head=Object.assign({},r.head,b.head),h}function w(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function v(b){let h=[],S=document.activeElement;if((S==null?void 0:S.tagName)!=="BODY"&&b.contains(S))for(;S&&(h.push(S),S!==b);)S=S.parentElement;return h}function k(b){var S;let h=Array.from(b.querySelectorAll("[id]"));return(S=b.getAttribute)!=null&&S.call(b,"id")&&h.push(b),h}function T(b,h,S,L){for(let O of L){let H=O.getAttribute("id");if(h.has(H)){let R=O;for(;R;){let B=b.get(R);if(B==null&&(B=new Set,b.set(R,B)),B.add(H),R===S)break;R=R.parentElement}}}}function A(b,h){let S=k(b),L=k(h),O=E(S,L),H=new Map;T(H,O,b,S);let R=h.__idiomorphRoot||h;return T(H,O,R,L),{persistentIds:O,idMap:H}}function E(b,h){let S=new Set,L=new Map;for(let{id:H,tagName:R}of b)L.has(H)?S.add(H):L.set(H,R);let O=new Set;for(let{id:H,tagName:R}of h)O.has(H)?S.add(H):L.get(H)===R&&O.add(H);for(let H of S)O.delete(H);return O}return m})(),{normalizeElement:u,normalizeParent:p}=(function(){let m=new WeakSet;function f(T){return T instanceof Document?T.documentElement:T}function w(T){if(T==null)return document.createElement("div");if(typeof T=="string")return w(k(T));if(m.has(T))return T;if(T instanceof Node){if(T.parentNode)return new v(T);{let A=document.createElement("div");return A.append(T),A}}else{let A=document.createElement("div");for(let E of[...T])A.append(E);return A}}class v{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],E=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;E&&E!=this.nextSibling;)A.push(E),E=E.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((E,b)=>{if(b instanceof Element){b.matches(A)&&E.push(b);let h=b.querySelectorAll(A);for(let S=0;S<h.length;S++)E.push(h[S])}return E},[])}insertBefore(A,E){return this.realParentNode.insertBefore(A,E)}moveBefore(A,E){return this.realParentNode.moveBefore(A,E)}get __idiomorphRoot(){return this.originalNode}}function k(T){let A=new DOMParser,E=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(E.match(/<\/html>/)||E.match(/<\/head>/)||E.match(/<\/body>/)){let b=A.parseFromString(T,"text/html");if(E.match(/<\/html>/))return m.add(b),b;{let h=b.firstChild;return h&&m.add(h),h}}else{let h=A.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return m.add(h),h}}return{normalizeElement:f,normalizeParent:w}})();return{morph:t,defaults:r}})();var Xi=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Xg.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,a){var s,i;if(o instanceof HTMLElement&&n){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let d=(s=o.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function Jg(e,r){var t,n,o,a,s,i,d,l,u,p,m,f,w,v,k,T,A,E,b,h,S,L,O,H,R,B,j,oe,ue,De;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(a=(o=e.content)==null?void 0:o.slice(-32))!=null?a:"",e.streaming?"1":"0",(s=e.variant)!=null?s:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(m=(p=e.approval)==null?void 0:p.status)!=null?m:"",(w=(f=e.toolCall)==null?void 0:f.status)!=null?w:"",(k=(v=e.toolCall)==null?void 0:v.name)!=null?k:"",(E=(A=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:A.length)!=null?E:0,(L=(S=(h=(b=e.toolCall)==null?void 0:b.chunks)==null?void 0:h[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?L:"",typeof((O=e.toolCall)==null?void 0:O.args)=="string"?e.toolCall.args.length:(H=e.toolCall)!=null&&H.args?JSON.stringify(e.toolCall.args).length:0,(j=(B=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:B.length)!=null?j:0,(ue=(oe=e.contentParts)==null?void 0:oe.length)!=null?ue:0,(De=e.stopReason)!=null?De:"",r].join("\0")}function Kg(){return new Map}function Yg(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Qg(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Zg(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Ji(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Cs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ws(e,r){return Cs(e)-e.scrollTop<=r}function Ki(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-n;return s||Math.abs(u)<a?{action:"none",delta:u,nextLastScrollTop:t}:!r&&o&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:r&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:r&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Yi(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return r&&t<0?"pause":!r&&o&&t>0&&n?"resume":"none"}var Dr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Or=1e5,Ao=Or+1;var vs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},vb=["pre","code","a","script","style"],Qi=e=>{var r,t,n,o,a;return{type:(r=e==null?void 0:e.type)!=null?r:vs.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:vs.placeholder,speed:(n=e==null?void 0:e.speed)!=null?n:vs.speed,duration:(o=e==null?void 0:e.duration)!=null?o:vs.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:vs.buffer}},th=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],As=new Map;for(let e of th)As.set(e.name,e);var ra=e=>{As.set(e.name,e)},op=e=>{th.some(r=>r.name===e)||As.delete(e)},ap=()=>Array.from(As.keys()),Ss=(e,r)=>{var t,n;return e==="none"?null:r&&Object.prototype.hasOwnProperty.call(r,e)?(t=r[e])!=null?t:null:(n=As.get(e))!=null?n:null},Zi=(e,r,t,n,o)=>{if(!o)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,n);if(!e)return e;if(r==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(r==="line"){let a=e.lastIndexOf(`
|
|
55
|
+
`);return a<0?"":e.slice(0,a)}return e},Ab=(e,r,t,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=r,o},Sb=(e,r,t,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=r,o},rp=/\s/,Tb=(e,r)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let n=t;if(r.has(n.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},kb=(e,r,t)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=(d=e.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(rp.test(a[i])){let l=i;for(;l<a.length&&rp.test(a[l]);)l+=1;s.appendChild(n.createTextNode(a.slice(i,l))),i=l}else{let l=n.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<a.length&&!rp.test(a[u]);)l.appendChild(Ab(n,a[u],r,t.value)),t.value+=1,u+=1;s.appendChild(l),i=u}o.replaceChild(s,e)},Eb=(e,r,t)=>{var d;let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=(d=e.nodeValue)!=null?d:"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(n.createTextNode(l)):(s.appendChild(Sb(n,l,r,t.value)),t.value+=1));o.replaceChild(s,e)},Ts=(e,r,t,n)=>{var p,m;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set(((p=n==null?void 0:n.skipTags)!=null?p:vb).map(f=>f.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=s.nextNode();for(;d;)Tb(d,a)||i.push(d),d=s.nextNode();let l={value:(m=n==null?void 0:n.startIndex)!=null?m:0},u=r==="char"?kb:Eb;for(let f of i)u(f,t,l);return o.innerHTML},el=(e=document)=>{let r=e.createElement("span");return r.className="persona-stream-caret",r.setAttribute("aria-hidden","true"),r.setAttribute("data-preserve-animation","stream-caret"),r},ks=(e=document)=>{let r=e.createElement("div");r.className="persona-stream-skeleton",r.setAttribute("data-preserve-animation","stream-skeleton"),r.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",r.appendChild(t),r},eh=new WeakMap,Mb=(e,r)=>{var a;if(!e.styles)return;let t=eh.get(r);if(t||(t=new Set,eh.set(r,t)),t.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(r.querySelector(`style[data-persona-animation="${s}"]`))return;t.delete(e.name)}t.add(e.name);let o=(r instanceof ShadowRoot?r.ownerDocument:(a=r.ownerDocument)!=null?a:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,r.appendChild(o)},np=new WeakMap,Lb=(e,r)=>{if(!e.onAttach)return;let t=np.get(r);if(t||(t=new Map,np.set(r,t)),t.has(e.name))return;let n=e.onAttach(r);t.set(e.name,n)},rh=e=>{let r=np.get(e);if(r){for(let t of r.values())typeof t=="function"&&t();r.clear()}},sp=(e,r)=>{Mb(e,r),Lb(e,r)};function ip(e,r=Or){let t=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{s&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=o}}var Es=0,So=null;function lp(e=document){var t;if(Es++,Es===1){let n=e.body,a=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;So={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:a},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${a}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Es=Math.max(0,Es-1),Es===0&&So)){let o=e.body,a=(n=e.defaultView)!=null?n:window;o.style.overflow=So.originalOverflow,o.style.position=So.originalPosition,o.style.top=So.originalTop,o.style.width=So.originalWidth,a.scrollTo(0,So.scrollY),So=null}}}var tl={side:"right",width:"420px",animate:!0,reveal:"resize"},hr=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},To=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="composer-bar"},vn=e=>{var t,n,o,a,s;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:tl.side,width:(o=r==null?void 0:r.width)!=null?o:tl.width,animate:(a=r==null?void 0:r.animate)!=null?a:tl.animate,reveal:(s=r==null?void 0:r.reveal)!=null?s:tl.reveal}};var On={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Ms=(e,r)=>{let t=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 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
|
-
`):""},
|
|
65
|
-
`);let
|
|
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=`
|
|
63
|
+
`,t.addEventListener("click",r);let n=a=>{var E,b,h,S,L,O,H,R,B,j,oe,ue,De,Xe;let s=(E=a.launcher)!=null?E:{},i=hr(a),d=t.querySelector("[data-role='launcher-title']");if(d){let xe=(b=s.title)!=null?b:"Chat Assistant";d.textContent=xe,d.setAttribute("title",xe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let xe=(h=s.subtitle)!=null?h:"Get answers fast";l.textContent=xe,l.setAttribute("title",xe)}let u=t.querySelector(".persona-flex-col");u&&(s.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(s.agentIconHidden)p.style.display="none";else{let xe=(S=s.agentIconSize)!=null?S:"40px";if(p.style.height=xe,p.style.width=xe,p.innerHTML="",s.agentIconName){let ge=parseFloat(xe)||24,Le=Ce(s.agentIconName,ge*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(p.appendChild(Le),p.style.display=""):(p.textContent=(L=s.agentIconText)!=null?L:"\u{1F4AC}",p.style.display="")}else s.iconUrl?p.style.display="none":(p.textContent=(O=s.agentIconText)!=null?O:"\u{1F4AC}",p.style.display="")}let m=t.querySelector("[data-role='launcher-image']");if(m){let xe=(H=s.agentIconSize)!=null?H:"40px";m.style.height=xe,m.style.width=xe,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(m.src=s.iconUrl,m.style.display="block"):m.style.display="none"}let f=t.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let xe=(R=s.callToActionIconSize)!=null?R:"32px";f.style.height=xe,f.style.width=xe,s.callToActionIconBackgroundColor?(f.style.backgroundColor=s.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(f.style.color=s.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let ge=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,ge=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",s.callToActionIconName){let Le=parseFloat(xe)||24,Ge=Math.max(Le-ge,8),Q=Ce(s.callToActionIconName,Ge,"currentColor",2);Q?f.appendChild(Q):f.textContent=(B=s.callToActionIconText)!=null?B:"\u2197"}else f.textContent=(j=s.callToActionIconText)!=null?j:"\u2197"}let w=s.position&&On[s.position]?On[s.position]:On["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?k:`${v} ${w}`,i||(t.style.zIndex=String((oe=s.zIndex)!=null?oe:Or));let T="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(ue=s.border)!=null?ue:T,t.style.boxShadow=(De=s.shadow)!=null?De:A,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Xe=s.collapsedMaxWidth)!=null?Xe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:o}};var Pb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",rl=(e,r={})=>{var v,k,T,A,E,b;let{showClose:t=!0,wrapperClassName:n=Pb,buttonSize:o,iconSize:a="28px"}=r,s=(v=e==null?void 0:e.launcher)!=null?v:{},i=(k=o!=null?o:s.closeButtonSize)!=null?k:"32px",d=x("div",n),l=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(T=s.closeButtonTooltipText)!=null?T:"Close chat",p=(A=s.closeButtonShowTooltip)!=null?A:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let m=(E=s.closeButtonIconName)!=null?E:"x",f=(b=s.closeButtonIconText)!=null?b:"\xD7";l.style.color=s.closeButtonColor||Kr.actionIconColor;let w=Ce(m,a,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=f,s.closeButtonBackgroundColor?(l.style.backgroundColor=s.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let h=s.closeButtonBorderWidth||"0px",S=s.closeButtonBorderColor||"transparent";l.style.border=`${h} solid ${S}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(l.style.borderRadius=s.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(l.style.paddingLeft=s.closeButtonPaddingX,l.style.paddingRight=s.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),s.closeButtonPaddingY?(l.style.paddingTop=s.closeButtonPaddingY,l.style.paddingBottom=s.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let h=null,S=()=>{if(h)return;let O=l.ownerDocument,H=O.body;if(!H)return;h=qn(O,"div","persona-clear-chat-tooltip"),h.textContent=u;let R=qn(O,"div");R.className="persona-clear-chat-tooltip-arrow",h.appendChild(R);let B=l.getBoundingClientRect();h.style.position="fixed",h.style.zIndex=String(Ao),h.style.left=`${B.left+B.width/2}px`,h.style.top=`${B.top-8}px`,h.style.transform="translate(-50%, -100%)",H.appendChild(h)},L=()=>{h&&h.parentNode&&(h.parentNode.removeChild(h),h=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",L),l.addEventListener("focus",S),l.addEventListener("blur",L),d._cleanupTooltip=()=>{L(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",L),l.removeEventListener("focus",S),l.removeEventListener("blur",L)}}return{button:l,wrapper:d}},Ib="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",nl=(e,r={})=>{var h,S,L,O,H,R,B,j,oe,ue,De,Xe,xe;let{wrapperClassName:t=Ib,buttonSize:n,iconSize:o="20px"}=r,s=(S=((h=e==null?void 0:e.launcher)!=null?h:{}).clearChat)!=null?S:{},i=(L=n!=null?n:s.size)!=null?L:"32px",d=(O=s.iconName)!=null?O:"refresh-cw",l=(H=s.iconColor)!=null?H:"",u=(R=s.backgroundColor)!=null?R:"",p=(B=s.borderWidth)!=null?B:"",m=(j=s.borderColor)!=null?j:"",f=(oe=s.borderRadius)!=null?oe:"",w=(ue=s.paddingX)!=null?ue:"",v=(De=s.paddingY)!=null?De:"",k=(Xe=s.tooltipText)!=null?Xe:"Clear chat",T=(xe=s.showTooltip)!=null?xe:!0,A=x("div",t),E=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");E.style.height=i,E.style.width=i,E.type="button",E.setAttribute("aria-label",k),E.style.color=l||Kr.actionIconColor;let b=Ce(d,o,"currentColor",1);if(b&&(b.style.display="block",E.appendChild(b)),u&&(E.style.backgroundColor=u,E.classList.remove("hover:persona-bg-gray-100")),p||m){let ge=p||"0px",Le=m||"transparent";E.style.border=`${ge} solid ${Le}`,E.classList.remove("persona-border-none")}if(f&&(E.style.borderRadius=f,E.classList.remove("persona-rounded-full")),w&&(E.style.paddingLeft=w,E.style.paddingRight=w),v&&(E.style.paddingTop=v,E.style.paddingBottom=v),A.appendChild(E),T&&k){let ge=null,Le=()=>{if(ge)return;let Q=E.ownerDocument,Se=Q.body;if(!Se)return;ge=qn(Q,"div","persona-clear-chat-tooltip"),ge.textContent=k;let J=qn(Q,"div");J.className="persona-clear-chat-tooltip-arrow",ge.appendChild(J);let ce=E.getBoundingClientRect();ge.style.position="fixed",ge.style.zIndex=String(Ao),ge.style.left=`${ce.left+ce.width/2}px`,ge.style.top=`${ce.top-8}px`,ge.style.transform="translate(-50%, -100%)",Se.appendChild(ge)},Ge=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};A.addEventListener("mouseenter",Le),A.addEventListener("mouseleave",Ge),E.addEventListener("focus",Le),E.addEventListener("blur",Ge),A._cleanupTooltip=()=>{Ge(),A.removeEventListener("mouseenter",Le),A.removeEventListener("mouseleave",Ge),E.removeEventListener("focus",Le),E.removeEventListener("blur",Ge)}}return{button:E,wrapper:A}};var Kr={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ao=e=>{var h,S,L,O,H,R,B,j,oe,ue,De,Xe,xe,ge,Le,Ge;let{config:r,showClose:t=!0}=e,n=x("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(h=r==null?void 0:r.launcher)!=null?h:{},a=(S=o.headerIconSize)!=null?S:"48px",s=(L=o.closeButtonPlacement)!=null?L:"inline",i=(O=o.headerIconHidden)!=null?O:!1,d=o.headerIconName,l=x("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=a,l.style.width=a,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let Q=parseFloat(a)||24,Se=Ce(d,Q*.6,"currentColor",1);Se?l.replaceChildren(Se):l.textContent=(R=(H=r==null?void 0:r.launcher)==null?void 0:H.agentIconText)!=null?R:"\u{1F4AC}"}else if((B=r==null?void 0:r.launcher)!=null&&B.iconUrl){let Q=x("img");Q.src=r.launcher.iconUrl,Q.alt="",Q.className="persona-rounded-xl persona-object-cover",Q.style.height=a,Q.style.width=a,l.replaceChildren(Q)}else l.textContent=(oe=(j=r==null?void 0:r.launcher)==null?void 0:j.agentIconText)!=null?oe:"\u{1F4AC}";let u=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=x("span","persona-text-base persona-font-semibold");p.style.color=Kr.titleColor,p.textContent=(De=(ue=r==null?void 0:r.launcher)==null?void 0:ue.title)!=null?De:"Chat Assistant";let m=x("span","persona-text-xs");m.style.color=Kr.subtitleColor,m.textContent=(xe=(Xe=r==null?void 0:r.launcher)==null?void 0:Xe.subtitle)!=null?xe:"Here to help you get answers fast",u.append(p,m),i?n.append(u):n.append(l,u);let f=(ge=o.clearChat)!=null?ge:{},w=(Le=f.enabled)!=null?Le:!0,v=(Ge=f.placement)!=null?Ge:"inline",k=null,T=null;if(w){let Se=nl(r,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=Se.button,T=Se.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&n.appendChild(T)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:E,wrapper:b}=rl(r,{showClose:t,wrapperClassName:A});return s!=="top-right"&&n.appendChild(b),{header:n,iconHolder:l,headerTitle:p,headerSubtitle:m,closeButton:E,closeButtonWrapper:b,clearChatButton:k,clearChatButtonWrapper:T}},na=(e,r,t)=>{var s,i,d,l;let n=(s=t==null?void 0:t.launcher)!=null?s:{},o=(i=n.closeButtonPlacement)!=null?i:"inline",a=(l=(d=n.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(r.header),o==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function ko(e){let{items:r,onSelect:t,anchor:n,position:o="bottom-left",portal:a}=e,s=x("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Ao)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",o==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of r){if(f.dividerBefore){let k=document.createElement("hr");s.appendChild(k)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",f.id),f.destructive&&w.setAttribute("data-destructive",""),f.icon){let k=Ce(f.icon,16,"currentColor",1.5);k&&w.appendChild(k)}let v=document.createElement("span");v.textContent=f.label,w.appendChild(v),w.addEventListener("click",k=>{k.stopPropagation(),u(),t(f.id)}),s.appendChild(w)}let i=null;function d(){if(!a)return;let f=n.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,o==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function l(){d(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=w=>{!s.contains(w.target)&&!n.contains(w.target)&&u()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function u(){s.classList.add("persona-hidden"),i==null||i(),i=null}function p(){s.classList.contains("persona-hidden")?l():u()}function m(){u(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:u,toggle:p,destroy:m}}function Qt(e){let{icon:r,label:t,size:n,strokeWidth:o,className:a,onClick:s,aria:i}=e,d=x("button","persona-icon-btn"+(a?" "+a:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=Ce(r,n!=null?n:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),s&&d.addEventListener("click",s),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ls(e){let{icon:r,label:t,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:d}=e,l="persona-label-btn";n!=="default"&&(l+=" persona-label-btn--"+n),l+=" persona-label-btn--"+o,s&&(l+=" "+s);let u=x("button",l);if(u.type="button",u.setAttribute("aria-label",t),r){let m=Ce(r,a!=null?a:14,"currentColor",2);m&&u.appendChild(m)}let p=x("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[m,f]of Object.entries(d))u.setAttribute(m,f);return u}function Ps(e){let{items:r,selectedId:t,onSelect:n,className:o}=e,a=x("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===s?"true":"false")}for(let u of r){let p;u.icon?p=Qt({icon:u.icon,label:u.label,onClick:()=>{s=u.id,d(),n(u.id)}}):(p=x("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{s=u.id,d(),n(u.id)})),p.setAttribute("aria-pressed",u.id===s?"true":"false"),i.push({id:u.id,btn:p}),a.appendChild(p)}function l(u){s=u,d()}return{element:a,setSelected:l}}function ol(e){var f,w;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:d}=e,l=x("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",r);let u=x("span","persona-combo-btn-label");u.textContent=r,l.appendChild(u);let p=Ce(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,k;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(k=d.border)!=null?k:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let m=ko({items:n,onSelect:v=>{l.setAttribute("aria-expanded","false"),o(v)},anchor:l,position:a,portal:s});return s||l.appendChild(m.element),l.addEventListener("click",v=>{v.stopPropagation();let k=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",k?"false":"true"),m.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{u.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),m.show()},close:()=>{l.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let v=!m.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),l.remove()}}}var dp=e=>{var n;let r=ao({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let o=r.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),t())}))}return r};function Rb(e,r,t){var n,o,a;if(r!=null&&r.length)for(let s of r){let i=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(n=s.ariaLabel)!=null?n:s.label)!=null?o:s.id),s.icon){let d=Ce(s.icon,14,"currentColor",2);d&&i.appendChild(d)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let d=x("div","persona-relative");d.appendChild(i);let l=ko({items:s.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(s.id)),e.appendChild(i)}}var cp=e=>{var A,E,b,h,S,L,O,H,R;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=(A=r==null?void 0:r.launcher)!=null?A:{},i=x("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,u;if(d)l=ol({label:(E=s.title)!=null?E:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Kr.titleColor,u=(b=l.querySelector(".persona-combo-btn-label"))!=null?b:l;else{if(l=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=x("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Kr.titleColor,u.textContent=(h=s.title)!=null?h:"Chat Assistant",l.appendChild(u),Rb(l,o==null?void 0:o.trailingActions,(S=o==null?void 0:o.onAction)!=null?S:a),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let j=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||j()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),j())})}let B=o==null?void 0:o.titleRowHover;B&&(l.style.borderRadius=(L=B.borderRadius)!=null?L:"10px",l.style.padding=(O=B.padding)!=null?O:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var j,oe;l.style.backgroundColor=(j=B.background)!=null?j:"",l.style.borderColor=(oe=B.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(H=s.closeButtonSize)!=null?H:"32px",m=x("div",""),f=x("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=p,f.style.width=p,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=t?"":"none",f.style.color=s.closeButtonColor||Kr.actionIconColor;let w=(R=s.closeButtonIconName)!=null?R:"x",v=Ce(w,"28px","currentColor",1);v?f.appendChild(v):f.textContent="\xD7",n&&f.addEventListener("click",n),m.appendChild(f),i.appendChild(m);let k=x("div");k.style.display="none";let T=x("span");return T.style.display="none",{header:i,iconHolder:k,headerTitle:u,headerSubtitle:T,closeButton:f,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}},al={default:dp,minimal:cp},pp=e=>{var r;return(r=al[e])!=null?r:al.default},Ta=(e,r,t)=>{var s,i,d;if(r!=null&&r.render){let l=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),u=x("div");u.style.display="none";let p=x("span"),m=x("span"),f=x("button");f.style.display="none";let w=x("div");return w.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:m,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let n=(s=r==null?void 0:r.layout)!=null?s:"default",a=pp(n)({config:e,showClose:(d=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(a.iconHolder.style.display="none"),r.showTitle===!1&&(a.headerTitle.style.display="none"),r.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(a.closeButton.style.display="none"),r.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var sl=e=>{var s,i;let r=x("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",r.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,n=20;r.style.maxHeight=`${t*n}px`,r.style.overflowY="auto";let o=()=>{let d=parseFloat(r.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*n},a=()=>{r.addEventListener("input",()=>{r.style.height="auto";let d=Math.min(r.scrollHeight,o());r.style.height=`${d}px`})};return r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:a}},il=e=>{var h,S,L,O,H,R,B,j,oe,ue,De,Xe;let r=(h=e==null?void 0:e.sendButton)!=null?h:{},t=(S=r.useIcon)!=null?S:!1,n=(L=r.iconText)!=null?L:"\u2191",o=r.iconName,a=(O=r.stopIconName)!=null?O:"square",s=(H=r.tooltipText)!=null?H:"Send message",i=(R=r.stopTooltipText)!=null?R:"Stop generating",d=(j=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?j:"Send",l=(ue=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?ue:"Stop",u=(De=r.showTooltip)!=null?De:!1,p=(Xe=r.size)!=null?Xe:"40px",m=r.backgroundColor,f=r.textColor,w=x("div","persona-send-button-wrapper"),v=x("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let k=null,T=null;if(t){v.style.width=p,v.style.height=p,v.style.minWidth=p,v.style.minHeight=p,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",f?v.style.color=f:v.style.color="var(--persona-button-primary-fg, #ffffff)";let xe=parseFloat(p)||24,ge=(f==null?void 0:f.trim())||"currentColor";o?(k=Ce(o,xe,ge,2),k?v.appendChild(k):v.textContent=n):v.textContent=n,T=Ce(a,xe,ge,2),m?v.style.backgroundColor=m:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,f?v.style.color=f:v.classList.add("persona-text-white");r.borderWidth&&(v.style.borderWidth=r.borderWidth,v.style.borderStyle="solid"),r.borderColor&&(v.style.borderColor=r.borderColor),r.paddingX?(v.style.paddingLeft=r.paddingX,v.style.paddingRight=r.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.paddingY?(v.style.paddingTop=r.paddingY,v.style.paddingBottom=r.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let A=null;u&&s&&(A=x("div","persona-send-button-tooltip"),A.textContent=s,w.appendChild(A)),v.setAttribute("aria-label",s),w.appendChild(v);let E="send";return{button:v,wrapper:w,setMode:xe=>{if(xe===E)return;E=xe;let ge=xe==="stop"?i:s;if(v.setAttribute("aria-label",ge),A&&(A.textContent=ge),t){if(k&&T){let Le=xe==="stop"?T:k,Ge=xe==="stop"?k:T;Ge.parentNode===v?v.replaceChild(Le,Ge):v.appendChild(Le)}}else v.textContent=xe==="stop"?l:d}}},ll=e=>{var A,E,b,h,S,L,O,H,R,B,j,oe;let r=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(r.enabled===!0))return null;let n=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((E=r.provider)==null?void 0:E.type)==="runtype";if(!(n||o))return null;let s=(h=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?h:"40px",i=x("div","persona-send-button-wrapper"),d=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(S=r.iconName)!=null?S:"mic",u=(L=r.iconSize)!=null?L:s,p=parseFloat(u)||24,m=(H=r.backgroundColor)!=null?H:(O=e==null?void 0:e.sendButton)==null?void 0:O.backgroundColor,f=(B=r.iconColor)!=null?B:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",f?d.style.color=f:d.style.color="var(--persona-text, #111827)";let v=Ce(l,p,f||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",m&&(d.style.backgroundColor=m),r.borderWidth&&(d.style.borderWidth=r.borderWidth,d.style.borderStyle="solid"),r.borderColor&&(d.style.borderColor=r.borderColor),r.paddingX&&(d.style.paddingLeft=r.paddingX,d.style.paddingRight=r.paddingX),r.paddingY&&(d.style.paddingTop=r.paddingY,d.style.paddingBottom=r.paddingY),i.appendChild(d);let k=(j=r.tooltipText)!=null?j:"Start voice recognition";if(((oe=r.showTooltip)!=null?oe:!1)&&k){let ue=x("div","persona-send-button-tooltip");ue.textContent=k,i.appendChild(ue)}return{button:d,wrapper:i}},dl=e=>{var w,v,k,T,A,E,b,h;let r=(w=e==null?void 0:e.attachments)!=null?w:{};if(r.enabled!==!0)return null;let t=(k=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?k:"40px",n=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.style.display="none";let o=x("input");o.type="file",o.accept=((T=r.allowedTypes)!=null?T:oo).join(","),o.multiple=((A=r.maxFiles)!=null?A:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let a=x("div","persona-send-button-wrapper"),s=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");s.type="button",s.setAttribute("aria-label",(E=r.buttonTooltipText)!=null?E:"Attach file");let i=(b=r.buttonIconName)!=null?b:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);s.style.width=d,s.style.height=d,s.style.minWidth=d,s.style.minHeight=d,s.style.fontSize="18px",s.style.lineHeight="1",s.style.backgroundColor="transparent",s.style.color="var(--persona-primary, #111827)",s.style.border="none",s.style.borderRadius="6px",s.style.transition="background-color 0.15s ease",s.addEventListener("mouseenter",()=>{s.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),s.addEventListener("mouseleave",()=>{s.style.backgroundColor="transparent"});let p=Ce(i,u,"currentColor",1.5);p?s.appendChild(p):s.textContent="\u{1F4CE}",s.addEventListener("click",S=>{S.preventDefault(),o.click()}),a.appendChild(s);let m=(h=r.buttonTooltipText)!=null?h:"Attach file",f=x("div","persona-send-button-tooltip");return f.textContent=m,a.appendChild(f),{button:s,wrapper:a,input:o,previewsContainer:n}},cl=e=>{var s,i,d;let r=(s=e==null?void 0:e.statusIndicator)!=null?s:{},t=r.align==="left"?"persona-text-left":r.align==="center"?"persona-text-center":"persona-text-right",n=x("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let o=(i=r.visible)!=null?i:!0;n.style.display=o?"":"none";let a=(d=r.idleText)!=null?d:"Online";if(r.idleLink){let l=x("a");l.href=r.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",n.appendChild(l)}else n.textContent=a;return n},pl=()=>x("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ka=e=>{var w,v,k,T,A,E;let{config:r}=e,t=x("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=pl(),o=x("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:a,attachAutoResize:s}=sl(r);s();let i=il(r),d=ll(r),l=dl(r),u=cl(r);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(a);let p=x("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),m=x("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=x("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&m.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),p.append(m,f),o.append(p),o.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.target!==(l==null?void 0:l.wrapper)&&a.focus()}),t.append(n,o,u),{footer:t,suggestions:n,composerForm:o,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:p,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var nh=()=>{let e=x("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let r=x("span","persona-pill-peek__icon"),t=Ce("message-square",16,"currentColor",1.5);t&&r.appendChild(t);let n=x("span","persona-pill-peek__text"),o=x("span","persona-pill-peek__caret"),a=Ce("chevron-up",16,"currentColor",1.5);return a&&o.appendChild(a),e.append(r,n,o),{root:e,textNode:n}},oh=e=>{var w,v,k,T,A,E;let{config:r}=e,t=x("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let n=pl();n.style.display="none";let o=cl(r);o.style.display="none";let{textarea:a,attachAutoResize:s}=sl(r);a.style.maxHeight="100px",s();let i=il(r),d=ll(r),l=dl(r);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=x("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=x("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let m=x("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&m.append(d.wrapper),m.append(i.wrapper),u.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==(d==null?void 0:d.button)&&b.target!==(d==null?void 0:d.wrapper)&&b.target!==(l==null?void 0:l.button)&&b.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&u.append(l.input),u.append(p,a,m),l&&t.append(l.previewsContainer),t.append(u,n,o);let f=u;return{footer:t,suggestions:n,composerForm:u,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(k=l==null?void 0:l.button)!=null?k:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(E=l==null?void 0:l.previewsContainer)!=null?E:null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:i.setMode}};var ah=e=>{var u,p,m,f,w,v,k,T,A,E,b,h,S,L,O,H,R;let r=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=hr(e);if(To(e)){let B=(f=(m=e==null?void 0:e.launcher)==null?void 0:m.composerBar)!=null?f:{},j=x("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(w=B.expandedSize)!=null?w:"anchored",j.style.zIndex=String((k=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?k:Or);let oe=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",j.appendChild(oe);let ue=x("div","persona-widget-pill-root");return ue.setAttribute("data-persona-composer-bar",""),ue.dataset.state="collapsed",ue.dataset.expandedSize=(T=B.expandedSize)!=null?T:"anchored",ue.style.zIndex=String((E=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?E:Or),{wrapper:j,panel:oe,pillRoot:ue}}if(t){let B=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return B.appendChild(j),{wrapper:B,panel:j}}if(!r){let B=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(h=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?h:"100%";return B.style.width=oe,j.style.width="100%",B.appendChild(j),{wrapper:B,panel:j}}let o=(S=e==null?void 0:e.launcher)!=null?S:{},a=o.position&&On[o.position]?On[o.position]:On["bottom-right"],s=x("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((O=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?O:Or);let i=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?R:e==null?void 0:e.launcherWidth,l=d!=null?d:mn;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},Hb=(e,r)=>{var b,h,S,L,O,H,R,B,j;let t=x("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=rl(e,{showClose:r,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=(S=(h=(b=e==null?void 0:e.launcher)==null?void 0:b.clearChat)==null?void 0:h.enabled)!=null?S:!0,s=null,i=null;if(a){let oe=nl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=x("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=x("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=x("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=x("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(O=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?O:"Hello \u{1F44B}";let m=x("p","persona-mt-2 persona-text-sm persona-text-persona-muted");m.textContent=(R=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",u.append(p,m);let f=x("div","persona-flex persona-flex-col persona-gap-3"),w=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;w&&(f.style.maxWidth=w,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((j=e==null?void 0:e.copy)==null?void 0:j.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,f);let k=x("div","persona-composer-overlay persona-pointer-events-none");k.setAttribute("data-persona-composer-overlay",""),k.style.position="absolute",k.style.left="0",k.style.right="0",k.style.bottom="0",k.style.zIndex="20";let T=oh({config:e}),{root:A,textNode:E}=nh();return t.append(d,o,l,k),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:f,composerOverlay:k,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:m,closeButton:n,closeButtonWrapper:o,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:A,peekTextNode:E}},sh=(e,r=!0)=>{var k,T,A,E,b,h,S,L,O;if(To(e))return Hb(e,r);let t=x("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(k=e==null?void 0:e.layout)==null?void 0:k.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,a=n?Ta(e,n,{showClose:r}):ao({config:e,showClose:r}),s=x("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");s.id="persona-scroll-container",s.setAttribute("data-persona-theme-zone","messages");let i=x("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=hr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=x("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(E=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?E:"Hello \u{1F44B}";let l=x("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(h=(b=e==null?void 0:e.copy)==null?void 0:b.welcomeSubtitle)!=null?h:"Ask anything about your account or products.",i.append(d,l);let u=x("div","persona-flex persona-flex-col persona-gap-3"),p=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((L=e==null?void 0:e.copy)==null?void 0:L.showWelcomeCard)!==!1||(i.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(i,u);let f=ka({config:e}),w=((O=e==null?void 0:e.layout)==null?void 0:O.showFooter)!==!1;o?na(t,a,e):(a.header.style.display="none",na(t,a,e)),t.append(s);let v=x("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",w||(f.footer.style.display="none"),t.append(f.footer),t.append(v),{container:t,body:s,messagesWrapper:u,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:d,introSubtitle:l,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Bb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Wb=(e,r)=>{if(!e)return null;let t=Bb(e);if(t===null)return null;let n=r==null?void 0:r[e],o=n!==void 0?n:t;return o||null},Db=(e,r)=>{let t=x("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=r,t},Ob=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},up=e=>{let r=e.toLowerCase();return r.startsWith("javascript:")||r.startsWith("data:text/html")||r.startsWith("data:text/javascript")||r.startsWith("data:text/xml")||r.startsWith("data:application/xhtml")||r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:")||!e.includes(":"))},fp=320,lh=320,Fb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="audio"&&typeof r.audio=="string"&&r.audio.trim().length>0),_b=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="video"&&typeof r.video=="string"&&r.video.trim().length>0),$b=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="file"&&typeof r.data=="string"&&r.data.trim().length>0),Ub=(e,r,t)=>{if(e.length===0)return null;try{let n=x("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=x("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${fp}px`,l.style.maxHeight=`${lh}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,l.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),l.remove(),o===0&&s())}),l.addEventListener("load",()=>{u=!0}),Ob(i.image)?(l.src=i.image,n.appendChild(l)):(u=!0,o=Math.max(0,o-1),l.remove())}),o===0?(s(),null):n}catch{return t==null||t(),null}},qb=e=>{if(e.length===0)return null;try{let r=x("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(n=>{if(!up(n.audio))return;let o=x("audio");o.controls=!0,o.preload="metadata",o.src=n.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${fp}px`,r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},zb=e=>{if(e.length===0)return null;try{let r=x("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","video");let t=0;return e.forEach(n=>{if(!up(n.video))return;let o=x("video");o.controls=!0,o.preload="metadata",o.src=n.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${fp}px`,o.style.maxHeight=`${lh}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},Vb=e=>{if(e.length===0)return null;try{let r=x("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","files");let t=0;return e.forEach(n=>{if(!up(n.data))return;let o=x("a");o.href=n.data,o.download=n.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=n.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",r.appendChild(o),t+=1}),t===0?(r.remove(),null):r}catch{return null}},oa=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(o),e},mp=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:oa};if(r){let o=r(n);if(o!==null)return o}return oa()},jb=(e,r)=>{let t=x("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let o=x("img");o.src=n,o.alt=r==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},ih=(e,r)=>{let t=x("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Gb=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},gp=(e,r,t)=>{var f,w,v,k,T,A;let n=(f=r.showCopy)!=null?f:!0,o=(w=r.showUpvote)!=null?w:!0,a=(v=r.showDownvote)!=null?v:!0;if(!n&&!o&&!a){let E=x("div");return E.style.display="none",E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id),E}let s=(k=r.visibility)!=null?k:"hover",i=(T=r.align)!=null?T:"right",d=(A=r.layout)!=null?A:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${s==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=(E,b,h)=>{let S=Qt({icon:E,label:b,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",h),S};return n&&p.appendChild(m("copy","Copy message","copy")),o&&p.appendChild(m("thumbs-up","Upvote","upvote")),a&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},Ea=(e,r,t,n,o,a)=>{var Q,Se,J,ce,pe,ie,Oe,Pe,K,_e,$e,Y,G,we,ke,ae,ve;let s=t!=null?t:{},i=(Q=s.layout)!=null?Q:"bubble",d=s.avatar,l=s.timestamp,u=(Se=d==null?void 0:d.show)!=null?Se:!1,p=(J=l==null?void 0:l.show)!=null?J:!1,m=(ce=d==null?void 0:d.position)!=null?ce:"left",f=(pe=l==null?void 0:l.position)!=null?pe:"below",w=Gb(e.role,i),v=x("div",w.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=Fb(e),T=(Oe=(ie=e.content)==null?void 0:ie.trim())!=null?Oe:"",E=k.length>0&&T===Ei,b=Qi((K=(Pe=a==null?void 0:a.widgetConfig)==null?void 0:Pe.features)==null?void 0:K.streamAnimation),h=(Y=($e=(_e=a==null?void 0:a.widgetConfig)==null?void 0:_e.features)==null?void 0:$e.streamAnimation)==null?void 0:Y.plugins,S=e.role==="assistant"&&b.type!=="none"?Ss(b.type,h):null,L=e.role==="assistant"&&((G=S==null?void 0:S.isAnimating)==null?void 0:G.call(S,e))===!0,O=e.role==="assistant"&&S!==null&&(!!e.streaming||L);O&&(S!=null&&S.bubbleClass)&&v.classList.add(S.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),O&&S&&(S.containerClass&&H.classList.add(S.containerClass),H.style.setProperty("--persona-stream-step",`${b.speed}ms`),H.style.setProperty("--persona-stream-duration",`${b.duration}ms`));let R=O?Zi((we=e.content)!=null?we:"",b.buffer,S,e,!!e.streaming):(ke=e.content)!=null?ke:"",B=r({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),j=B;O&&(S==null?void 0:S.wrap)==="char"?j=Ts(B,"char",e.id,{skipTags:S.skipTags}):O&&(S==null?void 0:S.wrap)==="word"&&(j=Ts(B,"word",e.id,{skipTags:S.skipTags}));let oe=null;if(E?(oe=document.createElement("div"),oe.innerHTML=j,oe.style.display="none",H.appendChild(oe)):H.innerHTML=j,O&&(S!=null&&S.useCaret)&&!E&&T){let ye=el(),Mt=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ne=Mt[Mt.length-1];if(ne!=null&&ne.parentNode)ne.parentNode.insertBefore(ye,ne.nextSibling);else{let He=H.lastElementChild;He?He.appendChild(ye):H.appendChild(ye)}}if(p&&f==="inline"&&e.createdAt){let ye=ih(e,l);ye.classList.add("persona-ml-2","persona-inline"),H.appendChild(ye)}if(k.length>0){let ye=Ub(k,!E&&!!T,()=>{E&&oe&&(oe.style.display="")});ye?v.appendChild(ye):E&&oe&&(oe.style.display="")}let ue=Nb(e);if(ue.length>0){let ye=qb(ue);ye&&v.appendChild(ye)}let De=_b(e);if(De.length>0){let ye=zb(De);ye&&v.appendChild(ye)}let Xe=$b(e);if(Xe.length>0){let ye=Vb(Xe);ye&&v.appendChild(ye)}if(v.appendChild(H),p&&f==="below"&&e.createdAt){let ye=ih(e,l);ye.classList.add("persona-mt-1"),v.appendChild(ye)}let xe=e.role==="assistant"?Wb(e.stopReason,(ve=(ae=a==null?void 0:a.widgetConfig)==null?void 0:ae.copy)==null?void 0:ve.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ye=!!(R&&R.trim()),Mt=b.placeholder==="skeleton",ne=Mt&&b.buffer==="line"&&ye;if(ye)ne&&v.appendChild(ks());else if(Mt)v.appendChild(ks());else{let He=mp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);He&&v.appendChild(He)}}if(xe&&e.stopReason&&!e.streaming&&(T||(H.style.display="none"),v.appendChild(Db(e.stopReason,xe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let ye=gp(e,n,o);v.appendChild(ye)}if(!u||e.role==="system")return v;let Le=x("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ge=jb(d,e.role);return m==="right"||m==="left"&&e.role==="user"?Le.append(v,Ge):Le.append(Ge,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Le},dh=(e,r,t,n,o,a)=>{let s=t!=null?t:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ea(e,r,t,n,o,a)};var Ma=new Set,Xb=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Jb=(e,r)=>{var n,o;let t=(o=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
|
|
64
|
+
`):""},ch=(e,r)=>{let t=Ma.has(e),n=r.querySelector('button[data-expand-header="true"]'),o=r.querySelector(".persona-border-t"),a=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!o)return;n.setAttribute("aria-expanded",t?"true":"false");let s=n.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ce(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",a&&(a.style.display=t?"none":a.textContent||a.childNodes.length?"":"none")},hp=(e,r)=>{var De,Xe,xe,ge,Le,Ge,Q,Se,J,ce,pe;let t=e.reasoning,n=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 o=(Xe=(De=r==null?void 0:r.features)==null?void 0:De.reasoningDisplay)!=null?Xe:{},a=o.expandable!==!1,s=a&&Ma.has(e.id),i=t.status!=="complete",d=Jb(e,(xe=o.previewMaxLines)!=null?xe:3),l=x("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",a&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=x("div","persona-flex persona-flex-col persona-text-left"),p=x("span","persona-text-xs persona-text-persona-primary"),m="Thinking...",f=(ge=r==null?void 0:r.reasoning)!=null?ge:{},w=String((Le=t.startedAt)!=null?Le:Date.now()),v=()=>{let ie=x("span","");return ie.setAttribute("data-tool-elapsed",w),ie.textContent=bi(t),ie},k=(Ge=f.renderCollapsedSummary)==null?void 0:Ge.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=Eg(t),u.appendChild(T);let A=(Q=o.loadingAnimation)!=null?Q:"none",E=f.activeTextTemplate,b=f.completeTextTemplate,h=i?E:b,S=k instanceof HTMLElement,L=(ie,Oe,Pe)=>{let K=Pe;for(let _e of Oe){let $e=x("span","persona-tool-char");$e.style.setProperty("--char-index",String(K)),$e.textContent=_e===" "?"\xA0":_e,ie.appendChild($e),K++}return K},O=(ie,Oe)=>{p.textContent="";let Pe=Ci(ie,""),K=0;for(let _e of Pe){let $e=_e.styles.length>0?(()=>{let Y=x("span",_e.styles.map(G=>`persona-tool-text-${G}`).join(" "));return p.appendChild(Y),Y})():p;if(_e.isDuration&&i)$e.appendChild(v());else{let Y=_e.isDuration?bi(t):_e.text;Oe?K=L($e,Y,K):$e.appendChild(document.createTextNode(Y))}}};if(!S&&h)if(T.style.display="none",p.style.display="",i&&A!=="none"){let ie=(Se=f.loadingAnimationDuration)!=null?Se:2e3;p.setAttribute("data-preserve-animation","true"),A==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),O(h,!1)):(p.classList.add(`persona-tool-loading-${A}`),p.style.setProperty("--persona-tool-anim-duration",`${ie}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 ie=(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",`${ie}ms`);else{p.classList.add(`persona-tool-loading-${A}`),p.style.setProperty("--persona-tool-anim-duration",`${ie}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 Oe=p.textContent||m;p.textContent="",L(p,Oe,0)}t.status==="complete"&&(p.style.display="none")}else S||(t.status==="complete"?p.style.display="none":p.style.display="");let H=null;if(a){H=x("div","persona-flex persona-items-center");let Oe=Ce(s?"chevron-up":"chevron-down",16,"currentColor",2);Oe?H.appendChild(Oe):H.textContent=s?"Hide":"Show";let Pe=x("div","persona-flex persona-items-center persona-ml-auto");Pe.append(H),l.append(u,Pe)}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&&o.activePreview&&d){let ie=(pe=(ce=r==null?void 0:r.reasoning)==null?void 0:ce.renderCollapsedPreview)==null?void 0:pe.call(ce,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:r!=null?r:{}});Xb(R,ie)||(R.textContent=d),R.style.display=""}if(!s&&i&&o.activeMinHeight&&(n.style.minHeight=o.activeMinHeight),!a)return n.append(l,R),n;let 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 j=t.chunks.join(""),oe=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=j||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),B.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),H){H.innerHTML="";let Oe=Ce(s?"chevron-up":"chevron-down",16,"currentColor",2);Oe?H.appendChild(Oe):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,Kb=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Yb=(e,r)=>{var a;let t=e.toolCall;if(!t)return"";let n=((a=t.chunks)!=null?a:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
|
|
65
|
+
`);let o=ba(t.args).trim();return o?o.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,r).join(`
|
|
66
|
+
`):""},Qb=(e,r)=>{var u,p,m,f,w;let t=e.toolCall,n=(u=r==null?void 0:r.features)==null?void 0:u.toolCallDisplay,o=(p=n==null?void 0:n.collapsedMode)!=null?p:"tool-call",a=Yb(e,(m=n==null?void 0:n.previewMaxLines)!=null?m:3),s=t?Mg(t):"";if(!t)return{summary:s,previewText:a,isActive:!1};let i=t.status!=="complete",d=(f=r==null?void 0:r.toolCall)!=null?f:{},l=s;return o==="tool-name"?l=((w=t.name)==null?void 0:w.trim())||s:o==="tool-preview"&&a&&(l=a),i&&d.activeTextTemplate?l=ed(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ed(t,d.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},ph=(e,r,t)=>{var u;let n=La.has(e),o=(u=t==null?void 0:t.toolCall)!=null?u:{},a=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",n?"true":"false");let d=a.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=o.toggleTextColor||o.headerTextColor||"currentColor",m=Ce(n?"chevron-up":"chevron-down",16,p,2);m?l.appendChild(m):l.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},xp=(e,r)=>{var j,oe,ue,De,Xe,xe,ge,Le,Ge;let t=e.toolCall,n=(j=r==null?void 0:r.toolCall)!=null?j:{},o=x("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),n.backgroundColor&&(o.style.backgroundColor=n.backgroundColor),n.borderColor&&(o.style.borderColor=n.borderColor),n.borderWidth&&(o.style.borderWidth=n.borderWidth),n.borderRadius&&(o.style.borderRadius=n.borderRadius),!t)return o;let a=(ue=(oe=r==null?void 0:r.features)==null?void 0:oe.toolCallDisplay)!=null?ue:{},s=a.expandable!==!1,i=s&&La.has(e.id),{summary:d,previewText:l,isActive:u}=Qb(e,r),p=x("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",s&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(p.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(p.style.paddingLeft=n.headerPaddingX,p.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(p.style.paddingTop=n.headerPaddingY,p.style.paddingBottom=n.headerPaddingY);let m=x("div","persona-flex persona-flex-col persona-text-left"),f=x("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(f.style.color=n.headerTextColor);let w=String((De=t.startedAt)!=null?De:Date.now()),v=()=>{let Q=x("span","");return Q.setAttribute("data-tool-elapsed",w),Q.textContent=ms(t),Q},k=(xe=n.renderCollapsedSummary)==null?void 0:xe.call(n,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Xe=a.collapsedMode)!=null?Xe:"tool-call",isActive:u,config:r!=null?r:{},elapsed:ms(t),createElapsedElement:v});typeof k=="string"&&k.trim()?(f.textContent=k,m.appendChild(f)):k instanceof HTMLElement?m.appendChild(k):(f.textContent=d,m.appendChild(f));let T=(ge=a.loadingAnimation)!=null?ge:"none",A=n.activeTextTemplate,E=n.completeTextTemplate,b=u?A:E,h=k instanceof HTMLElement,S=(Q,Se,J)=>{let ce=J;for(let pe of Se){let ie=x("span","persona-tool-char");ie.style.setProperty("--char-index",String(ce)),ie.textContent=pe===" "?"\xA0":pe,Q.appendChild(ie),ce++}return ce},L=(Q,Se)=>{var ie;f.textContent="";let J=((ie=t.name)==null?void 0:ie.trim())||"tool",ce=Ci(Q,J),pe=0;for(let Oe of ce){let Pe=Oe.styles.length>0?(()=>{let K=x("span",Oe.styles.map(_e=>`persona-tool-text-${_e}`).join(" "));return f.appendChild(K),K})():f;if(Oe.isDuration&&u)Pe.appendChild(v());else{let K=Oe.isDuration?ms(t):Oe.text;Se?pe=S(Pe,K,pe):Pe.appendChild(document.createTextNode(K))}}};if(!h)if(u&&T!=="none"){let Q=(Le=n.loadingAnimationDuration)!=null?Le:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),b&&L(b,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),T==="shimmer-color"&&(n.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)L(b,!0);else{let Se=f.textContent||d;f.textContent="",S(f,Se,0)}}else b&&L(b,!1);let O=null;if(s){O=x("div","persona-flex persona-items-center");let Q=n.toggleTextColor||n.headerTextColor||"currentColor",Se=Ce(i?"chevron-up":"chevron-down",16,Q,2);Se?O.appendChild(Se):O.textContent=i?"Hide":"Show";let J=x("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");J.append(O),p.append(m,J)}else p.append(m);let H=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!i&&u&&a.activePreview&&l){let Q=(Ge=n.renderCollapsedPreview)==null?void 0:Ge.call(n,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:r!=null?r:{}});Kb(H,Q)||(H.textContent=l),H.style.display=""}if(!i&&u&&a.activeMinHeight&&(o.style.minHeight=a.activeMinHeight),!s)return o.append(p,H),o;let R=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",n.contentBackgroundColor&&(R.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(R.style.color=n.contentTextColor),n.contentPaddingX&&(R.style.paddingLeft=n.contentPaddingX,R.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(R.style.paddingTop=n.contentPaddingY,R.style.paddingBottom=n.contentPaddingY),t.name){let Q=x("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?Q.style.color=n.contentTextColor:n.headerTextColor&&(Q.style.color=n.headerTextColor),Q.textContent=t.name,R.appendChild(Q)}if(t.args!==void 0){let Q=x("div","persona-space-y-1"),Se=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Arguments";let J=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=ba(t.args),Q.append(Se,J),R.appendChild(Q)}if(t.chunks&&t.chunks.length){let Q=x("div","persona-space-y-1"),Se=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Activity";let J=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=t.chunks.join(""),Q.append(Se,J),R.appendChild(Q)}if(t.status==="complete"&&t.result!==void 0){let Q=x("div","persona-space-y-1"),Se=x("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(Se.style.color=n.labelTextColor),Se.textContent="Result";let J=x("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");J.style.fontSize="0.75rem",J.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(J.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(J.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(J.style.color=n.codeBlockTextColor),J.textContent=ba(t.result),Q.append(Se,J),R.appendChild(Q)}if(t.status==="complete"&&typeof t.duration=="number"){let Q=x("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(Q.style.color=n.contentTextColor),Q.textContent=`Duration: ${t.duration}ms`,R.appendChild(Q)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let Q=n.toggleTextColor||n.headerTextColor||"currentColor",Se=Ce(i?"chevron-up":"chevron-down",16,Q,2);Se?O.appendChild(Se):O.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),o.append(p,H,R),o};var Eo=Bl(hi(),1);var bp="ask_user_question",yp=8,Pa="data-persona-ask-sheet-for",Zb="Other",e0="Other\u2026",fh="Type your own answer here",mh="Send",t0="Next",r0="Back",n0="Submit all",o0="Skip",a0=3,Cp="data-ask-current-index",wp="data-ask-question-count",gh="data-ask-answers",vp="data-ask-grouped",hh="data-ask-layout",s0=e=>e.layout==="pills"?"pills":"rows",i0=e=>e.getAttribute(hh)==="pills"?"pills":"rows",uh=!1,xh=e=>e.replace(/["\\]/g,"\\$&"),so=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===bp,ul=e=>{var r,t;return(t=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion)!=null?t:{}},io=e=>{let r=e.toolCall;if(!r)return{payload:null,complete:!1};let t=r.status==="complete";if(r.args&&typeof r.args=="object")return{payload:r.args,complete:t};let n=r.chunks;if(!n||n.length===0)return{payload:null,complete:t};try{let o=n.join(""),a=(0,Eo.parse)(o,Eo.STR|Eo.OBJ|Eo.ARR);if(a&&typeof a=="object")return{payload:a,complete:t}}catch{}return{payload:null,complete:t}},Is=e=>{let r=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return r.length>yp&&!uh&&(uh=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${r.length} questions; truncating to ${yp}.`)),r.slice(0,yp)},l0=e=>{var r;return(r=Is(e)[0])!=null?r:null},d0=(e,r)=>{var t;return(t=Is(e)[r])!=null?t:null},yh=(e,r)=>{let t=r.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},bh=(e,r,t)=>{if(e!=="rows")return null;let n=x("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),r){let o=x("span","persona-ask-row-check");n.appendChild(o)}else{let o=x("span","persona-ask-row-badge");o.textContent=String(t+1),n.appendChild(o)}return n},c0=(e,r,t,n)=>{let a=x("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(r)),a.setAttribute("data-option-label",e.label),t==="rows"){let s=x("span","persona-ask-row-content"),i=x("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=x("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let d=bh(t,n,r);d&&a.appendChild(d)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},p0=e=>{let t=x("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},u0=(e,r,t,n)=>{var u,p,m;let a=x("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!t){for(let f=0;f<a0;f++)a.appendChild(p0(n));return a}if(d.forEach((f,w)=>{a.appendChild(c0(f,w,n,s))}),(e==null?void 0:e.allowFreeText)!==!1){let f=n==="rows"?Zb:e0;if(n==="rows"){let w=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let v=x("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(u=r.freeTextPlaceholder)!=null?u:fh,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(p=r.freeTextLabel)!=null?p:f),v.appendChild(k),w.appendChild(v);let T=bh(n,s,d.length);T&&w.appendChild(T),a.appendChild(w)}else{let w=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(m=r.freeTextLabel)!=null?m:f,a.appendChild(w)}}return a},Ch=(e,r)=>{var a,s;let n=x("div",r==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(a=e.freeTextPlaceholder)!=null?a:fh,o.setAttribute("data-ask-free-text-input","true"),n.appendChild(o),r!=="rows"){let i=x("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:mh,i.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(i)}return n},f0=e=>{var n;let r=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");r.setAttribute("data-ask-multi-actions","true");let t=x("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(n=e.submitLabel)!=null?n:mh,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,r.appendChild(t),r},m0=(e,r,t)=>{var l,u,p,m;let n=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=x("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=t.backLabel)!=null?l:r0,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,n.appendChild(o);let a=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=x("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=t.skipLabel)!=null?u:o0,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=x("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===r-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:n0:(m=t.nextLabel)!=null?m:t0,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n},aa=e=>{let r=e.getAttribute(gh);if(!r)return{};try{let t=JSON.parse(r);return t&&typeof t=="object"?t:{}}catch{return{}}},wh=(e,r)=>{e.setAttribute(gh,JSON.stringify(r))},An=e=>{var t;let r=Number((t=e.getAttribute(Cp))!=null?t:"0");return Number.isFinite(r)?Math.max(0,Math.floor(r)):0},g0=(e,r)=>{e.setAttribute(Cp,String(Math.max(0,Math.floor(r))))},Ia=e=>{var t;let r=Number((t=e.getAttribute(wp))!=null?t:"1");return Number.isFinite(r)?Math.max(1,Math.floor(r)):1},Mo=e=>e.getAttribute(vp)==="true",h0=(e,r)=>{var o;let t=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let n={};return r.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(n[s]=d)}}),n},x0=(e,r)=>{var n;let t=(n=e.agentMetadata)==null?void 0:n.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(r-1,Math.floor(t)))},fl=(e,r)=>{let{payload:t}=io(r),n=Is(t),o=aa(e),a={},s=new Set;return n.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(a[l]=o[d]))}),a},vh=e=>{let r=aa(e),t=An(e),n=r[t],o=new Set;typeof n=="string"?o.add(n):Array.isArray(n)&&n.forEach(d=>o.add(d));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=o.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof n=="string"&&n.length>0&&!s.has(n)){i.value=n;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Ah=e=>{if(!Mo(e))return;let r=aa(e),t=An(e),n=r[t],o=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!o);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Ap=(e,r,t)=>{let n=ul(t),o=i0(e),{payload:a,complete:s}=io(r),i=Mo(e),d=An(e),l=Ia(e),u=i?d0(a,d):l0(a),p=!!(u!=null&&u.multiSelect),m=e.querySelector('[data-ask-step-inline="true"]');m&&(m.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let A=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=A,w.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let A=u0(u,n,s,o);v.replaceWith(A)}if(o!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Ch(n,o))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!k?e.appendChild(f0(n)):(!p||i)&&k&&k.remove(),e.setAttribute("data-multi-select",p?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=m0(d,l,n);T?T.replaceWith(A):e.appendChild(A)}else T&&T.remove();vh(e),Ah(e)},y0=(e,r,t)=>{let n=ul(r),o=s0(n),a=e.toolCall.id,s=Is(t),i=Math.max(1,s.length),d=i>1,l=h0(e,s),u=d?x0(e,i):0,p=x("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Pa,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(wp,String(i)),p.setAttribute(Cp,String(u)),p.setAttribute(vp,d?"true":"false"),p.setAttribute(hh,o),wh(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),yh(p,n);let m=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=x("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",m.appendChild(f);let w=x("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",m.appendChild(w),p.appendChild(m);let k=x("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),p.appendChild(k),o!=="rows"&&p.appendChild(Ch(n,o)),Ap(p,e,r),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},b0=(e,r,t)=>{let{payload:n}=io(r),o=Math.max(1,Is(n).length);o>Ia(e)&&(e.setAttribute(wp,String(o)),o>1&&!Mo(e)&&e.setAttribute(vp,"true")),Ap(e,r,t)},Sh=(e,r)=>{let t=x("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let n=ul(r);yh(t,n);let o=x("span","persona-ask-stub-label"),{complete:a}=io(e);return o.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},Ra=(e,r,t)=>{if(!t||!so(e)||ul(r).enabled===!1)return;let o=e.toolCall.id;t.querySelectorAll(`[${Pa}]`).forEach(l=>{l.getAttribute(Pa)!==o&&l.remove()});let s=t.querySelector(`[${Pa}="${xh(o)}"]`);if(s){b0(s,e,r);return}let{payload:i}=io(e),d=y0(e,r,i);t.appendChild(d)},Lo=(e,r)=>{if(!e)return;let t=r?`[${Pa}="${xh(r)}"]`:`[${Pa}]`;e.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(a)?a:180)})},Sp=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(r=>r.getAttribute("data-option-label")).filter(r=>typeof r=="string"&&r.length>0),Po=(e,r)=>{let t=aa(e),n=An(e);typeof r=="string"&&r.length===0||Array.isArray(r)&&r.length===0?delete t[n]:t[n]=r,wh(e,t),vh(e),Ah(e)},ml=(e,r,t,n)=>{let o=Ia(e),a=Math.max(0,Math.min(o-1,n));g0(e,a),Ap(e,r,t)};var Tp=(e,r)=>{var v,k,T,A,E,b,h,S,L,O,H,R;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,o=(t==null?void 0:t.status)==="pending",a=x("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(v=n==null?void 0:n.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(k=n==null?void 0:n.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",!t)return a;let s=x("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=x("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(T=n==null?void 0:n.titleColor)!=null?T:"currentColor",u=Ce(d,20,l,2);u&&i.appendChild(u);let p=x("div","persona-flex-1 persona-min-w-0"),m=x("div","persona-flex persona-items-center persona-gap-2"),f=x("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(f.style.color=n.titleColor),f.textContent=(A=n==null?void 0:n.title)!=null?A:"Approval Required",m.appendChild(f),!o){let B=x("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");B.setAttribute("data-approval-status",t.status),t.status==="approved"?(B.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",B.style.color="var(--persona-palette-colors-success-700, #15803d)",B.textContent="Approved"):t.status==="denied"?(B.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",B.style.color="var(--persona-palette-colors-error-700, #b91c1c)",B.textContent="Denied"):t.status==="timeout"&&(B.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",B.style.color="var(--persona-palette-colors-warning-700, #b45309)",B.textContent="Timeout"),m.appendChild(B)}p.appendChild(m);let w=x("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(w.style.color=n.descriptionColor),w.textContent=t.description,p.appendChild(w),t.parameters){let B=x("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(B.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(B.style.color=n.parameterTextColor),B.style.fontSize="0.75rem",B.style.lineHeight="1rem",B.textContent=ba(t.parameters),p.appendChild(B)}if(o){let B=x("div","persona-flex persona-gap-2 persona-mt-2");B.setAttribute("data-approval-buttons","true");let j=x("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");j.type="button",j.style.backgroundColor=(E=n==null?void 0:n.approveButtonColor)!=null?E:"var(--persona-approval-approve-bg, #22c55e)",j.style.color=(b=n==null?void 0:n.approveButtonTextColor)!=null?b:"#ffffff",j.setAttribute("data-approval-action","approve");let oe=Ce("shield-check",14,(h=n==null?void 0:n.approveButtonTextColor)!=null?h:"#ffffff",2);oe&&(oe.style.marginRight="4px",j.appendChild(oe));let ue=document.createTextNode((S=n==null?void 0:n.approveLabel)!=null?S:"Approve");j.appendChild(ue);let De=x("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");De.type="button",De.style.backgroundColor=(L=n==null?void 0:n.denyButtonColor)!=null?L:"transparent",De.style.color=(O=n==null?void 0:n.denyButtonTextColor)!=null?O:"var(--persona-feedback-error, #dc2626)",De.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,De.setAttribute("data-approval-action","deny");let Xe=Ce("shield-x",14,(H=n==null?void 0:n.denyButtonTextColor)!=null?H:"var(--persona-feedback-error, #dc2626)",2);Xe&&(Xe.style.marginRight="4px",De.appendChild(Xe));let xe=document.createTextNode((R=n==null?void 0:n.denyLabel)!=null?R:"Deny");De.appendChild(xe),B.append(j,De),p.appendChild(B)}return s.append(i,p),a.appendChild(s),a};var Th=e=>{let r=[];return{buttons:r,render:(n,o,a,s,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(s!=null?s:o?o.getMessages():[]).some(f=>f.role==="user"))return;let u=document.createDocumentFragment(),p=o?o.isStreaming():!1,m=f=>{switch(f){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(f=>{let w=x("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=f,w.disabled=p,i!=null&&i.fontFamily&&(w.style.fontFamily=m(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",o.sendMessage(f))}),u.appendChild(w),r.push(w)}),e.appendChild(u)}}};var Rs=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Hs=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let o=n.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of r)n.put(o)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{r(s.result)},s.onerror=()=>{t(s.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{r()},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of r)n.put(o)}catch{}}};function Ha(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var C0={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},w0={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},v0=["flowName","stepName","reasoningText","text","name","tool","toolName"],A0=100;function S0(e,r){let t={...C0,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return w0}function T0(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function k0(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),o=String(r.getSeconds()).padStart(2,"0"),a=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${o}.${a}`}function E0(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let o=n.split("."),a=t;for(let s of o)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function M0(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function L0(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function P0(e,r,t){let n,o;try{o=JSON.parse(e.payload),n=JSON.stringify(o,null,2)}catch{o=e.payload,n=e.payload}let a=r.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&t){let i=a.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>s(),parsedPayload:o});if(i)return i}return s();function s(){let i=x("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=x("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function kp(e,r,t,n,o,a,s,i){var m;let d=o.has(e.id),l=x("div","persona-border-b persona-border-persona-divider persona-text-xs");Ha(l,(m=n.classNames)==null?void 0:m.eventRow);let u=s.find(f=>f.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let f=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>a(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(p()),l;function p(){var j,oe;let f=x("div",""),w=x("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");w.setAttribute("data-event-id",e.id);let v=x("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),k=Ce(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&v.appendChild(k);let T=x("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(j=n.timestampFormat)!=null?j:"relative";T.textContent=A==="relative"?T0(e.timestamp,t):k0(e.timestamp);let E=null;n.showSequenceNumbers!==!1&&(E=x("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(r+1));let b=S0(e.type,n.badgeColors),h=x("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");h.style.backgroundColor=b.bg,h.style.color=b.text,h.style.borderColor=b.text+"50",h.textContent=e.type;let S=(oe=n.descriptionFields)!=null?oe:v0,L=E0(e.payload,S),O=null;L&&(O=x("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=L);let H=x("div","persona-flex-1 persona-min-w-0"),R=x("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),B=Ce("clipboard","12px","currentColor",1.5);return B&&R.appendChild(B),R.addEventListener("click",async ue=>{ue.stopPropagation(),await M0(L0(e)),R.innerHTML="";let De=Ce("check","12px","currentColor",1.5);De&&R.appendChild(De),setTimeout(()=>{R.innerHTML="";let Xe=Ce("clipboard","12px","currentColor",1.5);Xe&&R.appendChild(Xe)},1500)}),w.appendChild(v),w.appendChild(T),E&&w.appendChild(E),w.appendChild(h),O&&w.appendChild(O),w.appendChild(H),w.appendChild(R),f.appendChild(w),d&&f.appendChild(P0(e,s,i)),f}}function kh(e){var f,w,v,k,T;let{buffer:r,getFullHistory:t,onClose:n,config:o,plugins:a=[]}=e,s=(f=o==null?void 0:o.features)==null?void 0:f.scrollToBottom,i=(s==null?void 0:s.enabled)!==!1,d=(w=s==null?void 0:s.iconName)!=null?w:"arrow-down",l=(v=s==null?void 0:s.label)!=null?v:"",u=(T=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?T:{},p=a.find(A=>A.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&o){let A=p.renderEventStreamView({config:o,events:r.getAll(),defaultRenderer:()=>m().element,onClose:n});if(A)return{element:A,update:()=>{},destroy:()=>{}}}return m();function m(){let A=u.classNames,E=x("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ha(E,A==null?void 0:A.panel);let b=[],h="",S="",L=null,O=[],H={},R=0,B=Ji(),j=0,oe=0,ue=!1,De=null,Xe=!1,xe=0,ge=new Set,Le=new Map,Ge="",Q="",Se=null,J,ce,pe,ie,Oe;function Pe(){let N=x("div","persona-flex persona-flex-col persona-flex-shrink-0"),de=x("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Ha(de,A==null?void 0:A.headerBar);let Ee=x("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ee.textContent="Events",J=x("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),J.textContent="0";let ut=x("div","persona-flex-1");ce=x("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ye=x("option","");Ye.value="",Ye.textContent="All events",ce.appendChild(Ye),pe=x("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),pe.type="button",pe.title="Copy All";let or=Ce("clipboard-copy","12px","currentColor",1.5);or&&pe.appendChild(or);let It=x("span","persona-text-xs");It.textContent="Copy All",pe.appendChild(It),de.appendChild(Ee),de.appendChild(J),de.appendChild(ut),de.appendChild(ce),de.appendChild(pe);let St=x("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ha(St,A==null?void 0:A.searchBar);let rt=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),it=x("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");rt&&it.appendChild(rt),ie=x("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ha(ie,A==null?void 0:A.searchInput),ie.type="text",ie.placeholder="Search event payloads...",Oe=x("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Oe.type="button",Oe.style.display="none";let tr=Ce("x","12px","currentColor",2);return tr&&Oe.appendChild(tr),St.appendChild(it),St.appendChild(ie),St.appendChild(Oe),N.appendChild(de),N.appendChild(St),N}let K,_e=a.find(N=>N.renderEventStreamToolbar);if(_e!=null&&_e.renderEventStreamToolbar&&o){let N=_e.renderEventStreamToolbar({config:o,defaultRenderer:()=>Pe(),eventCount:r.getSize(),filteredCount:0,onFilterChange:de=>{h=de,He(),Yt()},onSearchChange:de=>{S=de,He(),Yt()}});K=N!=null?N:Pe()}else K=Pe();let $e=x("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");$e.style.display="none";let Y=x("div","persona-flex-1 persona-min-h-0 persona-relative"),G=x("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let we=x("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ha(we,A==null?void 0:A.scrollIndicator),we.style.display="none",we.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let ke=Ce(d,"14px","currentColor",2);ke&&we.appendChild(ke);let ae=x("span","");ae.textContent=l,we.appendChild(ae);let ve=x("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ve.style.display="none",Y.appendChild(G),Y.appendChild(ve),Y.appendChild(we),E.setAttribute("tabindex","0"),E.appendChild(K),E.appendChild($e),E.appendChild(Y);function ye(){let N=r.getAll(),de={};for(let It of N)de[It.type]=(de[It.type]||0)+1;let Ee=Object.keys(de).sort(),ut=Ee.length!==O.length||!Ee.every((It,St)=>It===O[St]),Ye=!ut&&Ee.some(It=>de[It]!==H[It]),Ut=N.length!==Object.values(H).reduce((It,St)=>It+St,0);if(!ut&&!Ye&&!Ut||(O=Ee,H=de,!ce))return;let or=ce.value;if(ce.options[0].textContent="All events",ut){for(;ce.options.length>1;)ce.remove(1);for(let It of Ee){let St=x("option","");St.value=It,St.textContent=`${It} (${de[It]||0})`,ce.appendChild(St)}or&&Ee.includes(or)?ce.value=or:or&&(ce.value="",h="")}else for(let It=1;It<ce.options.length;It++){let St=ce.options[It];St.textContent=`${St.value} (${de[St.value]||0})`}}function Mt(){let N=r.getAll();if(h&&(N=N.filter(de=>de.type===h)),S){let de=S.toLowerCase();N=N.filter(Ee=>Ee.type.toLowerCase().includes(de)||Ee.payload.toLowerCase().includes(de))}return N}function ne(){return h!==""||S!==""}function He(){R=0,j=0,B.resume(),we.style.display="none"}function fr(N){ge.has(N)?ge.delete(N):ge.add(N),Se=N;let de=G.scrollTop,Ee=B.isFollowing();Xe=!0,B.pause(),Yt(),G.scrollTop=de,Ee&&B.resume(),Xe=!1}function Ot(){return ws(G,50)}function Yt(){oe=Date.now(),ue=!1,ye();let N=r.getEvictedCount();N>0?($e.textContent=`${N.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",b=Mt();let de=b.length,Ee=r.getSize()>0;J&&(J.textContent=String(r.getSize())),de===0&&Ee&&ne()?(ve.textContent=S?`No events matching '${S}'`:"No events matching filter",ve.style.display="",G.style.display="none"):(ve.style.display="none",G.style.display=""),pe&&(pe.title=ne()?`Copy Filtered (${de})`:"Copy All"),i&&!B.isFollowing()&&de>R&&(j+=de-R,ae.textContent=l?`${l}${j>0?` (${j})`:""}`:"",we.style.display=""),R=de;let ut=r.getAll(),Ye=ut.length>0?ut[0].timestamp:0,Ut=new Set(b.map(St=>St.id));for(let St of ge)Ut.has(St)||ge.delete(St);let or=h!==Ge||S!==Q,It=Le.size===0&&b.length>0;if(or||It||b.length===0){G.innerHTML="",Le.clear();let St=document.createDocumentFragment();for(let rt=0;rt<b.length;rt++){let it=kp(b[rt],rt,Ye,u,ge,fr,a,o);Le.set(b[rt].id,it),St.appendChild(it)}G.appendChild(St),Ge=h,Q=S,Se=null}else{if(Se!==null){let rt=Le.get(Se);if(rt&&rt.parentNode===G){let it=b.findIndex(tr=>tr.id===Se);if(it>=0){let tr=kp(b[it],it,Ye,u,ge,fr,a,o);G.insertBefore(tr,rt),rt.remove(),Le.set(Se,tr)}}Se=null}let St=new Set(b.map(rt=>rt.id));for(let[rt,it]of Le)St.has(rt)||(it.remove(),Le.delete(rt));for(let rt=0;rt<b.length;rt++){let it=b[rt];if(!Le.has(it.id)){let tr=kp(it,rt,Ye,u,ge,fr,a,o);Le.set(it.id,tr),G.appendChild(tr)}}}B.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Fr(){if(Date.now()-oe>=A0){De!==null&&(cancelAnimationFrame(De),De=null),Yt();return}ue||(ue=!0,De=requestAnimationFrame(()=>{De=null,Yt()}))}let Ar=(N,de)=>{if(!pe)return;pe.innerHTML="";let Ee=Ce(N,"12px","currentColor",1.5);Ee&&pe.appendChild(Ee);let ut=x("span","persona-text-xs");ut.textContent="Copy All",pe.appendChild(ut),setTimeout(()=>{pe.innerHTML="";let Ye=Ce("clipboard-copy","12px","currentColor",1.5);Ye&&pe.appendChild(Ye);let Ut=x("span","persona-text-xs");Ut.textContent="Copy All",pe.appendChild(Ut),pe.disabled=!1},de)},F=async()=>{if(pe){pe.disabled=!0;try{let N;ne()?N=b:t?(N=await t(),N.length===0&&(N=r.getAll())):N=r.getAll();let de=N.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(de,null,2)),Ar("check",1500)}catch{Ar("x",1500)}}},le=()=>{ce&&(h=ce.value,He(),Yt())},Fe=()=>{!ie||!Oe||(Oe.style.display=ie.value?"":"none",L&&clearTimeout(L),L=setTimeout(()=>{S=ie.value,He(),Yt()},150))},Ke=()=>{!ie||!Oe||(ie.value="",S="",Oe.style.display="none",L&&clearTimeout(L),He(),Yt())},Ue=()=>{if(Xe)return;let N=G.scrollTop,{action:de,nextLastScrollTop:Ee}=Ki({following:B.isFollowing(),currentScrollTop:N,lastScrollTop:xe,nearBottom:Ot(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=Ee,de==="resume"?(B.resume(),j=0,we.style.display="none"):de==="pause"&&(B.pause(),i&&(ae.textContent=l,we.style.display=""))},qe=N=>{let de=Yi({following:B.isFollowing(),deltaY:N.deltaY,nearBottom:Ot(),resumeWhenNearBottom:!0});de==="pause"?(B.pause(),i&&(ae.textContent=l,we.style.display="")):de==="resume"&&(B.resume(),j=0,we.style.display="none")},nt=()=>{i&&(G.scrollTop=G.scrollHeight,B.resume(),j=0,we.style.display="none")},Ct=N=>{let de=N.target;if(!de||de.closest("button"))return;let Ee=de.closest("[data-event-id]");if(!Ee)return;let ut=Ee.getAttribute("data-event-id");ut&&fr(ut)},Pt=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),ie==null||ie.focus(),ie==null||ie.select();return}N.key==="Escape"&&(ie&&document.activeElement===ie?(Ke(),ie.blur(),E.focus()):n&&n())};pe&&pe.addEventListener("click",F),ce&&ce.addEventListener("change",le),ie&&ie.addEventListener("input",Fe),Oe&&Oe.addEventListener("click",Ke),G.addEventListener("scroll",Ue),G.addEventListener("wheel",qe,{passive:!0}),G.addEventListener("click",Ct),we.addEventListener("click",nt),E.addEventListener("keydown",Pt);function $t(){L&&clearTimeout(L),De!==null&&(cancelAnimationFrame(De),De=null),ue=!1,Le.clear(),pe&&pe.removeEventListener("click",F),ce&&ce.removeEventListener("change",le),ie&&ie.removeEventListener("input",Fe),Oe&&Oe.removeEventListener("click",Ke),G.removeEventListener("scroll",Ue),G.removeEventListener("wheel",qe),G.removeEventListener("click",Ct),we.removeEventListener("click",nt),E.removeEventListener("keydown",Pt)}return{element:E,update:Fr,destroy:$t}}}function Eh(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let m=document.createElement("span");m.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",m.style.backgroundColor="var(--persona-primary, #171717)",m.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(m);let f=document.createElement("span");f.textContent=`Generating ${s.toLowerCase()}...`,p.appendChild(f)}else p.textContent=s;if(l.append(u,p),i.append(d,l),o==="complete"){let m=document.createElement("button");m.type="button",m.textContent="Download",m.title=`Download ${t}`,m.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-text, #1f2937)",m.style.backgroundColor="transparent",m.style.cursor="pointer",m.setAttribute("data-download-artifact",n),i.append(m)}return i}var Mh=(e,r)=>{var n,o,a;let t=(a=(o=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:o.artifacts)==null?void 0:a.renderCard;if(t){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:s,artifactType:l,status:d},config:r.config,defaultRenderer:()=>Eh(e,r)});if(u)return u}return Eh(e,r)};var Ep=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},lo=new Ep;lo.register("PersonaArtifactCard",Mh);function I0(e){var o;let r=x("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=x("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),r.appendChild(t),r.appendChild(n),r}function Lh(e,r){var pe,ie,Oe,Pe;let t=(ie=(pe=e.features)==null?void 0:pe.artifacts)==null?void 0:ie.layout,o=((Oe=t==null?void 0:t.toolbarPreset)!=null?Oe:"default")==="document",a=(Pe=t==null?void 0:t.panePadding)==null?void 0:Pe.trim(),s=e.markdown?Xo(e.markdown):null,i=ya(e.sanitize),d=K=>{let _e=s?s(K):Jo(K);return i?i(_e):_e},l=typeof document!="undefined"?x("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),B==null||B.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let p=x("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),o&&p.classList.add("persona-artifact-pane-document");let m=x("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");m.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&m.classList.add("persona-artifact-toolbar-document");let f=x("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let w=x("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let v="rendered",k=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Qt({icon:"eye",label:"Rendered view"}),A=o?Qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Qt({icon:"code-2",label:"Source"}),E=x("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),b=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,h=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,S=t==null?void 0:t.documentToolbarCopyMenuItems,L=!!(h&&S&&S.length>0),O=null,H,R=null,B=null;if(o&&(b||h)&&!L){if(H=b?Ls({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),h){let K=Ce("chevron-down",14,"currentColor",2);K&&H.appendChild(K)}}else o&&L?(O=x("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=b?Ls({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Qt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),O.append(H,R)):o?H=Qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=Qt({icon:"copy",label:"Copy"});let j=o?Qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"refresh-cw",label:"Refresh"}),oe=o?Qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Qt({icon:"x",label:"Close"}),ue=()=>{var G,we,ke;let K=(G=Ge.find(ae=>ae.id===Q))!=null?G:Ge[Ge.length-1],_e=(we=K==null?void 0:K.id)!=null?we:null,$e=(K==null?void 0:K.artifactType)==="markdown"&&(ke=K.markdown)!=null?ke:"",Y=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:$e,jsonPayload:Y,id:_e}},De=async()=>{var G;let{markdown:K,jsonPayload:_e}=ue(),$e=(G=Ge.find(we=>we.id===Q))!=null?G:Ge[Ge.length-1],Y=($e==null?void 0:$e.artifactType)==="markdown"?K:$e?_e:"";try{await navigator.clipboard.writeText(Y)}catch{}};if(H.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&L){let{markdown:_e,jsonPayload:$e,id:Y}=ue();try{await K({actionId:"primary",artifactId:Y,markdown:_e,jsonPayload:$e})}catch{}return}await De()}),R&&(S!=null&&S.length)){let K=()=>{var $e;return($e=p.closest("[data-persona-root]"))!=null?$e:document.body},_e=()=>{B=ko({items:S.map($e=>({id:$e.id,label:$e.label})),onSelect:async $e=>{let{markdown:Y,jsonPayload:G,id:we}=ue(),ke=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ke?await ke({actionId:$e,artifactId:we,markdown:Y,jsonPayload:G}):$e==="markdown"||$e==="md"?await navigator.clipboard.writeText(Y):$e==="json"||$e==="source"?await navigator.clipboard.writeText(G):await navigator.clipboard.writeText(Y||G)}catch{}},anchor:O!=null?O:R,position:"bottom-right",portal:K()})};p.isConnected?_e():requestAnimationFrame(_e),R.addEventListener("click",$e=>{$e.stopPropagation(),B==null||B.toggle()})}j.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}J()}),oe.addEventListener("click",()=>{var K;u(),(K=r.onDismiss)==null||K.call(r)});let Xe=()=>{o&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),A.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",Xe(),J()}),A.addEventListener("click",()=>{v="source",Xe(),J()});let xe=x("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(m.replaceChildren(),k.append(T,A),O?E.append(O,j,oe):E.append(H,j,oe),m.append(k,xe,E),Xe()):(m.appendChild(f),m.appendChild(w)),a&&(m.style.paddingLeft=a,m.style.paddingRight=a);let ge=x("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=x("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(ge.style.paddingLeft=a,ge.style.paddingRight=a,Le.style.padding=a),p.appendChild(m),p.appendChild(ge),p.appendChild(Le);let Ge=[],Q=null,Se=!1,J=()=>{var Y,G,we,ke;let K=o&&Ge.length<=1;ge.classList.toggle("persona-hidden",K),ge.replaceChildren();for(let ae of Ge){let ve=x("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ve.type="button",ve.textContent=ae.title||ae.id.slice(0,8),ae.id===Q&&ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),ve.addEventListener("click",()=>r.onSelect(ae.id)),ge.appendChild(ve)}Le.replaceChildren();let _e=Q&&Ge.find(ae=>ae.id===Q)||Ge[Ge.length-1];if(!_e)return;if(o){let ae=_e.artifactType==="markdown"?"MD":(Y=_e.component)!=null?Y:"Component",ye=(_e.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${ye} \xB7 ${ae}`}else f.textContent="Artifacts";if(_e.artifactType==="markdown"){if(o&&v==="source"){let ve=x("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ve.textContent=(G=_e.markdown)!=null?G:"",Le.appendChild(ve);return}let ae=x("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ae.innerHTML=d((we=_e.markdown)!=null?we:""),Le.appendChild(ae);return}let $e=_e.component?lo.get(_e.component):void 0;if($e){let ve={message:{id:_e.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let ye=$e((ke=_e.props)!=null?ke:{},ve);if(ye){Le.appendChild(ye);return}}catch{}}Le.appendChild(I0(_e))},ce=()=>{var _e;let K=Ge.length>0;if(p.classList.toggle("persona-hidden",!K),l){let $e=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,G=((_e=$e==null?void 0:$e.classList.contains("persona-artifact-narrow-host"))!=null?_e:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&G&&Se?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var _e,$e,Y;Ge=K.artifacts,Q=(Y=($e=K.selectedId)!=null?$e:(_e=K.artifacts[K.artifacts.length-1])==null?void 0:_e.id)!=null?Y:null,Ge.length>0&&(Se=!0),J(),ce()},setMobileOpen(K){Se=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ce()}}}function Sn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Ph(e,r){var a,s,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Sn(r))return;let t=(s=(a=r.features)==null?void 0:a.artifacts)==null?void 0:s.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function R0(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function gl(e,r){var d,l,u,p,m,f,w,v,k,T;if(!Sn(r)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),R0(e),Ph(e,r);return}let t=(l=(d=r.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(m=t==null?void 0:t.paneMaxWidth)!=null?m:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(f=t==null?void 0:t.paneBackground)==null?void 0:f.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let o=(w=t==null?void 0:t.panePadding)==null?void 0:w.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let a=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(k=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:k.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ph(e,r)}var Ih=["panel","seamless"];function hl(e,r){var i,d,l,u,p,m;for(let f of Ih)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Sn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",o=Ih.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let a=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((m=t.unifiedSplitOuterRadius)==null?void 0:m.trim())||a;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Rh(e,r){var t,n,o;return!r||!Sn(e)?!1:((o=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function H0(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function B0(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function W0(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function D0(e,r,t,n){let o=e-n-2*r-t;return Math.max(0,o)}function Hh(e,r){var s;let n=(s=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",o=/^([\d.]+)px$/i.exec(n);if(o)return Number(o[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function Bh(e,r,t,n,o,a){let s=H0(o,200),i=D0(r,t,n,200);i=Math.max(s,i);let d=B0(a);return d!==null&&(i=Math.min(i,d)),W0(e,s,i)}var Wh={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Mp=(e,r,t,n)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(a=>{var w,v,k;if(a.dataset.enhanced==="true")return;let s=(w=a.dataset.tvForm)!=null?w:"init";a.dataset.enhanced="true";let i=(v=Wh[s])!=null?v:Wh.init;a.classList.add("persona-form-card","persona-space-y-4");let d=x("div","persona-space-y-1"),l=x("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=x("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var S,L;let A=x("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${r.id}-${s}-${T.name}`;let E=x("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=T.label,A.appendChild(E);let b=(S=T.type)!=null?S:"text",h;b==="textarea"?(h=document.createElement("textarea"),h.rows=3):(h=document.createElement("input"),h.type=b),h.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",h.id=`${r.id}-${s}-${T.name}`,h.name=T.name,h.placeholder=(L=T.placeholder)!=null?L:"",T.required&&(h.required=!0),A.appendChild(h),u.appendChild(A)});let p=x("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),m=x("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=x("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(k=i.submitLabel)!=null?k:"Submit",p.appendChild(m),p.appendChild(f),u.appendChild(p),a.replaceChildren(d,u),u.addEventListener("submit",async T=>{var h,S;T.preventDefault();let A=(h=t.formEndpoint)!=null?h:"/form",E=new FormData(u),b={};E.forEach((L,O)=>{b[O]=L}),b.type=s,f.disabled=!0,m.textContent="Submitting\u2026";try{let L=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let O=await L.json();m.textContent=(S=O.message)!=null?S:"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await n.sendMessage(String(O.nextPrompt))}catch(L){m.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Lp=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,o;return((n=t.priority)!=null?n:0)-((o=r.priority)!=null?o:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(a=>a.id));return[...t.filter(a=>!n.has(a.id)),...r].sort((a,s)=>{var i,d;return((i=s.priority)!=null?i:0)-((d=a.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Bs=new Lp;var Dh=()=>{let e=new Map,r=(o,a)=>(e.has(o)||e.set(o,new Set),e.get(o).add(a),()=>t(o,a)),t=(o,a)=>{var s;(s=e.get(o))==null||s.delete(a)};return{on:r,off:t,emit:(o,a)=>{var s;(s=e.get(o))==null||s.forEach(i=>{try{i(a)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var O0=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},F0=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let o=t;o<r.length;o+=1){let a=r[o];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return r.slice(t,o+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=O0(e),t=F0(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},Pp=e=>typeof e=="string"?e:e==null?"":String(e),sa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pp(e.payload.text)},messageAndClick:(e,r)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,n=Pp(t.element);if(n&&((o=r.document)!=null&&o.querySelector)){let a=r.document.querySelector(n);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Pp(t.text)}}},Oh=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ds=e=>{let r=new Set(Oh(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Oh(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(r);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||r.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:s,message:a.message}))||null,null):null;if(!i)return null;r.add(a.message.id),n();let d={action:i,message:a.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var N0=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},_0=e=>e.map(r=>({...r,streaming:!1})),$0=e=>e.map(r=>({...r,status:"complete"})),xl=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?N0(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let o={...t,messages:t.messages?_0(t.messages):void 0,artifacts:t.artifacts?$0(t.artifacts):void 0};n.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var Ba=Bl(hi(),1);function U0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function q0(e,r){if(!U0(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function yl(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let o=(0,Ba.parse)(t,Ba.STR|Ba.OBJ),a=q0(o,t);a&&(e=a)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Fh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function bl(e,r){let{config:t,message:n,onPropsUpdate:o}=r,a=lo.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:n,config:t,updateProps:i=>{o&&o(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Nh(){let e=yl();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function _h(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let r=e.content.trim();if(r.startsWith("{")||r.startsWith("["))return e.content}return null}function Cl(e){let r=_h(e);if(!r)return!1;try{let t=JSON.parse(r);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function wl(e){let r=_h(e);if(!r)return null;try{let t=JSON.parse(r);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let n=t;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:r}}}catch{}return null}var z0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vl(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=z0}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=n,f.appendChild(w);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,f.appendChild(v),m.appendChild(f);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let S=1;S<=5;S++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),L.title=l[S-1],L.dataset.rating=String(S),L.innerHTML=`
|
|
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=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=`
|
|
70
|
+
`,L.addEventListener("click",()=>{p=S,T.forEach((O,H)=>{let R=H<S;O.classList.toggle("selected",R),O.setAttribute("aria-checked",H===S-1?"true":"false")})}),T.push(L),k.appendChild(L)}m.appendChild(k);let A=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),S.appendChild(A),m.appendChild(S)}let E=document.createElement("div");E.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=i,b.addEventListener("click",()=>{t==null||t(),u.remove()});let h=document.createElement("button");return h.type="button",h.className="persona-feedback-btn persona-feedback-btn-submit",h.textContent=s,h.addEventListener("click",async()=>{if(p===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}h.disabled=!0,h.textContent="Submitting...";try{let S=(A==null?void 0:A.value.trim())||void 0;await r(p,S),u.remove()}catch(S){h.disabled=!1,h.textContent=s,console.error("[CSAT Feedback] Failed to submit:",S)}}),E.appendChild(b),E.appendChild(h),m.appendChild(E),u.appendChild(m),u}function Al(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,w.appendChild(v);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=o,w.appendChild(k),f.appendChild(w);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=l;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=u,A.appendChild(E),A.appendChild(b);let h=document.createElement("div");h.className="persona-feedback-numbers";let S=[];for(let B=0;B<=10;B++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${B} out of 10`),j.textContent=String(B),j.dataset.rating=String(B),B<=6?j.classList.add("persona-feedback-detractor"):B<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{m=B,S.forEach((oe,ue)=>{oe.classList.toggle("selected",ue===B),oe.setAttribute("aria-checked",ue===B?"true":"false")})}),S.push(j),h.appendChild(j)}T.appendChild(A),T.appendChild(h),f.appendChild(T);let L=null;if(d){let B=document.createElement("div");B.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),B.appendChild(L),f.appendChild(B)}let O=document.createElement("div");O.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{t==null||t(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=s,R.addEventListener("click",async()=>{if(m===null){h.classList.add("persona-feedback-shake"),setTimeout(()=>h.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let B=(L==null?void 0:L.value.trim())||void 0;await r(m,B),p.remove()}catch(B){R.disabled=!1,R.textContent=s,console.error("[NPS Feedback] Failed to submit:",B)}}),O.appendChild(H),O.appendChild(R),f.appendChild(O),p.appendChild(f),p}var Wa="persona-chat-history",V0=30*1e3,j0={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function G0(e){var n,o,a;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let s of t){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let d=(o=j0[i.type])!=null?o:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&r.push(s);return r}function Sl(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function X0(e){var r,t,n,o,a,s,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(n=e.persist)==null?void 0:n.openState)!=null?o:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function J0(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ip=e=>!e||typeof e!="object"?{}:{...e},$h=e=>e.map(r=>({...r,streaming:!1})),Uh=(e,r,t)=>{let n=e!=null&&e.markdown?Xo(e.markdown):null,o=ya(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var l,u,p;let s=(l=a.text)!=null?l:"",i=(u=a.message.rawContent)!=null?u:null;if(r){let m=r.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});m!==null&&(s=m.text,m.persist||(a.message.__skipPersist=!0),m.resubmit&&!a.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...a,text:s,raw:(p=i!=null?i:a.text)!=null?p:""}):n?d=n(s):d=Jo(s),o?o(d):d}};function qh(e){var i,d,l,u;let r=x("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",a=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,s=Ce(t,n,o,a);if(s&&r.appendChild(s),e!=null&&e.label){let p=x("span","persona-drop-overlay-label");p.textContent=e.label,r.appendChild(p)}return r}var Tl=(e,r,t)=>{var Qp,Zp,eu,tu,ru,nu,ou,au,su,iu,lu,du,cu,pu,uu,fu,mu,gu,hu,xu,yu,bu,Cu,wu,vu,Au,Su,Tu,ku,Eu,Mu,Lu,Pu,Iu,Ru,Hu,Bu,Wu,Du,Ou,Fu,Nu,_u,$u,Uu,qu,zu;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=zi(r),o=Bs.getForInstance(n.plugins);n.components&&lo.registerAll(n.components);let a=Dh(),i=n.persistState===!1?null:(Qp=n.storageAdapter)!=null?Qp:xl(),d={},l=null,u=!1,p=c=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:C}=g;return C&&(u=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=c!=null?c:{messages:[],metadata:{}},y=p(g);y.metadata&&(d=Ip(y.metadata)),(Zp=y.messages)!=null&&Zp.length&&(n={...n,initialMessages:y.messages}),(eu=y.artifacts)!=null&&eu.length&&(n={...n,initialArtifacts:y.artifacts,initialSelectedArtifactId:(tu=y.selectedArtifactId)!=null?tu:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(n.onStateLoaded)try{let c=p({messages:[],metadata:{}});(ru=c.messages)!=null&&ru.length&&(n={...n,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let m=()=>d,f=c=>{var y;d=(y=c({...d}))!=null?y:{},da()},w=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ws],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[sa.message,sa.messageAndClick],k=Ds({parsers:w,handlers:v,getSessionMetadata:m,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let T=(ou=(nu=n.launcher)==null?void 0:nu.enabled)!=null?ou:!0,A=(su=(au=n.launcher)==null?void 0:au.autoExpand)!=null?su:!1,E=(iu=n.autoFocusInput)!=null?iu:!1,b=A,h=T,S=(du=(lu=n.layout)==null?void 0:lu.header)==null?void 0:du.layout,L=!1,O=()=>To(n),H=()=>T||O(),R=O()?!1:T?A:!0,B=!1,j=null,oe=()=>{B=!0,j&&clearTimeout(j),j=setTimeout(()=>{B&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),B=!1)},1e4)},ue=Uh(n,k,oe),De=(pu=(cu=n.features)==null?void 0:cu.showReasoning)!=null?pu:!0,Xe=(fu=(uu=n.features)==null?void 0:uu.showToolCalls)!=null?fu:!0,xe=(gu=(mu=n.features)==null?void 0:mu.showEventStreamToggle)!=null?gu:!1,ge=(xu=(hu=n.features)==null?void 0:hu.scrollToBottom)!=null?xu:{},Ge=`${(bu=typeof n.persistState=="object"?(yu=n.persistState)==null?void 0:yu.keyPrefix:void 0)!=null?bu:"persona-"}event-stream`,Q=xe?new Hs(Ge):null,Se=(vu=(wu=(Cu=n.features)==null?void 0:Cu.eventStream)==null?void 0:wu.maxEvents)!=null?vu:2e3,J=xe?new Rs(Se,Q):null,ce=null,pe=!1,ie=null,Oe=0;Q==null||Q.open().then(()=>J==null?void 0:J.restore()).catch(c=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Pe={onCopy:c=>{var g,y;a.emit("message:copy",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.id,"copy").catch(C=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,c)},onFeedback:c=>{var g,y;a.emit("message:feedback",c),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(c.messageId,c.type).catch(C=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},K=(Au=n.statusIndicator)!=null?Au:{},_e=c=>{var g,y,C,D;return c==="idle"?(g=K.idleText)!=null?g:Dr.idle:c==="connecting"?(y=K.connectingText)!=null?y:Dr.connecting:c==="connected"?(C=K.connectedText)!=null?C:Dr.connected:c==="error"?(D=K.errorText)!=null?D:Dr.error:Dr[c]};function $e(c,g,y,C){if(C==="idle"&&y.idleLink){c.textContent="";let D=document.createElement("a");D.href=y.idleLink,D.target="_blank",D.rel="noopener noreferrer",D.textContent=g,D.style.color="inherit",D.style.textDecoration="none",c.appendChild(D)}else c.textContent=g}let{wrapper:Y,panel:G,pillRoot:we}=ah(n),ke=sh(n,H()),{container:ae,body:ve,messagesWrapper:ye,suggestions:Mt,textarea:ne,sendButton:He,sendButtonWrapper:fr,composerForm:Ot,statusText:Yt,introTitle:Fr,introSubtitle:Ar,closeButton:F,iconHolder:le,headerTitle:Fe,headerSubtitle:Ke,header:Ue,footer:qe,actionsRow:nt,leftActions:Ct,rightActions:Pt}=ke,$t=ke.setSendButtonMode,N=ke.micButton,de=ke.micButtonWrapper,Ee=ke.attachmentButton,ut=ke.attachmentButtonWrapper,Ye=ke.attachmentInput,Ut=ke.attachmentPreviewsContainer;ae.classList.add("persona-relative"),ve.classList.add("persona-relative");let or=12,It=()=>{var c;return(c=ge.label)!=null?c:""},St=()=>{var c;return(c=ge.iconName)!=null?c:"arrow-down"},rt=()=>ge.enabled!==!1,it=x("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");it.type="button",it.style.display="none",it.setAttribute("data-persona-scroll-to-bottom","true");let tr=x("span","persona-flex persona-items-center"),gn=x("span","");it.append(tr,gn),ae.appendChild(it);let Rr=()=>{let g=qe.style.display==="none"?0:qe.offsetHeight;it.style.bottom=`${g+or}px`};Rr();let Tn=()=>{let c=!!It();it.setAttribute("aria-label",It()||"Jump to latest"),it.title=It(),it.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),tr.innerHTML="";let g=Ce(St(),"14px","currentColor",2);g?(tr.appendChild(g),tr.style.display=""):tr.style.display="none",gn.textContent=It(),gn.style.display=c?"":"none"};Tn();let Tt=null,hn=null,ur=o.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:n,defaultRenderer:()=>{let g=ao({config:n,showClose:H()});return na(ae,g,n),g.header},onClose:()=>Nt(!1,"user")});if(c){let g=ae.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Ue=c)}}let Sr=()=>{var g,y,C,D;if(!J)return;if(pe=!0,!ce&&J&&(ce=kh({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Yr(),config:n,plugins:o})),ce&&(ve.style.display="none",(g=qe.parentNode)==null||g.insertBefore(ce.element,qe),ce.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${Kr.actionIconColor}`;let $=(D=(C=(y=n.features)==null?void 0:y.eventStream)==null?void 0:C.classNames)==null?void 0:D.toggleButtonActive;$&&$.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let c=()=>{if(!pe)return;let $=Date.now();$-Oe>=200&&(ce==null||ce.update(),Oe=$),ie=requestAnimationFrame(c)};Oe=0,ie=requestAnimationFrame(c),Jn(),a.emit("eventStream:opened",{timestamp:Date.now()})},Yr=()=>{var c,g,y;if(pe){if(pe=!1,ce&&ce.element.remove(),ve.style.display="",xt){xt.style.boxShadow="";let C=(y=(g=(c=n.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;C&&C.split(/\s+/).forEach(D=>D&&xt.classList.remove(D))}ie!==null&&(cancelAnimationFrame(ie),ie=null),Jn(),a.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(xe){let c=(Tu=(Su=n.features)==null?void 0:Su.eventStream)==null?void 0:Tu.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=x("button",g),xt.style.width="28px",xt.style.height="28px",xt.style.color=Kr.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let y=Ce("activity","18px","currentColor",1.5);y&&xt.appendChild(y);let C=ke.clearChatButtonWrapper,D=ke.closeButtonWrapper,$=C||D;$&&$.parentNode===Ue?Ue.insertBefore(xt,$):Ue.appendChild(xt),xt.addEventListener("click",()=>{pe?Yr():Sr()})}let kn=c=>{var C,D,$;let g=n.attachments;if(!(g!=null&&g.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let U=c.querySelector("[data-persona-composer-form]");U!=null&&U.parentNode?U.parentNode.insertBefore(y,U):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let U=x("input");U.type="file",U.accept=((C=g.allowedTypes)!=null?C:oo).join(","),U.multiple=((D=g.maxFiles)!=null?D:4)>1,U.style.display="none",U.setAttribute("aria-label",($=g.buttonTooltipText)!=null?$:"Attach files"),c.appendChild(U)}},nn=o.find(c=>c.renderComposer);if(nn!=null&&nn.renderComposer){let c=n.composer,g=nn.renderComposer({config:n,defaultRenderer:()=>ka({config:n}).footer,onSubmit:y=>{var U;if(!q||q.isStreaming())return;let C=y.trim(),D=(U=Tt==null?void 0:Tt.hasAttachments())!=null?U:!1;if(!C&&!D)return;ja();let $;D&&($=[],$.push(...Tt.getContentParts()),C&&$.push(gs(C))),q.sendMessage(C,{contentParts:$}),D&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((ku=n.voiceRecognition)==null?void 0:ku.enabled)===!0?()=>{hn==null||hn()}:void 0});g&&(qe.replaceWith(g),qe=g)}let Tr=c=>{let g=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),C=c.querySelector("[data-persona-composer-submit]"),D=c.querySelector("[data-persona-composer-mic]"),$=c.querySelector("[data-persona-composer-status]");g&&(Ot=g),y&&(ne=y),C&&(He=C),D&&(N=D,de=D.parentElement),$&&(Yt=$);let U=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Mt=U);let X=c.querySelector(".persona-attachment-button");X&&(Ee=X,ut=X.parentElement),Ye=c.querySelector('input[type="file"]'),Ut=c.querySelector(".persona-attachment-previews");let _=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(nt=_)};kn(qe),Tr(qe);let kr=(Iu=(Eu=n.layout)==null?void 0:Eu.contentMaxWidth)!=null?Iu:O()?(Pu=(Lu=(Mu=n.launcher)==null?void 0:Mu.composerBar)==null?void 0:Lu.contentMaxWidth)!=null?Pu:"720px":void 0;if(kr&&(ye.style.maxWidth=kr,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%"),kr&&Ot&&!O()&&(Ot.style.maxWidth=kr,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),kr&&Mt&&!O()&&(Mt.style.maxWidth=kr,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),kr&&Ut&&!O()&&(Ut.style.maxWidth=kr,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(Ru=n.attachments)!=null&&Ru.enabled&&Ye&&Ut){Tt=ta.fromConfig(n.attachments),Tt.setPreviewsContainer(Ut),Ye.addEventListener("change",y=>{let C=y.target;Tt==null||Tt.handleFileSelect(C.files),C.value=""});let c=n.attachments.dropOverlay,g=qh(c);ae.appendChild(g)}(()=>{var C,D;let c=(D=(C=n.layout)==null?void 0:C.slots)!=null?D:{},g=$=>{switch($){case"body-top":return ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ye;case"footer-top":return Mt;case"composer":return Ot;case"footer-bottom":return Yt;default:return null}},y=($,U)=>{var X;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")Ue.insertBefore(U,Ue.firstChild);else if($==="header-right")Ue.appendChild(U);else{let _=Ue.querySelector(".persona-flex-col");_?(X=_.parentNode)==null||X.insertBefore(U,_.nextSibling):Ue.appendChild(U)}break;case"body-top":{let _=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(U):ve.insertBefore(U,ve.firstChild);break}case"body-bottom":ve.appendChild(U);break;case"footer-top":Mt.replaceWith(U);break;case"footer-bottom":Yt.replaceWith(U);break;default:break}};for(let[$,U]of Object.entries(c))if(U)try{let X=U({config:n,defaultContent:()=>g($)});X&&y($,X)}catch(X){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,X)}})();let En=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let C=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=y.getAttribute("data-bubble-type");$==="reasoning"?(Ma.has(D)?Ma.delete(D):Ma.add(D),ch(D,C)):$==="tool"&&(La.has(D)?La.delete(D):La.add(D),ph(D,C,n)),ln.delete(D)};ye.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),En(c))}),ye.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),En(c))});let xn=new Map;ye.addEventListener("click",c=>{var U;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.closest("[data-actions-for]");if(!C)return;let D=C.getAttribute("data-actions-for");if(!D)return;let $=y.getAttribute("data-action");if($==="copy"){let _=q.getMessages().find(Te=>Te.id===D);if(_&&Pe.onCopy){let Te=_.content||"";navigator.clipboard.writeText(Te).then(()=>{y.classList.add("persona-message-action-success");let me=Ce("check",14,"currentColor",2);me&&(y.innerHTML="",y.appendChild(me)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let re=Ce("copy",14,"currentColor",2);re&&(y.innerHTML="",y.appendChild(re))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),Pe.onCopy(_)}}else if($==="upvote"||$==="downvote"){let _=((U=xn.get(D))!=null?U:null)===$,Te=$==="upvote"?"thumbs-up":"thumbs-down";if(_){xn.delete(D),y.classList.remove("persona-message-action-active");let me=Ce(Te,14,"currentColor",2);me&&(y.innerHTML="",y.appendChild(me))}else{let me=$==="upvote"?"downvote":"upvote",re=C.querySelector(`[data-action="${me}"]`);if(re){re.classList.remove("persona-message-action-active");let tt=Ce(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(re.innerHTML="",re.appendChild(tt))}xn.set(D,$),y.classList.add("persona-message-action-active");let be=Ce(Te,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(be)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ve=q.getMessages().find(lt=>lt.id===D);Ve&&Pe.onFeedback&&Pe.onFeedback({type:$,messageId:Ve.id,message:Ve})}}}),ye.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.closest(".persona-approval-bubble");if(!C)return;let D=C.getAttribute("data-message-id");if(!D)return;let $=y.getAttribute("data-approval-action");if(!$)return;let U=$==="approve"?"approved":"denied",_=q.getMessages().find(me=>me.id===D);if(!(_!=null&&_.approval))return;let Te=C.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),q.resolveApproval(_.approval,U)});let wt=null,Ie=null,M={artifacts:[],selectedId:null},Z=!1,se={current:null};ye.addEventListener("click",c=>{var re,be,Me,Ve,lt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let C=y.getAttribute("data-download-artifact");if(!C||((Me=(be=(re=n.features)==null?void 0:re.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Me.call(be,{type:"download",artifactId:C}))===!0)return;let $=q.getArtifactById(C),U=$==null?void 0:$.markdown,X=($==null?void 0:$.title)||"artifact";if(!U){let tt=y.closest("[data-open-artifact]"),ft=tt==null?void 0:tt.closest("[data-message-id]"),mt=ft==null?void 0:ft.getAttribute("data-message-id");if(mt){let Be=q.getMessages().find(Je=>Je.id===mt);if(Be!=null&&Be.rawContent)try{let Je=JSON.parse(Be.rawContent);U=(Ve=Je==null?void 0:Je.props)==null?void 0:Ve.markdown,X=((lt=Je==null?void 0:Je.props)==null?void 0:lt.title)||X}catch{}}}if(!U)return;let _=new Blob([U],{type:"text/markdown"}),Te=URL.createObjectURL(_),me=document.createElement("a");me.href=Te,me.download=`${X}.md`,me.click(),URL.revokeObjectURL(Te)}),ye.addEventListener("click",c=>{var $,U,X;let y=c.target.closest("[data-open-artifact]");if(!y)return;let C=y.getAttribute("data-open-artifact");!C||((X=(U=($=n.features)==null?void 0:$.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:X.call(U,{type:"open",artifactId:C}))===!0||(c.preventDefault(),c.stopPropagation(),Z=!1,q.selectArtifact(C),on())}),ye.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let kt=ke.composerOverlay,qt=(c,g,y)=>{var X,_,Te,me;let C=g.trim();if(!C||!se.current)return;let D=(X=c.getAttribute("data-tool-call-id"))!=null?X:"",$=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:D,answer:C,answers:y.structured,values:(_=y.values)!=null?_:y.source==="multi"?C.split(", "):[C],isFreeText:$,source:y.source},bubbles:!0,composed:!0})),Lo(kt,D);let U=se.current.getMessages().find(re=>{var be;return((be=re.toolCall)==null?void 0:be.id)===D});(Te=U==null?void 0:U.agentMetadata)!=null&&Te.awaitingLocalTool?se.current.resolveAskUserQuestion(U,(me=y.structured)!=null?me:C):se.current.sendMessage(C)},Bt=c=>{var D;let g=se.current;if(!g)return;let y=(D=c.getAttribute("data-tool-call-id"))!=null?D:"",C=g.getMessages().find($=>{var U;return((U=$.toolCall)==null?void 0:U.id)===y});C&&g.persistAskUserQuestionProgress(C,{answers:fl(c,C),currentIndex:An(c)})},ar=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),xr=c=>{var D,$,U;if((($=(D=n.features)==null?void 0:D.askUserQuestion)==null?void 0:$.groupedAutoAdvance)===!1)return;let g=An(c),y=Ia(c);if(g>=y-1)return;let C=(U=se.current)==null?void 0:U.getMessages().find(X=>{var _;return((_=X.toolCall)==null?void 0:_.id)===c.getAttribute("data-tool-call-id")});C&&(ml(c,C,n,g+1),Bt(c))};kt.addEventListener("click",c=>{var $,U,X,_,Te,me,re,be,Me,Ve,lt,tt,ft,mt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let C=y.closest("[data-persona-ask-sheet-for]");if(!C)return;let D=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),D==="dismiss"){let We=($=C.getAttribute("data-tool-call-id"))!=null?$:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Lo(kt,We);let Be=(U=se.current)==null?void 0:U.getMessages().find(Je=>{var W;return((W=Je.toolCall)==null?void 0:W.id)===We});(X=Be==null?void 0:Be.agentMetadata)!=null&&X.awaitingLocalTool&&((_=se.current)==null||_.markAskUserQuestionResolved(Be),(Te=se.current)==null||Te.resolveAskUserQuestion(Be,"(dismissed)"));return}if(D==="pick"){let We=y.getAttribute("data-option-label");if(!We)return;let Be=C.getAttribute("data-multi-select")==="true",Je=Mo(C);if(Je&&Be){let W=aa(C)[An(C)],Re=new Set(Array.isArray(W)?W:[]);Re.has(We)?Re.delete(We):Re.add(We),Po(C,Array.from(Re)),Bt(C);return}if(Je){Po(C,We),Bt(C),xr(C);return}if(Be){let W=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",W?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!W);let Re=C.querySelector('[data-ask-user-action="submit-multi"]');Re&&(Re.disabled=Sp(C).length===0);return}qt(C,We,{source:"pick",values:[We]});return}if(D==="submit-multi"){let We=Sp(C);if(We.length===0)return;qt(C,We.join(", "),{source:"multi",values:We});return}if(D==="open-free-text"){let We=C.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Be=We.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus()}return}if(D==="focus-free-text"){let We=C.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(D==="submit-free-text"){let We=C.querySelector('[data-ask-free-text-input="true"]'),Be=(me=We==null?void 0:We.value)!=null?me:"";if(!Be.trim())return;if(Mo(C)){Po(C,Be.trim()),Bt(C),xr(C);return}qt(C,Be,{source:"free-text"});return}if(D==="next"||D==="back"){if(!se.current)return;let We=(re=C.getAttribute("data-tool-call-id"))!=null?re:"",Be=se.current.getMessages().find(Qe=>{var Ae;return((Ae=Qe.toolCall)==null?void 0:Ae.id)===We});if(!Be)return;let Je=C.querySelector('[data-ask-free-text-input="true"]'),W=(Me=(be=Je==null?void 0:Je.value)==null?void 0:be.trim())!=null?Me:"";if(W){let Qe=aa(C)[An(C)];(typeof Qe!="string"||Qe!==W)&&Po(C,W)}let Re=D==="next"?1:-1,Ne=An(C)+Re;ml(C,Be,n,Ne),Bt(C);return}if(D==="submit-all"){if(!se.current)return;let We=(Ve=C.getAttribute("data-tool-call-id"))!=null?Ve:"",Be=se.current.getMessages().find(Qe=>{var Ae;return((Ae=Qe.toolCall)==null?void 0:Ae.id)===We});if(!Be)return;let Je=C.querySelector('[data-ask-free-text-input="true"]'),W=(tt=(lt=Je==null?void 0:Je.value)==null?void 0:lt.trim())!=null?tt:"";W&&Po(C,W);let Re=fl(C,Be);se.current.persistAskUserQuestionProgress(Be,{answers:Re,currentIndex:An(C)});let Ne=ar(Re);qt(C,Ne||"(submitted)",{source:"submit-all",structured:Re});return}if(D==="skip"){if(!se.current)return;let We=(ft=C.getAttribute("data-tool-call-id"))!=null?ft:"",Be=se.current.getMessages().find(Ae=>{var Dt;return((Dt=Ae.toolCall)==null?void 0:Dt.id)===We});if(!Be)return;let Je=Mo(C),W=An(C),Re=Ia(C),Ne=W>=Re-1;if(!Je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Lo(kt,We),(mt=Be.agentMetadata)!=null&&mt.awaitingLocalTool&&(se.current.markAskUserQuestionResolved(Be),se.current.resolveAskUserQuestion(Be,"(dismissed)"));return}Po(C,"");let Qe=C.querySelector('[data-ask-free-text-input="true"]');if(Qe&&(Qe.value=""),Ne){let Ae=fl(C,Be),Dt=ar(Ae);qt(C,Dt||"(skipped)",{source:"submit-all",structured:Ae});return}ml(C,Be,n,W+1),Bt(C);return}}),kt.addEventListener("keydown",c=>{var $;if(c.key!=="Enter")return;let y=c.target;if(!(($=y.matches)!=null&&$.call(y,'[data-ask-free-text-input="true"]')))return;let C=y.closest("[data-persona-ask-sheet-for]");if(!C)return;c.preventDefault();let D=y.value;if(D.trim()){if(Mo(C)){Po(C,D.trim()),Bt(C),xr(C);return}qt(C,D,{source:"free-text"})}});let Nr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let y=kt.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let C=Number(c.key),$=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[C-1];$&&(c.preventDefault(),$.click())};document.addEventListener("keydown",Nr);let Er=null,ot=null,wr=null,_r=null,po=()=>{};function jn(){_r==null||_r(),_r=null}let uo=()=>{var U;if(!Er||!ot)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){ot.style.removeProperty("position"),ot.style.removeProperty("left"),ot.style.removeProperty("top"),ot.style.removeProperty("bottom"),ot.style.removeProperty("width"),ot.style.removeProperty("z-index");return}let C=Er.firstElementChild;if(!C||C===ot)return;let D=10;ot.style.position="absolute",ot.style.top="0",ot.style.bottom="0",ot.style.width=`${D}px`,ot.style.zIndex="5";let $=C.offsetWidth-D/2;ot.style.left=`${Math.max(0,$)}px`},Fn=()=>{},on=()=>{var y,C,D,$,U;if(!wt||!Sn(n))return;gl(e,n),hl(e,n),Fn();let c=($=(D=(C=(y=n.features)==null?void 0:y.artifacts)==null?void 0:C.layout)==null?void 0:D.narrowHostMaxWidth)!=null?$:520,g=G.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),wt.update(M),Z?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(U=wt.backdrop)==null||U.classList.add("persona-hidden")):M.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),po()};if(Sn(n)){G.style.position="relative";let c=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ae),wt=Lh(n,{onSelect:y=>{var C;return(C=se.current)==null?void 0:C.selectArtifact(y)},onDismiss:()=>{Z=!0,on()}}),wt.element.classList.add("persona-hidden"),Er=g,g.appendChild(c),g.appendChild(wt.element),wt.backdrop&&G.appendChild(wt.backdrop),G.appendChild(g),po=()=>{var C,D,$,U;if(!Er||!wt)return;if(!((($=(D=(C=n.features)==null?void 0:C.artifacts)==null?void 0:D.layout)==null?void 0:$.resizable)===!0)){wr==null||wr(),wr=null,jn(),ot&&(ot.remove(),ot=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!ot){let X=x("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");X.setAttribute("role","separator"),X.setAttribute("aria-orientation","vertical"),X.setAttribute("aria-label","Resize artifacts panel"),X.tabIndex=0;let _=e.ownerDocument,Te=(U=_.defaultView)!=null?U:window,me=re=>{var ft,mt;if(!wt||re.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;re.preventDefault(),jn();let be=re.clientX,Me=wt.element.getBoundingClientRect().width,Ve=(mt=(ft=n.features)==null?void 0:ft.artifacts)==null?void 0:mt.layout,lt=We=>{let Be=Er.getBoundingClientRect().width,Je=e.classList.contains("persona-artifact-appearance-seamless"),W=Je?0:Hh(Er,Te),Re=Je?0:X.getBoundingClientRect().width||6,Ne=Me-(We.clientX-be),Qe=Bh(Ne,Be,W,Re,Ve==null?void 0:Ve.resizableMinWidth,Ve==null?void 0:Ve.resizableMaxWidth);wt.element.style.width=`${Qe}px`,wt.element.style.maxWidth="none",uo()},tt=()=>{_.removeEventListener("pointermove",lt),_.removeEventListener("pointerup",tt),_.removeEventListener("pointercancel",tt),_r=null;try{X.releasePointerCapture(re.pointerId)}catch{}};_r=tt,_.addEventListener("pointermove",lt),_.addEventListener("pointerup",tt),_.addEventListener("pointercancel",tt);try{X.setPointerCapture(re.pointerId)}catch{}};X.addEventListener("pointerdown",me),ot=X,Er.insertBefore(X,wt.element),wr=()=>{X.removeEventListener("pointerdown",me)}}if(ot){let X=M.artifacts.length>0&&!Z;ot.classList.toggle("persona-hidden",!X),uo()}},Fn=()=>{var Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be,Je,W;if(!T||!wt||((me=(Te=n.launcher)==null?void 0:Te.sidebarMode)!=null?me:!1)||hr(n)&&vn(n).reveal==="emerge")return;let C=(re=e.ownerDocument.defaultView)!=null?re:window,D=(Me=(be=n.launcher)==null?void 0:be.mobileFullscreen)!=null?Me:!0,$=(lt=(Ve=n.launcher)==null?void 0:Ve.mobileBreakpoint)!=null?lt:640;if(D&&C.innerWidth<=$||!Rh(n,T))return;let U=(mt=(ft=(tt=n.launcher)==null?void 0:tt.width)!=null?ft:n.launcherWidth)!=null?mt:mn,X=(W=(Je=(Be=(We=n.features)==null?void 0:We.artifacts)==null?void 0:Be.layout)==null?void 0:Je.expandedPanelWidth)!=null?W:"min(720px, calc(100vw - 24px))";M.artifacts.length>0&&!Z?(G.style.width=X,G.style.maxWidth=X):(G.style.width=U,G.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Ie=new ResizeObserver(()=>{on()}),Ie.observe(G))}else G.appendChild(ae),O()&&we&&(ke.peekBanner&&we.appendChild(ke.peekBanner),we.appendChild(qe));e.appendChild(Y),we&&e.appendChild(we);let Mn=()=>{var Qe,Ae,Dt,pt,cr,Lr,Ft,Ur,Pr,st,gt,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo,Et,Zr,Zn,zr,en,zt,Zt;if(O()){G.style.width="100%",G.style.maxWidth="100%";let Vt=(Ae=(Qe=n.launcher)==null?void 0:Qe.composerBar)!=null?Ae:{},nr=Y.dataset.state==="expanded",tn=(Dt=Vt.expandedSize)!=null?Dt:"anchored";if(!(nr&&tn!=="fullscreen")){ae.style.background="",ae.style.border="",ae.style.borderRadius="",ae.style.overflow="",ae.style.boxShadow="";return}let gr=(cr=(pt=n.theme)==null?void 0:pt.components)==null?void 0:cr.panel,$n=Sa(n),eo=($o,oi)=>{var Ya;return $o==null||$o===""?oi:(Ya=va($n,$o))!=null?Ya:$o},ti="1px solid var(--persona-border)",ri="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ni="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ae.style.background="var(--persona-surface, #ffffff)",ae.style.border=eo(gr==null?void 0:gr.border,ti),ae.style.borderRadius=eo(gr==null?void 0:gr.borderRadius,ni),ae.style.boxShadow=eo(gr==null?void 0:gr.shadow,ri),ae.style.overflow="hidden";return}let c=hr(n),g=(Ft=(Lr=n.launcher)==null?void 0:Lr.sidebarMode)!=null?Ft:!1,y=c||g||((Pr=(Ur=n.launcher)==null?void 0:Ur.fullHeight)!=null?Pr:!1),C=((st=n.launcher)==null?void 0:st.enabled)===!1,D=(qr=(gt=n.theme)==null?void 0:gt.components)==null?void 0:qr.panel,$=Sa(n),U=(Vt,nr)=>{var tn;return Vt==null||Vt===""?nr:(tn=va($,Vt))!=null?tn:Vt},X=(Br=e.ownerDocument.defaultView)!=null?Br:window,_=(Fo=(Oo=n.launcher)==null?void 0:Oo.mobileFullscreen)!=null?Fo:!0,Te=(ma=(No=n.launcher)==null?void 0:No.mobileBreakpoint)!=null?ma:640,me=X.innerWidth<=Te,re=_&&me&&T,be=(rr=(ga=n.launcher)==null?void 0:ga.position)!=null?rr:"bottom-left",Me=be==="bottom-left"||be==="top-left",Ve=(wo=(_o=n.launcher)==null?void 0:_o.zIndex)!=null?wo:Or,lt=g||re?"none":"1px solid var(--persona-border)",tt=re?"none":g?Me?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!re&&(tt="none",lt="none");let ft=g||re?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",mt=U(D==null?void 0:D.border,lt),We=U(D==null?void 0:D.shadow,tt),Be=U(D==null?void 0:D.borderRadius,ft),Je=ve.scrollTop;e.style.cssText="",Y.style.cssText="",G.style.cssText="",ae.style.cssText="",ve.style.cssText="",qe.style.cssText="";let W=()=>{var nr;if(Je<=0)return;((nr=ve.ownerDocument.defaultView)!=null?nr:window).requestAnimationFrame(()=>{if(ve.scrollTop===Je)return;let tn=ve.scrollHeight-ve.clientHeight;tn<=0||(ve.scrollTop=Math.min(Je,tn))})};if(re){Y.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Y.style.cssText=`
|
|
71
71
|
position: fixed !important;
|
|
72
72
|
inset: 0 !important;
|
|
73
73
|
width: 100% !important;
|
|
@@ -77,7 +77,7 @@ Please report this to https://github.com/markedjs/marked.`,r){let a="<p>An error
|
|
|
77
77
|
padding: 0 !important;
|
|
78
78
|
display: flex !important;
|
|
79
79
|
flex-direction: column !important;
|
|
80
|
-
z-index: ${
|
|
80
|
+
z-index: ${Ve} !important;
|
|
81
81
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
82
82
|
`,G.style.cssText=`
|
|
83
83
|
position: relative !important;
|
|
@@ -92,7 +92,7 @@ Please report this to https://github.com/markedjs/marked.`,r){let a="<p>An error
|
|
|
92
92
|
padding: 0 !important;
|
|
93
93
|
box-shadow: none !important;
|
|
94
94
|
border-radius: 0 !important;
|
|
95
|
-
`,
|
|
95
|
+
`,ae.style.cssText=`
|
|
96
96
|
display: flex !important;
|
|
97
97
|
flex-direction: column !important;
|
|
98
98
|
flex: 1 1 0% !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
|
-
`,
|
|
106
|
+
`,ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",qe.style.flexShrink="0",L=!0,W();return}let Re=(Zr=(Et=n==null?void 0:n.launcher)==null?void 0:Et.width)!=null?Zr:n==null?void 0:n.launcherWidth,Ne=Re!=null?Re:mn;if(!g&&!c)C&&y?(G.style.width="100%",G.style.maxWidth="100%"):(G.style.width=Ne,G.style.maxWidth=Ne);else if(c)if(vn(n).reveal==="emerge"){let nr=vn(n).width;G.style.width=nr,G.style.maxWidth=nr}else G.style.width="100%",G.style.maxWidth="100%";if(Fn(),G.style.boxShadow=We,G.style.borderRadius=Be,ae.style.border=mt,ae.style.borderRadius=Be,c&&!re&&(D==null?void 0:D.border)===void 0&&(ae.style.border="none",vn(n).side==="right"?ae.style.borderLeft="1px solid var(--persona-border)":ae.style.borderRight="1px solid var(--persona-border)"),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",ae.style.display="flex",ae.style.flexDirection="column",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.maxHeight="100%",ae.style.overflow="hidden",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",qe.style.flexShrink="0"),Y.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!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;
|
|
@@ -114,8 +114,8 @@ Please report this to https://github.com/markedjs/marked.`,r){let a="<p>An error
|
|
|
114
114
|
padding: 0 !important;
|
|
115
115
|
display: flex !important;
|
|
116
116
|
flex-direction: column !important;
|
|
117
|
-
z-index: ${
|
|
118
|
-
${
|
|
117
|
+
z-index: ${Ve} !important;
|
|
118
|
+
${Me?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
119
119
|
`,G.style.cssText=`
|
|
120
120
|
position: relative !important;
|
|
121
121
|
display: flex !important;
|
|
@@ -127,9 +127,9 @@ Please report this to https://github.com/markedjs/marked.`,r){let a="<p>An error
|
|
|
127
127
|
min-height: 0 !important;
|
|
128
128
|
margin: 0 !important;
|
|
129
129
|
padding: 0 !important;
|
|
130
|
-
box-shadow: ${
|
|
131
|
-
border-radius: ${
|
|
132
|
-
`,G.style.setProperty("width","100%","important"),G.style.setProperty("max-width","100%","important"),
|
|
130
|
+
box-shadow: ${We} !important;
|
|
131
|
+
border-radius: ${Be} !important;
|
|
132
|
+
`,G.style.setProperty("width","100%","important"),G.style.setProperty("max-width","100%","important"),ae.style.cssText=`
|
|
133
133
|
display: flex !important;
|
|
134
134
|
flex-direction: column !important;
|
|
135
135
|
flex: 1 1 0% !important;
|
|
@@ -138,29 +138,29 @@ Please report this to https://github.com/markedjs/marked.`,r){let a="<p>An error
|
|
|
138
138
|
min-height: 0 !important;
|
|
139
139
|
max-height: 100% !important;
|
|
140
140
|
overflow: hidden !important;
|
|
141
|
-
border-radius: ${
|
|
142
|
-
border: ${
|
|
143
|
-
`,
|
|
141
|
+
border-radius: ${Be} !important;
|
|
142
|
+
border: ${mt} !important;
|
|
143
|
+
`,qe.style.cssText=`
|
|
144
144
|
flex-shrink: 0 !important;
|
|
145
145
|
border-top: none !important;
|
|
146
146
|
padding: 8px 16px 12px 16px !important;
|
|
147
|
-
`}if(!C&&!c){let Vt="max-height: -moz-available !important; max-height: stretch !important;",nr=g?"":"padding-top: 1.25em !important;",tn=g?"":`z-index: ${(Zt=(zt=n.launcher)==null?void 0:zt.zIndex)!=null?Zt:Or} !important;`;Y.style.cssText+=Vt+nr+tn}W()};Mn(),vo(e,n),gl(e,n),hl(e,n);let 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:
|
|
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 vt=[];vt.push(()=>{document.removeEventListener("keydown",Nr)});let sr=null,ir=null;vt.push(()=>{sr==null||sr(),sr=null,ir==null||ir(),ir=null}),Ie&&vt.push(()=>{Ie==null||Ie.disconnect(),Ie=null}),vt.push(()=>{wr==null||wr(),wr=null,jn(),ot&&(ot.remove(),ot=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),xe&&vt.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),ce==null||ce.destroy(),ce=null,J==null||J.destroy(),J=null,Q=null});let an=null,fo=()=>{an&&(an(),an=null),n.colorScheme==="auto"&&(an=Gi(()=>{vo(e,n)}))};fo(),vt.push(()=>{an&&(an(),an=null)});let yn=(Hu=n.features)==null?void 0:Hu.streamAnimation;if(yn!=null&&yn.type&&yn.type!=="none"){let c=Ss(yn.type,yn.plugins);c&&(sp(c,e),vt.push(()=>rh(e)))}let Ln=Th(Mt),sn=null,q,he=!1,ln=Kg(),Pn=new Map,Nn=new Map,Oa=0,In=Ji(),Rn=0,Hn=null,Gn=!1,Ro=!1,Ns=4,Fa=24,_s=80,la=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Na=(Wu=(Bu=n.voiceRecognition)==null?void 0:Bu.autoResume)!=null?Wu:!1,bn=c=>{a.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Qr=()=>{f(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},$s=()=>{var C,D;if(((C=n.voiceRecognition)==null?void 0:C.enabled)===!1)return;let c=Ip(d.voiceState),g=!!c.active,y=Number((D=c.timestamp)!=null?D:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<V0&&setTimeout(()=>{var $,U;bt.active||(bt.manuallyDeactivated=!1,((U=($=n.voiceRecognition)==null?void 0:$.provider)==null?void 0:U.type)==="runtype"?q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("restore"),q.isVoiceActive()&&Co()}):Wo("restore"))},1e3)},Us=()=>q?$h(q.getMessages()).filter(c=>!c.__skipPersist):[];function da(c){if(!(i!=null&&i.save))return;let y={messages:c?$h(c):q?Us():[],metadata:d,artifacts:M.artifacts,selectedArtifactId:M.selectedId};try{let C=i.save(y);C instanceof Promise&&C.catch(D=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",D)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let Xn=null,qs=()=>Y.querySelector("#persona-scroll-container")||ve,Ho=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Gn=!1},_a=()=>{Hn!==null&&(cancelAnimationFrame(Hn),Hn=null),Ro=!1,Ho()},Jn=()=>{if(!rt()||pe){it.parentNode&&it.remove(),it.style.display="none";return}it.parentNode!==ae&&ae.appendChild(it),Rr();let c=Cs(ve)>0;it.style.display=In.isFollowing()||!c?"none":""},$a=()=>{In.pause()&&(_a(),Jn())},mo=()=>{In.resume(),Jn()},go=(c=!1)=>{In.isFollowing()&&(!c&&!he||(Hn!==null&&(cancelAnimationFrame(Hn),Hn=null),Ro=!0,Hn=requestAnimationFrame(()=>{Hn=null,Ro=!1,In.isFollowing()&&zs(qs(),c?220:140)})))},zs=(c,g=500)=>{let y=c.scrollTop,C=Cs(c),D=C-y;if(Math.abs(D)<1){Rn=c.scrollTop;return}if(Math.abs(D)>=_s){Ho(),Gn=!0,c.scrollTop=C,Rn=c.scrollTop,Gn=!1;return}Ho();let $=performance.now();Gn=!0;let U=_=>1-Math.pow(1-_,3),X=_=>{if(!In.isFollowing()){Ho();return}let Te=Cs(c);Te!==C&&(C=Te,D=C-y);let me=_-$,re=Math.min(me/g,1),be=U(re),Me=y+D*be;c.scrollTop=Me,Rn=c.scrollTop,re<1?Xn=requestAnimationFrame(X):(c.scrollTop=C,Rn=c.scrollTop,Xn=null,Gn=!1)};Xn=requestAnimationFrame(X)},Vs=c=>{let g=new Map;c.forEach(y=>{let C=la.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!C&&y.role==="assistant"&&a.emit("assistant:message",y),y.role==="assistant"&&(C!=null&&C.streaming)&&y.streaming===!1&&a.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(C?y.approval.status!=="pending"&&a.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):a.emit("approval:requested",{approval:y.approval,message:y}))}),la.clear(),g.forEach((y,C)=>{la.set(C,y)})},Bo=(c,g,y)=>{var tt,ft,mt,We,Be,Je;let C=document.createElement("div"),$=(()=>{var Re;let W=o.find(Ne=>Ne.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Re=n.loadingIndicator)!=null&&Re.render)return n.loadingIndicator.render})(),U=(W,Re)=>Re==null?!1:typeof Re=="string"?(W.textContent=Re,!0):(W.appendChild(Re),!0),X=new Set,_=new Set,Te=o.some(W=>W.renderAskUserQuestion),me=[],re=[],be=n.enableComponentStreaming!==!1;if(g.forEach(W=>{var Ur,Pr,st,gt,qr,Br,Oo,Fo,No,ma,ga,rr,_o,wo;X.add(W.id);let Re=Te&&so(W),Ne=!Re&&W.role==="assistant"&&!W.variant&&be&&Cl(W);if(!Ne&&Nn.has(W.id)){let Et=c.querySelector(`#wrapper-${W.id}`);Et==null||Et.removeAttribute("data-preserve-runtime"),Nn.delete(W.id)}let Qe=so(W)?`:${(Ur=W.agentMetadata)!=null&&Ur.askUserQuestionAnswered?"a":"u"}:${(Pr=W.agentMetadata)!=null&&Pr.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ae=Jg(W,Oa)+Qe,Dt=Re||Ne?null:Yg(ln,W.id,Ae);if(Dt){C.appendChild(Dt.cloneNode(!0)),so(W)&&((st=W.toolCall)!=null&&st.id)&&((gt=W.agentMetadata)==null?void 0:gt.awaitingLocalTool)===!0&&!((qr=W.agentMetadata)!=null&&qr.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,n,ke.composerOverlay));return}let pt=null,cr=o.find(Et=>!!(W.variant==="reasoning"&&Et.renderReasoning||W.variant==="tool"&&Et.renderToolCall||W.variant==="approval"&&Et.renderApproval||!W.variant&&Et.renderMessage)),Lr=(Br=n.layout)==null?void 0:Br.messages;if(so(W)&&((Oo=W.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){Pn.delete(W.id);let Et=c.querySelector(`#wrapper-${W.id}`);Et==null||Et.removeAttribute("data-preserve-runtime");return}if(so(W)&&((No=(Fo=n.features)==null?void 0:Fo.askUserQuestion)==null?void 0:No.enabled)!==!1){let Et=o.find(Zr=>typeof Zr.renderAskUserQuestion=="function");if(Et&&se.current){let Zr=Pn.get(W.id),Zn=Zr!==Ae,zr=null;if(Zn){let{payload:Zt,complete:Vt}=io(W),nr=W.id,tn=()=>{var cn;return(cn=se.current)==null?void 0:cn.getMessages().find(gr=>gr.id===nr)};zr=Et.renderAskUserQuestion({message:W,payload:Zt,complete:Vt,resolve:cn=>{var $n;let gr=tn();gr&&(($n=se.current)==null||$n.resolveAskUserQuestion(gr,cn))},dismiss:()=>{var gr,$n,eo;let cn=tn();(gr=cn==null?void 0:cn.agentMetadata)!=null&&gr.awaitingLocalTool&&(($n=se.current)==null||$n.markAskUserQuestionResolved(cn),(eo=se.current)==null||eo.resolveAskUserQuestion(cn,"(dismissed)"))},config:n})}let en=Zr!=null;if(Zn&&zr===null&&!en){((ma=W.agentMetadata)==null?void 0:ma.awaitingLocalTool)===!0&&!((ga=W.agentMetadata)!=null&&ga.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,n,ke.composerOverlay));return}let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-${W.id}`,zt.setAttribute("data-wrapper-id",W.id),zt.setAttribute("data-ask-plugin-stub","true"),zt.setAttribute("data-preserve-runtime","true"),C.appendChild(zt),me.push({messageId:W.id,fingerprint:Ae,bubble:zr});return}else{((rr=W.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((_o=W.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(_.add(W.toolCall.id),Ra(W,n,ke.composerOverlay));return}}else if(cr)if(W.variant==="reasoning"&&W.reasoning&&cr.renderReasoning){if(!De)return;pt=cr.renderReasoning({message:W,defaultRenderer:()=>hp(W,n),config:n})}else if(W.variant==="tool"&&W.toolCall&&cr.renderToolCall){if(!Xe)return;pt=cr.renderToolCall({message:W,defaultRenderer:()=>xp(W,n),config:n})}else if(W.variant==="approval"&&W.approval&&cr.renderApproval){if(n.approval===!1)return;pt=cr.renderApproval({message:W,defaultRenderer:()=>Tp(W,n),config:n})}else cr.renderMessage&&(pt=cr.renderMessage({message:W,defaultRenderer:()=>{let Et=Ea(W,y,Lr,n.messageActions,Pe,{loadingIndicatorRenderer:$,widgetConfig:n});return W.role!=="user"&&Mp(Et,W,n,q),Et},config:n}));if(!pt&&Ne){let Et=wl(W);if(Et){let Zr=Nn.get(W.id),Zn=Zr!==Ae,zr=n.wrapComponentDirectiveInBubble!==!1,en=null;if(Zn){let zt=bl(Et,{config:n,message:W,transform:y});if(zt)if(zr){let Zt=document.createElement("div");if(Zt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Zt.id=`bubble-${W.id}`,Zt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Vt=document.createElement("div");Vt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Vt.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Zt.appendChild(Vt)}Zt.appendChild(zt),en=Zt}else{let Zt=document.createElement("div");if(Zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Zt.id=`bubble-${W.id}`,Zt.setAttribute("data-message-id",W.id),Zt.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Vt=document.createElement("div");Vt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Vt.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Zt.appendChild(Vt)}Zt.appendChild(zt),en=Zt}}if(en||Zr!=null){let zt=document.createElement("div");zt.className="persona-flex",zt.id=`wrapper-${W.id}`,zt.setAttribute("data-wrapper-id",W.id),zt.setAttribute("data-component-directive-stub","true"),zt.setAttribute("data-preserve-runtime","true"),zr||zt.classList.add("persona-w-full"),C.appendChild(zt),re.push({messageId:W.id,fingerprint:Ae,bubble:en});return}}}if(!pt)if(W.variant==="reasoning"&&W.reasoning){if(!De)return;pt=hp(W,n)}else if(W.variant==="tool"&&W.toolCall){if(!Xe)return;pt=xp(W,n)}else if(W.variant==="approval"&&W.approval){if(n.approval===!1)return;pt=Tp(W,n)}else{let Et=(wo=n.layout)==null?void 0:wo.messages;Et!=null&&Et.renderUserMessage&&W.role==="user"?pt=Et.renderUserMessage({message:W,config:n,streaming:!!W.streaming}):Et!=null&&Et.renderAssistantMessage&&W.role==="assistant"?pt=Et.renderAssistantMessage({message:W,config:n,streaming:!!W.streaming}):pt=Ea(W,y,Et,n.messageActions,Pe,{loadingIndicatorRenderer:$,widgetConfig:n}),W.role!=="user"&&pt&&Mp(pt,W,n,q)}let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id=`wrapper-${W.id}`,Ft.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Ft.classList.add("persona-justify-end"),(pt==null?void 0:pt.getAttribute("data-persona-component-directive"))==="true"&&Ft.classList.add("persona-w-full"),Ft.appendChild(pt),Qg(ln,W.id,Ae,Ft),C.appendChild(Ft)}),ke.composerOverlay&&ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Ne=Re.getAttribute("data-persona-ask-sheet-for");Ne&&!_.has(Ne)&&Lo(ke.composerOverlay,Ne)}),(ft=(tt=n.features)==null?void 0:tt.toolCallDisplay)!=null&&ft.grouped){let W=[],Re=[];g.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&Xe){Re.push(Ne);return}Re.length>1&&W.push(Re),Re=[]}),Re.length>1&&W.push(Re),W.forEach((Ne,Qe)=>{var Pr,st;let Ae=Ne.map(gt=>Array.from(C.children).find(qr=>qr instanceof HTMLElement&&qr.getAttribute("data-wrapper-id")===gt.id)).filter(gt=>!!gt);if(Ae.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${Qe}-${Ne[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${Qe}-${Ne[0].id}`);let pt=document.createElement("div");pt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",pt.setAttribute("data-persona-tool-group","true");let cr=document.createElement("div");cr.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Lr=`Called ${Ne.length} tools`,Ft=(st=(Pr=n.toolCall)==null?void 0:Pr.renderGroupedSummary)==null?void 0:st.call(Pr,{messages:Ne,toolCalls:Ne.map(gt=>gt.toolCall).filter(gt=>!!gt),defaultSummary:Lr,config:n});U(cr,Ft)||(cr.textContent=Lr);let Ur=document.createElement("div");Ur.className="persona-tool-group-stack persona-flex persona-flex-col",pt.append(cr,Ur),Dt.appendChild(pt),Ae[0].before(Dt),Ae.forEach((gt,qr)=>{let Br=document.createElement("div");Br.className="persona-tool-group-item persona-relative",Br.setAttribute("data-persona-tool-group-item","true"),qr<Ae.length-1&&Br.setAttribute("data-persona-tool-group-connector","true"),Br.appendChild(gt),Ur.appendChild(Br)})})}Zg(ln,X);let Me=g.some(W=>W.role==="assistant"&&W.streaming),Ve=g[g.length-1],lt=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(he&&g.some(W=>W.role==="user")&&!Me&&!lt){let W={config:n,streaming:!0,location:"standalone",defaultRenderer:oa},Re=o.find(Qe=>Qe.renderLoadingIndicator),Ne=null;if(Re!=null&&Re.renderLoadingIndicator&&(Ne=Re.renderLoadingIndicator(W)),Ne===null&&((mt=n.loadingIndicator)!=null&&mt.render)&&(Ne=n.loadingIndicator.render(W)),Ne===null&&(Ne=oa()),Ne){let Qe=document.createElement("div"),Ae=((We=n.loadingIndicator)==null?void 0:We.showBubble)!==!1;Qe.className=Ae?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Qe.setAttribute("data-typing-indicator","true"),Qe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Qe.appendChild(Ne);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(Qe),C.appendChild(Dt)}}if(!he&&g.length>0){let W=g[g.length-1],Re={config:n,lastMessage:W,messageCount:g.length},Ne=o.find(Ae=>Ae.renderIdleIndicator),Qe=null;if(Ne!=null&&Ne.renderIdleIndicator&&(Qe=Ne.renderIdleIndicator(Re)),Qe===null&&((Be=n.loadingIndicator)!=null&&Be.renderIdle)&&(Qe=n.loadingIndicator.renderIdle(Re)),Qe){let Ae=document.createElement("div"),Dt=((Je=n.loadingIndicator)==null?void 0:Je.showBubble)!==!1;Ae.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ae.setAttribute("data-idle-indicator","true"),Ae.appendChild(Qe);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-idle-indicator",pt.setAttribute("data-wrapper-id","idle-indicator"),pt.appendChild(Ae),C.appendChild(pt)}}if(Xi(c,C),me.length>0)for(let{messageId:W,fingerprint:Re,bubble:Ne}of me){let Qe=c.querySelector(`#wrapper-${W}`);Qe&&Ne!==null&&(Qe.replaceChildren(Ne),Qe.setAttribute("data-bubble-fp",Re),Pn.set(W,Re))}if(Pn.size>0)for(let W of Pn.keys())X.has(W)||Pn.delete(W);if(re.length>0)for(let{messageId:W,fingerprint:Re,bubble:Ne}of re){let Qe=c.querySelector(`#wrapper-${W}`);Qe&&Ne!==null&&(Qe.replaceChildren(Ne),Qe.setAttribute("data-bubble-fp",Re),Nn.set(W,Re))}if(Nn.size>0)for(let W of Nn.keys())X.has(W)||Nn.delete(W)},ho=null,js=()=>{var y;if(ho)return;let c=C=>{let D=C.composedPath();D.includes(Y)||we&&D.includes(we)||Nt(!1,"user")};ho=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},Ua=()=>{var g;if(!ho)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",ho,!0),ho=null};vt.push(()=>Ua());let xo=null,Gs=()=>{var y;if(xo)return;let c=C=>{C.key==="Escape"&&(C.isComposing||Nt(!1,"user"))};xo=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},qa=()=>{var g;if(!xo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",xo,!0),xo=null};vt.push(()=>qa());let yo=!1,za=new Set,Xs=()=>{var g,y,C,D;let c=(C=(y=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:C.streamAnimation;return c||((D=n.features)==null?void 0:D.streamAnimation)},Kn=()=>{var ft,mt,We,Be;if(!O())return;let c=ke.peekBanner,g=ke.peekTextNode;if(!c||!g)return;if(R){c.classList.remove("persona-pill-peek--visible");return}let y=(ft=q==null?void 0:q.getMessages())!=null?ft:[],C;for(let Je=y.length-1;Je>=0;Je--){let W=y[Je];if(W.role==="assistant"&&W.content){C=W;break}}if(!C){c.classList.remove("persona-pill-peek--visible");return}let D=C.content,$=!!C.streaming,U=Xs(),X=Qi(U),_=X.type!=="none"?Ss(X.type,U==null?void 0:U.plugins):null,Te=((mt=_==null?void 0:_.isAnimating)==null?void 0:mt.call(_,C))===!0,me=_!==null&&($||Te);me&&_&&!za.has(_.name)&&(sp(_,e),za.add(_.name));let re=me&&(_!=null&&_.containerClass)?_.containerClass:null,be=(We=g.dataset.personaPeekStreamClass)!=null?We:null;be&&be!==re&&(g.classList.remove(be),delete g.dataset.personaPeekStreamClass),re&&be!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),me?(g.style.setProperty("--persona-stream-step",`${X.speed}ms`),g.style.setProperty("--persona-stream-duration",`${X.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Me=me?Zi(D,X.buffer,_,C,$):D;if(me&&X.placeholder==="skeleton"&&$&&(!Me||!Me.trim())){let Je=document.createElement("div"),W=ks();W.classList.add("persona-pill-peek__skeleton"),Je.appendChild(W),Xi(g,Je)}else{let Je=Math.max(0,Me.length-100),W=Me.length>100?Me.slice(-100):Me,Re=Jo(W);if(!me||!_){let Ne=Me.length>100?`\u2026${W}`:W;g.textContent!==Ne&&(g.textContent=Ne)}else{let Ne=Re;(_.wrap==="char"||_.wrap==="word")&&(Ne=Ts(Re,_.wrap,`peek-${C.id}`,{skipTags:_.skipTags,startIndex:Je}));let Qe=document.createElement("div");if(Qe.innerHTML=Ne,_.useCaret&&W.length>0){let Ae=el(),Dt=Qe.querySelectorAll(".persona-stream-char, .persona-stream-word"),pt=Dt[Dt.length-1];pt!=null&&pt.parentNode?pt.parentNode.insertBefore(Ae,pt.nextSibling):Qe.appendChild(Ae)}Xi(g,Qe),(Be=_.onAfterRender)==null||Be.call(_,{container:g,bubble:c,messageId:C.id,message:C,speed:X.speed,duration:X.duration})}}let tt=he||yo;c.classList.toggle("persona-pill-peek--visible",tt)};if(O()){let c=ke.peekBanner;if(c){let C=D=>{D.preventDefault(),D.stopPropagation(),Nt(!0,"user")};c.addEventListener("pointerdown",C),vt.push(()=>{c.removeEventListener("pointerdown",C)})}let g=()=>{yo||(yo=!0,Kn())},y=()=>{yo&&(yo=!1,Kn())};G.addEventListener("pointerenter",g),G.addEventListener("pointerleave",y),vt.push(()=>{G.removeEventListener("pointerenter",g),G.removeEventListener("pointerleave",y)}),we&&(we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),vt.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}))}let Js=c=>{var be,Me,Ve,lt,tt,ft,mt,We;let g=(Me=(be=n.launcher)==null?void 0:be.composerBar)!=null?Me:{},y=(Ve=g.expandedSize)!=null?Ve:"anchored",C=(lt=g.bottomOffset)!=null?lt:"16px",D=g.collapsedMaxWidth,$=(tt=g.expandedMaxWidth)!=null?tt:"880px",U=(ft=g.expandedTopOffset)!=null?ft:"5vh",X=(mt=g.modalMaxWidth)!=null?mt:"880px",_=(We=g.modalMaxHeight)!=null?We:"min(90vh, 800px)",Te="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",re=Y.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",we){let Be=we.style;Be.bottom=C,Be.width=D!=null?D:""}if(c&&y!=="fullscreen"){if(y==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=X,re.maxWidth=Te,re.maxHeight=_,re.height=_;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${C} + ${me})`,re.top=U,re.width=$,re.maxWidth=Te}},bo=()=>{var _,Te,me,re,be,Me,Ve,lt;if(!H())return;if(O()){let ft=(me=((Te=(_=n.launcher)==null?void 0:_.composerBar)!=null?Te:{}).expandedSize)!=null?me:"anchored",mt=R?"expanded":"collapsed";Y.dataset.state=mt,Y.dataset.expandedSize=ft,we&&(we.dataset.state=mt,we.dataset.expandedSize=ft),Y.style.removeProperty("display"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Js(R),ae.style.display=R?"flex":"none",Mn(),R?(js(),Gs()):(Ua(),qa()),Kn();return}let c=hr(n),g=(re=e.ownerDocument.defaultView)!=null?re:window,y=(Me=(be=n.launcher)==null?void 0:be.mobileBreakpoint)!=null?Me:640,C=(lt=(Ve=n.launcher)==null?void 0:Ve.mobileFullscreen)!=null?lt:!0,D=g.innerWidth<=y,$=C&&D&&T,U=vn(n).reveal;R?(Y.style.removeProperty("display"),Y.style.display=c?"flex":"",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-95","persona-opacity-0"),G.classList.add("persona-scale-100","persona-opacity-100"),I?I.element.style.display="none":V&&(V.style.display="none")):(c?c&&(U==="overlay"||U==="push")&&!$?(Y.style.removeProperty("display"),Y.style.display="flex",Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.setProperty("display","none","important"),Y.classList.remove("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Y.style.display="",Y.classList.add("persona-pointer-events-none","persona-opacity-0"),G.classList.remove("persona-scale-100","persona-opacity-100"),G.classList.add("persona-scale-95","persona-opacity-0")),I?I.element.style.display=c?"none":"":V&&(V.style.display=c?"none":""))},Nt=(c,g="user")=>{var $,U;if(!H()||R===c)return;let y=R;R=c,bo();let C=(()=>{var Ve,lt,tt,ft,mt,We,Be,Je,W,Re;let X=(lt=(Ve=n.launcher)==null?void 0:Ve.sidebarMode)!=null?lt:!1,_=(tt=e.ownerDocument.defaultView)!=null?tt:window,Te=(mt=(ft=n.launcher)==null?void 0:ft.mobileFullscreen)!=null?mt:!0,me=(Be=(We=n.launcher)==null?void 0:We.mobileBreakpoint)!=null?Be:640,re=_.innerWidth<=me,be=hr(n)&&Te&&re,Me=O()&&((Re=(W=(Je=n.launcher)==null?void 0:Je.composerBar)==null?void 0:W.expandedSize)!=null?Re:"fullscreen")==="fullscreen";return X||Te&&re&&T||be||Me})();if(R&&C){if(!sr){let X=e.getRootNode(),_=X instanceof ShadowRoot?X.host:e.closest(".persona-host");_&&(sr=ip(_,(U=($=n.launcher)==null?void 0:$.zIndex)!=null?U:Or))}ir||(ir=lp(e.ownerDocument))}else R||(sr==null||sr(),sr=null,ir==null||ir(),ir=null);R&&(fe(),go(!0));let D={open:R,source:g,timestamp:Date.now()};R&&!y?a.emit("widget:opened",D):!R&&y&&a.emit("widget:closed",D),a.emit("widget:state",{open:R,launcherEnabled:T,voiceActive:bt.active,streaming:q.isStreaming()})},ca=c=>{$t(c?"stop":"send"),N&&(N.disabled=c),Ln.buttons.forEach(g=>{g.disabled=c}),qe.dataset.personaComposerStreaming=c?"true":"false",qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},pa=()=>{bt.active||ne&&ne.focus()};a.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>pa(),200)});let Va=()=>{var y,C,D,$,U,X,_,Te,me,re,be;Fr.textContent=(C=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?C:"Hello \u{1F44B}",Ar.textContent=($=(D=n.copy)==null?void 0:D.welcomeSubtitle)!=null?$:"Ask anything about your account or products.",ne.placeholder=(X=(U=n.copy)==null?void 0:U.inputPlaceholder)!=null?X:"How can I help...";let c=ve.querySelector("[data-persona-intro-card]");if(c){let Me=((_=n.copy)==null?void 0:_.showWelcomeCard)!==!1;c.style.display=Me?"":"none",Me?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((me=(Te=n.sendButton)==null?void 0:Te.useIcon)!=null&&me)&&!(q!=null&&q.isStreaming())&&(He.textContent=(be=(re=n.copy)==null?void 0:re.sendButtonLabel)!=null?be:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{f(g=>({...g,sessionId:c}))}});let _n=null,Ks=()=>{_n==null&&(_n=setInterval(()=>{let c=ye.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(_n),_n=null;return}let g=Date.now();c.forEach(y=>{let C=Number(y.getAttribute("data-tool-elapsed"));C&&(y.textContent=yi(g-C))})},100))};if(q=new wa(n,{onMessagesChanged(c){Bo(ye,c,ue),Ks(),q&&(c.some(D=>D.role==="user")?Ln.render([],q,ne,c):Ln.render(n.suggestionChips,q,ne,c,n.suggestionChipsConfig)),go(!he),Vs(c);let g=[...c].reverse().find(C=>C.role==="user"),y=bt.lastUserMessageId;g&&g.id!==y&&(bt.lastUserMessageId=g.id,a.emit("user:message",g)),bt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),da(c),Kn()},onStatusChanged(c){var C;let g=(C=n.statusIndicator)!=null?C:{};$e(Yt,(D=>{var $,U,X,_;return D==="idle"?($=g.idleText)!=null?$:Dr.idle:D==="connecting"?(U=g.connectingText)!=null?U:Dr.connecting:D==="connected"?(X=g.connectedText)!=null?X:Dr.connected:D==="error"?(_=g.errorText)!=null?_:Dr.error:Dr[D]})(c),g,c)},onStreamingChanged(c){he=c,ca(c),q&&Bo(ye,q.getMessages(),ue),c||go(!0),Kn()},onVoiceStatusChanged(c){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":Wn(),Qs();break;case"speaking":Wn(),Zs();break;default:c==="idle"&&q.isBargeInActive()?(Wn(),Co(),N==null||N.setAttribute("aria-label","End voice session")):(bt.active=!1,Wn(),bn("system"),Qr());break}},onArtifactsState(c){M=c,on(),da()}}),se.current=q,((Ou=(Du=n.voiceRecognition)==null?void 0:Du.provider)==null?void 0:Ou.type)==="runtype")try{q.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}n.clientToken&&q.initClientSession().catch(c=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(J||n.onSSEEvent)&&q.setSSEEventCallback((c,g)=>{var y;(y=n.onSSEEvent)==null||y.call(n,c,g),J==null||J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,y,C;c&&(c.metadata&&(d=Ip(c.metadata),k.syncFromMetadata()),(g=c.messages)!=null&&g.length&&q.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&q.hydrateArtifacts(c.artifacts,(C=c.selectedArtifactId)!=null?C:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ja=()=>{var g,y,C;!O()||R||!((C=(y=(g=n.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||C)||Nt(!0,"auto")},Ga=c=>{var D;if(c.preventDefault(),q.isStreaming()){q.cancel();return}let g=ne.value.trim(),y=(D=Tt==null?void 0:Tt.hasAttachments())!=null?D:!1;if(!g&&!y)return;ja();let C;y&&(C=[],C.push(...Tt.getContentParts()),g&&C.push(gs(g))),ne.value="",ne.style.height="auto",q.sendMessage(g,{contentParts:C}),y&&Tt.clearAttachments()},Xa=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),He.click())},Ja=async c=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Tt)return;let g=G0(c.clipboardData);g.length!==0&&(c.preventDefault(),await Tt.handleFiles(g))},$r=null,dn=!1,Yn=null,dt=null,Ka=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Wo=(c="user")=>{var $,U,X,_,Te,me,re;if(dn||q.isStreaming())return;let g=Ka();if(!g)return;$r=new g;let C=(U=(($=n.voiceRecognition)!=null?$:{}).pauseDuration)!=null?U:2e3;$r.continuous=!0,$r.interimResults=!0,$r.lang="en-US";let D=ne.value;$r.onresult=be=>{let Me="",Ve="";for(let tt=0;tt<be.results.length;tt++){let ft=be.results[tt],mt=ft[0].transcript;ft.isFinal?Me+=mt+" ":Ve=mt}let lt=D+Me+Ve;ne.value=lt,Yn&&clearTimeout(Yn),(Me||Ve)&&(Yn=window.setTimeout(()=>{let tt=ne.value.trim();tt&&$r&&dn&&(Bn(),ne.value="",ne.style.height="auto",q.sendMessage(tt,{viaVoice:!0}))},C))},$r.onerror=be=>{be.error!=="no-speech"&&Bn()},$r.onend=()=>{if(dn){let be=ne.value.trim();be&&be!==D.trim()&&(ne.value="",ne.style.height="auto",q.sendMessage(be,{viaVoice:!0})),Bn()}};try{if($r.start(),dn=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),bn(c),Qr(),N){let be=(X=n.voiceRecognition)!=null?X:{};dt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((re=(me=be.iconSize)!=null?me:(Te=n.sendButton)==null?void 0:Te.size)!=null?re:"40")||24};let Me=be.recordingBackgroundColor,Ve=be.recordingIconColor,lt=be.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=Ve!=null?Ve:"var(--persona-voice-recording-indicator, #ffffff)",Ve){let tt=N.querySelector("svg");tt&&tt.setAttribute("stroke",Ve)}lt&&(N.style.borderColor=lt),N.setAttribute("aria-label","Stop voice recognition")}}catch{Bn("system")}},Bn=(c="user")=>{if(dn){if(dn=!1,Yn&&(clearTimeout(Yn),Yn=null),$r){try{$r.stop()}catch{}$r=null}if(bt.active=!1,bn(c),Qr(),N){if(N.classList.remove("persona-voice-recording"),dt){N.style.backgroundColor=dt.backgroundColor,N.style.color=dt.color,N.style.borderColor=dt.borderColor;let g=N.querySelector("svg");g&&g.setAttribute("stroke",dt.color||"currentColor"),dt=null}N.setAttribute("aria-label","Start voice recognition")}}},Ys=(c,g)=>{var ft,mt,We,Be,Je,W,Re,Ne;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((ft=c==null?void 0:c.provider)==null?void 0:ft.type)==="runtype";if(!(y||C))return null;let $=x("div","persona-send-button-wrapper"),U=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let X=(mt=c==null?void 0:c.iconName)!=null?mt:"mic",_=(We=g==null?void 0:g.size)!=null?We:"40px",Te=(Be=c==null?void 0:c.iconSize)!=null?Be:_,me=parseFloat(Te)||24,re=(Je=c==null?void 0:c.backgroundColor)!=null?Je:g==null?void 0:g.backgroundColor,be=(W=c==null?void 0:c.iconColor)!=null?W:g==null?void 0:g.textColor;U.style.width=Te,U.style.height=Te,U.style.minWidth=Te,U.style.minHeight=Te,U.style.fontSize="18px",U.style.lineHeight="1",be?U.style.color=be:U.style.color="var(--persona-text, #111827)";let Ve=Ce(X,me,be||"currentColor",1.5);Ve?U.appendChild(Ve):U.textContent="\u{1F3A4}",re?U.style.backgroundColor=re:U.style.backgroundColor="",c!=null&&c.borderWidth&&(U.style.borderWidth=c.borderWidth,U.style.borderStyle="solid"),c!=null&&c.borderColor&&(U.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(U.style.paddingLeft=c.paddingX,U.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(U.style.paddingTop=c.paddingY,U.style.paddingBottom=c.paddingY),$.appendChild(U);let lt=(Re=c==null?void 0:c.tooltipText)!=null?Re:"Start voice recognition";if(((Ne=c==null?void 0:c.showTooltip)!=null?Ne:!1)&<){let Qe=x("div","persona-send-button-tooltip");Qe.textContent=lt,$.appendChild(Qe)}return{micButton:U,micButtonWrapper:$}},ua=()=>{var g,y,C,D,$;if(!N||dt)return;let c=(g=n.voiceRecognition)!=null?g:{};dt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat(($=(D=c.iconSize)!=null?D:(C=n.sendButton)==null?void 0:C.size)!=null?$:"40")||24}},fa=(c,g)=>{var $,U,X,_,Te;if(!N)return;let y=N.querySelector("svg");y&&y.remove();let C=(Te=dt==null?void 0:dt.iconSize)!=null?Te:parseFloat((_=(X=($=n.voiceRecognition)==null?void 0:$.iconSize)!=null?X:(U=n.sendButton)==null?void 0:U.size)!=null?_:"40")||24,D=Ce(c,C,g,1.5);D&&N.appendChild(D)},Do=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Co=()=>{var D;if(!N)return;ua();let c=(D=n.voiceRecognition)!=null?D:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,C=c.recordingBorderColor;if(Do(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let $=N.querySelector("svg");$&&$.setAttribute("stroke",y)}C&&(N.style.borderColor=C),N.setAttribute("aria-label","Stop voice recognition")},Qs=()=>{var X,_,Te,me,re,be,Me,Ve;if(!N)return;ua();let c=(X=n.voiceRecognition)!=null?X:{},g=q.getVoiceInterruptionMode(),y=(_=c.processingIconName)!=null?_:"loader",C=(me=(Te=c.processingIconColor)!=null?Te:dt==null?void 0:dt.color)!=null?me:"",D=(be=(re=c.processingBackgroundColor)!=null?re:dt==null?void 0:dt.backgroundColor)!=null?be:"",$=(Ve=(Me=c.processingBorderColor)!=null?Me:dt==null?void 0:dt.borderColor)!=null?Ve:"";Do(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=D,N.style.borderColor=$;let U=C||"currentColor";N.style.color=U,fa(y,U),N.setAttribute("aria-label","Processing voice input"),g==="none"&&(N.style.cursor="default")},Zs=()=>{var Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be;if(!N)return;ua();let c=(Te=n.voiceRecognition)!=null?Te:{},g=q.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",C=(me=c.speakingIconName)!=null?me:y,D=(Ve=c.speakingIconColor)!=null?Ve:g==="barge-in"?(be=(re=c.recordingIconColor)!=null?re:dt==null?void 0:dt.color)!=null?be:"":(Me=dt==null?void 0:dt.color)!=null?Me:"",$=(ft=c.speakingBackgroundColor)!=null?ft:g==="barge-in"?(lt=c.recordingBackgroundColor)!=null?lt:"var(--persona-voice-recording-bg, #ef4444)":(tt=dt==null?void 0:dt.backgroundColor)!=null?tt:"",U=(Be=c.speakingBorderColor)!=null?Be:g==="barge-in"?(mt=c.recordingBorderColor)!=null?mt:"":(We=dt==null?void 0:dt.borderColor)!=null?We:"";Do(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=$,N.style.borderColor=U;let X=D||"currentColor";N.style.color=X,fa(C,X);let _=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",_),g==="none"&&(N.style.cursor="default"),g==="barge-in"&&N.classList.add("persona-voice-recording")},Wn=()=>{var c,g,y;N&&(Do(),dt&&(N.style.backgroundColor=(c=dt.backgroundColor)!=null?c:"",N.style.color=(g=dt.color)!=null?g:"",N.style.borderColor=(y=dt.borderColor)!=null?y:"",fa(dt.iconName,dt.color||"currentColor"),dt=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},Qn=()=>{var c,g;if(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let y=q.getVoiceStatus(),C=q.getVoiceInterruptionMode();if(C==="none"&&(y==="processing"||y==="speaking"))return;if(C==="cancel"&&(y==="processing"||y==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()});return}q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bt.manuallyDeactivated=!q.isVoiceActive(),Qr(),bn("user"),q.isVoiceActive()?Co():Wn()});return}if(dn){let y=ne.value.trim();bt.manuallyDeactivated=!0,Qr(),Bn("user"),y&&(ne.value="",ne.style.height="auto",q.sendMessage(y))}else bt.manuallyDeactivated=!1,Qr(),Wo("user")};hn=Qn,N&&(N.addEventListener("click",Qn),vt.push(()=>{var c,g;((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Wn()):Bn("system"),N&&N.removeEventListener("click",Qn)}));let Ze=a.on("assistant:complete",()=>{Na&&(bt.active||bt.manuallyDeactivated||Na==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!bt.active&&!bt.manuallyDeactivated&&(((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("auto"),q.isVoiceActive()&&Co()}):Wo("auto"))},600))});vt.push(Ze);let P=a.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});vt.push(P);let z=()=>{Nt(!R,"user")},I=null,V=null;if(T&&!O()){let c=o.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});g&&(V=g)}V||(I=Ms(n,z))}I?e.appendChild(I.element):V&&e.appendChild(V),bo(),Ln.render(n.suggestionChips,q,ne,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming()),go(!0),$s(),E&&(!T||O()?setTimeout(()=>pa(),0):R&&setTimeout(()=>pa(),200));let fe=()=>{var _,Te,me,re,be,Me,Ve,lt,tt,ft,mt,We,Be,Je,W,Re,Ne,Qe,Ae,Dt,pt,cr;if(O()){Rr(),bo();return}let c=hr(n),g=(Te=(_=n.launcher)==null?void 0:_.sidebarMode)!=null?Te:!1,y=c||g||((re=(me=n.launcher)==null?void 0:me.fullHeight)!=null?re:!1),C=(be=e.ownerDocument.defaultView)!=null?be:window,D=(Ve=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?Ve:!0,$=(tt=(lt=n.launcher)==null?void 0:lt.mobileBreakpoint)!=null?tt:640,U=C.innerWidth<=$,X=D&&U&&T;try{if(X){Mn(),vo(e,n);return}if(L&&(L=!1,Mn(),vo(e,n)),!T&&!c){G.style.height="",G.style.width="";return}if(!g&&!c){let Lr=(mt=(ft=n==null?void 0:n.launcher)==null?void 0:ft.width)!=null?mt:n==null?void 0:n.launcherWidth,Ft=Lr!=null?Lr:mn;G.style.width=Ft,G.style.maxWidth=Ft}if(Fn(),!y){let Lr=C.innerHeight,Ft=64,Ur=(Be=(We=n.launcher)==null?void 0:We.heightOffset)!=null?Be:0,Pr=Math.max(200,Lr-Ft),st=Math.min(640,Pr),gt=Math.max(200,st-Ur);G.style.height=`${gt}px`}}finally{if(Rr(),bo(),R&&T){let Ft=((Je=e.ownerDocument.defaultView)!=null?Je:window).innerWidth<=((Re=(W=n.launcher)==null?void 0:W.mobileBreakpoint)!=null?Re:640),Ur=(Qe=(Ne=n.launcher)==null?void 0:Ne.sidebarMode)!=null?Qe:!1,Pr=(Dt=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Dt:!0,st=hr(n)&&Pr&&Ft,gt=Ur||Pr&&Ft&&T||st;if(gt&&!ir){let qr=e.getRootNode(),Br=qr instanceof ShadowRoot?qr.host:e.closest(".persona-host");Br&&!sr&&(sr=ip(Br,(cr=(pt=n.launcher)==null?void 0:pt.zIndex)!=null?cr:Or)),ir=lp(e.ownerDocument)}else gt||(sr==null||sr(),sr=null,ir==null||ir(),ir=null)}}};fe();let te=(Fu=e.ownerDocument.defaultView)!=null?Fu:window;if(te.addEventListener("resize",fe),vt.push(()=>te.removeEventListener("resize",fe)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Rr()});c.observe(qe),vt.push(()=>c.disconnect())}Rn=ve.scrollTop;let et=ve.scrollHeight,ze=()=>{let c=ve.scrollTop,g=ve.scrollHeight,y=g<et;et=g;let{action:C,nextLastScrollTop:D}=Ki({following:In.isFollowing(),currentScrollTop:c,lastScrollTop:Rn,nearBottom:ws(ve,Fa),userScrollThreshold:Ns,isAutoScrolling:Gn||Ro||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Rn=D,C==="resume"){mo();return}C==="pause"&&$a()};ve.addEventListener("scroll",ze,{passive:!0}),vt.push(()=>ve.removeEventListener("scroll",ze));let ct=c=>{let g=Yi({following:In.isFollowing(),deltaY:c.deltaY,nearBottom:ws(ve,Fa),resumeWhenNearBottom:!0});g==="pause"?$a():g==="resume"&&mo()};ve.addEventListener("wheel",ct,{passive:!0}),vt.push(()=>ve.removeEventListener("wheel",ct)),it.addEventListener("click",()=>{ve.scrollTop=ve.scrollHeight,Rn=ve.scrollTop,mo(),go(!0)}),vt.push(()=>it.remove()),vt.push(()=>{_a()});let at=()=>{F&&(sn&&(F.removeEventListener("click",sn),sn=null),H()?(F.style.display="",sn=()=>{Nt(!1,"user")},F.addEventListener("click",sn)):F.style.display="none")};at(),(()=>{let{clearChatButton:c}=ke;c&&c.addEventListener("click",()=>{q.clearMessages(),ln.clear(),mo(),Lo(ke.composerOverlay);try{localStorage.removeItem(Wa),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wa)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},k.syncFromMetadata(),J==null||J.clear(),ce==null||ce.update()})})(),Ot&&Ot.addEventListener("submit",Ga),ne==null||ne.addEventListener("keydown",Xa),ne==null||ne.addEventListener("paste",Ja);let Gt="persona-attachment-drop-active",lr=0,Rt=()=>{lr=0,ae.classList.remove(Gt)},Lt=()=>{var c;return((c=n.attachments)==null?void 0:c.enabled)===!0&&Tt!==null},yr=c=>{!Sl(c.dataTransfer)||!Lt()||(lr++,lr===1&&ae.classList.add(Gt))},Hr=c=>{!Sl(c.dataTransfer)||!Lt()||(lr--,lr<=0&&Rt())},Mr=c=>{!Sl(c.dataTransfer)||!Lt()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},dr=c=>{var y;if(!Sl(c.dataTransfer)||!Lt())return;c.preventDefault(),c.stopPropagation(),Rt();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&Tt.handleFiles(g)},vr=!0;ae.addEventListener("dragenter",yr,vr),ae.addEventListener("dragleave",Hr,vr),e.addEventListener("dragover",Mr,vr),e.addEventListener("drop",dr,vr);let ei=e.ownerDocument,Kp=c=>{Lt()&&c.preventDefault()},Yp=c=>{Lt()&&c.preventDefault()};ei.addEventListener("dragover",Kp),ei.addEventListener("drop",Yp),vt.push(()=>{Ot&&Ot.removeEventListener("submit",Ga),ne==null||ne.removeEventListener("keydown",Xa),ne==null||ne.removeEventListener("paste",Ja)}),vt.push(()=>{ae.removeEventListener("dragenter",yr,vr),ae.removeEventListener("dragleave",Hr,vr),e.removeEventListener("dragover",Mr,vr),e.removeEventListener("drop",dr,vr),ei.removeEventListener("dragover",Kp),ei.removeEventListener("drop",Yp),Rt()}),vt.push(()=>{q.cancel()}),I?vt.push(()=>{I==null||I.destroy()}):V&&vt.push(()=>{V==null||V.remove()});let mr={update(c){var gr,$n,eo,ti,ri,ni,$o,oi,Ya,Vu,ju,Gu,Xu,Ju,Ku,Yu,Qu,Zu,ef,tf,rf,nf,of,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,Cf,wf,vf,Af,Sf,Tf,kf,Ef,Mf,Lf,Pf,If,Rf,Hf,Bf,Wf,Df,Of,Ff,Nf,_f,$f,Uf,qf,zf,Vf,jf,Gf,Xf,Jf,Kf,Yf,Qf,Zf,em,tm,rm,nm,om,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,Cm,wm,vm,Am,Sm,Tm,km,Em,Mm,Lm,Pm,Im,Rm,Hm,Bm,Wm,Dm,Om,Fm,Nm,_m,$m;let g=n.toolCall,y=n.messageActions,C=(gr=n.layout)==null?void 0:gr.messages,D=n.colorScheme,$=n.loadingIndicator,U=n.iterationDisplay,X=($n=n.features)==null?void 0:$n.showReasoning,_=(eo=n.features)==null?void 0:eo.showToolCalls,Te=(ti=n.features)==null?void 0:ti.toolCallDisplay,me=(ri=n.features)==null?void 0:ri.reasoningDisplay;n={...n,...c},Mn(),vo(e,n),gl(e,n),hl(e,n),on(),n.colorScheme!==D&&fo();let re=Bs.getForInstance(n.plugins);o.length=0,o.push(...re),T=($o=(ni=n.launcher)==null?void 0:ni.enabled)!=null?$o:!0,A=(Ya=(oi=n.launcher)==null?void 0:oi.autoExpand)!=null?Ya:!1,De=(ju=(Vu=n.features)==null?void 0:Vu.showReasoning)!=null?ju:!0,Xe=(Xu=(Gu=n.features)==null?void 0:Gu.showToolCalls)!=null?Xu:!0,ge=(Ku=(Ju=n.features)==null?void 0:Ju.scrollToBottom)!=null?Ku:{},Tn(),Jn();let be=xe;if(xe=(Qu=(Yu=n.features)==null?void 0:Yu.showEventStreamToggle)!=null?Qu:!1,xe&&!be){if(J||(Q=new Hs(Ge),J=new Rs(Se,Q),Q.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),q.setSSEEventCallback((ee,Ht)=>{var Xt;(Xt=n.onSSEEvent)==null||Xt.call(n,ee,Ht),J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Ht)})})),!xt&&Ue){let ee=(ef=(Zu=n.features)==null?void 0:Zu.eventStream)==null?void 0:ef.classNames,Ht="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");xt=x("button",Ht),xt.style.width="28px",xt.style.height="28px",xt.style.color=Kr.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Xt=Ce("activity","18px","currentColor",1.5);Xt&&xt.appendChild(Xt);let ht=ke.clearChatButtonWrapper,Wt=ke.closeButtonWrapper,br=ht||Wt;br&&br.parentNode===Ue?Ue.insertBefore(xt,br):Ue.appendChild(xt),xt.addEventListener("click",()=>{pe?Yr():Sr()})}}else!xe&&be&&(Yr(),xt&&(xt.remove(),xt=null),J==null||J.clear(),Q==null||Q.destroy(),J=null,Q=null);if(((tf=n.launcher)==null?void 0:tf.enabled)===!1&&I&&(I.destroy(),I=null),((rf=n.launcher)==null?void 0:rf.enabled)===!1&&V&&(V.remove(),V=null),((nf=n.launcher)==null?void 0:nf.enabled)!==!1&&!I&&!V){let ee=o.find(Ht=>Ht.renderLauncher);if(ee!=null&&ee.renderLauncher){let Ht=ee.renderLauncher({config:n,defaultRenderer:()=>Ms(n,z).element,onToggle:z});Ht&&(V=Ht,e.appendChild(V))}V||(I=Ms(n,z),e.appendChild(I.element))}I&&I.update(n),Fe&&((of=n.launcher)==null?void 0:of.title)!==void 0&&(Fe.textContent=n.launcher.title),Ke&&((af=n.launcher)==null?void 0:af.subtitle)!==void 0&&(Ke.textContent=n.launcher.subtitle);let Me=(sf=n.layout)==null?void 0:sf.header;if((Me==null?void 0:Me.layout)!==S&&Ue){let ee=Me?Ta(n,Me,{showClose:H(),onClose:()=>Nt(!1,"user")}):ao({config:n,showClose:H(),onClose:()=>Nt(!1,"user")});Ue.replaceWith(ee.header),Ue=ee.header,le=ee.iconHolder,Fe=ee.headerTitle,Ke=ee.headerSubtitle,F=ee.closeButton,S=Me==null?void 0:Me.layout}else if(Me&&(le&&(le.style.display=Me.showIcon===!1?"none":""),Fe&&(Fe.style.display=Me.showTitle===!1?"none":""),Ke&&(Ke.style.display=Me.showSubtitle===!1?"none":""),F&&(F.style.display=Me.showCloseButton===!1?"none":""),ke.clearChatButtonWrapper)){let ee=Me.showClearChat;if(ee!==void 0){ke.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ht}=ke;Ht&&!Ht.classList.contains("persona-absolute")&&(ee?Ht.classList.remove("persona-ml-auto"):Ht.classList.add("persona-ml-auto"))}}let lt=((lf=n.layout)==null?void 0:lf.showHeader)!==!1;Ue&&(Ue.style.display=lt?"":"none");let tt=((df=n.layout)==null?void 0:df.showFooter)!==!1;qe&&(qe.style.display=tt?"":"none"),Rr(),Jn(),T!==h?T?Nt(A,"auto"):(R=!0,bo()):A!==b&&Nt(A,"auto"),b=A,h=T,fe(),at();let We=JSON.stringify(c.toolCall)!==JSON.stringify(g),Be=JSON.stringify(n.messageActions)!==JSON.stringify(y),Je=JSON.stringify((cf=n.layout)==null?void 0:cf.messages)!==JSON.stringify(C),W=((pf=n.loadingIndicator)==null?void 0:pf.render)!==($==null?void 0:$.render)||((uf=n.loadingIndicator)==null?void 0:uf.renderIdle)!==($==null?void 0:$.renderIdle)||((ff=n.loadingIndicator)==null?void 0:ff.showBubble)!==($==null?void 0:$.showBubble),Re=n.iterationDisplay!==U,Ne=((gf=(mf=n.features)==null?void 0:mf.showReasoning)!=null?gf:!0)!==(X!=null?X:!0)||((xf=(hf=n.features)==null?void 0:hf.showToolCalls)!=null?xf:!0)!==(_!=null?_:!0)||JSON.stringify((yf=n.features)==null?void 0:yf.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((bf=n.features)==null?void 0:bf.reasoningDisplay)!==JSON.stringify(me);(We||Be||Je||W||Re||Ne)&&q&&(Oa++,Bo(ye,q.getMessages(),ue));let Ae=(Cf=n.launcher)!=null?Cf:{},Dt=(wf=Ae.headerIconHidden)!=null?wf:!1,pt=(Af=(vf=n.layout)==null?void 0:vf.header)==null?void 0:Af.showIcon,cr=Dt||pt===!1,Lr=Ae.headerIconName,Ft=(Sf=Ae.headerIconSize)!=null?Sf:"48px";if(le){let ee=ae.querySelector(".persona-border-b-persona-divider"),Ht=ee==null?void 0:ee.querySelector(".persona-flex-col");if(cr)le.style.display="none",ee&&Ht&&!ee.contains(Ht)&&ee.insertBefore(Ht,ee.firstChild);else{if(le.style.display="",le.style.height=Ft,le.style.width=Ft,ee&&Ht&&(ee.contains(le)?le.nextSibling!==Ht&&(le.remove(),ee.insertBefore(le,Ht)):ee.insertBefore(le,Ht)),Lr){let ht=parseFloat(Ft)||24,Wt=Ce(Lr,ht*.6,"#ffffff",2);Wt?le.replaceChildren(Wt):le.textContent=(Tf=Ae.agentIconText)!=null?Tf:"\u{1F4AC}"}else if(Ae.iconUrl){let ht=le.querySelector("img");if(ht)ht.src=Ae.iconUrl,ht.style.height=Ft,ht.style.width=Ft;else{let Wt=document.createElement("img");Wt.src=Ae.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=Ft,Wt.style.width=Ft,le.replaceChildren(Wt)}}else{let ht=le.querySelector("svg"),Wt=le.querySelector("img");(ht||Wt)&&le.replaceChildren(),le.textContent=(kf=Ae.agentIconText)!=null?kf:"\u{1F4AC}"}let Xt=le.querySelector("img");Xt&&(Xt.style.height=Ft,Xt.style.width=Ft)}}let Ur=(Mf=(Ef=n.layout)==null?void 0:Ef.header)==null?void 0:Mf.showTitle,Pr=(Pf=(Lf=n.layout)==null?void 0:Lf.header)==null?void 0:Pf.showSubtitle;if(Fe&&(Fe.style.display=Ur===!1?"none":""),Ke&&(Ke.style.display=Pr===!1?"none":""),F){((Rf=(If=n.layout)==null?void 0:If.header)==null?void 0:Rf.showCloseButton)===!1?F.style.display="none":F.style.display="";let Ht=(Hf=Ae.closeButtonSize)!=null?Hf:"32px",Xt=(Bf=Ae.closeButtonPlacement)!=null?Bf:"inline";F.style.height=Ht,F.style.width=Ht;let{closeButtonWrapper:ht}=ke,Wt=Xt==="top-right",br=ht==null?void 0:ht.classList.contains("persona-absolute");if(ht&&Wt!==br)if(ht.remove(),Wt)ht.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ae.style.position="relative",ae.appendChild(ht);else{let yt=(Df=(Wf=Ae.clearChat)==null?void 0:Wf.placement)!=null?Df:"inline",Cr=(Ff=(Of=Ae.clearChat)==null?void 0:Of.enabled)!=null?Ff:!0;ht.className=Cr&&yt==="inline"?"":"persona-ml-auto";let rn=ae.querySelector(".persona-border-b-persona-divider");rn&&rn.appendChild(ht)}if(F.style.color=Ae.closeButtonColor||Kr.actionIconColor,Ae.closeButtonBackgroundColor?(F.style.backgroundColor=Ae.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),Ae.closeButtonBorderWidth||Ae.closeButtonBorderColor){let yt=Ae.closeButtonBorderWidth||"0px",Cr=Ae.closeButtonBorderColor||"transparent";F.style.border=`${yt} solid ${Cr}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");Ae.closeButtonBorderRadius?(F.style.borderRadius=Ae.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),Ae.closeButtonPaddingX?(F.style.paddingLeft=Ae.closeButtonPaddingX,F.style.paddingRight=Ae.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),Ae.closeButtonPaddingY?(F.style.paddingTop=Ae.closeButtonPaddingY,F.style.paddingBottom=Ae.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let Wr=(Nf=Ae.closeButtonIconName)!=null?Nf:"x",Dn=(_f=Ae.closeButtonIconText)!=null?_f:"\xD7";F.innerHTML="";let Vr=Ce(Wr,"28px","currentColor",1);Vr?F.appendChild(Vr):F.textContent=Dn;let pr=($f=Ae.closeButtonTooltipText)!=null?$f:"Close chat",pn=(Uf=Ae.closeButtonShowTooltip)!=null?Uf:!0;if(F.setAttribute("aria-label",pr),ht&&(ht._cleanupTooltip&&(ht._cleanupTooltip(),delete ht._cleanupTooltip),pn&&pr)){let yt=null,Cr=()=>{if(yt||!F)return;let Uo=F.ownerDocument,Qa=Uo.body;if(!Qa)return;yt=qn(Uo,"div","persona-clear-chat-tooltip"),yt.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",yt.appendChild(Za);let qo=F.getBoundingClientRect();yt.style.position="fixed",yt.style.zIndex=String(Ao),yt.style.left=`${qo.left+qo.width/2}px`,yt.style.top=`${qo.top-8}px`,yt.style.transform="translate(-50%, -100%)",Qa.appendChild(yt)},rn=()=>{yt&&yt.parentNode&&(yt.parentNode.removeChild(yt),yt=null)};ht.addEventListener("mouseenter",Cr),ht.addEventListener("mouseleave",rn),F.addEventListener("focus",Cr),F.addEventListener("blur",rn),ht._cleanupTooltip=()=>{rn(),ht&&(ht.removeEventListener("mouseenter",Cr),ht.removeEventListener("mouseleave",rn)),F&&(F.removeEventListener("focus",Cr),F.removeEventListener("blur",rn))}}}let{clearChatButton:st,clearChatButtonWrapper:gt}=ke;if(st){let ee=(qf=Ae.clearChat)!=null?qf:{},Ht=(zf=ee.enabled)!=null?zf:!0,Xt=(jf=(Vf=n.layout)==null?void 0:Vf.header)==null?void 0:jf.showClearChat,ht=Xt!==void 0?Xt:Ht,Wt=(Gf=ee.placement)!=null?Gf:"inline";if(gt){gt.style.display=ht?"":"none";let{closeButtonWrapper:br}=ke;!O()&&br&&!br.classList.contains("persona-absolute")&&(ht?br.classList.remove("persona-ml-auto"):br.classList.add("persona-ml-auto"));let Wr=Wt==="top-right",Dn=gt.classList.contains("persona-absolute");if(!O()&&Wr!==Dn&&ht){if(gt.remove(),Wr)gt.className="persona-absolute persona-top-4 persona-z-50",gt.style.right="48px",ae.style.position="relative",ae.appendChild(gt);else{gt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gt.style.right="";let pr=ae.querySelector(".persona-border-b-persona-divider"),pn=ke.closeButtonWrapper;pr&&pn&&pn.parentElement===pr?pr.insertBefore(gt,pn):pr&&pr.appendChild(gt)}let Vr=ke.closeButtonWrapper;Vr&&!Vr.classList.contains("persona-absolute")&&(Wr?Vr.classList.add("persona-ml-auto"):Vr.classList.remove("persona-ml-auto"))}}if(ht){if(!O()){let yt=(Xf=ee.size)!=null?Xf:"32px";st.style.height=yt,st.style.width=yt}let br=(Jf=ee.iconName)!=null?Jf:"refresh-cw",Wr=(Kf=ee.iconColor)!=null?Kf:"";st.style.color=Wr||Kr.actionIconColor,st.innerHTML="";let Dn=O()?"14px":"20px",Vr=Ce(br,Dn,"currentColor",2);if(Vr&&st.appendChild(Vr),ee.backgroundColor?(st.style.backgroundColor=ee.backgroundColor,st.classList.remove("hover:persona-bg-gray-100")):(st.style.backgroundColor="",st.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let yt=ee.borderWidth||"0px",Cr=ee.borderColor||"transparent";st.style.border=`${yt} solid ${Cr}`,st.classList.remove("persona-border-none")}else st.style.border="",st.classList.add("persona-border-none");ee.borderRadius?(st.style.borderRadius=ee.borderRadius,st.classList.remove("persona-rounded-full")):(st.style.borderRadius="",st.classList.add("persona-rounded-full")),ee.paddingX?(st.style.paddingLeft=ee.paddingX,st.style.paddingRight=ee.paddingX):(st.style.paddingLeft="",st.style.paddingRight=""),ee.paddingY?(st.style.paddingTop=ee.paddingY,st.style.paddingBottom=ee.paddingY):(st.style.paddingTop="",st.style.paddingBottom="");let pr=(Yf=ee.tooltipText)!=null?Yf:"Clear chat",pn=(Qf=ee.showTooltip)!=null?Qf:!0;if(st.setAttribute("aria-label",pr),gt&&(gt._cleanupTooltip&&(gt._cleanupTooltip(),delete gt._cleanupTooltip),pn&&pr)){let yt=null,Cr=()=>{if(yt||!st)return;let Uo=st.ownerDocument,Qa=Uo.body;if(!Qa)return;yt=qn(Uo,"div","persona-clear-chat-tooltip"),yt.textContent=pr;let Za=qn(Uo,"div");Za.className="persona-clear-chat-tooltip-arrow",yt.appendChild(Za);let qo=st.getBoundingClientRect();yt.style.position="fixed",yt.style.zIndex=String(Ao),yt.style.left=`${qo.left+qo.width/2}px`,yt.style.top=`${qo.top-8}px`,yt.style.transform="translate(-50%, -100%)",Qa.appendChild(yt)},rn=()=>{yt&&yt.parentNode&&(yt.parentNode.removeChild(yt),yt=null)};gt.addEventListener("mouseenter",Cr),gt.addEventListener("mouseleave",rn),st.addEventListener("focus",Cr),st.addEventListener("blur",rn),gt._cleanupTooltip=()=>{rn(),gt&&(gt.removeEventListener("mouseenter",Cr),gt.removeEventListener("mouseleave",rn)),st&&(st.removeEventListener("focus",Cr),st.removeEventListener("blur",rn))}}}}let qr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ws],Br=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[sa.message,sa.messageAndClick];k=Ds({parsers:qr,handlers:Br,getSessionMetadata:m,updateSessionMetadata:f,emit:a.emit,documentRef:typeof document!="undefined"?document:null}),ue=Uh(n,k,oe),q.updateConfig(n),Bo(ye,q.getMessages(),ue),Ln.render(n.suggestionChips,q,ne,void 0,n.suggestionChipsConfig),Va(),ca(q.isStreaming());let Oo=((Zf=n.voiceRecognition)==null?void 0:Zf.enabled)===!0,Fo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),No=((tm=(em=n.voiceRecognition)==null?void 0:em.provider)==null?void 0:tm.type)==="runtype";if(Oo&&(Fo||No))if(!N||!de){let ee=Ys(n.voiceRecognition,n.sendButton);ee&&(N=ee.micButton,de=ee.micButtonWrapper,Pt.insertBefore(de,fr),N.addEventListener("click",Qn),N.disabled=q.isStreaming())}else{let ee=(rm=n.voiceRecognition)!=null?rm:{},Ht=(nm=n.sendButton)!=null?nm:{},Xt=(om=ee.iconName)!=null?om:"mic",ht=(am=Ht.size)!=null?am:"40px",Wt=(sm=ee.iconSize)!=null?sm:ht,br=parseFloat(Wt)||24;N.style.width=Wt,N.style.height=Wt,N.style.minWidth=Wt,N.style.minHeight=Wt;let Wr=(lm=(im=ee.iconColor)!=null?im:Ht.textColor)!=null?lm:"currentColor";N.innerHTML="";let Dn=Ce(Xt,br,Wr,2);Dn?N.appendChild(Dn):N.textContent="\u{1F3A4}";let Vr=(dm=ee.backgroundColor)!=null?dm:Ht.backgroundColor;Vr?N.style.backgroundColor=Vr:N.style.backgroundColor="",Wr?N.style.color=Wr:N.style.color="var(--persona-text, #111827)",ee.borderWidth?(N.style.borderWidth=ee.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),ee.borderColor?N.style.borderColor=ee.borderColor:N.style.borderColor="",ee.paddingX?(N.style.paddingLeft=ee.paddingX,N.style.paddingRight=ee.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),ee.paddingY?(N.style.paddingTop=ee.paddingY,N.style.paddingBottom=ee.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let pr=de==null?void 0:de.querySelector(".persona-send-button-tooltip"),pn=(cm=ee.tooltipText)!=null?cm:"Start voice recognition";if(((pm=ee.showTooltip)!=null?pm:!1)&&pn)if(pr)pr.textContent=pn,pr.style.display="";else{let Cr=document.createElement("div");Cr.className="persona-send-button-tooltip",Cr.textContent=pn,de==null||de.insertBefore(Cr,N)}else pr&&(pr.style.display="none");de.style.display="",N.disabled=q.isStreaming()}else N&&de&&(de.style.display="none",((fm=(um=n.voiceRecognition)==null?void 0:um.provider)==null?void 0:fm.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():dn&&Bn());if(((mm=n.attachments)==null?void 0:mm.enabled)===!0)if(!ut||!Ee){let ee=(gm=n.attachments)!=null?gm:{},Xt=(xm=((hm=n.sendButton)!=null?hm:{}).size)!=null?xm:"40px";Ut||(Ut=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",Ot.insertBefore(Ut,ne)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((ym=ee.allowedTypes)!=null?ym:oo).join(","),Ye.multiple=((bm=ee.maxFiles)!=null?bm:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),Ot.insertBefore(Ye,ne)),ut=x("div","persona-send-button-wrapper"),Ee=x("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ee.type="button",Ee.setAttribute("aria-label",(Cm=ee.buttonTooltipText)!=null?Cm:"Attach file");let ht=(wm=ee.buttonIconName)!=null?wm:"paperclip",Wt=Xt,br=parseFloat(Wt)||40,Wr=Math.round(br*.6);Ee.style.width=Wt,Ee.style.height=Wt,Ee.style.minWidth=Wt,Ee.style.minHeight=Wt,Ee.style.fontSize="18px",Ee.style.lineHeight="1",Ee.style.backgroundColor="transparent",Ee.style.color="var(--persona-primary, #111827)",Ee.style.border="none",Ee.style.borderRadius="6px",Ee.style.transition="background-color 0.15s ease",Ee.addEventListener("mouseenter",()=>{Ee.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ee.addEventListener("mouseleave",()=>{Ee.style.backgroundColor="transparent"});let Dn=Ce(ht,Wr,"currentColor",1.5);Dn?Ee.appendChild(Dn):Ee.textContent="\u{1F4CE}",Ee.addEventListener("click",pn=>{pn.preventDefault(),Ye==null||Ye.click()}),ut.appendChild(Ee);let Vr=(vm=ee.buttonTooltipText)!=null?vm:"Attach file",pr=x("div","persona-send-button-tooltip");pr.textContent=Vr,ut.appendChild(pr),Ct.append(ut),!Tt&&Ye&&Ut&&(Tt=ta.fromConfig(ee),Tt.setPreviewsContainer(Ut),Ye.addEventListener("change",async()=>{Tt&&(Ye!=null&&Ye.files)&&(await Tt.handleFileSelect(Ye.files),Ye.value="")})),ae.querySelector(".persona-attachment-drop-overlay")||ae.appendChild(qh(ee.dropOverlay))}else{ut.style.display="";let ee=(Am=n.attachments)!=null?Am:{};Ye&&(Ye.accept=((Sm=ee.allowedTypes)!=null?Sm:oo).join(","),Ye.multiple=((Tm=ee.maxFiles)!=null?Tm:4)>1),Tt&&Tt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ut&&(ut.style.display="none"),Tt&&Tt.clearAttachments(),(km=ae.querySelector(".persona-attachment-drop-overlay"))==null||km.remove();let rr=(Em=n.sendButton)!=null?Em:{},_o=(Mm=rr.useIcon)!=null?Mm:!1,wo=(Lm=rr.iconText)!=null?Lm:"\u2191",Et=rr.iconName,Zr=(Pm=rr.tooltipText)!=null?Pm:"Send message",Zn=(Im=rr.showTooltip)!=null?Im:!1,zr=(Rm=rr.size)!=null?Rm:"40px",en=rr.backgroundColor,zt=rr.textColor;if(_o){if(He.style.width=zr,He.style.height=zr,He.style.minWidth=zr,He.style.minHeight=zr,He.style.fontSize="18px",He.style.lineHeight="1",He.innerHTML="",zt?He.style.color=zt:He.style.color="var(--persona-button-primary-fg, #ffffff)",Et){let ee=parseFloat(zr)||24,Ht=(zt==null?void 0:zt.trim())||"currentColor",Xt=Ce(Et,ee,Ht,2);Xt?He.appendChild(Xt):He.textContent=wo}else He.textContent=wo;He.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",en?(He.style.backgroundColor=en,He.classList.remove("persona-bg-persona-primary")):(He.style.backgroundColor="",He.classList.add("persona-bg-persona-primary"))}else He.textContent=(Bm=(Hm=n.copy)==null?void 0:Hm.sendButtonLabel)!=null?Bm:"Send",He.style.width="",He.style.height="",He.style.minWidth="",He.style.minHeight="",He.style.fontSize="",He.style.lineHeight="",He.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",en?(He.style.backgroundColor=en,He.classList.remove("persona-bg-persona-accent")):He.classList.add("persona-bg-persona-accent"),zt?He.style.color=zt:He.classList.add("persona-text-white");rr.borderWidth?(He.style.borderWidth=rr.borderWidth,He.style.borderStyle="solid"):(He.style.borderWidth="",He.style.borderStyle=""),rr.borderColor?He.style.borderColor=rr.borderColor:He.style.borderColor="",rr.paddingX?(He.style.paddingLeft=rr.paddingX,He.style.paddingRight=rr.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),rr.paddingY?(He.style.paddingTop=rr.paddingY,He.style.paddingBottom=rr.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Zt=fr==null?void 0:fr.querySelector(".persona-send-button-tooltip");if(Zn&&Zr)if(Zt)Zt.textContent=Zr,Zt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=Zr,fr==null||fr.insertBefore(ee,He)}else Zt&&(Zt.style.display="none");let Vt=(Nm=(Wm=n.layout)==null?void 0:Wm.contentMaxWidth)!=null?Nm:O()?(Fm=(Om=(Dm=n.launcher)==null?void 0:Dm.composerBar)==null?void 0:Om.contentMaxWidth)!=null?Fm:"720px":void 0;Vt?(ye.style.maxWidth=Vt,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",Ot&&(Ot.style.maxWidth=Vt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=Vt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(ye.style.maxWidth="",ye.style.marginLeft="",ye.style.marginRight="",ye.style.width="",Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let nr=(_m=n.statusIndicator)!=null?_m:{},tn=($m=nr.visible)!=null?$m:!0;if(Yt.style.display=tn?"":"none",q){let ee=q.getStatus();$e(Yt,(Xt=>{var ht,Wt,br,Wr;return Xt==="idle"?(ht=nr.idleText)!=null?ht:Dr.idle:Xt==="connecting"?(Wt=nr.connectingText)!=null?Wt:Dr.connecting:Xt==="connected"?(br=nr.connectedText)!=null?br:Dr.connected:Xt==="error"?(Wr=nr.errorText)!=null?Wr:Dr.error:Dr[Xt]})(ee),nr,ee)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let cn=nr.align==="left"?"persona-text-left":nr.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(cn)},open(){H()&&Nt(!0,"api")},close(){H()&&Nt(!1,"api")},toggle(){H()&&Nt(!R,"api")},clearChat(){Z=!1,q.clearMessages(),ln.clear(),mo();try{localStorage.removeItem(Wa),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wa}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wa)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},k.syncFromMetadata(),J==null||J.clear(),ce==null||ce.update()},setMessage(c){return!ne||q.isStreaming()?!1:(!R&&H()&&Nt(!0,"system"),ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(q.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ne.value.trim();return g?(!R&&H()&&Nt(!0,"system"),ne.value="",ne.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return q.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(q.isVoiceActive()||(!R&&H()&&Nt(!0,"system"),bt.manuallyDeactivated=!1,Qr(),q.toggleVoice().then(()=>{bt.active=q.isVoiceActive(),bn("user"),q.isVoiceActive()&&Co()})),!0):dn?!0:Ka()?(!R&&H()&&Nt(!0,"system"),bt.manuallyDeactivated=!1,Qr(),Wo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=n.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Qr(),bn("user"),Wn()}),!0):!1:dn?(bt.manuallyDeactivated=!0,Qr(),Bn("user"),!0):!1},injectMessage(c){return!R&&H()&&Nt(!0,"system"),q.injectMessage(c)},injectAssistantMessage(c){!R&&H()&&Nt(!0,"system");let g=q.injectAssistantMessage(c);return B&&(B=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(c){return!R&&H()&&Nt(!0,"system"),q.injectUserMessage(c)},injectSystemMessage(c){return!R&&H()&&Nt(!0,"system"),q.injectSystemMessage(c)},injectMessageBatch(c){return!R&&H()&&Nt(!0,"system"),q.injectMessageBatch(c)},injectComponentDirective(c){return!R&&H()&&Nt(!0,"system"),q.injectComponentDirective(c)},injectTestMessage(c){!R&&H()&&Nt(!0,"system"),q.injectTestEvent(c)},async connectStream(c,g){return q.connectStream(c,g)},__pushEventStreamEvent(c){J&&J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!xe||!J||Sr()},hideEventStream(){pe&&Yr()},isEventStreamVisible(){return pe},showArtifacts(){Sn(n)&&(Z=!1,on(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){Sn(n)&&(Z=!0,on())},upsertArtifact(c){return Sn(n)?(Z=!1,q.upsertArtifact(c)):null},selectArtifact(c){Sn(n)&&q.selectArtifact(c)},clearArtifacts(){Sn(n)&&q.clearArtifacts()},getArtifacts(){var c;return(c=q==null?void 0:q.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=q==null?void 0:q.getSelectedArtifactId())!=null?c:null},focusInput(){return T&&!R&&!O()||!ne?!1:(ne.focus(),!0)},async resolveApproval(c,g){let C=q.getMessages().find(D=>{var $;return D.variant==="approval"&&(($=D.approval)==null?void 0:$.id)===c});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${c}`);return q.resolveApproval(C.approval,g)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){f(c)},on(c,g){return a.on(c,g)},off(c,g){a.off(c,g)},isOpen(){return H()&&R},isVoiceActive(){return bt.active},getState(){return{open:H()&&R,launcherEnabled:T,voiceActive:bt.active,streaming:q.isStreaming()}},showCSATFeedback(c){!R&&H()&&Nt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let y=vl({onSubmit:async(C,D)=>{var $;q.isClientTokenMode()&&await q.submitCSATFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ye.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!R&&H()&&Nt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let y=Al({onSubmit:async(C,D)=>{var $;q.isClientTokenMode()&&await q.submitNPSFeedback(C,D),($=c==null?void 0:c.onSubmit)==null||$.call(c,C,D)},onDismiss:c==null?void 0:c.onDismiss,...c});ye.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return q.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return q.submitNPSFeedback(c,g)},destroy(){_n!=null&&(clearInterval(_n),_n=null),vt.forEach(c=>c()),Y.remove(),we==null||we.remove(),I==null||I.destroy(),V==null||V.remove(),sn&&F.removeEventListener("click",sn)}};if((((Nu=t==null?void 0:t.debugTools)!=null?Nu:!1)||!!n.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:mr,getMessages:mr.getMessages,getStatus:mr.getStatus,getMetadata:mr.getPersistentMetadata,updateMetadata:mr.updatePersistentMetadata,clearHistory:()=>mr.clearChat(),setVoiceActive:y=>y?mr.startVoiceRecognition():mr.stopVoiceRecognition()};window.AgentWidgetBrowser=g,vt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.focusInput()};if(window.addEventListener("persona:focusInput",g),vt.push(()=>{window.removeEventListener("persona:focusInput",g)}),xe){let X=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&mr.showEventStream()},_=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&mr.hideEventStream()};window.addEventListener("persona:showEventStream",X),window.addEventListener("persona:hideEventStream",_),vt.push(()=>{window.removeEventListener("persona:showEventStream",X),window.removeEventListener("persona:hideEventStream",_)})}let y=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.showArtifacts()},C=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.hideArtifacts()},D=X=>{let _=X.detail;_!=null&&_.instanceId&&_.instanceId!==c||_!=null&&_.artifact&&mr.upsertArtifact(_.artifact)},$=X=>{let _=X.detail;_!=null&&_.instanceId&&_.instanceId!==c||typeof(_==null?void 0:_.id)=="string"&&mr.selectArtifact(_.id)},U=X=>{let _=X.detail;(!(_!=null&&_.instanceId)||_.instanceId===c)&&mr.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",U),vt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",U)})}let Cn=X0(n.persistState);if(Cn&&H()){let c=J0(Cn.storage),g=`${Cn.keyPrefix}widget-open`,y=`${Cn.keyPrefix}widget-voice`,C=`${Cn.keyPrefix}widget-voice-mode`;if(c){let D=((_u=Cn.persist)==null?void 0:_u.openState)&&c.getItem(g)==="true",$=(($u=Cn.persist)==null?void 0:$u.voiceState)&&c.getItem(y)==="true",U=((Uu=Cn.persist)==null?void 0:Uu.voiceState)&&c.getItem(C)==="true";if(D&&setTimeout(()=>{mr.open(),setTimeout(()=>{var X;if($||U)mr.startVoiceRecognition();else if((X=Cn.persist)!=null&&X.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(qu=Cn.persist)!=null&&qu.openState&&(a.on("widget:opened",()=>{c.setItem(g,"true")}),a.on("widget:closed",()=>{c.setItem(g,"false")})),(zu=Cn.persist)!=null&&zu.voiceState&&(a.on("voice:state",X=>{c.setItem(y,X.active?"true":"false")}),a.on("user:message",X=>{c.setItem(C,X.viaVoice?"true":"false")})),Cn.clearOnChatClear){let X=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(C)},_=()=>X();window.addEventListener("persona:clear-chat",_),vt.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return u&&H()&&setTimeout(()=>{mr.open()},0),Kn(),mr};var K0=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,r*parseFloat(o[1])/100):420},zh=(e,r)=>{var n,o;let t=(o=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?o:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Wp=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Vh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Wp(e)},Rp=e=>{e.style.transition=""},Hp=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Bp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},kl=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Y0=(e,r,t,n,o)=>{o?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},Q0=(e,r,t,n,o,a)=>{let s=a?r:e;o==="left"?s.firstElementChild!==n&&s.replaceChildren(n,t):s.lastElementChild!==n&&s.replaceChildren(t,n)},jh=(e,r,t,n,o,a,s)=>{var w,v,k,T,A,E;let i=vn(a),d=i.reveal==="push";Y0(e,r,t,n,d),Q0(e,r,t,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(v=(w=a==null?void 0:a.launcher)==null?void 0:w.mobileFullscreen)!=null?v:!0,p=(T=(k=a==null?void 0:a.launcher)==null?void 0:k.mobileBreakpoint)!=null?T:640,m=l!=null?l.innerWidth<=p:!1;if(u&&m&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hp(r),Rp(n),Vh(n),Bp(t),kl(o,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((E=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?E:Or),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Vh(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Hp(r),Rp(n),Bp(t),kl(o,n);let b=i.animate?"transform 180ms ease":"none",h=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=s?"translateX(0)":h;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=b,n.style.transform=S,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Rp(n),Wp(n),kl(o,n);let b=K0(i.width,e.clientWidth),h=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",L=i.side==="right"?s?`translateX(-${b}px)`:"translateX(0)":s?"translateX(0)":`translateX(-${b}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${h+b}px`,r.style.transition=S,r.style.transform=L,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${h}px`,t.style.maxWidth=`${h}px`,t.style.minWidth=`${h}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Hp(r),Wp(n),Bp(t),kl(o,n);let b=i.reveal==="emerge";b?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let h=s?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",L=!s;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${h}`,n.style.width=h,n.style.maxWidth=h,n.style.minWidth=h,n.style.minHeight="0",n.style.position="relative",n.style.overflow=b||L?"hidden":"visible",n.style.transition=S,b&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Z0=(e,r)=>{let t=e.ownerDocument.createElement("div");return zh(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){zh(t,n)},destroy(){t.remove()}}},eC=(e,r)=>{var A,E,b,h;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(E=(A=r==null?void 0:r.launcher)==null?void 0:A.enabled)==null||E?(h=(b=r==null?void 0:r.launcher)==null?void 0:b.autoExpand)!=null?h:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),n.insertBefore(s,e),d.appendChild(e);let m=null,f=()=>{m==null||m.disconnect(),m=null},w=()=>{f(),vn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(m=new ResizeObserver(()=>{jh(s,i,d,l,u,r,p)}),m.observe(s))},v=()=>{jh(s,i,d,l,u,r,p),w()},k=s.ownerDocument.defaultView,T=()=>{v()};return k==null||k.addEventListener("resize",T),vn(r).reveal==="push"?(i.appendChild(d),i.appendChild(l),s.appendChild(i)):(s.appendChild(d),s.appendChild(l)),v(),{mode:"docked",host:u,shell:s,syncWidgetState(S){let L=S.launcherEnabled?S.open:!0;p!==L&&(p=L,v())},updateConfig(S){var L,O;r=S,((O=(L=r==null?void 0:r.launcher)==null?void 0:L.enabled)!=null?O:!0)===!1&&(p=!0),v()},destroy(){k==null||k.removeEventListener("resize",T),f(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}},Os=(e,r)=>hr(r)?eC(e,r):Z0(e,r);var Dp={},tC=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},rC=()=>{try{if(typeof Dp!="undefined"&&Dp.url)return new URL("../widget.css",Dp.url).href}catch{}return null},Gh=(e,r)=>{let t=rC(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=r.head.querySelector("link[data-persona]");if(!o)return;let a=o.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let a=r.createElement("link");a.rel="stylesheet",a.href=t,a.setAttribute("data-persona","true"),r.head.appendChild(a)}},Xh=e=>{var k;let r=tC(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,o=e.config,a=Os(r,o),s,i=[],d=(T,A)=>{var S,L;let b=!((L=(S=A==null?void 0:A.launcher)==null?void 0:S.enabled)!=null?L:!0)||hr(A),h=n.createElement("div");if(h.setAttribute("data-persona-root","true"),b&&(h.style.height="100%",h.style.display="flex",h.style.flexDirection="column",h.style.flex="1",h.style.minHeight="0"),t){let O=T.attachShadow({mode:"open"});O.appendChild(h),Gh(O,n)}else T.appendChild(h),Gh(T,n);return r.id&&h.setAttribute("data-persona-instance",r.id),h},l=()=>{a.syncWidgetState(s.getState())},u=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",l),s.on("widget:closed",l)],l()},p=()=>{let T=d(a.host,o);s=Tl(T,o,{debugTools:e.debugTools}),u()},m=()=>{i.forEach(T=>T()),i=[],s.destroy()};p(),(k=e.onReady)==null||k.call(e);let f=T=>{m(),a.destroy(),a=Os(r,T),o=T,p()},w={update(T){var L,O,H,R,B,j;let A={...o,...T,launcher:{...(L=o==null?void 0:o.launcher)!=null?L:{},...(O=T==null?void 0:T.launcher)!=null?O:{},dock:{...(R=(H=o==null?void 0:o.launcher)==null?void 0:H.dock)!=null?R:{},...(j=(B=T==null?void 0:T.launcher)==null?void 0:B.dock)!=null?j:{}}}},E=hr(o),b=hr(A),h=To(o),S=To(A);if(E!==b||h!==S){f(A);return}o=A,a.updateConfig(o),s.update(T),l()},destroy(){m(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(w,{get(T,A,E){if(A==="host")return a.host;if(A in T)return Reflect.get(T,A,E);let b=s[A];return typeof b=="function"?b.bind(s):b}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Zh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),nC=new Set(["button","a","input","select","textarea","details","summary"]),oC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Op=/\b(product|card|item|listing|result)\b/i,Np=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,aC=3e3,sC=100;function ex(e){let r=typeof e.className=="string"?e.className:"";if(Op.test(r)||e.id&&Op.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Op.test(n.value))return!0}return!1}function tx(e){var r;return Np.test(((r=e.textContent)!=null?r:"").trim())}function rx(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let o=(t=r[n].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function iC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Jh(e){let r=e.match(Np);return r?r[0]:null}function Kh(e){var n,o,a;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((o=r.textContent)!=null&&o.trim())){let s=r.getAttribute("href");return{title:r.textContent.trim(),href:s&&s!=="#"?s:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=t==null?void 0:t.textContent)!=null&&a.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function lC(e){let r=[],t=n=>{let o=n.trim();o&&!r.includes(o)&&r.push(o)};return e.querySelectorAll("button").forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var o;return t((o=n.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var o;t((o=n.value)!=null?o:"")}),r.slice(0,6)}var dC="commerce-card",cC="result-card";function Yh(e){return!ex(e)||!tx(e)||!rx(e)&&!iC(e)?0:5200}function Qh(e){var n;return!ex(e)||tx(e)||!rx(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var _p=[{id:dC,scoreElement(e){return Yh(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Np.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,l,u;if(Yh(e)===0)return null;let{title:t,href:n}=Kh(e),o=(u=(l=Jh(((d=e.textContent)!=null?d:"").trim()))!=null?l:Jh(r.text))!=null?u:"",a=lC(e);return[n&&t?`[${t}](${n})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||r.text.trim().slice(0,120),`selector: ${r.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
148
|
+
`)}},{id:cC,scoreElement(e){return Qh(e)},formatSummary(e,r){if(Qh(e)===0)return null;let{title:t,href:n}=Kh(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
|
|
149
|
+
`)}}];function pC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function uC(e){var u,p,m,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",o=(k=(v=r.maxTextLength)!=null?v:e.maxTextLength)!=null?k:200,a=(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:_p;return i==="simple"&&e.rules&&e.rules.length>0?(pC(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:l}}function Fp(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var fC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function mC(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||nC.has(r)||t&&oC.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function nx(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function gC(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let o=e.getAttribute("aria-label");o&&(r["aria-label"]=o);let a=e.getAttribute("type");a&&(r.type=a);let s=e.getAttribute("value");s&&(r.value=s);let i=e.getAttribute("name");i&&(r.name=i);let d=e.getAttribute("role");d&&(r.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(r[u.name]=u.value)}return r}function $p(e){let r=e.tagName.toLowerCase();if(e.id){let o=`#${Fp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of fC){let a=e.getAttribute(o);if(a){let s=`${r}[${o}="${Fp(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let t=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${r}.${t.map(s=>Fp(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let a=e.parentElement;if(a){let i=Array.from(a.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(a>=0)return`${r}:nth-of-type(${a+1})`}return r}function hC(e){return e==="static"?sC:aC}function ox(e,r){var o;let t=e.tagName.toLowerCase(),n=((o=e.textContent)!=null?o:"").trim().substring(0,r);return{selector:$p(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:mC(e),attributes:gC(e)}}function xC(e,r,t,n){let o=hC(r.interactivity),a=null;for(let s of t){let i=s.scoreElement(e,r,n);i>0&&(o+=i,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function yC(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function bC(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Zh.has(u)){i=s.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!nx(l)){i=s.nextNode();continue}let p=ox(l,e.maxTextLength),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}=xC(l,p,e.rules,t);o.push({el:l,domIndex:a,enriched:p,score:w,formattingRule:v}),a+=1}i=s.nextNode()}o.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 o){if(d.length>=e.maxElements)break;yC(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,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 CC(e,r){let t=[],n=new Set,o=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&t.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let d=a,l=d.tagName.toLowerCase();if(Zh.has(l)){a=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!nx(d)){a=o.nextNode();continue}let u=ox(d,e.maxTextLength),p=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(f=>f==="role");if(!p&&!m){a=o.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}a=o.nextNode()}let s=[],i=[];for(let d of t)d.interactivity!=="static"?s.push(d):i.push(d);return[...s,...i].slice(0,e.maxElements)}function ax(e={}){var n;let r=uC(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?CC(r,t):bC(r,t):[]}var El=100;function sx(e,r={}){var a;if(e.length===0)return"No page elements found.";let t=(a=r.mode)!=null?a:"structured",n=[];if(t==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&n.push(`Structured summaries:
|
|
150
150
|
${s.map(i=>`- ${i.split(`
|
|
151
151
|
`).join(`
|
|
152
152
|
`)}`).join(`
|
|
153
|
-
`)}`)}let
|
|
153
|
+
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let s of e)t==="structured"&&s.formattedSummary||o[s.interactivity].push(s);if(o.clickable.length>0){let s=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,El)}" (clickable)`);n.push(`Interactive elements:
|
|
154
154
|
${s.join(`
|
|
155
|
-
`)}`)}if(
|
|
155
|
+
`)}`)}if(o.navigable.length>0){let s=o.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(
|
|
157
|
+
`)}`)}if(o.input.length>0){let s=o.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(
|
|
159
|
+
`)}`)}if(o.static.length>0){let s=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,El)}"`);n.push(`Content:
|
|
160
160
|
${s.join(`
|
|
161
161
|
`)}`)}return n.join(`
|
|
162
162
|
|
|
163
|
-
`)}var
|
|
163
|
+
`)}var ix={name:"@runtypelabs/persona",version:"3.21.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=ix.version;function co(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function vC(e){if(e)return{getHeaders:co(e.getHeaders),onFeedback:co(e.onFeedback),onCopy:co(e.onCopy),requestMiddleware:co(e.requestMiddleware),actionHandlers:co(e.actionHandlers),actionParsers:co(e.actionParsers),postprocessMessage:co(e.postprocessMessage),contextProviders:co(e.contextProviders),streamParser:co(e.streamParser)}}var lx=`({ text, message }: any) => {
|
|
164
164
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
165
165
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
166
166
|
let cleanJson = jsonSource
|
|
@@ -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
|
+
}`,dx=`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
|
+
}`,cx=`(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
|
+
}`,px=`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
|
+
}`,AC=`(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
|
+
}`,SC=`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 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
|
|
239
|
-
`)}function
|
|
235
|
+
}`;function TC(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:TC(e.streamParser))!=null?t:"plain"}function Ll(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,o])=>{typeof o=="string"&&t.push(`${r} ${n}: "${o}",`)}),t.push(`${r}},`)),t}function Pl(e,r,t){let n=[],o=e.messageActions&&Object.entries(e.messageActions).some(([s,i])=>s!=="onFeedback"&&s!=="onCopy"&&i!==void 0),a=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(o||a)&&(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,o=e.markdown.disableDefaultStyles!==void 0;(n||o)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([a,s])=>{typeof s=="string"?t.push(`${r} ${a}: "${s}",`):typeof s=="boolean"&&t.push(`${r} ${a}: ${s},`)}),t.push(`${r} },`)),o&&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(a=>a!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(a=>a!=="renderUserMessage"&&a!=="renderAssistantMessage");(n||o)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([a,s])=>{a!=="render"&&(typeof s=="string"?t.push(`${r} ${a}: "${s}",`):typeof s=="boolean"&&t.push(`${r} ${a}: ${s},`))}),t.push(`${r} },`)),o&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([a,s])=>{a==="renderUserMessage"||a==="renderAssistantMessage"||(a==="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} },`)):a==="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} ${a}: "${s}",`):typeof s=="boolean"&&t.push(`${r} ${a}: ${s},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function Up(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 ux(e,r,t){Object.entries(r).forEach(([n,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${t}${n}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${t}${n}: {`),ux(e,o,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(o)},`)}})}function Io(e,r,t,n){t&&(e.push(`${n}${r}: {`),ux(e,t,`${n} `),e.push(`${n}},`))}function fx(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let o=t?{...t,hooks:vC(t.hooks)}:void 0;return r==="esm"?kC(n,o):r==="script-installer"?LC(n,o):r==="script-advanced"?IC(n,o):r==="react-component"?EC(n,o):r==="react-advanced"?MC(n,o):PC(n,o)}function kC(e,r){let t=r==null?void 0:r.hooks,n=Ml(e),o=n!=="plain",a=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),o&&a.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Io(a,"theme",e.theme," "),e.launcher&&Io(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([s,i])=>{a.push(` ${s}: "${i}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"?a.push(` ${s}: ${i},`):typeof i=="number"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([s,i])=>{a.push(` ${s}: ${i},`)}),a.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{a.push(` "${s}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...Ll(e," ")),a.push(...Pl(e," ",t)),a.push(...Il(e," ")),a.push(...Rl(e," ")),a.push(...Up(t," ")),e.debug&&a.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?a.push(` postprocessMessage: ${t.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),a.push(" }"),a.push("});"),a.join(`
|
|
236
|
+
`)}function EC(e,r){let t=r==null?void 0:r.hooks,n=Ml(e),o=n!=="plain",a=["// 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&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),o&&a.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Io(a,"theme",e.theme," "),e.launcher&&Io(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([s,i])=>{a.push(` ${s}: "${i}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"?a.push(` ${s}: ${i},`):typeof i=="number"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([s,i])=>{a.push(` ${s}: ${i},`)}),a.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{a.push(` "${s}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...Ll(e," ")),a.push(...Pl(e," ",t)),a.push(...Il(e," ")),a.push(...Rl(e," ")),a.push(...Up(t," ")),e.debug&&a.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?a.push(` postprocessMessage: ${t.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push(""),a.push(" // Cleanup on unmount"),a.push(" return () => {"),a.push(" if (handle) {"),a.push(" handle.destroy();"),a.push(" }"),a.push(" };"),a.push(" }, []);"),a.push(""),a.push(" return null; // Widget injects itself into the DOM"),a.push("}"),a.push(""),a.push("// Usage in your app:"),a.push("// import { ChatWidget } from './components/ChatWidget';"),a.push("//"),a.push("// export default function App() {"),a.push("// return ("),a.push("// <div>"),a.push("// {/* Your app content */}"),a.push("// <ChatWidget />"),a.push("// </div>"),a.push("// );"),a.push("// }"),a.join(`
|
|
237
|
+
`)}function MC(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(([o,a])=>{n.push(` ${o}: "${a}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,a])=>{typeof a=="string"?n.push(` ${o}: "${a}",`):typeof a=="boolean"&&n.push(` ${o}: ${a},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,a])=>{typeof a=="string"?n.push(` ${o}: "${a}",`):typeof a=="boolean"?n.push(` ${o}: ${a},`):typeof a=="number"&&n.push(` ${o}: ${a},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,a])=>{typeof a=="string"?n.push(` ${o}: "${a}",`):typeof a=="boolean"&&n.push(` ${o}: ${a},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,a])=>{n.push(` ${o}: ${a},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),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(${AC}),`)),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(` ${lx}`),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(` ${lx}`),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(` ${cx}`),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(` ${cx}`),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 mx(e){var o;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),((o=e.suggestionChips)==null?void 0:o.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.debug=e.debug),e.toolCall){let a={};Object.entries(e.toolCall).forEach(([s,i])=>{typeof i=="string"&&(a[s]=i)}),Object.keys(a).length>0&&(n.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([s,i])=>{s!=="onFeedback"&&s!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(a[s]=i)}),Object.keys(a).length>0&&(n.messageActions=a)}if(e.markdown){let a={};e.markdown.options&&(a.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(a.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(a).length>0&&(n.markdown=a)}if(e.layout){let a={};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&&(a.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&&(a.messages=s)}Object.keys(a).length>0&&(n.layout=a)}return n}function LC(e,r){let t=mx(e),n=r!=null&&r.windowKey?{config:t,windowKey:r.windowKey}:t,o=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ia}/dist/install.global.js" data-config='${o}'></script>`}function PC(e,r){let t=r==null?void 0:r.hooks,n=Ml(e),o=n!=="plain",a=["<!-- 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&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),o&&a.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Io(a,"theme",e.theme," "),e.launcher&&Io(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([s,i])=>{a.push(` ${s}: "${i}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"?a.push(` ${s}: ${i},`):typeof i=="number"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,i])=>{typeof i=="string"?a.push(` ${s}: "${i}",`):typeof i=="boolean"&&a.push(` ${s}: ${i},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([s,i])=>{a.push(` ${s}: ${i},`)}),a.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{a.push(` "${s}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...Ll(e," ")),a.push(...Pl(e," ",t)),a.push(...Il(e," ")),a.push(...Rl(e," ")),a.push(...Up(t," ")),e.debug&&a.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?a.push(` postprocessMessage: ${t.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
|
|
239
|
+
`)}function IC(e,r){let t=r==null?void 0:r.hooks,n=mx(e),a=["<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&&(a.push(` widgetConfig.getHeaders = ${t.getHeaders};`),a.push("")),t!=null&&t.contextProviders&&(a.push(` widgetConfig.contextProviders = ${t.contextProviders};`),a.push("")),t!=null&&t.streamParser?a.push(` widgetConfig.streamParser = ${t.streamParser};`):(a.push(" // Flexible JSON stream parser for handling structured actions"),a.push(" widgetConfig.streamParser = function() {"),a.push(` return agentWidget.createFlexibleJsonStreamParser(${SC});`),a.push(" };")),a.push(""),t!=null&&t.actionParsers?(a.push(" // Action parsers (custom merged with defaults)"),a.push(` var customParsers = ${t.actionParsers};`),a.push(" widgetConfig.actionParsers = customParsers.concat(["),a.push(" agentWidget.defaultJsonActionParser,"),a.push(` ${dx}`),a.push(" ]);")):(a.push(" // Action parsers to detect JSON actions in responses"),a.push(" widgetConfig.actionParsers = ["),a.push(" agentWidget.defaultJsonActionParser,"),a.push(` ${dx}`),a.push(" ];")),a.push(""),t!=null&&t.actionHandlers?(a.push(" // Action handlers (custom merged with defaults)"),a.push(` var customHandlers = ${t.actionHandlers};`),a.push(" widgetConfig.actionHandlers = customHandlers.concat(["),a.push(" agentWidget.defaultActionHandlers.message,"),a.push(" agentWidget.defaultActionHandlers.messageAndClick,"),a.push(` ${px}`),a.push(" ]);")):(a.push(" // Action handlers for navigation and other actions"),a.push(" widgetConfig.actionHandlers = ["),a.push(" agentWidget.defaultActionHandlers.message,"),a.push(" agentWidget.defaultActionHandlers.messageAndClick,"),a.push(` ${px}`),a.push(" ];")),a.push(""),t!=null&&t.requestMiddleware?(a.push(" // Request middleware (custom merged with DOM context)"),a.push(" widgetConfig.requestMiddleware = function(ctx) {"),a.push(` var customResult = (${t.requestMiddleware})(ctx);`),a.push(" var merged = customResult || ctx.payload;"),a.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),a.push(" };")):(a.push(" // Send DOM context with each request"),a.push(" widgetConfig.requestMiddleware = function(ctx) {"),a.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),a.push(" };")),a.push(""),t!=null&&t.postprocessMessage?a.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(a.push(" // Markdown postprocessor"),a.push(" widgetConfig.postprocessMessage = function(ctx) {"),a.push(" return agentWidget.markdownPostprocessor(ctx.text);"),a.push(" };")),a.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(a.push(" // Message action callbacks"),a.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&a.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&a.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),a.push("")),a.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>"),a.join(`
|
|
242
|
+
`)}var gx={desktop:{w:1280,h:800},mobile:{w:390,h:844}},hx=.1,xx=.15,yx=1.5,qp=24,bx=40,RC=`
|
|
243
243
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
244
244
|
.persona-dc-root {
|
|
245
245
|
display: flex;
|
|
@@ -390,7 +390,7 @@ ${s.join(`
|
|
|
390
390
|
.persona-dc-stage {
|
|
391
391
|
height: 550px;
|
|
392
392
|
min-height: 400px;
|
|
393
|
-
padding: ${
|
|
393
|
+
padding: ${qp}px;
|
|
394
394
|
overflow: auto;
|
|
395
395
|
background: #f0f1f3;
|
|
396
396
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -480,7 +480,7 @@ ${s.join(`
|
|
|
480
480
|
min-height: 300px;
|
|
481
481
|
}
|
|
482
482
|
}
|
|
483
|
-
`;function
|
|
483
|
+
`;function HC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=RC,document.head.appendChild(e)}function BC(e,r){let t=e.clientWidth-qp*2-bx,n=e.clientHeight-qp*2-bx;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function WC(e,r,t,n,o){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=o==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Cx(e,r){let{items:t,initialIndex:n=0,initialDevice:o="desktop",initialColorScheme:a="light",showZoomControls:s=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");HC();let u=Math.max(0,Math.min(n,t.length-1)),p=o,m=a,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:()=>Oe(-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 j(){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 ke=x("span");if(ke.textContent=G.title,we.appendChild(ke),G.description){let ae=x("span","persona-dc-dropdown-desc");ae.textContent=G.description,we.appendChild(ae)}we.addEventListener("click",()=>{ue(),Pe(Y)}),R.appendChild(we)}}function oe(){B=!B,R.style.display=B?"":"none",S.setAttribute("aria-expanded",B?"true":"false"),B&&j()}function ue(){B&&(B=!1,R.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",Y=>{Y.stopPropagation(),oe()});let De=()=>ue();document.addEventListener("click",De),h.append(S,R);let Xe=Qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Oe(1)}),xe=x("span","persona-dc-counter");A.append(b,h,Xe,xe);let ge=null;i&&(ge=Ps({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:Y=>{p=Y,J.dataset.device=p,f=null,K()}}),E.appendChild(ge.element));let Le=null;if(s){let Y=x("div","persona-dc-zoom-controls"),G=Qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ae=f!=null?f:w;f=Math.max(xx,ae-hx),K()}});Le=x("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{f=1,K()});let we=Qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ae=f!=null?f:w;f=Math.min(yx,ae+hx),K()}}),ke=Qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,K()}});Y.append(G,Le,we,ke),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 Ge=x("div","persona-dc-separator");E.appendChild(Ge);let Q=Qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});E.appendChild(Q),T.append(A,E);let Se=x("div","persona-dc-stage"),J=x("div","persona-dc-iframe-wrapper");J.dataset.device=p,J.dataset.colorScheme=m;let ce=x("iframe","persona-dc-iframe");ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ce.setAttribute("loading","lazy"),ce.title=t[u].title,J.appendChild(ce),Se.appendChild(J),k.append(T,Se),e.appendChild(k);function pe(){var Y;try{let G=(Y=ce.contentDocument)==null?void 0:Y.body;if(!G)return;m==="dark"?G.classList.add("theme-dark"):G.classList.remove("theme-dark")}catch{}}ce.addEventListener("load",()=>pe());function ie(){let Y=t[u];L.textContent=Y.title,xe.textContent=`${u+1} / ${t.length}`,ce.title=Y.title}function Oe(Y){let G=((u+Y)%t.length+t.length)%t.length;Pe(G)}function Pe(Y){Y<0||Y>=t.length||(u=Y,ce.src=t[u].url,ie(),l==null||l(u,t[u]))}function K(){var we;if(v)return;let Y=(we=gx[p])!=null?we:gx.desktop;w=BC(Se,Y);let G=Math.max(xx,Math.min(yx,f!=null?f:w));WC(J,ce,Y,G,p),Le&&(Le.textContent=`${Math.round(G*100)}%`)}let _e=new ResizeObserver(()=>K());_e.observe(Se),ie(),ce.src=t[u].url,requestAnimationFrame(()=>K());function $e(){v||(v=!0,_e.disconnect(),document.removeEventListener("click",De),k.remove())}return{element:k,goTo:Pe,next:()=>Oe(1),prev:()=>Oe(-1),getIndex:()=>u,setDevice(Y){p=Y,J.dataset.device=Y,ge==null||ge.setSelected(Y),f=null,K()},setColorScheme(Y){m=Y,J.dataset.colorScheme=Y},setZoom(Y){f=Y,K()},destroy:$e}}function wx(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function vx(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Ax(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:zn(e.colors.primary,.95),100:zn(e.colors.primary,.9),200:zn(e.colors.primary,.8),300:zn(e.colors.primary,.7),400:zn(e.colors.primary,.6),500:e.colors.primary,600:zn(e.colors.primary,.8),700:zn(e.colors.primary,.7),800:zn(e.colors.primary,.6),900:zn(e.colors.primary,.5),950:zn(e.colors.primary,.45)}}),{...r,palette:t}}}}function Sx(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Tx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function zn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),a=Math.round(t+(255-t)*(1-r)),s=Math.round(n+(255-n)*(1-r)),i=Math.round(o+(255-o)*(1-r));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function kx(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var DC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Ex={components:{panel:{borderRadius:"0",shadow:"none"}}},zp={id:"shop",label:"Shopping Assistant",config:{theme:DC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:mn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Vp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ex}},jp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ex}},Gp={shop:zp,minimal:Vp,fullscreen:jp};function Mx(e){return Gp[e]}var OC=`
|
|
484
484
|
@keyframes persona-stream-wipe {
|
|
485
485
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
486
486
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -516,7 +516,7 @@ ${s.join(`
|
|
|
516
516
|
mask-image: none !important;
|
|
517
517
|
}
|
|
518
518
|
}
|
|
519
|
-
`.trim(),
|
|
519
|
+
`.trim(),FC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:OC};ra(FC);var NC=`
|
|
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#$%&@",_C=10,$C=120,Xp=120,UC=.4,qC=50,zC=e=>{var n;if(!e)return Xp;let t=((n=e.style.getPropertyValue("--persona-stream-step"))==null?void 0:n.trim()).match(/([\d.]+)\s*ms/);return t?parseFloat(t[1]):Xp},Dx=e=>{let r=e.closest(".persona-stream-glyph-cycle"),t=zC(r);return $C*t/Xp},Jp=e=>{let r=Fs[Math.floor(Math.random()*Fs.length)];return e&&r===e&&(r=Fs[(Fs.indexOf(r)+1)%Fs.length]),r},VC=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 o of Array.from(t)){if(o===e){n=!0;continue}n&&Math.random()<UC&&(o.textContent=Jp())}},Lx=new WeakMap,Px=25,Ix=.5,jC=6,Rx=.25,Hx=new WeakMap,Bx=new WeakMap,GC=(e,r)=>{var o;if(!e)return Px*Ix;let t=Hx.get(e);Hx.set(e,r);let n=(o=Bx.get(e))!=null?o:Px;if(t!==void 0){let a=r-t;a>1&&(n=n*(1-Rx)+a*Rx,Bx.set(e,n))}return Math.max(jC,n*Ix)},Da=new Map,XC=e=>{var t;let r=e.closest("[data-message-id]");return(t=r==null?void 0:r.dataset.messageId)!=null?t:null},JC=e=>{var r;e&&Da.set(e,((r=Da.get(e))!=null?r:0)+1)},KC=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)},Ox=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=Jp();let t=XC(e);t&&(e.dataset.glyphCycleMessageId=t),JC(t);let n=e.closest(".persona-stream-glyph-cycle"),o=Date.now(),a=GC(n,o),s=Dx(e),i=_C*s,d=o+i;if(n){let u=Lx.get(n);u!==void 0&&(d=Math.max(d,u)),Lx.set(n,d+a)}YC(e,r,d)},YC=(e,r,t)=>{var s;if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let n=Dx(e),o=(s=e.textContent)!=null?s:void 0,a=()=>{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,KC((d=e.dataset.glyphCycleMessageId)!=null?d:null),delete e.dataset.glyphCycleMessageId;return}let i=Jp(o);e.textContent=i,o=i,VC(e),setTimeout(a,n)};setTimeout(a,n)},Wx=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))Ox(n)},QC=e=>e.nodeType===1,ZC={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:NC,bufferContent(e){if(e.length<qC)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){Wx(e);let r=new MutationObserver(t=>{for(let n of t)for(let o of Array.from(n.addedNodes))QC(o)&&(o.classList.contains("persona-stream-char")&&o.closest(".persona-stream-glyph-cycle")?Ox(o):Wx(o))});return r.observe(e,{childList:!0,subtree:!0}),()=>r.disconnect()}};ra(ZC);return Vx(ew);})();
|
|
538
538
|
/*! Bundled license information:
|
|
539
539
|
|
|
540
540
|
dompurify/dist/purify.es.mjs:
|