@runtypelabs/persona 4.6.1 → 4.8.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.cjs +2 -2
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/glyph-cycle.js +2 -2
- package/dist/animations/{types-CSmiKRVa.d.cts → types-BsZtXPKK.d.cts} +43 -3
- package/dist/animations/{types-CSmiKRVa.d.ts → types-BsZtXPKK.d.ts} +43 -3
- package/dist/animations/wipe.cjs +2 -2
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-5EIIHQLQ.js +1 -0
- package/dist/codegen.cjs +12 -12
- package/dist/codegen.js +14 -14
- package/dist/index.cjs +91 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +918 -174
- package/dist/index.d.ts +918 -174
- package/dist/index.global.js +81 -57
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +89 -66
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +3 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +24 -24
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.js +1 -1
- package/dist/runtype-tts-entry-UJAEF7NZ.js +1 -0
- package/dist/runtype-tts.js +1 -1
- package/dist/session-reconnect-JKIJBHS5.js +1 -0
- package/dist/smart-dom-reader.cjs +17 -17
- package/dist/smart-dom-reader.d.cts +753 -15
- package/dist/smart-dom-reader.d.ts +753 -15
- package/dist/smart-dom-reader.js +17 -17
- package/dist/testing.cjs +3 -3
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +81 -58
- package/dist/theme-editor-preview.d.cts +761 -15
- package/dist/theme-editor-preview.d.ts +761 -15
- package/dist/theme-editor-preview.js +81 -58
- package/dist/theme-editor.cjs +6 -6
- package/dist/theme-editor.d.cts +753 -15
- package/dist/theme-editor.d.ts +753 -15
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +74 -0
- package/dist/theme-reference.d.ts +74 -0
- package/dist/theme-reference.js +1 -1
- package/dist/voice-worklet-player.cjs +2 -2
- package/dist/voice-worklet-player.js +2 -2
- package/dist/webmcp-polyfill.js +2 -2
- package/dist/widget.css +1 -1
- package/package.json +2 -3
- package/src/artifacts-session.test.ts +178 -0
- package/src/client.test.ts +500 -1
- package/src/client.ts +285 -93
- package/src/components/artifact-card.test.ts +333 -0
- package/src/components/artifact-card.ts +75 -28
- package/src/components/artifact-inline.test.ts +1328 -0
- package/src/components/artifact-inline.ts +920 -0
- package/src/components/artifact-pane.test.ts +1042 -0
- package/src/components/artifact-pane.ts +440 -131
- package/src/components/artifact-preview.test.ts +1155 -0
- package/src/components/artifact-preview.ts +994 -0
- package/src/components/pill-composer-builder.test.ts +6 -2
- package/src/components/pill-composer-builder.ts +6 -6
- package/src/components/reasoning-bubble.ts +1 -13
- package/src/components/registry.ts +38 -3
- package/src/components/tool-bubble.ts +1 -13
- package/src/defaults.ts +1 -0
- package/src/generated/runtype-openapi-contract.ts +55 -3
- package/src/index-core.ts +20 -1
- package/src/index.ts +8 -0
- package/src/markdown-parsers-loader.test.ts +158 -0
- package/src/markdown-parsers-loader.ts +74 -9
- package/src/runtime/host-layout.test.ts +163 -0
- package/src/runtime/host-layout.ts +110 -7
- package/src/runtime/init.ts +18 -61
- package/src/runtime/persist-state.test.ts +118 -0
- package/src/session.ts +76 -22
- package/src/styles/widget.css +773 -26
- package/src/theme-editor/preview.ts +2 -0
- package/src/theme-editor/sections.test.ts +26 -1
- package/src/theme-editor/sections.ts +10 -2
- package/src/theme-reference.ts +2 -2
- package/src/tool-call-display-defaults.test.ts +1 -0
- package/src/types/theme.ts +77 -0
- package/src/types.ts +516 -17
- package/src/ui.artifact-pane-gating.test.ts +636 -0
- package/src/ui.component-directive.test.ts +104 -0
- package/src/ui.composer-bar.test.ts +60 -2
- package/src/ui.detached-panel.test.ts +1049 -0
- package/src/ui.scroll-additive.test.ts +1 -1
- package/src/ui.streaming-coalescing.test.ts +312 -0
- package/src/ui.tool-display.test.ts +51 -0
- package/src/ui.ts +933 -214
- package/src/utils/artifact-custom-actions.ts +128 -0
- package/src/utils/artifact-display.test.ts +42 -0
- package/src/utils/artifact-display.ts +84 -0
- package/src/utils/artifact-file.test.ts +116 -0
- package/src/utils/artifact-file.ts +117 -0
- package/src/utils/artifact-gate.test.ts +112 -5
- package/src/utils/artifact-gate.ts +39 -14
- package/src/utils/artifact-loading-status.ts +55 -0
- package/src/utils/artifact-status-label.ts +190 -0
- package/src/utils/buttons.ts +7 -1
- package/src/utils/code-highlight.test.ts +186 -0
- package/src/utils/code-highlight.ts +400 -0
- package/src/utils/icons.ts +2 -0
- package/src/utils/roving-tablist.test.ts +152 -0
- package/src/utils/roving-tablist.ts +111 -0
- package/src/utils/spinner.ts +45 -0
- package/src/utils/theme.test.ts +48 -0
- package/src/utils/theme.ts +7 -0
- package/src/utils/tokens.ts +91 -0
- package/src/utils/tool-loading-animation.test.ts +32 -0
- package/src/utils/tool-loading-animation.ts +24 -0
- package/dist/chunk-DFBSCFYN.js +0 -1
- package/dist/runtype-tts-entry-HFUV2UF7.js +0 -1
- package/dist/session-reconnect-U77QFUR7.js +0 -1
package/dist/index.global.js
CHANGED
|
@@ -1,23 +1,29 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[
|
|
3
|
-
`),
|
|
4
|
-
`):e};var
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var oy=Object.create;var Ls=Object.defineProperty;var ry=Object.getOwnPropertyDescriptor;var ny=Object.getOwnPropertyNames;var ay=Object.getPrototypeOf,sy=Object.prototype.hasOwnProperty;var Dl=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var iy=(e,t)=>()=>(e&&(t=e(e=0)),t);var df=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),cf=(e,t)=>{for(var o in t)Ls(e,o,{get:t[o],enumerable:!0})},pf=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ny(t))!sy.call(e,n)&&n!==o&&Ls(e,n,{get:()=>t[n],enumerable:!(r=ry(t,n))||r.enumerable});return e};var wn=(e,t,o)=>(o=e!=null?oy(ay(e)):{},pf(t||!e||!e.__esModule?Ls(o,"default",{value:e,enumerable:!0}):o,e)),ly=e=>pf(Ls({},"__esModule",{value:!0}),e);var ql=df(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.Allow=ge.ALL=ge.COLLECTION=ge.ATOM=ge.SPECIAL=ge.INF=ge._INFINITY=ge.INFINITY=ge.NAN=ge.BOOL=ge.NULL=ge.OBJ=ge.ARR=ge.NUM=ge.STR=void 0;ge.STR=1;ge.NUM=2;ge.ARR=4;ge.OBJ=8;ge.NULL=16;ge.BOOL=32;ge.NAN=64;ge.INFINITY=128;ge._INFINITY=256;ge.INF=ge.INFINITY|ge._INFINITY;ge.SPECIAL=ge.NULL|ge.BOOL|ge.INF|ge.NAN;ge.ATOM=ge.STR|ge.NUM|ge.SPECIAL;ge.COLLECTION=ge.ARR|ge.OBJ;ge.ALL=ge.ATOM|ge.COLLECTION;ge.Allow={STR:ge.STR,NUM:ge.NUM,ARR:ge.ARR,OBJ:ge.OBJ,NULL:ge.NULL,BOOL:ge.BOOL,NAN:ge.NAN,INFINITY:ge.INFINITY,_INFINITY:ge._INFINITY,INF:ge.INF,SPECIAL:ge.SPECIAL,ATOM:ge.ATOM,COLLECTION:ge.COLLECTION,ALL:ge.ALL};ge.default=ge.Allow});var Ds=df(Ut=>{"use strict";var My=Ut&&Ut.__createBinding||(Object.create?(function(e,t,o,r){r===void 0&&(r=o);var n=Object.getOwnPropertyDescriptor(t,o);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,n)}):(function(e,t,o,r){r===void 0&&(r=o),e[r]=t[o]})),Ey=Ut&&Ut.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&My(t,e,o)};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Allow=Ut.MalformedJSON=Ut.PartialJSON=Ut.parseJSON=Ut.parse=void 0;var Xt=ql();Object.defineProperty(Ut,"Allow",{enumerable:!0,get:function(){return Xt.Allow}});Ey(ql(),Ut);var Hs=class extends Error{};Ut.PartialJSON=Hs;var Ws=class extends Error{};Ut.MalformedJSON=Ws;function Pf(e,t=Xt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return ky(e.trim(),t)}Ut.parseJSON=Pf;var ky=(e,t)=>{let o=e.length,r=0,n=g=>{throw new Hs(`${g} at position ${r}`)},a=g=>{throw new Ws(`${g} at position ${r}`)},s=()=>(u(),r>=o&&n("Unexpected end of input"),e[r]==='"'?l():e[r]==="{"?p():e[r]==="["?d():e.substring(r,r+4)==="null"||Xt.Allow.NULL&t&&o-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)==="true"||Xt.Allow.BOOL&t&&o-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)==="false"||Xt.Allow.BOOL&t&&o-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)==="Infinity"||Xt.Allow.INFINITY&t&&o-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)==="-Infinity"||Xt.Allow._INFINITY&t&&1<o-r&&o-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)==="NaN"||Xt.Allow.NAN&t&&o-r<3&&"NaN".startsWith(e.substring(r))?(r+=3,NaN):c()),l=()=>{let g=r,f=!1;for(r++;r<o&&(e[r]!=='"'||f&&e[r-1]==="\\");)f=e[r]==="\\"?!f:!1,r++;if(e.charAt(r)=='"')try{return JSON.parse(e.substring(g,++r-Number(f)))}catch(h){a(String(h))}else if(Xt.Allow.STR&t)try{return JSON.parse(e.substring(g,r-Number(f))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},p=()=>{r++,u();let g={};try{for(;e[r]!=="}";){if(u(),r>=o&&Xt.Allow.OBJ&t)return g;let f=l();u(),r++;try{let h=s();g[f]=h}catch(h){if(Xt.Allow.OBJ&t)return g;throw h}u(),e[r]===","&&r++}}catch{if(Xt.Allow.OBJ&t)return g;n("Expected '}' at end of object")}return r++,g},d=()=>{r++;let g=[];try{for(;e[r]!=="]";)g.push(s()),u(),e[r]===","&&r++}catch{if(Xt.Allow.ARR&t)return g;n("Expected ']' at end of array")}return r++,g},c=()=>{if(r===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Xt.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(f))}}let g=r;for(e[r]==="-"&&r++;e[r]&&",]}".indexOf(e[r])===-1;)r++;r==o&&!(Xt.Allow.NUM&t)&&n("Unterminated number literal");try{return JSON.parse(e.substring(g,r))}catch{e.substring(g,r)==="-"&&n("Not sure what '-' is");try{return JSON.parse(e.substring(g,e.lastIndexOf("e")))}catch(h){a(String(h))}}},u=()=>{for(;r<o&&`
|
|
2
|
+
\r `.includes(e[r]);)r++};return s()},Ly=Pf;Ut.parse=Ly});var um={};cf(um,{createReconnectController:()=>gb});function gb(e){let t=0,o=null,r=null,n=!1,a=()=>{if(r&&(clearTimeout(r),r=null),o){let h=o;o=null,h()}},s=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||a()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||s()},p=()=>{s()},d=()=>{n||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),n=!0)},c=()=>{n&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),n=!1)},u=h=>new Promise(C=>{o=C,r=setTimeout(()=>{r=null,o=null,C()},h)}),g=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let M=e.buildErrorContent("Connection lost and the response could not be resumed.");M?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??mb,C=e.config.reconnect?.maxAttempts??h.length,M=e.config.reconnectStream;if(!M){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),A=L.lastEventId,T=new AbortController;e.setAbortController(T),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let S=null;try{let E=await M({executionId:L.executionId,after:L.lastEventId,signal:T.signal});E&&E.ok&&E.body&&(S=E.body)}catch{S=null}if(T.signal.aborted)return;if(S){let E=e.getMessages().find(H=>H.id===L.assistantMessageId)?.content,B=typeof E=="string"?E:"";try{await e.resumeConnect(S,L.assistantMessageId,B)}catch{}if(T.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==A&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),T.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,d(),f()},teardown(){r&&(clearTimeout(r),r=null),o=null,t=0,c()},wake:a}}var mb,fm=iy(()=>{"use strict";mb=[1e3,2e3,4e3,8e3,8e3]});var kC={};cf(kC,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Yl,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Ql,ASK_USER_QUESTION_TOOL_NAME:()=>Sa,AgentWidgetClient:()=>Jr,AgentWidgetSession:()=>In,AttachmentManager:()=>Zr,BrowserSpeechEngine:()=>hr,DEFAULT_COMPONENTS:()=>op,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>fi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>lo,DEFAULT_PALETTE:()=>ep,DEFAULT_SEMANTIC:()=>tp,DEFAULT_WIDGET_CONFIG:()=>pt,PRESETS:()=>Jp,PRESET_FULLSCREEN:()=>Xp,PRESET_MINIMAL:()=>Kp,PRESET_SHOP:()=>Gp,ReadAloudController:()=>Yr,SUGGEST_REPLIES_CLIENT_TOOL:()=>_s,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Kl,SUGGEST_REPLIES_TOOL_NAME:()=>To,THEME_ZONES:()=>xm,VERSION:()=>Xr,WEBMCP_TOOL_PREFIX:()=>So,WebMcpBridge:()=>Tn,accessibilityPlugin:()=>th,animationsPlugin:()=>oh,applyThemeVariables:()=>en,attachHeaderToContainer:()=>rn,brandPlugin:()=>rh,buildComposer:()=>Un,buildDefaultHeader:()=>hp,buildHeader:()=>Ko,buildHeaderWithLayout:()=>_n,buildMinimalHeader:()=>yp,builtInClientToolsForDispatch:()=>Ln,collectEnrichedPageContext:()=>Zg,componentRegistry:()=>Mo,createActionManager:()=>Za,createAgentExperience:()=>tl,createAskUserQuestionBubble:()=>zf,createBestAvailableVoiceProvider:()=>ei,createBubbleWithLayout:()=>sg,createCSATFeedback:()=>Yi,createComboButton:()=>Ai,createComponentMiddleware:()=>Ig,createComponentStreamParser:()=>Xi,createDefaultSanitizer:()=>Nl,createDirectivePostprocessor:()=>bf,createDropdownMenu:()=>Cr,createFlexibleJsonStreamParser:()=>Kf,createIconButton:()=>kt,createImagePart:()=>om,createJsonStreamParser:()=>Ks,createLabelButton:()=>Go,createLocalStorageAdapter:()=>Ki,createMarkdownProcessor:()=>Ca,createMarkdownProcessorFromConfig:()=>$r,createMessageActions:()=>Sp,createNPSFeedback:()=>Zi,createPlainTextParser:()=>js,createPlugin:()=>sh,createRegexJsonParser:()=>Gs,createStandardBubble:()=>qn,createTextPart:()=>Pa,createTheme:()=>Bn,createThemeObserver:()=>Hn,createToggleGroup:()=>Fn,createTypingIndicator:()=>nn,createVoiceProvider:()=>gr,createWidgetHostLayout:()=>ts,createXmlParser:()=>Xs,defaultActionHandlers:()=>dn,defaultJsonActionParser:()=>Ya,defaultParseRules:()=>$p,detectColorScheme:()=>Wa,directivePostprocessor:()=>xf,ensureAskUserQuestionSheet:()=>kn,escapeHtml:()=>Ro,extractComponentDirectiveFromMessage:()=>Qi,fileToImagePart:()=>rm,formatEnrichedContext:()=>eh,generateAssistantMessageId:()=>mr,generateMessageId:()=>Qf,generateStableSelector:()=>jp,generateUserMessageId:()=>Pn,getActiveTheme:()=>yr,getColorScheme:()=>xi,getDisplayText:()=>Zf,getHeaderLayout:()=>bp,getImageParts:()=>tm,getPreset:()=>lh,hasComponentDirective:()=>es,hasImages:()=>em,headerLayouts:()=>Oi,highContrastPlugin:()=>ah,initAgentWidget:()=>qg,isAskUserQuestionMessage:()=>Vo,isComponentDirectiveType:()=>Rg,isDockedMountMode:()=>It,isSuggestRepliesMessage:()=>Ma,isVoiceSupported:()=>Ia,isWebMcpToolName:()=>lr,latestAgentSuggestions:()=>Us,listRegisteredStreamAnimations:()=>fp,loadMarkdownParsers:()=>va,markdownPostprocessor:()=>Ol,mergeWithDefaults:()=>mi,normalizeContent:()=>Yf,onMarkdownParsersReady:()=>An,parseAskUserQuestionPayload:()=>zo,parseSuggestRepliesPayload:()=>Jl,pickBestVoice:()=>Rn,pluginRegistry:()=>Qa,reducedMotionPlugin:()=>nh,registerStreamAnimationPlugin:()=>on,removeAskUserQuestionSheet:()=>pr,renderComponentDirective:()=>Ji,renderLoadingIndicatorWithFallback:()=>Ap,renderLucideIcon:()=>ne,resolveDockConfig:()=>oo,resolveSanitizer:()=>Sn,resolveTokens:()=>yi,stripWebMcpPrefix:()=>Is,themeToCssVariables:()=>bi,unregisterStreamAnimationPlugin:()=>up,validateImageFile:()=>nm,validateTheme:()=>rp});var Fl=null,xa=null,zr=null,Ps=new Set,uf=e=>{xa=e;let t=[...Ps];Ps.clear();for(let o of t)try{o()}catch{}return e},mf=e=>{Fl=e},An=e=>xa?()=>{}:(Ps.add(e),va().catch(()=>{}),()=>{Ps.delete(e)});var ff=e=>{throw zr=null,e},va=()=>xa?Promise.resolve(xa):zr||(Fl?(zr=Fl().then(uf,ff),zr):(zr=import("./markdown-parsers-entry").then(uf,ff),zr)),qo=()=>xa;var dy=e=>{if(e)return e},Ca=e=>{let t=null;return o=>{let r=qo();if(!r)return Ro(o);if(!t){let{Marked:n}=r,a=e?.markedOptions;t=new n({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let s=dy(e?.renderer);s&&t.use({renderer:s})}return t.parse(o)}},$r=e=>e?Ca({markedOptions:e.options,renderer:e.renderer}):Ca(),cy=Ca(),Ol=e=>cy(e),Ro=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),hf=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),gf=e=>`%%FORM_PLACEHOLDER_${e}%%`,yf=(e,t)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,n)=>{try{let a=JSON.parse(n.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=gf(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return r}return r}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,n)=>{let a=gf(t.length);return t.push({token:a,type:n}),a}),o},bf=e=>{let t=$r(e);return o=>{let r=[],n=yf(o,r),a=t(n);return r.forEach(({token:s,type:l})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${hf(l)}"></div>`;a=a.replace(p,c)}),a}},xf=e=>{let t=[],o=yf(e,t),r=Ol(o);return t.forEach(({token:n,type:a})=>{let s=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${hf(a)}"></div>`;r=r.replace(s,p)}),r};var py={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"]},uy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Nl=()=>{let e=null;return t=>{let o=qo();if(!o)return Ro(t);if(!e){let{DOMPurify:r}=o;e=r(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(n,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!uy.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,py)}},Sn=e=>e===!1?null:typeof e=="function"?e:Nl();var vf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Cf=e=>e.includes("|"),wf=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(o=>o.trim())},fy=e=>`| ${e.join(" | ")} |`,my=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,gy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Af=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
3
|
+
`),o=!1;for(let r=0;r<t.length-1;r++){let n=t[r],a=t[r+1];if(!Cf(n)||vf.test(n)||!vf.test(a))continue;let s=wf(n).length;if(s<1)continue;let l=my(s);t[r+1]!==l&&(t[r+1]=l,o=!0);let p=r+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Cf(d))break;let c=fy(gy(wf(d),s));t[p]!==c&&(t[p]=c,o=!0)}r=p-1}return o?t.join(`
|
|
4
|
+
`):e};var So="webmcp:",_l=new Map,Sf=e=>{_l.clear();for(let t of e){let o=t.title?.trim();o&&_l.set(t.name,o)}},wa=e=>_l.get(Is(e)),Rs={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Ul=null,Mf=e=>{Ul=e};function Ef(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${hy(t.join(""))}`}function Tf(e,t){let o=3735928559^t,r=1103547991^t;for(let n=0;n<e.length;n++){let a=e.charCodeAt(n);o=Math.imul(o^a,2654435761),r=Math.imul(r^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&r)+(o>>>0)}function hy(e){let t=Tf(e,0).toString(36),o=Tf(e,2654435761).toString(36);return`${t}.${o}`}var Tn=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let o;try{o=await t.getTools()}catch(n){return Rs.warn("getTools() threw: shipping an empty WebMCP snapshot.",n),[]}Sf(o);let r=typeof location<"u"?location.origin:"";return o.filter(n=>this.passesClientAllowlist(n.name)).map(n=>{let a={name:n.name,description:n.description,origin:"webmcp",...r?{pageOrigin:r}:{}},s=by(n.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,o,r){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let n=this.getModelContext();if(!n){let h=typeof document<"u"&&!!document.modelContext;return Ao(h?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=Is(t),s;try{s=await n.getTools()}catch(h){let C=h instanceof Error?h.message:String(h);return Ao(`Failed to read WebMCP registry: ${C}`)}Sf(s);let l=s.find(h=>h.name===a);if(!l)return Ao(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Ao(`WebMCP tool not allowed by client allowlist: ${a}`);if(r?.aborted)return Ao("Aborted by cancel()");let p=wa(a),d={toolName:a,args:o,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Ao("User declined the tool call.");if(r?.aborted)return Ao("Aborted by cancel()");let c=new AbortController,u=!1,g=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();r&&(r.aborted?c.abort():r.addEventListener("abort",f,{once:!0}));try{let h=await n.executeTool(l,wy(o),{signal:c.signal});return xy(h)}catch(h){if(u)return Ao(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(r?.aborted)return Ao("Aborted by cancel()");let C=h instanceof Error?h.message:String(h);return Ao(C)}finally{clearTimeout(g),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Ul?await Ul():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Rs.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let o=t;return typeof o.getTools!="function"||typeof o.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Rs.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let o=this.confirmHandler??vy;try{return await o(t)}catch(r){return Rs.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let o=this.config.allowlist;return!o||o.length===0?!0:o.some(r=>yy(t,r))}},Is=e=>e.startsWith(So)?e.slice(So.length):e,lr=e=>e.startsWith(So),yy=(e,t)=>{if(t==="*")return!0;let o=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+o.replace(/\*/g,".*")+"$").test(e)},by=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},xy=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Ay(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),vy=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Cy(e.args),o=`Allow the AI to call ${e.toolName}`+(t?`
|
|
5
5
|
|
|
6
6
|
Arguments:
|
|
7
7
|
${t}`:"")+(e.description?`
|
|
8
8
|
|
|
9
|
-
${e.description}`:"");return window.confirm(r)},sb=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},ib=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},lb=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var db="agent_",cb="flow_";function zg(e){return e.startsWith(db)?{kind:"agentId",agentId:e}:e.startsWith(cb)?{kind:"flowId",flowId:e}:null}function $g(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let s=r.slice(0,o),i=r.slice(o+1);if(s==="runtype"){let d=zg(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let c=t==null?void 0:t[s];if(!c)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(i).payload}}let n=zg(r);if(n)return n;let a=t==null?void 0:t.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var Mn=La(oi(),1);var S=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},No=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var Tt=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},gs=(...e)=>e.filter(Boolean).join(" ");var xs="ask_user_question",hs=8,Ha="data-persona-ask-sheet-for",gb="Other",hb="Other\u2026",Kg="Type your own answer here",Xg="Send",xb="Next",yb="Back",bb="Submit all",vb="Skip",wb=3,Fl="data-ask-current-index",Nl="data-ask-question-count",Qg="data-ask-answers",Ol="data-ask-grouped",Jg="data-ask-layout",Cb=e=>e.layout==="pills"?"pills":"rows",Sb=e=>e.getAttribute(Jg)==="pills"?"pills":"rows",Gg=!1,Yg=e=>e.replace(/["\\]/g,"\\$&"),Jo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xs,ni=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},Yo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,Mn.parse)(n,Mn.STR|Mn.OBJ|Mn.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ys=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>hs&&!Gg&&(Gg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${hs}.`)),t.slice(0,hs)},Ab=e=>{var t;return(t=ys(e)[0])!=null?t:null},Mb=(e,t)=>{var r;return(r=ys(e)[t])!=null?r:null},Zg=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},eh=(e,t,r)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=S("span","persona-ask-row-check");o.appendChild(n)}else{let n=S("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Tb=(e,t,r,o)=>{let a=S("button",r==="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",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=S("span","persona-ask-row-content"),i=S("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=S("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let c=eh(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Eb=e=>{let r=S("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 r.setAttribute("aria-hidden","true"),r},kb=(e,t,r,o)=>{var p,u,g;let a=S("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(c.length===0&&!r){for(let f=0;f<wb;f++)a.appendChild(Eb(o));return a}if(c.forEach((f,h)=>{a.appendChild(Tb(f,h,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let f=o==="rows"?gb:hb;if(o==="rows"){let h=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");h.setAttribute("data-ask-user-action","focus-free-text"),h.setAttribute("data-option-index",String(c.length)),h.setAttribute("data-ask-other-row","true");let b=S("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=(p=t.freeTextPlaceholder)!=null?p:Kg,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),b.appendChild(k),h.appendChild(b);let E=eh(o,s,c.length);E&&h.appendChild(E),a.appendChild(h)}else{let h=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");h.type="button",h.setAttribute("data-ask-user-action","open-free-text"),h.textContent=(g=t.freeTextLabel)!=null?g:f,a.appendChild(h)}}return a},th=(e,t)=>{var a,s;let o=S("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:Kg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=S("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Xg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Lb=e=>{var o;let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=S("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Xg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Pb=(e,t,r)=>{var d,p,u,g;let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=S("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:yb,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=S("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:vb,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=S("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(u=r.submitAllLabel)!=null?u:bb:(g=r.nextLabel)!=null?g:xb,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},na=e=>{let t=e.getAttribute(Qg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},rh=(e,t)=>{e.setAttribute(Qg,JSON.stringify(t))},ao=e=>{var r;let t=Number((r=e.getAttribute(Fl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Rb=(e,t)=>{e.setAttribute(Fl,String(Math.max(0,Math.floor(t))))},Wa=e=>{var r;let t=Number((r=e.getAttribute(Nl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Tn=e=>e.getAttribute(Ol)==="true",Ib=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},Hb=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},ai=(e,t)=>{let{payload:r}=Yo(t),o=ys(r),n=na(e),a={},s=new Set;return o.forEach((i,c)=>{let d=typeof(i==null?void 0:i.question)=="string"?i.question:"";d&&(s.has(d)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,c)&&(a[d]=n[c]))}),a},oh=e=>{let t=na(e),r=ao(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var u;let d=(u=c.getAttribute("data-option-label"))!=null?u:"",p=n.has(d);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.getAttribute("data-option-label"))!=null?d:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},nh=e=>{if(!Tn(e))return;let t=na(e),r=ao(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);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}},_l=(e,t,r)=>{let o=ni(r),n=Sb(e),{payload:a,complete:s}=Yo(t),i=Tn(e),c=ao(e),d=Wa(e),p=i?Mb(a,c):Ab(a),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${c+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";h.textContent=A,h.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let A=kb(p,o,s,n);b.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(th(o,n))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!k?e.appendChild(Lb(o)):(!u||i)&&k&&k.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=Pb(c,d,o);E?E.replaceWith(A):e.appendChild(A)}else E&&E.remove();oh(e),nh(e)},Wb=(e,t,r)=>{let o=ni(t),n=Cb(o),a=e.toolCall.id,s=ys(r),i=Math.max(1,s.length),c=i>1,d=Ib(e,s),p=c?Hb(e,i):0,u=S("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ha,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(Nl,String(i)),u.setAttribute(Fl,String(p)),u.setAttribute(Ol,c?"true":"false"),u.setAttribute(Jg,n),rh(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Zg(u,o);let g=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=S("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=S("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let k=S("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");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),n!=="rows"&&u.appendChild(th(o,n)),_l(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Bb=(e,t,r)=>{let{payload:o}=Yo(t),n=Math.max(1,ys(o).length);n>Wa(e)&&(e.setAttribute(Nl,String(n)),n>1&&!Tn(e)&&e.setAttribute(Ol,"true")),_l(e,t,r)},ah=(e,t)=>{let r=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=ni(t);Zg(r,o);let n=S("span","persona-ask-stub-label"),{complete:a}=Yo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Ba=(e,t,r)=>{if(!r||!Jo(e)||ni(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ha}]`).forEach(d=>{d.getAttribute(Ha)!==n&&d.remove()});let s=r.querySelector(`[${Ha}="${Yg(n)}"]`);if(s){Bb(s,e,t);return}let{payload:i}=Yo(e),c=Wb(e,t,i);r.appendChild(c)},En=(e,t)=>{if(!e)return;let r=t?`[${Ha}="${Yg(t)}"]`:`[${Ha}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Ul=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),kn=(e,t)=>{let r=na(e),o=ao(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,rh(e,r),oh(e),nh(e)},si=(e,t,r,o)=>{let n=Wa(e),a=Math.max(0,Math.min(n-1,o));Rb(e,a),_l(e,t,r)};var vo="suggest_replies";var ql={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ii={name:vo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:ql,origin:"sdk",annotations:{readOnlyHint:!0}},Vl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),bs=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===vo},zl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},li=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!bs(o))continue;let n=zl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},sh=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var $l={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:hs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},jl={name:xs,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:$l,origin:"sdk",annotations:{readOnlyHint:!0}},vs=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(jl),sh(e)&&t.push(ii),t};var Zo=La(oi(),1),di=e=>e.replace(/\\n/g,`
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,
|
|
12
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ss=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},mi=()=>{var t;let e=Nb();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},gi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?di(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=di(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},dh=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?di(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?di(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:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},hi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ch="4.6.1";var aa=ch;var _b="https://api.runtype.com/v1/dispatch",xi="https://api.runtype.com";function Ub(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+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 Kl=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 qb(e){switch(e){case"json":return gi;case"regex-json":return mi;case"xml":return hi;default:return fi}}var ph=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Vb(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=ph(r);if(!ph(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=Ss(e);return Ss(t)!==null&&s===null?t:e}var sa=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(r=t.apiUrl)!=null?r:_b,this.headers={"Content-Type":"application/json","X-Persona-Version":aa,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:qb(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ia(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=$g(o,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,d;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(d=r.agentId)!=null?d:r.flowId,n={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/client/feedback`}async sendFeedback(t){var s,i;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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let d=await this.buildPayload(t.messages),p=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,u={sessionId:c.sessionId,messages:t.messages.filter(Kl).map(y=>{var w,v,M;return{id:y.id,role:y.role,content:(M=(v=(w=y.contentParts)!=null?w:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},g=d.clientTools,f=!!(g&&g.length>0),h=f?Vg(g):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,k=f&&b&&this.lastSentClientToolsFingerprint===h,E=!1,A=null,T;for(let y=0;;y++){let v={...u,...f&&(E||!k)&&g?{clientTools:g}:{},...h?{clientToolsFingerprint:h}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&f){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let w=new Error(y.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=h!=null?h:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&r({type:"error",error:d}),d}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);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(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);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(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o,n){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var d,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||xi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Kl).filter(d=>d.role==="user"||d.role==="assistant"||d.role==="system").filter(d=>!d.variant||d.variant==="assistant").sort((d,p)=>{let u=new Date(d.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(d=>{var p,u,g;return{role:d.role,content:(g=(u=(p=d.contentParts)!=null?p:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...vs(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(d).length&&(n.context=d)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(Kl).sort((c,d)=>{let p=new Date(c.createdAt).getTime(),u=new Date(d.createdAt).getTime();return p-u}).map(c=>{var d,p,u;return{role:c.role,content:(u=(p=(d=c.contentParts)!=null?d:c.llmContent)!=null?p:c.rawContent)!=null?u:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,d]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=d);let a=[...vs(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async d=>{try{let p=await d({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let d=c;return n.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=n.clientTools),d}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=u,n(u),u},d=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=d(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o,n){var xr,Co,So,Ve;let a=t.getReader(),s=new TextDecoder,i="",c=Date.now(),d=0,p=()=>c+d++,u=W=>{let ce=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,Se=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Ae=W.tools?W.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...W,reasoning:ce,toolCall:Se,tools:Ae}},g=W=>{if(W.role!=="assistant"||W.variant)return!0;let ce=Array.isArray(W.contentParts)&&W.contentParts.length>0,Se=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||ce||Se||!!W.stopReason},f=W=>{g(W)&&r({type:"message",message:u(W)})},h=null,b=null,k={current:null},E={current:null},A=null,T="",y=new Map,w=new Map,v=new Map,M=new Map,H=new Map,I={lastId:null,byStep:new Map},P={lastId:null,byCall:new Map},B=W=>{if(W==null)return null;try{return String(W)}catch{return null}},O=W=>{var ce,Se,Ae,Ie,et;return B((et=(Ie=(Ae=(Se=(ce=W.stepId)!=null?ce:W.step_id)!=null?Se:W.step)!=null?Ae:W.parentId)!=null?Ie:W.flowStepId)!=null?et:W.flow_step_id)},Q=W=>{var ce,Se,Ae,Ie,et,Qe,gt;return B((gt=(Qe=(et=(Ie=(Ae=(Se=(ce=W.callId)!=null?ce:W.call_id)!=null?Se:W.requestId)!=null?Ae:W.request_id)!=null?Ie:W.toolCallId)!=null?et:W.tool_call_id)!=null?Qe:W.stepId)!=null?gt:W.step_id)},me=o,ue=!1,Z=()=>{if(h)return h;let W,ce="",Se=A;return!ue&&me?(W=me,ue=!0,ce=n!=null?n:""):me&&Se?W=`${me}_${Se}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:W,role:"assistant",content:ce,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},f(h),h},Le=(W,ce)=>{I.lastId=ce,W&&I.byStep.set(W,ce)},We=(W,ce)=>{var et;let Se=(et=W.reasoningId)!=null?et:W.id,Ae=O(W);if(Se){let Qe=String(Se);return Le(Ae,Qe),Qe}if(Ae){let Qe=I.byStep.get(Ae);if(Qe)return I.lastId=Qe,Qe}if(I.lastId&&!ce)return I.lastId;if(!ce)return null;let Ie=`reason-${p()}`;return Le(Ae,Ie),Ie},ie=W=>{let ce=M.get(W);if(ce)return ce;let Se={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:W,status:"streaming",chunks:[]}};return M.set(W,Se),f(Se),Se},Me=(W,ce)=>{P.lastId=ce,W&&P.byCall.set(W,ce)},oe=new Set,se=new Map,ge=new Set,Te=new Map,qe=W=>{if(!W)return!1;let ce=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return ce==="emit_artifact_markdown"||ce==="emit_artifact_component"},j=(W,ce)=>{var et;let Se=(et=W.toolId)!=null?et:W.id,Ae=Q(W);if(Se){let Qe=String(Se);return Me(Ae,Qe),Qe}if(Ae){let Qe=P.byCall.get(Ae);if(Qe)return P.lastId=Qe,Qe}if(P.lastId&&!ce)return P.lastId;if(!ce)return null;let Ie=`tool-${p()}`;return Me(Ae,Ie),Ie},ee=W=>{let ce=H.get(W);if(ce)return ce;let Se={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:W,status:"pending"}};return H.set(W,Se),f(Se),Se},Ee=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let ce=Number(W);if(!Number.isNaN(ce)&&Number.isFinite(ce))return ce;let Se=Date.parse(W);if(!Number.isNaN(Se))return Se}return Date.now()},te=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},le=new Map,ke=new Map,nt=new Map,yt=(W,ce,Se)=>{var gt;let Ae=nt.get(W);Ae||(Ae=[],nt.set(W,Ae));let Ie=0,et=Ae.length;for(;Ie<et;){let pe=Ie+et>>>1;Ae[pe].seq<ce?Ie=pe+1:et=pe}((gt=Ae[Ie])==null?void 0:gt.seq)===ce?Ae[Ie]={seq:ce,text:Se}:Ae.splice(Ie,0,{seq:ce,text:Se});let Qe="";for(let pe=0;pe<Ae.length;pe++)Qe+=Ae[pe].text;return Qe},Kt=(W,ce)=>{let Se=te(ce),Ae=ke.get(W.id),Ie=Vb(Ae,Se);W.rawContent=Ie;let et=le.get(W.id),Qe=ae=>{var Ke;let mt=(Ke=W.content)!=null?Ke:"";ae.trim()!==""&&(mt.trim().length===0||ae.startsWith(mt)||ae.trimStart().startsWith(mt.trim()))&&(W.content=ae)},gt=()=>{var ae;if(et){let mt=(ae=et.close)==null?void 0:ae.call(et);mt instanceof Promise&&mt.catch(()=>{})}le.delete(W.id),ke.delete(W.id),W.streaming=!1,f(W)};if(!et){Qe(Se),gt();return}let pe=Ss(Ie);if(pe!==null&&pe.trim()!==""){Qe(pe),gt();return}let N=ae=>{var Lt;let mt=typeof ae=="string"?ae:(Lt=ae==null?void 0:ae.text)!=null?Lt:null;if(mt!==null&&mt.trim()!=="")return mt;let Ke=et.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Se},ye;try{ye=et.processChunk(Ie)}catch{Qe(Se),gt();return}if(ye instanceof Promise){ye.then(ae=>{Qe(N(ae)),gt()}).catch(()=>{Qe(Se),gt()});return}Qe(N(ye)),gt()},jt=null,ct=(W,ce,Se,Ae)=>{var pe;W.rawContent=ce,le.has(W.id)||le.set(W.id,this.createStreamParser());let Ie=le.get(W.id),et=ce.trim().startsWith("{")||ce.trim().startsWith("[");if(et&&ke.set(W.id,ce),Ie.__isPlainTextParser===!0){W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W);return}let gt=Ie.processChunk(ce);if(gt instanceof Promise)gt.then(N=>{var ae;let ye=typeof N=="string"?N:(ae=N==null?void 0:N.text)!=null?ae:null;ye!==null&&ye.trim()!==""?(W.content=ye,f(W)):!et&&!ce.trim().startsWith("<")&&(W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W))}).catch(()=>{W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W)});else{let N=typeof gt=="string"?gt:(pe=gt==null?void 0:gt.text)!=null?pe:null;N!==null&&N.trim()!==""?(W.content=N,f(W)):!et&&!ce.trim().startsWith("<")&&(W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W))}},fe=(W,ce)=>{var pe,N;let Se=ce!=null?ce:W.content;if(Se==null||Se===""){W.streaming=!1,f(W);return}let Ae=ke.get(W.id),Ie=Ae!=null?Ae:te(Se);W.rawContent=Ie;let et=le.get(W.id),Qe=null,gt=!1;if(et&&(Qe=et.getExtractedText(),Qe===null&&(Qe=Ss(Ie)),Qe===null)){let ye=et.processChunk(Ie);ye instanceof Promise?(gt=!0,ye.then(ae=>{var Ke;let mt=typeof ae=="string"?ae:(Ke=ae==null?void 0:ae.text)!=null?Ke:null;mt!==null&&(W.content=mt,W.streaming=!1,le.delete(W.id),ke.delete(W.id),f(W))}).catch(()=>{})):Qe=typeof ye=="string"?ye:(pe=ye==null?void 0:ye.text)!=null?pe:null}if(!gt){Qe!==null&&Qe.trim()!==""?W.content=Qe:ke.has(W.id)||(W.content=te(Se));let ye=le.get(W.id);if(ye){let ae=(N=ye.close)==null?void 0:N.call(ye);ae instanceof Promise&&ae.catch(()=>{}),le.delete(W.id)}ke.delete(W.id),W.streaming=!1,f(W)}},X=(W,ce,Se)=>{let Ae=w.get(W);if(Ae)return Ae;let Ie={id:`nested-${ce}-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Se?{variant:Se}:{},...Se==="reasoning"?{reasoning:{id:W,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ce}};return w.set(W,Ie),f(Ie),Ie},st=[],je,Ce=new Map,ve=0,Ye="agent",Vt=!1,xe=null,de=null,Cr=new Map,Ct=(xr=this.config.iterationDisplay)!=null?xr:"separate";for(je=()=>{var W,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,tr,Ao,Uo,io,lo,on,zt,co,qo,Fr,Rr,Nr,po,Mo,nn,Qr,an,St,To,Eo,Vo,uo,ht,On,ko,_n,Ir,xa,sn,zo,ln,dn,Un,qn,cn,vt,Or,_r,Sr,At,Jr,Yr,Ur,pn,we,$o,Zr,Nt,eo,jo,Ya,ya,Za,Vn,Lo,un,it,ar,sr,Po,es,Go,zn,Ro,U,ba,fo,Io,Ko,Ho,mo,va,$s,yr,Ar,go,Mr,$n,ho,br,Wo,wa,jn,Ca,fn;for(let mn=0;mn<st.length;mn++){let rt=st[mn].payloadType,L=st[mn].payload;if(!Vt&&Ye!=="flow"&&typeof L.stepType=="string"&&(Ye="flow"),rt==="reasoning_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){y.set($,z),X($,z,"reasoning");continue}let K=(W=We(L,!0))!=null?W:`reason-${p()}`,G=ie(K);G.reasoning=(ce=G.reasoning)!=null?ce:{id:K,status:"streaming",chunks:[]},G.reasoning.startedAt=(Ae=G.reasoning.startedAt)!=null?Ae:Ee((Se=L.startedAt)!=null?Se:L.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(rt==="reasoning_delta"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)&&w.has($)){let De=w.get($),tt=(Qe=(et=(Ie=L.reasoningText)!=null?Ie:L.text)!=null?et:L.delta)!=null?Qe:"";tt&&L.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(tt)),f(De));continue}let z=(pe=(gt=We(L,!1))!=null?gt:We(L,!0))!=null?pe:`reason-${p()}`,K=ie(z);K.reasoning=(N=K.reasoning)!=null?N:{id:z,status:"streaming",chunks:[]},K.reasoning.startedAt=(ae=K.reasoning.startedAt)!=null?ae:Ee((ye=L.startedAt)!=null?ye:L.timestamp);let G=(Lt=(Ke=(mt=L.reasoningText)!=null?mt:L.text)!=null?Ke:L.delta)!=null?Lt:"";if(G&&L.hidden!==!0){let De=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(De!==void 0){let tt=yt(z,De,String(G));K.reasoning.chunks=[tt]}else K.reasoning.chunks.push(String(G))}if(K.reasoning.status=L.done?"complete":"streaming",L.done){K.reasoning.completedAt=Ee((Et=L.completedAt)!=null?Et:L.timestamp);let De=(bt=K.reasoning.startedAt)!=null?bt:Date.now();K.reasoning.durationMs=Math.max(0,((It=K.reasoning.completedAt)!=null?It:Date.now())-De)}K.streaming=K.reasoning.status!=="complete",f(K)}else if(rt==="reasoning_complete"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)&&w.has($)){let tt=w.get($);if(tt.reasoning){let lt=typeof L.text=="string"?L.text:"";lt&&tt.reasoning.chunks.length===0&&tt.reasoning.chunks.push(lt),tt.reasoning.status="complete",tt.streaming=!1,f(tt)}y.delete($),w.delete($);continue}let z=(Ft=(Qt=We(L,!1))!=null?Qt:We(L,!0))!=null?Ft:`reason-${p()}`,K=typeof L.text=="string"?L.text:"";!M.get(z)&&(K||L.scope==="loop")&&ie(z);let G=M.get(z);if(G!=null&&G.reasoning){(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),K&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(K),G.reasoning.status="complete",G.reasoning.completedAt=Ee((tr=L.completedAt)!=null?tr:L.timestamp);let tt=(Ao=G.reasoning.startedAt)!=null?Ao:Date.now();G.reasoning.durationMs=Math.max(0,((Uo=G.reasoning.completedAt)!=null?Uo:Date.now())-tt),G.streaming=!1,f(G)}let De=O(L);De&&I.byStep.delete(De)}else if(rt==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof L.iteration=="number"&&(ve=L.iteration);let $=(lo=(io=typeof L.toolCallId=="string"?L.toolCallId:void 0)!=null?io:j(L,!0))!=null?lo:`tool-${p()}`,z=(on=L.toolName)!=null?on:L.name;if(qe(z)){oe.add($);continue}Me(Q(L),$);let K=ee($),G=(zt=K.toolCall)!=null?zt:{id:$,status:"pending"};G.name=z!=null?z:G.name,G.status="running",L.parameters!==void 0?G.args=L.parameters:L.args!==void 0&&(G.args=L.args),G.startedAt=(qo=G.startedAt)!=null?qo:Ee((co=L.startedAt)!=null?co:L.timestamp),G.completedAt=void 0,G.durationMs=void 0,K.toolCall=G,K.streaming=!0,L.executionId&&(K.agentMetadata={executionId:L.executionId,iteration:L.iteration}),f(K)}else if(rt==="tool_output_delta"){let $=(Rr=(Fr=j(L,!1))!=null?Fr:j(L,!0))!=null?Rr:`tool-${p()}`;if(oe.has($))continue;let z=ee($),K=(Nr=z.toolCall)!=null?Nr:{id:$,status:"running"};K.startedAt=(Mo=K.startedAt)!=null?Mo:Ee((po=L.startedAt)!=null?po:L.timestamp);let G=(an=(Qr=(nn=L.text)!=null?nn:L.delta)!=null?Qr:L.message)!=null?an:"";G&&(K.chunks=(St=K.chunks)!=null?St:[],K.chunks.push(String(G))),K.status="running",z.toolCall=K,z.streaming=!0;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(Vo=z.agentMetadata)!=null?Vo:{executionId:(To=De==null?void 0:De.executionId)!=null?To:L.executionId,iteration:(Eo=De==null?void 0:De.iteration)!=null?Eo:L.iteration}),f(z)}else if(rt==="tool_complete"){let $=(ht=(uo=j(L,!1))!=null?uo:j(L,!0))!=null?ht:`tool-${p()}`;if(oe.has($)){oe.delete($);continue}let z=ee($),K=(On=z.toolCall)!=null?On:{id:$,status:"running"};K.status="complete",L.result!==void 0&&(K.result=L.result),typeof L.duration=="number"&&(K.duration=L.duration),K.completedAt=Ee((ko=L.completedAt)!=null?ko:L.timestamp);let G=(_n=L.duration)!=null?_n:L.executionTime;if(typeof G=="number")K.durationMs=G;else{let lt=(Ir=K.startedAt)!=null?Ir:Date.now();K.durationMs=Math.max(0,((xa=K.completedAt)!=null?xa:Date.now())-lt)}z.toolCall=K,z.streaming=!1;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(ln=z.agentMetadata)!=null?ln:{executionId:(sn=De==null?void 0:De.executionId)!=null?sn:L.executionId,iteration:(zo=De==null?void 0:De.iteration)!=null?zo:L.iteration}),f(z);let tt=Q(L);tt&&P.byCall.delete(tt)}else if(rt==="await"&&L.toolName){let $=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,z=(dn=$!=null?$:L.toolId)!=null?dn:`local-${p()}`,K=ee(z),G=L.toolName,De=L.origin==="webmcp"&&!An(G)?`webmcp:${G}`:G,tt=An(De),lt=(Un=K.toolCall)!=null?Un:{id:z,status:"pending"};lt.name=De,lt.args=L.parameters,lt.status=tt?"running":"complete",lt.chunks=(qn=lt.chunks)!=null?qn:[],lt.startedAt=(Or=lt.startedAt)!=null?Or:Ee((vt=(cn=L.startedAt)!=null?cn:L.timestamp)!=null?vt:L.awaitedAt),tt?(lt.completedAt=void 0,lt.duration=void 0,lt.durationMs=void 0):lt.completedAt=(_r=lt.completedAt)!=null?_r:lt.startedAt,K.toolCall=lt,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:(At=L.executionId)!=null?At:(Sr=K.agentMetadata)==null?void 0:Sr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(K)}else if(rt==="text_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){y.set($,z);continue}let K=h;K&&(Ye==="flow"?(fe(K),jt=K):(K.streaming=!1,f(K)),h=null),A=typeof L.id=="string"?L.id:A,T=""}else if(rt==="text_delta"){let $=typeof L.id=="string"?L.id:null,z=$?y.get($):void 0;if($&&z){let G=typeof L.delta=="string"?L.delta:"",De=((Jr=v.get($))!=null?Jr:"")+G;if(v.set($,De),De.trim()==="")continue;let tt=X($,z);tt.agentMetadata={...tt.agentMetadata,executionId:L.executionId,parentToolId:z},ct(tt,De,G,void 0);continue}if(A=typeof L.id=="string"?L.id:A,Ye==="flow"){let G=typeof L.delta=="string"?L.delta:"";if(T+=G,T.trim()==="")continue;let De=Z();De.agentMetadata={executionId:L.executionId,iteration:L.iteration},ct(De,T,G,void 0),b=De;continue}let K=Z();K.content+=(Yr=L.delta)!=null?Yr:"",K.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:xe!=null?xe:void 0,agentName:de==null?void 0:de.agentName},b=K,f(K)}else if(rt==="text_complete"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)){let K=w.get($);K&&fe(K),y.delete($),v.delete($),w.delete($);continue}let z=h;z&&(Ye==="flow"?(fe(z),jt=z):(((Ur=z.content)!=null?Ur:"")===""&&typeof L.text=="string"&&(z.content=L.text),z.streaming=!1,f(z)),h=null),A=null,T=""}else if(rt==="step_complete"){let $=L.stepType,z=L.executionType;if($==="tool"||z==="context")continue;if(L.success===!1){let K=L.error,G=typeof K=="string"&&K!==""?K:K!=null&&typeof K=="object"&&Reflect.has(K,"message")?String((pn=K.message)!=null?pn:"Step failed"):"Step failed";r({type:"error",error:new Error(G)});let De=h;De&&De.streaming&&(De.streaming=!1,f(De)),r({type:"status",status:"idle"});continue}{let K=jt;jt=null;let G=L.stopReason,De=(we=L.result)==null?void 0:we.response;if(K)G&&(K.stopReason=G),De!=null?Kt(K,De):K.streaming!==!1&&(le.delete(K.id),ke.delete(K.id),K.streaming=!1,f(K));else{let tt=De!=null&&De!=="";if(tt||G){let lt=Z();G&&(lt.stopReason=G),tt?fe(lt,De):(lt.streaming=!1,f(lt))}}continue}}else if(rt==="execution_start")Ye=L.kind==="flow"?"flow":"agent",Vt=!0,Ye==="agent"&&(de={executionId:L.executionId,agentId:($o=L.agentId)!=null?$o:"virtual",agentName:(Zr=L.agentName)!=null?Zr:"",status:"running",currentIteration:0,maxTurns:(Nt=L.maxTurns)!=null?Nt:1,startedAt:Ee(L.startedAt)});else if(rt==="turn_start"){let $=typeof L.iteration=="number"?L.iteration:ve;if($!==ve){if(de&&(de.currentIteration=$),Ct==="separate"&&$>1){let z=h;z&&(z.streaming=!1,f(z),Cr.set($-1,z),h=null)}ve=$}xe=typeof L.id=="string"?L.id:null,b=null}else if(rt==="tool_input_delta"){let $=(eo=L.toolCallId)!=null?eo:P.lastId;if($){let z=H.get($);z!=null&&z.toolCall&&(z.toolCall.chunks=(jo=z.toolCall.chunks)!=null?jo:[],z.toolCall.chunks.push((Ya=L.delta)!=null?Ya:""),f(z))}}else{if(rt==="tool_input_complete")continue;if(rt==="turn_complete"){let $=L.stopReason,z=h!=null?h:b;if($&&z!==null){let K=L.id;(!K||((ya=z.agentMetadata)==null?void 0:ya.turnId)===K)&&(z.stopReason=$,f(z))}xe===L.id&&(xe=null)}else if(rt==="media_start"){let $=String(L.id);Ce.set($,{mediaType:typeof L.mediaType=="string"?L.mediaType:void 0,role:typeof L.role=="string"?L.role:void 0,toolCallId:L.toolCallId,parts:[]})}else if(rt==="media_delta"){let $=Ce.get(String(L.id));$&&typeof L.delta=="string"&&$.parts.push(L.delta)}else if(rt==="media_complete"){let $=String(L.id),z=Ce.get($);Ce.delete($);let K=(Vn=(Za=typeof L.mediaType=="string"?L.mediaType:void 0)!=null?Za:z==null?void 0:z.mediaType)!=null?Vn:"application/octet-stream",G=typeof L.data=="string"?L.data:void 0,De=typeof L.url=="string"?L.url:z&&z.parts.length>0?z.parts.join(""):void 0,tt=null;if(G)tt={type:"media",data:G,mediaType:K};else if(De){let Hr=K.toLowerCase();tt={type:Hr==="image"||Hr.startsWith("image/")?"image-url":"file-url",url:De,mediaType:K}}let lt=(Lo=L.toolCallId)!=null?Lo:z==null?void 0:z.toolCallId,bl=tt?[tt]:[],gn=[];for(let Hr of bl){if(!Hr||typeof Hr!="object")continue;let Jt=Hr,hn=typeof Jt.type=="string"?Jt.type:void 0,to=typeof Jt.mediaType=="string"?Jt.mediaType.toLowerCase():"",Tr=null,Wr="";if(hn==="media"){let Er=typeof Jt.data=="string"?Jt.data:void 0;if(!Er)continue;Wr=to.length>0?to:"application/octet-stream",Tr=`data:${Wr};base64,${Er}`}else if(hn==="image-url"){let Er=typeof Jt.url=="string"?Jt.url:void 0;if(!Er)continue;Wr=to,Tr=Er}else if(hn==="file-url"){let Er=typeof Jt.url=="string"?Jt.url:void 0;if(!Er)continue;Wr=to,Tr=Er}else continue;if(Tr)if(hn==="image-url"||Wr.startsWith("image/"))gn.push({type:"image",image:Tr,...Wr.includes("/")?{mimeType:Wr}:{}});else if(Wr.startsWith("audio/"))gn.push({type:"audio",audio:Tr,mimeType:Wr});else if(Wr.startsWith("video/"))gn.push({type:"video",video:Tr,mimeType:Wr});else{let Er=Wr||"application/octet-stream";gn.push({type:"file",data:Tr,mimeType:Er,filename:Ub(Er)})}}if(gn.length>0){let Hr=p(),Jt=lt,to={id:`agent-media-${typeof Jt=="string"&&Jt.length>0?`${Jt}-${Hr}`:String(Hr)}`,role:"assistant",content:"",contentParts:gn,createdAt:new Date().toISOString(),streaming:!1,sequence:Hr,agentMetadata:{executionId:L.executionId,iteration:typeof L.iteration=="number"?L.iteration:ve}};f(to);let Tr=h;Tr&&(Tr.streaming=!1,f(Tr)),h=null,k.current=null}}else if(rt==="execution_complete"){let $=(un=L.kind)!=null?un:Ye;$==="agent"&&de&&(de.status=L.success?"complete":"error",de.completedAt=Ee(L.completedAt),de.stopReason=L.stopReason);let z=h;z&&($==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,f(z)),h=null),A=null,T="",jt=null,r({type:"status",status:"idle",terminal:!0})}else if(rt==="execution_error"){let $=typeof L.error=="string"?L.error:(ar=(it=L.error)==null?void 0:it.message)!=null?ar:"Execution error";r({type:"error",error:new Error($)})}else if(rt!=="ping"){if(rt==="approval_start"){let $=(sr=L.approvalId)!=null?sr:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(Po=de==null?void 0:de.agentId)!=null?Po:"virtual",executionId:(Go=(es=L.executionId)!=null?es:de==null?void 0:de.executionId)!=null?Go:"",toolName:(zn=L.toolName)!=null?zn:"",toolType:L.toolType,description:(U=L.description)!=null?U:`Execute ${(Ro=L.toolName)!=null?Ro:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(z)}else if(rt==="step_await"&&L.awaitReason==="approval_required"){let $=(ba=L.approvalId)!=null?ba:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(fo=de==null?void 0:de.agentId)!=null?fo:"virtual",executionId:(Ko=(Io=L.executionId)!=null?Io:de==null?void 0:de.executionId)!=null?Ko:"",toolName:(Ho=L.toolName)!=null?Ho:"",toolType:L.toolType,description:(va=L.description)!=null?va:`Execute ${(mo=L.toolName)!=null?mo:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(z)}else if(rt==="approval_complete"){let $=L.approvalId;if($){let K={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:($s=L.decision)!=null?$s:"approved",agentId:(yr=de==null?void 0:de.agentId)!=null?yr:"virtual",executionId:(go=(Ar=L.executionId)!=null?Ar:de==null?void 0:de.executionId)!=null?go:"",toolName:(Mr=L.toolName)!=null?Mr:"",description:($n=L.description)!=null?$n:"",resolvedAt:Date.now()}};f(K)}}else if(rt==="artifact_start"||rt==="artifact_delta"||rt==="artifact_update"||rt==="artifact_complete"){if(rt==="artifact_start"){let $=L.artifactType,z=String(L.id),K=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:z,artifactType:$,title:K,component:typeof L.component=="string"?L.component:void 0}),Te.set(z,{markdown:"",title:K}),!ge.has(z)){ge.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:K,artifactType:$,status:"streaming"}})};se.set(z,G),f(G)}}else if(rt==="artifact_delta"){let $=String(L.id),z=typeof L.delta=="string"?L.delta:String((ho=L.delta)!=null?ho:"");r({type:"artifact_delta",id:$,artDelta:z});let K=Te.get($);K&&(K.markdown+=z)}else if(rt==="artifact_update"){let $=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:$,component:typeof L.component=="string"?L.component:void 0})}else if(rt==="artifact_complete"){let $=String(L.id);r({type:"artifact_complete",id:$});let z=se.get($);if(z){z.streaming=!1;try{let K=JSON.parse((br=z.rawContent)!=null?br:"{}");if(K.props){K.props.status="complete";let G=Te.get($);G!=null&&G.markdown&&(K.props.markdown=G.markdown)}z.rawContent=JSON.stringify(K)}catch{}Te.delete($),f(z),se.delete($)}}}else if(rt==="transcript_insert"){let $=L.message;if(!$||typeof $!="object")continue;let z=String((Wo=$.id)!=null?Wo:`msg-${p()}`),K=$.role,De={id:z,role:K==="user"?"user":K==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:p()};if(f(De),De.rawContent)try{let tt=JSON.parse(De.rawContent),lt=(wa=tt==null?void 0:tt.props)==null?void 0:wa.artifactId;typeof lt=="string"&&ge.add(lt)}catch{}h=null,k.current=null,le.delete(z),ke.delete(z)}else if(rt==="error"){if(L.recoverable===!1&&L.error!=null&&L.error!==""){let $=typeof L.error=="string"?L.error:((jn=L.error)==null?void 0:jn.message)!=null?String(L.error.message):"Execution error";r({type:"error",error:new Error($)});let z=h;z&&z.streaming&&(z.streaming=!1,f(z)),r({type:"status",status:"idle"})}}else if(rt==="step_error"||rt==="dispatch_error"||rt==="flow_error"){let $=null;if(L.error instanceof Error)$=L.error;else if(rt==="dispatch_error"){let z=(Ca=L.message)!=null?Ca:L.error;z!=null&&z!==""&&($=new Error(String(z)))}else{let z=L.error;typeof z=="string"&&z!==""?$=new Error(z):z!=null&&typeof z=="object"&&Reflect.has(z,"message")&&($=new Error(String((fn=z.message)!=null?fn:z)))}if($){r({type:"error",error:$});let z=h;z&&z.streaming&&(z.streaming=!1,f(z)),r({type:"status",status:"idle"})}}}}}st.length=0};;){let{done:W,value:ce}=await a.read();if(W)break;i+=s.decode(ce,{stream:!0});let Se=i.split(`
|
|
9
|
+
${e.description}`:"");return window.confirm(o)},Cy=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},wy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ay=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function jr(e,t){let o=e?.display;return o?typeof o=="string"?o:o.byType?.[t]??o.default??"panel":"panel"}function Bs(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Sy="agent_",Ty="flow_";function kf(e){return e.startsWith(Sy)?{kind:"agentId",agentId:e}:e.startsWith(Ty)?{kind:"flowId",flowId:e}:null}function Lf(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let r=o.indexOf(":");if(r>0){let s=o.slice(0,r),l=o.slice(r+1);if(s==="runtype"){let d=kf(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[s];if(!p)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let n=kf(o);if(n)return n;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var dr=wn(Ds(),1);var y=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o},Io=(e,t,o)=>{let r=e.createElement(t);return o&&(r.className=o),r},Rf=()=>document.createDocumentFragment(),rt=(e,t={},...o)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))r.setAttribute(a,s);if(t.style){let a=r.style,s=t.style;for(let l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let n=o.filter(a=>a!=null);return n.length>0&&r.append(...n),r},Gr=(...e)=>e.filter(Boolean).join(" ");var Sa="ask_user_question",Aa=8,Mn="data-persona-ask-sheet-for",Py="Other",Ry="Other\u2026",Bf="Type your own answer here",Hf="Send",Iy="Next",By="Back",Hy="Submit all",Wy="Skip",Dy=3,Vl="data-ask-current-index",zl="data-ask-question-count",Wf="data-ask-answers",$l="data-ask-grouped",Df="data-ask-layout",Fy=e=>e.layout==="pills"?"pills":"rows",Oy=e=>e.getAttribute(Df)==="pills"?"pills":"rows",If=!1,Ff=e=>e.replace(/["\\]/g,"\\$&"),Vo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Sa,Fs=e=>e?.features?.askUserQuestion??{},zo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:o};try{let n=r.join(""),a=(0,dr.parse)(n,dr.STR|dr.OBJ|dr.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},Ta=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Aa&&!If&&(If=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Aa}.`)),t.slice(0,Aa)},Ny=e=>Ta(e)[0]??null,_y=(e,t)=>Ta(e)[t]??null,Of=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},Nf=(e,t,o)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let n=y("span","persona-ask-row-check");r.appendChild(n)}else{let n=y("span","persona-ask-row-badge");n.textContent=String(o+1),r.appendChild(n)}return r},Uy=(e,t,o,r)=>{let a=y("button",o==="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",r?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let s=y("span","persona-ask-row-content"),l=y("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let d=y("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let p=Nf(o,r,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},qy=e=>{let o=y("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 o.setAttribute("aria-hidden","true"),o},Vy=(e,t,o,r)=>{let a=y("div",r==="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?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!o){for(let c=0;c<Dy;c++)a.appendChild(qy(r));return a}if(p.forEach((c,u)=>{a.appendChild(Uy(c,u,r,s))}),e?.allowFreeText!==!1){let c=r==="rows"?Py:Ry;if(r==="rows"){let u=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let g=y("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Bf,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),g.appendChild(f),u.appendChild(g);let h=Nf(r,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,a.appendChild(u)}}return a},_f=(e,t)=>{let r=y("div",t==="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");r.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=e.freeTextPlaceholder??Bf,n.setAttribute("data-ask-free-text-input","true"),r.appendChild(n),t!=="rows"){let a=y("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Hf,a.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(a)}return r},zy=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=y("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??Hf,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},$y=(e,t,o)=>{let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let n=y("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=o.backLabel??By,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,r.appendChild(n);let a=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=y("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=o.skipLabel??Wy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=y("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?o.submitAllLabel??Hy:o.nextLabel??Iy,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),r.appendChild(a),r},Kr=e=>{let t=e.getAttribute(Wf);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},Uf=(e,t)=>{e.setAttribute(Wf,JSON.stringify(t))},ho=e=>{let t=Number(e.getAttribute(Vl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},jy=(e,t)=>{e.setAttribute(Vl,String(Math.max(0,Math.floor(t))))},En=e=>{let t=Number(e.getAttribute(zl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},cr=e=>e.getAttribute($l)==="true",Gy=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let r={};return t.forEach((n,a)=>{let s=typeof n?.question=="string"?n.question:"";if(s&&Object.prototype.hasOwnProperty.call(o,s)){let l=o[s];(typeof l=="string"||Array.isArray(l))&&(r[a]=l)}}),r},Ky=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},Os=(e,t)=>{let{payload:o}=zo(t),r=Ta(o),n=Kr(e),a={},s=new Set;return r.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(s.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,p)&&(a[d]=n[p]))}),a},qf=e=>{let t=Kr(e),o=ho(e),r=t[o],n=new Set;typeof r=="string"?n.add(r):Array.isArray(r)&&r.forEach(p=>n.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=n.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let s=new Set(Array.from(a).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof r=="string"&&r.length>0&&!s.has(r)?(l.value=r,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Vf=e=>{if(!cr(e))return;let t=Kr(e),o=ho(e),r=t[o],n=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=l.length===0}},jl=(e,t,o)=>{let r=Fs(o),n=Oy(e),{payload:a,complete:s}=zo(t),l=cr(e),p=ho(e),d=En(e),c=l?_y(a,p):Ny(a),u=!!c?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let A=typeof c?.question=="string"?c.question:"";h.textContent=A,h.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let A=Vy(c,r,s,n);C.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(_f(r,n))}let M=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!M?e.appendChild(zy(r)):(!u||l)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(l){let A=$y(p,d,r);L?L.replaceWith(A):e.appendChild(A)}else L&&L.remove();qf(e),Vf(e)},Xy=(e,t,o)=>{let r=Fs(t),n=Fy(r),a=e.toolCall.id,s=Ta(o),l=Math.max(1,s.length),p=l>1,d=Gy(e,s),c=p?Ky(e,l):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Mn,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(zl,String(l)),u.setAttribute(Vl,String(c)),u.setAttribute($l,p?"true":"false"),u.setAttribute(Df,n),Uf(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Of(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=y("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let M=y("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");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),n!=="rows"&&u.appendChild(_f(r,n)),jl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Jy=(e,t,o)=>{let{payload:r}=zo(t),n=Math.max(1,Ta(r).length);n>En(e)&&(e.setAttribute(zl,String(n)),n>1&&!cr(e)&&e.setAttribute($l,"true")),jl(e,t,o)},zf=(e,t)=>{let o=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let r=Fs(t);Of(o,r);let n=y("span","persona-ask-stub-label"),{complete:a}=zo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(n),o},kn=(e,t,o)=>{if(!o||!Vo(e)||Fs(t).enabled===!1)return;let n=e.toolCall.id;o.querySelectorAll(`[${Mn}]`).forEach(d=>{d.getAttribute(Mn)!==n&&d.remove()});let s=o.querySelector(`[${Mn}="${Ff(n)}"]`);if(s){Jy(s,e,t);return}let{payload:l}=zo(e),p=Xy(e,t,l);o.appendChild(p)},pr=(e,t)=>{if(!e)return;let o=t?`[${Mn}="${Ff(t)}"]`:`[${Mn}]`;e.querySelectorAll(o).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Gl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ur=(e,t)=>{let o=Kr(e),r=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[r]:o[r]=t,Uf(e,o),qf(e),Vf(e)},Ns=(e,t,o,r)=>{let n=En(e),a=Math.max(0,Math.min(n-1,r));jy(e,a),jl(e,t,o)};var To="suggest_replies";var Kl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},_s={name:To,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Kl,origin:"sdk",annotations:{readOnlyHint:!0}},Xl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ma=e=>e.variant==="tool"&&e.toolCall?.name===To,Jl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let r=o.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Us=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Ma(o))continue;let r=Jl(o.toolCall?.args);return r.length>0?r:null}return null},$f=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var Ql={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Aa,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Yl={name:Sa,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Ql,origin:"sdk",annotations:{readOnlyHint:!0}},Ln=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(Yl),$f(e)&&t.push(_s),t};var $o=wn(Ds(),1),qs=e=>e.replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fr=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)}},Qy=e=>{let t=e.completedAt??Date.now(),o=e.startedAt??t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-o))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},jf=e=>e.status==="complete"?Qy(e):e.status==="pending"?"Waiting":"",Yy=e=>{let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Gf=e=>e.status==="complete"?Yy(e):"Using tool...",Vs=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ka=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Vs(t)},zs=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Vs(t)},Zl=(e,t,o)=>{if(!t)return o;let r=e.name?.trim()||"tool",n=ka(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,n)},$s=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),r=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(o))!==null;)s.index>a&&Ea(r,o.slice(a,s.index),[]),s[1]!==void 0?Ea(r,s[1],["bold"]):s[2]!==void 0?Ea(r,s[2],["italic"]):s[3]!==void 0&&Ea(r,s[3],["dim"]),a=s.index+s[0].length;return a<o.length&&Ea(r,o.slice(a),[]),r},Ea=(e,t,o)=>{let r=t.split("{duration}");for(let n=0;n<r.length;n++)r[n]&&e.push({text:r[n],styles:o}),n<r.length-1&&e.push({text:"{duration}",styles:o,isDuration:!0})},Zy=()=>{let e=null,t=0,o=r=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=r.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=r.match(s);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
12
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=o(r);return a!==null&&(e=a),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},La=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},js=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gs=()=>{let e=Zy();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ks=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let n=(0,$o.parse)(o,$o.STR|$o.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?qs(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=qs(n.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Kf=e=>{let t=null,o=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?qs(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?qs(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:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let l=(0,$o.parse)(a,$o.STR|$o.OBJ),p=n(l);p!==null&&(t=p)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Xs=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Xf="4.8.0";var Xr=Xf;var tb="https://api.runtype.com/v1/dispatch",Js="https://api.runtype.com";function ob(e){let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let n=t.indexOf("/");if(n>0){let a=t.slice(n+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var ed=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function rb(e){switch(e){case"json":return Ks;case"regex-json":return Gs;case"xml":return Xs;default:return js}}var Jf=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function nb(e,t){if(!e)return t;let o=e.trim(),r=t.trim();if(o.length===0)return t;if(r.length===0)return e;let n=Jf(o);if(!Jf(r))return e;if(!n||r===o||r.startsWith(o))return t;let s=La(e);return La(t)!==null&&s===null?t:e}var Jr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??tb,this.headers={"Content-Type":"application/json","X-Persona-Version":Xr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??rb(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Tn(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,o,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:r,targetProviders:n}=this.config;if(!r)return{agentId:t,flowId:o};let a=Lf(r,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,o=this.routing(),r=o.agentId??o.flowId,n={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},body:JSON.stringify(n)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},body:JSON.stringify(n)});if(!a.ok){let s=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(s.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:o})}async dispatch(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){o({type:"status",status:"connecting"});try{let r=await this.initSession();if(new Date>=new Date(r.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:d}),d}let n=await this.buildPayload(t.messages),a=n.metadata?Object.fromEntries(Object.entries(n.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,s={sessionId:r.sessionId,messages:t.messages.filter(ed).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...n.inputs&&Object.keys(n.inputs).length>0&&{inputs:n.inputs},...n.context&&{context:n.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(r.sessionId,n.clientTools,d=>{let c={...s,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw o({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw o({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw o({type:"error",error:d}),d}p(),o({type:"status",status:"connected"});try{await this.streamResponse(l.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(r){let n=r instanceof Error?r:new Error(String(r));throw!n.message.includes("Session expired")&&!n.message.includes("Message limit")&&o({type:"error",error:n}),n}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let n={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();n={...n,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(r),signal:t.signal},r)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw o({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(r),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:s}),s}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let n={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();n={...n,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(r),signal:t.signal},r)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw o({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(r),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:s}),s}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,r,n){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,r,n)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,r,n){let a=!!(o&&o.length>0),s=a?Ef(o):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,d=!a&&n?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let g=0;;g++){if(u=await r({...a&&(c||!p)&&o?{clientTools:o}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),u.status===409&&g===0&&a&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,r){let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Js}/resume`,s;n&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:o,streamResponse:r?.streamResponse??!0};if(s&&(p.sessionId=s),n&&s){let d=[...Ln(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(s,d,g=>{let f={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(a,{method:"POST",headers:l,body:JSON.stringify(f),signal:r?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(a,{method:"POST",headers:l,body:JSON.stringify(p),signal:r?.signal})}async buildAgentPayload(t){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(ed).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,l)=>{let p=new Date(s.createdAt).getTime(),d=new Date(l.createdAt).getTime();return p-d}).map(s=>({role:s.role,content:s.contentParts??s.llmContent??s.rawContent??s.content,createdAt:s.createdAt})),n={agent:this.config.agent??{agentId:o},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...Ln(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(s,p)}catch(p){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(t){let o=t.slice().filter(ed).sort((s,l)=>{let p=new Date(s.createdAt).getTime(),d=new Date(l.createdAt).getTime();return p-d}).map(s=>({role:s.role,content:s.contentParts??s.llmContent??s.rawContent??s.content,createdAt:s.createdAt})),r=this.routing(),n={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[s,l]of Object.entries(r.targetPayload))s!=="messages"&&(n[s]=l);let a=[...Ln(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(s,p)}catch(p){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object"){let l=s;return n.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=n.clientTools),l}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(t,o,r,n,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...c!==void 0&&{partId:c}};return r.current=u,n(u),u},d=c=>r.current?r.current:p(c);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(r.current&&(r.current.streaming=!1,n(r.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,n(c)}return l.done&&(r.current&&(r.current.streaming=!1,n(r.current)),s.current=null,o({type:"status",status:"idle"})),l.error&&(s.current=null,o({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,o,r,n){let a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=R=>{let J=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,x=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,k=R.tools?R.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...R,reasoning:J,toolCall:x,tools:k}},g=R=>{if(R.role!=="assistant"||R.variant)return!0;let J=Array.isArray(R.contentParts)&&R.contentParts.length>0,x=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||J||x||!!R.stopReason},f=R=>{g(R)&&o({type:"message",message:u(R)})},h=null,C=null,M={current:null},L={current:null},A=null,T="",S=new Map,E=new Map,B=new Map,H=new Map,w=new Map,F={lastId:null,byStep:new Map},q={lastId:null,byCall:new Map},O=R=>{if(R==null)return null;try{return String(R)}catch{return null}},z=R=>O(R.stepId??R.step_id??R.step??R.parentId??R.flowStepId??R.flow_step_id),le=R=>O(R.callId??R.call_id??R.requestId??R.request_id??R.toolCallId??R.tool_call_id??R.stepId??R.step_id),ue=r,Ee=!1,De=()=>{if(h)return h;let R,J="",x=A;return!Ee&&ue?(R=ue,Ee=!0,J=n??""):ue&&x?R=`${ue}_${x}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:R,role:"assistant",content:J,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},se=(R,J)=>{F.lastId=J,R&&F.byStep.set(R,J)},xe=(R,J)=>{let x=R.reasoningId??R.id,k=z(R);if(x){let N=String(x);return se(k,N),N}if(k){let N=F.byStep.get(k);if(N)return F.lastId=N,N}if(F.lastId&&!J)return F.lastId;if(!J)return null;let I=`reason-${c()}`;return se(k,I),I},Y=R=>{let J=H.get(R);if(J)return J;let x={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:R,status:"streaming",chunks:[]}};return H.set(R,x),f(x),x},de=(R,J)=>{q.lastId=J,R&&q.byCall.set(R,J)},ee=new Set,Ce=new Map,Ae=new Set,be=new Map,He=R=>{if(!R)return!1;let J=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return J==="emit_artifact_markdown"||J==="emit_artifact_component"},Oe=(R,J)=>{let x=R.toolId??R.id,k=le(R);if(x){let N=String(x);return de(k,N),N}if(k){let N=q.byCall.get(k);if(N)return q.lastId=N,N}if(q.lastId&&!J)return q.lastId;if(!J)return null;let I=`tool-${c()}`;return de(k,I),I},Ke=R=>{let J=w.get(R);if(J)return J;let x={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:R,status:"pending"}};return w.set(R,x),f(x),x},Ue=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let J=Number(R);if(!Number.isNaN(J)&&Number.isFinite(J))return J;let x=Date.parse(R);if(!Number.isNaN(x))return x}return Date.now()},ke=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},Re=new Map,it=new Map,Ne=new Map,Je=(R,J,x)=>{let k=Ne.get(R);k||(k=[],Ne.set(R,k));let I=0,N=k.length;for(;I<N;){let _=I+N>>>1;k[_].seq<J?I=_+1:N=_}k[I]?.seq===J?k[I]={seq:J,text:x}:k.splice(I,0,{seq:J,text:x});let K="";for(let _=0;_<k.length;_++)K+=k[_].text;return K},po=(R,J)=>{let x=ke(J),k=it.get(R.id),I=nb(k,x);R.rawContent=I;let N=Re.get(R.id),K=Pe=>{let dt=R.content??"";Pe.trim()!==""&&(dt.trim().length===0||Pe.startsWith(dt)||Pe.trimStart().startsWith(dt.trim()))&&(R.content=Pe)},_=()=>{if(N){let Pe=N.close?.();Pe instanceof Promise&&Pe.catch(()=>{})}Re.delete(R.id),it.delete(R.id),R.streaming=!1,f(R)};if(!N){K(x),_();return}let j=La(I);if(j!==null&&j.trim()!==""){K(j),_();return}let re=Pe=>{let dt=typeof Pe=="string"?Pe:Pe?.text??null;if(dt!==null&&dt.trim()!=="")return dt;let G=N.getExtractedText();return G!==null&&G.trim()!==""?G:x},tt;try{tt=N.processChunk(I)}catch{K(x),_();return}if(tt instanceof Promise){tt.then(Pe=>{K(re(Pe)),_()}).catch(()=>{K(x),_()});return}K(re(tt)),_()},Lt=null,mt=(R,J,x,k)=>{R.rawContent=J,Re.has(R.id)||Re.set(R.id,this.createStreamParser());let I=Re.get(R.id),N=J.trim().startsWith("{")||J.trim().startsWith("[");if(N&&it.set(R.id,J),I.__isPlainTextParser===!0){R.content=k!==void 0?J:R.content+x,it.delete(R.id),Re.delete(R.id),R.rawContent=void 0,f(R);return}let _=I.processChunk(J);if(_ instanceof Promise)_.then(j=>{let re=typeof j=="string"?j:j?.text??null;re!==null&&re.trim()!==""?(R.content=re,f(R)):!N&&!J.trim().startsWith("<")&&(R.content=k!==void 0?J:R.content+x,it.delete(R.id),Re.delete(R.id),R.rawContent=void 0,f(R))}).catch(()=>{R.content=k!==void 0?J:R.content+x,it.delete(R.id),Re.delete(R.id),R.rawContent=void 0,f(R)});else{let j=typeof _=="string"?_:_?.text??null;j!==null&&j.trim()!==""?(R.content=j,f(R)):!N&&!J.trim().startsWith("<")&&(R.content=k!==void 0?J:R.content+x,it.delete(R.id),Re.delete(R.id),R.rawContent=void 0,f(R))}},Se=(R,J)=>{let x=J??R.content;if(x==null||x===""){R.streaming=!1,f(R);return}let I=it.get(R.id)??ke(x);R.rawContent=I;let N=Re.get(R.id),K=null,_=!1;if(N&&(K=N.getExtractedText(),K===null&&(K=La(I)),K===null)){let j=N.processChunk(I);j instanceof Promise?(_=!0,j.then(re=>{let tt=typeof re=="string"?re:re?.text??null;tt!==null&&(R.content=tt,R.streaming=!1,Re.delete(R.id),it.delete(R.id),f(R))}).catch(()=>{})):K=typeof j=="string"?j:j?.text??null}if(!_){K!==null&&K.trim()!==""?R.content=K:it.has(R.id)||(R.content=ke(x));let j=Re.get(R.id);if(j){let re=j.close?.();re instanceof Promise&&re.catch(()=>{}),Re.delete(R.id)}it.delete(R.id),R.streaming=!1,f(R)}},me=(R,J,x)=>{let k=E.get(R);if(k)return k;let I={id:`nested-${J}-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:R,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:J}};return E.set(R,I),f(I),I},lt=[],Le,fe=new Map,ie=0,he="agent",xt=!1,U=null,te=null,We=new Map,Te=this.config.iterationDisplay??"separate";for(Le=()=>{for(let R=0;R<lt.length;R++){let J=lt[R].payloadType,x=lt[R].payload;if(!xt&&he!=="flow"&&typeof x.stepType=="string"&&(he="flow"),J==="reasoning_start"){let k=typeof x.id=="string"?x.id:null,I=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(k&&I){S.set(k,I),me(k,I,"reasoning");continue}let N=xe(x,!0)??`reason-${c()}`,K=Y(N);K.reasoning=K.reasoning??{id:N,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Ue(x.startedAt??x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(J==="reasoning_delta"){let k=typeof x.id=="string"?x.id:null;if(k&&S.has(k)&&E.has(k)){let _=E.get(k),j=x.reasoningText??x.text??x.delta??"";j&&x.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String(j)),f(_));continue}let I=xe(x,!1)??xe(x,!0)??`reason-${c()}`,N=Y(I);N.reasoning=N.reasoning??{id:I,status:"streaming",chunks:[]},N.reasoning.startedAt=N.reasoning.startedAt??Ue(x.startedAt??x.timestamp);let K=x.reasoningText??x.text??x.delta??"";if(K&&x.hidden!==!0){let _=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(_!==void 0){let j=Je(I,_,String(K));N.reasoning.chunks=[j]}else N.reasoning.chunks.push(String(K))}if(N.reasoning.status=x.done?"complete":"streaming",x.done){N.reasoning.completedAt=Ue(x.completedAt??x.timestamp);let _=N.reasoning.startedAt??Date.now();N.reasoning.durationMs=Math.max(0,(N.reasoning.completedAt??Date.now())-_)}N.streaming=N.reasoning.status!=="complete",f(N)}else if(J==="reasoning_complete"){let k=typeof x.id=="string"?x.id:null;if(k&&S.has(k)&&E.has(k)){let j=E.get(k);if(j.reasoning){let re=typeof x.text=="string"?x.text:"";re&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(re),j.reasoning.status="complete",j.streaming=!1,f(j)}S.delete(k),E.delete(k);continue}let I=xe(x,!1)??xe(x,!0)??`reason-${c()}`,N=typeof x.text=="string"?x.text:"";!H.get(I)&&(N||x.scope==="loop")&&Y(I);let K=H.get(I);if(K?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),N&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(N),K.reasoning.status="complete",K.reasoning.completedAt=Ue(x.completedAt??x.timestamp);let j=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-j),K.streaming=!1,f(K)}let _=z(x);_&&F.byStep.delete(_)}else if(J==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof x.iteration=="number"&&(ie=x.iteration);let k=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??Oe(x,!0)??`tool-${c()}`,I=x.toolName??x.name;if(He(I)){ee.add(k);continue}de(le(x),k);let N=Ke(k),K=N.toolCall??{id:k,status:"pending"};K.name=I??K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=K.startedAt??Ue(x.startedAt??x.timestamp),K.completedAt=void 0,K.durationMs=void 0,N.toolCall=K,N.streaming=!0,x.executionId&&(N.agentMetadata={executionId:x.executionId,iteration:x.iteration}),f(N)}else if(J==="tool_output_delta"){let k=Oe(x,!1)??Oe(x,!0)??`tool-${c()}`;if(ee.has(k))continue;let I=Ke(k),N=I.toolCall??{id:k,status:"running"};N.startedAt=N.startedAt??Ue(x.startedAt??x.timestamp);let K=x.text??x.delta??x.message??"";K&&(N.chunks=N.chunks??[],N.chunks.push(String(K))),N.status="running",I.toolCall=N,I.streaming=!0;let _=x.agentContext;(_||x.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(I)}else if(J==="tool_complete"){let k=Oe(x,!1)??Oe(x,!0)??`tool-${c()}`;if(ee.has(k)){ee.delete(k);continue}let I=Ke(k),N=I.toolCall??{id:k,status:"running"};N.status="complete",x.result!==void 0&&(N.result=x.result),typeof x.duration=="number"&&(N.duration=x.duration),N.completedAt=Ue(x.completedAt??x.timestamp);let K=x.duration??x.executionTime;if(typeof K=="number")N.durationMs=K;else{let re=N.startedAt??Date.now();N.durationMs=Math.max(0,(N.completedAt??Date.now())-re)}I.toolCall=N,I.streaming=!1;let _=x.agentContext;(_||x.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(I);let j=le(x);j&&q.byCall.delete(j)}else if(J==="await"&&x.toolName){let k=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,I=k??x.toolId??`local-${c()}`,N=Ke(I),K=x.toolName,_=x.origin==="webmcp"&&!lr(K)?`webmcp:${K}`:K,j=lr(_),re=N.toolCall??{id:I,status:"pending"};re.name=_,re.args=x.parameters,re.status=j?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??Ue(x.startedAt??x.timestamp??x.awaitedAt),j?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,N.toolCall=re,N.streaming=!1,N.agentMetadata={...N.agentMetadata,executionId:x.executionId??N.agentMetadata?.executionId,awaitingLocalTool:!0,...k?{webMcpToolCallId:k}:{}},f(N)}else if(J==="text_start"){let k=typeof x.id=="string"?x.id:null,I=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(k&&I){S.set(k,I);continue}let N=h;N&&(he==="flow"?(Se(N),Lt=N):(N.streaming=!1,f(N)),h=null),A=typeof x.id=="string"?x.id:A,T=""}else if(J==="text_delta"){let k=typeof x.id=="string"?x.id:null,I=k?S.get(k):void 0;if(k&&I){let K=typeof x.delta=="string"?x.delta:"",_=(B.get(k)??"")+K;if(B.set(k,_),_.trim()==="")continue;let j=me(k,I);j.agentMetadata={...j.agentMetadata,executionId:x.executionId,parentToolId:I},mt(j,_,K,void 0);continue}if(A=typeof x.id=="string"?x.id:A,he==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(T+=K,T.trim()==="")continue;let _=De();_.agentMetadata={executionId:x.executionId,iteration:x.iteration},mt(_,T,K,void 0),C=_;continue}let N=De();N.content+=x.delta??"",N.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:U??void 0,agentName:te?.agentName},C=N,f(N)}else if(J==="text_complete"){let k=typeof x.id=="string"?x.id:null;if(k&&S.has(k)){let N=E.get(k);N&&Se(N),S.delete(k),B.delete(k),E.delete(k);continue}let I=h;I&&(he==="flow"?(Se(I),Lt=I):((I.content??"")===""&&typeof x.text=="string"&&(I.content=x.text),I.streaming=!1,f(I)),h=null),A=null,T=""}else if(J==="step_complete"){let k=x.stepType,I=x.executionType;if(k==="tool"||I==="context")continue;if(x.success===!1){let N=x.error,K=typeof N=="string"&&N!==""?N:N!=null&&typeof N=="object"&&Reflect.has(N,"message")?String(N.message??"Step failed"):"Step failed";o({type:"error",error:new Error(K)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),o({type:"status",status:"idle"});continue}{let N=Lt;Lt=null;let K=x.stopReason,_=x.result?.response;if(N)K&&(N.stopReason=K),_!=null?po(N,_):N.streaming!==!1&&(Re.delete(N.id),it.delete(N.id),N.streaming=!1,f(N));else{let j=_!=null&&_!=="";if(j||K){let re=De();K&&(re.stopReason=K),j?Se(re,_):(re.streaming=!1,f(re))}}continue}}else if(J==="execution_start")he=x.kind==="flow"?"flow":"agent",xt=!0,he==="agent"&&(te={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:Ue(x.startedAt)});else if(J==="turn_start"){let k=typeof x.iteration=="number"?x.iteration:ie;if(k!==ie){if(te&&(te.currentIteration=k),Te==="separate"&&k>1){let I=h;I&&(I.streaming=!1,f(I),We.set(k-1,I),h=null)}ie=k}U=typeof x.id=="string"?x.id:null,C=null}else if(J==="tool_input_delta"){let k=x.toolCallId??q.lastId;if(k){let I=w.get(k);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(x.delta??""),f(I))}}else{if(J==="tool_input_complete")continue;if(J==="turn_complete"){let k=x.stopReason,I=h??C;if(k&&I!==null){let N=x.id;(!N||I.agentMetadata?.turnId===N)&&(I.stopReason=k,f(I))}U===x.id&&(U=null)}else if(J==="media_start"){let k=String(x.id);fe.set(k,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(J==="media_delta"){let k=fe.get(String(x.id));k&&typeof x.delta=="string"&&k.parts.push(x.delta)}else if(J==="media_complete"){let k=String(x.id),I=fe.get(k);fe.delete(k);let N=(typeof x.mediaType=="string"?x.mediaType:void 0)??I?.mediaType??"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,_=typeof x.url=="string"?x.url:I&&I.parts.length>0?I.parts.join(""):void 0,j=null;if(K)j={type:"media",data:K,mediaType:N};else if(_){let dt=N.toLowerCase();j={type:dt==="image"||dt.startsWith("image/")?"image-url":"file-url",url:_,mediaType:N}}let re=x.toolCallId??I?.toolCallId,tt=j?[j]:[],Pe=[];for(let dt of tt){if(!dt||typeof dt!="object")continue;let G=dt,qe=typeof G.type=="string"?G.type:void 0,ve=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",Ie=null,Me="";if(qe==="media"){let Qe=typeof G.data=="string"?G.data:void 0;if(!Qe)continue;Me=ve.length>0?ve:"application/octet-stream",Ie=`data:${Me};base64,${Qe}`}else if(qe==="image-url"){let Qe=typeof G.url=="string"?G.url:void 0;if(!Qe)continue;Me=ve,Ie=Qe}else if(qe==="file-url"){let Qe=typeof G.url=="string"?G.url:void 0;if(!Qe)continue;Me=ve,Ie=Qe}else continue;if(Ie)if(qe==="image-url"||Me.startsWith("image/"))Pe.push({type:"image",image:Ie,...Me.includes("/")?{mimeType:Me}:{}});else if(Me.startsWith("audio/"))Pe.push({type:"audio",audio:Ie,mimeType:Me});else if(Me.startsWith("video/"))Pe.push({type:"video",video:Ie,mimeType:Me});else{let Qe=Me||"application/octet-stream";Pe.push({type:"file",data:Ie,mimeType:Qe,filename:ob(Qe)})}}if(Pe.length>0){let dt=c(),G=re,ve={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${dt}`:String(dt)}`,role:"assistant",content:"",contentParts:Pe,createdAt:new Date().toISOString(),streaming:!1,sequence:dt,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:ie}};f(ve);let Ie=h;Ie&&(Ie.streaming=!1,f(Ie)),h=null,M.current=null}}else if(J==="execution_complete"){let k=x.kind??he;k==="agent"&&te&&(te.status=x.success?"complete":"error",te.completedAt=Ue(x.completedAt),te.stopReason=x.stopReason);let I=h;I&&(k==="flow"&&I.streaming!==!1?Se(I):(I.streaming=!1,f(I)),h=null),A=null,T="",Lt=null,o({type:"status",status:"idle",terminal:!0})}else if(J==="execution_error"){let k=typeof x.error=="string"?x.error:x.error?.message??"Execution error";o({type:"error",error:new Error(k)})}else if(J!=="ping"){if(J==="approval_start"){let k=x.approvalId??`approval-${c()}`,I={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:"pending",agentId:te?.agentId??"virtual",executionId:x.executionId??te?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(I)}else if(J==="step_await"&&x.awaitReason==="approval_required"){let k=x.approvalId??`approval-${c()}`,I={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:"pending",agentId:te?.agentId??"virtual",executionId:x.executionId??te?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(I)}else if(J==="approval_complete"){let k=x.approvalId;if(k){let N={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:x.decision??"approved",agentId:te?.agentId??"virtual",executionId:x.executionId??te?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};f(N)}}else if(J==="artifact_start"||J==="artifact_delta"||J==="artifact_update"||J==="artifact_complete"){if(J==="artifact_start"){let k=x.artifactType,I=String(x.id),N=typeof x.title=="string"?x.title:void 0,K=x.file,_;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(_={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),o({type:"artifact_start",id:I,artifactType:k,title:N,component:typeof x.component=="string"?x.component:void 0,..._?{file:_}:{}});let j=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(be.set(I,{markdown:"",title:N,file:_,...j?{props:j}:{}}),!Ae.has(I)){Ae.add(I);let re=jr(this.config.features?.artifacts,k),tt=typeof x.component=="string"?x.component:void 0,Pe={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Bs(re,{artifactId:I,title:N,artifactType:k,status:"streaming",..._?{file:_}:{},...tt?{component:tt}:{}})};Ce.set(I,Pe),f(Pe)}}else if(J==="artifact_delta"){let k=String(x.id),I=typeof x.delta=="string"?x.delta:String(x.delta??"");o({type:"artifact_delta",id:k,artDelta:I});let N=be.get(k);N&&(N.markdown+=I)}else if(J==="artifact_update"){let k=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};o({type:"artifact_update",id:String(x.id),props:k,component:typeof x.component=="string"?x.component:void 0});let I=be.get(String(x.id));I&&(I.props={...I.props??{},...k})}else if(J==="artifact_complete"){let k=String(x.id);o({type:"artifact_complete",id:k});let I=Ce.get(k);if(I){I.streaming=!1;try{let N=JSON.parse(I.rawContent??"{}");if(N.props){N.props.status="complete";let K=be.get(k);K?.markdown&&(N.props.markdown=K.markdown),K?.file&&(N.props.file=K.file),N.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(N.props.componentProps=K.props)}I.rawContent=JSON.stringify(N)}catch{}be.delete(k),f(I),Ce.delete(k)}}}else if(J==="transcript_insert"){let k=x.message;if(!k||typeof k!="object")continue;let I=String(k.id??`msg-${c()}`),N=k.role,_={id:I,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof k.content=="string"?k.content:"",rawContent:typeof k.rawContent=="string"?k.rawContent:void 0,createdAt:typeof k.createdAt=="string"?k.createdAt:new Date().toISOString(),streaming:k.streaming===!0,...typeof k.variant=="string"?{variant:k.variant}:{},sequence:c()};if(f(_),_.rawContent)try{let re=JSON.parse(_.rawContent)?.props?.artifactId;typeof re=="string"&&Ae.add(re)}catch{}h=null,M.current=null,Re.delete(I),it.delete(I)}else if(J==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let k=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";o({type:"error",error:new Error(k)});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),o({type:"status",status:"idle"})}}else if(J==="step_error"||J==="dispatch_error"||J==="flow_error"){let k=null;if(x.error instanceof Error)k=x.error;else if(J==="dispatch_error"){let I=x.message??x.error;I!=null&&I!==""&&(k=new Error(String(I)))}else{let I=x.error;typeof I=="string"&&I!==""?k=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(k=new Error(String(I.message??I)))}if(k){o({type:"error",error:k});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),o({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:R,value:J}=await a.read();if(R)break;l+=s.decode(J,{stream:!0});let x=l.split(`
|
|
13
13
|
|
|
14
|
-
`);
|
|
15
|
-
`),et="message",Qe="",gt=null;for(let ae of Ie)ae.startsWith("event:")?et=ae.replace("event:","").trim():ae.startsWith("data:")?Qe+=ae.replace("data:","").trim():ae.startsWith("id:")&&(gt=ae.slice(3).trim());let pe=()=>{gt!==null&>!==""&&r({type:"cursor",id:gt})};if(!Qe){pe();continue}let N;try{N=JSON.parse(Qe)}catch(ae){r({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let ye=et!=="message"?et:(So=N.type)!=null?So:"message";if((Ve=this.onSSEEvent)==null||Ve.call(this,ye,N),this.parseSSEEvent){k.current=h;let ae=await this.handleCustomSSEEvent(N,r,k,f,p,E);if(k.current&&k.current!==h&&(h=k.current),ae){pe();continue}}st.push({payloadType:ye,payload:N}),je(),pe()}}je()}};function uh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Da(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Pn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var yi="[Image]";function fh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function mh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function gh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function hh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function As(e){return{type:"text",text:e}}function xh(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function yh(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function bh(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var vh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zb=["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"],en=[...vh,...zb];function $b(e){return vh.includes(e)||e.startsWith("image/")}function bi(e){return $b(e.type)}async function wh(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;bi(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Ch(e,t=en,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function jb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Sh(e,t){let r=jb(t).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]||r||"FILE"}var vi=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Ah=16e3,Gb=24e3,Kb=4096,Xb=1380533830;function Qb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Xb?new Uint8Array(e,44):new Uint8Array(e)}function Jb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ms=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Ah,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){d.getTracks().forEach(b=>b.stop());return}this.mediaStream=d;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Ah});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new vi(Gb);if(n!==this.callGeneration){g.destroy(),d.getTracks().forEach(b=>b.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Jb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,h=new WebSocket(f,["runtype.bearer",r]);h.binaryType="arraybuffer",this.ws=h,h.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,d,h,n))},h.onmessage=b=>this.handleMessage(b,n),h.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},h.onclose=b=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(b.code!==1e3){let k=b.code?` (code ${b.code})`:"";this.emitError(new Error(`Voice connection closed${k}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(d){throw this.cleanup(),this.emitError(d),this.emitStatus("error"),d}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(Kb,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let p=0;p<c.length;p++){let u=Math.max(-1,Math.min(1,c[p]));d[p]=u<0?u*32768:u*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=Qb(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var ia=class{constructor(t={}){this.config=t;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(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Rn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ms(e.runtype);case"browser":if(!ia.isSupported())throw new Error("Browser speech recognition not supported");return new ia(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function wi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Rn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Rn({type:"runtype",runtype:e.runtype});if(ia.isSupported())return Rn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ts(e){try{return wi(e),!0}catch{return!1}}function Fa(e){var r;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 n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var In=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Fa(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var d,p;let c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var la=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function Xl(e){if(!e)return"";let t=Yb(e);return Mh(t!==null?t:e)}function Yb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Mh(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
14
|
+
`);l=x.pop()??"";for(let k of x){let I=k.split(`
|
|
15
|
+
`),N="message",K="",_=null;for(let Pe of I)Pe.startsWith("event:")?N=Pe.replace("event:","").trim():Pe.startsWith("data:")?K+=Pe.replace("data:","").trim():Pe.startsWith("id:")&&(_=Pe.slice(3).trim());let j=()=>{_!==null&&_!==""&&o({type:"cursor",id:_})};if(!K){j();continue}let re;try{re=JSON.parse(K)}catch(Pe){o({type:"error",error:Pe instanceof Error?Pe:new Error("Failed to parse chat stream payload")});continue}let tt=N!=="message"?N:re.type??"message";if(this.onSSEEvent?.(tt,re),this.parseSSEEvent){M.current=h;let Pe=await this.handleCustomSSEEvent(re,o,M,f,c,L);if(M.current&&M.current!==h&&(h=M.current),Pe){j();continue}}lt.push({payloadType:tt,payload:re}),Le(),j()}}Le()}};function Qf(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Pn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function mr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Qs="[Image]";function Yf(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Zf(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function em(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function tm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Pa(e){return{type:"text",text:e}}function om(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function rm(e){return new Promise((t,o)=>{let r=new FileReader;r.onload=()=>{let n=r.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},r.onerror=()=>o(new Error("Failed to read file")),r.readAsDataURL(e)})}function nm(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var am=["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"],jo=[...am,...ab];function sb(e){return am.includes(e)||e.startsWith("image/")}function Ys(e){return sb(e.type)}async function sm(e){return new Promise((t,o)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Ys(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>o(new Error("Failed to read file")),r.readAsDataURL(e)})}function im(e,t=jo,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function ib(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function lm(e,t){let o=ib(t).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]||o||"FILE"}var Zs=class{constructor(t=24e3,o={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let r=Math.max(0,o.prebufferMs??0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let o=typeof window<"u"?window:void 0;if(!o)throw new Error("AudioPlaybackManager requires a browser environment");let r=o.AudioContext||o.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let o=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),o=n,this.remainder=null}if(o.length%2!==0&&(this.remainder=new Uint8Array([o[o.length-1]]),o=o.subarray(0,o.length-1)),o.length===0)return;let r=this.pcmToFloat32(o);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let o of t)this.scheduleSamples(o)}scheduleSamples(t){if(t.length===0)return;let o=this.ensureContext(),r=o.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let n=o.createBufferSource();n.buffer=r,n.connect(o.destination);let a=o.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let o of t)o()}}pcmToFloat32(t){let o=Math.floor(t.length/2),r=new Float32Array(o),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<o;a++){let s=n.getInt16(a*2,!0);r[a]=s/32768}return r}};var dm=16e3,lb=24e3,db=4096,cb=1380533830;function pb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===cb?new Uint8Array(e,44):new Uint8Array(e)}function ub(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ra=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,o=this.config?.clientToken,r=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!o)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:dm,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){a.getTracks().forEach(u=>u.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:dm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Zs(lb);if(n!==this.callGeneration){p.destroy(),a.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${ub(r)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",o]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,a,c,n))},c.onmessage=u=>this.handleMessage(u,n),c.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(u.code!==1e3){let g=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(a){throw this.cleanup(),this.emitError(a),this.emitStatus("error"),a}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,o,r,n){let a=t.createMediaStreamSource(o);this.sourceNode=a;let s=t.createScriptProcessor(db,1,1);this.processor=s,s.onaudioprocess=l=>{if(n!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}r.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,o){if(o!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,o);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",r.text??"",!1);break;case"transcript_final":{let n=r.role==="assistant"?"assistant":"user";this.emitStatus(n==="user"?"processing":"speaking"),this.emitTranscript(n,r.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,o){if(o!==this.callGeneration||!this.playback)return;let r=pb(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(o=>o(t))}emitError(t){this.errorCallbacks.forEach(o=>o(t))}emitTranscript(t,o,r){this.transcriptCallbacks.forEach(n=>n(t,o,r))}emitMetrics(t){this.metricsCallbacks.forEach(o=>o(t))}};var Qr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{let r=Array.from(o.results).map(a=>a[0]).map(a=>a.transcript).join(""),n=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({text:r,confidence:n?.8:.5,provider:"browser"})),n&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(r=>r(new Error(o.error))),this.statusCallbacks.forEach(r=>r("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(t){throw this.errorCallbacks.forEach(o=>o(t)),this.statusCallbacks.forEach(o=>o("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function gr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ra(e.runtype);case"browser":if(!Qr.isSupported())throw new Error("Browser speech recognition not supported");return new Qr(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let o=typeof t=="function"?t():t;if(!o||typeof o.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return o}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ei(e){if(e?.type==="custom"&&e.custom)return gr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return gr({type:"runtype",runtype:e.runtype});if(Qr.isSupported())return gr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ia(e){try{return ei(e),!0}catch{return!1}}function Rn(e){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 r=e.find(n=>n.name===o);if(r)return r}return e.find(o=>o.lang.startsWith("en"))??e[0]}var hr=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,o){if(!e.isSupported()){o.onError?.(new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let n=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(n.voice=s)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Rn(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>o.onEnd?.(),n.onerror=s=>{let l=s.error;l==="canceled"||l==="interrupted"?o.onEnd?.():o.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{r.speak(n),o.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Yr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,o){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,o)}async play(t,o){let r=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let n=await this.resolveEngine();if(r!==this.generation)return;if(!n){this.set(null,"idle");return}this.engine=n}this.engine.speak(o,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,o){this.activeId=o==="idle"?null:t,this.state=o;for(let r of this.listeners)r(this.activeId,this.state)}};function td(e){if(!e)return"";let t=fb(e);return cm(t!==null?t:e)}function fb(e){let t=e.trim(),o=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(o&&(t=o[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function cm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
16
16
|
`),t=t.replace(/\n{2,}/g,`
|
|
17
|
-
`),t.trim()}var
|
|
17
|
+
`),t.trim()}var od=null,pm=e=>{od=e},rd=()=>od?od():import("./runtype-tts-entry");var hb=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function yb(e,t){return hb.some(o=>e[o]!==t[o])}function nd(e,t){let o=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(o);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return o.message?`${r}
|
|
18
18
|
|
|
19
|
-
_Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]}),Lh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ph=e=>An(e)||e===vo,Na=class{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new la(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(An(g.name)||g.name===vo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new sa(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(d=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId)!=null?d:this.config.agentId;!r||!o||!this.config.clientToken||Jl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ts((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i,c;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=In.isSupported()?new In({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(o=t.host)!=null?o:this.config.apiUrl,p=(c=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId)!=null?c:this.config.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(d&&p&&u)return Jl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:h})=>{let b=new f({host:d,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new h(b,r,{onFallback:k=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${k.message}`)}):b});if(g&&r)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Rn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=p.id}if(d){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=p.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,d,p,u,g,f;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(a=(n=(o=t.runtype)==null?void 0:o.agentId)!=null?n:this.config.agentId)!=null?a:"",clientToken:(i=(s=t.runtype)==null?void 0:s.clientToken)!=null?i:this.config.clientToken,host:(d=(c=t.runtype)==null?void 0:c.host)!=null?d:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!rv(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new sa(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:d=!1,voiceProcessing:p,rawContent:u}=t,f={id:s!=null?s:r==="user"?Da():r==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:d,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,b={id:c!=null?c:n==="user"?Da():n==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};r.push(b)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,p,u,g,f;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let n=Da(),a=Pn();this.activeAssistantMessageId=null;let s={id:n,role:"user",content:o||yi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(h){if(this.status==="resuming"||this.reconnecting)return;let b=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!b){let k=Yl(h,this.config.errorMessage);if(k){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:k,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(h instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,h):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(h))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort(),this.teardownReconnect();let t=Pn();this.activeAssistantMessageId=null,this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let p=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!p){let u=Yl(d,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(d))))}}async connectStream(t,r){var a,s,i;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(a=this.abortController)==null||a.abort(),r!=null&&r.preserveAssistantId&&r.assistantMessageId&&(this.activeAssistantMessageId=r.assistantMessageId);let o=r!=null&&r.preserveAssistantId?r.assistantMessageId:void 0,n=!1;for(let c of this.messages)c.streaming&&c.id!==o&&(c.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId,r==null?void 0:r.seedContent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(s=this.callbacks).onError)==null||i.call(s,c instanceof Error?c:new Error(String(c)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,u,g,f,h;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(b=>b.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,d=c&&typeof c=="object"?c.onDecision:void 0;try{let b;if(d?b=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):b=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),b){let k=null;if(b instanceof Response){if(!b.ok){let E=await b.json().catch(()=>null);throw new Error((g=E==null?void 0:E.error)!=null?g:`Approval request failed: ${b.status}`)}k=b.body}else b instanceof ReadableStream&&(k=b);k?await this.connectStream(k,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(b){let k=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(h=(f=this.callbacks).onError)==null||h.call(f,b instanceof Error?b:new Error(String(b)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,u,g,f,h,b,k,E,A,T,y,w;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(u=t.agentMetadata)==null?void 0:u.executionId,a=(g=t.toolCall)==null?void 0:g.name;if(!n||!a){(h=(f=this.callbacks).onError)==null||h.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let v=(b=t.toolCall)==null?void 0:b.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let H=typeof((k=M[0])==null?void 0:k.question)=="string"?M[0].question:"";H&&(s={[H]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(A=t.toolCall)==null?void 0:A.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let v=typeof r=="string"?r:Object.entries(r).map(([M,H])=>`${M}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};d.forEach((M,H)=>{let I=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!I)return;let P=v[I],B=Array.isArray(P)?P.join(", "):typeof P=="string"?P:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:B||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:r});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((T=M==null?void 0:M.error)!=null?T:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(w=(y=this.callbacks).onError)==null||w.call(y,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==vo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,d,p,u;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async g=>{var w,v,M,H,I,P,B;let f=(w=g.toolCall)==null?void 0:w.name,h=(v=g.toolCall)==null?void 0:v.id;if(!f||!h)return null;let b=`${t}:${h}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(b),o.push(b);let k=this.markWebMcpToolRunning(g),E=(H=(M=g.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?H:f;if(f===vo)return{dedupeKey:b,resumeKey:E,output:Vl(),toolMessage:g,startedAt:k,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let T=this.client.executeWebMcpToolCall(f,(I=g.toolCall)==null?void 0:I.args,A.signal),y;if(!T)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await T}catch(O){let Q=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Q||(B=(P=this.callbacks).onError)==null||B.call(P,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(g,Es(Q?"Aborted by cancel()":Lh(O)),k),this.webMcpInflightKeys.delete(b),null}return A.signal.aborted?(this.markWebMcpToolComplete(g,Es("Aborted by cancel()"),k),this.webMcpInflightKeys.delete(b),null):{dedupeKey:b,resumeKey:E,output:y,toolMessage:g,startedAt:k,completedAt:Date.now()}})),i=[];try{if(i=s.filter(h=>h!==null),i.length===0)return;let g={};for(let h of i)g[h.resumeKey]=h.output;let f=await this.client.resumeFlow(t,g,{signal:a.signal});if(!f.ok){let h=await f.json().catch(()=>null);throw new Error((c=h==null?void 0:h.error)!=null?c:`Resume failed: ${f.status}`)}for(let h of i)this.webMcpResolvedKeys.add(h.dedupeKey),this.markWebMcpToolComplete(h.toolMessage,h.output,h.startedAt,h.completedAt,((d=h.toolMessage.toolCall)==null?void 0:d.name)===vo?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let h of i)this.markWebMcpToolComplete(h.toolMessage,Es("Aborted by cancel()"),h.startedAt)}finally{for(let g of o)this.webMcpInflightKeys.delete(g);for(let g of n)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var h,b,k,E,A,T,y,w,v,M,H,I;let r=(h=t.agentMetadata)==null?void 0:h.executionId,o=(b=t.toolCall)==null?void 0:b.name,n=(k=t.toolCall)==null?void 0:k.id;if(!r){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let P=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(P)||this.webMcpResolvedKeys.has(P))return;this.webMcpInflightKeys.add(P);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(P)}catch(B){(y=(T=this.callbacks).onError)==null||y.call(T,B instanceof Error?B:new Error(String(B)))}finally{this.webMcpInflightKeys.delete(P)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let d=o===vo,p=(w=t.toolCall)==null?void 0:w.args,u=d?null:this.client.executeWebMcpToolCall(o,p,c),g="execute",f=s;try{let P;if(d?P=Vl():u?P=await u:P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Es("Aborted by cancel()"),s);return}let B=(M=(v=t.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?M:o;g="resume",await this.resumeWithToolOutput(r,B,P,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,P,s,f,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(P){let B=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));(g==="execute"||B||c.aborted)&&this.markWebMcpToolComplete(t,Es(B||c.aborted?"Aborted by cancel()":Lh(P)),s),B||(I=(H=this.callbacks).onError)==null||I.call(H,P instanceof Error?P:new Error(String(P)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}trackCursor(t){var n,a;let r=(n=this.agentExecution)==null?void 0:n.executionId;if(!r||!this.activeAssistantMessageId||((a=this.agentExecution)==null?void 0:a.status)!=="running")return;let o=this.resumable===null;this.resumable={executionId:r,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var r,o,n;return((r=t.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&((o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((n=t.approval)==null?void 0:n.status)==="pending"})}beginReconnect(){var t,r;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(r=(t=this.callbacks).onReconnect)==null||r.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(o=>{this.reconnecting&&this.resumable&&o.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(kh(),Eh)).then(({createReconnectController:t})=>{let r=t(this.buildReconnectHost());return this.reconnectController=r,r})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:r=>t.setStatus(r),setStreaming:r=>t.setStreaming(r),setReconnecting:r=>{t.reconnecting=r},setAbortController:r=>{t.abortController=r},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(r,o,n)=>t.connectStream(r,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:r=>t.appendMessage(r),nextSequence:()=>t.nextSequence(),emitReconnect:r=>{var o,n;return(n=(o=t.callbacks).onReconnect)==null?void 0:n.call(o,r)},buildErrorContent:r=>Yl(new Error(r),t.config.errorMessage),onError:r=>{var o,n;return(n=(o=t.callbacks).onError)==null?void 0:n.call(o,r)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let r=this.reopenTrailingAssistant();r||(r=Pn(),this.appendMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=r,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:r,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(r.role==="assistant"&&!r.variant)return r.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),r.id;if(r.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var r,o;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((o=(r=this.config).onExecutionState)==null||o.call(r,null))}notifyExecutionState(t){let r=this.config.onExecutionState;if(r){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),r(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var o,n;this.executionStateTimer=null,(n=(o=this.config).onExecutionState)==null||n.call(o,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=Xl(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Fa(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=Xl(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,u,g,f,h,b,k,E,A,T,y,w,v,M,H;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=n.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(g=s.agentMetadata)!=null?g:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let I=n.approval,P=r.approval;s.approval={...I,...P,executionId:P.executionId||I.executionId,toolName:P.toolName||I.toolName,description:P.description||I.description,toolType:(f=P.toolType)!=null?f:I.toolType,reason:(h=P.reason)!=null?h:I.reason,parameters:(b=P.parameters)!=null?b:I.parameters}}let i=(k=r.toolCall)==null?void 0:k.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(A=r.toolCall)==null?void 0:A.id;if(i&&Ph(i)&&c&&d&&((T=r.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let I=`${c}:${d}`,P=this.webMcpInflightKeys.has(I),B=this.webMcpResolvedKeys.has(I),O=(y=n.toolCall)==null?void 0:y.name,Q=((w=n.agentMetadata)==null?void 0:w.executionId)===c&&((v=n.toolCall)==null?void 0:v.id)===d&&O!==void 0&&Ph(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(P||B||Q)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,o)=>{var c,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var Zl=[["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 ed=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var td=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var rd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var od=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var nd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var ad=[["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 sd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var id=[["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 ld=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var dd=[["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 cd=[["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 pd=[["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 ud=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var fd=[["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 md=[["path",{d:"M20 6 9 17l-5-5"}]];var gd=[["path",{d:"m6 9 6 6 6-6"}]];var hd=[["path",{d:"m15 18-6-6 6-6"}]];var xd=[["path",{d:"m9 18 6-6-6-6"}]];var yd=[["path",{d:"m18 15-6-6-6 6"}]];var Ci=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Si=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var bd=[["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 vd=[["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 wd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Cd=[["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 Sd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Ad=[["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 Ai=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Mi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Td=[["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 Ed=[["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 kd=[["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 Ld=[["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 Pd=[["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 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 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Id=[["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 Hd=[["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 Wd=[["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 Bd=[["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 Dd=[["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 Fd=[["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 Ti=[["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 Nd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Od=[["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 _d=[["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 Ud=[["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 qd=[["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 Vd=[["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 Ei=[["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 zd=[["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 $d=[["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 Gd=[["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 Kd=[["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 ki=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Xd=[["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 Qd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Jd=[["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 Yd=[["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 Zd=[["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 ec=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var tc=[["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 rc=[["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 oc=[["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 nc=[["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 ac=[["path",{d:"M5 12h14"}]];var sc=[["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 ic=[["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 lc=[["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 dc=[["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 cc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var pc=[["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 uc=[["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 fc=[["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 mc=[["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 gc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var hc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var xc=[["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 yc=[["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 bc=[["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 vc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var wc=[["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 Cc=[["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 Sc=[["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 Ac=[["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 Li=[["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 Tc=[["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 Ec=[["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 kc=[["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 Lc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Pi=[["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 Pc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Rc=[["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 Ic=[["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 Hc=[["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 Wc=[["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 Bc=[["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"}],["path",{d:"M17 14V2"}]];var Dc=[["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"}],["path",{d:"M7 10v12"}]];var Fc=[["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 Nc=[["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 Oc=[["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 Ri=[["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 _c=[["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 Uc=[["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 qc=[["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 Vc=[["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 zc=[["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 $c=[["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 Gc=[["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 ov={activity:Zl,"arrow-down":ed,"arrow-up":nd,"arrow-up-right":od,bot:dd,"chevron-down":gd,"chevron-up":yd,"chevron-right":xd,"chevron-left":hd,check:md,clipboard:vd,"clipboard-copy":bd,copy:Cd,file:Id,"file-code":Ld,"file-spreadsheet":Pd,"file-text":Rd,"image-plus":zd,loader:Xd,"loader-circle":ki,mic:oc,paperclip:dc,"refresh-cw":xc,search:vc,send:wc,"shield-alert":Ac,"shield-check":Mc,"shield-x":Li,square:Pc,"thumbs-down":Bc,"thumbs-up":Dc,upload:Uc,"volume-2":Vc,x:jc,user:qc,mail:Jd,phone:fc,calendar:ud,clock:wd,building:cd,"map-pin":Yd,lock:Qd,key:Gd,"credit-card":Sd,"at-sign":ad,hash:_d,globe:Od,link:Kd,"circle-check":Ci,"circle-x":Si,"triangle-alert":Ri,info:jd,ban:sd,shield:Tc,"arrow-left":td,"arrow-right":rd,"external-link":Ed,ellipsis:Mi,"ellipsis-vertical":Ai,menu:ec,house:Ei,plus:gc,minus:ac,pencil:pc,trash:Oc,"trash-2":Nc,save:bc,download:Md,share:Sc,funnel:Ti,settings:Cc,"rotate-cw":yc,maximize:Zd,minimize:nc,"shopping-cart":kc,"shopping-bag":Ec,package:lc,truck:_c,tag:Wc,gift:Nd,receipt:hc,wallet:$c,store:Ic,"dollar-sign":Ad,percent:uc,play:mc,pause:cc,"volume-x":zc,camera:fd,image:$d,film:Wd,headphones:Ud,"message-circle":tc,"message-square":rc,bell:id,heart:qd,star:Rc,eye:kd,"eye-off":Td,bookmark:ld,"calendar-days":pd,history:Vd,timer:Fc,folder:Fd,"folder-open":Dd,files:Hd,sparkles:Pi,zap:Gc,sun:Hc,moon:ic,flag:Bd,monitor:sc,smartphone:Lc},he=(e,t=24,r="currentColor",o=2)=>{let n=ov[e];return n?nv(n,t,r,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function nv(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.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 c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,p])=>{d!=="stroke"&&c.setAttribute(d,String(p))}),n.appendChild(c)}),n}var Ii={allowedTypes:en,maxFileSize:10*1024*1024,maxFiles:4};function av(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sv(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 da=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ii.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ii.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ii.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ii.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let p=Ch(d,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,u);continue}try{let u=await wh(d),g=bi(d)?URL.createObjectURL(d):null,f={id:av(),file:d,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=bi(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=S("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=S("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=sv(t.file.type),c=he(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=S("span");d.textContent=Sh(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let n=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=he("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var Rh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ks(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];Rh(a)&&Rh(n)?r[o]=ks(a,n):r[o]=n}return r}var Gr="min(440px, calc(100vw - 24px))",Hi="440px",iv={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:Gr,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)"},Ht={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:iv,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},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 Ih(e,t){if(!(!e&&!t))return e?t?ks(e,t):e:t}function Wi(e){var t,r,o,n,a,s,i,c,d,p,u,g,f,h,b,k,E,A,T,y,w;return e?{...Ht,...e,theme:Ih(Ht.theme,e.theme),darkTheme:Ih(Ht.darkTheme,e.darkTheme),launcher:{...Ht.launcher,...e.launcher,dock:{...(t=Ht.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Ht.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Ht.copy,...e.copy},sendButton:{...Ht.sendButton,...e.sendButton},statusIndicator:{...Ht.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,se,ge,Te,qe,j,ee,Ee,te,le;let v=(oe=Ht.features)==null?void 0:oe.artifacts,M=(se=e.features)==null?void 0:se.artifacts,H=(ge=Ht.features)==null?void 0:ge.scrollToBottom,I=(Te=e.features)==null?void 0:Te.scrollToBottom,P=(qe=Ht.features)==null?void 0:qe.scrollBehavior,B=(j=e.features)==null?void 0:j.scrollBehavior,O=(ee=Ht.features)==null?void 0:ee.streamAnimation,Q=(Ee=e.features)==null?void 0:Ee.streamAnimation,me=(te=Ht.features)==null?void 0:te.askUserQuestion,ue=(le=e.features)==null?void 0:le.askUserQuestion,Z=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},Le=H===void 0&&I===void 0?void 0:{...H,...I},We=P===void 0&&B===void 0?void 0:{...P,...B},ie=O===void 0&&Q===void 0?void 0:{...O,...Q},Me=me===void 0&&ue===void 0?void 0:{...me,...ue,styles:{...me==null?void 0:me.styles,...ue==null?void 0:ue.styles}};return{...Ht.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...We!==void 0?{scrollBehavior:We}:{},...Z!==void 0?{artifacts:Z}:{},...ie!==void 0?{streamAnimation:ie}:{},...Me!==void 0?{askUserQuestion:Me}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ht.layout,...e.layout,header:{...(s=Ht.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=Ht.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(u=(p=Ht.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(b=(h=Ht.layout)==null?void 0:h.messages)==null?void 0:b.timestamp,...(E=(k=e.layout)==null?void 0:k.messages)==null?void 0:E.timestamp}},slots:{...(A=Ht.layout)==null?void 0:A.slots,...(T=e.layout)==null?void 0:T.slots}},markdown:{...Ht.markdown,...e.markdown,options:{...(y=Ht.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{...Ht.messageActions,...e.messageActions}}:Ht}var Kc={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"}},Xc={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"}},Qc={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:Gr,maxWidth:Hi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",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 Oa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Oa(e,o):o}function Bi(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Oa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Jc(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function Hh(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=Hh(a,n):r[o]=n}return r}function lv(e,t){return t?Hh(e,t):e}function _a(e,t={}){var n,a,s,i,c,d,p,u,g,f,h,b,k;let r={palette:Kc,semantic:Xc,components:Qc},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...r.semantic.colors.feedback,...(h=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:h.feedback}},spacing:{...r.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...r.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:lv(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Jc(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Di(e){var b,k,E,A,T,y,w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me,oe,se,ge,Te,qe,j,ee,Ee,te,le,ke,nt,yt,Kt,jt,ct,fe,X,st,je,Ce,ve,Ye,Vt,xe,de,Cr,Ct,xr,Co,So,Ve,W,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,tr,Ao,Uo,io,lo,on,zt,co,qo,Fr,Rr,Nr,po,Mo,nn,Qr,an,St,To,Eo,Vo,uo,ht,On,ko,_n,Ir,xa,sn,zo,ln,dn,Un,qn,cn,vt,Or,_r,Sr,At,Jr,Yr,Ur,pn;let t=Bi(e),r={};for(let[we,$o]of Object.entries(t)){let Zr=we.replace(/\./g,"-");r[`--persona-${Zr}`]=$o.value}r["--persona-primary"]=(b=r["--persona-semantic-colors-primary"])!=null?b:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(k=r["--persona-semantic-colors-secondary"])!=null?k:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(T=r["--persona-semantic-colors-background"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(H=r["--persona-semantic-colors-border"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(I=r["--persona-semantic-colors-divider"])!=null?I:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(P=r["--persona-components-voice-recording-indicator"])!=null?P:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(B=r["--persona-components-voice-recording-background"])!=null?B:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Q=r["--persona-components-voice-speaking-icon"])!=null?Q:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-surface"],r["--persona-approval-border"]=(ue=r["--persona-components-approval-requested-border"])!=null?ue:r["--persona-border"],r["--persona-approval-text"]=(Z=r["--persona-components-approval-requested-text"])!=null?Z:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Le=r["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",r["--persona-approval-approve-bg"]=(We=r["--persona-components-approval-approve-background"])!=null?We:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(ie=r["--persona-components-approval-deny-background"])!=null?ie:r["--persona-container"],r["--persona-attachment-image-bg"]=(Me=r["--persona-components-attachment-image-background"])!=null?Me:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(oe=r["--persona-components-attachment-image-border"])!=null?oe:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(se=r["--persona-semantic-typography-fontFamily"])!=null?se:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(ge=r["--persona-semantic-typography-fontSize"])!=null?ge:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(Te=r["--persona-semantic-typography-fontWeight"])!=null?Te:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(qe=r["--persona-semantic-typography-lineHeight"])!=null?qe:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(j=r["--persona-palette-radius-sm"])!=null?j:"0.125rem",r["--persona-radius-md"]=(ee=r["--persona-palette-radius-md"])!=null?ee:"0.375rem",r["--persona-radius-lg"]=(Ee=r["--persona-palette-radius-lg"])!=null?Ee:"0.5rem",r["--persona-radius-xl"]=(te=r["--persona-palette-radius-xl"])!=null?te:"0.75rem",r["--persona-radius-full"]=(le=r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-radius"]=(nt=(ke=r["--persona-components-launcher-borderRadius"])!=null?ke:r["--persona-palette-radius-full"])!=null?nt:"9999px",r["--persona-launcher-bg"]=(yt=r["--persona-components-launcher-background"])!=null?yt:r["--persona-primary"],r["--persona-launcher-fg"]=(Kt=r["--persona-components-launcher-foreground"])!=null?Kt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(jt=r["--persona-components-launcher-border"])!=null?jt:r["--persona-border"],r["--persona-button-primary-bg"]=(ct=r["--persona-components-button-primary-background"])!=null?ct:r["--persona-primary"],r["--persona-button-primary-fg"]=(fe=r["--persona-components-button-primary-foreground"])!=null?fe:r["--persona-text-inverse"],r["--persona-button-radius"]=(st=(X=r["--persona-components-button-primary-borderRadius"])!=null?X:r["--persona-palette-radius-full"])!=null?st:"9999px",r["--persona-panel-radius"]=(Ce=(je=r["--persona-components-panel-borderRadius"])!=null?je:r["--persona-radius-xl"])!=null?Ce:"0.75rem",r["--persona-panel-border"]=(ve=r["--persona-components-panel-border"])!=null?ve:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Vt=(Ye=r["--persona-components-panel-shadow"])!=null?Ye:r["--persona-palette-shadows-xl"])!=null?Vt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(xe=r["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Cr=(de=r["--persona-components-input-borderRadius"])!=null?de:r["--persona-radius-lg"])!=null?Cr:"0.5rem",r["--persona-message-user-radius"]=(xr=(Ct=r["--persona-components-message-user-borderRadius"])!=null?Ct:r["--persona-radius-lg"])!=null?xr:"0.5rem",r["--persona-message-assistant-radius"]=(So=(Co=r["--persona-components-message-assistant-borderRadius"])!=null?Co:r["--persona-radius-lg"])!=null?So:"0.5rem",r["--persona-header-bg"]=(Ve=r["--persona-components-header-background"])!=null?Ve:r["--persona-surface"],r["--persona-header-border"]=(W=r["--persona-components-header-border"])!=null?W:r["--persona-divider"],r["--persona-header-icon-bg"]=(ce=r["--persona-components-header-iconBackground"])!=null?ce:r["--persona-primary"],r["--persona-header-icon-fg"]=(Se=r["--persona-components-header-iconForeground"])!=null?Se:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Ae=r["--persona-components-header-titleForeground"])!=null?Ae:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Ie=r["--persona-components-header-subtitleForeground"])!=null?Ie:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(et=r["--persona-components-header-actionIconForeground"])!=null?et:r["--persona-muted"];let o=(Qe=e.components)==null?void 0:Qe.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(gt=e.components)==null?void 0:gt.introCard;r["--persona-intro-card-bg"]=(pe=r["--persona-components-introCard-background"])!=null?pe:r["--persona-surface"],r["--persona-intro-card-radius"]=(N=r["--persona-components-introCard-borderRadius"])!=null?N:"1rem",r["--persona-intro-card-padding"]=(ye=r["--persona-components-introCard-padding"])!=null?ye:"1.5rem",r["--persona-intro-card-shadow"]=(mt=(ae=n==null?void 0:n.shadow)!=null?ae:r["--persona-components-introCard-shadow"])!=null?mt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Ke=r["--persona-components-input-background"])!=null?Ke:r["--persona-surface"],r["--persona-input-placeholder"]=(Lt=r["--persona-components-input-placeholder"])!=null?Lt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Et=r["--persona-components-message-user-background"])!=null?Et:r["--persona-accent"],r["--persona-message-user-text"]=(bt=r["--persona-components-message-user-text"])!=null?bt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(It=r["--persona-components-message-user-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Qt=r["--persona-components-message-assistant-background"])!=null?Qt:r["--persona-surface"],r["--persona-message-assistant-text"]=(Ft=r["--persona-components-message-assistant-text"])!=null?Ft:r["--persona-text"],r["--persona-message-assistant-border"]=(tr=r["--persona-components-message-assistant-border"])!=null?tr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(Ao=r["--persona-components-message-assistant-shadow"])!=null?Ao:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(io=(Uo=r["--persona-components-scrollToBottom-background"])!=null?Uo:r["--persona-button-primary-bg"])!=null?io:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(on=(lo=r["--persona-components-scrollToBottom-foreground"])!=null?lo:r["--persona-button-primary-fg"])!=null?on:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(zt=r["--persona-components-scrollToBottom-border"])!=null?zt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(co=r["--persona-components-scrollToBottom-size"])!=null?co:"40px",r["--persona-scroll-to-bottom-radius"]=(Rr=(Fr=(qo=r["--persona-components-scrollToBottom-borderRadius"])!=null?qo:r["--persona-button-radius"])!=null?Fr:r["--persona-radius-full"])!=null?Rr:"9999px",r["--persona-scroll-to-bottom-shadow"]=(po=(Nr=r["--persona-components-scrollToBottom-shadow"])!=null?Nr:r["--persona-palette-shadows-sm"])!=null?po:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Mo=r["--persona-components-scrollToBottom-padding"])!=null?Mo:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(nn=r["--persona-components-scrollToBottom-gap"])!=null?nn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(an=(Qr=r["--persona-components-scrollToBottom-fontSize"])!=null?Qr:r["--persona-palette-typography-fontSize-sm"])!=null?an:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(St=r["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",r["--persona-tool-bubble-shadow"]=(To=r["--persona-components-toolBubble-shadow"])!=null?To:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(Eo=r["--persona-components-reasoningBubble-shadow"])!=null?Eo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Vo=r["--persona-components-composer-shadow"])!=null?Vo:"none",r["--persona-md-inline-code-bg"]=(uo=r["--persona-components-markdown-inlineCode-background"])!=null?uo:r["--persona-container"],r["--persona-md-inline-code-color"]=(ht=r["--persona-components-markdown-inlineCode-foreground"])!=null?ht:r["--persona-text"],r["--persona-md-link-color"]=(ko=(On=r["--persona-components-markdown-link-foreground"])!=null?On:r["--persona-accent"])!=null?ko:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(_n=r["--persona-components-markdown-codeBlock-background"])!=null?_n:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Ir=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Ir:r["--persona-border"],r["--persona-md-code-block-text-color"]=(xa=r["--persona-components-markdown-codeBlock-textColor"])!=null?xa:"inherit",r["--persona-md-table-header-bg"]=(sn=r["--persona-components-markdown-table-headerBackground"])!=null?sn:r["--persona-container"],r["--persona-md-table-border-color"]=(zo=r["--persona-components-markdown-table-borderColor"])!=null?zo:r["--persona-border"],r["--persona-md-hr-color"]=(ln=r["--persona-components-markdown-hr-color"])!=null?ln:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(dn=r["--persona-components-markdown-blockquote-borderColor"])!=null?dn:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(Un=r["--persona-components-markdown-blockquote-background"])!=null?Un:"transparent",r["--persona-md-blockquote-text-color"]=(qn=r["--persona-components-markdown-blockquote-textColor"])!=null?qn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(cn=r["--persona-components-collapsibleWidget-container"])!=null?cn:r["--persona-surface"],r["--cw-surface"]=(vt=r["--persona-components-collapsibleWidget-surface"])!=null?vt:r["--persona-surface"],r["--cw-border"]=(Or=r["--persona-components-collapsibleWidget-border"])!=null?Or:r["--persona-border"],r["--persona-message-border"]=(_r=r["--persona-components-message-border"])!=null?_r:r["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(r["--persona-icon-btn-bg"]=u.background),u.border&&(r["--persona-icon-btn-border"]=u.border),u.color&&(r["--persona-icon-btn-color"]=u.color),u.padding&&(r["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(r["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(r["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(r["--persona-icon-btn-active-border"]=u.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(r["--persona-label-btn-bg"]=g.background),g.border&&(r["--persona-label-btn-border"]=g.border),g.color&&(r["--persona-label-btn-color"]=g.color),g.padding&&(r["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(r["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(r["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(r["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(r["--persona-toggle-group-radius"]=f.borderRadius));let h=p==null?void 0:p.artifact;if(h!=null&&h.toolbar){let we=h.toolbar;we.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=we.iconHoverColor),we.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=we.iconHoverBackground),we.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=we.iconPadding),we.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=we.iconBorderRadius),we.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=we.iconBorder),we.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=we.toggleGroupGap),we.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=we.toggleBorderRadius),we.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=we.copyBackground),we.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=we.copyBorder),we.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=we.copyColor),we.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=we.copyBorderRadius),we.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=we.copyPadding),we.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=we.copyMenuBackground,r["--persona-dropdown-bg"]=(Sr=r["--persona-dropdown-bg"])!=null?Sr:we.copyMenuBackground),we.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,r["--persona-dropdown-border"]=(At=r["--persona-dropdown-border"])!=null?At:we.copyMenuBorder),we.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,r["--persona-dropdown-shadow"]=(Jr=r["--persona-dropdown-shadow"])!=null?Jr:we.copyMenuShadow),we.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Yr=r["--persona-dropdown-radius"])!=null?Yr:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ur=r["--persona-dropdown-item-hover-bg"])!=null?Ur:we.copyMenuItemHoverBackground),we.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(h!=null&&h.tab){let we=h.tab;we.background&&(r["--persona-artifact-tab-bg"]=we.background),we.activeBackground&&(r["--persona-artifact-tab-active-bg"]=we.activeBackground),we.activeBorder&&(r["--persona-artifact-tab-active-border"]=we.activeBorder),we.borderRadius&&(r["--persona-artifact-tab-radius"]=we.borderRadius),we.textColor&&(r["--persona-artifact-tab-color"]=we.textColor),we.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=we.hoverBackground),we.listBackground&&(r["--persona-artifact-tab-list-bg"]=we.listBackground),we.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=we.listBorderColor),we.listPadding&&(r["--persona-artifact-tab-list-padding"]=we.listPadding)}if(h!=null&&h.pane){let we=h.pane;if(we.toolbarBackground){let $o=(pn=Oa(e,we.toolbarBackground))!=null?pn:we.toolbarBackground;r["--persona-artifact-toolbar-bg"]=$o}}return r}var Wh={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 dv={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"}}},Bh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ls=()=>{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"},cv=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Ls()},Yc=e=>cv(e),pv=e=>_a(e),uv=e=>{var r;let t=_a(void 0,{validate:!1});return _a({...e,palette:{...t.palette,colors:{...dv.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ua=e=>{let t=Yc(e),r=Bh(e==null?void 0:e.theme),o=Bh(e==null?void 0:e.darkTheme);return t==="dark"?uv(ks(r!=null?r:{},o!=null?o:{})):pv(r)},fv=e=>Di(e),Hn=(e,t)=>{let r=Ua(t),o=fv(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Fi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Ls())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ls());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var Dh=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(g,f,h={}){g=p(g);let b=u(f),k=d(g,b,h),E=n(k,()=>i(k,g,b,A=>A.morphStyle==="innerHTML"?(a(A,g,b),Array.from(g.childNodes)):o(A,g,b)));return k.pantry.remove(),E}function o(g,f,h){let b=u(f);return a(g,b,h,f,f.nextSibling),Array.from(b.childNodes)}function n(g,f){var T;if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:b,selectionStart:k,selectionEnd:E}=h,A=f();return b&&b!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(h=g.target.querySelector(`[id="${b}"]`),h==null||h.focus()),h&&!h.selectionEnd&&E&&h.setSelectionRange(k,E),A}let a=(function(){function g(y,w,v,M=null,H=null){w instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(w=w.content,v=v.content),M||(M=w.firstChild);for(let I of v.childNodes){if(M&&M!=H){let B=h(y,I,M,H);if(B){B!==M&&k(y,M,B),s(B,I,y),M=B.nextSibling;continue}}if(I instanceof Element){let B=I.getAttribute("id");if(y.persistentIds.has(B)){let O=E(w,B,M,y);s(O,I,y),M=O.nextSibling;continue}}let P=f(w,I,M,y);P&&(M=P.nextSibling)}for(;M&&M!=H;){let I=M;M=M.nextSibling,b(y,I)}}function f(y,w,v,M){if(M.callbacks.beforeNodeAdded(w)===!1)return null;if(M.idMap.has(w)){let H=document.createElement(w.tagName);return y.insertBefore(H,v),s(H,w,M),M.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return y.insertBefore(H,v),M.callbacks.afterNodeAdded(H),H}}let h=(function(){function y(M,H,I,P){let B=null,O=H.nextSibling,Q=0,me=I;for(;me&&me!=P;){if(v(me,H)){if(w(M,me,H))return me;B===null&&(M.idMap.has(me)||(B=me))}if(B===null&&O&&v(me,O)&&(Q++,O=O.nextSibling,Q>=2&&(B=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return B||null}function w(M,H,I){let P=M.idMap.get(H),B=M.idMap.get(I);if(!B||!P)return!1;for(let O of P)if(B.has(O))return!0;return!1}function v(M,H){var B,O,Q;let I=M,P=H;return I.nodeType===P.nodeType&&I.tagName===P.tagName&&(!((B=I.getAttribute)!=null&&B.call(I,"id"))||((O=I.getAttribute)==null?void 0:O.call(I,"id"))===((Q=P.getAttribute)==null?void 0:Q.call(P,"id")))}return y})();function b(y,w){var v;if(y.idMap.has(w))T(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(v=w.parentNode)==null||v.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function k(y,w,v){let M=w;for(;M&&M!==v;){let H=M;M=M.nextSibling,b(y,H)}return M}function E(y,w,v,M){var I,P;let H=((P=(I=M.target).getAttribute)==null?void 0:P.call(I,"id"))===w&&M.target||M.target.querySelector(`[id="${w}"]`)||M.pantry.querySelector(`[id="${w}"]`);return A(H,M),T(y,H,v),H}function A(y,w){let v=y.getAttribute("id");for(;y=y.parentNode;){let M=w.idMap.get(y);M&&(M.delete(v),M.size||w.idMap.delete(y))}}function T(y,w,v){if(y.moveBefore)try{y.moveBefore(w,v)}catch{y.insertBefore(w,v)}else y.insertBefore(w,v)}return g})(),s=(function(){function g(A,T,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?c(A,T,y):(f(A,T,y),E(A,y)||a(y,A,T))),y.callbacks.afterNodeMorphed(A,T)),A)}function f(A,T,y){let w=T.nodeType;if(w===1){let v=A,M=T,H=v.attributes,I=M.attributes;for(let P of I)k(P.name,v,"update",y)||v.getAttribute(P.name)!==P.value&&v.setAttribute(P.name,P.value);for(let P=H.length-1;0<=P;P--){let B=H[P];if(B&&!M.hasAttribute(B.name)){if(k(B.name,v,"remove",y))continue;v.removeAttribute(B.name)}}E(v,y)||h(v,M,y)}(w===8||w===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function h(A,T,y){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let w=T.value,v=A.value;b(A,T,"checked",y),b(A,T,"disabled",y),T.hasAttribute("value")?v!==w&&(k("value",A,"update",y)||(A.setAttribute("value",w),A.value=w)):k("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)b(A,T,"selected",y);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let w=T.value,v=A.value;if(k("value",A,"update",y))return;w!==v&&(A.value=w),A.firstChild&&A.firstChild.nodeValue!==w&&(A.firstChild.nodeValue=w)}}function b(A,T,y,w){let v=T[y],M=A[y];if(v!==M){let H=k(y,A,"update",w);H||(A[y]=T[y]),v?H||A.setAttribute(y,""):k(y,A,"remove",w)||A.removeAttribute(y)}}function k(A,T,y,w){return A==="value"&&w.ignoreActiveValue&&T===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(A,T,y)===!1}function E(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function i(g,f,h,b){if(g.head.block){let k=f.querySelector("head"),E=h.querySelector("head");if(k&&E){let A=c(k,E,g);return Promise.all(A).then(()=>{let T=Object.assign(g,{head:{block:!1,ignore:!0}});return b(T)})}}return b(g)}function c(g,f,h){let b=[],k=[],E=[],A=[],T=new Map;for(let w of f.children)T.set(w.outerHTML,w);for(let w of g.children){let v=T.has(w.outerHTML),M=h.head.shouldReAppend(w),H=h.head.shouldPreserve(w);v||H?M?k.push(w):(T.delete(w.outerHTML),E.push(w)):h.head.style==="append"?M&&(k.push(w),A.push(w)):h.head.shouldRemove(w)!==!1&&k.push(w)}A.push(...T.values());let y=[];for(let w of A){let v=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,H=new Promise(function(I){M=I});v.addEventListener("load",function(){M()}),y.push(H)}g.appendChild(v),h.callbacks.afterNodeAdded(v),b.push(v)}}for(let w of k)h.callbacks.beforeNodeRemoved(w)!==!1&&(g.removeChild(w),h.callbacks.afterNodeRemoved(w));return h.head.afterHeadMorphed(g,{added:b,kept:E,removed:k}),y}let d=(function(){function g(y,w,v){let{persistentIds:M,idMap:H}=A(y,w),I=f(v),P=I.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(P))throw`Do not understand how to morph style ${P}`;return{target:y,newContent:w,config:I,morphStyle:P,ignoreActive:I.ignoreActive,ignoreActiveValue:I.ignoreActiveValue,restoreFocus:I.restoreFocus,idMap:H,persistentIds:M,pantry:h(),activeElementAndParents:b(y),callbacks:I.callbacks,head:I.head}}function f(y){let w=Object.assign({},t);return Object.assign(w,y),w.callbacks=Object.assign({},t.callbacks,y.callbacks),w.head=Object.assign({},t.head,y.head),w}function h(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function b(y){let w=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&y.contains(v))for(;v&&(w.push(v),v!==y);)v=v.parentElement;return w}function k(y){var v;let w=Array.from(y.querySelectorAll("[id]"));return(v=y.getAttribute)!=null&&v.call(y,"id")&&w.push(y),w}function E(y,w,v,M){for(let H of M){let I=H.getAttribute("id");if(w.has(I)){let P=H;for(;P;){let B=y.get(P);if(B==null&&(B=new Set,y.set(P,B)),B.add(I),P===v)break;P=P.parentElement}}}}function A(y,w){let v=k(y),M=k(w),H=T(v,M),I=new Map;E(I,H,y,v);let P=w.__idiomorphRoot||w;return E(I,H,P,M),{persistentIds:H,idMap:I}}function T(y,w){let v=new Set,M=new Map;for(let{id:I,tagName:P}of y)M.has(I)?v.add(I):M.set(I,P);let H=new Set;for(let{id:I,tagName:P}of w)H.has(I)?v.add(I):M.get(I)===P&&H.add(I);for(let I of v)H.delete(I);return H}return g})(),{normalizeElement:p,normalizeParent:u}=(function(){let g=new WeakSet;function f(E){return E instanceof Document?E.documentElement:E}function h(E){if(E==null)return document.createElement("div");if(typeof E=="string")return h(k(E));if(g.has(E))return E;if(E instanceof Node){if(E.parentNode)return new b(E);{let A=document.createElement("div");return A.append(E),A}}else{let A=document.createElement("div");for(let T of[...E])A.append(T);return A}}class b{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,y)=>{if(y instanceof Element){y.matches(A)&&T.push(y);let w=y.querySelectorAll(A);for(let v=0;v<w.length;v++)T.push(w[v])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function k(E){let A=new DOMParser,T=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let y=A.parseFromString(E,"text/html");if(T.match(/<\/html>/))return g.add(y),y;{let w=y.firstChild;return w&&g.add(w),w}}else{let w=A.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return g.add(w),w}}return{normalizeElement:f,normalizeParent:h}})();return{morph:r,defaults:t}})();var Ni=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;Dh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===n.getAttribute("data-tool-elapsed")?!1:void 0;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var Fh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Oi={index:-1,draft:""};function Nh(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Oi}}}function Oh(e,t){var r,o,n,a,s,i,c,d,p,u,g,f,h,b,k,E,A,T,y,w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me,oe,se,ge;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(d=e.llmContent)==null?void 0:d.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(h=(f=e.toolCall)==null?void 0:f.status)!=null?h:"",(k=(b=e.toolCall)==null?void 0:b.name)!=null?k:"",(T=(A=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?T:0,(M=(v=(w=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(I=e.toolCall)!=null&&I.args?JSON.stringify(e.toolCall.args).length:0,(O=(B=(P=e.reasoning)==null?void 0:P.chunks)==null?void 0:B.length)!=null?O:0,(Z=(ue=(me=(Q=e.reasoning)==null?void 0:Q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?Z:0,(Me=(ie=(We=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?Me:"",(se=(oe=e.contentParts)==null?void 0:oe.length)!=null?se:0,(ge=e.stopReason)!=null?ge:"",t].join("\0")}function _h(){return new Map}function Uh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function qh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function Vh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function _i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Oo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wn(e,t){return Oo(e)-e.scrollTop<=t}function Ui(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function qi(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function zh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function $h(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function jh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var or={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},wr=1e5,Bn=wr+1;var Ps={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},mv=["pre","code","a","script","style"],Vi=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Ps.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ps.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ps.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Ps.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Ps.buffer}},Kh=[{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"}],Rs=new Map;for(let e of Kh)Rs.set(e.name,e);var ca=e=>{Rs.set(e.name,e)},tp=e=>{Kh.some(t=>t.name===e)||Rs.delete(e)},rp=()=>Array.from(Rs.keys()),qa=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Rs.get(e))!=null?o:null},zi=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
20
|
-
`);return a<0?"":e.slice(0,a)}return e},gv=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},hv=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},Zc=/\s/,xv=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},yv=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(Zc.test(a[i])){let d=i;for(;d<a.length&&Zc.test(a[d]);)d+=1;s.appendChild(o.createTextNode(a.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=i;for(;p<a.length&&!Zc.test(a[p]);)d.appendChild(gv(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(d),i=p}n.replaceChild(s,e)},bv=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(hv(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},Is=(e,t,r,o)=>{var u,g;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((u=o==null?void 0:o.skipTags)!=null?u:mv).map(f=>f.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)xv(c,a)||i.push(c),c=s.nextNode();let d={value:(g=o==null?void 0:o.startIndex)!=null?g:0},p=t==="char"?yv:bv;for(let f of i)p(f,r,d);return n.innerHTML},$i=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Hs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},Gh=new WeakMap,vv=(e,t)=>{var a;if(!e.styles)return;let r=Gh.get(t);if(r||(r=new Set,Gh.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},ep=new WeakMap,wv=(e,t)=>{if(!e.onAttach)return;let r=ep.get(t);if(r||(r=new Map,ep.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},Xh=e=>{let t=ep.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},ji=(e,t)=>{vv(e,t),wv(e,t)};function op(e,t=wr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Ws=0,Dn=null;function np(e=document){var r;if(Ws++,Ws===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Dn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Ws=Math.max(0,Ws-1),Ws===0&&Dn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Dn.originalOverflow,n.style.position=Dn.originalPosition,n.style.top=Dn.originalTop,n.style.width=Dn.originalWidth,a.scrollTo(0,Dn.scrollY),Dn=null}}}var Bs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Fn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Kr=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Bs.side,width:(n=t==null?void 0:t.width)!=null?n:Bs.width,animate:(a=t==null?void 0:t.animate)!=null?a:Bs.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Bs.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Bs.maxHeight}};var wo={"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 Cv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Gi=(e,t={})=>{var k,E,A,T,y,w;let{showClose:r=!0,wrapperClassName:o=Cv,buttonSize:n,iconSize:a="28px"}=t,s=(k=e==null?void 0:e.launcher)!=null?k:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=S("div",o),d=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(T=s.closeButtonShowTooltip)!=null?T:!0,u=(y=s.closeButtonIconName)!=null?y:"x",g=(w=s.closeButtonIconText)!=null?w:"\xD7",f=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=Tt("button",{className:gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Pr.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:f?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),b=he(u,a,"currentColor",1);if(b?(b.style.display="block",h.appendChild(b)):h.textContent=g,c.appendChild(h),p&&d){let v=null,M=()=>{if(v)return;let I=h.ownerDocument,P=I.body;if(!P)return;v=No(I,"div","persona-clear-chat-tooltip"),v.textContent=d;let B=No(I,"div");B.className="persona-clear-chat-tooltip-arrow",v.appendChild(B);let O=h.getBoundingClientRect();v.style.position="fixed",v.style.zIndex=String(Bn),v.style.left=`${O.left+O.width/2}px`,v.style.top=`${O.top-8}px`,v.style.transform="translate(-50%, -100%)",P.appendChild(v)},H=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=null)};c.addEventListener("mouseenter",M),c.addEventListener("mouseleave",H),h.addEventListener("focus",M),h.addEventListener("blur",H),c._cleanupTooltip=()=>{H(),c.removeEventListener("mouseenter",M),c.removeEventListener("mouseleave",H),h.removeEventListener("focus",M),h.removeEventListener("blur",H)}}return{button:h,wrapper:c}},Sv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ki=(e,t={})=>{var v,M,H,I,P,B,O,Q,me,ue,Z,Le,We;let{wrapperClassName:r=Sv,buttonSize:o,iconSize:n="20px"}=t,s=(M=((v=e==null?void 0:e.launcher)!=null?v:{}).clearChat)!=null?M:{},i=(H=o!=null?o:s.size)!=null?H:"32px",c=(I=s.iconName)!=null?I:"refresh-cw",d=(P=s.iconColor)!=null?P:"",p=(B=s.backgroundColor)!=null?B:"",u=(O=s.borderWidth)!=null?O:"",g=(Q=s.borderColor)!=null?Q:"",f=(me=s.borderRadius)!=null?me:"",h=(ue=s.paddingX)!=null?ue:"",b=(Z=s.paddingY)!=null?Z:"",k=(Le=s.tooltipText)!=null?Le:"Clear chat",E=(We=s.showTooltip)!=null?We:!0,A=S("div",r),T=!!(u||g),y=Tt("button",{className:gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:i,width:i,color:d||Pr.actionIconColor,backgroundColor:p||void 0,border:T?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:b||void 0,paddingBottom:b||void 0}}),w=he(c,n,"currentColor",1);if(w&&(w.style.display="block",y.appendChild(w)),A.appendChild(y),E&&k){let ie=null,Me=()=>{if(ie)return;let se=y.ownerDocument,ge=se.body;if(!ge)return;ie=No(se,"div","persona-clear-chat-tooltip"),ie.textContent=k;let Te=No(se,"div");Te.className="persona-clear-chat-tooltip-arrow",ie.appendChild(Te);let qe=y.getBoundingClientRect();ie.style.position="fixed",ie.style.zIndex=String(Bn),ie.style.left=`${qe.left+qe.width/2}px`,ie.style.top=`${qe.top-8}px`,ie.style.transform="translate(-50%, -100%)",ge.appendChild(ie)},oe=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};A.addEventListener("mouseenter",Me),A.addEventListener("mouseleave",oe),y.addEventListener("focus",Me),y.addEventListener("blur",oe),A._cleanupTooltip=()=>{oe(),A.removeEventListener("mouseenter",Me),A.removeEventListener("mouseleave",oe),y.removeEventListener("focus",Me),y.removeEventListener("blur",oe)}}return{button:y,wrapper:A}};var Pr={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))"},tn=e=>{var w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me;let{config:t,showClose:r=!0}=e,o=Tt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(w=t==null?void 0:t.launcher)!=null?w:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(H=n.headerIconHidden)!=null?H:!1,c=n.headerIconName,d=Tt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let oe=parseFloat(a)||24,se=he(c,oe*.6,"currentColor",1);se?d.replaceChildren(se):d.textContent=(P=(I=t==null?void 0:t.launcher)==null?void 0:I.agentIconText)!=null?P:"\u{1F4AC}"}else if((B=t==null?void 0:t.launcher)!=null&&B.iconUrl){let oe=S("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=a,oe.style.width=a,d.replaceChildren(oe)}else d.textContent=(Q=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Q:"\u{1F4AC}";let p=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Tt("span",{className:"persona-text-base persona-font-semibold",text:(ue=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?ue:"Chat Assistant",style:{color:Pr.titleColor}}),g=Tt("span",{className:"persona-text-xs",text:(Le=(Z=t==null?void 0:t.launcher)==null?void 0:Z.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Pr.subtitleColor}});p.append(u,g),i?o.append(p):o.append(d,p);let f=(We=n.clearChat)!=null?We:{},h=(ie=f.enabled)!=null?ie:!0,b=(Me=f.placement)!=null?Me:"inline",k=null,E=null;if(h){let se=Ki(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=se.button,E=se.wrapper,b==="top-right"&&(E.style.right="48px"),b==="inline"&&o.appendChild(E)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&b==="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:T,wrapper:y}=Gi(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:g,closeButton:T,closeButtonWrapper:y,clearChatButton:k,clearChatButtonWrapper:E}},pa=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.placement)!=null?d:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Nn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=S("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(Bn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let k=document.createElement("hr");s.appendChild(k)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let k=he(f.icon,16,"currentColor",1.5);k&&h.appendChild(k)}let b=document.createElement("span");b.textContent=f.label,h.appendChild(b),h.addEventListener("click",k=>{k.stopPropagation(),p(),r(f.id)}),s.appendChild(h)}let i=null;function c(){if(!a)return;let f=o.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,n==="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 d(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!s.contains(h.target)&&!o.contains(h.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function u(){s.classList.contains("persona-hidden")?d():p()}function g(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:p,toggle:u,destroy:g}}function pr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=S("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=he(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[p,u]of Object.entries(i))c.setAttribute(p,u);return c}function Ds(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let p=S("button",d);if(p.type="button",p.setAttribute("aria-label",r),t){let g=he(t,a!=null?a:14,"currentColor",2);g&&p.appendChild(g)}let u=S("span");if(u.textContent=r,p.appendChild(u),i&&p.addEventListener("click",i),c)for(let[g,f]of Object.entries(c))p.setAttribute(g,f);return p}function Qh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=S("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let u;p.icon?u=pr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(u=S("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),u.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:u}),a.appendChild(u)}function d(p){s=p,c()}return{element:a,setSelected:d}}function Xi(e){var f,h;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,d=S("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let p=S("span","persona-combo-btn-label");p.textContent=t,d.appendChild(p);let u=he(r,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),c&&(d.style.borderRadius=(f=c.borderRadius)!=null?f:"10px",d.style.padding=(h=c.padding)!=null?h:"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{var b,k;d.style.backgroundColor=(b=c.background)!=null?b:"",d.style.borderColor=(k=c.border)!=null?k:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let g=Nn({items:o,onSelect:b=>{d.setAttribute("aria-expanded","false"),n(b)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",b=>{b.stopPropagation();let k=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",k?"false":"true"),g.toggle()}),d.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),d.click())}),{element:d,setLabel:b=>{p.textContent=b,d.setAttribute("aria-label",b)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let b=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var ap=e=>{var o;let t=tn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Av(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=S("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",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=he(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=S("div","persona-relative");c.appendChild(i);let d=Nn({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",p=>{p.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var sp=e=>{var A,T,y,w,v,M,H,I,P;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=S("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 c=n==null?void 0:n.titleMenu,d,p;if(c)d=Xi({label:(T=s.title)!=null?T:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=Pr.titleColor,p=(y=d.querySelector(".persona-combo-btn-label"))!=null?y:d;else{if(d=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=S("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Pr.titleColor,p.textContent=(w=s.title)!=null?w:"Chat Assistant",d.appendChild(p),Av(d,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let O=n.onTitleClick;d.addEventListener("click",Q=>{Q.target.closest("button")||O()}),d.addEventListener("keydown",Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),O())})}let B=n==null?void 0:n.titleRowHover;B&&(d.style.borderRadius=(M=B.borderRadius)!=null?M:"10px",d.style.padding=(H=B.padding)!=null?H:"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{var O,Q;d.style.backgroundColor=(O=B.background)!=null?O:"",d.style.borderColor=(Q=B.border)!=null?Q:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=(I=s.closeButtonSize)!=null?I:"32px",g=S("div",""),f=S("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=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=s.closeButtonColor||Pr.actionIconColor;let h=(P=s.closeButtonIconName)!=null?P:"x",b=he(h,"28px","currentColor",1);b?f.appendChild(b):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),i.appendChild(g);let k=S("div");k.style.display="none";let E=S("span");return E.style.display="none",{header:i,iconHolder:k,headerTitle:p,headerSubtitle:E,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Qi={default:ap,minimal:sp},ip=e=>{var t;return(t=Qi[e])!=null?t:Qi.default},Va=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let d=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=S("div");p.style.display="none";let u=S("span"),g=S("span"),f=S("button");f.style.display="none";let h=S("div");return h.style.display="none",{header:d,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=ip(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ji=e=>{var s,i;let t=S("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},Yi=e=>{var w,v,M,H,I,P,B,O,Q,me,ue,Z;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(v=t.useIcon)!=null?v:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(H=t.stopIconName)!=null?H:"square",s=(I=t.tooltipText)!=null?I:"Send message",i=(P=t.stopTooltipText)!=null?P:"Stop generating",c=(O=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?O:"Send",d=(me=(Q=e==null?void 0:e.copy)==null?void 0:Q.stopButtonLabel)!=null?me:"Stop",p=(ue=t.showTooltip)!=null?ue:!1,u=(Z=t.size)!=null?Z:"40px",g=t.backgroundColor,f=t.textColor,h=S("div","persona-send-button-wrapper"),b=Tt("button",{className:gs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!g&&"persona-bg-persona-primary",!r&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?u:void 0,height:r?u:void 0,minWidth:r?u:void 0,minHeight:r?u:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:r&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),k=null,E=null;if(r){let Le=parseFloat(u)||24,We=(f==null?void 0:f.trim())||"currentColor";n?(k=he(n,Le,We,2),k?b.appendChild(k):b.textContent=o):b.textContent=o,E=he(a,Le,We,2)}else b.textContent=c;let A=null;p&&s&&(A=S("div","persona-send-button-tooltip"),A.textContent=s,h.appendChild(A)),b.setAttribute("aria-label",s),h.appendChild(b);let T="send";return{button:b,wrapper:h,setMode:Le=>{if(Le===T)return;T=Le;let We=Le==="stop"?i:s;if(b.setAttribute("aria-label",We),A&&(A.textContent=We),r){if(k&&E){let ie=Le==="stop"?E:k;b.replaceChildren(ie)}}else b.textContent=Le==="stop"?d:c}}},Zi=e=>{var A,T,y,w,v,M,H,I,P,B,O,Q;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((T=t.provider)==null?void 0:T.type)==="runtype";if(!(o||n))return null;let s=(w=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?w:"40px",i=(v=t.iconName)!=null?v:"mic",c=(M=t.iconSize)!=null?M:s,d=parseFloat(c)||24,p=(I=t.backgroundColor)!=null?I:(H=e==null?void 0:e.sendButton)==null?void 0:H.backgroundColor,u=(B=t.iconColor)!=null?B:(P=e==null?void 0:e.sendButton)==null?void 0:P.textColor,g=S("div","persona-send-button-wrapper"),f=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),b=he(i,d,u||"currentColor",1.5);b?f.appendChild(b):f.textContent="\u{1F3A4}",g.appendChild(f);let k=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Q=t.showTooltip)!=null?Q:!1)&&k){let me=S("div","persona-send-button-tooltip");me.textContent=k,g.appendChild(me)}return{button:f,wrapper:g}},el=e=>{var h,b,k,E,A,T,y,w;let t=(h=e==null?void 0:e.attachments)!=null?h:{};if(t.enabled!==!0)return null;let r=(k=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?k:"40px",o=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=S("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:en).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(T=t.buttonIconName)!=null?T:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=S("div","persona-send-button-wrapper"),p=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=he(a,c,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",v=>{v.preventDefault(),n.click()}),d.appendChild(p);let g=(w=t.buttonTooltipText)!=null?w:"Attach file",f=S("div","persona-send-button-tooltip");return f.textContent=g,d.appendChild(f),{button:p,wrapper:d,input:n,previewsContainer:o}},tl=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let d=S("a");d.href=t.idleLink,d.target="_blank",d.rel="noopener noreferrer",d.textContent=a,d.style.color="inherit",d.style.textDecoration="none",o.appendChild(d)}else o.textContent=a;return o},rl=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var za=e=>{var h,b,k,E,A,T;let{config:t}=e,r=Tt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=rl(),n=Tt("form",{className:"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",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=Ji(t);s();let i=Yi(t),c=Zi(t),d=el(t),p=tl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let u=Tt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=S("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=S("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&g.append(d.wrapper),c&&f.append(c.wrapper),f.append(i.wrapper),u.append(g,f),n.append(u),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(h=c==null?void 0:c.button)!=null?h:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:p,attachmentButton:(k=d==null?void 0:d.button)!=null?k:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(T=d==null?void 0:d.previewsContainer)!=null?T:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var Jh=()=>{let e=Tt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),r=he("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=S("span","persona-pill-peek__text"),n=S("span","persona-pill-peek__caret"),a=he("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Yh=e=>{var h,b,k,E,A,T;let{config:t}=e,r=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=rl();o.style.display="none";let n=tl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=Ji(t);a.style.maxHeight="100px",s();let i=Yi(t),c=Zi(t),d=el(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let p=Tt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=S("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let g=S("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&g.append(c.wrapper),g.append(i.wrapper),p.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),d&&p.append(d.input),p.append(u,a,g),d&&r.append(d.previewsContainer),r.append(p,o,n);let f=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(h=c==null?void 0:c.button)!=null?h:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:n,attachmentButton:(k=d==null?void 0:d.button)!=null?k:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(T=d==null?void 0:d.previewsContainer)!=null?T:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Zh=e=>{var p,u,g,f,h,b,k,E,A,T,y,w,v,M,H,I,P;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,r=nr(e);if(Fn(e)){let B=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},O=S("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(h=B.expandedSize)!=null?h:"anchored",O.style.zIndex=String((k=(b=e==null?void 0:e.launcher)==null?void 0:b.zIndex)!=null?k:wr);let Q=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Q.style.width="100%",O.appendChild(Q);let me=S("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=B.expandedSize)!=null?E:"anchored",me.style.zIndex=String((T=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?T:wr),{wrapper:O,panel:Q,pillRoot:me}}if(r){let B=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return B.appendChild(O),{wrapper:B,panel:O}}if(!t){let B=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Q=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?w:"100%";return B.style.width=Q,O.style.width="100%",B.appendChild(O),{wrapper:B,panel:O}}let n=(v=e==null?void 0:e.launcher)!=null?v:{},a=n.position&&wo[n.position]?wo[n.position]:wo["bottom-right"],s=S("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?H:wr);let i=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(P=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?P:e==null?void 0:e.launcherWidth,d=c!=null?c:Gr;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Mv=(e,t)=>{var y,w,v,M,H,I,P,B,O;let r=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Gi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:w.enabled)!=null?v:!0,s=null,i=null;if(a){let Q=Ki(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Q.button,i=Q.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Tt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let p=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),u=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),g=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),f=S("div","persona-flex persona-flex-col persona-gap-3"),h=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(g.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(g,f);let k=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=Yh({config:e}),{root:A,textNode:T}=Jh();return r.append(c,n,d,k),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:f,composerOverlay:k,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:u,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:T}},ex=(e,t=!0)=>{var k,E,A,T,y,w,v,M,H;if(Fn(e))return Mv(e,t);let r=Tt("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=(k=e==null?void 0:e.layout)==null?void 0:k.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?Va(e,o,{showClose:t}):tn({config:e,showClose:t}),s=Tt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(T=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?T:"Hello \u{1F44B}"}),c=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(w=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?w:"Ask anything about your account or products."}),d=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:nr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=S("div","persona-flex persona-flex-col persona-gap-3"),u=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,p);let f=za({config:e}),h=((H=e==null?void 0:e.layout)==null?void 0:H.showFooter)!==!1;n?pa(r,a,e):(a.header.style.display="none",pa(r,a,e)),r.append(s);let b=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),r.append(f.footer),r.append(b),{container:r,body:s,messagesWrapper:p,composerOverlay:b,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:i,introSubtitle:c,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 lp=(e,t)=>{let r=S("button");r.type="button",r.innerHTML=`
|
|
19
|
+
_Details: ${o.message}_`:r}var Ba=e=>({isError:!0,content:[{type:"text",text:e}]}),mm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,gm=e=>lr(e)||e===To,In=class{constructor(t={},o){this.config=t;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Yr(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,r=!!o?.name&&(lr(o.name)||o.name===To&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&r&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Jr(t),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!r||!this.config.clientToken||rd().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ia(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=hr.isSupported()?new hr({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let r=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,s=t.browserFallback!==!1;if(r&&n&&a)return rd().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:r,agentId:n,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&o?new p(d,o,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(s&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=gr(o);let n=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,s,l)=>{if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:s,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:n,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(a=>{this.voiceStatus=a,this.voiceActive=a==="listening",this.callbacks.onVoiceStatusChanged?.(a)}),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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}updateConfig(t){let o={...this.config,...t};if(!yb(this.config,o)){this.config=o,this.client.updateConfig(o);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=o,this.client=new Jr(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:r,llmContent:n,contentParts:a,id:s,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:s??(o==="user"?Pn():o==="assistant"?mr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:r,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let r of t){let{role:n,content:a,llmContent:s,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:g,rawContent:f}=r,C={id:p??(n==="user"?Pn():n==="assistant"?mr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:a,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};o.push(C)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:r={},text:n="",llmContent:a,id:s,createdAt:l,sequence:p}=t,d={text:n,component:o,props:r};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async sendMessage(t,o){let r=t.trim();if(!r&&(!o?.contentParts||o.contentParts.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let n=Pn(),a=mr();this.activeAssistantMessageId=null;let s={id:n,role:"user",content:r||Qs,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts}};this.appendMessage(s),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:l.signal,assistantMessageId:a},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let c=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!c){let u=nd(d,this.config.errorMessage);if(u){let g={id:a,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=mr();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(n){if(this.status==="resuming"||this.reconnecting)return;let a=n instanceof Error&&(n.name==="AbortError"||n.message.includes("aborted")||n.message.includes("abort"));if(!a){let s=nd(n,this.config.errorMessage);if(s){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:s,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(n instanceof Error?this.callbacks.onError?.(n):this.callbacks.onError?.(new Error(String(n))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let r=o?.preserveAssistantId?o.assistantMessageId:void 0,n=!1;for(let a of this.messages)a.streaming&&a.id!==r&&(a.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${o.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(n=>{this.webMcpApprovalResolvers.set(r,n)})}resolveWebMcpApproval(t,o){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n?.approval&&this.upsertMessage({...n,approval:{...n.approval,status:o,resolvedAt:Date.now()}}),r(o==="approved")}async resolveApproval(t,o,r){let n=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},s=this.messages.find(c=>c.id===n),l={id:n,role:"assistant",content:"",createdAt:s?.createdAt??new Date().toISOString(),...s?.sequence!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,r):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),c){let u=null;if(c instanceof Response){if(!c.ok){let g=await c.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,o){let r=this.messages.find(n=>n.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let r=this.messages.find(n=>n.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let n=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!n||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof o=="string"?void 0:o;if(s===void 0&&typeof o=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let g=typeof u[0]?.question=="string"?u[0].question:"";g&&(s={[g]:o})}}this.markAskUserQuestionResolved(t,s),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof o=="string"?o:Object.entries(o).map(([u,g])=>`${u}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=s??{};d.forEach((u,g)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=c[f],C=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(n,{[a]:o});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,r=t.toolCall?.id;if(!o||!r){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(o);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,n)),!n.seen.has(r)&&(n.seen.add(r),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=o;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){let r=[this.messages.find(n=>n.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let n of r)if(typeof n=="number"&&Number.isFinite(n))return n;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==To?!1:(this.messages.find(r=>r.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,r,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:r,completedAt:n,duration:void 0,durationMs:Math.max(0,n-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let r=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(o.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),r.push(u);let g=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===To)return{dedupeKey:u,resumeKey:f,output:Xl(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),n.push(h);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,h.signal),M;if(!C)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await C}catch(L){let A=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return A||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,Ba(A?"Aborted by cancel()":mm(L)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ba("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:M,toolMessage:p,startedAt:g,completedAt:Date.now()}})),l=[];try{if(l=s.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:a.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===To?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,Ba("Aborted by cancel()"),c.startedAt)}finally{for(let p of r)this.webMcpInflightKeys.delete(p);for(let p of n)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,r=t.toolCall?.name,n=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!n){let h=`${o}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(o,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(h)}return}let a=`${o}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=r===To,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(r,c,p),g="execute",f=s;try{let h;if(d?h=Xl():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Ba("Aborted by cancel()"),s);return}let C=t.agentMetadata?.webMcpToolCallId??r;g="resume",await this.resumeWithToolOutput(o,C,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let C=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,Ba(C||p.aborted?"Aborted by cancel()":mm(h)),s),C||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,o,r,n){let a=await this.client.resumeFlow(t,{[o]:r},{signal:n?.signal});if(!a.ok){let s=await a.json().catch(()=>null);throw new Error(s?.error??`Resume failed: ${a.status}`)}n?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,r=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(o,r),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(r),r}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,r=jr(this.config.features?.artifacts,t.artifactType),n=Bs(r,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(s=>s.id===o);if(a){a.rawContent=n,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:n})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let r=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(fm(),um)).then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,r,n)=>t.connectStream(o,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>nd(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=mr(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let n=td(r.content);n.trim()&&this.readAloud.play(r.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Rn(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let r=td(o.content||"");if(!r.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:n?.voice,rate:n?.rate,pitch:n?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),r=this.messages.findIndex(n=>n.id===o.id);if(r===-1){this.appendMessage(o);return}this.messages=this.messages.map((n,a)=>{if(a!==r)return n;let s={...n,...o};if(n.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(s.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),n.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(s.agentMetadata={...s.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&o.approval&&n.approval.id===o.approval.id){let c=n.approval,u=o.approval;s.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=o.toolCall?.name,p=o.agentMetadata?.executionId,d=o.toolCall?.id;if(l&&gm(l)&&p&&d&&o.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),g=this.webMcpResolvedKeys.has(c),f=n.toolCall?.name,h=n.agentMetadata?.executionId===p&&n.toolCall?.id===d&&f!==void 0&&gm(f)&&n.toolCall?.status==="complete";(u||g||h)&&(s.agentMetadata={...s.agentMetadata??{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,r)=>{let n=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=o.sequence??0,l=r.sequence??0;return s!==l?s-l:o.id.localeCompare(r.id)})}};var ad=[["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 sd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var id=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ld=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var dd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var cd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var pd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var ud=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var fd=[["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 md=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var gd=[["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 hd=[["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 yd=[["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 bd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var xd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var vd=[["path",{d:"M20 6 9 17l-5-5"}]];var Cd=[["path",{d:"m6 9 6 6 6-6"}]];var wd=[["path",{d:"m15 18-6-6 6-6"}]];var Ad=[["path",{d:"m9 18 6-6-6-6"}]];var Sd=[["path",{d:"m18 15-6-6-6 6"}]];var ti=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var oi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Td=[["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 Md=[["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 Ed=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var ri=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var kd=[["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 Ld=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Pd=[["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 Rd=[["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 ni=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var ai=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Id=[["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 Bd=[["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 Hd=[["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 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"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var Dd=[["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 Fd=[["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 Od=[["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 Nd=[["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 _d=[["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 Ud=[["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 qd=[["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 Vd=[["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 si=[["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 zd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var $d=[["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 jd=[["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 Gd=[["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 Kd=[["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 Xd=[["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 ii=[["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 Jd=[["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 Qd=[["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 Yd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Zd=[["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 ec=[["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 li=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var tc=[["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 oc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var rc=[["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 nc=[["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 ac=[["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 sc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var ic=[["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 lc=[["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 dc=[["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 cc=[["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 pc=[["path",{d:"M5 12h14"}]];var uc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var fc=[["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 mc=[["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 gc=[["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 hc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var yc=[["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 bc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var xc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var vc=[["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 Cc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var wc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var Ac=[["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 Sc=[["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 Tc=[["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 Mc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Ec=[["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 kc=[["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 Lc=[["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 Pc=[["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 Rc=[["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 di=[["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 Ic=[["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 Bc=[["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 Hc=[["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 Wc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var ci=[["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 Dc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Fc=[["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 Oc=[["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 Nc=[["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 _c=[["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 Uc=[["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"}],["path",{d:"M17 14V2"}]];var qc=[["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"}],["path",{d:"M7 10v12"}]];var Vc=[["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 zc=[["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 $c=[["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 pi=[["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 jc=[["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 Gc=[["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 Kc=[["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 Xc=[["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 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"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Qc=[["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 Yc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Zc=[["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 bb={activity:ad,"arrow-down":sd,"arrow-up":cd,"arrow-up-right":dd,bot:gd,"chevron-down":Cd,"chevron-up":Sd,"chevron-right":Ad,"chevron-left":wd,check:vd,clipboard:Md,"clipboard-copy":Td,"code-xml":ri,copy:kd,file:Od,"file-code":Wd,"file-spreadsheet":Dd,"file-text":Fd,"image-plus":Jd,loader:tc,"loader-circle":li,mic:dc,paperclip:gc,"refresh-cw":Ac,search:Mc,send:Ec,"shield-alert":Pc,"shield-check":Rc,"shield-x":di,square:Dc,"thumbs-down":Uc,"thumbs-up":qc,upload:Gc,"volume-2":Xc,x:Yc,user:Kc,mail:rc,phone:xc,calendar:bd,clock:Ed,building:hd,"map-pin":nc,lock:oc,key:Zd,"credit-card":Ld,"at-sign":pd,hash:jd,globe:$d,link:ec,"circle-check":ti,"circle-x":oi,"triangle-alert":pi,info:Yd,ban:ud,shield:Ic,"arrow-left":id,"arrow-right":ld,"external-link":Bd,ellipsis:ai,"ellipsis-vertical":ni,menu:sc,house:ii,plus:Cc,minus:pc,pencil:yc,trash:$c,"trash-2":zc,save:Tc,download:Rd,share:Lc,funnel:si,settings:kc,"rotate-cw":Sc,maximize:ac,minimize:cc,"shopping-cart":Hc,"shopping-bag":Bc,package:mc,truck:jc,tag:_c,gift:zd,receipt:wc,wallet:Qc,store:Oc,"dollar-sign":Pd,percent:bc,play:vc,pause:hc,"volume-x":Jc,camera:xd,image:Qd,film:_d,headphones:Gd,"message-circle":ic,"message-square":lc,bell:fd,heart:Kd,star:Fc,eye:Hd,"eye-off":Id,bookmark:md,"calendar-days":yd,history:Xd,timer:Vc,folder:Vd,"folder-open":qd,files:Nd,sparkles:ci,zap:Zc,sun:Nc,moon:fc,flag:Ud,monitor:uc,smartphone:Wc},ne=(e,t=24,o="currentColor",r=2)=>{let n=bb[e];return n?xb(n,t,o,r):(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 xb(e,t,o,r){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",o),n.setAttribute("stroke-width",String(r)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],l=a[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(l).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),n.appendChild(p)}),n}var ui={allowedTypes:jo,maxFileSize:10*1024*1024,maxFiles:4};function vb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Cb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Zr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??ui.allowedTypes,maxFileSize:t.maxFileSize??ui.maxFileSize,maxFiles:t.maxFiles??ui.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ui.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=im(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let n=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,n);continue}try{let n=await sm(o),a=Ys(o)?URL.createObjectURL(o):null,s={id:vb(),file:o,previewUrl:a,contentPart:n};this.attachments.push(s),this.renderPreview(s)}catch(n){console.error("[AttachmentManager] Failed to process file:",n)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let r=this.attachments[o];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(o,1);let n=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=Ys(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",o&&t.previewUrl){let s=y("img");s.src=t.previewUrl,s.alt=t.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",r.appendChild(s)}else{let s=y("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 l=Cb(t.file.type),p=ne(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let d=y("span");d.textContent=lm(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),r.appendChild(s)}let n=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=ne("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(n),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o})}};var hm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ha(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[r,n]of Object.entries(t)){let a=o[r];hm(a)&&hm(n)?o[r]=Ha(a,n):o[r]=n}return o}var lo="min(440px, calc(100vw - 24px))",fi="440px",wb={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:lo,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)"},pt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:wb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",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 ym(e,t){if(!(!e&&!t))return e?t?Ha(e,t):e:t}function mi(e){return e?{...pt,...e,theme:ym(pt.theme,e.theme),darkTheme:ym(pt.darkTheme,e.darkTheme),launcher:{...pt.launcher,...e.launcher,dock:{...pt.launcher?.dock,...e.launcher?.dock},clearChat:{...pt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...pt.copy,...e.copy},sendButton:{...pt.sendButton,...e.sendButton},statusIndicator:{...pt.statusIndicator,...e.statusIndicator},voiceRecognition:{...pt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=pt.features?.artifacts,o=e.features?.artifacts,r=pt.features?.scrollToBottom,n=e.features?.scrollToBottom,a=pt.features?.scrollBehavior,s=e.features?.scrollBehavior,l=pt.features?.streamAnimation,p=e.features?.streamAnimation,d=pt.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&o===void 0?void 0:{...t,...o,layout:{...t?.layout,...o?.layout}},g=r===void 0&&n===void 0?void 0:{...r,...n},f=a===void 0&&s===void 0?void 0:{...a,...s},h=l===void 0&&p===void 0?void 0:{...l,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...pt.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??pt.suggestionChips,suggestionChipsConfig:{...pt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...pt.layout,...e.layout,header:{...pt.layout?.header,...e.layout?.header},messages:{...pt.layout?.messages,...e.layout?.messages,avatar:{...pt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...pt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...pt.layout?.slots,...e.layout?.slots}},markdown:{...pt.markdown,...e.markdown,options:{...pt.markdown?.options,...e.markdown?.options}},messageActions:{...pt.messageActions,...e.messageActions}}:pt}var gi="16px",hi="transparent",ep={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"}},tp={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"}},op={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:lo,maxWidth:fi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:gi,canvasBackground:hi},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",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 Jt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),r=e;for(let n of o){if(r==null)return;r=r[n]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Jt(e,r):r}function yi(e){let t={};function o(r,n){for(let[a,s]of Object.entries(r)){let l=`${n}.${a}`;if(typeof s=="string"){let p=Jt(e,s);p!==void 0&&(t[l]={path:l,value:p,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&o(s,l)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function rp(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function bm(e,t){let o={...e};for(let[r,n]of Object.entries(t)){let a=o[r];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?o[r]=bm(a,n):o[r]=n}return o}function Ab(e,t){return t?bm(e,t):e}function Bn(e,t={}){let o={palette:ep,semantic:tp,components:op},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:Ab(o.components,e?.components)};if(t.validate!==!1){let n=rp(r);if(!n.valid)throw new Error(`Theme validation failed: ${n.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let n of t.plugins)r=n.transform(r);return r}function bi(e){let t=yi(e),o={};for(let[w,F]of Object.entries(t)){let q=w.replace(/\./g,"-");o[`--persona-${q}`]=F.value}o["--persona-primary"]=o["--persona-semantic-colors-primary"]??o["--persona-palette-colors-primary-500"],o["--persona-secondary"]=o["--persona-semantic-colors-secondary"]??o["--persona-palette-colors-secondary-500"],o["--persona-accent"]=o["--persona-semantic-colors-accent"]??o["--persona-palette-colors-accent-500"],o["--persona-surface"]=o["--persona-semantic-colors-surface"]??o["--persona-palette-colors-gray-50"],o["--persona-background"]=o["--persona-semantic-colors-background"]??o["--persona-palette-colors-gray-50"],o["--persona-container"]=o["--persona-semantic-colors-container"]??o["--persona-palette-colors-gray-100"],o["--persona-text"]=o["--persona-semantic-colors-text"]??o["--persona-palette-colors-gray-900"],o["--persona-text-muted"]=o["--persona-semantic-colors-text-muted"]??o["--persona-palette-colors-gray-500"],o["--persona-text-inverse"]=o["--persona-semantic-colors-text-inverse"]??o["--persona-palette-colors-gray-50"],o["--persona-border"]=o["--persona-semantic-colors-border"]??o["--persona-palette-colors-gray-200"],o["--persona-divider"]=o["--persona-semantic-colors-divider"]??o["--persona-palette-colors-gray-200"],o["--persona-muted"]=o["--persona-text-muted"],o["--persona-voice-recording-indicator"]=o["--persona-components-voice-recording-indicator"]??o["--persona-palette-colors-error-500"],o["--persona-voice-recording-bg"]=o["--persona-components-voice-recording-background"]??o["--persona-palette-colors-error-50"],o["--persona-voice-processing-icon"]=o["--persona-components-voice-processing-icon"]??o["--persona-palette-colors-primary-500"],o["--persona-voice-speaking-icon"]=o["--persona-components-voice-speaking-icon"]??o["--persona-palette-colors-success-500"],o["--persona-approval-bg"]=o["--persona-components-approval-requested-background"]??o["--persona-surface"],o["--persona-approval-border"]=o["--persona-components-approval-requested-border"]??o["--persona-border"],o["--persona-approval-text"]=o["--persona-components-approval-requested-text"]??o["--persona-palette-colors-gray-900"],o["--persona-approval-shadow"]=o["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",o["--persona-approval-approve-bg"]=o["--persona-components-approval-approve-background"]??o["--persona-button-primary-bg"],o["--persona-approval-deny-bg"]=o["--persona-components-approval-deny-background"]??o["--persona-container"],o["--persona-attachment-image-bg"]=o["--persona-components-attachment-image-background"]??o["--persona-palette-colors-gray-100"],o["--persona-attachment-image-border"]=o["--persona-components-attachment-image-border"]??o["--persona-palette-colors-gray-200"],o["--persona-font-family"]=o["--persona-semantic-typography-fontFamily"]??o["--persona-palette-typography-fontFamily-sans"],o["--persona-font-size"]=o["--persona-semantic-typography-fontSize"]??o["--persona-palette-typography-fontSize-base"],o["--persona-font-weight"]=o["--persona-semantic-typography-fontWeight"]??o["--persona-palette-typography-fontWeight-normal"],o["--persona-line-height"]=o["--persona-semantic-typography-lineHeight"]??o["--persona-palette-typography-lineHeight-normal"],o["--persona-input-font-family"]=o["--persona-font-family"],o["--persona-input-font-weight"]=o["--persona-font-weight"],o["--persona-radius-sm"]=o["--persona-palette-radius-sm"]??"0.125rem",o["--persona-radius-md"]=o["--persona-palette-radius-md"]??"0.375rem",o["--persona-radius-lg"]=o["--persona-palette-radius-lg"]??"0.5rem",o["--persona-radius-xl"]=o["--persona-palette-radius-xl"]??"0.75rem",o["--persona-radius-full"]=o["--persona-palette-radius-full"]??"9999px",o["--persona-launcher-radius"]=o["--persona-components-launcher-borderRadius"]??o["--persona-palette-radius-full"]??"9999px",o["--persona-launcher-bg"]=o["--persona-components-launcher-background"]??o["--persona-primary"],o["--persona-launcher-fg"]=o["--persona-components-launcher-foreground"]??o["--persona-text-inverse"],o["--persona-launcher-border"]=o["--persona-components-launcher-border"]??o["--persona-border"],o["--persona-button-primary-bg"]=o["--persona-components-button-primary-background"]??o["--persona-primary"],o["--persona-button-primary-fg"]=o["--persona-components-button-primary-foreground"]??o["--persona-text-inverse"],o["--persona-button-radius"]=o["--persona-components-button-primary-borderRadius"]??o["--persona-palette-radius-full"]??"9999px",o["--persona-panel-radius"]=o["--persona-components-panel-borderRadius"]??o["--persona-radius-xl"]??"0.75rem",o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,o["--persona-panel-shadow"]=o["--persona-components-panel-shadow"]??o["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??gi,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??hi,o["--persona-launcher-shadow"]=o["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",o["--persona-input-radius"]=o["--persona-components-input-borderRadius"]??o["--persona-radius-lg"]??"0.5rem",o["--persona-message-user-radius"]=o["--persona-components-message-user-borderRadius"]??o["--persona-radius-lg"]??"0.5rem",o["--persona-message-assistant-radius"]=o["--persona-components-message-assistant-borderRadius"]??o["--persona-radius-lg"]??"0.5rem",o["--persona-header-bg"]=o["--persona-components-header-background"]??o["--persona-surface"],o["--persona-header-border"]=o["--persona-components-header-border"]??o["--persona-divider"],o["--persona-header-icon-bg"]=o["--persona-components-header-iconBackground"]??o["--persona-primary"],o["--persona-header-icon-fg"]=o["--persona-components-header-iconForeground"]??o["--persona-text-inverse"],o["--persona-header-title-fg"]=o["--persona-components-header-titleForeground"]??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitleForeground"]??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??o["--persona-muted"];let r=e.components?.header;r?.shadow&&(o["--persona-header-shadow"]=r.shadow),r?.borderBottom&&(o["--persona-header-border-bottom"]=r.borderBottom);let n=e.components?.introCard;o["--persona-intro-card-bg"]=o["--persona-components-introCard-background"]??o["--persona-surface"],o["--persona-intro-card-radius"]=o["--persona-components-introCard-borderRadius"]??"1rem",o["--persona-intro-card-padding"]=o["--persona-components-introCard-padding"]??"1.5rem",o["--persona-intro-card-shadow"]=n?.shadow??o["--persona-components-introCard-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",o["--persona-input-background"]=o["--persona-components-input-background"]??o["--persona-surface"],o["--persona-input-placeholder"]=o["--persona-components-input-placeholder"]??o["--persona-text-muted"],o["--persona-message-user-bg"]=o["--persona-components-message-user-background"]??o["--persona-accent"],o["--persona-message-user-text"]=o["--persona-components-message-user-text"]??o["--persona-text-inverse"],o["--persona-message-user-shadow"]=o["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",o["--persona-message-assistant-bg"]=o["--persona-components-message-assistant-background"]??o["--persona-surface"],o["--persona-message-assistant-text"]=o["--persona-components-message-assistant-text"]??o["--persona-text"],o["--persona-message-assistant-border"]=o["--persona-components-message-assistant-border"]??o["--persona-border"],o["--persona-message-assistant-shadow"]=o["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",o["--persona-scroll-to-bottom-bg"]=o["--persona-components-scrollToBottom-background"]??o["--persona-button-primary-bg"]??o["--persona-accent"],o["--persona-scroll-to-bottom-fg"]=o["--persona-components-scrollToBottom-foreground"]??o["--persona-button-primary-fg"]??o["--persona-text-inverse"],o["--persona-scroll-to-bottom-border"]=o["--persona-components-scrollToBottom-border"]??o["--persona-primary"],o["--persona-scroll-to-bottom-size"]=o["--persona-components-scrollToBottom-size"]??"40px",o["--persona-scroll-to-bottom-radius"]=o["--persona-components-scrollToBottom-borderRadius"]??o["--persona-button-radius"]??o["--persona-radius-full"]??"9999px",o["--persona-scroll-to-bottom-shadow"]=o["--persona-components-scrollToBottom-shadow"]??o["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",o["--persona-scroll-to-bottom-padding"]=o["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",o["--persona-scroll-to-bottom-gap"]=o["--persona-components-scrollToBottom-gap"]??"0.5rem",o["--persona-scroll-to-bottom-font-size"]=o["--persona-components-scrollToBottom-fontSize"]??o["--persona-palette-typography-fontSize-sm"]??"0.875rem",o["--persona-scroll-to-bottom-icon-size"]=o["--persona-components-scrollToBottom-iconSize"]??"14px",o["--persona-tool-bubble-shadow"]=o["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",o["--persona-reasoning-bubble-shadow"]=o["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",o["--persona-composer-shadow"]=o["--persona-components-composer-shadow"]??"none",o["--persona-md-inline-code-bg"]=o["--persona-components-markdown-inlineCode-background"]??o["--persona-container"],o["--persona-md-inline-code-color"]=o["--persona-components-markdown-inlineCode-foreground"]??o["--persona-text"],o["--persona-md-link-color"]=o["--persona-components-markdown-link-foreground"]??o["--persona-accent"]??"#0f0f0f";let a=o["--persona-components-markdown-heading-h1-fontSize"];a&&(o["--persona-md-h1-size"]=a);let s=o["--persona-components-markdown-heading-h1-fontWeight"];s&&(o["--persona-md-h1-weight"]=s);let l=o["--persona-components-markdown-heading-h2-fontSize"];l&&(o["--persona-md-h2-size"]=l);let p=o["--persona-components-markdown-heading-h2-fontWeight"];p&&(o["--persona-md-h2-weight"]=p);let d=o["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(o["--persona-md-prose-font-family"]=d),o["--persona-md-code-block-bg"]=o["--persona-components-markdown-codeBlock-background"]??o["--persona-container"],o["--persona-md-code-block-border-color"]=o["--persona-components-markdown-codeBlock-borderColor"]??o["--persona-border"],o["--persona-md-code-block-text-color"]=o["--persona-components-markdown-codeBlock-textColor"]??"inherit",o["--persona-md-table-header-bg"]=o["--persona-components-markdown-table-headerBackground"]??o["--persona-container"],o["--persona-md-table-border-color"]=o["--persona-components-markdown-table-borderColor"]??o["--persona-border"],o["--persona-md-hr-color"]=o["--persona-components-markdown-hr-color"]??o["--persona-divider"],o["--persona-md-blockquote-border-color"]=o["--persona-components-markdown-blockquote-borderColor"]??o["--persona-palette-colors-gray-900"],o["--persona-md-blockquote-bg"]=o["--persona-components-markdown-blockquote-background"]??"transparent",o["--persona-md-blockquote-text-color"]=o["--persona-components-markdown-blockquote-textColor"]??o["--persona-palette-colors-gray-500"],o["--cw-container"]=o["--persona-components-collapsibleWidget-container"]??o["--persona-surface"],o["--cw-surface"]=o["--persona-components-collapsibleWidget-surface"]??o["--persona-surface"],o["--cw-border"]=o["--persona-components-collapsibleWidget-border"]??o["--persona-border"],o["--persona-message-border"]=o["--persona-components-message-border"]??o["--persona-border"];let c=e.components,u=c?.iconButton;u&&(u.background&&(o["--persona-icon-btn-bg"]=u.background),u.border&&(o["--persona-icon-btn-border"]=u.border),u.color&&(o["--persona-icon-btn-color"]=u.color),u.padding&&(o["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(o["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(o["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(o["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(o["--persona-icon-btn-active-border"]=u.activeBorder));let g=c?.labelButton;g&&(g.background&&(o["--persona-label-btn-bg"]=g.background),g.border&&(o["--persona-label-btn-border"]=g.border),g.color&&(o["--persona-label-btn-color"]=g.color),g.padding&&(o["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(o["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(o["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(o["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(o["--persona-label-btn-gap"]=g.gap));let f=c?.toggleGroup;f&&(f.gap&&(o["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(o["--persona-toggle-group-radius"]=f.borderRadius));let h=c?.artifact;if(h?.toolbar){let w=h.toolbar;w.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=Jt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(h?.tab){let w=h.tab;w.background&&(o["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(o["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(o["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(o["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(o["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(o["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(o["--persona-artifact-tab-list-padding"]=w.listPadding)}if(h?.pane){let w=h.pane;if(w.toolbarBackground){let F=Jt(e,w.toolbarBackground)??w.toolbarBackground;o["--persona-artifact-toolbar-bg"]=F}}if(h?.card){let w=h.card;w.background&&(o["--persona-artifact-card-bg"]=w.background),w.border&&(o["--persona-artifact-card-border"]=w.border),w.borderRadius&&(o["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(h?.inline){let w=h.inline;w.background&&(o["--persona-artifact-inline-bg"]=Jt(e,w.background)??w.background),w.border&&(o["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(o["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=Jt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=Jt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(o["--persona-artifact-inline-title-color"]=Jt(e,w.titleColor)??w.titleColor),w.mutedColor&&(o["--persona-artifact-inline-muted-color"]=Jt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(o["--persona-artifact-inline-frame-height"]=w.frameHeight)}let C=c?.code;C&&(C.keywordColor&&(o["--persona-code-keyword-color"]=C.keywordColor),C.stringColor&&(o["--persona-code-string-color"]=C.stringColor),C.commentColor&&(o["--persona-code-comment-color"]=C.commentColor),C.numberColor&&(o["--persona-code-number-color"]=C.numberColor),C.tagColor&&(o["--persona-code-tag-color"]=C.tagColor),C.attrColor&&(o["--persona-code-attr-color"]=C.attrColor),C.propertyColor&&(o["--persona-code-property-color"]=C.propertyColor),C.lineNumberColor&&(o["--persona-code-line-number-color"]=C.lineNumberColor),C.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=C.gutterBorderColor),C.background&&(o["--persona-code-bg"]=Jt(e,C.background)??C.background));let M=o["--persona-surface"],L=o["--persona-container"],A=o["--persona-palette-colors-gray-100"]??"#f3f4f6",T=o["--persona-palette-colors-gray-200"]??"#e5e7eb",S=o["--persona-palette-colors-gray-300"]??"#d1d5db",E=!L||L===M,B=E?A:L,H=E?T:L;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??B,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??H,E&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??S),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??B,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??B,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??B,o}var xm={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","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var Sb={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"}}},vm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Wa=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Tb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Wa()},xi=e=>Tb(e),Mb=e=>Bn(e),Eb=e=>{let t=Bn(void 0,{validate:!1});return Bn({...e,palette:{...t.palette,colors:{...Sb.colors,...e?.palette?.colors}}},{validate:!1})},yr=e=>{let t=xi(e),o=vm(e?.theme),r=vm(e?.darkTheme);return t==="dark"?Eb(Ha(o??{},r??{})):Mb(o)},kb=e=>bi(e),en=(e,t)=>{let o=yr(t),r=kb(o);for(let[n,a]of Object.entries(r))e.style.setProperty(n,a);e.setAttribute("data-persona-color-scheme",xi(t))},Hn=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(Wa())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Wa());o.addEventListener?(o.addEventListener("change",r),t.push(()=>o.removeEventListener("change",r))):o.addListener&&(o.addListener(r),t.push(()=>o.removeListener(r)))}return()=>{t.forEach(o=>o())}};function Bo(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Cm(e){let t=Bo(e),o=t.lastIndexOf(".");return o<=0?"":t.slice(o+1).toLowerCase()}function vi(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
20
|
+
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let r=e.slice(t+1),n=r.lastIndexOf(`
|
|
21
|
+
`);return(n===-1?r:r.slice(0,n)).split("`\u200B``").join("```")}function Da(e){let t=Cm(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let o=(e.mimeType||"").toLowerCase();return o.includes("html")?"html":o.includes("svg")?"svg":o.includes("markdown")?"markdown":"other"}function br(e){switch(Da(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Cm(e.path);return t?t.toUpperCase():"File"}}}function wm(e){let t=e.markdown??"";return e.file?{filename:Bo(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:vi(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var np="http://www.w3.org/2000/svg";function Am(e){let t=document.createElementNS(np,"svg");t.setAttribute("class",Gr("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let o=document.createElementNS(np,"circle");o.setAttribute("class","persona-spinner-track"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9");let r=document.createElementNS(np,"circle");return r.setAttribute("class","persona-spinner-arc"),r.setAttribute("cx","12"),r.setAttribute("cy","12"),r.setAttribute("r","9"),t.appendChild(o),t.appendChild(r),t}var xr=(e,t,o)=>{let r=o;for(let n of t){let a=y("span","persona-tool-char");a.style.setProperty("--char-index",String(r)),a.textContent=n===" "?"\xA0":n,e.appendChild(a),r++}return r};function Sm(e,t,o){let r=o?.loadingAnimation??"shimmer",n=o?.loadingAnimationDuration??2e3;if(r==="none"){e.textContent=t;return}if(r==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${n}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${r}`),e.style.setProperty("--persona-tool-anim-duration",`${n}ms`),r==="shimmer-color"&&(o?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),xr(e,t,0)}var ap="persona-artifact-status-label",Tm="persona-artifact-status-detail",Mm="data-artifact-status-label",sp=new Map,Em=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Wn(e){e&&sp.delete(e)}function Lb(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?br(t):e.artifactType==="component"?"Component":"Document"}function Dn(e,t,o){let r=Lb(e),n=`Generating ${r.toLowerCase()}...`,a=t?.statusLabel;if(typeof a=="string")return{label:a};if(typeof a!="function")return{label:n};let s=e.id,l=sp.get(s);e.status!=="complete"&&l===void 0&&(l=Em(),sp.set(s,l));let p=l===void 0?0:Math.max(0,Em()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,g=d||c===""?0:c.split(`
|
|
22
|
+
`).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:r,file:f,chars:u,lines:g,elapsedMs:p,content:()=>d?"":c,surface:o};try{let C=a(h);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:n}}catch{return{label:n}}}function Pb(e){e.className=ap,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function tn(e,t,o){let r=e.querySelector(`:scope > .${ap}`);r||(r=y("span",ap),e.appendChild(r)),r.getAttribute(Mm)!==t.label&&(Pb(r),Sm(r,t.label,o),r.setAttribute(Mm,t.label));let n=e.querySelector(`:scope > .${Tm}`),a=t.detail;a?(n||(n=y("span",Tm),e.appendChild(n)),n.textContent!==a&&(n.textContent=a)):n&&n.remove()}var Rb={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},Ib=15e4,Ci={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Bb(e,t){let o=(e||"").trim().toLowerCase();if(o&&Ci[o])return Ci[o];if(t){let r=t.lastIndexOf(".");if(r>=0){let n=t.slice(r+1).toLowerCase();if(Ci[n])return Ci[n]}}return null}function wi(e,t){let o=[],r=0,n=0,a=s=>{s>n&&o.push({type:"plain",value:e.slice(n,s)})};for(;r<e.length;){let s=!1;for(let l of t){l.re.lastIndex=r;let p=l.re.exec(e);if(p&&p.index===r&&p[0].length>0){a(r);let d=l.map?l.map(p[0]):l.type;o.push({type:d,value:p[0]}),r+=p[0].length,n=r,s=!0;break}}s||(r+=1)}return a(e.length),o}var Hb=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Wb=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Hb.has(e)?"keyword":"plain"}];function km(e){return wi(e,Wb)}var Db=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Fb(e){let t=wi(e,Db);for(let o=0;o<t.length;o+=1){if(t[o].type!=="string")continue;let r=o+1;for(;r<t.length&&t[r].value.trim()==="";)r+=1;let n=t[r];n&&n.value.replace(/^\s*/,"").startsWith(":")&&(t[o].type="property")}return t}var Ob=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function Lm(e){let t=wi(e,Ob),o="";for(let r=0;r<t.length;r+=1){let n=t[r];if(n.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(n.value)){let s=r+1;for(;s<t.length&&t[s].value.trim()==="";)s+=1;let l=t[s];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(o===""||o==="{"||o==="}"||o===";"||o===",")&&(n.type="property")}let a=n.value.replace(/\s+$/,"");a&&(o=a[a.length-1])}return t}var Nb=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function _b(e){let t=[],o=(a,s)=>{s&&t.push({type:a,value:s})},r=e.length,n=0;for(;n<r;){if(e.startsWith("<!--",n)){let s=e.indexOf("-->",n+4),l=s===-1?r:s+3;o("comment",e.slice(n,l)),n=l;continue}if(e[n]==="<"&&e[n+1]==="!"){let s=e.indexOf(">",n),l=s===-1?r:s+1;o("tag",e.slice(n,l)),n=l;continue}if(e[n]==="<"&&/[A-Za-z/]/.test(e[n+1]||"")){let s=e.indexOf(">",n),l=s===-1?r:s+1,p=e.slice(n,l);for(let c of wi(p,Nb))t.push(c);n=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),g=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(n)),f=g?n+g.index:r,h=e.slice(n,f),C=c==="script"?km(h):Lm(h);for(let M of C)t.push(M);n=f}continue}let a=e.indexOf("<",n);if(a===n)o("plain",e[n]),n+=1;else{let s=a===-1?r:a;o("plain",e.slice(n,s)),n=s}}return t}function Ub(e,t){switch(t){case"html":return _b(e);case"css":return Lm(e);case"js":return km(e);case"json":return Fb(e)}}function qb(e){let t=Rf(),o=y("span","persona-code-line"),r=(n,a)=>{if(!a)return;let s=Rb[n];if(s){let l=y("span",s);l.textContent=a,o.appendChild(l)}else o.appendChild(document.createTextNode(a))};for(let n of e){let a=n.value.split(`
|
|
23
|
+
`);for(let s=0;s<a.length;s+=1)s>0&&(t.appendChild(o),t.appendChild(document.createTextNode(`
|
|
24
|
+
`)),o=y("span","persona-code-line")),r(n.type,a[s])}return o.childNodes.length>0?t.appendChild(o):t.lastChild||t.appendChild(o),t}function Pm(e,t,o){let r=e.length<=Ib?Bb(t,o):null,n=r?Ub(e,r):[{type:"plain",value:e}];return qb(n)}var Wt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,vr=zt+1;function Cr(e){let{items:t,onSelect:o,anchor:r,position:n="bottom-left",portal:a}=e,s=y("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(vr)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let M=document.createElement("hr");s.appendChild(M)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let M=ne(f.icon,16,"currentColor",1.5);M&&h.appendChild(M)}let C=document.createElement("span");C.textContent=f.label,h.appendChild(C),h.addEventListener("click",M=>{M.stopPropagation(),c(),o(f.id)}),s.appendChild(h)}let l=null;function p(){if(!a)return;let f=r.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,n==="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 d(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!s.contains(h.target)&&!r.contains(h.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){s.classList.add("persona-hidden"),l?.(),l=null}function u(){s.classList.contains("persona-hidden")?d():c()}function g(){c(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:c,toggle:u,destroy:g}}function kt(e){let{icon:t,label:o,size:r,strokeWidth:n,className:a,onClick:s,aria:l}=e,p=y("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",o),p.title=o;let d=ne(t,r??16,"currentColor",n??2);if(d&&p.appendChild(d),s&&p.addEventListener("click",s),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Go(e){let{icon:t,label:o,variant:r="default",size:n="sm",iconSize:a,className:s,onClick:l,aria:p}=e,d="persona-label-btn";r!=="default"&&(d+=" persona-label-btn--"+r),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let c=y("button",d);if(c.type="button",c.setAttribute("aria-label",o),t){let g=ne(t,a??14,"currentColor",2);g&&c.appendChild(g)}let u=y("span");if(u.textContent=o,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[g,f]of Object.entries(p))c.setAttribute(g,f);return c}function Fn(e){let{items:t,selectedId:o,onSelect:r,className:n}=e,a=y("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=o,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===s?"true":"false")}for(let c of t){let u;c.icon?u=kt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{s=c.id,p(),r(c.id)}}):(u=y("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{s=c.id,p(),r(c.id)})),u.setAttribute("aria-pressed",c.id===s?"true":"false"),l.push({id:c.id,btn:u}),a.appendChild(u)}function d(c){s=c,p()}return{element:a,setSelected:d}}function Ai(e){let{label:t,icon:o="chevron-down",menuItems:r,onSelect:n,position:a="bottom-left",portal:s,className:l,hover:p}=e,d=y("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=y("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ne(o,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let g=Cr({items:r,onSelect:f=>{d.setAttribute("aria-expanded","false"),n(f)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",f=>{f.stopPropagation();let h=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),g.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let f=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var Si="persona-artifact-custom-action-btn";function On(e,t){let o=t?.documentChrome??!1,r;if(typeof e.icon=="function"){if(e.showLabel){let n="persona-label-btn persona-label-btn--sm "+Si+(o?" persona-artifact-doc-copy-btn":"");r=y("button",n)}else{let n="persona-icon-btn "+Si+(o?" persona-artifact-doc-icon-btn":"");r=y("button",n)}r.type="button",r.setAttribute("aria-label",e.label),r.title=e.label;try{let n=e.icon();n&&r.appendChild(n)}catch{}if(e.showLabel){let n=y("span");n.textContent=e.label,r.appendChild(n)}}else e.showLabel||!e.icon?r=Go({icon:e.icon,label:e.label,className:Si+(o?" persona-artifact-doc-copy-btn":"")}):r=kt({icon:e.icon,label:e.label,className:Si+(o?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&r.addEventListener("click",t.onClick),r}function Fa(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Rm(e,t){let o=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=o?Bo(o.path):r,a=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=o?br(o):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${n} in artifact panel`),a&&d.setAttribute("data-open-artifact",a);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=n;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let h=t?.config?.features?.artifacts,C={id:a,artifactType:l==="component"?"component":"markdown",title:r,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...o?{file:o}:{}},M=Dn(C,h,"card");tn(f,M,h)}else a&&Wn(a),f.textContent=p;if(u.append(g,f),d.append(c,u),s==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let M={artifactId:a||null,title:n,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:o};for(let L of h)try{if(L.visible===void 0||L.visible(M)){let A=On(L);A.setAttribute("data-artifact-custom-action",L.id),A.className=`${A.className} persona-flex-shrink-0`,d.append(A)}}catch{}}let C=Go({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${n}`,C.setAttribute("data-download-artifact",a),d.append(C)}return d}var Ti=(e,t)=>{let o=t?.config?.features?.artifacts?.renderCard;if(o){let r=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",l=o({artifact:{artifactId:n,title:r,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Rm(e,t)});if(l)return l}return Rm(e,t)};var wr=new WeakMap;function ip(e,t,o){if(t.length===0)return;let r=new Map(t.map(n=>[n.id,n]));e.querySelectorAll("[data-artifact-inline]").forEach(n=>{let a=wr.get(n);if(!a)return;let s=r.get(n.getAttribute("data-artifact-inline")??"");s&&a(s,o)})}function Dm(e){return wr.has(e)}function Vb(e){let t=typeof e.artifactId=="string"?e.artifactId:"",o=typeof e.title=="string"&&e.title?e.title:void 0,r=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let a=e.componentProps,s=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:o,status:r,component:typeof e.component=="string"?e.component:"",props:s}}let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:o,status:r,markdown:typeof e.markdown=="string"?e.markdown:"",...n?{file:n}:{}}}function Im(e){let t=e.artifactType==="markdown"?e.file:void 0,o=t?Bo(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",r=t?br(t):e.artifactType==="component"?"Component":"Document";return{title:o,typeLabel:r}}function zb(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Bm=180,$b=240,jb=.8,Gb=300,Kb=500,Xb="cubic-bezier(0.2, 0, 0, 1)",Hm=240,Jb=.35;function Qb(e,t,o){let{swap:r,onSettled:n}=o,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!="function"){r(),n();return}e.style.height=`${t}px`,e.style.overflow="hidden";let s=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&s.push(l.animate([{opacity:1},{opacity:0}],{duration:Bm,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of s)L.cancel();r();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),n();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),n();return}let d=Math.abs(t-p),c=Math.round(Math.min(Kb,Math.max(Gb,$b+d*jb))),u=Math.round(c*Jb),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:Hm,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:Xb});e.style.height=`${p}px`;let C=!1,M=()=>{C||(C=!0,l(),n())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(c,u+Hm)+120)},Bm)}function Yb(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let o=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:o?.showCopy!==!1,showExpand:o?.showExpand!==!1,showViewToggle:o?.showViewToggle!==!1}}var Oa="--persona-artifact-inline-body-height";function Zb(e){let t=e?.inlineBody,o=t?.streamingView==="status"?"status":"source",r=t?.viewMode==="source"?"source":"rendered",n=320,a=320,s=t?.height;typeof s=="number"||s==="auto"?(n=s,a=s):s&&typeof s=="object"&&(n=s.streaming??320,a=s.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let g=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:o,viewMode:r,streamingHeight:n,completeHeight:a,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:g,completeDisplay:f}}function Wm(e,t){let o=Vb(e),r=t.config?.features?.artifacts,{chromeEnabled:n,showCopy:a,showExpand:s,showViewToggle:l}=Yb(r),p=r?.inlineActions??[],d=Zb(r),c=d.completeDisplay==="card",u=null,g=o,f=y("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),o.id&&f.setAttribute("data-artifact-inline",o.id);let h=Y=>Ti(zb(Y),t),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Oa),f.replaceChildren(h(Y)),wr.set(f,de=>{f.replaceChildren(h(de))})};if(c&&o.status==="complete")return C(o),f;let M=Mi(o,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),L=y("div","persona-artifact-inline-body");L.appendChild(M.el);let A=Y=>{let de=Y.status!=="complete",ee=de?d.streamingHeight:d.completeHeight,Ce=typeof ee=="number";Ce?f.style.setProperty(Oa,`${ee}px`):f.style.removeProperty(Oa);let Ae=!!M.el.querySelector(".persona-code-pre"),be=!!M.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",Ae),L.classList.toggle("persona-artifact-inline-body--sized",Ce&&be),L.classList.toggle("persona-artifact-inline-body--cap",!de&&!be&&typeof d.completeHeight=="number")},T=o.status,S=(Y,de)=>{T!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(Oa,`${d.completeHeight}px`):f.style.removeProperty(Oa),Om(L,de?.suppressTransition?"none":d.transition,Y.id,()=>{M.update(Y),A(Y)})):M.update(Y),A(Y),T=Y.status};A(o);let E=d.overflow==="clip"&&s&&!!o.id;if(E&&(L.setAttribute("data-expand-artifact-inline",o.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${Im(o).title} in panel`)),!n)return f.appendChild(L),wr.set(f,S),f;let B=y("div","persona-artifact-inline-chrome");B.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let H=y("div","persona-artifact-inline-chrome-lead"),w=y("span","persona-flex persona-items-center persona-flex-shrink-0"),F=ne("file-text",16,"currentColor",2);F&&w.appendChild(F);let q=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=y("span","persona-artifact-inline-type");H.append(w,q,O);let z=y("div","persona-artifact-inline-chrome-actions"),le=y("span","persona-flex persona-items-center persona-gap-1"),ue=()=>u??d.viewMode,Ee=l?Fn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ue(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let de=Y==="source"?"source":"rendered";de!==ue()&&(u=de,M.update(g),A(g))}}):null,De=a?kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;De&&o.id&&De.setAttribute("data-copy-artifact",o.id);let se=s?kt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&o.id&&se.setAttribute("data-expand-artifact-inline",o.id),z.appendChild(le),Ee&&z.appendChild(Ee.element),De&&z.appendChild(De),se&&z.appendChild(se),B.append(H,z),f.append(B,L);let xe=Y=>{let{title:de,typeLabel:ee}=Im(Y);q.textContent=de,q.title=de,E&&L.setAttribute("aria-label",`Open ${de} in panel`);let Ce=Y.status!=="complete";if(Ce){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let Ae=Dn(Y,r,"inline-chrome");tn(O,Ae,r)}else Wn(Y.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=ee;if(De&&De.classList.toggle("persona-hidden",Ce),Ee){let Ae=Y.artifactType==="markdown"?Y.file:void 0,be=!1;if(!Ce&&Ae&&d.viewMode!=="source"){let He=Da(Ae);He==="markdown"?be=!0:(He==="html"||He==="svg")&&(be=r?.filePreview?.enabled!==!1)}Ee.element.classList.toggle("persona-hidden",!be),Ee.setSelected(ue())}if(le.replaceChildren(),!Ce&&p.length>0){let Ae=Fa(Y);if(Ae)for(let be of p)try{if(be.visible===void 0||be.visible(Ae)){let He=On(be,{documentChrome:!0});He.setAttribute("data-artifact-custom-action",be.id),He.classList.add("persona-flex-shrink-0"),le.appendChild(He)}}catch{}}};return xe(o),wr.set(f,(Y,de)=>{if(c&&T!=="complete"&&Y.status==="complete"){let ee=f.isConnected?f.getBoundingClientRect().height:0;T="complete";let Ce=Y,Ae=!1,be=He=>{Ce=He,Ae=!0};wr.set(f,be),Qb(f,ee,{swap:()=>{C(Ce),Ae=!1,wr.set(f,be)},onSettled:()=>{Ae?C(Ce):wr.set(f,He=>{f.replaceChildren(h(He))})}});return}(Y.status!=="complete"||Y.id!==g.id)&&(u=null),g=Y,S(Y,de),xe(Y)}),f}var Fm=(e,t)=>{let o=t?.config?.features?.artifacts?.renderInline;if(o){let r=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",l=o({artifact:{artifactId:n,title:r,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Wm(e,t)});if(l)return l}return Wm(e,t)};var lp=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),r?this.options.set(t,r):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,r])=>{this.register(o,r)})}},Mo=new lp;Mo.register("PersonaArtifactCard",Ti,{bubbleChrome:!1});Mo.register("PersonaArtifactInline",Fm,{bubbleChrome:!1});function Na(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?vi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var dp=!1;function ex(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Om(e,t,o,r){let n=typeof document<"u"?document.startViewTransition:void 0,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(t!=="auto"||!e||typeof n!="function"||dp||a){r();return}dp=!0;let s=ex(o);e.style.setProperty("view-transition-name",s);let l=()=>{dp=!1,e.style.removeProperty("view-transition-name")};try{n.call(document,()=>{r()}).finished.then(l,l)}catch{l(),r()}}var tx="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",ox="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function rx(e){let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),o=y("div","persona-font-semibold persona-text-sm persona-mb-2");o.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(o),t.appendChild(r),t}function nx(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var ax=220;function sx(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function ix(e){return`
|
|
25
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function lx(e,t,o){let r=y("div","persona-artifact-frame-loading");if(o.renderIndicator)try{let s=o.renderIndicator({artifactId:e,config:t});if(s)return r.appendChild(s),{el:r,revealLabel:()=>{}}}catch{}let n=y("div","persona-artifact-frame-loading-indicator");n.appendChild(Am());let a=null;return o.label!==!1&&(a=y("div","persona-artifact-frame-loading-text"),a.textContent=o.label,n.appendChild(a)),r.appendChild(n),{el:r,revealLabel:()=>{a&&a.classList.add("persona-artifact-frame-loading-text--visible")}}}function dx(e,t,o,r,n,a){let s=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(T=>clearTimeout(T)),d.clear()},u=(T,S)=>{let E=setTimeout(()=>{d.delete(E),T()},S);d.add(E)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let T=lx(n,a,r);s=T.el,e.appendChild(s),l=Date.now(),r.label!==!1&&u(T.revealLabel,r.labelDelayMs)},h=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),u(g,ax))},C=()=>{o!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",A)},M=()=>{if(p||(p=!0,C(),c(),!s))return;let T=Math.max(0,r.minVisibleMs-(Date.now()-l));T>0?u(h,T):h()};function L(T){if(o===null)return;let S=T.data;!S||S.persona!=="artifact-preview-ready"||S.token!==o||T.source===t.contentWindow&&M()}function A(){let T=S=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>S()):setTimeout(S,0)};T(()=>T(()=>M()))}return u(f,r.delayMs),u(M,r.timeoutMs),o!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",A),()=>{p=!0,c(),C(),g()}}function Mi(e,t){let{config:o}=t,r=t.registry??Mo,n=t.bodyLayout,a=o.markdown?$r(o.markdown):null,s=Sn(o.sanitize),l=e,p=!1,d=se=>{let xe=qo()!==null;a&&!xe&&!p&&(p=!0,An(()=>De(l)));let Y=a?a(se):Ro(se);return a&&xe&&s?s(Y):Y},c=y("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},C=null,M=null,L=null,A=!1,T=()=>{C=null,M=null,L=null,A=!1},S=null,E=null,B=()=>{S=null,E=null},H=40,w=0,F=se=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>se()):setTimeout(se,0),q=se=>se.scrollHeight-se.clientHeight-se.scrollTop<=H,O=se=>{if(!n)return;let xe=se.scrollHeight-se.clientHeight>1,Y=se.scrollHeight-se.clientHeight-se.scrollTop;se.classList.toggle("persona-artifact-fade-top",n.fadeTop&&xe&&se.scrollTop>1),se.classList.toggle("persona-artifact-fade-bottom",n.fadeBottom&&xe&&Y>1)},z=se=>{w||(w=F(()=>{w=0,se.scrollTop=se.scrollHeight,O(se)}))},le=(se,xe,Y,de)=>{let ee=!!n,Ce=Y.id+"|"+(ee?"w":"p");if(!C||L!==Ce||C.parentElement!==c){h(),B(),c.replaceChildren();let He=y("pre",tx+" persona-code-pre"),Oe=y("code","persona-code");if(He.appendChild(Oe),ee){let Ke=y("div","persona-artifact-source-window");if(Ke.appendChild(He),c.appendChild(Ke),!(n?.overflow==="clip")&&typeof Ke.addEventListener=="function"){let ke=()=>Ke.scrollHeight-Ke.clientHeight>1;Ke.addEventListener("scroll",()=>{q(Ke)&&(A=!1),O(Ke)},{passive:!0}),Ke.addEventListener("wheel",Re=>{ke()&&Re.deltaY<0&&(A=!0)},{passive:!0}),Ke.addEventListener("touchmove",()=>{ke()&&(A=!0)},{passive:!0})}C=Ke}else c.appendChild(He),C=He;M=Oe,L=Ce}let Ae=ee?C:null;Ae&&(Ae.classList.toggle("persona-artifact-source-window--fixed",de),Ae.classList.toggle("persona-artifact-source-window--clip",de&&n?.overflow==="clip"));let be=Ae?q(Ae):!0;if(M.replaceChildren(Pm(se,xe?.language,xe?.path)),Ae){let He=Y.status!=="complete";de&&He&&n?.followOutput&&!A&&be?z(Ae):He||(A=!1),O(Ae)}},ue=se=>{h(),T(),B(),c.replaceChildren();let xe=y("div",ox);xe.innerHTML=d(se),c.appendChild(xe)},Ee=se=>{let xe=se.id,Y=o.features?.artifacts,de=Dn(se,Y,"status-body");if(S&&E===xe&&S.parentElement===c){let Ae=S.querySelector(".persona-artifact-status-view-text");Ae&&tn(Ae,de,Y);return}h(),T(),c.replaceChildren();let ee=y("div","persona-artifact-status-view"),Ce=y("div","persona-artifact-status-view-text");tn(Ce,de,Y),ee.appendChild(Ce),c.appendChild(ee),S=ee,E=xe},De=se=>{l=se;let xe=t.resolveViewMode?.(se)??n?.viewMode??"rendered",Y=se.artifactType==="markdown"?se.file:void 0,de=se.status!=="complete";de||Wn(se.id);let ee=de?n?.streamingHeight:n?.completeHeight,Ce=!!n&&typeof ee=="number";if(n?.streamingView==="status"&&de){Ee(se);return}if(Y){let be=vi(se.markdown??""),He=Da(Y),Oe=o.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&xe==="rendered"&&Oe&&(He==="html"||He==="svg")){let Ue=se.id+"\0"+be;if(u&&g===Ue&&u.parentElement===c)return;T(),B(),h(),c.replaceChildren();let ke=o.features?.artifacts?.filePreview,Re=ke?.iframeSandbox??"allow-scripts";!ke?.dangerouslyAllowSameOrigin&&Re.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Re=Re.split(/\s+/).filter(Lt=>Lt&&Lt!=="allow-same-origin").join(" "));let it=nx(ke?.loading),Ne=y("div","persona-artifact-frame"),Je=y("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",Re),Je.setAttribute("data-artifact-id",se.id);let po=null;it.enabled&&it.injectReadySignal?(po=sx(),Je.srcdoc=be+ix(po)):Je.srcdoc=be,Ne.appendChild(Je),c.appendChild(Ne),it.enabled&&(f=dx(Ne,Je,po,it,se.id,o)),u=Ne,g=Ue;return}if(h(),!de&&He==="markdown"&&xe==="rendered"){ue(be);return}le(be,{language:Y.language,path:Y.path},se,Ce);return}if(se.artifactType==="markdown"){if(xe==="source"){h(),le(se.markdown??"",void 0,se,Ce);return}ue(se.markdown??"");return}h(),T(),B(),c.replaceChildren();let Ae=se.component?r.get(se.component):void 0;if(Ae){let He={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:o,updateProps:()=>{}};try{let Oe=Ae(se.props??{},He);if(Oe){c.appendChild(Oe);return}}catch{}}c.appendChild(rx(se))};return De(e),{el:c,update(se){De(se)}}}var Nm=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(g,f,h={}){g=c(g);let C=u(f),M=d(g,C,h),L=n(M,()=>l(M,g,C,A=>A.morphStyle==="innerHTML"?(a(A,g,C),Array.from(g.childNodes)):r(A,g,C)));return M.pantry.remove(),L}function r(g,f,h){let C=u(f);return a(g,C,h,f,f.nextSibling),Array.from(C.childNodes)}function n(g,f){if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:C,selectionStart:M,selectionEnd:L}=h,A=f();return C&&C!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${C}"]`),h?.focus()),h&&!h.selectionEnd&&L&&h.setSelectionRange(M,L),A}let a=(function(){function g(S,E,B,H=null,w=null){E instanceof HTMLTemplateElement&&B instanceof HTMLTemplateElement&&(E=E.content,B=B.content),H||(H=E.firstChild);for(let F of B.childNodes){if(H&&H!=w){let O=h(S,F,H,w);if(O){O!==H&&M(S,H,O),s(O,F,S),H=O.nextSibling;continue}}if(F instanceof Element){let O=F.getAttribute("id");if(S.persistentIds.has(O)){let z=L(E,O,H,S);s(z,F,S),H=z.nextSibling;continue}}let q=f(E,F,H,S);q&&(H=q.nextSibling)}for(;H&&H!=w;){let F=H;H=H.nextSibling,C(S,F)}}function f(S,E,B,H){if(H.callbacks.beforeNodeAdded(E)===!1)return null;if(H.idMap.has(E)){let w=document.createElement(E.tagName);return S.insertBefore(w,B),s(w,E,H),H.callbacks.afterNodeAdded(w),w}else{let w=document.importNode(E,!0);return S.insertBefore(w,B),H.callbacks.afterNodeAdded(w),w}}let h=(function(){function S(H,w,F,q){let O=null,z=w.nextSibling,le=0,ue=F;for(;ue&&ue!=q;){if(B(ue,w)){if(E(H,ue,w))return ue;O===null&&(H.idMap.has(ue)||(O=ue))}if(O===null&&z&&B(ue,z)&&(le++,z=z.nextSibling,le>=2&&(O=void 0)),H.activeElementAndParents.includes(ue))break;ue=ue.nextSibling}return O||null}function E(H,w,F){let q=H.idMap.get(w),O=H.idMap.get(F);if(!O||!q)return!1;for(let z of q)if(O.has(z))return!0;return!1}function B(H,w){let F=H,q=w;return F.nodeType===q.nodeType&&F.tagName===q.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===q.getAttribute?.("id"))}return S})();function C(S,E){if(S.idMap.has(E))T(S.pantry,E,null);else{if(S.callbacks.beforeNodeRemoved(E)===!1)return;E.parentNode?.removeChild(E),S.callbacks.afterNodeRemoved(E)}}function M(S,E,B){let H=E;for(;H&&H!==B;){let w=H;H=H.nextSibling,C(S,w)}return H}function L(S,E,B,H){let w=H.target.getAttribute?.("id")===E&&H.target||H.target.querySelector(`[id="${E}"]`)||H.pantry.querySelector(`[id="${E}"]`);return A(w,H),T(S,w,B),w}function A(S,E){let B=S.getAttribute("id");for(;S=S.parentNode;){let H=E.idMap.get(S);H&&(H.delete(B),H.size||E.idMap.delete(S))}}function T(S,E,B){if(S.moveBefore)try{S.moveBefore(E,B)}catch{S.insertBefore(E,B)}else S.insertBefore(E,B)}return g})(),s=(function(){function g(A,T,S){return S.ignoreActive&&A===document.activeElement?null:(S.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&S.head.ignore||(A instanceof HTMLHeadElement&&S.head.style!=="morph"?p(A,T,S):(f(A,T,S),L(A,S)||a(S,A,T))),S.callbacks.afterNodeMorphed(A,T)),A)}function f(A,T,S){let E=T.nodeType;if(E===1){let B=A,H=T,w=B.attributes,F=H.attributes;for(let q of F)M(q.name,B,"update",S)||B.getAttribute(q.name)!==q.value&&B.setAttribute(q.name,q.value);for(let q=w.length-1;0<=q;q--){let O=w[q];if(O&&!H.hasAttribute(O.name)){if(M(O.name,B,"remove",S))continue;B.removeAttribute(O.name)}}L(B,S)||h(B,H,S)}(E===8||E===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function h(A,T,S){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let E=T.value,B=A.value;C(A,T,"checked",S),C(A,T,"disabled",S),T.hasAttribute("value")?B!==E&&(M("value",A,"update",S)||(A.setAttribute("value",E),A.value=E)):M("value",A,"remove",S)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)C(A,T,"selected",S);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let E=T.value,B=A.value;if(M("value",A,"update",S))return;E!==B&&(A.value=E),A.firstChild&&A.firstChild.nodeValue!==E&&(A.firstChild.nodeValue=E)}}function C(A,T,S,E){let B=T[S],H=A[S];if(B!==H){let w=M(S,A,"update",E);w||(A[S]=T[S]),B?w||A.setAttribute(S,""):M(S,A,"remove",E)||A.removeAttribute(S)}}function M(A,T,S,E){return A==="value"&&E.ignoreActiveValue&&T===document.activeElement?!0:E.callbacks.beforeAttributeUpdated(A,T,S)===!1}function L(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function l(g,f,h,C){if(g.head.block){let M=f.querySelector("head"),L=h.querySelector("head");if(M&&L){let A=p(M,L,g);return Promise.all(A).then(()=>{let T=Object.assign(g,{head:{block:!1,ignore:!0}});return C(T)})}}return C(g)}function p(g,f,h){let C=[],M=[],L=[],A=[],T=new Map;for(let E of f.children)T.set(E.outerHTML,E);for(let E of g.children){let B=T.has(E.outerHTML),H=h.head.shouldReAppend(E),w=h.head.shouldPreserve(E);B||w?H?M.push(E):(T.delete(E.outerHTML),L.push(E)):h.head.style==="append"?H&&(M.push(E),A.push(E)):h.head.shouldRemove(E)!==!1&&M.push(E)}A.push(...T.values());let S=[];for(let E of A){let B=document.createRange().createContextualFragment(E.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(B)!==!1){if("href"in B&&B.href||"src"in B&&B.src){let H,w=new Promise(function(F){H=F});B.addEventListener("load",function(){H()}),S.push(w)}g.appendChild(B),h.callbacks.afterNodeAdded(B),C.push(B)}}for(let E of M)h.callbacks.beforeNodeRemoved(E)!==!1&&(g.removeChild(E),h.callbacks.afterNodeRemoved(E));return h.head.afterHeadMorphed(g,{added:C,kept:L,removed:M}),S}let d=(function(){function g(S,E,B){let{persistentIds:H,idMap:w}=A(S,E),F=f(B),q=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(q))throw`Do not understand how to morph style ${q}`;return{target:S,newContent:E,config:F,morphStyle:q,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:w,persistentIds:H,pantry:h(),activeElementAndParents:C(S),callbacks:F.callbacks,head:F.head}}function f(S){let E=Object.assign({},t);return Object.assign(E,S),E.callbacks=Object.assign({},t.callbacks,S.callbacks),E.head=Object.assign({},t.head,S.head),E}function h(){let S=document.createElement("div");return S.hidden=!0,document.body.insertAdjacentElement("afterend",S),S}function C(S){let E=[],B=document.activeElement;if(B?.tagName!=="BODY"&&S.contains(B))for(;B&&(E.push(B),B!==S);)B=B.parentElement;return E}function M(S){let E=Array.from(S.querySelectorAll("[id]"));return S.getAttribute?.("id")&&E.push(S),E}function L(S,E,B,H){for(let w of H){let F=w.getAttribute("id");if(E.has(F)){let q=w;for(;q;){let O=S.get(q);if(O==null&&(O=new Set,S.set(q,O)),O.add(F),q===B)break;q=q.parentElement}}}}function A(S,E){let B=M(S),H=M(E),w=T(B,H),F=new Map;L(F,w,S,B);let q=E.__idiomorphRoot||E;return L(F,w,q,H),{persistentIds:w,idMap:F}}function T(S,E){let B=new Set,H=new Map;for(let{id:F,tagName:q}of S)H.has(F)?B.add(F):H.set(F,q);let w=new Set;for(let{id:F,tagName:q}of E)w.has(F)?B.add(F):H.get(F)===q&&w.add(F);for(let F of B)w.delete(F);return w}return g})(),{normalizeElement:c,normalizeParent:u}=(function(){let g=new WeakSet;function f(L){return L instanceof Document?L.documentElement:L}function h(L){if(L==null)return document.createElement("div");if(typeof L=="string")return h(M(L));if(g.has(L))return L;if(L instanceof Node){if(L.parentNode)return new C(L);{let A=document.createElement("div");return A.append(L),A}}else{let A=document.createElement("div");for(let T of[...L])A.append(T);return A}}class C{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,S)=>{if(S instanceof Element){S.matches(A)&&T.push(S);let E=S.querySelectorAll(A);for(let B=0;B<E.length;B++)T.push(E[B])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function M(L){let A=new DOMParser,T=L.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let S=A.parseFromString(L,"text/html");if(T.match(/<\/html>/))return g.add(S),S;{let E=S.firstChild;return E&&g.add(E),E}}else{let E=A.parseFromString("<body><template>"+L+"</template></body>","text/html").body.querySelector("template").content;return g.add(E),E}}return{normalizeElement:f,normalizeParent:h}})();return{morph:o,defaults:t}})();var Ei=(e,t,o={})=>{let{preserveTypingAnimation:r=!0}=o;Nm.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){if(n instanceof HTMLElement&&r){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===n.getAttribute("data-tool-elapsed")?!1:void 0;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let s=n.textContent??"",l=a.textContent??"";if(s!==l)return}return!1}}}}})};var _m=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ki={index:-1,draft:""};function Um(e){let{direction:t,history:o,currentValue:r,atStart:n,state:a}=e,s=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let l=o.length-1;return{handled:!0,value:o[l],state:{index:l,draft:r}}}if(a.index>0){let l=a.index-1;return{handled:!0,value:o[l],state:{index:l,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<o.length-1){let l=a.index+1;return{handled:!0,value:o[l],state:{index:l,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...ki}}}function qm(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Vm(){return new Map}function zm(e,t,o){let r=e.get(t);return r&&r.fingerprint===o?r.wrapper:null}function $m(e,t,o,r){e.set(t,{fingerprint:o,wrapper:r})}function jm(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function Li(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Ho(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ar(e,t){return Ho(e)-e.scrollTop<=t}function Pi(e){let{following:t,currentScrollTop:o,lastScrollTop:r,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=o-r;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:o}:!t&&n&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:o}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:o}:t&&p&&!n?{action:"pause",delta:c,nextLastScrollTop:o}:{action:"none",delta:c,nextLastScrollTop:o}}function Ri(e){let{following:t,deltaY:o,nearBottom:r=!1,resumeWhenNearBottom:n=!1}=e;return t&&o<0?"pause":!t&&n&&o>0&&r?"resume":"none"}function Gm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Km(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:o}}function Xm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var _a={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},cx=["pre","code","a","script","style"],Ii=e=>({type:e?.type??_a.type,placeholder:e?.placeholder??_a.placeholder,speed:e?.speed??_a.speed,duration:e?.duration??_a.duration,buffer:e?.buffer??_a.buffer}),Qm=[{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"}],Ua=new Map;for(let e of Qm)Ua.set(e.name,e);var on=e=>{Ua.set(e.name,e)},up=e=>{Qm.some(t=>t.name===e)||Ua.delete(e)},fp=()=>Array.from(Ua.keys()),Nn=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ua.get(e)??null,Bi=(e,t,o,r,n)=>{if(!n)return e;if(o?.bufferContent)return o.bufferContent(e,r);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
26
|
+
`);return a<0?"":e.slice(0,a)}return e},px=(e,t,o,r)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${o}-${r}`,n.style.setProperty("--char-index",String(r)),n.textContent=t,n},ux=(e,t,o,r)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${o}-${r}`,n.style.setProperty("--word-index",String(r)),n.textContent=t,n},cp=/\s/,fx=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let r=o;if(t.has(r.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},mx=(e,t,o)=>{let r=e.ownerDocument,n=e.parentNode;if(!r||!n)return;let a=e.nodeValue??"";if(!a)return;let s=r.createDocumentFragment(),l=0;for(;l<a.length;)if(cp.test(a[l])){let p=l;for(;p<a.length&&cp.test(a[p]);)p+=1;s.appendChild(r.createTextNode(a.slice(l,p))),l=p}else{let p=r.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<a.length&&!cp.test(a[d]);)p.appendChild(px(r,a[d],t,o.value)),o.value+=1,d+=1;s.appendChild(p),l=d}n.replaceChild(s,e)},gx=(e,t,o)=>{let r=e.ownerDocument,n=e.parentNode;if(!r||!n)return;let a=e.nodeValue??"";if(!a)return;let s=r.createDocumentFragment(),l=a.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?s.appendChild(r.createTextNode(p)):(s.appendChild(ux(r,p,t,o.value)),o.value+=1));n.replaceChild(s,e)},qa=(e,t,o,r)=>{if(!e||typeof document>"u")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set((r?.skipTags??cx).map(u=>u.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)fx(p,a)||l.push(p),p=s.nextNode();let d={value:r?.startIndex??0},c=t==="char"?mx:gx;for(let u of l)c(u,o,d);return n.innerHTML},Hi=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Va=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},Jm=new WeakMap,hx=(e,t)=>{if(!e.styles)return;let o=Jm.get(t);if(o||(o=new Set,Jm.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},pp=new WeakMap,yx=(e,t)=>{if(!e.onAttach)return;let o=pp.get(t);if(o||(o=new Map,pp.set(t,o)),o.has(e.name))return;let r=e.onAttach(t);o.set(e.name,r)},Ym=e=>{let t=pp.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Wi=(e,t)=>{hx(e,t),yx(e,t)};function mp(e,t=zt){let o=e.style.position,r=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=o),e.style.zIndex=r,e.style.isolation=n}}var za=0,Sr=null;function gp(e=document){if(za++,za===1){let o=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Sr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:n},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${n}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,za=Math.max(0,za-1),za===0&&Sr)){let o=e.body,r=e.defaultView??window;o.style.overflow=Sr.originalOverflow,o.style.position=Sr.originalPosition,o.style.top=Sr.originalTop,o.style.width=Sr.originalWidth,r.scrollTo(0,Sr.scrollY),Sr=null}}}var $a={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},It=e=>(e?.launcher?.mountMode??"floating")==="docked",Tr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",oo=e=>{let t=e?.launcher?.dock;return{side:t?.side??$a.side,width:t?.width??$a.width,animate:t?.animate??$a.animate,reveal:t?.reveal??$a.reveal,maxHeight:t?.maxHeight??$a.maxHeight}};var Eo={"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 bx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Di=(e,t={})=>{let{showClose:o=!0,wrapperClassName:r=bx,buttonSize:n,iconSize:a="28px"}=t,s=e?.launcher??{},l=n??s.closeButtonSize??"32px",p=y("div",r),d=s.closeButtonTooltipText??"Close chat",c=s.closeButtonShowTooltip??!0,u=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",f=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=rt("button",{className:Gr("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:o?void 0:"none",color:s.closeButtonColor||Qt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:f?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),C=ne(u,a,"currentColor",1);if(C?(C.style.display="block",h.appendChild(C)):h.textContent=g,p.appendChild(h),c&&d){let M=null,L=()=>{if(M)return;let T=h.ownerDocument,S=T.body;if(!S)return;M=Io(T,"div","persona-clear-chat-tooltip"),M.textContent=d;let E=Io(T,"div");E.className="persona-clear-chat-tooltip-arrow",M.appendChild(E);let B=h.getBoundingClientRect();M.style.position="fixed",M.style.zIndex=String(vr),M.style.left=`${B.left+B.width/2}px`,M.style.top=`${B.top-8}px`,M.style.transform="translate(-50%, -100%)",S.appendChild(M)},A=()=>{M&&M.parentNode&&(M.parentNode.removeChild(M),M=null)};p.addEventListener("mouseenter",L),p.addEventListener("mouseleave",A),h.addEventListener("focus",L),h.addEventListener("blur",A),p._cleanupTooltip=()=>{A(),p.removeEventListener("mouseenter",L),p.removeEventListener("mouseleave",A),h.removeEventListener("focus",L),h.removeEventListener("blur",A)}}return{button:h,wrapper:p}},xx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Fi=(e,t={})=>{let{wrapperClassName:o=xx,buttonSize:r,iconSize:n="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=r??s.size??"32px",p=s.iconName??"refresh-cw",d=s.iconColor??"",c=s.backgroundColor??"",u=s.borderWidth??"",g=s.borderColor??"",f=s.borderRadius??"",h=s.paddingX??"",C=s.paddingY??"",M=s.tooltipText??"Clear chat",L=s.showTooltip??!0,A=y("div",o),T=!!(u||g),S=rt("button",{className:Gr("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:l,width:l,color:d||Qt.actionIconColor,backgroundColor:c||void 0,border:T?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),E=ne(p,n,"currentColor",1);if(E&&(E.style.display="block",S.appendChild(E)),A.appendChild(S),L&&M){let B=null,H=()=>{if(B)return;let F=S.ownerDocument,q=F.body;if(!q)return;B=Io(F,"div","persona-clear-chat-tooltip"),B.textContent=M;let O=Io(F,"div");O.className="persona-clear-chat-tooltip-arrow",B.appendChild(O);let z=S.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(vr),B.style.left=`${z.left+z.width/2}px`,B.style.top=`${z.top-8}px`,B.style.transform="translate(-50%, -100%)",q.appendChild(B)},w=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};A.addEventListener("mouseenter",H),A.addEventListener("mouseleave",w),S.addEventListener("focus",H),S.addEventListener("blur",w),A._cleanupTooltip=()=>{w(),A.removeEventListener("mouseenter",H),A.removeEventListener("mouseleave",w),S.removeEventListener("focus",H),S.removeEventListener("blur",w)}}return{button:S,wrapper:A}};var Qt={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))"},Ko=e=>{let{config:t,showClose:o=!0}=e,r=rt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=t?.launcher??{},a=n.headerIconSize??"48px",s=n.closeButtonPlacement??"inline",l=n.headerIconHidden??!1,p=n.headerIconName,d=rt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let E=parseFloat(a)||24,B=ne(p,E*.6,"currentColor",1);B?d.replaceChildren(B):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let E=y("img");E.src=t.launcher.iconUrl,E.alt="",E.className="persona-rounded-xl persona-object-cover",E.style.height=a,E.style.width=a,d.replaceChildren(E)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=rt("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Qt.titleColor}}),g=rt("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Qt.subtitleColor}});c.append(u,g),l?r.append(c):r.append(d,c);let f=n.clearChat??{},h=f.enabled??!0,C=f.placement??"inline",M=null,L=null;if(h){let B=Fi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=B.button,L=B.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&r.appendChild(L)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:T,wrapper:S}=Di(t,{showClose:o,wrapperClassName:A});return s!=="top-right"&&r.appendChild(S),{header:r,iconHolder:d,headerTitle:u,headerSubtitle:g,closeButton:T,closeButtonWrapper:S,clearChatButton:M,clearChatButtonWrapper:L}},rn=(e,t,o)=>{let r=o?.launcher??{},n=r.closeButtonPlacement??"inline",a=r.clearChat?.placement??"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var hp=e=>{let t=Ko({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>o()),r.addEventListener("keydown",n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),o())}))}return t};function vx(e,t,o){if(t?.length)for(let r of t){let n=y("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(n.type="button",n.setAttribute("aria-label",r.ariaLabel??r.label??r.id),r.icon){let a=ne(r.icon,14,"currentColor",2);a&&n.appendChild(a)}else r.label&&(n.textContent=r.label);if(r.menuItems?.length){let a=y("div","persona-relative");a.appendChild(n);let s=Cr({items:r.menuItems,onSelect:l=>o?.(l),anchor:a,position:"bottom-left"});a.appendChild(s.element),n.addEventListener("click",l=>{l.stopPropagation(),s.toggle()}),e.appendChild(a)}else n.addEventListener("click",()=>o?.(r.id)),e.appendChild(n)}}var yp=e=>{let{config:t,showClose:o=!0,onClose:r,layoutHeaderConfig:n,onHeaderAction:a}=e,s=t?.launcher??{},l=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=n?.titleMenu,d,c;if(p)d=Ai({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Qt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=y("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Qt.titleColor,c.textContent=s.title??"Chat Assistant",d.appendChild(c),vx(d,n?.trailingActions,n?.onAction??a),n?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let T=n.onTitleClick;d.addEventListener("click",S=>{S.target.closest("button")||T()}),d.addEventListener("keydown",S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),T())})}let A=n?.titleRowHover;A&&(d.style.borderRadius=A.borderRadius??"10px",d.style.padding=A.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=A.background??"",d.style.borderColor=A.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=s.closeButtonSize??"32px",g=y("div",""),f=y("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=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=o?"":"none",f.style.color=s.closeButtonColor||Qt.actionIconColor;let h=s.closeButtonIconName??"x",C=ne(h,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),l.appendChild(g);let M=y("div");M.style.display="none";let L=y("span");return L.style.display="none",{header:l,iconHolder:M,headerTitle:c,headerSubtitle:L,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Oi={default:hp,minimal:yp},bp=e=>Oi[e]??Oi.default,_n=(e,t,o)=>{if(t?.render){let s=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=y("div");l.style.display="none";let p=y("span"),d=y("span"),c=y("button");c.style.display="none";let u=y("div");return u.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??"default",a=bp(r)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ni=e=>{let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=3,r=20;t.style.maxHeight=`${o*r}px`,t.style.overflowY="auto";let n=()=>{let s=parseFloat(t.style.maxHeight);return Number.isFinite(s)&&s>0?s:o*r},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let s=Math.min(t.scrollHeight,n());t.style.height=`${s}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},_i=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,r=t.iconText??"\u2191",n=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",g=t.backgroundColor,f=t.textColor,h=y("div","persona-send-button-wrapper"),C=rt("button",{className:Gr("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!g&&"persona-bg-persona-primary",!o&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:o?u:void 0,height:o?u:void 0,minWidth:o?u:void 0,minHeight:o?u:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:o&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=null,L=null;if(o){let E=parseFloat(u)||24,B=f?.trim()||"currentColor";n?(M=ne(n,E,B,2),M?C.appendChild(M):C.textContent=r):C.textContent=r,L=ne(a,E,B,2)}else C.textContent=p;let A=null;c&&s&&(A=y("div","persona-send-button-tooltip"),A.textContent=s,h.appendChild(A)),C.setAttribute("aria-label",s),h.appendChild(C);let T="send";return{button:C,wrapper:h,setMode:E=>{if(E===T)return;T=E;let B=E==="stop"?l:s;if(C.setAttribute("aria-label",B),A&&(A.textContent=B),o){if(M&&L){let H=E==="stop"?L:M;C.replaceChildren(H)}}else C.textContent=E==="stop"?d:p}}},Ui=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let r=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),n=t.provider?.type==="runtype";if(!(r||n))return null;let s=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??s,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,g=y("div","persona-send-button-wrapper"),f=rt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ne(l,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",g.appendChild(f);let M=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&M){let A=y("div","persona-send-button-tooltip");A.textContent=M,g.appendChild(A)}return{button:f,wrapper:g}},qi=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=e?.sendButton?.size??"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let n=y("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??jo).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=t.buttonIconName??"paperclip",s=o,l=parseFloat(s)||40,p=Math.round(l*.6),d=y("div","persona-send-button-wrapper"),c=rt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});c.addEventListener("mouseenter",()=>{c.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="transparent"});let u=ne(a,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",h=>{h.preventDefault(),n.click()}),d.appendChild(c);let g=t.buttonTooltipText??"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,d.appendChild(f),{button:c,wrapper:d,input:n,previewsContainer:r}},Vi=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let n=t.visible??!0;r.style.display=n?"":"none";let a=t.idleText??"Online";if(t.idleLink){let s=y("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,s.style.color="inherit",s.style.textDecoration="none",r.appendChild(s)}else r.textContent=a;return r},zi=()=>rt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Un=e=>{let{config:t}=e,o=rt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=zi(),n=rt("form",{className:"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",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=Ni(t);s();let l=_i(t),p=Ui(t),d=qi(t),c=Vi(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let u=rt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&g.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(g,f),n.append(u),n.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&a.focus()}),o.append(r,n,c),{footer:o,suggestions:r,composerForm:n,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};var Zm=()=>{let e=rt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),o=ne("message-square",16,"currentColor",1.5);o&&t.appendChild(o);let r=y("span","persona-pill-peek__text"),n=y("span","persona-pill-peek__caret"),a=ne("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,r,n),{root:e,textNode:r}},eg=e=>{let{config:t}=e,o=rt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=zi(),n=Vi(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=Ni(t);a.style.maxHeight="100px",s();let l=_i(t),p=Ui(t),d=qi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=rt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),c.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(u,a,g),d&&o.append(d.previewsContainer),o.append(r,c,n);let f=c;return{footer:o,suggestions:r,composerForm:c,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:n,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:l.setMode}};var tg=e=>{let t=e?.launcher?.enabled??!0,o=It(e);if(Tr(e)){let c=e?.launcher?.composerBar??{},u=y("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??zt);let g=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",u.appendChild(g);let f=y("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??zt),{wrapper:u,panel:g,pillRoot:f}}if(o){let c=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=e?.launcher?.width??"100%";return c.style.width=g,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let n=e?.launcher??{},a=n.position&&Eo[n.position]?Eo[n.position]:Eo["bottom-right"],s=y("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??zt);let l=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??lo;return l.style.width=d,l.style.maxWidth=d,s.appendChild(l),{wrapper:s,panel:l}},Cx=(e,t)=>{let o=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:n}=Di(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,s=null,l=null;if(a){let S=Fi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=S.button,l=S.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=rt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=rt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=rt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=rt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),g=rt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},c,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(g.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(g,f);let M=rt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),L=eg({config:e}),{root:A,textNode:T}=Zm();return o.append(p,n,d,M),l&&o.appendChild(l),{container:o,body:d,messagesWrapper:f,composerOverlay:M,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:c,introSubtitle:u,closeButton:r,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:p,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:A,peekTextNode:T}},og=(e,t=!0)=>{if(Tr(e))return Cx(e,t);let o=rt("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),r=e?.layout?.header,n=e?.layout?.showHeader!==!1,a=r?_n(e,r,{showClose:t}):Ko({config:e,showClose:t}),s=rt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let l=rt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=rt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=rt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:It(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},l,p),c=y("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,c);let f=Un({config:e}),h=e?.layout?.showFooter!==!1;n?rn(o,a,e):(a.header.style.display="none",rn(o,a,e)),o.append(s);let C=rt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),o.append(f.footer),o.append(C),{container:o,body:s,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,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 xp=(e,t)=>{let o=y("button");o.type="button",o.innerHTML=`
|
|
21
27
|
<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>
|
|
22
28
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
23
29
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -25,14 +31,14 @@ _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
25
31
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
26
32
|
</span>
|
|
27
33
|
<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>
|
|
28
|
-
`,r.addEventListener("click",t);let o=a=>{var T,y,w,v,M,H,I,P,B,O,Q,me,ue;let s=(T=a.launcher)!=null?T:{},i=nr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let Z=(y=s.title)!=null?y:"Chat Assistant";c.textContent=Z,c.setAttribute("title",Z)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Z=(w=s.subtitle)!=null?w:"Here to help you get answers fast";d.textContent=Z,d.setAttribute("title",Z)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let u=r.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let Z=(v=s.agentIconSize)!=null?v:"40px";if(u.style.height=Z,u.style.width=Z,s.agentIconBackgroundColor?(u.style.backgroundColor=s.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",s.agentIconName){let Le=parseFloat(Z)||24,We=he(s.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);We?(u.appendChild(We),u.style.display=""):(u.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",u.style.display="")}else s.iconUrl?u.style.display="none":(u.textContent=(H=s.agentIconText)!=null?H:"\u{1F4AC}",u.style.display="")}let g=r.querySelector("[data-role='launcher-image']");if(g){let Z=(I=s.agentIconSize)!=null?I:"40px";g.style.height=Z,g.style.width=Z,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let Z=(P=s.callToActionIconSize)!=null?P:"32px";f.style.height=Z,f.style.width=Z,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 Le=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,Le=(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 We=parseFloat(Z)||24,ie=Math.max(We-Le,8),Me=he(s.callToActionIconName,ie,"currentColor",2);Me?f.appendChild(Me):f.textContent=(B=s.callToActionIconText)!=null?B:"\u2197"}else f.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}let h=s.position&&wo[s.position]?wo[s.position]:wo["bottom-right"],b="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";r.className=i?k:`${b} ${h}`,i||(r.style.zIndex=String((Q=s.zIndex)!=null?Q:wr));let E="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(ue=s.collapsedMaxWidth)!=null?ue:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var tx=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Zh(e),a=ex(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:d,replaceHeader:g=>(c.element.replaceWith(g.header),c.element=g.header,c.iconHolder=g.iconHolder,c.headerTitle=g.headerTitle,c.headerSubtitle=g.headerSubtitle,c.closeButton=g.closeButton,c.closeButtonWrapper=g.closeButtonWrapper,c.clearChatButton=g.clearChatButton,c.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{d.footer.replaceWith(g),d.footer=g}}},dp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>lp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=lp(e,r);return{instance:n,element:n.element}};var Tv=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}},Ev=(e,t)=>{if(!e)return null;let r=Tv(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},kv=(e,t)=>{let r=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Lv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},cp=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},pp=320,ox=320,Pv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Rv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Iv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Hv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Wv=(e,t,r)=>{if(e.length===0)return null;try{let o=S("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var u;let d=S("img");d.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${pp}px`,d.style.maxHeight=`${ox}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;n+=1,d.addEventListener("error",()=>{p||(p=!0,n=Math.max(0,n-1),d.remove(),n===0&&s())}),d.addEventListener("load",()=>{p=!0}),Lv(i.image)?(d.src=i.image,o.appendChild(d)):(p=!0,n=Math.max(0,n-1),d.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},Bv=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!cp(o.audio))return;let n=S("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${pp}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Dv=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!cp(o.video))return;let n=S("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${pp}px`,n.style.maxHeight=`${ox}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Fv=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!cp(o.data))return;let n=S("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ua=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},up=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ua};if(t){let n=t(o);if(n!==null)return n}return ua()},Nv=(e,t)=>{let r=S("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=S("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},rx=(e,t,r="div")=>{let o=S(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Ov=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},fp=(e,t,r)=>{var h,b,k,E,A,T,y;let o=(h=t.showCopy)!=null?h:!0,n=(b=t.showUpvote)!=null?b:!0,a=(k=t.showDownvote)!=null?k:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let w=S("div");return w.style.display="none",w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id),w}let i=(A=t.visibility)!=null?A:"hover",c=(T=t.align)!=null?T:"right",d=(y=t.layout)!=null?y:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(w,v,M)=>{let H=pr({icon:w,label:v,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",M),H};return o&&g.appendChild(f("copy","Copy message","copy")),s&&g.appendChild(f("volume-2","Read aloud","read-aloud")),n&&g.appendChild(f("thumbs-up","Upvote","upvote")),a&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},$a=(e,t,r,o,n,a)=>{var oe,se,ge,Te,qe,j,ee,Ee,te,le,ke,nt,yt,Kt,jt,ct,fe;let s=r!=null?r:{},i=(oe=s.layout)!=null?oe:"bubble",c=s.avatar,d=s.timestamp,p=(se=c==null?void 0:c.show)!=null?se:!1,u=(ge=d==null?void 0:d.show)!=null?ge:!1,g=(Te=c==null?void 0:c.position)!=null?Te:"left",f=(qe=d==null?void 0:d.position)!=null?qe:"below",h=Ov(e.role,i),b=S("div",h.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=Pv(e),E=(ee=(j=e.content)==null?void 0:j.trim())!=null?ee:"",T=k.length>0&&E===yi,y=Vi((te=(Ee=a==null?void 0:a.widgetConfig)==null?void 0:Ee.features)==null?void 0:te.streamAnimation),w=(nt=(ke=(le=a==null?void 0:a.widgetConfig)==null?void 0:le.features)==null?void 0:ke.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&y.type!=="none"?qa(y.type,w):null,M=e.role==="assistant"&&((yt=v==null?void 0:v.isAnimating)==null?void 0:yt.call(v,e))===!0,H=e.role==="assistant"&&v!==null&&(!!e.streaming||M);H&&(v!=null&&v.bubbleClass)&&b.classList.add(v.bubbleClass);let I=document.createElement("div");I.classList.add("persona-message-content"),e.streaming&&I.classList.add("persona-content-streaming"),H&&v&&(v.containerClass&&I.classList.add(v.containerClass),I.style.setProperty("--persona-stream-step",`${y.speed}ms`),I.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let P=H?zi((Kt=e.content)!=null?Kt:"",y.buffer,v,e,!!e.streaming):(jt=e.content)!=null?jt:"",B=t({text:P,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=B;H&&(v==null?void 0:v.wrap)==="char"?O=Is(B,"char",e.id,{skipTags:v.skipTags}):H&&(v==null?void 0:v.wrap)==="word"&&(O=Is(B,"word",e.id,{skipTags:v.skipTags}));let Q=null;if(T?(Q=document.createElement("div"),Q.innerHTML=O,Q.style.display="none",I.appendChild(Q)):I.innerHTML=O,H&&(v!=null&&v.useCaret)&&!T&&E){let X=$i(),st=I.querySelectorAll(".persona-stream-char, .persona-stream-word"),je=st[st.length-1];if(je!=null&&je.parentNode)je.parentNode.insertBefore(X,je.nextSibling);else{let Ce=I.lastElementChild;Ce?Ce.appendChild(X):I.appendChild(X)}}if(u&&f==="inline"&&e.createdAt){let X=rx(e,d,"span");X.classList.add("persona-timestamp-inline");let st=I.lastElementChild;st?st.appendChild(X):I.appendChild(X)}if(k.length>0){let X=Wv(k,!T&&!!E,()=>{T&&Q&&(Q.style.display="")});X?b.appendChild(X):T&&Q&&(Q.style.display="")}let me=Rv(e);if(me.length>0){let X=Bv(me);X&&b.appendChild(X)}let ue=Iv(e);if(ue.length>0){let X=Dv(ue);X&&b.appendChild(X)}let Z=Hv(e);if(Z.length>0){let X=Fv(Z);X&&b.appendChild(X)}if(b.appendChild(I),u&&f==="below"&&e.createdAt){let X=rx(e,d);X.classList.add("persona-mt-1"),b.appendChild(X)}let Le=e.role==="assistant"?Ev(e.stopReason,(fe=(ct=a==null?void 0:a.widgetConfig)==null?void 0:ct.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(P&&P.trim()),st=y.placeholder==="skeleton",je=st&&y.buffer==="line"&&X;if(X)je&&b.appendChild(Hs());else if(st)b.appendChild(Hs());else{let Ce=up("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Ce&&b.appendChild(Ce)}}if(Le&&e.stopReason&&!e.streaming&&(E||(I.style.display="none"),b.appendChild(kv(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=fp(e,o,n);b.appendChild(X)}if(!p||e.role==="system")return b;let ie=S("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Me=Nv(c,e.role);return g==="right"||g==="left"&&e.role==="user"?ie.append(b,Me):ie.append(Me,b),b.classList.remove("persona-max-w-[85%]"),b.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ie},nx=(e,t,r,o,n,a)=>{let s=r!=null?r:{};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}):$a(e,t,r,o,n,a)};var ja=new Set,_v=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Uv=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
29
|
-
`):""},
|
|
30
|
-
`);let n=
|
|
31
|
-
`):""},gp=(e,t)=>{var r,o,n;e.style.backgroundColor=(r=t.codeBlockBackgroundColor)!=null?r:"var(--persona-container, #f3f4f6)",e.style.borderColor=(o=t.codeBlockBorderColor)!=null?o:"var(--persona-border, #e5e7eb)",e.style.color=(n=t.codeBlockTextColor)!=null?n:"var(--persona-text, #171717)"},zv=(e,t)=>{var p,u,g,f,h;let r=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,n=(u=o==null?void 0:o.collapsedMode)!=null?u:"tool-call",a=Vv(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),s=r?lh(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(f=t==null?void 0:t.toolCall)!=null?f:{},d=s;return n==="tool-name"?d=((h=r.name)==null?void 0:h.trim())||s:n==="tool-preview"&&a&&(d=a),i&&c.activeTextTemplate?d=Gl(r,c.activeTextTemplate,d):!i&&c.completeTextTemplate&&(d=Gl(r,c.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},sx=(e,t,r)=>{var p;let o=Ga.has(e),n=(p=r==null?void 0:r.toolCall)!=null?p:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),d=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let u=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",g=he(o?"chevron-up":"chevron-down",16,u,2);g?d.appendChild(g):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},hp=(e,t)=>{var O,Q,me,ue,Z,Le,We,ie,Me;let r=e.toolCall,o=(O=t==null?void 0:t.toolCall)!=null?O:{},n=S("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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(me=(Q=t==null?void 0:t.features)==null?void 0:Q.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Ga.has(e.id),{summary:c,previewText:d,isActive:p}=zv(e,t),u=S("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");u.type="button",s&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=S("div","persona-flex persona-flex-col persona-text-left"),f=S("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String((ue=r.startedAt)!=null?ue:Date.now()),b=()=>{let oe=S("span","");return oe.setAttribute("data-tool-elapsed",h),oe.textContent=Cs(r),oe},k=(Le=o.renderCollapsedSummary)==null?void 0:Le.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:d,collapsedMode:(Z=a.collapsedMode)!=null?Z:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Cs(r),createElapsedElement:b});typeof k=="string"&&k.trim()?(f.textContent=k,g.appendChild(f)):k instanceof HTMLElement?g.appendChild(k):(f.textContent=c,g.appendChild(f));let E=(We=a.loadingAnimation)!=null?We:"none",A=o.activeTextTemplate,T=o.completeTextTemplate,y=p?A:T,w=k instanceof HTMLElement,v=(oe,se,ge)=>{let Te=ge;for(let qe of se){let j=S("span","persona-tool-char");j.style.setProperty("--char-index",String(Te)),j.textContent=qe===" "?"\xA0":qe,oe.appendChild(j),Te++}return Te},M=(oe,se)=>{var j;f.textContent="";let ge=((j=r.name)==null?void 0:j.trim())||"tool",Te=ui(oe,ge),qe=0;for(let ee of Te){let Ee=ee.styles.length>0?(()=>{let te=S("span",ee.styles.map(le=>`persona-tool-text-${le}`).join(" "));return f.appendChild(te),te})():f;if(ee.isDuration&&p)Ee.appendChild(b());else{let te=ee.isDuration?Cs(r):ee.text;se?qe=v(Ee,te,qe):Ee.appendChild(document.createTextNode(te))}}};if(!w)if(p&&E!=="none"){let oe=(ie=o.loadingAnimationDuration)!=null?ie:2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),y&&M(y,!1);else if(f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)M(y,!0);else{let se=f.textContent||c;f.textContent="",v(f,se,0)}}else y&&M(y,!1);let H=null;if(s){H=S("div","persona-flex persona-items-center");let oe=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",se=he(i?"chevron-up":"chevron-down",16,oe,2);se?H.appendChild(se):H.textContent=i?"Hide":"Show";let ge=S("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ge.append(H),u.append(g,ge)}else u.append(g);let I=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","tool"),I.style.display="none",I.style.whiteSpace="pre-wrap",!i&&p&&a.activePreview&&d){let oe=(Me=o.renderCollapsedPreview)==null?void 0:Me.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:p,config:t!=null?t:{}});qv(I,oe)||(I.textContent=d),I.style.display=""}if(!i&&p&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(u,I),n;let P=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(P.style.display=i?"":"none",o.contentBackgroundColor&&(P.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(P.style.color=o.contentTextColor),o.contentPaddingX&&(P.style.paddingLeft=o.contentPaddingX,P.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(P.style.paddingTop=o.contentPaddingY,P.style.paddingBottom=o.contentPaddingY),r.name){let oe=S("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?oe.style.color=o.contentTextColor:o.headerTextColor&&(oe.style.color=o.headerTextColor),oe.textContent=r.name,P.appendChild(oe)}if(r.args!==void 0){let oe=S("div","persona-space-y-1"),se=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Arguments";let ge=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",gp(ge,o),ge.textContent=Ln(r.args),oe.append(se,ge),P.appendChild(oe)}if(r.chunks&&r.chunks.length){let oe=S("div","persona-space-y-1"),se=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Activity";let ge=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",gp(ge,o),ge.textContent=r.chunks.join(""),oe.append(se,ge),P.appendChild(oe)}if(r.status==="complete"&&r.result!==void 0){let oe=S("div","persona-space-y-1"),se=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Result";let ge=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",gp(ge,o),ge.textContent=Ln(r.result),oe.append(se,ge),P.appendChild(oe)}if(r.status==="complete"&&typeof r.duration=="number"){let oe=S("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(oe.style.color=o.contentTextColor),oe.textContent=`Duration: ${r.duration}ms`,P.appendChild(oe)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let oe=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",se=he(i?"chevron-up":"chevron-down",16,oe,2);se?H.appendChild(se):H.textContent=i?"Hide":"Show"}P.style.display=i?"":"none",I.style.display=i?"none":I.textContent||I.childNodes.length?"":"none"})(),n.append(u,I,P),n};var fa=new Map,ol=e=>{let r=(e.startsWith(bo)?e.slice(bo.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},ix=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,lx=(e,t)=>{var o,n,a;let r=(n=(o=ix(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=fa.get(e))!=null?a:r==="expanded"},dx=(e,t,r)=>{var s,i;let o=ix(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let c=he(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},cx=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=lx(e,r);dx(o,a,r),n.style.display=a?"":"none"};var nl=(e,t)=>{var M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me,oe;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=S("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=(M=o==null?void 0:o.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(H=o==null?void 0:o.borderColor)!=null?H:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=S("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=S("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",d=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",p=he(c,20,d,2);p&&i.appendChild(p);let u=S("div","persona-flex-1 persona-min-w-0"),g=S("div","persona-flex persona-items-center persona-gap-2"),f=S("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(f.style.color=o.titleColor),f.textContent=(P=o==null?void 0:o.title)!=null?P:"Approval Required",g.appendChild(f),!n){let se=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",r.status),r.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):r.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):r.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),g.appendChild(se)}u.appendChild(g);let b=r.toolType==="webmcp"||r.toolName.startsWith(bo)?ms(r.toolName):void 0,k=(B=o==null?void 0:o.formatDescription)==null?void 0:B.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...b?{displayTitle:b}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,A=k||(E?r.description:`The assistant wants to use \u201C${b!=null?b:ol(r.toolName)}\u201D.`),T=S("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=A,u.appendChild(T),r.reason){let se=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?se.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor);let ge=S("span","persona-font-medium");ge.textContent=`${(O=o==null?void 0:o.reasonLabel)!=null?O:"Agent's stated reason:"} `,se.appendChild(ge),se.appendChild(document.createTextNode(r.reason)),u.appendChild(se)}let y=(Q=o==null?void 0:o.detailsDisplay)!=null?Q:"collapsed",w=!!r.description&&!E,v=w||!!r.parameters;if(y!=="hidden"&&v){let se=lx(e.id,t),ge=S("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ge.type="button",ge.setAttribute("data-expand-header","true"),ge.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(ge.style.color=o.descriptionColor);let Te=S("span");Te.setAttribute("data-approval-details-label","true");let qe=S("span","persona-inline-flex persona-items-center");qe.setAttribute("data-approval-details-chevron","true"),ge.append(Te,qe),dx(ge,se,t),u.appendChild(ge);let j=S("div");if(j.setAttribute("data-approval-details","true"),j.style.display=se?"":"none",w){let ee=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ee.style.color=o.descriptionColor),ee.textContent=r.description,j.appendChild(ee)}if(r.parameters){let ee=S("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(ee.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ee.style.color=o.parameterTextColor),ee.style.fontSize="0.75rem",ee.style.lineHeight="1rem",ee.textContent=Ln(r.parameters),j.appendChild(ee)}u.appendChild(j)}if(n){let se=S("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let ge=S("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");ge.type="button",ge.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",ge.style.color=(ue=o==null?void 0:o.approveButtonTextColor)!=null?ue:"#ffffff",ge.setAttribute("data-approval-action","approve");let Te=he("shield-check",14,(Z=o==null?void 0:o.approveButtonTextColor)!=null?Z:"#ffffff",2);Te&&(Te.style.marginRight="4px",ge.appendChild(Te));let qe=document.createTextNode((Le=o==null?void 0:o.approveLabel)!=null?Le:"Approve");ge.appendChild(qe);let j=S("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");j.type="button",j.style.backgroundColor=(We=o==null?void 0:o.denyButtonColor)!=null?We:"transparent",j.style.color=(ie=o==null?void 0:o.denyButtonTextColor)!=null?ie:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let ee=he("shield-x",14,(Me=o==null?void 0:o.denyButtonTextColor)!=null?Me:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",j.appendChild(ee));let Ee=document.createTextNode((oe=o==null?void 0:o.denyLabel)!=null?oe:"Deny");j.appendChild(Ee),se.append(ge,j),u.appendChild(se)}return s.append(i,u),a.appendChild(s),a};function $v(e){var r,o;let t=(r=e.getRootNode)==null?void 0:r.call(e);return t instanceof ShadowRoot?t:((o=e.ownerDocument)!=null?o:document).body}function px(e){var b;let{anchor:t,content:r,placement:o="bottom-start",offset:n=6,matchAnchorWidth:a=!1,zIndex:s=2147483e3,onOpen:i,onDismiss:c}=e,d=(b=e.container)!=null?b:$v(t),p=!1,u=null,g=()=>{if(!p)return;let k=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${k.width}px`);let E=o==="top-start"||o==="top-end"?k.top-n-r.getBoundingClientRect().height:k.bottom+n,A=o==="bottom-end"||o==="top-end"?k.right-r.getBoundingClientRect().width:k.left;r.style.top=`${E}px`,r.style.left=`${A}px`},f=()=>{p&&(p=!1,u&&(u(),u=null),r.remove())},h=()=>{var w,v,M;if(p)return;p=!0,s!=null&&(r.style.zIndex=String(s)),d.appendChild(r),g();let k=(v=((w=t.ownerDocument)!=null?w:document).defaultView)!=null?v:window,E=(M=t.ownerDocument)!=null?M:document,A=()=>{if(!t.isConnected){f(),c==null||c("anchor-removed");return}g()},T=H=>{let I=typeof H.composedPath=="function"?H.composedPath():[];I.includes(r)||I.includes(t)||(f(),c==null||c("outside"))},y=k.setTimeout(()=>{E.addEventListener("pointerdown",T,!0)},0);k.addEventListener("scroll",A,!0),k.addEventListener("resize",A),u=()=>{k.clearTimeout(y),E.removeEventListener("pointerdown",T,!0),k.removeEventListener("scroll",A,!0),k.removeEventListener("resize",A)},i==null||i()};return{get isOpen(){return p},open:h,close:f,toggle:()=>p?f():h(),reposition:g,destroy:f}}function ux(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(r=>r instanceof HTMLElement&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))}var jv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),fx=(e,t)=>{let r=e.keyHandlers.get(t);r&&(document.removeEventListener("keydown",r),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},ma=(e,t)=>{fx(e,t);let r=e.pendingOrder.indexOf(t);r!==-1&&e.pendingOrder.splice(r,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Gv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Kv=(e,t)=>{var o,n;let r=(o=t==null?void 0:t.detailsDisplay)!=null?o:"collapsed";return(n=fa.get(e))!=null?n:r==="expanded"},xp=e=>{let t=S("span","persona-approval-kbd");return t.textContent=e,t},Xv=(e,t)=>{var d,p;let r=S("span","persona-approval-title");t!=null&&t.titleColor&&(r.style.color=t.titleColor);let n=e.toolType==="webmcp"||e.toolName.startsWith(bo)?ms(e.toolName):void 0,a=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(d=e.description)!=null?d:"",parameters:e.parameters,...n?{displayTitle:n}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=n!=null?n:ol(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;r.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=s,r.appendChild(c),i){r.append(" from ");let u=document.createElement("strong");u.textContent=i,r.appendChild(u)}return r},Qv=e=>{let t=S("div","persona-approval-resolved"),r=he("ban",15,"currentColor",2);r&&t.appendChild(r);let o=S("span","persona-approval-resolved-name");return o.textContent=e.toolName?ol(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Jv=(e,t,r,o,n,a,s)=>{var H,I,P,B,O,Q,me;let i=S("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o!=null&&o.backgroundColor&&(i.style.background=o.backgroundColor),o!=null&&o.borderColor&&(i.style.borderColor=o.borderColor),(o==null?void 0:o.shadow)!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let c=(H=o==null?void 0:o.detailsDisplay)!=null?H:"collapsed",d=!!r.description&&c!=="hidden",p=r.parameters!=null&&c!=="hidden",u=d||p,g=u&&Kv(t.id,o),f=(I=o==null?void 0:o.showDetailsLabel)!=null?I:"Show details",h=(P=o==null?void 0:o.hideDetailsLabel)!=null?P:"Hide details",b=S("button","persona-approval-head");b.type="button",u?(b.setAttribute("data-action","toggle-params"),b.setAttribute("aria-expanded",g?"true":"false"),b.setAttribute("aria-label",g?h:f)):b.setAttribute("data-static","true");let k=S("span","persona-approval-logo"),E=he("shield-check",16,"currentColor",2);E&&k.appendChild(E),b.appendChild(k);let A=Xv(r,o);if(u){let ue=S("span","persona-approval-toggle");ue.setAttribute("aria-hidden","true");let Z=he("chevron-down",14,"currentColor",2);Z&&ue.appendChild(Z),A.append(" "),A.appendChild(ue)}b.appendChild(A),i.appendChild(b);let T=S("div","persona-approval-body");if(u){let ue=S("div","persona-approval-details");if(ue.setAttribute("data-role","params"),ue.hidden=!g,d){let Z=S("p","persona-approval-desc");o!=null&&o.descriptionColor&&(Z.style.color=o.descriptionColor),Z.textContent=r.description,ue.appendChild(Z)}if(p){let Z=S("pre","persona-approval-params");o!=null&&o.parameterBackgroundColor&&(Z.style.background=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(Z.style.color=o.parameterTextColor),Z.textContent=Ln(r.parameters),ue.appendChild(Z)}T.appendChild(ue)}if(r.reason){let ue=S("p","persona-approval-reason");o!=null&&o.reasonColor?ue.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ue.style.color=o.descriptionColor);let Z=S("span","persona-approval-reason-label");Z.textContent=`${(B=o==null?void 0:o.reasonLabel)!=null?B:"Agent's stated reason:"} `,ue.append(Z,document.createTextNode(r.reason)),T.appendChild(ue)}let y=S("div","persona-approval-actions"),w=null,v=ue=>{o!=null&&o.approveButtonColor&&(ue.style.background=o.approveButtonColor),o!=null&&o.approveButtonTextColor&&(ue.style.color=o.approveButtonTextColor)},M=S("button","persona-approval-deny");if(M.type="button",M.setAttribute("data-action","deny"),o!=null&&o.denyButtonColor&&(M.style.background=o.denyButtonColor),o!=null&&o.denyButtonTextColor&&(M.style.color=o.denyButtonTextColor),M.append((O=o==null?void 0:o.denyLabel)!=null?O:"Deny"),s){let ue=S("div","persona-approval-split"),Z=S("button","persona-approval-primary");Z.type="button",Z.setAttribute("data-action","always"),v(Z),Z.append((Q=o==null?void 0:o.approveLabel)!=null?Q:"Always allow",xp("\u23CE"));let Le=S("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),v(Le);let We=he("chevron-down",15,"currentColor",2);We&&Le.appendChild(We),ue.append(Z,Le),y.append(ue,M),M.append(xp("Esc"));let ie=S("div","persona-approval-menu"),Me=S("button","persona-approval-menu-item");Me.type="button",Me.append("Allow once",xp("\u2318\u23CE")),ie.appendChild(Me),w=px({anchor:ue,content:ie,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,w),Me.addEventListener("click",()=>{ma(e,t.id),n()})}else{let ue=S("button","persona-approval-primary persona-approval-primary--solo");ue.type="button",ue.setAttribute("data-action","allow"),v(ue),ue.append((me=o==null?void 0:o.approveLabel)!=null?me:"Allow"),y.append(ue,M)}return T.appendChild(y),i.appendChild(T),i.addEventListener("click",ue=>{let Z=ue.target instanceof Element?ue.target.closest("[data-action]"):null;if(!Z)return;let Le=Z.getAttribute("data-action");if(Le==="toggle-params"){let We=i.querySelector('[data-role="params"]');if(We){let ie=We.hidden;We.hidden=!ie,b.setAttribute("aria-expanded",ie?"true":"false"),b.setAttribute("aria-label",ie?h:f),fa.set(t.id,ie)}return}if(Le==="toggle-menu"){w==null||w.toggle();return}if(Le==="always"){ma(e,t.id),n({remember:!0});return}if(Le==="allow"){ma(e,t.id),n();return}if(Le==="deny"){ma(e,t.id),a();return}}),i},mx=()=>{let e=jv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:n,deny:a,config:s})=>{let i=o==null?void 0:o.approval;if(!i)return null;let c=Gv(s);if(i.status!=="pending"){if(ma(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Qv(i)}fx(e,o.id);let d=(c==null?void 0:c.enableAlwaysAllow)===!0,p=Jv(e,o,i,c,n,a,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{ux(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),ma(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?n():n({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])ma(e,o);e.latestPendingApprovalId=null}}};var gx=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,d)=>{e.innerHTML="",t.length=0;let p=(d==null?void 0:d.agentPushed)===!0;if(p||(r=null),!n||!n.length||!p&&(i!=null?i:a?a.getMessages():[]).some(k=>k.role==="user"))return;let u=document.createDocumentFragment(),g=a?a.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(h=>{let b=S("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");b.type="button",b.textContent=h,b.disabled=g,c!=null&&c.fontFamily&&(b.style.fontFamily=f(c.fontFamily)),c!=null&&c.fontWeight&&(b.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(b.style.paddingLeft=c.paddingX,b.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(b.style.paddingTop=c.paddingY,b.style.paddingBottom=c.paddingY),b.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),a.sendMessage(h))}),u.appendChild(b),t.push(b)}),e.appendChild(u),p){let h=JSON.stringify(n);h!==r&&(r=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var Fs=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ns=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var Yv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Zv=new Set(["step_start","execution_start"]),e0=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),t0=new Set(["step_complete","agent_turn_complete"]),r0=new Set(["flow_complete","agent_complete"]),hx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),yx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ga=(e,t)=>{let r=e[t];return yx(r)?r:void 0};function yp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function al(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function o0(e,t){return typeof t.type=="string"?t.type:e}function n0(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function a0(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function xx(e){var o,n,a,s,i;let t=ga(e,"result"),r=[ga(e,"tokens"),ga(e,"totalTokens"),t?ga(t,"tokens"):void 0,ga(e,"usage"),t?ga(t,"usage"):void 0];for(let c of r){if(!c)continue;let d=(n=(o=Xr(c.output))!=null?o:Xr(c.outputTokens))!=null?n:Xr(c.completionTokens);if(d!==void 0)return d}return(i=(a=Xr(e.outputTokens))!=null?a:Xr(e.completionTokens))!=null?i:t?(s=Xr(t.outputTokens))!=null?s:Xr(t.completionTokens):void 0}function s0(e){var r,o,n,a,s;let t=ga(e,"result");return(s=(n=(o=(r=Xr(e.executionTime))!=null?r:Xr(e.executionTimeMs))!=null?o:Xr(e.execution_time))!=null?n:Xr(e.duration))!=null?s:t?(a=Xr(t.executionTime))!=null?a:Xr(t.executionTimeMs):void 0}function i0(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Os=class{constructor(t=i0){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:al(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,r){var a;if(!yx(r)){hx.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=o0(t,r),n=this.now();if(Yv.has(o)){this.startRun(n);return}if(Zv.has(o)){this.run||this.startRun(n);return}if(e0.has(o)){if(!a0(o,r))return;let s=n0(r);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let c=i.exactOutputTokens+yp(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:al(c,d),outputTokens:c,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(t0.has(o)){if(!this.run)return;let s=this.run,i=xx(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,d=s.exactOutputTokens+yp(s.visibleCharCount),p=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:al(d,p),outputTokens:d,durationMs:p,source:c?"usage":"estimate"};return}if(r0.has(o)){if(!this.run)return;let s=this.run,i=xx(r),c=i!=null?i:s.exactOutputTokens+yp(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:al(c,p),outputTokens:c,durationMs:p,source:d},this.run=null;return}if(hx.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,o){let n=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=s0(r);return a!=null?a:o-t.startedAt}};function Ka(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var l0={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)"}},d0={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},c0=["flowName","stepName","reasoningText","text","name","tool","toolName"],p0=100;function u0(e,t){let r={...l0,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return d0}function f0(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function m0(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${o}:${n}.${a}`}function g0(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let o of t){let n=o.split("."),a=r;for(let s of n)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 h0(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function x0(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function y0(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function b0(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function v0(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=S("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]"),c=S("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,i.appendChild(c),i}}function bp(e,t,r,o,n,a,s,i){var g;let c=n.has(e.id),d=S("div","persona-border-b persona-border-persona-divider persona-text-xs");Ka(d,(g=o.classNames)==null?void 0:g.eventRow);let p=s.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(f)return d.appendChild(f),d}return d.appendChild(u()),d;function u(){var O,Q;let f=S("div",""),h=S("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");h.setAttribute("data-event-id",e.id);let b=S("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),k=he(c?"chevron-down":"chevron-right","14px","currentColor",2);k&&b.appendChild(k);let E=S("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(O=o.timestampFormat)!=null?O:"relative";E.textContent=A==="relative"?f0(e.timestamp,r):m0(e.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=S("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(t+1));let y=u0(e.type,o.badgeColors),w=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=y.bg,w.style.color=y.text,w.style.borderColor=y.text+"50",w.textContent=e.type;let v=(Q=o.descriptionFields)!=null?Q:c0,M=g0(e.payload,v),H=null;M&&(H=S("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=M);let I=S("div","persona-flex-1 persona-min-w-0"),P=S("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=he("clipboard","12px","currentColor",1.5);return B&&P.appendChild(B),P.addEventListener("click",async me=>{me.stopPropagation(),await h0(x0(e)),P.innerHTML="";let ue=he("check","12px","currentColor",1.5);ue&&P.appendChild(ue),setTimeout(()=>{P.innerHTML="";let Z=he("clipboard","12px","currentColor",1.5);Z&&P.appendChild(Z)},1500)}),h.appendChild(b),h.appendChild(E),T&&h.appendChild(T),h.appendChild(w),H&&h.appendChild(H),h.appendChild(I),h.appendChild(P),f.appendChild(h),c&&f.appendChild(v0(e,s,i)),f}}function bx(e){var h,b,k,E,A;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(h=n==null?void 0:n.features)==null?void 0:h.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,d=(b=i==null?void 0:i.iconName)!=null?b:"arrow-down",p=(k=i==null?void 0:i.label)!=null?k:"",u=(A=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?A:{},g=a.find(T=>T.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&n){let T=g.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(T)return{element:T,update:()=>{},destroy:()=>{}}}return f();function f(){let T=u.classNames,y=S("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ka(y,T==null?void 0:T.panel);let w=[],v="",M="",H=null,I=[],P={},B=0,O=_i(),Q=0,me=0,ue=!1,Z=null,Le=!1,We=0,ie=new Set,Me=new Map,oe="",se="",ge=null,Te,qe,j,ee,Ee=null,te=null,le=null;function ke(){let pe=S("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),N=S("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");if(Ka(N,T==null?void 0:T.headerBar),s){te=S("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),te.style.cursor="help",Ee=S("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ee.textContent="-- tok/s",le=S("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let Ft=te,tr=le,Ao=()=>{if(!tr.textContent)return;let io=Ft.getBoundingClientRect(),lo=pe.getBoundingClientRect();tr.style.left=`${io.left-lo.left}px`,tr.style.top=`${io.bottom-lo.top+4}px`,tr.style.display="block"},Uo=()=>{tr.style.display="none"};te.addEventListener("mouseenter",Ao),te.addEventListener("mouseleave",Uo),te.appendChild(Ee)}let ye=S("div","persona-flex-1");Te=S("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 ae=S("option","");ae.value="",ae.textContent="All events (0)",Te.appendChild(ae),qe=S("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"),qe.type="button",qe.title="Copy All";let Ke=he("clipboard-copy","12px","currentColor",1.5);Ke&&qe.appendChild(Ke);let Lt=S("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",qe.appendChild(Lt),te&&N.appendChild(te),N.appendChild(ye),N.appendChild(Te),N.appendChild(qe);let Et=S("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ka(Et,T==null?void 0:T.searchBar);let bt=he("search","14px","var(--persona-muted, #9ca3af)",1.5),It=S("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&It.appendChild(bt),j=S("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"),Ka(j,T==null?void 0:T.searchInput),j.type="text",j.placeholder="Search event payloads...",ee=S("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"),ee.type="button",ee.style.display="none";let Qt=he("x","12px","currentColor",2);return Qt&&ee.appendChild(Qt),Et.appendChild(It),Et.appendChild(j),Et.appendChild(ee),pe.appendChild(N),pe.appendChild(Et),le&&pe.appendChild(le),pe}let nt,yt=a.find(pe=>pe.renderEventStreamToolbar);if(yt!=null&&yt.renderEventStreamToolbar&&n){let pe=yt.renderEventStreamToolbar({config:n,defaultRenderer:()=>ke(),eventCount:t.getSize(),filteredCount:0,onFilterChange:N=>{v=N,xe(),Ct()},onSearchChange:N=>{M=N,xe(),Ct()}});nt=pe!=null?pe:ke()}else nt=ke();let Kt=S("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");Kt.style.display="none";function jt(){if(!s||!Ee||!te)return;let pe=s(),N=y0(pe);Ee.textContent=N;let ye=b0(pe);le&&(le.textContent=ye,ye||(le.style.display="none")),te.setAttribute("aria-label",ye?`Throughput: ${N}, ${ye}`:`Throughput: ${N}`)}let ct=S("div","persona-flex-1 persona-min-h-0 persona-relative"),fe=S("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");fe.style.height="100%";let X=S("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");Ka(X,T==null?void 0:T.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let st=he(d,"14px","currentColor",2);st&&X.appendChild(st);let je=S("span","");je.textContent=p,X.appendChild(je);let Ce=S("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ce.style.display="none",ct.appendChild(fe),ct.appendChild(Ce),ct.appendChild(X),y.setAttribute("tabindex","0"),y.appendChild(nt),y.appendChild(Kt),y.appendChild(ct);function ve(){let pe=t.getAll(),N={};for(let Et of pe)N[Et.type]=(N[Et.type]||0)+1;let ye=Object.keys(N).sort(),ae=ye.length!==I.length||!ye.every((Et,bt)=>Et===I[bt]),mt=!ae&&ye.some(Et=>N[Et]!==P[Et]),Ke=pe.length!==Object.values(P).reduce((Et,bt)=>Et+bt,0);if(!ae&&!mt&&!Ke||(I=ye,P=N,!Te))return;let Lt=Te.value;if(Te.options[0].textContent=`All events (${pe.length})`,ae){for(;Te.options.length>1;)Te.remove(1);for(let Et of ye){let bt=S("option","");bt.value=Et,bt.textContent=`${Et} (${N[Et]||0})`,Te.appendChild(bt)}Lt&&ye.includes(Lt)?Te.value=Lt:Lt&&(Te.value="",v="")}else for(let Et=1;Et<Te.options.length;Et++){let bt=Te.options[Et];bt.textContent=`${bt.value} (${N[bt.value]||0})`}}function Ye(){let pe=t.getAll();if(v&&(pe=pe.filter(N=>N.type===v)),M){let N=M.toLowerCase();pe=pe.filter(ye=>ye.type.toLowerCase().includes(N)||ye.payload.toLowerCase().includes(N))}return pe}function Vt(){return v!==""||M!==""}function xe(){B=0,Q=0,O.resume(),X.style.display="none"}function de(pe){ie.has(pe)?ie.delete(pe):ie.add(pe),ge=pe;let N=fe.scrollTop,ye=O.isFollowing();Le=!0,O.pause(),Ct(),fe.scrollTop=N,ye&&O.resume(),Le=!1}function Cr(){return Wn(fe,50)}function Ct(){me=Date.now(),ue=!1,jt(),ve();let pe=t.getEvictedCount();pe>0?(Kt.textContent=`${pe.toLocaleString()} older events truncated`,Kt.style.display=""):Kt.style.display="none",w=Ye();let N=w.length,ye=t.getSize()>0;N===0&&ye&&Vt()?(Ce.textContent=M?`No events matching '${M}'`:"No events matching filter",Ce.style.display="",fe.style.display="none"):(Ce.style.display="none",fe.style.display=""),qe&&(qe.title=Vt()?`Copy Filtered (${N})`:"Copy All"),c&&!O.isFollowing()&&N>B&&(Q+=N-B,je.textContent=p?`${p}${Q>0?` (${Q})`:""}`:"",X.style.display=""),B=N;let ae=t.getAll(),mt=ae.length>0?ae[0].timestamp:0,Ke=new Set(w.map(bt=>bt.id));for(let bt of ie)Ke.has(bt)||ie.delete(bt);let Lt=v!==oe||M!==se,Et=Me.size===0&&w.length>0;if(Lt||Et||w.length===0){fe.innerHTML="",Me.clear();let bt=document.createDocumentFragment();for(let It=0;It<w.length;It++){let Qt=bp(w[It],It,mt,u,ie,de,a,n);Me.set(w[It].id,Qt),bt.appendChild(Qt)}fe.appendChild(bt),oe=v,se=M,ge=null}else{if(ge!==null){let It=Me.get(ge);if(It&&It.parentNode===fe){let Qt=w.findIndex(Ft=>Ft.id===ge);if(Qt>=0){let Ft=bp(w[Qt],Qt,mt,u,ie,de,a,n);fe.insertBefore(Ft,It),It.remove(),Me.set(ge,Ft)}}ge=null}let bt=new Set(w.map(It=>It.id));for(let[It,Qt]of Me)bt.has(It)||(Qt.remove(),Me.delete(It));for(let It=0;It<w.length;It++){let Qt=w[It];if(!Me.has(Qt.id)){let Ft=bp(Qt,It,mt,u,ie,de,a,n);Me.set(Qt.id,Ft),fe.appendChild(Ft)}}}O.isFollowing()&&(fe.scrollTop=fe.scrollHeight)}function xr(){if(Date.now()-me>=p0){Z!==null&&(cancelAnimationFrame(Z),Z=null),Ct();return}ue||(ue=!0,Z=requestAnimationFrame(()=>{Z=null,Ct()}))}let Co=(pe,N)=>{if(!qe)return;qe.innerHTML="";let ye=he(pe,"12px","currentColor",1.5);ye&&qe.appendChild(ye);let ae=S("span","persona-text-xs");ae.textContent="Copy All",qe.appendChild(ae),setTimeout(()=>{qe.innerHTML="";let mt=he("clipboard-copy","12px","currentColor",1.5);mt&&qe.appendChild(mt);let Ke=S("span","persona-text-xs");Ke.textContent="Copy All",qe.appendChild(Ke),qe.disabled=!1},N)},So=async()=>{if(qe){qe.disabled=!0;try{let pe;Vt()?pe=w:r?(pe=await r(),pe.length===0&&(pe=t.getAll())):pe=t.getAll();let N=pe.map(ye=>{try{return JSON.parse(ye.payload)}catch{return ye.payload}});await navigator.clipboard.writeText(JSON.stringify(N,null,2)),Co("check",1500)}catch{Co("x",1500)}}},Ve=()=>{Te&&(v=Te.value,xe(),Ct())},W=()=>{!j||!ee||(ee.style.display=j.value?"":"none",H&&clearTimeout(H),H=setTimeout(()=>{M=j.value,xe(),Ct()},150))},ce=()=>{!j||!ee||(j.value="",M="",ee.style.display="none",H&&clearTimeout(H),xe(),Ct())},Se=()=>{if(Le)return;let pe=fe.scrollTop,{action:N,nextLastScrollTop:ye}=Ui({following:O.isFollowing(),currentScrollTop:pe,lastScrollTop:We,nearBottom:Cr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});We=ye,N==="resume"?(O.resume(),Q=0,X.style.display="none"):N==="pause"&&(O.pause(),c&&(je.textContent=p,X.style.display=""))},Ae=pe=>{let N=qi({following:O.isFollowing(),deltaY:pe.deltaY,nearBottom:Cr(),resumeWhenNearBottom:!0});N==="pause"?(O.pause(),c&&(je.textContent=p,X.style.display="")):N==="resume"&&(O.resume(),Q=0,X.style.display="none")},Ie=()=>{c&&(fe.scrollTop=fe.scrollHeight,O.resume(),Q=0,X.style.display="none")},et=pe=>{let N=pe.target;if(!N||N.closest("button"))return;let ye=N.closest("[data-event-id]");if(!ye)return;let ae=ye.getAttribute("data-event-id");ae&&de(ae)},Qe=pe=>{if((pe.metaKey||pe.ctrlKey)&&pe.key==="f"){pe.preventDefault(),j==null||j.focus(),j==null||j.select();return}pe.key==="Escape"&&(j&&document.activeElement===j?(ce(),j.blur(),y.focus()):o&&o())};qe&&qe.addEventListener("click",So),Te&&Te.addEventListener("change",Ve),j&&j.addEventListener("input",W),ee&&ee.addEventListener("click",ce),fe.addEventListener("scroll",Se),fe.addEventListener("wheel",Ae,{passive:!0}),fe.addEventListener("click",et),X.addEventListener("click",Ie),y.addEventListener("keydown",Qe);function gt(){H&&clearTimeout(H),Z!==null&&(cancelAnimationFrame(Z),Z=null),ue=!1,Me.clear(),qe&&qe.removeEventListener("click",So),Te&&Te.removeEventListener("change",Ve),j&&j.removeEventListener("input",W),ee&&ee.removeEventListener("click",ce),fe.removeEventListener("scroll",Se),fe.removeEventListener("wheel",Ae),fe.removeEventListener("click",et),X.removeEventListener("click",Ie),y.removeEventListener("keydown",Qe)}return{element:y,update:xr,destroy:gt}}}function vx(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=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 ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${s.toLowerCase()}...`,u.appendChild(f)}else u.textContent=s;if(d.append(p,u),i.append(c,d),n==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${r}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var wx=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",d=typeof e.artifactType=="string"?e.artifactType:"markdown",p=r({artifact:{artifactId:i,title:s,artifactType:d,status:c},config:t.config,defaultRenderer:()=>vx(e,t)});if(p)return p}return vx(e,t)};var vp=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,o])=>{this.register(r,o)})}},rn=new vp;rn.register("PersonaArtifactCard",wx);function w0(e){var n;let t=S("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=S("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function Cx(e,t){var qe,j,ee,Ee;let r=(j=(qe=e.features)==null?void 0:qe.artifacts)==null?void 0:j.layout,n=((ee=r==null?void 0:r.toolbarPreset)!=null?ee:"default")==="document",a=(Ee=r==null?void 0:r.panePadding)==null?void 0:Ee.trim(),s=e.markdown?oa(e.markdown):null,i=Ra(e.sanitize),c=te=>{let le=s?s(te):Fo(te);return i?i(le):le},d=typeof document!="undefined"?S("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{d==null||d.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),B==null||B.hide()};d&&d.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let u=S("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),n&&u.classList.add("persona-artifact-pane-document");let g=S("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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&g.classList.add("persona-artifact-toolbar-document");let f=S("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let h=S("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");h.type="button",h.textContent="Close",h.setAttribute("aria-label","Close artifacts panel"),h.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let b="rendered",k=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?pr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):pr({icon:"eye",label:"Rendered view"}),A=n?pr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):pr({icon:"code-2",label:"Source"}),T=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,w=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,v=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(w&&v&&v.length>0),H=null,I,P=null,B=null;if(n&&(y||w)&&!M){if(I=y?Ds({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w){let te=he("chevron-down",14,"currentColor",2);te&&I.appendChild(te)}}else n&&M?(H=S("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),I=y?Ds({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P=pr({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),H.append(I,P)):n?I=pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):I=pr({icon:"copy",label:"Copy"});let O=n?pr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):pr({icon:"refresh-cw",label:"Refresh"}),Q=n?pr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):pr({icon:"x",label:"Close"}),me=()=>{var yt,Kt,jt;let te=(yt=Me.find(ct=>ct.id===oe))!=null?yt:Me[Me.length-1],le=(Kt=te==null?void 0:te.id)!=null?Kt:null,ke=(te==null?void 0:te.artifactType)==="markdown"&&(jt=te.markdown)!=null?jt:"",nt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:ke,jsonPayload:nt,id:le}},ue=async()=>{var yt;let{markdown:te,jsonPayload:le}=me(),ke=(yt=Me.find(Kt=>Kt.id===oe))!=null?yt:Me[Me.length-1],nt=(ke==null?void 0:ke.artifactType)==="markdown"?te:ke?le:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(I.addEventListener("click",async()=>{let te=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(te&&M){let{markdown:le,jsonPayload:ke,id:nt}=me();try{await te({actionId:"primary",artifactId:nt,markdown:le,jsonPayload:ke})}catch{}return}await ue()}),P&&(v!=null&&v.length)){let te=()=>{var ke;return(ke=u.closest("[data-persona-root]"))!=null?ke:document.body},le=()=>{B=Nn({items:v.map(ke=>({id:ke.id,label:ke.label})),onSelect:async ke=>{let{markdown:nt,jsonPayload:yt,id:Kt}=me(),jt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{jt?await jt({actionId:ke,artifactId:Kt,markdown:nt,jsonPayload:yt}):ke==="markdown"||ke==="md"?await navigator.clipboard.writeText(nt):ke==="json"||ke==="source"?await navigator.clipboard.writeText(yt):await navigator.clipboard.writeText(nt||yt)}catch{}},anchor:H!=null?H:P,position:"bottom-right",portal:te()})};u.isConnected?le():requestAnimationFrame(le),P.addEventListener("click",ke=>{ke.stopPropagation(),B==null||B.toggle()})}O.addEventListener("click",async()=>{var te;try{await((te=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:te.call(r))}catch{}ge()}),Q.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let Z=()=>{n&&(E.setAttribute("aria-pressed",b==="rendered"?"true":"false"),A.setAttribute("aria-pressed",b==="source"?"true":"false"))};E.addEventListener("click",()=>{b="rendered",Z(),ge()}),A.addEventListener("click",()=>{b="source",Z(),ge()});let Le=S("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");n?(g.replaceChildren(),k.append(E,A),H?T.append(H,O,Q):T.append(I,O,Q),g.append(k,Le,T),Z()):(g.appendChild(f),g.appendChild(h)),a&&(g.style.paddingLeft=a,g.style.paddingRight=a);let We=S("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"),ie=S("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(We.style.paddingLeft=a,We.style.paddingRight=a,ie.style.padding=a),u.appendChild(g),u.appendChild(We),u.appendChild(ie);let Me=[],oe=null,se=!1,ge=()=>{var nt,yt,Kt,jt;let te=n&&Me.length<=1;We.classList.toggle("persona-hidden",te),We.replaceChildren();for(let ct of Me){let fe=S("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");fe.type="button",fe.textContent=ct.title||ct.id.slice(0,8),ct.id===oe&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(ct.id)),We.appendChild(fe)}ie.replaceChildren();let le=oe&&Me.find(ct=>ct.id===oe)||Me[Me.length-1];if(!le)return;if(n){let ct=le.artifactType==="markdown"?"MD":(nt=le.component)!=null?nt:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${X} \xB7 ${ct}`}else f.textContent="Artifacts";if(le.artifactType==="markdown"){if(n&&b==="source"){let fe=S("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(yt=le.markdown)!=null?yt:"",ie.appendChild(fe);return}let ct=S("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ct.innerHTML=c((Kt=le.markdown)!=null?Kt:""),ie.appendChild(ct);return}let ke=le.component?rn.get(le.component):void 0;if(ke){let fe={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ke((jt=le.props)!=null?jt:{},fe);if(X){ie.appendChild(X);return}}catch{}}ie.appendChild(w0(le))},Te=()=>{var le;let te=Me.length>0;if(u.classList.toggle("persona-hidden",!te),d){let ke=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,yt=((le=ke==null?void 0:ke.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&yt&&se?(d.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:d,update(te){var le,ke,nt;Me=te.artifacts,oe=(nt=(ke=te.selectedId)!=null?ke:(le=te.artifacts[te.artifacts.length-1])==null?void 0:le.id)!=null?nt:null,Me.length>0&&(se=!0),ge(),Te()},setMobileOpen(te){se=te,!te&&d?(d.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):Te()}}}function so(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function Sx(e,t){var a,s,i,c;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!so(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(c=r==null?void 0:r.paneBorderLeft)==null?void 0:c.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function C0(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 sl(e,t){var c,d,p,u,g,f,h,b,k,E;if(!so(t)){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"),C0(e),Sx(e,t);return}let r=(d=(c=t.features)==null?void 0:c.artifacts)==null?void 0:d.layout;e.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=r==null?void 0:r.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=r==null?void 0:r.paneMaxWidth)!=null?g:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(f=r==null?void 0:r.paneBackground)==null?void 0:f.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(h=r==null?void 0:r.panePadding)==null?void 0:h.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(b=r==null?void 0:r.documentToolbarIconColor)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(k=r==null?void 0:r.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=(E=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Sx(e,t)}var Ax=["panel","seamless"];function il(e,t){var i,c,d,p,u,g;for(let f of Ax)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!so(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=Ax.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(u=r==null?void 0:r.paneShadow)==null?void 0:u.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=r.unifiedSplitOuterRadius)==null?void 0:g.trim())||a;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Mx(e,t){var r,o,n;return!t||!so(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function S0(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function A0(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function M0(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function T0(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Tx(e,t){var s;let o=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Ex(e,t,r,o,n,a){let s=S0(n,200),i=T0(t,r,o,200);i=Math.max(s,i);let c=A0(a);return c!==null&&(i=Math.min(i,c)),M0(e,s,i)}var kx={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"}},wp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var h,b,k;if(a.dataset.enhanced==="true")return;let s=(h=a.dataset.tvForm)!=null?h:"init";a.dataset.enhanced="true";let i=(b=kx[s])!=null?b:kx.init;a.classList.add("persona-form-card","persona-space-y-4");let c=S("div","persona-space-y-1"),d=S("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,c.appendChild(d),i.description){let E=S("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var v,M;let A=S("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${E.name}`;let T=S("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=E.label,A.appendChild(T);let y=(v=E.type)!=null?v:"text",w;y==="textarea"?(w=document.createElement("textarea"),w.rows=3):(w=document.createElement("input"),w.type=y),w.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",w.id=`${t.id}-${s}-${E.name}`,w.name=E.name,w.placeholder=(M=E.placeholder)!=null?M:"",E.required&&(w.required=!0),A.appendChild(w),p.appendChild(A)});let u=S("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=S("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=S("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",u.appendChild(g),u.appendChild(f),p.appendChild(u),a.replaceChildren(c,p),p.addEventListener("submit",async E=>{var w,v;E.preventDefault();let A=(w=r.formEndpoint)!=null?w:"/form",T=new FormData(p),y={};T.forEach((M,H)=>{y[H]=M}),y.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let H=await M.json();g.textContent=(v=H.message)!=null?v:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await o.sendMessage(String(H.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Cp=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,c;return((i=s.priority)!=null?i:0)-((c=a.priority)!=null?c:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},_s=new Cp;var Lx=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var E0=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},k0=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},Us=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=E0(e),r=k0(t);if(!r)return null;let o=JSON.parse(r);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Sp=e=>typeof e=="string"?e:e==null?"":String(e),ha={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Sp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Sp(r.element);if(o&&((n=t.document)!=null&&n.querySelector)){let a=t.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Sp(r.text)}}},Px=e=>Array.isArray(e)?e.map(t=>String(t)):[],qs=e=>{let t=new Set(Px(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Px(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.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((d,p)=>d||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let p=()=>{e.emit("action:resubmit",c)},u=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var L0=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},P0=e=>e.map(t=>({...t,streaming:!1})),R0=e=>e.map(t=>({...t,status:"complete"})),ll=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?L0(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?P0(r.messages):void 0,artifacts:r.artifacts?R0(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Xa=La(oi(),1);function I0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function H0(e,t){if(!I0(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function dl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e;try{let n=(0,Xa.parse)(r,Xa.STR|Xa.OBJ),a=H0(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function Rx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function cl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=rn.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:o,config:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Ix(){let e=dl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Hx(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function pl(e){let t=Hx(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function ul(e){let t=Hx(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let o=r;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var W0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function fl(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:d=W0}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=n,f.appendChild(b),g.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 E=[];for(let v=1;v<=5;v++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${d[v-1]}`),M.title=d[v-1],M.dataset.rating=String(v),M.innerHTML=`
|
|
34
|
+
`,o.addEventListener("click",t);let r=a=>{let s=a.launcher??{},l=It(a),p=o.querySelector("[data-role='launcher-title']");if(p){let T=s.title??"Chat Assistant";p.textContent=T,p.setAttribute("title",T)}let d=o.querySelector("[data-role='launcher-subtitle']");if(d){let T=s.subtitle??"Here to help you get answers fast";d.textContent=T,d.setAttribute("title",T)}let c=o.querySelector(".persona-flex-col");c&&(s.textHidden||l?c.style.display="none":c.style.display="");let u=o.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let T=s.agentIconSize??"40px";if(u.style.height=T,u.style.width=T,s.agentIconBackgroundColor?(u.style.backgroundColor=s.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",s.agentIconName){let S=parseFloat(T)||24,E=ne(s.agentIconName,S*.6,"var(--persona-text-inverse, #ffffff)",2);E?(u.appendChild(E),u.style.display=""):(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}else s.iconUrl?u.style.display="none":(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}let g=o.querySelector("[data-role='launcher-image']");if(g){let T=s.agentIconSize??"40px";g.style.height=T,g.style.width=T,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let f=o.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let T=s.callToActionIconSize??"32px";f.style.height=T,f.style.width=T,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 S=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,S=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",s.callToActionIconName){let E=parseFloat(T)||24,B=Math.max(E-S,8),H=ne(s.callToActionIconName,B,"currentColor",2);H?f.appendChild(H):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&Eo[s.position]?Eo[s.position]:Eo["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="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";o.className=l?M:`${C} ${h}`,l||(o.style.zIndex=String(s.zIndex??zt));let L="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=s.border??L,o.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,l?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=s.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},n=()=>{o.removeEventListener("click",t),o.remove()};return e&&r(e),{element:o,update:r,destroy:n}};var rg=({config:e,showClose:t})=>{let{wrapper:o,panel:r,pillRoot:n}=tg(e),a=og(e,t),s={wrapper:o,panel:r,pillRoot:n},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},p={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:l,header:p,composer:d,replaceHeader:g=>(p.element.replaceWith(g.header),p.element=g.header,p.iconHolder=g.iconHolder,p.headerTitle=g.headerTitle,p.headerSubtitle=g.headerSubtitle,p.closeButton=g.closeButton,p.closeButtonWrapper=g.closeButtonWrapper,p.clearChatButton=g.clearChatButton,p.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{d.footer.replaceWith(g),d.footer=g}}},vp=({config:e,plugins:t,onToggle:o})=>{let r=t.find(a=>a.renderLauncher);if(r?.renderLauncher){let a=r.renderLauncher({config:e,defaultRenderer:()=>xp(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let n=xp(e,o);return{instance:n,element:n.element}};var wx=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}},Ax=(e,t)=>{if(!e)return null;let o=wx(e);if(o===null)return null;let r=t?.[e],n=r!==void 0?r:o;return n||null},Sx=(e,t)=>{let o=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},Tx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Cp=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},wp=320,ag=320,Mx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ex=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),kx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Lx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Px=(e,t,o)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,r.remove(),o?.())};return e.forEach((l,p)=>{let d=y("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${wp}px`,d.style.maxHeight=`${ag}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;n+=1,d.addEventListener("error",()=>{c||(c=!0,n=Math.max(0,n-1),d.remove(),n===0&&s())}),d.addEventListener("load",()=>{c=!0}),Tx(l.image)?(d.src=l.image,r.appendChild(d)):(c=!0,n=Math.max(0,n-1),d.remove())}),n===0?(s(),null):r}catch{return o?.(),null}},Rx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(r=>{if(!Cp(r.audio))return;let n=y("audio");n.controls=!0,n.preload="metadata",n.src=r.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${wp}px`,t.appendChild(n),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Ix=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(r=>{if(!Cp(r.video))return;let n=y("video");n.controls=!0,n.preload="metadata",n.src=r.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${wp}px`,n.style.maxHeight=`${ag}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Bx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(r=>{if(!Cp(r.data))return;let n=y("a");n.href=r.data,n.download=r.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=r.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),o+=1}),o===0?(t.remove(),null):t}catch{return null}},nn=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="0ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="250ms";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="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(r),e.appendChild(n),e},Ap=(e,t,o)=>{let r={config:o??{},streaming:!0,location:e,defaultRenderer:nn};if(t){let n=t(r);if(n!==null)return n}return nn()},Hx=(e,t)=>{let o=y("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"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let n=y("img");n.src=r,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(n)}else o.textContent=r,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},ng=(e,t,o="div")=>{let r=y(o,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?r.textContent=t.format(n):r.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Wx=(e,t="bubble")=>{let o=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.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 o},Sp=(e,t,o)=>{let r=t.showCopy??!0,n=t.showUpvote??!0,a=t.showDownvote??!0,s=t.showReadAloud??!1;if(!r&&!n&&!a&&!s){let h=y("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}let l=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(h,C,M)=>{let L=kt({icon:h,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",M),L};return r&&g.appendChild(f("copy","Copy message","copy")),s&&g.appendChild(f("volume-2","Read aloud","read-aloud")),n&&g.appendChild(f("thumbs-up","Upvote","upvote")),a&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},qn=(e,t,o,r,n,a)=>{let s=o??{},l=s.layout??"bubble",p=s.avatar,d=s.timestamp,c=p?.show??!1,u=d?.show??!1,g=p?.position??"left",f=d?.position??"below",h=Wx(e.role,l),C=y("div",h.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Mx(e),L=e.content?.trim()??"",T=M.length>0&&L===Qs,S=Ii(a?.widgetConfig?.features?.streamAnimation),E=a?.widgetConfig?.features?.streamAnimation?.plugins,B=e.role==="assistant"&&S.type!=="none"?Nn(S.type,E):null,H=e.role==="assistant"&&B?.isAnimating?.(e)===!0,w=e.role==="assistant"&&B!==null&&(!!e.streaming||H);w&&B?.bubbleClass&&C.classList.add(B.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),w&&B&&(B.containerClass&&F.classList.add(B.containerClass),F.style.setProperty("--persona-stream-step",`${S.speed}ms`),F.style.setProperty("--persona-stream-duration",`${S.duration}ms`));let q=w?Bi(e.content??"",S.buffer,B,e,!!e.streaming):e.content??"",O=t({text:q,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=O;w&&B?.wrap==="char"?z=qa(O,"char",e.id,{skipTags:B.skipTags}):w&&B?.wrap==="word"&&(z=qa(O,"word",e.id,{skipTags:B.skipTags}));let le=null;if(T?(le=document.createElement("div"),le.innerHTML=z,le.style.display="none",F.appendChild(le)):F.innerHTML=z,w&&B?.useCaret&&!T&&L){let ee=Hi(),Ce=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ae=Ce[Ce.length-1];if(Ae?.parentNode)Ae.parentNode.insertBefore(ee,Ae.nextSibling);else{let be=F.lastElementChild;be?be.appendChild(ee):F.appendChild(ee)}}if(u&&f==="inline"&&e.createdAt){let ee=ng(e,d,"span");ee.classList.add("persona-timestamp-inline");let Ce=F.lastElementChild;Ce?Ce.appendChild(ee):F.appendChild(ee)}if(M.length>0){let ee=Px(M,!T&&!!L,()=>{T&&le&&(le.style.display="")});ee?C.appendChild(ee):T&&le&&(le.style.display="")}let ue=Ex(e);if(ue.length>0){let ee=Rx(ue);ee&&C.appendChild(ee)}let Ee=kx(e);if(Ee.length>0){let ee=Ix(Ee);ee&&C.appendChild(ee)}let De=Lx(e);if(De.length>0){let ee=Bx(De);ee&&C.appendChild(ee)}if(C.appendChild(F),u&&f==="below"&&e.createdAt){let ee=ng(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let se=e.role==="assistant"?Ax(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(q&&q.trim()),Ce=S.placeholder==="skeleton",Ae=Ce&&S.buffer==="line"&ⅇif(ee)Ae&&C.appendChild(Va());else if(Ce)C.appendChild(Va());else{let be=Ap("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);be&&C.appendChild(be)}}if(se&&e.stopReason&&!e.streaming&&(L||(F.style.display="none"),C.appendChild(Sx(e.stopReason,se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&r?.enabled!==!1&&r){let ee=Sp(e,r,n);C.appendChild(ee)}if(!c||e.role==="system")return C;let Y=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=Hx(p,e.role);return g==="right"||g==="left"&&e.role==="user"?Y.append(C,de):Y.append(de,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},sg=(e,t,o,r,n,a)=>{let s=o??{};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}):qn(e,t,o,r,n,a)};var Vn=new Set,Dx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Fx=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).slice(0,t).join(`
|
|
35
|
+
`):""},ig=(e,t)=>{let o=Vn.has(e),r=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!n)return;r.setAttribute("aria-expanded",o?"true":"false");let l=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=ne(o?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=o?"Hide":"Show"}n.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")},Tp=(e,t)=>{let o=e.reasoning,r=y("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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!o)return r;let n=t?.features?.reasoningDisplay??{},a=n.expandable!==!1,s=a&&Vn.has(e.id),l=o.status!=="complete",p=Fx(e,n.previewMaxLines??3),d=y("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");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=t?.reasoning??{},h=String(o.startedAt??Date.now()),C=()=>{let ue=y("span","");return ue.setAttribute("data-tool-elapsed",h),ue.textContent=zs(o),ue},M=f.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:zs(o),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,c.appendChild(u)):M instanceof HTMLElement?c.appendChild(M):(u.textContent=g,c.appendChild(u));let L=y("span","persona-text-xs persona-text-persona-primary");L.textContent=jf(o),c.appendChild(L);let A=n.loadingAnimation??"none",T=f.activeTextTemplate,S=f.completeTextTemplate,E=l?T:S,B=M instanceof HTMLElement,H=(ue,Ee)=>{u.textContent="";let De=$s(ue,""),se=0;for(let xe of De){let Y=xe.styles.length>0?(()=>{let de=y("span",xe.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return u.appendChild(de),de})():u;if(xe.isDuration&&l)Y.appendChild(C());else{let de=xe.isDuration?zs(o):xe.text;Ee?se=xr(Y,de,se):Y.appendChild(document.createTextNode(de))}}};if(!B&&E)if(L.style.display="none",u.style.display="",l&&A!=="none"){let ue=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),A==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),H(E,!1)):(u.classList.add(`persona-tool-loading-${A}`),u.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),A==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),H(E,!0))}else H(E,!1);else if(!B&&l&&A!=="none"){u.style.display="";let ue=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),A==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ue}ms`);else{u.classList.add(`persona-tool-loading-${A}`),u.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),A==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ee=u.textContent||g;u.textContent="",xr(u,Ee,0)}o.status==="complete"&&(u.style.display="none")}else B||(o.status==="complete"?u.style.display="none":u.style.display="");let w=null;if(a){w=y("div","persona-flex persona-items-center");let Ee=ne(s?"chevron-up":"chevron-down",16,"currentColor",2);Ee?w.appendChild(Ee):w.textContent=s?"Hide":"Show";let De=y("div","persona-flex persona-items-center persona-ml-auto");De.append(w),d.append(c,De)}else d.append(c);let F=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","reasoning"),F.style.display="none",F.style.whiteSpace="pre-wrap",!s&&l&&n.activePreview&&p){let ue=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:p,isActive:l,config:t??{}});Dx(F,ue)||(F.textContent=p),F.style.display=""}if(!s&&l&&n.activeMinHeight&&(r.style.minHeight=n.activeMinHeight),!a)return r.append(d,F),r;let q=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");q.style.display=s?"":"none";let O=o.chunks.join(""),z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return z.textContent=O||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),q.appendChild(z),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),w){w.innerHTML="";let Ee=ne(s?"chevron-up":"chevron-down",16,"currentColor",2);Ee?w.appendChild(Ee):w.textContent=s?"Hide":"Show"}q.style.display=s?"":"none",F.style.display=s?"none":F.textContent||F.childNodes.length?"":"none"})(),r.append(d,F,q),r};var zn=new Set,Ox=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Nx=(e,t)=>{let o=e.toolCall;if(!o)return"";let r=(o.chunks??[]).join("").trim();if(r)return r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(-t).join(`
|
|
36
|
+
`);let n=fr(o.args).trim();return n?n.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
37
|
+
`):""},Mp=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},_x=(e,t)=>{let o=e.toolCall,r=t?.features?.toolCallDisplay,n=r?.collapsedMode??"tool-call",a=Nx(e,r?.previewMaxLines??3),s=o?Gf(o):"";if(!o)return{summary:s,previewText:a,isActive:!1};let l=o.status!=="complete",p=t?.toolCall??{},d=s;return n==="tool-name"?d=o.name?.trim()||s:n==="tool-preview"&&a&&(d=a),l&&p.activeTextTemplate?d=Zl(o,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=Zl(o,p.completeTextTemplate,d)),{summary:d,previewText:a,isActive:l}},lg=(e,t,o)=>{let r=zn.has(e),n=o?.toolCall??{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",r?"true":"false");let d=a.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",u=ne(r?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=r?"Hide":"Show"}s.style.display=r?"":"none",l&&(l.style.display=r?"none":l.textContent||l.childNodes.length?"":"none")},Ep=(e,t)=>{let o=e.toolCall,r=t?.toolCall??{},n=y("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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),r.backgroundColor&&(n.style.backgroundColor=r.backgroundColor),r.borderColor&&(n.style.borderColor=r.borderColor),r.borderWidth&&(n.style.borderWidth=r.borderWidth),r.borderRadius&&(n.style.borderRadius=r.borderRadius),n.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return n;let a=t?.features?.toolCallDisplay??{},s=a.expandable!==!1,l=s&&zn.has(e.id),{summary:p,previewText:d,isActive:c}=_x(e,t),u=y("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");u.type="button",s&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let h=String(o.startedAt??Date.now()),C=()=>{let O=y("span","");return O.setAttribute("data-tool-elapsed",h),O.textContent=ka(o),O},M=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:d,collapsedMode:a.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:ka(o),createElapsedElement:C});typeof M=="string"&&M.trim()?(f.textContent=M,g.appendChild(f)):M instanceof HTMLElement?g.appendChild(M):(f.textContent=p,g.appendChild(f));let L=a.loadingAnimation??"none",A=r.activeTextTemplate,T=r.completeTextTemplate,S=c?A:T,E=M instanceof HTMLElement,B=(O,z)=>{f.textContent="";let le=o.name?.trim()||"tool",ue=$s(O,le),Ee=0;for(let De of ue){let se=De.styles.length>0?(()=>{let xe=y("span",De.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(xe),xe})():f;if(De.isDuration&&c)se.appendChild(C());else{let xe=De.isDuration?ka(o):De.text;z?Ee=xr(se,xe,Ee):se.appendChild(document.createTextNode(xe))}}};if(!E)if(c&&L!=="none"){let O=r.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),S&&B(S,!1);else if(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),L==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),S)B(S,!0);else{let z=f.textContent||p;f.textContent="",xr(f,z,0)}}else S&&B(S,!1);let H=null;if(s){H=y("div","persona-flex persona-items-center");let O=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",z=ne(l?"chevron-up":"chevron-down",16,O,2);z?H.appendChild(z):H.textContent=l?"Hide":"Show";let le=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");le.append(H),u.append(g,le)}else u.append(g);let w=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(w.setAttribute("data-persona-collapsed-preview","tool"),w.style.display="none",w.style.whiteSpace="pre-wrap",!l&&c&&a.activePreview&&d){let O=r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:d,isActive:c,config:t??{}});Ox(w,O)||(w.textContent=d),w.style.display=""}if(!l&&c&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(u,w),n;let F=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(F.style.display=l?"":"none",r.contentBackgroundColor&&(F.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(F.style.color=r.contentTextColor),r.contentPaddingX&&(F.style.paddingLeft=r.contentPaddingX,F.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(F.style.paddingTop=r.contentPaddingY,F.style.paddingBottom=r.contentPaddingY),o.name){let O=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?O.style.color=r.contentTextColor:r.headerTextColor&&(O.style.color=r.headerTextColor),O.textContent=o.name,F.appendChild(O)}if(o.args!==void 0){let O=y("div","persona-space-y-1"),z=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(z.style.color=r.labelTextColor),z.textContent="Arguments";let le=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",Mp(le,r),le.textContent=fr(o.args),O.append(z,le),F.appendChild(O)}if(o.chunks&&o.chunks.length){let O=y("div","persona-space-y-1"),z=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(z.style.color=r.labelTextColor),z.textContent="Activity";let le=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",Mp(le,r),le.textContent=o.chunks.join(""),O.append(z,le),F.appendChild(O)}if(o.status==="complete"&&o.result!==void 0){let O=y("div","persona-space-y-1"),z=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(z.style.color=r.labelTextColor),z.textContent="Result";let le=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");le.style.fontSize="0.75rem",le.style.lineHeight="1rem",Mp(le,r),le.textContent=fr(o.result),O.append(z,le),F.appendChild(O)}if(o.status==="complete"&&typeof o.duration=="number"){let O=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(O.style.color=r.contentTextColor),O.textContent=`Duration: ${o.duration}ms`,F.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),H){H.innerHTML="";let O=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",z=ne(l?"chevron-up":"chevron-down",16,O,2);z?H.appendChild(z):H.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",w.style.display=l?"none":w.textContent||w.childNodes.length?"":"none"})(),n.append(u,w,F),n};var an=new Map,$i=e=>{let o=(e.startsWith(So)?e.slice(So.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(o.length===0)return e;let r=o.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},dg=e=>e?.approval!==!1?e?.approval:void 0,cg=(e,t)=>{let o=dg(t)?.detailsDisplay??"collapsed";return an.get(e)??o==="expanded"},pg=(e,t,o)=>{let r=dg(o);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?r?.hideDetailsLabel??"Hide details":r?.showDetailsLabel??"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let s=ne(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},ug=(e,t,o)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!r||!n)return;let a=cg(e,o);pg(r,a,o),n.style.display=a?"":"none"};var ji=(e,t)=>{let o=e.approval,r=t?.approval!==!1?t?.approval:void 0,n=o?.status==="pending",a=y("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=r?.backgroundColor??"var(--persona-approval-bg, #fefce8)",a.style.borderColor=r?.borderColor??"var(--persona-approval-border, #fef08a)",a.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return a;let s=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=y("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=o.status==="denied"?"shield-x":o.status==="timeout"?"shield-alert":"shield-check",d=o.status==="approved"?"var(--persona-feedback-success, #16a34a)":o.status==="denied"?"var(--persona-feedback-error, #dc2626)":o.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":r?.titleColor??"currentColor",c=ne(p,20,d,2);c&&l.appendChild(c);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(f.style.color=r.titleColor),f.textContent=r?.title??"Approval Required",g.appendChild(f),!n){let H=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");H.setAttribute("data-approval-status",o.status),o.status==="approved"?(H.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",H.style.color="var(--persona-palette-colors-success-700, #15803d)",H.textContent="Approved"):o.status==="denied"?(H.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",H.style.color="var(--persona-palette-colors-error-700, #b91c1c)",H.textContent="Denied"):o.status==="timeout"&&(H.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",H.style.color="var(--persona-palette-colors-warning-700, #b45309)",H.textContent="Timeout"),g.appendChild(H)}u.appendChild(g);let C=o.toolType==="webmcp"||o.toolName.startsWith(So)?wa(o.toolName):void 0,M=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...C?{displayTitle:C}:{},...o.reason?{reason:o.reason}:{}}),L=!o.toolName,A=M||(L?o.description:`The assistant wants to use \u201C${C??$i(o.toolName)}\u201D.`),T=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(T.style.color=r.descriptionColor),T.textContent=A,u.appendChild(T),o.reason){let H=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");H.setAttribute("data-approval-reason","true"),r?.reasonColor?H.style.color=r.reasonColor:r?.descriptionColor&&(H.style.color=r.descriptionColor);let w=y("span","persona-font-medium");w.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,H.appendChild(w),H.appendChild(document.createTextNode(o.reason)),u.appendChild(H)}let S=r?.detailsDisplay??"collapsed",E=!!o.description&&!L,B=E||!!o.parameters;if(S!=="hidden"&&B){let H=cg(e.id,t),w=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");w.type="button",w.setAttribute("data-expand-header","true"),w.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(w.style.color=r.descriptionColor);let F=y("span");F.setAttribute("data-approval-details-label","true");let q=y("span","persona-inline-flex persona-items-center");q.setAttribute("data-approval-details-chevron","true"),w.append(F,q),pg(w,H,t),u.appendChild(w);let O=y("div");if(O.setAttribute("data-approval-details","true"),O.style.display=H?"":"none",E){let z=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(z.style.color=r.descriptionColor),z.textContent=o.description,O.appendChild(z)}if(o.parameters){let z=y("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");r?.parameterBackgroundColor&&(z.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(z.style.color=r.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=fr(o.parameters),O.appendChild(z)}u.appendChild(O)}if(n){let H=y("div","persona-flex persona-gap-2 persona-mt-2");H.setAttribute("data-approval-buttons","true");let w=y("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");w.type="button",w.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",w.style.color=r?.approveButtonTextColor??"#ffffff",w.setAttribute("data-approval-action","approve");let F=ne("shield-check",14,r?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",w.appendChild(F));let q=document.createTextNode(r?.approveLabel??"Approve");w.appendChild(q);let O=y("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");O.type="button",O.style.backgroundColor=r?.denyButtonColor??"transparent",O.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let z=ne("shield-x",14,r?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);z&&(z.style.marginRight="4px",O.appendChild(z));let le=document.createTextNode(r?.denyLabel??"Deny");O.appendChild(le),H.append(w,O),u.appendChild(H)}return s.append(l,u),a.appendChild(s),a};function Ux(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function fg(e){let{anchor:t,content:o,placement:r="bottom-start",offset:n=6,matchAnchorWidth:a=!1,zIndex:s=2147483e3,onOpen:l,onDismiss:p}=e,d=e.container??Ux(t),c=!1,u=null,g=()=>{if(!c)return;let C=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${C.width}px`);let M=r==="top-start"||r==="top-end"?C.top-n-o.getBoundingClientRect().height:C.bottom+n,L=r==="bottom-end"||r==="top-end"?C.right-o.getBoundingClientRect().width:C.left;o.style.top=`${M}px`,o.style.left=`${L}px`},f=()=>{c&&(c=!1,u&&(u(),u=null),o.remove())},h=()=>{if(c)return;c=!0,s!=null&&(o.style.zIndex=String(s)),d.appendChild(o),g();let C=(t.ownerDocument??document).defaultView??window,M=t.ownerDocument??document,L=()=>{if(!t.isConnected){f(),p?.("anchor-removed");return}g()},A=S=>{let E=typeof S.composedPath=="function"?S.composedPath():[];E.includes(o)||E.includes(t)||(f(),p?.("outside"))},T=C.setTimeout(()=>{M.addEventListener("pointerdown",A,!0)},0);C.addEventListener("scroll",L,!0),C.addEventListener("resize",L),u=()=>{C.clearTimeout(T),M.removeEventListener("pointerdown",A,!0),C.removeEventListener("scroll",L,!0),C.removeEventListener("resize",L)},l?.()};return{get isOpen(){return c},open:h,close:f,toggle:()=>c?f():h(),reposition:g,destroy:f}}function mg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(o=>o instanceof HTMLElement&&(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable))}var qx=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),gg=(e,t)=>{let o=e.keyHandlers.get(t);o&&(document.removeEventListener("keydown",o),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},sn=(e,t)=>{gg(e,t);let o=e.pendingOrder.indexOf(t);o!==-1&&e.pendingOrder.splice(o,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Vx=e=>e?.approval!==!1?e?.approval:void 0,zx=(e,t)=>{let o=t?.detailsDisplay??"collapsed";return an.get(e)??o==="expanded"},kp=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},$x=(e,t)=>{let o=y("span","persona-approval-title");t?.titleColor&&(o.style.color=t.titleColor);let n=e.toolType==="webmcp"||e.toolName.startsWith(So)?wa(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...n?{displayTitle:n}:{},...e.reason?{reason:e.reason}:{}});if(a)return o.textContent=a,o;let s=n??$i(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;o.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=s,o.appendChild(p),l){o.append(" from ");let d=document.createElement("strong");d.textContent=l,o.appendChild(d)}return o},jx=e=>{let t=y("div","persona-approval-resolved"),o=ne("ban",15,"currentColor",2);o&&t.appendChild(o);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?$i(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Gx=(e,t,o,r,n,a,s)=>{let l=y("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(l.style.background=r.backgroundColor),r?.borderColor&&(l.style.borderColor=r.borderColor),r?.shadow!==void 0&&(l.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",d=!!o.description&&p!=="hidden",c=o.parameters!=null&&p!=="hidden",u=d||c,g=u&&zx(t.id,r),f=r?.showDetailsLabel??"Show details",h=r?.hideDetailsLabel??"Hide details",C=y("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",g?"true":"false"),C.setAttribute("aria-label",g?h:f)):C.setAttribute("data-static","true");let M=y("span","persona-approval-logo"),L=ne("shield-check",16,"currentColor",2);L&&M.appendChild(L),C.appendChild(M);let A=$x(o,r);if(u){let w=y("span","persona-approval-toggle");w.setAttribute("aria-hidden","true");let F=ne("chevron-down",14,"currentColor",2);F&&w.appendChild(F),A.append(" "),A.appendChild(w)}C.appendChild(A),l.appendChild(C);let T=y("div","persona-approval-body");if(u){let w=y("div","persona-approval-details");if(w.setAttribute("data-role","params"),w.hidden=!g,d){let F=y("p","persona-approval-desc");r?.descriptionColor&&(F.style.color=r.descriptionColor),F.textContent=o.description,w.appendChild(F)}if(c){let F=y("pre","persona-approval-params");r?.parameterBackgroundColor&&(F.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(F.style.color=r.parameterTextColor),F.textContent=fr(o.parameters),w.appendChild(F)}T.appendChild(w)}if(o.reason){let w=y("p","persona-approval-reason");r?.reasonColor?w.style.color=r.reasonColor:r?.descriptionColor&&(w.style.color=r.descriptionColor);let F=y("span","persona-approval-reason-label");F.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,w.append(F,document.createTextNode(o.reason)),T.appendChild(w)}let S=y("div","persona-approval-actions"),E=null,B=w=>{r?.approveButtonColor&&(w.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(w.style.color=r.approveButtonTextColor)},H=y("button","persona-approval-deny");if(H.type="button",H.setAttribute("data-action","deny"),r?.denyButtonColor&&(H.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(H.style.color=r.denyButtonTextColor),H.append(r?.denyLabel??"Deny"),s){let w=y("div","persona-approval-split"),F=y("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),B(F),F.append(r?.approveLabel??"Always allow",kp("\u23CE"));let q=y("button","persona-approval-caret");q.type="button",q.setAttribute("data-action","toggle-menu"),q.setAttribute("aria-label","More options"),B(q);let O=ne("chevron-down",15,"currentColor",2);O&&q.appendChild(O),w.append(F,q),S.append(w,H),H.append(kp("Esc"));let z=y("div","persona-approval-menu"),le=y("button","persona-approval-menu-item");le.type="button",le.append("Allow once",kp("\u2318\u23CE")),z.appendChild(le),E=fg({anchor:w,content:z,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,E),le.addEventListener("click",()=>{sn(e,t.id),n()})}else{let w=y("button","persona-approval-primary persona-approval-primary--solo");w.type="button",w.setAttribute("data-action","allow"),B(w),w.append(r?.approveLabel??"Allow"),S.append(w,H)}return T.appendChild(S),l.appendChild(T),l.addEventListener("click",w=>{let F=w.target instanceof Element?w.target.closest("[data-action]"):null;if(!F)return;let q=F.getAttribute("data-action");if(q==="toggle-params"){let O=l.querySelector('[data-role="params"]');if(O){let z=O.hidden;O.hidden=!z,C.setAttribute("aria-expanded",z?"true":"false"),C.setAttribute("aria-label",z?h:f),an.set(t.id,z)}return}if(q==="toggle-menu"){E?.toggle();return}if(q==="always"){sn(e,t.id),n({remember:!0});return}if(q==="allow"){sn(e,t.id),n();return}if(q==="deny"){sn(e,t.id),a();return}}),l},hg=()=>{let e=qx();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:n,deny:a,config:s})=>{let l=r?.approval;if(!l)return null;let p=Vx(s);if(l.status!=="pending"){if(sn(e,r.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return jx(l)}gg(e,r.id);let d=p?.enableAlwaysAllow===!0,c=Gx(e,r,l,p,n,a,d);if(d){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{mg(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),sn(e,r.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?n():n({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])sn(e,r);e.latestPendingApprovalId=null}}};var yg=e=>{let t=[],o=null;return{buttons:t,render:(n,a,s,l,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(o=null),!n||!n.length||!c&&(l??(a?a.getMessages():[])).some(M=>M.role==="user"))return;let u=document.createDocumentFragment(),g=a?a.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(h=>{let C=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=h,C.disabled=g,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),a.sendMessage(h))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let h=JSON.stringify(n);h!==o&&(o=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var ja=class{constructor(t=2e3,o=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=o}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let o=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of o)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,o.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let o=this.getAll();return t>=o.length?o:o.slice(o.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ga=class{constructor(t="persona-event-stream",o="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=o}open(){return new Promise((t,o)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{o(r.error)}}catch(r){o(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)r.put(n)}catch{}}getAll(){return new Promise((t,o)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{o(s.error)}}catch(r){o(r)}})}getCount(){return new Promise((t,o)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{o(a.error)}}catch(r){o(r)}})}clear(){return new Promise((t,o)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{o(a.error)}}catch(r){o(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,o)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{o(r.error)}}catch(r){o(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)r.put(n)}catch{}}};var Kx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Xx=new Set(["step_start","execution_start"]),Jx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Qx=new Set(["step_complete","agent_turn_complete"]),Yx=new Set(["flow_complete","agent_complete"]),bg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),vg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),co=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ln=(e,t)=>{let o=e[t];return vg(o)?o:void 0};function Lp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Gi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Zx(e,t){return typeof t.type=="string"?t.type:e}function ev(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function tv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function xg(e){let t=ln(e,"result"),o=[ln(e,"tokens"),ln(e,"totalTokens"),t?ln(t,"tokens"):void 0,ln(e,"usage"),t?ln(t,"usage"):void 0];for(let r of o){if(!r)continue;let n=co(r.output)??co(r.outputTokens)??co(r.completionTokens);if(n!==void 0)return n}return co(e.outputTokens)??co(e.completionTokens)??(t?co(t.outputTokens)??co(t.completionTokens):void 0)}function ov(e){let t=ln(e,"result");return co(e.executionTime)??co(e.executionTimeMs)??co(e.execution_time)??co(e.duration)??(t?co(t.executionTime)??co(t.executionTimeMs):void 0)}function rv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ka=class{constructor(t=rv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let o=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:o,tokensPerSecond:Gi(this.metric.outputTokens,o)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,o){if(!vg(o)){bg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Zx(t,o),n=this.now();if(Kx.has(r)){this.startRun(n);return}if(Xx.has(r)){this.run||this.startRun(n);return}if(Jx.has(r)){if(!tv(r,o))return;let a=ev(o);if(!a)return;this.run||this.startRun(n);let s=this.run;s.firstDeltaAt??(s.firstDeltaAt=n),s.visibleCharCount+=a.length;let l=s.exactOutputTokens+Lp(s.visibleCharCount),p=n-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Gi(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(Qx.has(r)){if(!this.run)return;let a=this.run,s=xg(o);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+Lp(a.visibleCharCount),d=this.resolveDuration(a,o,n);this.metric={status:"running",tokensPerSecond:Gi(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Yx.has(r)){if(!this.run)return;let a=this.run,s=xg(o),l=s??a.exactOutputTokens+Lp(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(a,o,n);this.metric={status:"complete",tokensPerSecond:Gi(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(bg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,o,r){let n=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;return n!==void 0&&n>=250?n:ov(o)??r-t.startedAt}};function $n(e,t){t&&t.split(/\s+/).forEach(o=>o&&e.classList.add(o))}var nv={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)"}},av={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},sv=["flowName","stepName","reasoningText","text","name","tool","toolName"],iv=100;function lv(e,t){let o={...nv,...t};if(o[e])return o[e];for(let r of Object.keys(o))if(r.endsWith("_")&&e.startsWith(r))return o[r];return av}function dv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function cv(e){let t=new Date(e),o=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${o}:${r}:${n}.${a}`}function pv(e,t){try{let o=JSON.parse(e);if(typeof o!="object"||o===null)return null;for(let r of t){let n=r.split("."),a=o;for(let s of n)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 uv(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),t()})}function fv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function mv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function gv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function hv(e,t,o){let r,n;try{n=JSON.parse(e.payload),r=JSON.stringify(n,null,2)}catch{n=e.payload,r=e.payload}let a=t.find(l=>l.renderEventStreamPayload);if(a?.renderEventStreamPayload&&o){let l=a.renderEventStreamPayload({event:e,config:o,defaultRenderer:()=>s(),parsedPayload:n});if(l)return l}return s();function s(){let l=y("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]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=r,l.appendChild(p),l}}function Pp(e,t,o,r,n,a,s,l){let p=n.has(e.id),d=y("div","persona-border-b persona-border-persona-divider persona-text-xs");$n(d,r.classNames?.eventRow);let c=s.find(g=>g.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let g=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return d.appendChild(g),d}return d.appendChild(u()),d;function u(){let g=y("div",""),f=y("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");f.setAttribute("data-event-id",e.id);let h=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ne(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&h.appendChild(C);let M=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=r.timestampFormat??"relative";M.textContent=L==="relative"?dv(e.timestamp,o):cv(e.timestamp);let A=null;r.showSequenceNumbers!==!1&&(A=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),A.textContent=String(t+1));let T=lv(e.type,r.badgeColors),S=y("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");S.style.backgroundColor=T.bg,S.style.color=T.text,S.style.borderColor=T.text+"50",S.textContent=e.type;let E=r.descriptionFields??sv,B=pv(e.payload,E),H=null;B&&(H=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=B);let w=y("div","persona-flex-1 persona-min-w-0"),F=y("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"),q=ne("clipboard","12px","currentColor",1.5);return q&&F.appendChild(q),F.addEventListener("click",async O=>{O.stopPropagation(),await uv(fv(e)),F.innerHTML="";let z=ne("check","12px","currentColor",1.5);z&&F.appendChild(z),setTimeout(()=>{F.innerHTML="";let le=ne("clipboard","12px","currentColor",1.5);le&&F.appendChild(le)},1500)}),f.appendChild(h),f.appendChild(M),A&&f.appendChild(A),f.appendChild(S),H&&f.appendChild(H),f.appendChild(w),f.appendChild(F),g.appendChild(f),p&&g.appendChild(hv(e,s,l)),g}}function Cg(e){let{buffer:t,getFullHistory:o,onClose:r,config:n,plugins:a=[],getThroughput:s}=e,l=n?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=n?.features?.eventStream??{},g=a.find(h=>h.renderEventStreamView);if(g?.renderEventStreamView&&n){let h=g.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,C=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");$n(C,h?.panel);let M=[],L="",A="",T=null,S=[],E={},B=0,H=Li(),w=0,F=0,q=!1,O=null,z=!1,le=0,ue=new Set,Ee=new Map,De="",se="",xe=null,Y,de,ee,Ce,Ae=null,be=null,He=null;function Oe(){let _=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=y("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");if($n(j,h?.headerBar),s){be=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),be.style.cursor="help",Ae=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ae.textContent="-- tok/s",He=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),He.style.display="none",He.style.pointerEvents="none";let Qe=be,Mr=He,Er=()=>{if(!Mr.textContent)return;let rs=Qe.getBoundingClientRect(),Zt=_.getBoundingClientRect();Mr.style.left=`${rs.left-Zt.left}px`,Mr.style.top=`${rs.bottom-Zt.top+4}px`,Mr.style.display="block"},nl=()=>{Mr.style.display="none"};be.addEventListener("mouseenter",Er),be.addEventListener("mouseleave",nl),be.appendChild(Ae)}let re=y("div","persona-flex-1");Y=y("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 tt=y("option","");tt.value="",tt.textContent="All events (0)",Y.appendChild(tt),de=y("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"),de.type="button",de.title="Copy All";let dt=ne("clipboard-copy","12px","currentColor",1.5);dt&&de.appendChild(dt);let G=y("span","persona-event-copy-all persona-text-xs");G.textContent="Copy All",de.appendChild(G),be&&j.appendChild(be),j.appendChild(re),j.appendChild(Y),j.appendChild(de);let qe=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");$n(qe,h?.searchBar);let ve=ne("search","14px","var(--persona-muted, #9ca3af)",1.5),Ie=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");ve&&Ie.appendChild(ve),ee=y("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"),$n(ee,h?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",Ce=y("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"),Ce.type="button",Ce.style.display="none";let Me=ne("x","12px","currentColor",2);return Me&&Ce.appendChild(Me),qe.appendChild(Ie),qe.appendChild(ee),qe.appendChild(Ce),_.appendChild(j),_.appendChild(qe),He&&_.appendChild(He),_}let Ke,Ue=a.find(_=>_.renderEventStreamToolbar);Ue?.renderEventStreamToolbar&&n?Ke=Ue.renderEventStreamToolbar({config:n,defaultRenderer:()=>Oe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{L=j,Le(),he()},onSearchChange:j=>{A=j,Le(),he()}})??Oe():Ke=Oe();let ke=y("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");ke.style.display="none";function Re(){if(!s||!Ae||!be)return;let _=s(),j=mv(_);Ae.textContent=j;let re=gv(_);He&&(He.textContent=re,re||(He.style.display="none")),be.setAttribute("aria-label",re?`Throughput: ${j}, ${re}`:`Throughput: ${j}`)}let it=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Ne=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Ne.style.height="100%";let Je=y("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");$n(Je,h?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let po=ne(d,"14px","currentColor",2);po&&Je.appendChild(po);let Lt=y("span","");Lt.textContent=c,Je.appendChild(Lt);let mt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");mt.style.display="none",it.appendChild(Ne),it.appendChild(mt),it.appendChild(Je),C.setAttribute("tabindex","0"),C.appendChild(Ke),C.appendChild(ke),C.appendChild(it);function Se(){let _=t.getAll(),j={};for(let qe of _)j[qe.type]=(j[qe.type]||0)+1;let re=Object.keys(j).sort(),tt=re.length!==S.length||!re.every((qe,ve)=>qe===S[ve]),Pe=!tt&&re.some(qe=>j[qe]!==E[qe]),dt=_.length!==Object.values(E).reduce((qe,ve)=>qe+ve,0);if(!tt&&!Pe&&!dt||(S=re,E=j,!Y))return;let G=Y.value;if(Y.options[0].textContent=`All events (${_.length})`,tt){for(;Y.options.length>1;)Y.remove(1);for(let qe of re){let ve=y("option","");ve.value=qe,ve.textContent=`${qe} (${j[qe]||0})`,Y.appendChild(ve)}G&&re.includes(G)?Y.value=G:G&&(Y.value="",L="")}else for(let qe=1;qe<Y.options.length;qe++){let ve=Y.options[qe];ve.textContent=`${ve.value} (${j[ve.value]||0})`}}function me(){let _=t.getAll();if(L&&(_=_.filter(j=>j.type===L)),A){let j=A.toLowerCase();_=_.filter(re=>re.type.toLowerCase().includes(j)||re.payload.toLowerCase().includes(j))}return _}function lt(){return L!==""||A!==""}function Le(){B=0,w=0,H.resume(),Je.style.display="none"}function fe(_){ue.has(_)?ue.delete(_):ue.add(_),xe=_;let j=Ne.scrollTop,re=H.isFollowing();z=!0,H.pause(),he(),Ne.scrollTop=j,re&&H.resume(),z=!1}function ie(){return Ar(Ne,50)}function he(){F=Date.now(),q=!1,Re(),Se();let _=t.getEvictedCount();_>0?(ke.textContent=`${_.toLocaleString()} older events truncated`,ke.style.display=""):ke.style.display="none",M=me();let j=M.length,re=t.getSize()>0;j===0&&re&<()?(mt.textContent=A?`No events matching '${A}'`:"No events matching filter",mt.style.display="",Ne.style.display="none"):(mt.style.display="none",Ne.style.display=""),de&&(de.title=lt()?`Copy Filtered (${j})`:"Copy All"),p&&!H.isFollowing()&&j>B&&(w+=j-B,Lt.textContent=c?`${c}${w>0?` (${w})`:""}`:"",Je.style.display=""),B=j;let tt=t.getAll(),Pe=tt.length>0?tt[0].timestamp:0,dt=new Set(M.map(ve=>ve.id));for(let ve of ue)dt.has(ve)||ue.delete(ve);let G=L!==De||A!==se,qe=Ee.size===0&&M.length>0;if(G||qe||M.length===0){Ne.innerHTML="",Ee.clear();let ve=document.createDocumentFragment();for(let Ie=0;Ie<M.length;Ie++){let Me=Pp(M[Ie],Ie,Pe,u,ue,fe,a,n);Ee.set(M[Ie].id,Me),ve.appendChild(Me)}Ne.appendChild(ve),De=L,se=A,xe=null}else{if(xe!==null){let Ie=Ee.get(xe);if(Ie&&Ie.parentNode===Ne){let Me=M.findIndex(Qe=>Qe.id===xe);if(Me>=0){let Qe=Pp(M[Me],Me,Pe,u,ue,fe,a,n);Ne.insertBefore(Qe,Ie),Ie.remove(),Ee.set(xe,Qe)}}xe=null}let ve=new Set(M.map(Ie=>Ie.id));for(let[Ie,Me]of Ee)ve.has(Ie)||(Me.remove(),Ee.delete(Ie));for(let Ie=0;Ie<M.length;Ie++){let Me=M[Ie];if(!Ee.has(Me.id)){let Qe=Pp(Me,Ie,Pe,u,ue,fe,a,n);Ee.set(Me.id,Qe),Ne.appendChild(Qe)}}}H.isFollowing()&&(Ne.scrollTop=Ne.scrollHeight)}function xt(){if(Date.now()-F>=iv){O!==null&&(cancelAnimationFrame(O),O=null),he();return}q||(q=!0,O=requestAnimationFrame(()=>{O=null,he()}))}let U=(_,j)=>{if(!de)return;de.innerHTML="";let re=ne(_,"12px","currentColor",1.5);re&&de.appendChild(re);let tt=y("span","persona-text-xs");tt.textContent="Copy All",de.appendChild(tt),setTimeout(()=>{de.innerHTML="";let Pe=ne("clipboard-copy","12px","currentColor",1.5);Pe&&de.appendChild(Pe);let dt=y("span","persona-text-xs");dt.textContent="Copy All",de.appendChild(dt),de.disabled=!1},j)},te=async()=>{if(de){de.disabled=!0;try{let _;lt()?_=M:o?(_=await o(),_.length===0&&(_=t.getAll())):_=t.getAll();let j=_.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),U("check",1500)}catch{U("x",1500)}}},We=()=>{Y&&(L=Y.value,Le(),he())},Te=()=>{!ee||!Ce||(Ce.style.display=ee.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{A=ee.value,Le(),he()},150))},R=()=>{!ee||!Ce||(ee.value="",A="",Ce.style.display="none",T&&clearTimeout(T),Le(),he())},J=()=>{if(z)return;let _=Ne.scrollTop,{action:j,nextLastScrollTop:re}=Pi({following:H.isFollowing(),currentScrollTop:_,lastScrollTop:le,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});le=re,j==="resume"?(H.resume(),w=0,Je.style.display="none"):j==="pause"&&(H.pause(),p&&(Lt.textContent=c,Je.style.display=""))},x=_=>{let j=Ri({following:H.isFollowing(),deltaY:_.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});j==="pause"?(H.pause(),p&&(Lt.textContent=c,Je.style.display="")):j==="resume"&&(H.resume(),w=0,Je.style.display="none")},k=()=>{p&&(Ne.scrollTop=Ne.scrollHeight,H.resume(),w=0,Je.style.display="none")},I=_=>{let j=_.target;if(!j||j.closest("button"))return;let re=j.closest("[data-event-id]");if(!re)return;let tt=re.getAttribute("data-event-id");tt&&fe(tt)},N=_=>{if((_.metaKey||_.ctrlKey)&&_.key==="f"){_.preventDefault(),ee?.focus(),ee?.select();return}_.key==="Escape"&&(ee&&document.activeElement===ee?(R(),ee.blur(),C.focus()):r&&r())};de&&de.addEventListener("click",te),Y&&Y.addEventListener("change",We),ee&&ee.addEventListener("input",Te),Ce&&Ce.addEventListener("click",R),Ne.addEventListener("scroll",J),Ne.addEventListener("wheel",x,{passive:!0}),Ne.addEventListener("click",I),Je.addEventListener("click",k),C.addEventListener("keydown",N);function K(){T&&clearTimeout(T),O!==null&&(cancelAnimationFrame(O),O=null),q=!1,Ee.clear(),de&&de.removeEventListener("click",te),Y&&Y.removeEventListener("change",We),ee&&ee.removeEventListener("input",Te),Ce&&Ce.removeEventListener("click",R),Ne.removeEventListener("scroll",J),Ne.removeEventListener("wheel",x),Ne.removeEventListener("click",I),Je.removeEventListener("click",k),C.removeEventListener("keydown",N)}return{element:C,update:xt,destroy:K}}}function wg(e,t){let o=t.orientation??"horizontal",r=o==="vertical"?"ArrowUp":"ArrowLeft",n=o==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let g=u;return a.findIndex(f=>f===g||f.contains(g))},d=u=>{let g=p(u.target);if(g<0)return;let f=g;if(u.key===n)f=Math.min(g+1,a.length-1);else if(u.key===r)f=Math.max(g-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=a.length-1;else return;u.preventDefault(),f!==g&&t.onSelect(f)},c=u=>{let g=p(u.target);g>=0&&l(a[g])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){s=typeof document<"u"&&e.contains(document.activeElement)},render(u,g){if(a=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let C=h===g;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||g<0&&h===0?0:-1}),s){let f=(g>=0?u[g]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Ag(e,t){let o=e.features?.artifacts?.layout,n=(o?.toolbarPreset??"default")==="document",a=o?.toolbarTitle??"Artifacts",s=o?.closeButtonLabel??"Close",l=o?.panePadding?.trim(),p=o?.tabFadeSize?.trim(),d=U=>({start:U===!1?!1:typeof U=="object"&&U?U.start!==!1:!0,end:U===!1?!1:typeof U=="object"&&U?U.end!==!1:!0}),{start:c,end:u}=d(o?.tabFade),g=typeof document<"u"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{g?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),z?.hide()};g&&g.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=y("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");h.setAttribute("data-persona-theme-zone","artifact-pane"),n&&h.classList.add("persona-artifact-pane-document");let C=y("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");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&C.classList.add("persona-artifact-toolbar-document");let M=y("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=a;let L=kt({icon:"x",label:s});L.addEventListener("click",()=>{f(),t.onDismiss?.()});let A="rendered",T=Fn({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:n?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:n?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:U=>{A=U==="source"?"source":"rendered",ie()}}),S=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=o?.documentToolbarShowCopyLabel===!0,B=o?.documentToolbarShowCopyChevron===!0,H=o?.documentToolbarCopyMenuItems,w=!!(B&&H&&H.length>0),F=null,q,O=null,z=null;if(n&&(E||B)&&!w){if(q=E?Go({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let U=ne("chevron-down",14,"currentColor",2);U&&q.appendChild(U)}}else n&&w?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),q=E?Go({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=kt({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"}}),F.append(q,O)):n?q=kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(q=kt({icon:"copy",label:"Copy"}),o?.showCopyButton!==!0&&q.classList.add("persona-hidden"));let le=n?kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):kt({icon:"refresh-cw",label:"Refresh"}),ue=n?kt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):kt({icon:"x",label:s}),Ee=kt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(n?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});o?.showExpandToggle!==!0&&Ee.classList.add("persona-hidden");let De=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),se=e.features?.artifacts?.toolbarActions??[],xe=()=>{let U=ke.find(R=>R.id===Re)??ke[ke.length-1],te=U?.id??null,We=U?.artifactType==="markdown"?U.markdown??"":"",Te=U?JSON.stringify({component:U.component,props:U.props},null,2):"";return{markdown:We,jsonPayload:Te,id:te}},Y=async()=>{let U=ke.find(te=>te.id===Re)??ke[ke.length-1];try{await navigator.clipboard.writeText(Na(U))}catch{}};if(q.addEventListener("click",async()=>{let U=o?.onDocumentToolbarCopyMenuSelect;if(U&&w){let{markdown:te,jsonPayload:We,id:Te}=xe();try{await U({actionId:"primary",artifactId:Te,markdown:te,jsonPayload:We})}catch{}return}await Y()}),O&&H?.length){let U=()=>h.closest("[data-persona-root]")??document.body,te=()=>{z=Cr({items:H.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:Te,jsonPayload:R,id:J}=xe(),x=o?.onDocumentToolbarCopyMenuSelect;try{x?await x({actionId:We,artifactId:J,markdown:Te,jsonPayload:R}):We==="markdown"||We==="md"?await navigator.clipboard.writeText(Te):We==="json"||We==="source"?await navigator.clipboard.writeText(R):await navigator.clipboard.writeText(Te||R)}catch{}},anchor:F??O,position:"bottom-right",portal:U()})};h.isConnected?te():requestAnimationFrame(te),O.addEventListener("click",We=>{We.stopPropagation(),z?.toggle()})}le.addEventListener("click",async()=>{try{await o?.onDocumentToolbarRefresh?.()}catch{}ie()}),ue.addEventListener("click",()=>{f(),t.onDismiss?.()});let de=y("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");if(n)C.replaceChildren(),F?S.append(F,le,ue):S.append(q,le,ue),S.insertBefore(De,ue),S.insertBefore(Ee,ue),C.append(T.element,de,S);else{let U=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");U.append(q,De,Ee,L),C.appendChild(M),C.appendChild(U)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ee=y("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");p&&ee.style.setProperty("--persona-artifact-tab-fade-size",p);let Ce=e.features?.artifacts?.renderTabBar,Ae=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),be=wg(ee,{onSelect:U=>t.onSelect(ke[U].id)}),He=U=>{let te=U.scrollWidth-U.clientWidth,We=te>1,Te=Math.abs(U.scrollLeft);U.classList.toggle("persona-artifact-tab-fade-start",c&&We&&Te>1),U.classList.toggle("persona-artifact-tab-fade-end",u&&We&&Te<te-1)},Oe=0,Ke=()=>{if(Oe)return;let U=()=>{Oe=0,He(ee)};Oe=typeof requestAnimationFrame=="function"?requestAnimationFrame(U):setTimeout(U,0)};ee.addEventListener("scroll",()=>Ke(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>He(ee)).observe(ee);let Ue=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(l){for(let U of[ee,Ae])U.style.paddingLeft=l,U.style.paddingRight=l;Ue.style.padding=l}h.appendChild(C),h.appendChild(ee),h.appendChild(Ae),h.appendChild(Ue);let ke=[],Re=null,it=!1,Ne=!0,Je=!1,po=null,Lt="",mt=null,Se=!1,me=U=>U.artifactType==="markdown"&&!!U.file||n?A:"rendered",lt=U=>{n||(U&&!Se?(C.insertBefore(T.element,M),Se=!0):!U&&Se&&(T.element.remove(),Se=!1))},Le=()=>Re&&ke.find(U=>U.id===Re)||ke[ke.length-1],fe=()=>{let U=Fa(Le());if(!U){De.replaceChildren();return}let te=se.filter(We=>We.visible===void 0||We.visible(U)).map(We=>On(We,{documentChrome:n,onClick:()=>{let Te=Fa(Le());if(Te)try{Promise.resolve(We.onClick(Te)).catch(()=>{})}catch{}}}));De.replaceChildren(...te)},ie=()=>{fe();let U=n&&ke.length<=1,te=!!Ce;if(ee.classList.toggle("persona-hidden",U||te),Ae.classList.toggle("persona-hidden",U||!te),te&&Ce){let R=ke.map(J=>J.id).join("|")+" "+(Re??"");if(R!==Lt){Lt=R;let J=Ce({records:ke,selectedId:Re,onSelect:t.onSelect});Ae.firstElementChild!==J&&Ae.replaceChildren(J)}}else{be.beforeRender(),ee.replaceChildren();let R=[],J=-1;for(let[x,k]of ke.entries()){let I=y("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");I.type="button";let N=k.artifactType==="markdown"?k.file:void 0,K=N?Bo(N.path):k.title||k.id.slice(0,8),_=N?.path||k.title||K;I.textContent=K,I.title=_,I.setAttribute("aria-label",_),k.id===Re&&(I.classList.add("persona-bg-persona-container","persona-border-persona-border"),J=x),I.addEventListener("click",()=>t.onSelect(k.id)),ee.appendChild(I),R.push(I)}if(be.render(R,J),J>=0&&Re!==po){po=Re;let x=R[J];typeof x.scrollIntoView=="function"&&x.scrollIntoView({block:"nearest",inline:"nearest"})}He(ee)}let We=Re&&ke.find(R=>R.id===Re)||ke[ke.length-1];if(!We){Ue.replaceChildren(),mt=null,lt(!1);return}let Te=We.artifactType==="markdown"?We.file:void 0;if(lt(!!Te),n){let R=Te?br(Te):We.artifactType==="markdown"?"MD":We.component??"Component",J=(We.title||"Document").trim(),x=Te?Bo(Te.path):J.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${x} \xB7 ${R}`}else M.textContent=Te?Bo(Te.path):a;mt?(mt.el.parentElement!==Ue&&Ue.replaceChildren(mt.el),mt.update(We)):(mt=Mi(We,{config:e,resolveViewMode:me}),Ue.replaceChildren(mt.el)),Ue.classList.toggle("persona-artifact-content-flush",!!Ue.querySelector(".persona-code-pre"))},he=()=>{let U=ke.length>0;if(h.classList.toggle("persona-hidden",!U),g){let Te=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;U&&Te&&it?(g.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},xt=()=>{Je=!1,ie(),he()};return{element:h,backdrop:g,update(U){ke=U.artifacts,Re=U.selectedId??U.artifacts[U.artifacts.length-1]?.id??null,ke.length>0&&(it=!0),Je=!0,Ne&&xt()},setMobileOpen(U){it=U,!U&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):he()},setExpanded(U){let te=ne(U?"minimize":"maximize",16,"currentColor",2);te&&Ee.replaceChildren(te);let We=U?"Collapse artifacts panel":"Expand artifacts panel";Ee.setAttribute("aria-label",We),Ee.title=We},setExpandToggleVisible(U){Ee.classList.toggle("persona-hidden",!U)},setCopyButtonVisible(U){n||q.classList.toggle("persona-hidden",!U)},setCustomActions(U){se=U,fe()},setTabFade(U){let te=d(U);te.start===c&&te.end===u||(c=te.start,u=te.end,He(ee))},setRenderTabBar(U){U!==Ce&&(Ce=U,Lt="",ie())},setVisible(U){U!==Ne&&(Ne=U,U&&Je&&xt())}}}function Yt(e){return e?.features?.artifacts?.enabled===!0}function Sg(e,t){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"),!Yt(t))return;let o=t.features?.artifacts?.layout,r=o?.paneBorder?.trim(),n=o?.paneBorderLeft?.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function yv(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")}var Tg=["panel","seamless","detached"];function Rp(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Tg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Ip(e){return!e||!Yt(e)?!1:Rp(e)==="detached"}function Xa(e,t){if(!Yt(t)){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"),yv(e),Sg(e,t);return}let o=t.features?.artifacts?.layout,r=Rp(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??r),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=o?.paneBackground?.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=o?.documentToolbarIconColor?.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=o?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=o?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Sg(e,t)}function Ja(e,t){for(let l of Tg)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Yt(t))return;let o=t.features?.artifacts?.layout,r=Rp(t);e.classList.add(`persona-artifact-appearance-${r}`);let n=o?.paneBorderRadius?.trim();n&&e.style.setProperty("--persona-artifact-pane-radius",n);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=o?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}function Mg(e,t){return!t||!Yt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function bv(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function xv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function vv(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function Cv(e,t,o,r){let n=e-r-2*t-o;return Math.max(0,n)}function Bp(e,t){let r=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",n=/^([\d.]+)px$/i.exec(r);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(r);return a?Number(a[1]):8}function Eg(e,t,o,r,n,a){let s=bv(n,200),l=Cv(t,o,r,200);l=Math.max(s,l);let p=xv(a);return p!==null&&(l=Math.min(l,p)),vv(e,s,l)}var kg={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"}},Hp=(e,t,o,r)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{if(a.dataset.enhanced==="true")return;let s=a.dataset.tvForm??"init";a.dataset.enhanced="true";let l=kg[s]??kg.init;a.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),d=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let h=y("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,p.appendChild(h)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let C=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${s}-${h.name}`;let M=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=h.label,C.appendChild(M);let L=h.type??"text",A;L==="textarea"?(A=document.createElement("textarea"),A.rows=3):(A=document.createElement("input"),A.type=L),A.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",A.id=`${t.id}-${s}-${h.name}`,A.name=h.name,A.placeholder=h.placeholder??"",h.required&&(A.required=!0),C.appendChild(A),c.appendChild(C)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("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=l.submitLabel??"Submit",u.appendChild(g),u.appendChild(f),c.appendChild(u),a.replaceChildren(p,c),c.addEventListener("submit",async h=>{h.preventDefault();let C=o.formEndpoint??"/form",M=new FormData(c),L={};M.forEach((A,T)=>{L[T]=A}),L.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let A=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let T=await A.json();g.textContent=T.message??"Thanks! We'll be in touch soon.",T.success&&T.nextPrompt&&await r.sendMessage(String(T.nextPrompt))}catch(A){g.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Wp=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let r=new Set(t.map(a=>a.id));return[...o.filter(a=>!r.has(a.id)),...t].sort((a,s)=>(s.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Qa=new Wp;var Lg=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>o(n,a)),o=(n,a)=>{e.get(n)?.delete(a)};return{on:t,off:o,emit:(n,a)=>{e.get(n)?.forEach(s=>{try{s(a)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var wv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Av=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let r=0;for(let n=o;n<t.length;n+=1){let a=t[n];if(a==="{"&&(r+=1),a==="}"&&(r-=1,r===0))return t.slice(o,n+1)}return null},Ya=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wv(e),o=Av(t);if(!o)return null;let r=JSON.parse(o);if(!r||typeof r!="object"||!r.action)return null;let{action:n,...a}=r;return{type:String(n),payload:a,raw:r}}catch{return null}},Dp=e=>typeof e=="string"?e:e==null?"":String(e),dn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Dp(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,r=Dp(o.element);if(r&&t.document?.querySelector){let n=t.document.querySelector(r);n?setTimeout(()=>{n.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Dp(o.text)}}},Pg=e=>Array.isArray(e)?e.map(t=>String(t)):[],Za=e=>{let t=new Set(Pg(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(Pg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.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<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=s?e.parsers.reduce((d,c)=>d||c?.({text:s,message:a.message})||null,null):null;if(!l)return null;t.add(a.message.id),r();let p={action:l,message:a.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:o}};var Sv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Tv=e=>e.map(t=>({...t,streaming:!1})),Mv=e=>e.map(t=>({...t,status:"complete"})),Ki=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?Sv(o.getItem(e)):null},save:o=>{let r=t();if(r)try{let n={...o,messages:o.messages?Tv(o.messages):void 0,artifacts:o.artifacts?Mv(o.artifacts):void 0};r.setItem(e,JSON.stringify(n))}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var jn=wn(Ds(),1);function Ev(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function kv(e,t){if(!Ev(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function Xi(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(o.length<=t)return e;try{let n=(0,jn.parse)(o,jn.STR|jn.OBJ),a=kv(n,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function Rg(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ji(e,t){let{config:o,message:r,onPropsUpdate:n}=t,a=Mo.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:r,config:o,updateProps:l=>{n&&n(l)}};try{return a(e.props,s)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function Ig(){let e=Xi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Bg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function es(e){let t=Bg(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function Qi(e){let t=Bg(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let r=o;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Lv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Yi(e){let{onSubmit:t,onDismiss:o,title:r="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=Lv}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=r,f.appendChild(h);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=n,f.appendChild(C),g.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let B=1;B<=5;B++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${B} star${B>1?"s":""}: ${d[B-1]}`),H.title=d[B-1],H.dataset.rating=String(B),H.innerHTML=`
|
|
32
38
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
33
39
|
<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>
|
|
34
40
|
</svg>
|
|
35
|
-
`,M.addEventListener("click",()=>{u=v,E.forEach((H,I)=>{let P=I<v;H.classList.toggle("selected",P),H.setAttribute("aria-checked",I===v-1?"true":"false")})}),E.push(M),k.appendChild(M)}g.appendChild(k);let A=null;if(c){let v=document.createElement("div");v.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"),v.appendChild(A),g.appendChild(v)}let T=document.createElement("div");T.className="persona-feedback-actions";let y=document.createElement("button");y.type="button",y.className="persona-feedback-btn persona-feedback-btn-skip",y.textContent=i,y.addEventListener("click",()=>{r==null||r(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=s,w.addEventListener("click",async()=>{if(u===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let v=(A==null?void 0:A.value.trim())||void 0;await t(u,v),p.remove()}catch(v){w.disabled=!1,w.textContent=s,console.error("[CSAT Feedback] Failed to submit:",v)}}),T.appendChild(y),T.appendChild(w),g.appendChild(T),p.appendChild(g),p}function ml(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,lowLabel:d="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,h.appendChild(b);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=n,h.appendChild(k),f.appendChild(h);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=d;let y=document.createElement("span");y.className="persona-feedback-label-high",y.textContent=p,A.appendChild(T),A.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-numbers";let v=[];for(let B=0;B<=10;B++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${B} out of 10`),O.textContent=String(B),O.dataset.rating=String(B),B<=6?O.classList.add("persona-feedback-detractor"):B<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{g=B,v.forEach((Q,me)=>{Q.classList.toggle("selected",me===B),Q.setAttribute("aria-checked",me===B?"true":"false")})}),v.push(O),w.appendChild(O)}E.appendChild(A),E.appendChild(w),f.appendChild(E);let M=null;if(c){let B=document.createElement("div");B.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),B.appendChild(M),f.appendChild(B)}let H=document.createElement("div");H.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{r==null||r(),u.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=s,P.addEventListener("click",async()=>{if(g===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let B=(M==null?void 0:M.value.trim())||void 0;await t(g,B),u.remove()}catch(B){P.disabled=!1,P.textContent=s,console.error("[NPS Feedback] Failed to submit:",B)}}),H.appendChild(I),H.appendChild(P),f.appendChild(H),u.appendChild(f),u}var Qa="persona-chat-history",B0=30*1e3,D0={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function F0(e){var o,n,a;if(!e)return[];let t=[],r=Array.from((o=e.items)!=null?o:[]);for(let s of r){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let c=(n=D0[i.type])!=null?n:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${c}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&t.push(s);return t}function gl(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function N0(e){var t,r,o,n,a,s,i,c,d;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(d=e.clearOnChatClear)!=null?d:!0}:null}function O0(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Ap=e=>!e||typeof e!="object"?{}:{...e},Wx=e=>e.map(t=>({...t,streaming:!1})),Bx=(e,t,r)=>{let o=e!=null&&e.markdown?oa(e.markdown):null,n=Ra(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(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 p,u,g;let s=(p=a.text)!=null?p:"",i=(u=a.message.rawContent)!=null?u:null;if(t){let f=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});f!==null&&(s=f.text,f.persist||(a.message.__skipPersist=!0),f.resubmit&&!a.streaming&&r&&r())}let c=ra()!==null,d;if(e!=null&&e.postprocessMessage){let f=e.postprocessMessage({...a,text:s,raw:(g=i!=null?i:a.text)!=null?g:""});d=n?n(f):f}else if(o){let f=a.streaming?Og(s):s,h=o(f);d=n&&c?n(h):h}else d=Fo(s);return d}};function Dx(e){var i,c,d,p;let t=S("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(d=e==null?void 0:e.iconColor)!=null?d:"rgba(59, 130, 246, 0.6)",a=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,s=he(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let u=S("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var hl=(e,t,r)=>{var Su,Au,Mu,Tu,Eu,ku,Lu,Pu,Ru,Iu,Hu,Wu,Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,zu,$u,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Wi(t),n=_s.getForInstance(o.plugins),{plugin:a,teardown:s}=mx();o.components&&rn.registerAll(o.components);let i=Lx(),d=o.persistState===!1?null:(Su=o.storageAdapter)!=null?Su:ll(),p={},u=null,g=!1,f=l=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:x,open:C}=m;return C&&(g=!0),x}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(d!=null&&d.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(m=>{let x=m!=null?m:{messages:[],metadata:{}};return f(x)});else{let m=l!=null?l:{messages:[],metadata:{}},x=f(m);x.metadata&&(p=Ap(x.metadata)),(Au=x.messages)!=null&&Au.length&&(o={...o,initialMessages:x.messages}),(Mu=x.artifacts)!=null&&Mu.length&&(o={...o,initialArtifacts:x.artifacts,initialSelectedArtifactId:(Tu=x.selectedArtifactId)!=null?Tu:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=f({messages:[],metadata:{}});(Eu=l.messages)!=null&&Eu.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let h=()=>p,b=l=>{var x;p=(x=l({...p}))!=null?x:{},Hr()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Us],E=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ha.message,ha.messageAndClick],A=qs({parsers:k,handlers:E,getSessionMetadata:h,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let T=(Lu=(ku=o.launcher)==null?void 0:ku.enabled)!=null?Lu:!0,y=(Ru=(Pu=o.launcher)==null?void 0:Pu.autoExpand)!=null?Ru:!1,w=(Iu=o.autoFocusInput)!=null?Iu:!1,v=y,M=T,H=(Wu=(Hu=o.layout)==null?void 0:Hu.header)==null?void 0:Wu.layout,I=!1,P=()=>Fn(o),B=()=>T||P(),O=P()?!1:T?y:!0,Q=!1,me=null,ue=()=>{Q=!0,me&&clearTimeout(me),me=setTimeout(()=>{Q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Q=!1)},1e4)},Z=Bx(o,A,ue),Le=(Du=(Bu=o.features)==null?void 0:Bu.showReasoning)!=null?Du:!0,We=(Nu=(Fu=o.features)==null?void 0:Fu.showToolCalls)!=null?Nu:!0,ie=(_u=(Ou=o.features)==null?void 0:Ou.showEventStreamToggle)!=null?_u:!1,Me=(qu=(Uu=o.features)==null?void 0:Uu.scrollToBottom)!=null?qu:{},oe=(zu=(Vu=o.features)==null?void 0:Vu.scrollBehavior)!=null?zu:{},ge=`${(ju=typeof o.persistState=="object"?($u=o.persistState)==null?void 0:$u.keyPrefix:void 0)!=null?ju:"persona-"}event-stream`,Te=ie?new Ns(ge):null,qe=(Xu=(Ku=(Gu=o.features)==null?void 0:Gu.eventStream)==null?void 0:Ku.maxEvents)!=null?Xu:2e3,j=ie?new Fs(qe,Te):null,ee=ie?new Os:null,Ee=null,te=!1,le=null,ke=0;Te==null||Te.open().then(()=>j==null?void 0:j.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let nt={onCopy:l=>{var m,x;i.emit("message:copy",l),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(l.id,"copy").catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",C)}),(x=(m=o.messageActions)==null?void 0:m.onCopy)==null||x.call(m,l)},onFeedback:l=>{var m,x;i.emit("message:feedback",l),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(l.messageId,l.type).catch(C=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",C)}),(x=(m=o.messageActions)==null?void 0:m.onFeedback)==null||x.call(m,l)}},yt=(Qu=o.statusIndicator)!=null?Qu:{},Kt=l=>{var m,x,C,R,D,V;return l==="idle"?(m=yt.idleText)!=null?m:or.idle:l==="connecting"?(x=yt.connectingText)!=null?x:or.connecting:l==="connected"?(C=yt.connectedText)!=null?C:or.connected:l==="error"?(R=yt.errorText)!=null?R:or.error:l==="paused"?(D=yt.pausedText)!=null?D:or.paused:l==="resuming"?(V=yt.resumingText)!=null?V:or.resuming:or[l]};function jt(l,m,x,C){if(C==="idle"&&x.idleLink){l.textContent="";let R=document.createElement("a");R.href=x.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=m,R.style.color="inherit",R.style.textDecoration="none",l.appendChild(R)}else l.textContent=m}let ct=tx({config:o,showClose:B()}),{wrapper:fe,panel:X,pillRoot:st}=ct.shell,je=ct.panelElements,{container:Ce,body:ve,messagesWrapper:Ye,suggestions:Vt,textarea:xe,sendButton:de,sendButtonWrapper:Cr,composerForm:Ct,statusText:xr,introTitle:Co,introSubtitle:So,closeButton:Ve,iconHolder:W,headerTitle:ce,headerSubtitle:Se,header:Ae,footer:Ie,actionsRow:et,leftActions:Qe,rightActions:gt}=je,pe=je.setSendButtonMode,N=je.micButton,ye=je.micButtonWrapper,ae=je.attachmentButton,mt=je.attachmentButtonWrapper,Ke=je.attachmentInput,Lt=je.attachmentPreviewsContainer;Ce.classList.add("persona-relative"),ve.classList.add("persona-relative");let Et=12,bt=()=>{var l;return(l=Me.label)!=null?l:""},It=()=>{var l;return(l=Me.iconName)!=null?l:"arrow-down"},Qt=()=>Me.enabled!==!1,Ft=()=>{var l;return(l=oe.mode)!=null?l:"anchor-top"},tr=()=>Ft()==="follow"||Ft()==="anchor-top"&&fn,Ao=()=>{var l;return(l=oe.anchorTopOffset)!=null?l:16},Uo=()=>{var l;return(l=oe.restorePosition)!=null?l:"bottom"},io=()=>oe.pauseOnInteraction===!0,lo=()=>oe.showActivityWhilePinned!==!1,on=()=>oe.announce===!0,zt=S("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");zt.type="button",zt.style.display="none",zt.setAttribute("data-persona-scroll-to-bottom","true");let co=S("span","persona-flex persona-items-center"),qo=S("span",""),Fr=S("span","");Fr.setAttribute("data-persona-scroll-to-bottom-count",""),Fr.style.display="none",zt.append(co,qo,Fr),Ce.appendChild(zt);let Rr=S("div","persona-stream-anchor-spacer");Rr.setAttribute("aria-hidden","true"),Rr.setAttribute("data-persona-anchor-spacer",""),Rr.style.flexShrink="0",Rr.style.pointerEvents="none",Rr.style.height="0px",ve.appendChild(Rr);let Nr=S("div","persona-sr-only");Nr.setAttribute("aria-live","polite"),Nr.setAttribute("aria-atomic","true"),Nr.setAttribute("role","status"),Nr.setAttribute("data-persona-live-region",""),Object.assign(Nr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Ce.appendChild(Nr);let po=null,Mo=null,nn=l=>{!on()||!l||(Mo=l,po===null&&(po=setTimeout(()=>{po=null,Mo&&on()&&(Nr.textContent=Mo),Mo=null},400)))},Qr=()=>{let m=Ie.style.display==="none"?0:Ie.offsetHeight;zt.style.bottom=`${m+Et}px`};Qr();let an=()=>{let l=!!bt();zt.setAttribute("aria-label",bt()||"Jump to latest"),zt.title=bt(),zt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),co.innerHTML="";let m=he(It(),"14px","currentColor",2);m?(co.appendChild(m),co.style.display=""):co.style.display="none",qo.textContent=bt(),qo.style.display=l?"":"none"};an();let St=null,To=null,Eo=n.find(l=>l.renderHeader);if(Eo!=null&&Eo.renderHeader){let l=Eo.renderHeader({config:o,defaultRenderer:()=>{let m=tn({config:o,showClose:B()});return pa(Ce,m,o),m.header},onClose:()=>Ot(!1,"user")});if(l){let m=Ce.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),Ae=l,ct.header.element=l)}}let Vo=()=>{var m,x,C,R;if(!j)return;if(te=!0,!Ee&&j&&(Ee=bx({buffer:j,getFullHistory:()=>j.getAllFromStore(),onClose:()=>uo(),config:o,plugins:n,getThroughput:()=>{var D;return(D=ee==null?void 0:ee.getMetric())!=null?D:{status:"idle"}}})),Ee&&(ve.style.display="none",(m=Ie.parentNode)==null||m.insertBefore(Ee.element,Ie),Ee.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Pr.actionIconColor}`;let D=(R=(C=(x=o.features)==null?void 0:x.eventStream)==null?void 0:C.classNames)==null?void 0:R.toggleButtonActive;D&&D.split(/\s+/).forEach(V=>V&&ht.classList.add(V))}let l=()=>{if(!te)return;let D=Date.now();D-ke>=200&&(Ee==null||Ee.update(),ke=D),le=requestAnimationFrame(l)};ke=0,le=requestAnimationFrame(l),qr(),i.emit("eventStream:opened",{timestamp:Date.now()})},uo=()=>{var l,m,x;if(te){if(te=!1,Ee&&Ee.element.remove(),ve.style.display="",ht){ht.style.boxShadow="";let C=(x=(m=(l=o.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:x.toggleButtonActive;C&&C.split(/\s+/).forEach(R=>R&&ht.classList.remove(R))}le!==null&&(cancelAnimationFrame(le),le=null),qr(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(ie){let l=(Yu=(Ju=o.features)==null?void 0:Ju.eventStream)==null?void 0:Yu.classNames,m="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"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ht=S("button",m),ht.style.width="28px",ht.style.height="28px",ht.style.color=Pr.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let x=he("activity","18px","currentColor",1.5);x&&ht.appendChild(x);let C=je.clearChatButtonWrapper,R=je.closeButtonWrapper,D=C||R;D&&D.parentNode===Ae?Ae.insertBefore(ht,D):Ae.appendChild(ht),ht.addEventListener("click",()=>{te?uo():Vo()})}let On=l=>{var R,D,V,q,_;let m=o.attachments;if(!(m!=null&&m.enabled))return;let x=(R=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?R:l.querySelector(".persona-attachment-previews");if(!x){x=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),x.setAttribute("data-persona-composer-attachment-previews",""),x.style.display="none";let ne=l.querySelector("[data-persona-composer-form]");ne!=null&&ne.parentNode?ne.parentNode.insertBefore(x,ne):l.insertBefore(x,l.firstChild)}if(!((D=l.querySelector("[data-persona-composer-attachment-input]"))!=null?D:l.querySelector('input[type="file"]'))){let ne=S("input");ne.type="file",ne.setAttribute("data-persona-composer-attachment-input",""),ne.accept=((V=m.allowedTypes)!=null?V:en).join(","),ne.multiple=((q=m.maxFiles)!=null?q:4)>1,ne.style.display="none",ne.setAttribute("aria-label",(_=m.buttonTooltipText)!=null?_:"Attach files"),l.appendChild(ne)}},ko=n.find(l=>l.renderComposer);if(ko!=null&&ko.renderComposer){let l=o.composer,m=ko.renderComposer({config:o,defaultRenderer:()=>za({config:o}).footer,onSubmit:x=>{var V;if(!U||U.isStreaming())return;let C=x.trim(),R=(V=St==null?void 0:St.hasAttachments())!=null?V:!1;if(!C&&!R)return;Yp();let D;R&&(D=[],D.push(...St.getContentParts()),C&&D.push(As(C))),U.sendMessage(C,{contentParts:D}),R&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:((Zu=o.voiceRecognition)==null?void 0:Zu.enabled)===!0?()=>{To==null||To()}:void 0});m&&(ct.replaceComposer(m),Ie=ct.composer.footer)}let _n=l=>{let m=(...re)=>{for(let J of re){let be=l.querySelector(J);if(be)return be}return null},x=l.querySelector("[data-persona-composer-form]"),C=l.querySelector("[data-persona-composer-input]"),R=l.querySelector("[data-persona-composer-submit]"),D=l.querySelector("[data-persona-composer-mic]"),V=l.querySelector("[data-persona-composer-status]");x&&(Ct=x),C&&(xe=C),R&&(de=R),D&&(N=D,ye=D.parentElement),V&&(xr=V);let q=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");q&&(Vt=q);let _=m("[data-persona-composer-attachment-button]",".persona-attachment-button");_&&(ae=_,mt=_.parentElement),Ke=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ne=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ne&&(et=ne)};On(Ie),_n(Ie);let Ir=(nf=(ef=o.layout)==null?void 0:ef.contentMaxWidth)!=null?nf:P()?(of=(rf=(tf=o.launcher)==null?void 0:tf.composerBar)==null?void 0:rf.contentMaxWidth)!=null?of:"720px":void 0;if(Ir&&(Ye.style.maxWidth=Ir,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%"),Ir&&Ct&&!P()&&(Ct.style.maxWidth=Ir,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Ir&&Vt&&!P()&&(Vt.style.maxWidth=Ir,Vt.style.marginLeft="auto",Vt.style.marginRight="auto"),Ir&&Lt&&!P()&&(Lt.style.maxWidth=Ir,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(af=o.attachments)!=null&&af.enabled&&Ke&&Lt){St=da.fromConfig(o.attachments),St.setPreviewsContainer(Lt),Ke.addEventListener("change",x=>{let C=x.target;St==null||St.handleFileSelect(C.files),C.value=""});let l=o.attachments.dropOverlay,m=Dx(l);Ce.appendChild(m)}(()=>{var C,R;let l=(R=(C=o.layout)==null?void 0:C.slots)!=null?R:{},m=D=>{switch(D){case"body-top":return Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ye;case"footer-top":return Vt;case"composer":return Ct;case"footer-bottom":return xr;default:return null}},x=(D,V)=>{var q;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Ae.insertBefore(V,Ae.firstChild);else if(D==="header-right")Ae.appendChild(V);else{let _=Ae.querySelector(".persona-flex-col");_?(q=_.parentNode)==null||q.insertBefore(V,_.nextSibling):Ae.appendChild(V)}break;case"body-top":{let _=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(V):ve.insertBefore(V,ve.firstChild);break}case"body-bottom":ve.appendChild(V);break;case"footer-top":Vt.replaceWith(V);break;case"footer-bottom":xr.replaceWith(V);break;default:break}};for(let[D,V]of Object.entries(l))if(V)try{let q=V({config:o,defaultContent:()=>m(D)});q&&x(D,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,q)}})();let sn=l=>{var V,q;let x=l.target.closest('button[data-expand-header="true"]');if(!x)return;let C=x.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!C)return;let R=C.getAttribute("data-message-id");if(!R)return;let D=x.getAttribute("data-bubble-type");if(D==="reasoning")ja.has(R)?ja.delete(R):ja.add(R),ax(R,C);else if(D==="tool")Ga.has(R)?Ga.delete(R):Ga.add(R),sx(R,C,o);else if(D==="approval"){let _=o.approval!==!1?o.approval:void 0,ne=((V=_==null?void 0:_.detailsDisplay)!=null?V:"collapsed")==="expanded",re=(q=fa.get(R))!=null?q:ne;fa.set(R,!re),cx(R,C,o)}Io.delete(R)};Ye.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),sn(l))}),Ye.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),sn(l))}),Ye.addEventListener("copy",l=>{let{clipboardData:m}=l;if(!m)return;let x=Ye.getRootNode(),C=typeof x.getSelection=="function"?x.getSelection():window.getSelection();if(!C||C.isCollapsed)return;let R=C.toString(),D=Fh(R);!D||D===R||(m.setData("text/plain",D),l.preventDefault())});let zo=new Map,ln=null,dn="idle",Un={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},qn=(l,m)=>{let{icon:x,label:C}=Un[m];l.setAttribute("aria-label",C),l.title=C,l.setAttribute("aria-pressed",m==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",m!=="idle"),l.classList.toggle("persona-message-action-loading",m==="loading");let R=he(x,14,"currentColor",2);R&&(l.innerHTML="",l.appendChild(R))},cn=()=>{Ye.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var D;let x=m.closest("[data-actions-for]"),C=(D=x==null?void 0:x.getAttribute("data-actions-for"))!=null?D:null;qn(m,C&&C===ln?dn:"idle")})};Ye.addEventListener("click",l=>{var V;let x=l.target.closest(".persona-message-action-btn[data-action]");if(!x)return;l.preventDefault(),l.stopPropagation();let C=x.closest("[data-actions-for]");if(!C)return;let R=C.getAttribute("data-actions-for");if(!R)return;let D=x.getAttribute("data-action");if(D==="copy"){let _=U.getMessages().find(ne=>ne.id===R);if(_&&nt.onCopy){let ne=_.content||"";navigator.clipboard.writeText(ne).then(()=>{x.classList.add("persona-message-action-success");let re=he("check",14,"currentColor",2);re&&(x.innerHTML="",x.appendChild(re)),setTimeout(()=>{x.classList.remove("persona-message-action-success");let J=he("copy",14,"currentColor",2);J&&(x.innerHTML="",x.appendChild(J))},2e3)}).catch(re=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",re)}),nt.onCopy(_)}}else if(D==="read-aloud")U.toggleReadAloud(R);else if(D==="upvote"||D==="downvote"){let _=((V=zo.get(R))!=null?V:null)===D,ne=D==="upvote"?"thumbs-up":"thumbs-down";if(_){zo.delete(R),x.classList.remove("persona-message-action-active");let re=he(ne,14,"currentColor",2);re&&(x.innerHTML="",x.appendChild(re))}else{let re=D==="upvote"?"downvote":"upvote",J=C.querySelector(`[data-action="${re}"]`);if(J){J.classList.remove("persona-message-action-active");let ze=he(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(J.innerHTML="",J.appendChild(ze))}zo.set(R,D),x.classList.add("persona-message-action-active");let be=he(ne,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),x.innerHTML="",x.appendChild(be)),x.classList.remove("persona-message-action-pop"),x.offsetWidth,x.classList.add("persona-message-action-pop");let Ne=U.getMessages().find(Ue=>Ue.id===R);Ne&&nt.onFeedback&&nt.onFeedback({type:D,messageId:Ne.id,message:Ne})}}}),Ye.addEventListener("click",l=>{let x=l.target.closest("button[data-approval-action]");if(!x)return;l.preventDefault(),l.stopPropagation();let C=x.closest(".persona-approval-bubble");if(!C)return;let R=C.getAttribute("data-message-id");if(!R)return;let D=x.getAttribute("data-approval-action");if(!D)return;let V=D==="approve"?"approved":"denied",_=U.getMessages().find(re=>re.id===R);if(!(_!=null&&_.approval))return;let ne=C.querySelector("[data-approval-buttons]");ne&&ne.querySelectorAll("button").forEach(J=>{J.disabled=!0,J.style.opacity="0.5",J.style.cursor="not-allowed"}),_.approval.toolType==="webmcp"?U.resolveWebMcpApproval(R,V):U.resolveApproval(_.approval,V)});let vt=null,Or=null,_r={artifacts:[],selectedId:null},Sr=!1,At={current:null};Ye.addEventListener("click",l=>{var J,be,Fe,Ne,Ue;let x=l.target.closest("[data-download-artifact]");if(!x)return;l.preventDefault(),l.stopPropagation();let C=x.getAttribute("data-download-artifact");if(!C||((Fe=(be=(J=o.features)==null?void 0:J.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Fe.call(be,{type:"download",artifactId:C}))===!0)return;let D=U.getArtifactById(C),V=D==null?void 0:D.markdown,q=(D==null?void 0:D.title)||"artifact";if(!V){let ze=x.closest("[data-open-artifact]"),ut=ze==null?void 0:ze.closest("[data-message-id]"),ot=ut==null?void 0:ut.getAttribute("data-message-id");if(ot){let Pe=U.getMessages().find($e=>$e.id===ot);if(Pe!=null&&Pe.rawContent)try{let $e=JSON.parse(Pe.rawContent);V=(Ne=$e==null?void 0:$e.props)==null?void 0:Ne.markdown,q=((Ue=$e==null?void 0:$e.props)==null?void 0:Ue.title)||q}catch{}}}if(!V)return;let _=new Blob([V],{type:"text/markdown"}),ne=URL.createObjectURL(_),re=document.createElement("a");re.href=ne,re.download=`${q}.md`,re.click(),URL.revokeObjectURL(ne)}),Ye.addEventListener("click",l=>{var D,V,q;let x=l.target.closest("[data-open-artifact]");if(!x)return;let C=x.getAttribute("data-open-artifact");!C||((q=(V=(D=o.features)==null?void 0:D.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:q.call(V,{type:"open",artifactId:C}))===!0||(l.preventDefault(),l.stopPropagation(),Sr=!1,U.selectArtifact(C),Lo())}),Ye.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Jr=je.composerOverlay,Yr=(l,m,x)=>{var q,_,ne,re;let C=m.trim();if(!C||!At.current)return;let R=(q=l.getAttribute("data-tool-call-id"))!=null?q:"",D=x.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:C,answers:x.structured,values:(_=x.values)!=null?_:x.source==="multi"?C.split(", "):[C],isFreeText:D,source:x.source},bubbles:!0,composed:!0})),En(Jr,R);let V=At.current.getMessages().find(J=>{var be;return((be=J.toolCall)==null?void 0:be.id)===R});(ne=V==null?void 0:V.agentMetadata)!=null&&ne.awaitingLocalTool?At.current.resolveAskUserQuestion(V,(re=x.structured)!=null?re:C):At.current.sendMessage(C)},Ur=l=>{var R;let m=At.current;if(!m)return;let x=(R=l.getAttribute("data-tool-call-id"))!=null?R:"",C=m.getMessages().find(D=>{var V;return((V=D.toolCall)==null?void 0:V.id)===x});C&&m.persistAskUserQuestionProgress(C,{answers:ai(l,C),currentIndex:ao(l)})},pn=l=>Object.entries(l).map(([m,x])=>`${m}: ${Array.isArray(x)?x.join(", "):x}`).join(" | "),we=l=>{var R,D,V;if(((D=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let m=ao(l),x=Wa(l);if(m>=x-1)return;let C=(V=At.current)==null?void 0:V.getMessages().find(q=>{var _;return((_=q.toolCall)==null?void 0:_.id)===l.getAttribute("data-tool-call-id")});C&&(si(l,C,o,m+1),Ur(l))};Jr.addEventListener("click",l=>{var D,V,q,_,ne,re,J,be,Fe,Ne,Ue,ze,ut,ot;let x=l.target.closest("[data-ask-user-action]");if(!x)return;let C=x.closest("[data-persona-ask-sheet-for]");if(!C)return;let R=x.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),R==="dismiss"){let He=(D=C.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),En(Jr,He);let Pe=(V=At.current)==null?void 0:V.getMessages().find($e=>{var Xe;return((Xe=$e.toolCall)==null?void 0:Xe.id)===He});(q=Pe==null?void 0:Pe.agentMetadata)!=null&&q.awaitingLocalTool&&((_=At.current)==null||_.markAskUserQuestionResolved(Pe),(ne=At.current)==null||ne.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(R==="pick"){let He=x.getAttribute("data-option-label");if(!He)return;let Pe=C.getAttribute("data-multi-select")==="true",$e=Tn(C);if($e&&Pe){let Xe=na(C)[ao(C)],xt=new Set(Array.isArray(Xe)?Xe:[]);xt.has(He)?xt.delete(He):xt.add(He),kn(C,Array.from(xt)),Ur(C);return}if($e){kn(C,He),Ur(C),we(C);return}if(Pe){let Xe=x.getAttribute("aria-pressed")==="true";x.setAttribute("aria-pressed",Xe?"false":"true"),x.classList.toggle("persona-ask-pill-selected",!Xe);let xt=C.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Ul(C).length===0);return}Yr(C,He,{source:"pick",values:[He]});return}if(R==="submit-multi"){let He=Ul(C);if(He.length===0)return;Yr(C,He.join(", "),{source:"multi",values:He});return}if(R==="open-free-text"){let He=C.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let Pe=He.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(R==="focus-free-text"){let He=C.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(R==="submit-free-text"){let He=C.querySelector('[data-ask-free-text-input="true"]'),Pe=(re=He==null?void 0:He.value)!=null?re:"";if(!Pe.trim())return;if(Tn(C)){kn(C,Pe.trim()),Ur(C),we(C);return}Yr(C,Pe,{source:"free-text"});return}if(R==="next"||R==="back"){if(!At.current)return;let He=(J=C.getAttribute("data-tool-call-id"))!=null?J:"",Pe=At.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===He});if(!Pe)return;let $e=C.querySelector('[data-ask-free-text-input="true"]'),Xe=(Fe=(be=$e==null?void 0:$e.value)==null?void 0:be.trim())!=null?Fe:"";if(Xe){let Be=na(C)[ao(C)];(typeof Be!="string"||Be!==Xe)&&kn(C,Xe)}let xt=R==="next"?1:-1,F=ao(C)+xt;si(C,Pe,o,F),Ur(C);return}if(R==="submit-all"){if(!At.current)return;let He=(Ne=C.getAttribute("data-tool-call-id"))!=null?Ne:"",Pe=At.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===He});if(!Pe)return;let $e=C.querySelector('[data-ask-free-text-input="true"]'),Xe=(ze=(Ue=$e==null?void 0:$e.value)==null?void 0:Ue.trim())!=null?ze:"";Xe&&kn(C,Xe);let xt=ai(C,Pe);At.current.persistAskUserQuestionProgress(Pe,{answers:xt,currentIndex:ao(C)});let F=pn(xt);Yr(C,F||"(submitted)",{source:"submit-all",structured:xt});return}if(R==="skip"){if(!At.current)return;let He=(ut=C.getAttribute("data-tool-call-id"))!=null?ut:"",Pe=At.current.getMessages().find(Re=>{var Je;return((Je=Re.toolCall)==null?void 0:Je.id)===He});if(!Pe)return;let $e=Tn(C),Xe=ao(C),xt=Wa(C),F=Xe>=xt-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),En(Jr,He),(ot=Pe.agentMetadata)!=null&&ot.awaitingLocalTool&&(At.current.markAskUserQuestionResolved(Pe),At.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}kn(C,"");let Be=C.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),F){let Re=ai(C,Pe),Je=pn(Re);Yr(C,Je||"(skipped)",{source:"submit-all",structured:Re});return}si(C,Pe,o,Xe+1),Ur(C);return}}),Jr.addEventListener("keydown",l=>{var D;if(l.key!=="Enter")return;let x=l.target;if(!((D=x.matches)!=null&&D.call(x,'[data-ask-free-text-input="true"]')))return;let C=x.closest("[data-persona-ask-sheet-for]");if(!C)return;l.preventDefault();let R=x.value;if(R.trim()){if(Tn(C)){kn(C,R.trim()),Ur(C),we(C);return}Yr(C,R,{source:"free-text"})}});let $o=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let x=Jr.querySelector("[data-persona-ask-sheet-for]");if(!x||x.getAttribute("data-ask-layout")!=="rows"||x.getAttribute("data-multi-select")==="true")return;let C=Number(l.key),D=x.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];D&&(l.preventDefault(),D.click())};document.addEventListener("keydown",$o);let Zr=null,Nt=null,eo=null,jo=null,Ya=()=>{};function ya(){jo==null||jo(),jo=null}let Za=()=>{var V;if(!Zr||!Nt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),x=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||x){Nt.style.removeProperty("position"),Nt.style.removeProperty("left"),Nt.style.removeProperty("top"),Nt.style.removeProperty("bottom"),Nt.style.removeProperty("width"),Nt.style.removeProperty("z-index");return}let C=Zr.firstElementChild;if(!C||C===Nt)return;let R=10;Nt.style.position="absolute",Nt.style.top="0",Nt.style.bottom="0",Nt.style.width=`${R}px`,Nt.style.zIndex="5";let D=C.offsetWidth-R/2;Nt.style.left=`${Math.max(0,D)}px`},Vn=()=>{},Lo=()=>{var x,C,R,D,V;if(!vt||!so(o))return;sl(e,o),il(e,o),Vn();let l=(D=(R=(C=(x=o.features)==null?void 0:x.artifacts)==null?void 0:C.layout)==null?void 0:R.narrowHostMaxWidth)!=null?D:520,m=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),vt.update(_r),Sr?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(V=vt.backdrop)==null||V.classList.add("persona-hidden")):_r.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),Ya()};if(so(o)){X.style.position="relative";let l=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Ce),vt=Cx(o,{onSelect:x=>{var C;return(C=At.current)==null?void 0:C.selectArtifact(x)},onDismiss:()=>{Sr=!0,Lo()}}),vt.element.classList.add("persona-hidden"),Zr=m,m.appendChild(l),m.appendChild(vt.element),vt.backdrop&&X.appendChild(vt.backdrop),X.appendChild(m),Ya=()=>{var C,R,D,V;if(!Zr||!vt)return;if(!(((D=(R=(C=o.features)==null?void 0:C.artifacts)==null?void 0:R.layout)==null?void 0:D.resizable)===!0)){eo==null||eo(),eo=null,ya(),Nt&&(Nt.remove(),Nt=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Nt){let q=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let _=e.ownerDocument,ne=(V=_.defaultView)!=null?V:window,re=J=>{var ut,ot;if(!vt||J.button!==0||e.classList.contains("persona-artifact-narrow-host")||ne.innerWidth<=640)return;J.preventDefault(),ya();let be=J.clientX,Fe=vt.element.getBoundingClientRect().width,Ne=(ot=(ut=o.features)==null?void 0:ut.artifacts)==null?void 0:ot.layout,Ue=He=>{let Pe=Zr.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),Xe=$e?0:Tx(Zr,ne),xt=$e?0:q.getBoundingClientRect().width||6,F=Fe-(He.clientX-be),Be=Ex(F,Pe,Xe,xt,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);vt.element.style.width=`${Be}px`,vt.element.style.maxWidth="none",Za()},ze=()=>{_.removeEventListener("pointermove",Ue),_.removeEventListener("pointerup",ze),_.removeEventListener("pointercancel",ze),jo=null;try{q.releasePointerCapture(J.pointerId)}catch{}};jo=ze,_.addEventListener("pointermove",Ue),_.addEventListener("pointerup",ze),_.addEventListener("pointercancel",ze);try{q.setPointerCapture(J.pointerId)}catch{}};q.addEventListener("pointerdown",re),Nt=q,Zr.insertBefore(q,vt.element),eo=()=>{q.removeEventListener("pointerdown",re)}}if(Nt){let q=_r.artifacts.length>0&&!Sr;Nt.classList.toggle("persona-hidden",!q),Za()}},Vn=()=>{var ne,re,J,be,Fe,Ne,Ue,ze,ut,ot,He,Pe,$e,Xe;if(!T||!vt||((re=(ne=o.launcher)==null?void 0:ne.sidebarMode)!=null?re:!1)||nr(o)&&Kr(o).reveal==="emerge")return;let C=(J=e.ownerDocument.defaultView)!=null?J:window,R=(Fe=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?Fe:!0,D=(Ue=(Ne=o.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?Ue:640;if(R&&C.innerWidth<=D||!Mx(o,T))return;let V=(ot=(ut=(ze=o.launcher)==null?void 0:ze.width)!=null?ut:o.launcherWidth)!=null?ot:Gr,q=(Xe=($e=(Pe=(He=o.features)==null?void 0:He.artifacts)==null?void 0:Pe.layout)==null?void 0:$e.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";_r.artifacts.length>0&&!Sr?(X.style.width=q,X.style.maxWidth=q):(X.style.width=V,X.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(Or=new ResizeObserver(()=>{Lo()}),Or.observe(X))}else X.appendChild(Ce),P()&&st&&(je.peekBanner&&st.appendChild(je.peekBanner),st.appendChild(Ie));e.appendChild(fe),st&&e.appendChild(st);let un=()=>{var Be,Re,Je,Pt,Oe,Gt,wt,lr,Br,Wt,mr,Vr,Ge,Rt,zr,Kn,Xn,Qn,Jn,Ea,ka,Xt,Yn,wn,Cn,Qo,Zn,Ze;if(P()){X.style.width="100%",X.style.maxWidth="100%";let Dt=(Re=(Be=o.launcher)==null?void 0:Be.composerBar)!=null?Re:{},Bt=fe.dataset.state==="expanded",$t=(Je=Dt.expandedSize)!=null?Je:"anchored";if(!(Bt&&$t!=="fullscreen")){Ce.style.background="",Ce.style.border="",Ce.style.borderRadius="",Ce.style.overflow="",Ce.style.boxShadow="";return}let ft=(Oe=(Pt=o.theme)==null?void 0:Pt.components)==null?void 0:Oe.panel,Ut=Ua(o),gr=(fr,no)=>{var Sn;return fr==null||fr===""?no:(Sn=Oa(Ut,fr))!=null?Sn:fr},$r="1px solid var(--persona-border)",Do="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ur="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ce.style.background="var(--persona-surface, #ffffff)",Ce.style.border=gr(ft==null?void 0:ft.border,$r),Ce.style.borderRadius=gr(ft==null?void 0:ft.borderRadius,ur),Ce.style.boxShadow=gr(ft==null?void 0:ft.shadow,Do),Ce.style.overflow="hidden";return}let l=nr(o),m=(wt=(Gt=o.launcher)==null?void 0:Gt.sidebarMode)!=null?wt:!1,x=l||m||((Br=(lr=o.launcher)==null?void 0:lr.fullHeight)!=null?Br:!1),C=((Wt=o.launcher)==null?void 0:Wt.enabled)===!1,R=(Vr=(mr=o.theme)==null?void 0:mr.components)==null?void 0:Vr.panel,D=Ua(o),V=(Dt,Bt)=>{var $t;return Dt==null||Dt===""?Bt:($t=Oa(D,Dt))!=null?$t:Dt},q=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,_=(zr=(Rt=o.launcher)==null?void 0:Rt.mobileFullscreen)!=null?zr:!0,ne=(Xn=(Kn=o.launcher)==null?void 0:Kn.mobileBreakpoint)!=null?Xn:640,re=q.innerWidth<=ne,J=_&&re&&T,be=(Jn=(Qn=o.launcher)==null?void 0:Qn.position)!=null?Jn:"bottom-left",Fe=be==="bottom-left"||be==="top-left",Ne=(ka=(Ea=o.launcher)==null?void 0:Ea.zIndex)!=null?ka:wr,Ue=m||J?"none":"1px solid var(--persona-border)",ze=J?"none":m?Fe?"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))";l&&!J&&(ze="none",Ue="none");let ut=m||J?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ot=V(R==null?void 0:R.border,Ue),He=V(R==null?void 0:R.shadow,ze),Pe=V(R==null?void 0:R.borderRadius,ut),$e=ve.scrollTop;e.style.cssText="",fe.style.cssText="",X.style.cssText="",Ce.style.cssText="",ve.style.cssText="",Ie.style.cssText="",te&&(ve.style.display="none");let Xe=()=>{var Bt;if($e<=0)return;((Bt=ve.ownerDocument.defaultView)!=null?Bt:window).requestAnimationFrame(()=>{if(ve.scrollTop===$e)return;let $t=ve.scrollHeight-ve.clientHeight;$t<=0||(ve.scrollTop=Math.min($e,$t))})};if(J){fe.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"),fe.style.cssText=`
|
|
41
|
+
`,H.addEventListener("click",()=>{u=B,L.forEach((w,F)=>{let q=F<B;w.classList.toggle("selected",q),w.setAttribute("aria-checked",F===B-1?"true":"false")})}),L.push(H),M.appendChild(H)}g.appendChild(M);let A=null;if(p){let B=document.createElement("div");B.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"),B.appendChild(A),g.appendChild(B)}let T=document.createElement("div");T.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=l,S.addEventListener("click",()=>{o?.(),c.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=s,E.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let B=A?.value.trim()||void 0;await t(u,B),c.remove()}catch(B){E.disabled=!1,E.textContent=s,console.error("[CSAT Feedback] Failed to submit:",B)}}),T.appendChild(S),T.appendChild(E),g.appendChild(T),c.appendChild(g),c}function Zi(e){let{onSubmit:t,onDismiss:o,title:r="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=r,h.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=n,h.appendChild(M),f.appendChild(h);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=d;let S=document.createElement("span");S.className="persona-feedback-label-high",S.textContent=c,A.appendChild(T),A.appendChild(S);let E=document.createElement("div");E.className="persona-feedback-numbers";let B=[];for(let O=0;O<=10;O++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${O} out of 10`),z.textContent=String(O),z.dataset.rating=String(O),O<=6?z.classList.add("persona-feedback-detractor"):O<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=O,B.forEach((le,ue)=>{le.classList.toggle("selected",ue===O),le.setAttribute("aria-checked",ue===O?"true":"false")})}),B.push(z),E.appendChild(z)}L.appendChild(A),L.appendChild(E),f.appendChild(L);let H=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=a,H.rows=3,H.setAttribute("aria-label","Additional comments"),O.appendChild(H),f.appendChild(O)}let w=document.createElement("div");w.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=l,F.addEventListener("click",()=>{o?.(),u.remove()});let q=document.createElement("button");return q.type="button",q.className="persona-feedback-btn persona-feedback-btn-submit",q.textContent=s,q.addEventListener("click",async()=>{if(g===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}q.disabled=!0,q.textContent="Submitting...";try{let O=H?.value.trim()||void 0;await t(g,O),u.remove()}catch(O){q.disabled=!1,q.textContent=s,console.error("[NPS Feedback] Failed to submit:",O)}}),w.appendChild(F),w.appendChild(q),f.appendChild(w),u.appendChild(f),u}var Gn="persona-chat-history",Pv=30*1e3,Rv=641,Iv={"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 Bv(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let r of o){if(r.kind!=="file"||!r.type.startsWith("image/"))continue;let n=r.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let a=Iv[n.type]??"png";t.push(new File([n],`clipboard-image-${Date.now()}.${a}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let r of Array.from(e.files??[]))r.type.startsWith("image/")&&t.push(r);return t}function el(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Hv(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Wv(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var Fp=e=>!e||typeof e!="object"?{}:{...e},Hg=e=>e.map(t=>({...t,streaming:!1})),Wg=(e,t,o)=>{let r=e?.markdown?$r(e.markdown):null,n=Sn(e?.sanitize);return e?.postprocessMessage&&n&&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=>{let s=a.text??"",l=a.message.rawContent??null;if(t){let c=t.process({text:s,raw:l??s,message:a.message,streaming:a.streaming});c!==null&&(s=c.text,c.persist||(a.message.__skipPersist=!0),c.resubmit&&!a.streaming&&o&&o())}let p=qo()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...a,text:s,raw:l??a.text??""});d=n?n(c):c}else if(r){let c=a.streaming?Af(s):s,u=r(c);d=n&&p?n(u):u}else d=Ro(s);return d}};function Dg(e){let t=y("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",r=e?.iconSize??"48px",n=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,s=ne(o,r,n,a);if(s&&t.appendChild(s),e?.label){let l=y("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var tl=(e,t,o)=>{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 r=mi(t),n=Qa.getForInstance(r.plugins),{plugin:a,teardown:s}=hg();r.components&&Mo.registerAll(r.components);let l=Lg(),d=r.persistState===!1?null:r.storageAdapter??Ki(),c={},u=null,g=!1,f=i=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(i);if(m&&typeof m=="object"&&"state"in m){let{state:b,open:v}=m;return v&&(g=!0),b}return m}catch(m){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")u=i.then(m=>f(m??{messages:[],metadata:{}}));else{let b=f(i??{messages:[],metadata:{}});b.metadata&&(c=Fp(b.metadata)),b.messages?.length&&(r={...r,initialMessages:b.messages}),b.artifacts?.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:b.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(r.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(r={...r,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let h=()=>c,C=i=>{c=i({...c})??{},vl()},M=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ya],L=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[dn.message,dn.messageAndClick],A=Za({parsers:M,handlers:L,getSessionMetadata:h,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});A.syncFromMetadata();let T=r.launcher?.enabled??!0,S=r.launcher?.autoExpand??!1,E=r.autoFocusInput??!1,B=S,H=T,w=r.layout?.header?.layout,F=!1,q=()=>Tr(r),O=()=>T||q(),z=q()?!1:T?S:!0,le=!1,ue=null,Ee=()=>{le=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{le&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),le=!1)},1e4)},De=Wg(r,A,Ee),se=r.features?.showReasoning??!0,xe=r.features?.showToolCalls??!0,Y=r.features?.showEventStreamToggle??!1,de=r.features?.scrollToBottom??{},ee=r.features?.scrollBehavior??{},Ae=`${(typeof r.persistState=="object"?r.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,be=Y?new Ga(Ae):null,He=r.features?.eventStream?.maxEvents??2e3,Oe=Y?new ja(He,be):null,Ke=Y?new Ka:null,Ue=null,ke=!1,Re=null,it=0;be?.open().then(()=>Oe?.restore()).catch(i=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Ne={onCopy:i=>{l.emit("message:copy",i),V?.isClientTokenMode()&&V.submitMessageFeedback(i.id,"copy").catch(m=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",m)}),r.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),V?.isClientTokenMode()&&V.submitMessageFeedback(i.messageId,i.type).catch(m=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",m)}),r.messageActions?.onFeedback?.(i)}},Je=r.statusIndicator??{},po=i=>i==="idle"?Je.idleText??Wt.idle:i==="connecting"?Je.connectingText??Wt.connecting:i==="connected"?Je.connectedText??Wt.connected:i==="error"?Je.errorText??Wt.error:i==="paused"?Je.pausedText??Wt.paused:i==="resuming"?Je.resumingText??Wt.resuming:Wt[i];function Lt(i,m,b,v){if(v==="idle"&&b.idleLink){i.textContent="";let P=document.createElement("a");P.href=b.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=m,P.style.color="inherit",P.style.textDecoration="none",i.appendChild(P)}else i.textContent=m}let mt=rg({config:r,showClose:O()}),{wrapper:Se,panel:me,pillRoot:lt}=mt.shell,Le=mt.panelElements,{container:fe,body:ie,messagesWrapper:he,suggestions:xt,textarea:U,sendButton:te,sendButtonWrapper:We,composerForm:Te,statusText:R,introTitle:J,introSubtitle:x,closeButton:k,iconHolder:I,headerTitle:N,headerSubtitle:K,header:_,footer:j,actionsRow:re,leftActions:tt,rightActions:Pe}=Le,dt=Le.setSendButtonMode,G=Le.micButton,qe=Le.micButtonWrapper,ve=Le.attachmentButton,Ie=Le.attachmentButtonWrapper,Me=Le.attachmentInput,Qe=Le.attachmentPreviewsContainer;fe.classList.add("persona-relative"),ie.classList.add("persona-relative");let Mr=12,Er=()=>de.label??"",nl=()=>de.iconName??"arrow-down",rs=()=>de.enabled!==!1,Zt=()=>ee.mode??"anchor-top",Jo=()=>Zt()==="follow"||Zt()==="anchor-top"&&ra,Zp=()=>ee.anchorTopOffset??16,bh=()=>ee.restorePosition??"bottom",eu=()=>ee.pauseOnInteraction===!0,tu=()=>ee.showActivityWhilePinned!==!1,ou=()=>ee.announce===!0,Bt=y("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");Bt.type="button",Bt.style.display="none",Bt.setAttribute("data-persona-scroll-to-bottom","true");let Xn=y("span","persona-flex persona-items-center"),al=y("span",""),kr=y("span","");kr.setAttribute("data-persona-scroll-to-bottom-count",""),kr.style.display="none",Bt.append(Xn,al,kr),fe.appendChild(Bt);let Qo=y("div","persona-stream-anchor-spacer");Qo.setAttribute("aria-hidden","true"),Qo.setAttribute("data-persona-anchor-spacer",""),Qo.style.flexShrink="0",Qo.style.pointerEvents="none",Qo.style.height="0px",ie.appendChild(Qo);let Lr=y("div","persona-sr-only");Lr.setAttribute("aria-live","polite"),Lr.setAttribute("aria-atomic","true"),Lr.setAttribute("role","status"),Lr.setAttribute("data-persona-live-region",""),Object.assign(Lr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),fe.appendChild(Lr);let Jn=null,ns=null,ru=i=>{!ou()||!i||(ns=i,Jn===null&&(Jn=setTimeout(()=>{Jn=null,ns&&ou()&&(Lr.textContent=ns),ns=null},400)))},cn=()=>{let m=j.style.display==="none"?0:j.offsetHeight;Bt.style.bottom=`${m+Mr}px`};cn();let nu=()=>{let i=!!Er();Bt.setAttribute("aria-label",Er()||"Jump to latest"),Bt.title=Er(),Bt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Xn.innerHTML="";let m=ne(nl(),"14px","currentColor",2);m?(Xn.appendChild(m),Xn.style.display=""):Xn.style.display="none",al.textContent=Er(),al.style.display=i?"":"none"};nu();let Mt=null,au=null,su=n.find(i=>i.renderHeader);if(su?.renderHeader){let i=su.renderHeader({config:r,defaultRenderer:()=>{let m=Ko({config:r,showClose:O()});return rn(fe,m,r),m.header},onClose:()=>ht(!1,"user")});if(i){let m=fe.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),_=i,mt.header.element=i)}}let sl=()=>{if(!Oe)return;if(ke=!0,!Ue&&Oe&&(Ue=Cg({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Qn(),config:r,plugins:n,getThroughput:()=>Ke?.getMetric()??{status:"idle"}})),Ue&&(ie.style.display="none",j.parentNode?.insertBefore(Ue.element,j),Ue.update()),at){at.style.boxShadow=`inset 0 0 0 1.5px ${Qt.actionIconColor}`;let m=r.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(b=>b&&at.classList.add(b))}let i=()=>{if(!ke)return;let m=Date.now();m-it>=200&&(Ue?.update(),it=m),Re=requestAnimationFrame(i)};it=0,Re=requestAnimationFrame(i),no(),l.emit("eventStream:opened",{timestamp:Date.now()})},Qn=()=>{if(ke){if(ke=!1,Ue&&Ue.element.remove(),ie.style.display="",at){at.style.boxShadow="";let i=r.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&at.classList.remove(m))}Re!==null&&(cancelAnimationFrame(Re),Re=null),no(),l.emit("eventStream:closed",{timestamp:Date.now()})}},at=null;if(Y){let i=r.features?.eventStream?.classNames,m="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"+(i?.toggleButton?" "+i.toggleButton:"");at=y("button",m),at.style.width="28px",at.style.height="28px",at.style.color=Qt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let b=ne("activity","18px","currentColor",1.5);b&&at.appendChild(b);let v=Le.clearChatButtonWrapper,P=Le.closeButtonWrapper,W=v||P;W&&W.parentNode===_?_.insertBefore(at,W):_.appendChild(at),at.addEventListener("click",()=>{ke?Qn():sl()})}let xh=i=>{let m=r.attachments;if(!m?.enabled)return;let b=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!b){b=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.setAttribute("data-persona-composer-attachment-previews",""),b.style.display="none";let P=i.querySelector("[data-persona-composer-form]");P?.parentNode?P.parentNode.insertBefore(b,P):i.insertBefore(b,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let P=y("input");P.type="file",P.setAttribute("data-persona-composer-attachment-input",""),P.accept=(m.allowedTypes??jo).join(","),P.multiple=(m.maxFiles??4)>1,P.style.display="none",P.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(P)}},iu=n.find(i=>i.renderComposer);if(iu?.renderComposer){let i=r.composer,m=iu.renderComposer({config:r,defaultRenderer:()=>Un({config:r}).footer,onSubmit:b=>{if(!V||V.isStreaming())return;let v=b.trim(),P=Mt?.hasAttachments()??!1;if(!v&&!P)return;Du();let W;P&&(W=[],W.push(...Mt.getContentParts()),v&&W.push(Pa(v))),V.sendMessage(v,{contentParts:W}),P&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Me?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},onVoiceToggle:r.voiceRecognition?.enabled===!0?()=>{au?.()}:void 0});m&&(mt.replaceComposer(m),j=mt.composer.footer)}let vh=i=>{let m=(...ce)=>{for(let oe of ce){let ye=i.querySelector(oe);if(ye)return ye}return null},b=i.querySelector("[data-persona-composer-form]"),v=i.querySelector("[data-persona-composer-input]"),P=i.querySelector("[data-persona-composer-submit]"),W=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");b&&(Te=b),v&&(U=v),P&&(te=P),W&&(G=W,qe=W.parentElement),Q&&(R=Q);let $=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(xt=$);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(ve=X,Ie=X.parentElement),Me=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Qe=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(re=ae)};xh(j),vh(j);let Yo=r.layout?.contentMaxWidth??(q()?r.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Yo&&(he.style.maxWidth=Yo,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%"),Yo&&Te&&!q()&&(Te.style.maxWidth=Yo,Te.style.marginLeft="auto",Te.style.marginRight="auto"),Yo&&xt&&!q()&&(xt.style.maxWidth=Yo,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Yo&&Qe&&!q()&&(Qe.style.maxWidth=Yo,Qe.style.marginLeft="auto",Qe.style.marginRight="auto"),r.attachments?.enabled&&Me&&Qe){Mt=Zr.fromConfig(r.attachments),Mt.setPreviewsContainer(Qe),Me.addEventListener("change",b=>{let v=b.target;Mt?.handleFileSelect(v.files),v.value=""});let i=r.attachments.dropOverlay,m=Dg(i);fe.appendChild(m)}(()=>{let i=r.layout?.slots??{},m=v=>{switch(v){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return he;case"footer-top":return xt;case"composer":return Te;case"footer-bottom":return R;default:return null}},b=(v,P)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")_.insertBefore(P,_.firstChild);else if(v==="header-right")_.appendChild(P);else{let W=_.querySelector(".persona-flex-col");W?W.parentNode?.insertBefore(P,W.nextSibling):_.appendChild(P)}break;case"body-top":{let W=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");W?W.replaceWith(P):ie.insertBefore(P,ie.firstChild);break}case"body-bottom":ie.appendChild(P);break;case"footer-top":xt.replaceWith(P);break;case"footer-bottom":R.replaceWith(P);break;default:break}};for(let[v,P]of Object.entries(i))if(P)try{let W=P({config:r,defaultContent:()=>m(v)});W&&b(v,W)}catch(W){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,W)}})();let lu=i=>{let b=i.target.closest('button[data-expand-header="true"]');if(!b)return;let v=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let P=v.getAttribute("data-message-id");if(!P)return;let W=b.getAttribute("data-bubble-type");if(W==="reasoning")Vn.has(P)?Vn.delete(P):Vn.add(P),ig(P,v);else if(W==="tool")zn.has(P)?zn.delete(P):zn.add(P),lg(P,v,r);else if(W==="approval"){let $=((r.approval!==!1?r.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=an.get(P)??$;an.set(P,!X),ug(P,v,r)}Br.delete(P)};he.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),lu(i))}),he.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),lu(i))}),he.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let b=he.getRootNode(),v=typeof b.getSelection=="function"?b.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let P=v.toString(),W=_m(P);!W||W===P||(m.setData("text/plain",W),i.preventDefault())});let il=new Map,du=null,cu="idle",Ch={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},wh=(i,m)=>{let{icon:b,label:v}=Ch[m];i.setAttribute("aria-label",v),i.title=v,i.setAttribute("aria-pressed",m==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",m!=="idle"),i.classList.toggle("persona-message-action-loading",m==="loading");let P=ne(b,14,"currentColor",2);P&&(i.innerHTML="",i.appendChild(P))},pu=()=>{he.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;wh(m,v&&v===du?cu:"idle")})};he.addEventListener("click",i=>{let b=i.target.closest(".persona-message-action-btn[data-action]");if(!b)return;i.preventDefault(),i.stopPropagation();let v=b.closest("[data-actions-for]");if(!v)return;let P=v.getAttribute("data-actions-for");if(!P)return;let W=b.getAttribute("data-action");if(W==="copy"){let $=V.getMessages().find(X=>X.id===P);if($&&Ne.onCopy){let X=$.content||"";navigator.clipboard.writeText(X).then(()=>{b.classList.add("persona-message-action-success");let ae=ne("check",14,"currentColor",2);ae&&(b.innerHTML="",b.appendChild(ae)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ce=ne("copy",14,"currentColor",2);ce&&(b.innerHTML="",b.appendChild(ce))},2e3)}).catch(ae=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ae)}),Ne.onCopy($)}}else if(W==="read-aloud")V.toggleReadAloud(P);else if(W==="upvote"||W==="downvote"){let $=(il.get(P)??null)===W,X=W==="upvote"?"thumbs-up":"thumbs-down";if($){il.delete(P),b.classList.remove("persona-message-action-active");let ae=ne(X,14,"currentColor",2);ae&&(b.innerHTML="",b.appendChild(ae))}else{let ae=W==="upvote"?"downvote":"upvote",ce=v.querySelector(`[data-action="${ae}"]`);if(ce){ce.classList.remove("persona-message-action-active");let st=ne(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);st&&(ce.innerHTML="",ce.appendChild(st))}il.set(P,W),b.classList.add("persona-message-action-active");let oe=ne(X,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(oe)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let je=V.getMessages().find(yt=>yt.id===P);je&&Ne.onFeedback&&Ne.onFeedback({type:W,messageId:je.id,message:je})}}}),he.addEventListener("click",i=>{let b=i.target.closest("button[data-approval-action]");if(!b)return;i.preventDefault(),i.stopPropagation();let v=b.closest(".persona-approval-bubble");if(!v)return;let P=v.getAttribute("data-message-id");if(!P)return;let W=b.getAttribute("data-approval-action");if(!W)return;let Q=W==="approve"?"approved":"denied",X=V.getMessages().find(ce=>ce.id===P);if(!X?.approval)return;let ae=v.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?V.resolveWebMcpApproval(P,Q):V.resolveApproval(X.approval,Q)});let Ye=null,Yn=null,Zn=()=>{},ea="none",as=null,yo={artifacts:[],selectedId:null},Do=!1,bo=!1,ta=!1,pn=!1,uu=()=>pn||yo.artifacts.some(i=>jr(r.features?.artifacts,i.artifactType)==="panel"),ss=()=>yo.artifacts.length>0&&!Do&&uu(),gt={current:null},ll=(i,m)=>{let b=V.getArtifactById(m),v=b?.markdown,P=b?.title||"artifact",W=b?.file,Q=b?.artifactType??"markdown";if(!v){let ae=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ae){let oe=V.getMessages().find(ye=>ye.id===ae);if(oe?.rawContent)try{let ye=JSON.parse(oe.rawContent);v=ye?.props?.markdown,P=ye?.props?.title||P,ye?.props?.file&&typeof ye.props.file=="object"&&(W=ye.props.file),!b&&typeof ye?.props?.artifactType=="string"&&(Q=ye.props.artifactType)}catch{}}}return{markdown:v,title:P,file:W,artifactType:Q}};he.addEventListener("click",i=>{let b=i.target.closest("[data-download-artifact]");if(!b)return;i.preventDefault(),i.stopPropagation();let v=b.getAttribute("data-download-artifact");if(!v||r.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:W,title:Q,file:$}=ll(b,v);if(!W)return;let{filename:X,mime:ae,content:ce}=wm({title:Q,markdown:W,file:$}),oe=new Blob([ce],{type:ae}),ye=URL.createObjectURL(oe),je=document.createElement("a");je.href=ye,je.download=X,je.click(),URL.revokeObjectURL(ye)}),he.addEventListener("click",i=>{let b=i.target.closest("[data-artifact-custom-action]");if(!b)return;i.preventDefault(),i.stopPropagation();let v=b.getAttribute("data-artifact-custom-action");if(!v)return;let P=b.closest("[data-artifact-inline]"),W=P?null:b.closest("[data-open-artifact]"),Q=P?P.getAttribute("data-artifact-inline"):W?.getAttribute("data-open-artifact")??null,X=(P?r.features?.artifacts?.inlineActions:r.features?.artifacts?.cardActions)?.find(yt=>yt.id===v);if(!X)return;let{markdown:ae,title:ce,file:oe,artifactType:ye}=ll(b,Q??""),je={artifactId:Q,title:ce,artifactType:ye,markdown:ae,file:oe};try{Promise.resolve(X.onClick(je)).catch(()=>{})}catch{}}),he.addEventListener("click",i=>{let b=i.target.closest("[data-copy-artifact]");if(!b)return;i.preventDefault(),i.stopPropagation();let v=b.getAttribute("data-copy-artifact");if(!v)return;let P=V.getArtifactById(v),W="";if(P)W=Na(P);else{let{markdown:Q,file:$,artifactType:X}=ll(b,v);X==="markdown"&&(W=Na({id:v,artifactType:"markdown",status:"complete",markdown:Q??"",...$?{file:$}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let Q=ne("check",16,"currentColor",2);Q&&(b.replaceChildren(Q),setTimeout(()=>{let $=ne("copy",16,"currentColor",2);$&&b.replaceChildren($)},1500))}).catch(()=>{})}),he.addEventListener("click",i=>{let b=i.target.closest("[data-expand-artifact-inline]");if(!b)return;i.preventDefault(),i.stopPropagation();let v=b.getAttribute("data-expand-artifact-inline");!v||r.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Do=!1,pn=!0,bo=!0,ta=!0,V.selectArtifact(v),Fo())}),he.addEventListener("click",i=>{let m=i.target;if(m.closest("[data-download-artifact]")||m.closest("[data-artifact-custom-action]"))return;let b=m.closest("[data-open-artifact]");if(!b)return;let v=b.getAttribute("data-open-artifact");!v||r.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(i.preventDefault(),i.stopPropagation(),Do=!1,pn=!0,V.selectArtifact(v),Fo())}),he.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let m=i.target;!m.hasAttribute("data-open-artifact")&&!m.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),m.click())});let un=Le.composerOverlay,fn=(i,m,b)=>{let v=m.trim();if(!v||!gt.current)return;let P=i.getAttribute("data-tool-call-id")??"",W=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:v,answers:b.structured,values:b.values??(b.source==="multi"?v.split(", "):[v]),isFreeText:W,source:b.source},bubbles:!0,composed:!0})),pr(un,P);let Q=gt.current.getMessages().find($=>$.toolCall?.id===P);Q?.agentMetadata?.awaitingLocalTool?gt.current.resolveAskUserQuestion(Q,b.structured??v):gt.current.sendMessage(v)},Pr=i=>{let m=gt.current;if(!m)return;let b=i.getAttribute("data-tool-call-id")??"",v=m.getMessages().find(P=>P.toolCall?.id===b);v&&m.persistAskUserQuestionProgress(v,{answers:Os(i,v),currentIndex:ho(i)})},fu=i=>Object.entries(i).map(([m,b])=>`${m}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),dl=i=>{if(r.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=ho(i),b=En(i);if(m>=b-1)return;let v=gt.current?.getMessages().find(P=>P.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(Ns(i,v,r,m+1),Pr(i))};un.addEventListener("click",i=>{let b=i.target.closest("[data-ask-user-action]");if(!b)return;let v=b.closest("[data-persona-ask-sheet-for]");if(!v)return;let P=b.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),P==="dismiss"){let W=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),pr(un,W);let Q=gt.current?.getMessages().find($=>$.toolCall?.id===W);Q?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(Q),gt.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(P==="pick"){let W=b.getAttribute("data-option-label");if(!W)return;let Q=v.getAttribute("data-multi-select")==="true",$=cr(v);if($&&Q){let X=Kr(v)[ho(v)],ae=new Set(Array.isArray(X)?X:[]);ae.has(W)?ae.delete(W):ae.add(W),ur(v,Array.from(ae)),Pr(v);return}if($){ur(v,W),Pr(v),dl(v);return}if(Q){let X=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",X?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!X);let ae=v.querySelector('[data-ask-user-action="submit-multi"]');ae&&(ae.disabled=Gl(v).length===0);return}fn(v,W,{source:"pick",values:[W]});return}if(P==="submit-multi"){let W=Gl(v);if(W.length===0)return;fn(v,W.join(", "),{source:"multi",values:W});return}if(P==="open-free-text"){let W=v.querySelector('[data-ask-free-text-row="true"]');W&&(W.classList.remove("persona-hidden"),W.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(P==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(P==="submit-free-text"){let Q=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(cr(v)){ur(v,Q.trim()),Pr(v),dl(v);return}fn(v,Q,{source:"free-text"});return}if(P==="next"||P==="back"){if(!gt.current)return;let W=v.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(oe=>oe.toolCall?.id===W);if(!Q)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let oe=Kr(v)[ho(v)];(typeof oe!="string"||oe!==X)&&ur(v,X)}let ae=P==="next"?1:-1,ce=ho(v)+ae;Ns(v,Q,r,ce),Pr(v);return}if(P==="submit-all"){if(!gt.current)return;let W=v.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(oe=>oe.toolCall?.id===W);if(!Q)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&ur(v,X);let ae=Os(v,Q);gt.current.persistAskUserQuestionProgress(Q,{answers:ae,currentIndex:ho(v)});let ce=fu(ae);fn(v,ce||"(submitted)",{source:"submit-all",structured:ae});return}if(P==="skip"){if(!gt.current)return;let W=v.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(ye=>ye.toolCall?.id===W);if(!Q)return;let $=cr(v),X=ho(v),ae=En(v),ce=X>=ae-1;if(!$){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),pr(un,W),Q.agentMetadata?.awaitingLocalTool&&(gt.current.markAskUserQuestionResolved(Q),gt.current.resolveAskUserQuestion(Q,"(dismissed)"));return}ur(v,"");let oe=v.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),ce){let ye=Os(v,Q),je=fu(ye);fn(v,je||"(skipped)",{source:"submit-all",structured:ye});return}Ns(v,Q,r,X+1),Pr(v);return}}),un.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let b=i.target;if(!b.matches?.('[data-ask-free-text-input="true"]'))return;let v=b.closest("[data-persona-ask-sheet-for]");if(!v)return;i.preventDefault();let P=b.value;if(P.trim()){if(cr(v)){ur(v,P.trim()),Pr(v),dl(v);return}fn(v,P,{source:"free-text"})}});let mu=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let m=i.target;if(m?.tagName==="INPUT"||m?.tagName==="TEXTAREA"||m?.isContentEditable)return;let b=un.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let v=Number(i.key),W=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];W&&(i.preventDefault(),W.click())};document.addEventListener("keydown",mu);let Zo=null,vt=null,oa=null,is=null,cl=()=>{},gu=!1,ls="",ds="";function pl(){is?.(),is=null}let hu=()=>{if(!Zo||!vt)return;let i=e.classList.contains("persona-artifact-welded-split"),m=e.ownerDocument.defaultView??window,b=m.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||b){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let v=Zo.firstElementChild;if(!v||v===vt)return;let P=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${P}px`,vt.style.zIndex="5";let W=Bp(Zo,m),Q=v.offsetWidth+W/2-P/2;vt.style.left=`${Math.max(0,Q)}px`},cs=()=>{},Ah=()=>{let i=e.ownerDocument.defaultView??window,m=r.launcher?.mobileFullscreen??!0,b=r.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>b?!1:T||It(r)},ps=()=>!Yt(r)||!ss()||e.classList.contains("persona-artifact-narrow-host")||Ah()||(e.ownerDocument.defaultView??window).innerWidth<Rv?"none":Ip(r)?"detached":"welded",Fo=()=>{if(!Ye||!Yt(r))return;Xa(e,r),Ja(e,r),cs();let i=r.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=me.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let b=ss();Ye.setVisible(b),Ye.update(yo),Do?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),bo=!1,ta=!1):yo.artifacts.length>0&&uu()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),bo=!1,ta=!1);let v=r.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(v),Ye.setCopyButtonVisible(r.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(r.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(r.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(r.features?.artifacts?.renderTabBar),!v&&!ta&&(bo=!1),bo!==gu){let W=Ye.element;bo?(ls=W.style.width,ds=W.style.maxWidth,W.style.removeProperty("width"),W.style.removeProperty("max-width")):(ls&&(W.style.width=ls),ds&&(W.style.maxWidth=ds),ls="",ds=""),gu=bo}e.classList.toggle("persona-artifact-expanded",bo),Ye.setExpanded(bo);let P=ps();P!==ea&&(ea=P,Zn()),cl()};if(Yt(r)){me.style.position="relative";let i=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(fe),Ye=Ag(r,{onSelect:b=>gt.current?.selectArtifact(b),onDismiss:()=>{Do=!0,Fo()},onToggleExpand:()=>{let b=!bo,v=yo.selectedId??yo.artifacts[yo.artifacts.length-1]?.id??null;r.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:b})!==!0&&(bo=b,b||(ta=!1),Fo())}}),Ye.element.classList.add("persona-hidden"),Zo=m,m.appendChild(i),m.appendChild(Ye.element),Ye.backdrop&&me.appendChild(Ye.backdrop),me.appendChild(m),cl=()=>{if(!Zo||!Ye)return;if(!(r.features?.artifacts?.layout?.resizable===!0)){oa?.(),oa=null,pl(),vt&&(vt.remove(),vt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!vt){let v=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let P=e.ownerDocument,W=P.defaultView??window,Q=$=>{if(!Ye||$.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||W.innerWidth<=640)return;$.preventDefault(),pl();let X=$.clientX,ae=Ye.element.getBoundingClientRect().width,ce=r.features?.artifacts?.layout,oe=je=>{let yt=Zo.getBoundingClientRect().width,st=e.classList.contains("persona-artifact-welded-split"),jt=Bp(Zo,W),Dt=st?0:v.getBoundingClientRect().width||6,D=ae-(je.clientX-X),Fe=Eg(D,yt,jt,Dt,ce?.resizableMinWidth,ce?.resizableMaxWidth);Ye.element.style.width=`${Fe}px`,Ye.element.style.maxWidth="none",hu()},ye=()=>{P.removeEventListener("pointermove",oe),P.removeEventListener("pointerup",ye),P.removeEventListener("pointercancel",ye),is=null;try{v.releasePointerCapture($.pointerId)}catch{}};is=ye,P.addEventListener("pointermove",oe),P.addEventListener("pointerup",ye),P.addEventListener("pointercancel",ye);try{v.setPointerCapture($.pointerId)}catch{}};v.addEventListener("pointerdown",Q),vt=v,Zo.insertBefore(v,Ye.element),oa=()=>{v.removeEventListener("pointerdown",Q)}}if(vt){let v=ss();vt.classList.toggle("persona-hidden",!v),hu()}},cs=()=>{if(!T||!Ye||(r.launcher?.sidebarMode??!1)||It(r)&&oo(r).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,P=r.launcher?.mobileFullscreen??!0,W=r.launcher?.mobileBreakpoint??640;if(P&&v.innerWidth<=W||!Mg(r,T))return;let Q=r.launcher?.width??r.launcherWidth??lo,$=r.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ss()?(me.style.width=$,me.style.maxWidth=$):(me.style.width=Q,me.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(Yn=new ResizeObserver(()=>{Fo()}),Yn.observe(me))}else me.appendChild(fe);q()&<&&(Le.peekBanner&<.appendChild(Le.peekBanner),lt.appendChild(j)),e.appendChild(Se),lt&&e.appendChild(lt);let us=()=>{if(q()){me.style.width="100%",me.style.maxWidth="100%";let Rt=r.launcher?.composerBar??{},eo=Se.dataset.state==="expanded",Ms=Rt.expandedSize??"anchored";if(!(eo&&Ms!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let ma=r.theme?.components?.panel,Es=yr(r),Cn=(Uo,Ur)=>Uo==null||Uo===""?Ur:Jt(Es,Uo)??Uo,ga="1px solid var(--persona-border)",Wl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",_r="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=Cn(ma?.border,ga),fe.style.borderRadius=Cn(ma?.borderRadius,_r),fe.style.boxShadow=Cn(ma?.shadow,Wl),fe.style.overflow="hidden";return}let i=It(r),m=r.launcher?.sidebarMode??!1,b=i||m||(r.launcher?.fullHeight??!1),v=r.launcher?.enabled===!1,P=r.launcher?.detachedPanel===!0,W=r.theme?.components?.panel,Q=yr(r),$=(Rt,eo)=>Rt==null||Rt===""?eo:Jt(Q,Rt)??Rt,X=e.ownerDocument.defaultView??window,ae=r.launcher?.mobileFullscreen??!0,ce=r.launcher?.mobileBreakpoint??640,oe=X.innerWidth<=ce,ye=ae&&oe&&T,je=i&&ae&&oe,yt=r.launcher?.position??"bottom-left",st=yt==="bottom-left"||yt==="top-left",jt=r.launcher?.zIndex??zt,Dt="var(--persona-panel-border, 1px solid var(--persona-border))",D="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Fe="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",we=P&&!ye&&!je;we?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let _e=we?Dt:m||ye?"none":Dt,Tt=we?D:ye?"none":m?st?"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))":v?"none":D;i&&!ye&&!we&&(Tt="none",_e="none");let ut=we?Fe:m||ye?"0":Fe,wt=$(W?.border,_e),bt=$(W?.shadow,Tt),qt=$(W?.borderRadius,ut),Or=ps(),ft=Or==="detached",pe=Or==="welded";e.classList.toggle("persona-artifact-detached-split",ft),e.classList.toggle("persona-artifact-welded-split",pe);let At="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",nt=(r.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Yt(r)&&Ip(r)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",nt);let ze=ft||nt?"none":bt,Ze=ft?Dt:pe?"none":wt,Pt=ft?Fe:qt;nt&&(Ze="none",Pt="0");let Be=W?.borderRadius!=null&&W.borderRadius!=="",et=nt&&!Be?"0":qt,ao=ie.scrollTop;e.style.cssText="",Se.style.cssText="",me.style.cssText="",fe.style.cssText="",ie.style.cssText="",j.style.cssText="",ke&&(ie.style.display="none");let Nr=()=>{if(ao<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===ao)return;let eo=ie.scrollHeight-ie.clientHeight;eo<=0||(ie.scrollTop=Math.min(ao,eo))})};if(ye){Se.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"),Se.style.cssText=`
|
|
36
42
|
position: fixed !important;
|
|
37
43
|
inset: 0 !important;
|
|
38
44
|
width: 100% !important;
|
|
@@ -42,9 +48,9 @@ _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
42
48
|
padding: 0 !important;
|
|
43
49
|
display: flex !important;
|
|
44
50
|
flex-direction: column !important;
|
|
45
|
-
z-index: ${
|
|
51
|
+
z-index: ${jt} !important;
|
|
46
52
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
47
|
-
`,
|
|
53
|
+
`,me.style.cssText=`
|
|
48
54
|
position: relative !important;
|
|
49
55
|
display: flex !important;
|
|
50
56
|
flex-direction: column !important;
|
|
@@ -57,7 +63,7 @@ _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
57
63
|
padding: 0 !important;
|
|
58
64
|
box-shadow: none !important;
|
|
59
65
|
border-radius: 0 !important;
|
|
60
|
-
`,
|
|
66
|
+
`,fe.style.cssText=`
|
|
61
67
|
display: flex !important;
|
|
62
68
|
flex-direction: column !important;
|
|
63
69
|
flex: 1 1 0% !important;
|
|
@@ -68,20 +74,33 @@ _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
68
74
|
overflow: hidden !important;
|
|
69
75
|
border-radius: 0 !important;
|
|
70
76
|
border: none !important;
|
|
71
|
-
`,
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
77
|
+
`,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0",F=!0,Nr();return}let Ts=r?.launcher?.width??r?.launcherWidth??lo;if(!m&&!i)v&&b?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=Ts,me.style.maxWidth=Ts);else if(i)if(oo(r).reveal==="emerge"&&!P){let eo=oo(r).width;me.style.width=eo,me.style.maxWidth=eo}else me.style.width="100%",me.style.maxWidth="100%";if(cs(),me.style.boxShadow=ze,me.style.borderRadius=et,ft?me.style.border="none":pe&&(me.style.border=wt),fe.style.border=Ze,fe.style.borderRadius=Pt,fe.style.boxShadow=ft&&!nt?At:"",nt&&(fe.style.background="transparent",ie.style.background="transparent",j.style.background="transparent",j.style.borderTop="none"),pe){let Rt=r.features?.artifacts?.layout;as=Rt?.unifiedSplitOuterRadius?.trim()||Rt?.paneBorderRadius?.trim()||qt}else as=null;if(i&&!ye&&!we&&!ft&&!pe&&W?.border===void 0&&(fe.style.border="none",oo(r).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.style.borderRight="1px solid var(--persona-border)"),i&&!ye&&pe&&W?.border===void 0&&(oo(r).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",v&&(Se.style.overflow="hidden"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",ft||(me.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0"),v&&(we||ft||nt)&&!i&&(nt||(Se.style.padding="var(--persona-panel-inset)"),Se.style.background="var(--persona-panel-canvas-bg)"),Se.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"),!m&&!v&&!i&&(Eo[yt]??Eo["bottom-right"]).split(" ").forEach(eo=>Se.classList.add(eo)),m){let Rt=r.launcher?.sidebarWidth??"420px";P?Se.style.cssText=`
|
|
78
|
+
position: fixed !important;
|
|
79
|
+
top: var(--persona-panel-inset) !important;
|
|
80
|
+
bottom: var(--persona-panel-inset) !important;
|
|
81
|
+
width: ${Rt} !important;
|
|
82
|
+
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
83
|
+
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
84
|
+
margin: 0 !important;
|
|
85
|
+
padding: 0 !important;
|
|
86
|
+
display: flex !important;
|
|
87
|
+
flex-direction: column !important;
|
|
88
|
+
z-index: ${jt} !important;
|
|
89
|
+
${st?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
90
|
+
`:Se.style.cssText=`
|
|
91
|
+
position: fixed !important;
|
|
92
|
+
top: 0 !important;
|
|
93
|
+
bottom: 0 !important;
|
|
94
|
+
width: ${Rt} !important;
|
|
95
|
+
height: 100vh !important;
|
|
96
|
+
max-height: 100vh !important;
|
|
97
|
+
margin: 0 !important;
|
|
98
|
+
padding: 0 !important;
|
|
99
|
+
display: flex !important;
|
|
100
|
+
flex-direction: column !important;
|
|
101
|
+
z-index: ${jt} !important;
|
|
102
|
+
${st?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
103
|
+
`,me.style.cssText=`
|
|
85
104
|
position: relative !important;
|
|
86
105
|
display: flex !important;
|
|
87
106
|
flex-direction: column !important;
|
|
@@ -92,9 +111,10 @@ _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
92
111
|
min-height: 0 !important;
|
|
93
112
|
margin: 0 !important;
|
|
94
113
|
padding: 0 !important;
|
|
95
|
-
box-shadow: ${
|
|
96
|
-
border-radius: ${
|
|
97
|
-
|
|
114
|
+
box-shadow: ${ze} !important;
|
|
115
|
+
border-radius: ${et} !important;
|
|
116
|
+
${ft?"border: none !important;":pe?`border: ${wt} !important;`:""}
|
|
117
|
+
`,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),fe.style.cssText=`
|
|
98
118
|
display: flex !important;
|
|
99
119
|
flex-direction: column !important;
|
|
100
120
|
flex: 1 1 0% !important;
|
|
@@ -103,29 +123,32 @@ _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
103
123
|
min-height: 0 !important;
|
|
104
124
|
max-height: 100% !important;
|
|
105
125
|
overflow: hidden !important;
|
|
106
|
-
border-radius: ${
|
|
107
|
-
border: ${
|
|
108
|
-
|
|
126
|
+
border-radius: ${Pt} !important;
|
|
127
|
+
border: ${Ze} !important;
|
|
128
|
+
${ft&&!nt?`box-shadow: ${At} !important;`:""}
|
|
129
|
+
${nt?"background: transparent !important;":""}
|
|
130
|
+
`,j.style.cssText=`
|
|
109
131
|
flex-shrink: 0 !important;
|
|
110
132
|
border-top: none !important;
|
|
111
133
|
padding: 8px 16px 12px 16px !important;
|
|
112
|
-
`}if(!C&&!l){let Dt="max-height: -moz-available !important; max-height: stretch !important;",Bt=m?"":"padding-top: 1.25em !important;",$t=m?"":`z-index: ${(Ze=(Zn=o.launcher)==null?void 0:Zn.zIndex)!=null?Ze:wr} !important;`;fe.style.cssText+=Dt+Bt+$t}Xe()};un(),Hn(e,o),sl(e,o),il(e,o);let it=[];it.push(()=>{document.removeEventListener("keydown",$o)}),it.push(()=>{po!==null&&clearTimeout(po)});let ar=null,sr=null;it.push(()=>{ar==null||ar(),ar=null,sr==null||sr(),sr=null}),Or&&it.push(()=>{Or==null||Or.disconnect(),Or=null}),it.push(()=>{eo==null||eo(),eo=null,ya(),Nt&&(Nt.remove(),Nt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ie&&it.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Ee==null||Ee.destroy(),Ee=null,j==null||j.destroy(),j=null,Te=null});let Po=null,es=()=>{Po&&(Po(),Po=null),o.colorScheme==="auto"&&(Po=Fi(()=>{Hn(e,o)}))};es(),it.push(()=>{Po&&(Po(),Po=null)}),it.push(s);let Go=(sf=o.features)==null?void 0:sf.streamAnimation;if(Go!=null&&Go.type&&Go.type!=="none"){let l=qa(Go.type,Go.plugins);l&&(ji(l,e),it.push(()=>Xh(e)))}let zn=gx(Vt),Ro=null,U,ba=l=>{var C,R;if(!U)return;let m=l!=null?l:U.getMessages(),x=((R=(C=o.features)==null?void 0:C.suggestReplies)==null?void 0:R.enabled)!==!1?li(m):null;x?zn.render(x,U,xe,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(D=>D.role==="user")?zn.render([],U,xe,m):zn.render(o.suggestionChips,U,xe,m,o.suggestionChipsConfig)},fo=!1,Io=_h(),Ko=new Map,Ho=new Map,mo=new Map,va=0,$s=ra()!==null,yr=_i(),Ar=0,go=null,Mr=!1,$n=!1,ho=0,br=null,Wo=null,wa=!1,jn=!1,Ca=null,fn=!0,mn=!1,rt=null,L=4,$=24,z=80,K=new Map,G={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},De=(df=(lf=o.voiceRecognition)==null?void 0:lf.autoResume)!=null?df:!1,tt=l=>{i.emit("voice:state",{active:G.active,source:l,timestamp:Date.now()})},lt=()=>{b(l=>({...l,voiceState:{active:G.active,timestamp:Date.now(),manuallyDeactivated:G.manuallyDeactivated}}))},bl=()=>{var C,R;if(((C=o.voiceRecognition)==null?void 0:C.enabled)===!1)return;let l=Ap(p.voiceState),m=!!l.active,x=Number((R=l.timestamp)!=null?R:0);G.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-x<B0&&setTimeout(()=>{var D,V;G.active||(G.manuallyDeactivated=!1,((V=(D=o.voiceRecognition)==null?void 0:D.provider)==null?void 0:V.type)==="runtype"?U.toggleVoice().then(()=>{G.active=U.isVoiceActive(),tt("restore"),U.isVoiceActive()&&Ma()}):Gs("restore"))},1e3)},gn=()=>U?Wx(U.getMessages()).filter(l=>!l.__skipPersist):[];function Hr(l){if(!(d!=null&&d.save))return;let x={messages:l?Wx(l):U?gn():[],metadata:p,artifacts:_r.artifacts,selectedArtifactId:_r.selectedId};try{let C=d.save(x);C instanceof Promise&&C.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(C){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",C)}}let Jt=null,hn=()=>fe.querySelector("#persona-scroll-container")||ve,to=()=>{Jt!==null&&(cancelAnimationFrame(Jt),Jt=null),Mr=!1},Tr=()=>{go!==null&&(cancelAnimationFrame(go),go=null),$n=!1,to()},Wr=()=>fo&&vl()&&(Ft()!=="anchor-top"||lo()),Er=()=>{let l=bt()||"Jump to latest",m=Wr();zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),ho>0?(Fr.textContent=String(ho),Fr.style.display="",zt.setAttribute("aria-label",`${l} (${ho} new)`)):(Fr.textContent="",Fr.style.display="none",zt.setAttribute("aria-label",m?`${l} (response streaming below)`:l))},Up=()=>{ho!==0&&(ho=0,Er())},vl=()=>tr()?!yr.isFollowing():!Wn(ve,$),qr=()=>{if(!Qt()||te){zt.parentNode&&zt.remove(),zt.style.display="none";return}zt.parentNode!==Ce&&Ce.appendChild(zt),Qr();let m=Oo(ve)>0&&vl();m?Er():Up(),zt.style.display=m?"":"none"},ts=()=>{yr.pause()&&(Tr(),qr())},xn=()=>{yr.resume(),Up(),qr()},yn=(l=!1)=>{tr()&&yr.isFollowing()&&(!l&&!fo||(go!==null&&(cancelAnimationFrame(go),go=null),$n=!0,go=requestAnimationFrame(()=>{go=null,$n=!1,yr.isFollowing()&&by(hn(),l?220:140)})))},qp=(l,m,x,C=()=>!0)=>{let R=l.scrollTop,D=m(),V=D-R;if(to(),Math.abs(V)<1){Mr=!0,l.scrollTop=D,Ar=l.scrollTop,Mr=!1;return}let q=performance.now();Mr=!0;let _=re=>1-Math.pow(1-re,3),ne=re=>{if(!C()){to();return}let J=m();J!==D&&(D=J,V=D-R);let be=re-q,Fe=Math.min(be/x,1),Ne=_(Fe),Ue=R+V*Ne;l.scrollTop=Ue,Ar=l.scrollTop,Fe<1?Jt=requestAnimationFrame(ne):(l.scrollTop=D,Ar=l.scrollTop,Jt=null,Mr=!1)};Jt=requestAnimationFrame(ne)},by=(l,m=500)=>{let x=Oo(l)-l.scrollTop;if(Math.abs(x)<1){Ar=l.scrollTop;return}if(Math.abs(x)>=z){to(),Mr=!0,l.scrollTop=Oo(l),Ar=l.scrollTop,Mr=!1;return}qp(l,()=>Oo(l),m,()=>yr.isFollowing())},Vp=()=>{let l=hn();Mr=!0,l.scrollTop=Oo(l),Ar=l.scrollTop,Mr=!1,qr()},zp=l=>{let m=0,x=l;for(;x&&x!==ve;)m+=x.offsetTop,x=x.offsetParent;return m},$p=()=>{var D;if(Uo()!=="last-user-turn")return!1;let l=(D=U==null?void 0:U.getMessages())!=null?D:[];if(l.length<2)return!1;let m=[...l].reverse().find(V=>V.role==="user");if(!m)return!1;let x=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),C=ve.querySelector(`[data-message-id="${x}"]`);if(!C)return!1;let R=Math.min(Math.max(0,zp(C)-Ao()),Oo(ve));return Mr=!0,ve.scrollTop=R,Ar=ve.scrollTop,Mr=!1,Ft()==="follow"&&!Wn(ve,$)&&yr.pause(),qr(),!0},jp=l=>{Rr.style.height=`${Math.max(0,Math.round(l))}px`,br&&(br.spacerHeight=Math.max(0,l))},rs=()=>{Wo!==null&&(cancelAnimationFrame(Wo),Wo=null),to(),br=null,Rr.style.height="0px"},vy=l=>{Wo!==null&&cancelAnimationFrame(Wo),Wo=requestAnimationFrame(()=>{var _;Wo=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ve.querySelector(`[data-message-id="${m}"]`);if(!x)return;let C=zp(x),R=(_=br==null?void 0:br.spacerHeight)!=null?_:0,D=ve.scrollHeight-R,{targetScrollTop:V,spacerHeight:q}=$h({anchorOffsetTop:C,topOffset:Ao(),viewportHeight:ve.clientHeight,contentHeight:D});br={initialSpacerHeight:q,contentHeightAtAnchor:D,spacerHeight:q},jp(q),qp(ve,()=>V,220)})},wy=()=>{if(tr()){if(!yr.isFollowing()||Wn(ve,1))return;yn(!fo);return}if(br&&br.initialSpacerHeight>0){let l=ve.scrollHeight-br.spacerHeight,m=jh({initialSpacerHeight:br.initialSpacerHeight,contentHeightAtAnchor:br.contentHeightAtAnchor,currentContentHeight:l});m!==br.spacerHeight&&jp(m)}qr()},Cy=l=>{let m=Ft();m==="follow"?(xn(),yn(!0)):m==="anchor-top"&&(fn=!1,mn=!0,vy(l))},Sy=()=>{if(Ft()==="anchor-top"){if(mn){fn=!1;return}fn=!0,rs(),xn(),yn(!0)}},Ay=l=>{let m=new Map;l.forEach(x=>{let C=K.get(x.id);m.set(x.id,{streaming:x.streaming,role:x.role}),!C&&x.role==="assistant"&&(i.emit("assistant:message",x),!jn&&(Ft()!=="anchor-top"||lo())&&vl()&&(ho+=1,Er(),qr(),nn(ho===1?"1 new message below.":`${ho} new messages below.`))),x.role==="assistant"&&(C!=null&&C.streaming)&&x.streaming===!1&&i.emit("assistant:complete",x),x.variant==="approval"&&x.approval&&(C?x.approval.status!=="pending"&&i.emit("approval:resolved",{approval:x.approval,decision:x.approval.status}):i.emit("approval:requested",{approval:x.approval,message:x}))}),K.clear(),m.forEach((x,C)=>{K.set(C,x)})},My=(l,m,x)=>{var ot,He,Pe,$e,Xe,xt;let C=document.createElement("div"),D=(()=>{var Be;let F=n.find(Re=>Re.renderLoadingIndicator);if(F!=null&&F.renderLoadingIndicator)return F.renderLoadingIndicator;if((Be=o.loadingIndicator)!=null&&Be.render)return o.loadingIndicator.render})(),V=(F,Be)=>Be==null?!1:typeof Be=="string"?(F.textContent=Be,!0):(F.appendChild(Be),!0),q=new Set,_=new Set,ne=n.some(F=>F.renderAskUserQuestion),re=[],J=[],be=o.enableComponentStreaming!==!1,Fe=o.approval!==!1,Ne=[];if(m.forEach(F=>{var mr,Vr,Ge,Rt,zr,Kn,Xn,Qn,Jn,Ea,ka,Xt,Yn,wn,Cn,Qo,Zn;q.add(F.id);let Be=ne&&Jo(F),Re=Fe&&F.variant==="approval"&&!!F.approval,Je=!Be&&F.role==="assistant"&&!F.variant&&be&&pl(F);if(!Re&&mo.has(F.id)){let Ze=l.querySelector(`#wrapper-${F.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),mo.delete(F.id)}if(!Je&&Ho.has(F.id)){let Ze=l.querySelector(`#wrapper-${F.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Ho.delete(F.id)}let Pt=Jo(F)?`:${(mr=F.agentMetadata)!=null&&mr.askUserQuestionAnswered?"a":"u"}:${(Vr=F.agentMetadata)!=null&&Vr.askUserQuestionAnswers?Object.keys(F.agentMetadata.askUserQuestionAnswers).length:0}`:"",Oe=Oh(F,va)+Pt,Gt=Be||Re||Je?null:Uh(Io,F.id,Oe);if(Gt){C.appendChild(Gt.cloneNode(!0)),Jo(F)&&((Ge=F.toolCall)!=null&&Ge.id)&&((Rt=F.agentMetadata)==null?void 0:Rt.awaitingLocalTool)===!0&&!((zr=F.agentMetadata)!=null&&zr.askUserQuestionAnswered)&&(_.add(F.toolCall.id),Ba(F,o,je.composerOverlay));return}let wt=null,lr=n.find(Ze=>!!(F.variant==="reasoning"&&Ze.renderReasoning||F.variant==="tool"&&Ze.renderToolCall||!F.variant&&Ze.renderMessage)),Br=(Kn=o.layout)==null?void 0:Kn.messages;if(Jo(F)&&((Xn=F.agentMetadata)==null?void 0:Xn.askUserQuestionAnswered)===!0){Ko.delete(F.id);let Ze=l.querySelector(`#wrapper-${F.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(bs(F)&&((Jn=(Qn=o.features)==null?void 0:Qn.suggestReplies)==null?void 0:Jn.enabled)!==!1)return;if(Jo(F)&&((ka=(Ea=o.features)==null?void 0:Ea.askUserQuestion)==null?void 0:ka.enabled)!==!1){let Ze=n.find(Dt=>typeof Dt.renderAskUserQuestion=="function");if(Ze&&At.current){let Dt=Ko.get(F.id),Bt=Dt!==Oe,$t=null;if(Bt){let{payload:Ut,complete:gr}=Yo(F),$r=F.id,Do=()=>{var ur;return(ur=At.current)==null?void 0:ur.getMessages().find(fr=>fr.id===$r)};$t=Ze.renderAskUserQuestion({message:F,payload:Ut,complete:gr,resolve:ur=>{var no;let fr=Do();fr&&((no=At.current)==null||no.resolveAskUserQuestion(fr,ur))},dismiss:()=>{var fr,no,Sn;let ur=Do();(fr=ur==null?void 0:ur.agentMetadata)!=null&&fr.awaitingLocalTool&&((no=At.current)==null||no.markAskUserQuestionResolved(ur),(Sn=At.current)==null||Sn.resolveAskUserQuestion(ur,"(dismissed)"))},config:o})}let _t=Dt!=null;if(Bt&&$t===null&&!_t){((Xt=F.agentMetadata)==null?void 0:Xt.awaitingLocalTool)===!0&&!((Yn=F.agentMetadata)!=null&&Yn.askUserQuestionAnswered)&&(_.add(F.toolCall.id),Ba(F,o,je.composerOverlay));return}let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${F.id}`,ft.setAttribute("data-wrapper-id",F.id),ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),C.appendChild(ft),re.push({messageId:F.id,fingerprint:Oe,bubble:$t});return}else{((wn=F.agentMetadata)==null?void 0:wn.awaitingLocalTool)===!0&&!((Cn=F.agentMetadata)!=null&&Cn.askUserQuestionAnswered)&&(_.add(F.toolCall.id),Ba(F,o,je.composerOverlay));return}}else if(Re){let Ze=(Qo=n.find(_t=>typeof _t.renderApproval=="function"))!=null?Qo:a,Bt=mo.get(F.id)!==Oe,$t=null;if(Bt&&(Ze!=null&&Ze.renderApproval)){let _t=F.id,ft=(Ut,gr)=>{var Do,ur,fr;let $r=(Do=At.current)==null?void 0:Do.getMessages().find(no=>no.id===_t);$r!=null&&$r.approval&&($r.approval.toolType==="webmcp"?(ur=At.current)==null||ur.resolveWebMcpApproval($r.id,Ut):(fr=At.current)==null||fr.resolveApproval($r.approval,Ut,gr))};$t=Ze.renderApproval({message:F,defaultRenderer:()=>nl(F,o),config:o,approve:Ut=>ft("approved",Ut),deny:Ut=>ft("denied",Ut)})}if(Bt&&$t===null){let _t=l.querySelector(`#wrapper-${F.id}`);_t==null||_t.removeAttribute("data-preserve-runtime"),mo.delete(F.id),wt=nl(F,o)}else{let _t=document.createElement("div");_t.className="persona-flex",_t.id=`wrapper-${F.id}`,_t.setAttribute("data-wrapper-id",F.id),_t.setAttribute("data-approval-plugin-stub","true"),_t.setAttribute("data-preserve-runtime","true"),C.appendChild(_t),Ne.push({messageId:F.id,fingerprint:Oe,bubble:$t});return}}else if(lr)if(F.variant==="reasoning"&&F.reasoning&&lr.renderReasoning){if(!Le)return;wt=lr.renderReasoning({message:F,defaultRenderer:()=>mp(F,o),config:o})}else if(F.variant==="tool"&&F.toolCall&&lr.renderToolCall){if(!We)return;wt=lr.renderToolCall({message:F,defaultRenderer:()=>hp(F,o),config:o})}else lr.renderMessage&&(wt=lr.renderMessage({message:F,defaultRenderer:()=>{let Ze=$a(F,x,Br,o.messageActions,nt,{loadingIndicatorRenderer:D,widgetConfig:o});return F.role!=="user"&&wp(Ze,F,o,U),Ze},config:o}));if(!wt&&Je){let Ze=ul(F);if(Ze){let Dt=Ho.get(F.id),Bt=Dt!==Oe,$t=o.wrapComponentDirectiveInBubble!==!1,_t=null;if(Bt){let ft=cl(Ze,{config:o,message:F,transform:x});if(ft)if($t){let Ut=document.createElement("div");if(Ut.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(" "),Ut.id=`bubble-${F.id}`,Ut.setAttribute("data-message-id",F.id),F.content&&F.content.trim()){let gr=document.createElement("div");gr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gr.innerHTML=x({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),Ut.appendChild(gr)}Ut.appendChild(ft),_t=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${F.id}`,Ut.setAttribute("data-message-id",F.id),Ut.setAttribute("data-persona-component-directive","true"),F.content&&F.content.trim()){let gr=document.createElement("div");gr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gr.innerHTML=x({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),Ut.appendChild(gr)}Ut.appendChild(ft),_t=Ut}}if(_t||Dt!=null){let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${F.id}`,ft.setAttribute("data-wrapper-id",F.id),ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),$t||ft.classList.add("persona-w-full"),C.appendChild(ft),J.push({messageId:F.id,fingerprint:Oe,bubble:_t});return}}}if(!wt)if(F.variant==="reasoning"&&F.reasoning){if(!Le)return;wt=mp(F,o)}else if(F.variant==="tool"&&F.toolCall){if(!We)return;wt=hp(F,o)}else if(F.variant==="approval"&&F.approval){if(o.approval===!1)return;wt=nl(F,o)}else{let Ze=(Zn=o.layout)==null?void 0:Zn.messages;Ze!=null&&Ze.renderUserMessage&&F.role==="user"?wt=Ze.renderUserMessage({message:F,config:o,streaming:!!F.streaming}):Ze!=null&&Ze.renderAssistantMessage&&F.role==="assistant"?wt=Ze.renderAssistantMessage({message:F,config:o,streaming:!!F.streaming}):wt=$a(F,x,Ze,o.messageActions,nt,{loadingIndicatorRenderer:D,widgetConfig:o}),F.role!=="user"&&wt&&wp(wt,F,o,U)}let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-${F.id}`,Wt.setAttribute("data-wrapper-id",F.id),F.role==="user"&&Wt.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Wt.classList.add("persona-w-full"),Wt.appendChild(wt),qh(Io,F.id,Oe,Wt),C.appendChild(Wt)}),je.composerOverlay&&je.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Re=Be.getAttribute("data-persona-ask-sheet-for");Re&&!_.has(Re)&&En(je.composerOverlay,Re)}),(He=(ot=o.features)==null?void 0:ot.toolCallDisplay)!=null&&He.grouped){let F=[],Be=[];m.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&We){Be.push(Re);return}Be.length>1&&F.push(Be),Be=[]}),Be.length>1&&F.push(Be),F.forEach((Re,Je)=>{var mr,Vr;let Pt=Re.map(Ge=>Array.from(C.children).find(Rt=>Rt instanceof HTMLElement&&Rt.getAttribute("data-wrapper-id")===Ge.id)).filter(Ge=>!!Ge);if(Pt.length<2)return;let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id=`wrapper-tool-group-${Je}-${Re[0].id}`,Oe.setAttribute("data-wrapper-id",`tool-group-${Je}-${Re[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let lr=`Called ${Re.length} tools`,Br=(Vr=(mr=o.toolCall)==null?void 0:mr.renderGroupedSummary)==null?void 0:Vr.call(mr,{messages:Re,toolCalls:Re.map(Ge=>Ge.toolCall).filter(Ge=>!!Ge),defaultSummary:lr,config:o});V(wt,Br)||(wt.textContent=lr);let Wt=document.createElement("div");Wt.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(wt,Wt),Oe.appendChild(Gt),Pt[0].before(Oe),Pt.forEach((Ge,Rt)=>{let zr=document.createElement("div");zr.className="persona-tool-group-item persona-relative",zr.setAttribute("data-persona-tool-group-item","true"),Rt<Pt.length-1&&zr.setAttribute("data-persona-tool-group-connector","true"),zr.appendChild(Ge),Wt.appendChild(zr)})})}Vh(Io,q);let Ue=m.some(F=>F.role==="assistant"&&F.streaming),ze=m[m.length-1],ut=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(fo&&m.some(F=>F.role==="user")&&!Ue&&!ut){let F={config:o,streaming:!0,location:"standalone",defaultRenderer:ua},Be=n.find(Je=>Je.renderLoadingIndicator),Re=null;if(Be!=null&&Be.renderLoadingIndicator&&(Re=Be.renderLoadingIndicator(F)),Re===null&&((Pe=o.loadingIndicator)!=null&&Pe.render)&&(Re=o.loadingIndicator.render(F)),Re===null&&(Re=ua()),Re){let Je=document.createElement("div"),Pt=(($e=o.loadingIndicator)==null?void 0:$e.showBubble)!==!1;Je.className=Pt?["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(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(Re);let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id="wrapper-typing-indicator",Oe.setAttribute("data-wrapper-id","typing-indicator"),Oe.appendChild(Je),C.appendChild(Oe)}}if(!fo&&m.length>0){let F=m[m.length-1],Be={config:o,lastMessage:F,messageCount:m.length},Re=n.find(Pt=>Pt.renderIdleIndicator),Je=null;if(Re!=null&&Re.renderIdleIndicator&&(Je=Re.renderIdleIndicator(Be)),Je===null&&((Xe=o.loadingIndicator)!=null&&Xe.renderIdle)&&(Je=o.loadingIndicator.renderIdle(Be)),Je){let Pt=document.createElement("div"),Oe=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Pt.className=Oe?["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(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Je);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(Pt),C.appendChild(Gt)}}if(Ni(l,C),re.length>0)for(let{messageId:F,fingerprint:Be,bubble:Re}of re){let Je=l.querySelector(`#wrapper-${F}`);Je&&Re!==null&&(Je.replaceChildren(Re),Je.setAttribute("data-bubble-fp",Be),Ko.set(F,Be))}if(Ko.size>0)for(let F of Ko.keys())q.has(F)||Ko.delete(F);if(J.length>0)for(let{messageId:F,fingerprint:Be,bubble:Re}of J){let Je=l.querySelector(`#wrapper-${F}`);Je&&Re!==null&&(Je.replaceChildren(Re),Je.setAttribute("data-bubble-fp",Be),Ho.set(F,Be))}if(Ho.size>0)for(let F of Ho.keys())q.has(F)||Ho.delete(F);if(Ne.length>0)for(let{messageId:F,fingerprint:Be,bubble:Re}of Ne){let Je=l.querySelector(`#wrapper-${F}`);Je&&Re!==null&&(Je.replaceChildren(Re),Je.setAttribute("data-bubble-fp",Be),mo.set(F,Be))}if(mo.size>0)for(let F of mo.keys())q.has(F)||mo.delete(F)},os=(l,m,x)=>{My(l,m,x),cn()},ns=null,Ty=()=>{var x;if(ns)return;let l=C=>{let R=C.composedPath();R.includes(fe)||st&&R.includes(st)||Ot(!1,"user")};ns=l,((x=e.ownerDocument)!=null?x:document).addEventListener("pointerdown",l,!0)},Gp=()=>{var m;if(!ns)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",ns,!0),ns=null};it.push(()=>Gp());let as=null,Ey=()=>{var x;if(as)return;let l=C=>{C.key==="Escape"&&(C.isComposing||Ot(!1,"user"))};as=l,((x=e.ownerDocument)!=null?x:document).addEventListener("keydown",l,!0)},Kp=()=>{var m;if(!as)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",as,!0),as=null};it.push(()=>Kp());let ss=!1,Xp=new Set,ky=()=>{var m,x,C,R;let l=(C=(x=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:x.peek)==null?void 0:C.streamAnimation;return l||((R=o.features)==null?void 0:R.streamAnimation)},Sa=()=>{var ut,ot,He,Pe;if(!P())return;let l=je.peekBanner,m=je.peekTextNode;if(!l||!m)return;if(O){l.classList.remove("persona-pill-peek--visible");return}let x=(ut=U==null?void 0:U.getMessages())!=null?ut:[],C;for(let $e=x.length-1;$e>=0;$e--){let Xe=x[$e];if(Xe.role==="assistant"&&Xe.content){C=Xe;break}}if(!C){l.classList.remove("persona-pill-peek--visible");return}let R=C.content,D=!!C.streaming,V=ky(),q=Vi(V),_=q.type!=="none"?qa(q.type,V==null?void 0:V.plugins):null,ne=((ot=_==null?void 0:_.isAnimating)==null?void 0:ot.call(_,C))===!0,re=_!==null&&(D||ne);re&&_&&!Xp.has(_.name)&&(ji(_,e),Xp.add(_.name));let J=re&&(_!=null&&_.containerClass)?_.containerClass:null,be=(He=m.dataset.personaPeekStreamClass)!=null?He:null;be&&be!==J&&(m.classList.remove(be),delete m.dataset.personaPeekStreamClass),J&&be!==J&&(m.classList.add(J),m.dataset.personaPeekStreamClass=J),re?(m.style.setProperty("--persona-stream-step",`${q.speed}ms`),m.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Fe=re?zi(R,q.buffer,_,C,D):R;if(re&&q.placeholder==="skeleton"&&D&&(!Fe||!Fe.trim())){let $e=document.createElement("div"),Xe=Hs();Xe.classList.add("persona-pill-peek__skeleton"),$e.appendChild(Xe),Ni(m,$e)}else{let $e=Math.max(0,Fe.length-100),Xe=Fe.length>100?Fe.slice(-100):Fe,xt=Fo(Xe);if(!re||!_){let F=Fe.length>100?`\u2026${Xe}`:Xe;m.textContent!==F&&(m.textContent=F)}else{let F=xt;(_.wrap==="char"||_.wrap==="word")&&(F=Is(xt,_.wrap,`peek-${C.id}`,{skipTags:_.skipTags,startIndex:$e}));let Be=document.createElement("div");if(Be.innerHTML=F,_.useCaret&&Xe.length>0){let Re=$i(),Je=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Je[Je.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(Re,Pt.nextSibling):Be.appendChild(Re)}Ni(m,Be),(Pe=_.onAfterRender)==null||Pe.call(_,{container:m,bubble:l,messageId:C.id,message:C,speed:q.speed,duration:q.duration})}}let ze=fo||ss;l.classList.toggle("persona-pill-peek--visible",ze)};if(P()){let l=je.peekBanner;if(l){let C=R=>{R.preventDefault(),R.stopPropagation(),Ot(!0,"user")};l.addEventListener("pointerdown",C),it.push(()=>{l.removeEventListener("pointerdown",C)})}let m=()=>{ss||(ss=!0,Sa())},x=()=>{ss&&(ss=!1,Sa())};X.addEventListener("pointerenter",m),X.addEventListener("pointerleave",x),it.push(()=>{X.removeEventListener("pointerenter",m),X.removeEventListener("pointerleave",x)}),st&&(st.addEventListener("pointerenter",m),st.addEventListener("pointerleave",x),it.push(()=>{st.removeEventListener("pointerenter",m),st.removeEventListener("pointerleave",x)}))}let Ly=l=>{var be,Fe,Ne,Ue,ze,ut,ot,He;let m=(Fe=(be=o.launcher)==null?void 0:be.composerBar)!=null?Fe:{},x=(Ne=m.expandedSize)!=null?Ne:"anchored",C=(Ue=m.bottomOffset)!=null?Ue:"16px",R=m.collapsedMaxWidth,D=(ze=m.expandedMaxWidth)!=null?ze:"880px",V=(ut=m.expandedTopOffset)!=null?ut:"5vh",q=(ot=m.modalMaxWidth)!=null?ot:"880px",_=(He=m.modalMaxHeight)!=null?He:"min(90vh, 800px)",ne="calc(100vw - 32px)",re="var(--persona-pill-area-height, 80px)",J=fe.style;if(J.left="",J.right="",J.top="",J.bottom="",J.transform="",J.width="",J.maxWidth="",J.height="",J.maxHeight="",st){let Pe=st.style;Pe.bottom=C,Pe.width=R!=null?R:""}if(l&&x!=="fullscreen"){if(x==="modal"){J.top="50%",J.left="50%",J.transform="translate(-50%, -50%)",J.bottom="auto",J.right="auto",J.width=q,J.maxWidth=ne,J.maxHeight=_,J.height=_;return}J.left="50%",J.transform="translateX(-50%)",J.bottom=`calc(${C} + ${re})`,J.top=V,J.width=D,J.maxWidth=ne}},is=()=>{var _,ne,re,J,be,Fe,Ne,Ue;if(!B())return;if(P()){let ut=(re=((ne=(_=o.launcher)==null?void 0:_.composerBar)!=null?ne:{}).expandedSize)!=null?re:"anchored",ot=O?"expanded":"collapsed";fe.dataset.state=ot,fe.dataset.expandedSize=ut,st&&(st.dataset.state=ot,st.dataset.expandedSize=ut),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ly(O),Ce.style.display=O?"flex":"none",un(),O?(Ty(),Ey()):(Gp(),Kp()),Sa();return}let l=nr(o),m=(J=e.ownerDocument.defaultView)!=null?J:window,x=(Fe=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?Fe:640,C=(Ue=(Ne=o.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ue:!0,R=m.innerWidth<=x,D=C&&R&&T,V=Kr(o).reveal;O?(fe.style.removeProperty("display"),fe.style.display=l?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Zt?Zt.element.style.display="none":ir&&(ir.style.display="none")):(l?l&&(V==="overlay"||V==="push")&&!D?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=l?"none":"":ir&&(ir.style.display=l?"none":""))},Ot=(l,m="user")=>{var D,V;if(!B()||O===l)return;let x=O;O=l,is();let C=(()=>{var Ne,Ue,ze,ut,ot,He,Pe,$e,Xe,xt;let q=(Ue=(Ne=o.launcher)==null?void 0:Ne.sidebarMode)!=null?Ue:!1,_=(ze=e.ownerDocument.defaultView)!=null?ze:window,ne=(ot=(ut=o.launcher)==null?void 0:ut.mobileFullscreen)!=null?ot:!0,re=(Pe=(He=o.launcher)==null?void 0:He.mobileBreakpoint)!=null?Pe:640,J=_.innerWidth<=re,be=nr(o)&&ne&&J,Fe=P()&&((xt=(Xe=($e=o.launcher)==null?void 0:$e.composerBar)==null?void 0:Xe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return q||ne&&J&&T||be||Fe})();if(O&&C){if(!ar){let q=e.getRootNode(),_=q instanceof ShadowRoot?q.host:e.closest(".persona-host");_&&(ar=op(_,(V=(D=o.launcher)==null?void 0:D.zIndex)!=null?V:wr))}sr||(sr=np(e.ownerDocument))}else O||(ar==null||ar(),ar=null,sr==null||sr(),sr=null);O&&(ls(),$p()||(Ft()==="follow"?yn(!0):Vp()));let R={open:O,source:m,timestamp:Date.now()};O&&!x?i.emit("widget:opened",R):!O&&x&&i.emit("widget:closed",R),i.emit("widget:state",{open:O,launcherEnabled:T,voiceActive:G.active,streaming:U.isStreaming()})},wl=l=>{pe(l?"stop":"send"),N&&(N.disabled=l),zn.buttons.forEach(m=>{m.disabled=l}),Ie.dataset.personaComposerStreaming=l?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Cl=()=>{G.active||xe&&xe.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Cl(),200)});let Qp=()=>{var x,C,R,D,V,q,_,ne,re,J,be;Co.textContent=(C=(x=o.copy)==null?void 0:x.welcomeTitle)!=null?C:"Hello \u{1F44B}",So.textContent=(D=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",xe.placeholder=(q=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?q:"How can I help...";let l=ve.querySelector("[data-persona-intro-card]");if(l){let Fe=((_=o.copy)==null?void 0:_.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((re=(ne=o.sendButton)==null?void 0:ne.useIcon)!=null&&re)&&!(U!=null&&U.isStreaming())&&(de.textContent=(be=(J=o.copy)==null?void 0:J.sendButtonLabel)!=null?be:"Send"),xe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',xe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{b(m=>({...m,sessionId:l}))}});let Gn=null,Py=()=>{Gn==null&&(Gn=setInterval(()=>{let l=Ye.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Gn),Gn=null;return}let m=Date.now();l.forEach(x=>{let C=Number(x.getAttribute("data-tool-elapsed"));C&&(x.textContent=ci(m-C))})},100))};U=new Na(o,{onMessagesChanged(l){var R,D;os(Ye,l,Z),Py(),ba(l),yn(!fo),Ay(l);let m=[...l].reverse().find(V=>V.role==="user"),x=[...l].reverse().find(V=>V.role==="assistant");l.length===0&&(rs(),fn=!0,mn=!1),!wa||jn?(wa=!0,Ca=(R=m==null?void 0:m.id)!=null?R:null,rt=(D=x==null?void 0:x.id)!=null?D:null):m&&m.id!==Ca?(Ca=m.id,Cy(m.id)):x&&x.id!==rt&&Sy(),x&&(rt=x.id);let C=G.lastUserMessageId;m&&m.id!==C&&(G.lastUserMessageId=m.id,i.emit("user:message",m)),G.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Hr(l),Sa()},onStatusChanged(l){var C;let m=(C=o.statusIndicator)!=null?C:{};jt(xr,(R=>{var D,V,q,_,ne,re;return R==="idle"?(D=m.idleText)!=null?D:or.idle:R==="connecting"?(V=m.connectingText)!=null?V:or.connecting:R==="connected"?(q=m.connectedText)!=null?q:or.connected:R==="error"?(_=m.errorText)!=null?_:or.error:R==="paused"?(ne=m.pausedText)!=null?ne:or.paused:R==="resuming"?(re=m.resumingText)!=null?re:or.resuming:or[R]})(l),m,l)},onStreamingChanged(l){fo=l,wl(l),U&&os(Ye,U.getMessages(),Z),l||yn(!0),qr(),nn(l?"Responding\u2026":"Response complete."),Sa()},onVoiceStatusChanged(l){var m,x;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((x=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:x.type)==="runtype")switch(l){case"listening":Xo(),Ma();break;case"processing":Xo(),By();break;case"speaking":Xo(),Dy();break;default:l==="idle"&&U.isBargeInActive()?(Xo(),Ma(),N==null||N.setAttribute("aria-label","End voice session")):(G.active=!1,Xo(),tt("system"),lt());break}},onArtifactsState(l){_r=l,Lo(),Hr()},onReconnect(l){var C;let{executionId:m,lastEventId:x}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:m,after:x}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:m,after:x,attempt:(C=l.attempt)!=null?C:1}):i.emit("stream:resumed",{executionId:m,after:x})}}),At.current=U,it.push(()=>U.cancel());let Sl=null;if(U.onReadAloudChange((l,m)=>{var R;ln=l,dn=m,cn();let x=l!=null?l:Sl;l&&(Sl=l);let C=x&&(R=U.getMessages().find(D=>D.id===x))!=null?R:null;i.emit("message:read-aloud",{messageId:x,message:C,state:m,timestamp:Date.now()}),m==="idle"&&(Sl=null)}),wa=!0,((pf=(cf=o.voiceRecognition)==null?void 0:cf.provider)==null?void 0:pf.type)==="runtype")try{U.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&U.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(j||o.onSSEEvent)&&U.setSSEEventCallback((l,m)=>{var x;(x=o.onSSEEvent)==null||x.call(o,l,m),ee==null||ee.processEvent(l,m),j==null||j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})});let Jp=()=>{o.resume&&typeof o.reconnectStream=="function"&&U.resumeFromHandle(o.resume)};u?u.then(l=>{var m,x,C;if(l){if(l.metadata&&(p=Ap(l.metadata),A.syncFromMetadata()),(m=l.messages)!=null&&m.length){jn=!0;try{U.hydrateMessages(l.messages)}finally{jn=!1}}(x=l.artifacts)!=null&&x.length&&U.hydrateArtifacts(l.artifacts,(C=l.selectedArtifactId)!=null?C:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Jp()):Jp();let Yp=()=>{var m,x,C;!P()||O||!((C=(x=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:x.expandOnSubmit)==null||C)||Ot(!0,"auto")},Zp=l=>{var R;if(l.preventDefault(),U.isStreaming()){U.cancel(),ee==null||ee.reset(),Ee==null||Ee.update();return}let m=xe.value.trim(),x=(R=St==null?void 0:St.hasAttachments())!=null?R:!1;if(!m&&!x)return;Yp();let C;x&&(C=[],C.push(...St.getContentParts()),m&&C.push(As(m))),xe.value="",xe.style.height="auto",js(),U.sendMessage(m,{contentParts:C}),x&&St.clearAttachments()},Ry=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},Al={...Oi},Ml=!1,js=()=>{Al={...Oi}},Iy=()=>U.getMessages().filter(l=>l.role==="user").map(l=>{var m;return(m=l.content)!=null?m:""}).filter(l=>l.length>0),Hy=l=>{if(!xe)return;Ml=!0,xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),Ml=!1;let m=xe.value.length;xe.setSelectionRange(m,m)},eu=()=>{Ml||js()},tu=l=>{if(xe){if(Ry()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let m=xe.selectionStart===0&&xe.selectionEnd===0,x=Nh({direction:l.key==="ArrowUp"?"up":"down",history:Iy(),currentValue:xe.value,atStart:m,state:Al});if(Al=x.state,x.handled){l.preventDefault(),x.value!==void 0&&Hy(x.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(U.isStreaming()){l.preventDefault();return}js(),l.preventDefault(),de.click()}}},ru=l=>{l.key!=="Escape"||l.isComposing||U.isStreaming()&&l.composedPath().includes(Ce)&&(U.cancel(),ee==null||ee.reset(),Ee==null||Ee.update(),js(),l.preventDefault(),l.stopImmediatePropagation())},ou=async l=>{var x;if(((x=o.attachments)==null?void 0:x.enabled)!==!0||!St)return;let m=F0(l.clipboardData);m.length!==0&&(l.preventDefault(),await St.handleFiles(m))},ro=null,Bo=!1,Aa=null,pt=null,nu=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Gs=(l="user")=>{var D,V,q,_,ne,re,J;if(Bo||U.isStreaming())return;let m=nu();if(!m)return;ro=new m;let C=(V=((D=o.voiceRecognition)!=null?D:{}).pauseDuration)!=null?V:2e3;ro.continuous=!0,ro.interimResults=!0,ro.lang="en-US";let R=xe.value;ro.onresult=be=>{let Fe="",Ne="";for(let ze=0;ze<be.results.length;ze++){let ut=be.results[ze],ot=ut[0].transcript;ut.isFinal?Fe+=ot+" ":Ne=ot}let Ue=R+Fe+Ne;xe.value=Ue,Aa&&clearTimeout(Aa),(Fe||Ne)&&(Aa=window.setTimeout(()=>{let ze=xe.value.trim();ze&&ro&&Bo&&(bn(),xe.value="",xe.style.height="auto",U.sendMessage(ze,{viaVoice:!0}))},C))},ro.onerror=be=>{be.error!=="no-speech"&&bn()},ro.onend=()=>{if(Bo){let be=xe.value.trim();be&&be!==R.trim()&&(xe.value="",xe.style.height="auto",U.sendMessage(be,{viaVoice:!0})),bn()}};try{if(ro.start(),Bo=!0,G.active=!0,l!=="system"&&(G.manuallyDeactivated=!1),tt(l),lt(),N){let be=(q=o.voiceRecognition)!=null?q:{};pt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((J=(re=be.iconSize)!=null?re:(ne=o.sendButton)==null?void 0:ne.size)!=null?J:"40")||24};let Fe=be.recordingBackgroundColor,Ne=be.recordingIconColor,Ue=be.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let ze=N.querySelector("svg");ze&&ze.setAttribute("stroke",Ne)}Ue&&(N.style.borderColor=Ue),N.setAttribute("aria-label","Stop voice recognition")}}catch{bn("system")}},bn=(l="user")=>{if(Bo){if(Bo=!1,Aa&&(clearTimeout(Aa),Aa=null),ro){try{ro.stop()}catch{}ro=null}if(G.active=!1,tt(l),lt(),N){if(N.classList.remove("persona-voice-recording"),pt){N.style.backgroundColor=pt.backgroundColor,N.style.color=pt.color,N.style.borderColor=pt.borderColor;let m=N.querySelector("svg");m&&m.setAttribute("stroke",pt.color||"currentColor"),pt=null}N.setAttribute("aria-label","Start voice recognition")}}},Wy=(l,m)=>{var ot,He,Pe,$e,Xe,xt,F,Be,Re;let x=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),C=((ot=l==null?void 0:l.provider)==null?void 0:ot.type)==="runtype",R=((He=l==null?void 0:l.provider)==null?void 0:He.type)==="custom";if(!(x||C||R))return null;let V=S("div","persona-send-button-wrapper"),q=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");q.type="button",q.setAttribute("aria-label","Start voice recognition");let _=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",ne=($e=m==null?void 0:m.size)!=null?$e:"40px",re=(Xe=l==null?void 0:l.iconSize)!=null?Xe:ne,J=parseFloat(re)||24,be=(xt=l==null?void 0:l.backgroundColor)!=null?xt:m==null?void 0:m.backgroundColor,Fe=(F=l==null?void 0:l.iconColor)!=null?F:m==null?void 0:m.textColor;q.style.width=re,q.style.height=re,q.style.minWidth=re,q.style.minHeight=re,q.style.fontSize="18px",q.style.lineHeight="1",Fe?q.style.color=Fe:q.style.color="var(--persona-text, #111827)";let Ue=he(_,J,Fe||"currentColor",1.5);Ue?q.appendChild(Ue):q.textContent="\u{1F3A4}",be?q.style.backgroundColor=be:q.style.backgroundColor="",l!=null&&l.borderWidth&&(q.style.borderWidth=l.borderWidth,q.style.borderStyle="solid"),l!=null&&l.borderColor&&(q.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(q.style.paddingLeft=l.paddingX,q.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(q.style.paddingTop=l.paddingY,q.style.paddingBottom=l.paddingY),V.appendChild(q);let ze=(Be=l==null?void 0:l.tooltipText)!=null?Be:"Start voice recognition";if(((Re=l==null?void 0:l.showTooltip)!=null?Re:!1)&&ze){let Je=S("div","persona-send-button-tooltip");Je.textContent=ze,V.appendChild(Je)}return{micButton:q,micButtonWrapper:V}},Tl=()=>{var m,x,C,R,D;if(!N||pt)return;let l=(m=o.voiceRecognition)!=null?m:{};pt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(x=l.iconName)!=null?x:"mic",iconSize:parseFloat((D=(R=l.iconSize)!=null?R:(C=o.sendButton)==null?void 0:C.size)!=null?D:"40")||24}},El=(l,m)=>{var D,V,q,_,ne;if(!N)return;let x=N.querySelector("svg");x&&x.remove();let C=(ne=pt==null?void 0:pt.iconSize)!=null?ne:parseFloat((_=(q=(D=o.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(V=o.sendButton)==null?void 0:V.size)!=null?_:"40")||24,R=he(l,C,m,1.5);R&&N.appendChild(R)},Ks=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ma=()=>{var R;if(!N)return;Tl();let l=(R=o.voiceRecognition)!=null?R:{},m=l.recordingBackgroundColor,x=l.recordingIconColor,C=l.recordingBorderColor;if(Ks(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=x!=null?x:"var(--persona-voice-recording-indicator, #ffffff)",x){let D=N.querySelector("svg");D&&D.setAttribute("stroke",x)}C&&(N.style.borderColor=C),N.setAttribute("aria-label","Stop voice recognition")},By=()=>{var q,_,ne,re,J,be,Fe,Ne;if(!N)return;Tl();let l=(q=o.voiceRecognition)!=null?q:{},m=U.getVoiceInterruptionMode(),x=(_=l.processingIconName)!=null?_:"loader",C=(re=(ne=l.processingIconColor)!=null?ne:pt==null?void 0:pt.color)!=null?re:"",R=(be=(J=l.processingBackgroundColor)!=null?J:pt==null?void 0:pt.backgroundColor)!=null?be:"",D=(Ne=(Fe=l.processingBorderColor)!=null?Fe:pt==null?void 0:pt.borderColor)!=null?Ne:"";Ks(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=R,N.style.borderColor=D;let V=C||"currentColor";N.style.color=V,El(x,V),N.setAttribute("aria-label","Processing voice input"),m==="none"&&(N.style.cursor="default")},Dy=()=>{var ne,re,J,be,Fe,Ne,Ue,ze,ut,ot,He,Pe;if(!N)return;Tl();let l=(ne=o.voiceRecognition)!=null?ne:{},m=U.getVoiceInterruptionMode(),x=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",C=(re=l.speakingIconName)!=null?re:x,R=(Ne=l.speakingIconColor)!=null?Ne:m==="barge-in"?(be=(J=l.recordingIconColor)!=null?J:pt==null?void 0:pt.color)!=null?be:"":(Fe=pt==null?void 0:pt.color)!=null?Fe:"",D=(ut=l.speakingBackgroundColor)!=null?ut:m==="barge-in"?(Ue=l.recordingBackgroundColor)!=null?Ue:"var(--persona-voice-recording-bg, #ef4444)":(ze=pt==null?void 0:pt.backgroundColor)!=null?ze:"",V=(Pe=l.speakingBorderColor)!=null?Pe:m==="barge-in"?(ot=l.recordingBorderColor)!=null?ot:"":(He=pt==null?void 0:pt.borderColor)!=null?He:"";Ks(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=D,N.style.borderColor=V;let q=R||"currentColor";N.style.color=q,El(C,q);let _=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",_),m==="none"&&(N.style.cursor="default"),m==="barge-in"&&N.classList.add("persona-voice-recording")},Xo=()=>{var l,m,x;N&&(Ks(),pt&&(N.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",N.style.color=(m=pt.color)!=null?m:"",N.style.borderColor=(x=pt.borderColor)!=null?x:"",El(pt.iconName,pt.color||"currentColor"),pt=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},Xs=()=>{var l,m;if(((m=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let x=U.getVoiceStatus(),C=U.getVoiceInterruptionMode();if(C==="none"&&(x==="processing"||x==="speaking"))return;if(C==="cancel"&&(x==="processing"||x==="speaking")){U.stopVoicePlayback();return}if(U.isBargeInActive()){U.stopVoicePlayback(),U.deactivateBargeIn().then(()=>{G.active=!1,G.manuallyDeactivated=!0,lt(),tt("user"),Xo()});return}U.toggleVoice().then(()=>{G.active=U.isVoiceActive(),G.manuallyDeactivated=!U.isVoiceActive(),lt(),tt("user"),U.isVoiceActive()?Ma():Xo()});return}if(Bo){let x=xe.value.trim();G.manuallyDeactivated=!0,lt(),bn("user"),x&&(xe.value="",xe.style.height="auto",U.sendMessage(x))}else G.manuallyDeactivated=!1,lt(),Gs("user")};To=Xs,N&&(N.addEventListener("click",Xs),it.push(()=>{var l,m;((m=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(U.isVoiceActive()&&U.toggleVoice(),Xo()):bn("system"),N&&N.removeEventListener("click",Xs)}));let Fy=i.on("assistant:complete",()=>{De&&(G.active||G.manuallyDeactivated||De==="assistant"&&!G.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!G.active&&!G.manuallyDeactivated&&(((m=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?U.toggleVoice().then(()=>{G.active=U.isVoiceActive(),tt("auto"),U.isVoiceActive()&&Ma()}):Gs("auto"))},600))});it.push(Fy);let Ny=i.on("action:resubmit",()=>{setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)});it.push(Ny);let au=()=>{Ot(!O,"user")},Zt=null,ir=null;if(T&&!P()){let{instance:l,element:m}=dp({config:o,plugins:n,onToggle:au});Zt=l,l||(ir=m)}Zt?e.appendChild(Zt.element):ir&&e.appendChild(ir),is(),ba(),Qp(),wl(U.isStreaming()),$p()||(Ft()==="follow"?yn(!0):Vp()),bl(),w&&(!T||P()?setTimeout(()=>Cl(),0):O&&setTimeout(()=>Cl(),200));let ls=()=>{var _,ne,re,J,be,Fe,Ne,Ue,ze,ut,ot,He,Pe,$e,Xe,xt,F,Be,Re,Je,Pt,Oe;if(P()){Qr(),is();return}let l=nr(o),m=(ne=(_=o.launcher)==null?void 0:_.sidebarMode)!=null?ne:!1,x=l||m||((J=(re=o.launcher)==null?void 0:re.fullHeight)!=null?J:!1),C=(be=e.ownerDocument.defaultView)!=null?be:window,R=(Ne=(Fe=o.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ne:!0,D=(ze=(Ue=o.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?ze:640,V=C.innerWidth<=D,q=R&&V&&T;try{if(q){un(),Hn(e,o);return}if(I&&(I=!1,un(),Hn(e,o)),!T&&!l){X.style.height="",X.style.width="";return}if(!m&&!l){let Gt=(ot=(ut=o==null?void 0:o.launcher)==null?void 0:ut.width)!=null?ot:o==null?void 0:o.launcherWidth,wt=Gt!=null?Gt:Gr;X.style.width=wt,X.style.maxWidth=wt}if(Vn(),!x){let Gt=C.innerHeight,wt=64,lr=(Pe=(He=o.launcher)==null?void 0:He.heightOffset)!=null?Pe:0,Br=Math.max(200,Gt-wt),Wt=Math.min(640,Br),mr=Math.max(200,Wt-lr);X.style.height=`${mr}px`}}finally{if(Qr(),is(),O&&T){let wt=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((xt=(Xe=o.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?xt:640),lr=(Be=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?Be:!1,Br=(Je=(Re=o.launcher)==null?void 0:Re.mobileFullscreen)!=null?Je:!0,Wt=nr(o)&&Br&&wt,mr=lr||Br&&wt&&T||Wt;if(mr&&!sr){let Vr=e.getRootNode(),Ge=Vr instanceof ShadowRoot?Vr.host:e.closest(".persona-host");Ge&&!ar&&(ar=op(Ge,(Oe=(Pt=o.launcher)==null?void 0:Pt.zIndex)!=null?Oe:wr)),sr=np(e.ownerDocument)}else mr||(ar==null||ar(),ar=null,sr==null||sr(),sr=null)}}};ls();let su=(uf=e.ownerDocument.defaultView)!=null?uf:window;if(su.addEventListener("resize",ls),it.push(()=>su.removeEventListener("resize",ls)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Qr()});l.observe(Ie),it.push(()=>l.disconnect())}Ar=ve.scrollTop;let iu=Oo(ve),Oy=()=>{let l=ve.getRootNode(),m=typeof l.getSelection=="function"?l.getSelection():null;return m!=null?m:ve.ownerDocument.getSelection()},kl=()=>zh(Oy(),ve),lu=()=>{let l=ve.scrollTop,m=Oo(ve),x=m<iu;if(iu=m,!tr()){Ar=l,qr();return}let{action:C,nextLastScrollTop:R}=Ui({following:yr.isFollowing(),currentScrollTop:l,lastScrollTop:Ar,nearBottom:Wn(ve,$),userScrollThreshold:L,isAutoScrolling:Mr||$n||x,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Ar=R,C==="resume"){kl()||xn();return}C==="pause"&&ts()};if(ve.addEventListener("scroll",lu,{passive:!0}),it.push(()=>ve.removeEventListener("scroll",lu)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{wy()});l.observe(Ye),l.observe(ve),it.push(()=>l.disconnect())}let du=()=>{tr()&&yr.isFollowing()&&kl()&&ts()},cu=ve.ownerDocument;cu.addEventListener("selectionchange",du),it.push(()=>{cu.removeEventListener("selectionchange",du)});let _y=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),pu=l=>{io()&&tr()&&yr.isFollowing()&&_y.has(l.key)&&ts()},uu=l=>{if(!io()||!tr()||!yr.isFollowing())return;let m=l.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&ts()};ve.addEventListener("keydown",pu),ve.addEventListener("focusin",uu),it.push(()=>{ve.removeEventListener("keydown",pu),ve.removeEventListener("focusin",uu)});let fu=l=>{if(!tr())return;let m=qi({following:yr.isFollowing(),deltaY:l.deltaY,nearBottom:Wn(ve,$),resumeWhenNearBottom:!0});m==="pause"?ts():m==="resume"&&!kl()&&xn()};ve.addEventListener("wheel",fu,{passive:!0}),it.push(()=>ve.removeEventListener("wheel",fu)),zt.addEventListener("click",()=>{rs(),ve.scrollTop=ve.scrollHeight,Ar=ve.scrollTop,xn(),yn(!0),qr()}),it.push(()=>zt.remove()),it.push(()=>{Tr(),rs()});let mu=()=>{Ve&&(Ro&&(Ve.removeEventListener("click",Ro),Ro=null),B()?(Ve.style.display="",Ro=()=>{Ot(!1,"user")},Ve.addEventListener("click",Ro)):Ve.style.display="none")};mu(),(()=>{let{clearChatButton:l}=je;l&&l.addEventListener("click",()=>{U.clearMessages(),Io.clear(),xn(),En(je.composerOverlay);try{localStorage.removeItem(Qa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qa}`)}catch(x){console.error("[AgentWidget] Failed to clear default localStorage:",x)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(x){console.error("[AgentWidget] Failed to clear custom localStorage:",x)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),d!=null&&d.clear)try{let x=d.clear();x instanceof Promise&&x.catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",C)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)}p={},A.syncFromMetadata(),j==null||j.clear(),ee==null||ee.reset(),Ee==null||Ee.update()})})(),Ct&&Ct.addEventListener("submit",Zp),xe==null||xe.addEventListener("keydown",tu),xe==null||xe.addEventListener("input",eu),xe==null||xe.addEventListener("paste",ou);let gu=(ff=e.ownerDocument)!=null?ff:document;gu.addEventListener("keydown",ru,!0);let hu="persona-attachment-drop-active",ds=0,Ll=()=>{ds=0,Ce.classList.remove(hu)},Ta=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&St!==null},xu=l=>{!gl(l.dataTransfer)||!Ta()||(ds++,ds===1&&Ce.classList.add(hu))},yu=l=>{!gl(l.dataTransfer)||!Ta()||(ds--,ds<=0&&Ll())},bu=l=>{!gl(l.dataTransfer)||!Ta()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},vu=l=>{var x;if(!gl(l.dataTransfer)||!Ta())return;l.preventDefault(),l.stopPropagation(),Ll();let m=Array.from((x=l.dataTransfer.files)!=null?x:[]);m.length!==0&&St.handleFiles(m)},vn=!0;Ce.addEventListener("dragenter",xu,vn),Ce.addEventListener("dragleave",yu,vn),e.addEventListener("dragover",bu,vn),e.addEventListener("drop",vu,vn);let Qs=e.ownerDocument,wu=l=>{Ta()&&l.preventDefault()},Cu=l=>{Ta()&&l.preventDefault()};Qs.addEventListener("dragover",wu),Qs.addEventListener("drop",Cu),it.push(()=>{Ct&&Ct.removeEventListener("submit",Zp),xe==null||xe.removeEventListener("keydown",tu),xe==null||xe.removeEventListener("input",eu),xe==null||xe.removeEventListener("paste",ou),gu.removeEventListener("keydown",ru,!0)}),it.push(()=>{Ce.removeEventListener("dragenter",xu,vn),Ce.removeEventListener("dragleave",yu,vn),e.removeEventListener("dragover",bu,vn),e.removeEventListener("drop",vu,vn),Qs.removeEventListener("dragover",wu),Qs.removeEventListener("drop",Cu),Ll()}),it.push(()=>{U.cancel()}),Zt?it.push(()=>{Zt==null||Zt.destroy()}):ir&&it.push(()=>{ir==null||ir.remove()});let rr={update(l){var $r,Do,ur,fr,no,Sn,vf,wf,Cf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf,If,Hf,Wf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,zf,$f,jf,Gf,Kf,Xf,Qf,Jf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,wm,Cm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Hm,Wm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,zm,$m,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,og,ng,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,vg,wg,Cg,Sg,Ag,Mg,Tg;let m=o.toolCall,x=o.messageActions,C=($r=o.layout)==null?void 0:$r.messages,R=o.colorScheme,D=o.loadingIndicator,V=o.iterationDisplay,q=(Do=o.features)==null?void 0:Do.showReasoning,_=(ur=o.features)==null?void 0:ur.showToolCalls,ne=(fr=o.features)==null?void 0:fr.toolCallDisplay,re=(no=o.features)==null?void 0:no.reasoningDisplay,J=(vf=(Sn=o.features)==null?void 0:Sn.streamAnimation)==null?void 0:vf.type;o={...o,...l},un(),Hn(e,o),sl(e,o),il(e,o),Lo(),o.colorScheme!==R&&es();let be=_s.getForInstance(o.plugins);n.length=0,n.push(...be),T=(Cf=(wf=o.launcher)==null?void 0:wf.enabled)!=null?Cf:!0,y=(Af=(Sf=o.launcher)==null?void 0:Sf.autoExpand)!=null?Af:!1,Le=(Tf=(Mf=o.features)==null?void 0:Mf.showReasoning)!=null?Tf:!0,We=(kf=(Ef=o.features)==null?void 0:Ef.showToolCalls)!=null?kf:!0,Me=(Pf=(Lf=o.features)==null?void 0:Lf.scrollToBottom)!=null?Pf:{};let Fe=Ft();oe=(If=(Rf=o.features)==null?void 0:Rf.scrollBehavior)!=null?If:{},Fe!==Ft()&&(rs(),xn()),an(),qr();let Ne=ie;if(ie=(Wf=(Hf=o.features)==null?void 0:Hf.showEventStreamToggle)!=null?Wf:!1,ie&&!Ne){if(j||(Te=new Ns(ge),j=new Fs(qe,Te),ee=ee!=null?ee:new Os,Te.open().then(()=>j==null?void 0:j.restore()).catch(()=>{}),U.setSSEEventCallback((Y,Mt)=>{var qt;(qt=o.onSSEEvent)==null||qt.call(o,Y,Mt),ee==null||ee.processEvent(Y,Mt),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(Mt)})})),!ht&&Ae){let Y=(Df=(Bf=o.features)==null?void 0:Bf.eventStream)==null?void 0:Df.classNames,Mt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");ht=S("button",Mt),ht.style.width="28px",ht.style.height="28px",ht.style.color=Pr.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let qt=he("activity","18px","currentColor",1.5);qt&&ht.appendChild(qt);let at=je.clearChatButtonWrapper,kt=je.closeButtonWrapper,dr=at||kt;dr&&dr.parentNode===Ae?Ae.insertBefore(ht,dr):Ae.appendChild(ht),ht.addEventListener("click",()=>{te?uo():Vo()})}}else!ie&&Ne&&(uo(),ht&&(ht.remove(),ht=null),j==null||j.clear(),Te==null||Te.destroy(),j=null,Te=null,ee==null||ee.reset(),ee=null);if(((Ff=o.launcher)==null?void 0:Ff.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((Nf=o.launcher)==null?void 0:Nf.enabled)===!1&&ir&&(ir.remove(),ir=null),((Of=o.launcher)==null?void 0:Of.enabled)!==!1&&!Zt&&!ir){let{instance:Y,element:Mt}=dp({config:o,plugins:n,onToggle:au});Zt=Y,Y||(ir=Mt),e.appendChild(Mt)}Zt&&Zt.update(o),ce&&((_f=o.launcher)==null?void 0:_f.title)!==void 0&&(ce.textContent=o.launcher.title),Se&&((Uf=o.launcher)==null?void 0:Uf.subtitle)!==void 0&&(Se.textContent=o.launcher.subtitle);let Ue=(qf=o.layout)==null?void 0:qf.header;if((Ue==null?void 0:Ue.layout)!==H&&Ae){let Y=Ue?Va(o,Ue,{showClose:B(),onClose:()=>Ot(!1,"user")}):tn({config:o,showClose:B(),onClose:()=>Ot(!1,"user")});ct.replaceHeader(Y),Ae=ct.header.element,W=ct.header.iconHolder,ce=ct.header.headerTitle,Se=ct.header.headerSubtitle,Ve=ct.header.closeButton,H=Ue==null?void 0:Ue.layout}else if(Ue&&(W&&(W.style.display=Ue.showIcon===!1?"none":""),ce&&(ce.style.display=Ue.showTitle===!1?"none":""),Se&&(Se.style.display=Ue.showSubtitle===!1?"none":""),Ve&&(Ve.style.display=Ue.showCloseButton===!1?"none":""),je.clearChatButtonWrapper)){let Y=Ue.showClearChat;if(Y!==void 0){je.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:Mt}=je;Mt&&!Mt.classList.contains("persona-absolute")&&(Y?Mt.classList.remove("persona-ml-auto"):Mt.classList.add("persona-ml-auto"))}}let ut=((Vf=o.layout)==null?void 0:Vf.showHeader)!==!1;Ae&&(Ae.style.display=ut?"":"none");let ot=((zf=o.layout)==null?void 0:zf.showFooter)!==!1;Ie&&(Ie.style.display=ot?"":"none"),Qr(),qr(),T!==M?T?Ot(y,"auto"):(O=!0,is()):y!==v&&Ot(y,"auto"),v=y,M=T,ls(),mu();let $e=JSON.stringify(l.toolCall)!==JSON.stringify(m),Xe=JSON.stringify(o.messageActions)!==JSON.stringify(x),xt=JSON.stringify(($f=o.layout)==null?void 0:$f.messages)!==JSON.stringify(C),F=((jf=o.loadingIndicator)==null?void 0:jf.render)!==(D==null?void 0:D.render)||((Gf=o.loadingIndicator)==null?void 0:Gf.renderIdle)!==(D==null?void 0:D.renderIdle)||((Kf=o.loadingIndicator)==null?void 0:Kf.showBubble)!==(D==null?void 0:D.showBubble),Be=o.iterationDisplay!==V,Re=((Qf=(Xf=o.features)==null?void 0:Xf.showReasoning)!=null?Qf:!0)!==(q!=null?q:!0)||((Yf=(Jf=o.features)==null?void 0:Jf.showToolCalls)!=null?Yf:!0)!==(_!=null?_:!0)||JSON.stringify((Zf=o.features)==null?void 0:Zf.toolCallDisplay)!==JSON.stringify(ne)||JSON.stringify((em=o.features)==null?void 0:em.reasoningDisplay)!==JSON.stringify(re);($e||Xe||xt||F||Be||Re)&&U&&(va++,os(Ye,U.getMessages(),Z));let Pt=(rm=(tm=o.features)==null?void 0:tm.streamAnimation)==null?void 0:rm.type;if(Pt!==J&&Pt&&Pt!=="none"){let Y=qa(Pt,(nm=(om=o.features)==null?void 0:om.streamAnimation)==null?void 0:nm.plugins);Y&&ji(Y,e)}let Oe=(am=o.launcher)!=null?am:{},Gt=(sm=Oe.headerIconHidden)!=null?sm:!1,wt=(lm=(im=o.layout)==null?void 0:im.header)==null?void 0:lm.showIcon,lr=Gt||wt===!1,Br=Oe.headerIconName,Wt=(dm=Oe.headerIconSize)!=null?dm:"48px";if(W){let Y=Ce.querySelector(".persona-border-b-persona-divider"),Mt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(lr)W.style.display="none",Y&&Mt&&!Y.contains(Mt)&&Y.insertBefore(Mt,Y.firstChild);else{if(W.style.display="",W.style.height=Wt,W.style.width=Wt,Y&&Mt&&(Y.contains(W)?W.nextSibling!==Mt&&(W.remove(),Y.insertBefore(W,Mt)):Y.insertBefore(W,Mt)),Br){let at=parseFloat(Wt)||24,kt=he(Br,at*.6,"currentColor",1);kt?W.replaceChildren(kt):W.textContent=(cm=Oe.agentIconText)!=null?cm:"\u{1F4AC}"}else if(Oe.iconUrl){let at=W.querySelector("img");if(at)at.src=Oe.iconUrl,at.style.height=Wt,at.style.width=Wt;else{let kt=document.createElement("img");kt.src=Oe.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Wt,kt.style.width=Wt,W.replaceChildren(kt)}}else{let at=W.querySelector("svg"),kt=W.querySelector("img");(at||kt)&&W.replaceChildren(),W.textContent=(pm=Oe.agentIconText)!=null?pm:"\u{1F4AC}"}let qt=W.querySelector("img");qt&&(qt.style.height=Wt,qt.style.width=Wt)}}let mr=(fm=(um=o.layout)==null?void 0:um.header)==null?void 0:fm.showTitle,Vr=(gm=(mm=o.layout)==null?void 0:mm.header)==null?void 0:gm.showSubtitle;if(ce&&(ce.style.display=mr===!1?"none":""),Se&&(Se.style.display=Vr===!1?"none":""),Ve){((xm=(hm=o.layout)==null?void 0:hm.header)==null?void 0:xm.showCloseButton)===!1?Ve.style.display="none":Ve.style.display="";let Mt=(ym=Oe.closeButtonSize)!=null?ym:"32px",qt=(bm=Oe.closeButtonPlacement)!=null?bm:"inline";Ve.style.height=Mt,Ve.style.width=Mt;let{closeButtonWrapper:at}=je,kt=qt==="top-right",dr=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==dr)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ce.style.position="relative",Ce.appendChild(at);else{let dt=(wm=(vm=Oe.clearChat)==null?void 0:vm.placement)!=null?wm:"inline",cr=(Sm=(Cm=Oe.clearChat)==null?void 0:Cm.enabled)!=null?Sm:!0;at.className=cr&&dt==="inline"?"":"persona-ml-auto";let Dr=Ce.querySelector(".persona-border-b-persona-divider");Dr&&Dr.appendChild(at)}if(Ve.style.color=Oe.closeButtonColor||Pr.actionIconColor,Oe.closeButtonBackgroundColor?(Ve.style.backgroundColor=Oe.closeButtonBackgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),Oe.closeButtonBorderWidth||Oe.closeButtonBorderColor){let dt=Oe.closeButtonBorderWidth||"0px",cr=Oe.closeButtonBorderColor||"transparent";Ve.style.border=`${dt} solid ${cr}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");Oe.closeButtonBorderRadius?(Ve.style.borderRadius=Oe.closeButtonBorderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),Oe.closeButtonPaddingX?(Ve.style.paddingLeft=Oe.closeButtonPaddingX,Ve.style.paddingRight=Oe.closeButtonPaddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Oe.closeButtonPaddingY?(Ve.style.paddingTop=Oe.closeButtonPaddingY,Ve.style.paddingBottom=Oe.closeButtonPaddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let vr=(Am=Oe.closeButtonIconName)!=null?Am:"x",xo=(Mm=Oe.closeButtonIconText)!=null?Mm:"\xD7";Ve.innerHTML="";let kr=he(vr,"28px","currentColor",1);kr?Ve.appendChild(kr):Ve.textContent=xo;let Yt=(Tm=Oe.closeButtonTooltipText)!=null?Tm:"Close chat",jr=(Em=Oe.closeButtonShowTooltip)!=null?Em:!0;if(Ve.setAttribute("aria-label",Yt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),jr&&Yt)){let dt=null,cr=()=>{if(dt||!Ve)return;let ea=Ve.ownerDocument,cs=ea.body;if(!cs)return;dt=No(ea,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let ps=No(ea,"div");ps.className="persona-clear-chat-tooltip-arrow",dt.appendChild(ps);let ta=Ve.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Bn),dt.style.left=`${ta.left+ta.width/2}px`,dt.style.top=`${ta.top-8}px`,dt.style.transform="translate(-50%, -100%)",cs.appendChild(dt)},Dr=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",cr),at.addEventListener("mouseleave",Dr),Ve.addEventListener("focus",cr),Ve.addEventListener("blur",Dr),at._cleanupTooltip=()=>{Dr(),at&&(at.removeEventListener("mouseenter",cr),at.removeEventListener("mouseleave",Dr)),Ve&&(Ve.removeEventListener("focus",cr),Ve.removeEventListener("blur",Dr))}}}let{clearChatButton:Ge,clearChatButtonWrapper:Rt}=je;if(Ge){let Y=(km=Oe.clearChat)!=null?km:{},Mt=(Lm=Y.enabled)!=null?Lm:!0,qt=(Rm=(Pm=o.layout)==null?void 0:Pm.header)==null?void 0:Rm.showClearChat,at=qt!==void 0?qt:Mt,kt=(Im=Y.placement)!=null?Im:"inline";if(Rt){Rt.style.display=at?"":"none";let{closeButtonWrapper:dr}=je;!P()&&dr&&!dr.classList.contains("persona-absolute")&&(at?dr.classList.remove("persona-ml-auto"):dr.classList.add("persona-ml-auto"));let vr=kt==="top-right",xo=Rt.classList.contains("persona-absolute");if(!P()&&vr!==xo&&at){if(Rt.remove(),vr)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",Ce.style.position="relative",Ce.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let Yt=Ce.querySelector(".persona-border-b-persona-divider"),jr=je.closeButtonWrapper;Yt&&jr&&jr.parentElement===Yt?Yt.insertBefore(Rt,jr):Yt&&Yt.appendChild(Rt)}let kr=je.closeButtonWrapper;kr&&!kr.classList.contains("persona-absolute")&&(vr?kr.classList.add("persona-ml-auto"):kr.classList.remove("persona-ml-auto"))}}if(at){if(!P()){let dt=(Hm=Y.size)!=null?Hm:"32px";Ge.style.height=dt,Ge.style.width=dt}let dr=(Wm=Y.iconName)!=null?Wm:"refresh-cw",vr=(Bm=Y.iconColor)!=null?Bm:"";Ge.style.color=vr||Pr.actionIconColor,Ge.innerHTML="";let xo=P()?"14px":"20px",kr=he(dr,xo,"currentColor",2);if(kr&&Ge.appendChild(kr),Y.backgroundColor?(Ge.style.backgroundColor=Y.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let dt=Y.borderWidth||"0px",cr=Y.borderColor||"transparent";Ge.style.border=`${dt} solid ${cr}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");Y.borderRadius?(Ge.style.borderRadius=Y.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),Y.paddingX?(Ge.style.paddingLeft=Y.paddingX,Ge.style.paddingRight=Y.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),Y.paddingY?(Ge.style.paddingTop=Y.paddingY,Ge.style.paddingBottom=Y.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Yt=(Dm=Y.tooltipText)!=null?Dm:"Clear chat",jr=(Fm=Y.showTooltip)!=null?Fm:!0;if(Ge.setAttribute("aria-label",Yt),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),jr&&Yt)){let dt=null,cr=()=>{if(dt||!Ge)return;let ea=Ge.ownerDocument,cs=ea.body;if(!cs)return;dt=No(ea,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let ps=No(ea,"div");ps.className="persona-clear-chat-tooltip-arrow",dt.appendChild(ps);let ta=Ge.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Bn),dt.style.left=`${ta.left+ta.width/2}px`,dt.style.top=`${ta.top-8}px`,dt.style.transform="translate(-50%, -100%)",cs.appendChild(dt)},Dr=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};Rt.addEventListener("mouseenter",cr),Rt.addEventListener("mouseleave",Dr),Ge.addEventListener("focus",cr),Ge.addEventListener("blur",Dr),Rt._cleanupTooltip=()=>{Dr(),Rt&&(Rt.removeEventListener("mouseenter",cr),Rt.removeEventListener("mouseleave",Dr)),Ge&&(Ge.removeEventListener("focus",cr),Ge.removeEventListener("blur",Dr))}}}}let zr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Us],Kn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ha.message,ha.messageAndClick];A=qs({parsers:zr,handlers:Kn,getSessionMetadata:h,updateSessionMetadata:b,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),Z=Bx(o,A,ue),U.updateConfig(o),os(Ye,U.getMessages(),Z),ba(),Qp(),wl(U.isStreaming());let Xn=((Nm=o.voiceRecognition)==null?void 0:Nm.enabled)===!0,Qn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Jn=((_m=(Om=o.voiceRecognition)==null?void 0:Om.provider)==null?void 0:_m.type)==="runtype";if(Xn&&(Qn||Jn))if(!N||!ye){let Y=Wy(o.voiceRecognition,o.sendButton);Y&&(N=Y.micButton,ye=Y.micButtonWrapper,gt.insertBefore(ye,Cr),N.addEventListener("click",Xs),N.disabled=U.isStreaming())}else{let Y=(Um=o.voiceRecognition)!=null?Um:{},Mt=(qm=o.sendButton)!=null?qm:{},qt=(Vm=Y.iconName)!=null?Vm:"mic",at=(zm=Mt.size)!=null?zm:"40px",kt=($m=Y.iconSize)!=null?$m:at,dr=parseFloat(kt)||24;N.style.width=kt,N.style.height=kt,N.style.minWidth=kt,N.style.minHeight=kt;let vr=(Gm=(jm=Y.iconColor)!=null?jm:Mt.textColor)!=null?Gm:"currentColor";N.innerHTML="";let xo=he(qt,dr,vr,2);xo?N.appendChild(xo):N.textContent="\u{1F3A4}";let kr=(Km=Y.backgroundColor)!=null?Km:Mt.backgroundColor;kr?N.style.backgroundColor=kr:N.style.backgroundColor="",vr?N.style.color=vr:N.style.color="var(--persona-text, #111827)",Y.borderWidth?(N.style.borderWidth=Y.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),Y.borderColor?N.style.borderColor=Y.borderColor:N.style.borderColor="",Y.paddingX?(N.style.paddingLeft=Y.paddingX,N.style.paddingRight=Y.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),Y.paddingY?(N.style.paddingTop=Y.paddingY,N.style.paddingBottom=Y.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let Yt=ye==null?void 0:ye.querySelector(".persona-send-button-tooltip"),jr=(Xm=Y.tooltipText)!=null?Xm:"Start voice recognition";if(((Qm=Y.showTooltip)!=null?Qm:!1)&&jr)if(Yt)Yt.textContent=jr,Yt.style.display="";else{let cr=document.createElement("div");cr.className="persona-send-button-tooltip",cr.textContent=jr,ye==null||ye.insertBefore(cr,N)}else Yt&&(Yt.style.display="none");ye.style.display="",N.disabled=U.isStreaming()}else N&&ye&&(ye.style.display="none",((Ym=(Jm=o.voiceRecognition)==null?void 0:Jm.provider)==null?void 0:Ym.type)==="runtype"?U.isVoiceActive()&&U.toggleVoice():Bo&&bn());if(((Zm=o.attachments)==null?void 0:Zm.enabled)===!0)if(!mt||!ae){let Y=(eg=o.attachments)!=null?eg:{},qt=(rg=((tg=o.sendButton)!=null?tg:{}).size)!=null?rg:"40px";Lt||(Lt=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,xe)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((og=Y.allowedTypes)!=null?og:en).join(","),Ke.multiple=((ng=Y.maxFiles)!=null?ng:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Ct.insertBefore(Ke,xe)),mt=S("div","persona-send-button-wrapper"),ae=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ae.type="button",ae.setAttribute("aria-label",(ag=Y.buttonTooltipText)!=null?ag:"Attach file");let at=(sg=Y.buttonIconName)!=null?sg:"paperclip",kt=qt,dr=parseFloat(kt)||40,vr=Math.round(dr*.6);ae.style.width=kt,ae.style.height=kt,ae.style.minWidth=kt,ae.style.minHeight=kt,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.style.backgroundColor="transparent",ae.style.color="var(--persona-primary, #111827)",ae.style.border="none",ae.style.borderRadius="6px",ae.style.transition="background-color 0.15s ease",ae.addEventListener("mouseenter",()=>{ae.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ae.addEventListener("mouseleave",()=>{ae.style.backgroundColor="transparent"});let xo=he(at,vr,"currentColor",1.5);xo?ae.appendChild(xo):ae.textContent="\u{1F4CE}",ae.addEventListener("click",jr=>{jr.preventDefault(),Ke==null||Ke.click()}),mt.appendChild(ae);let kr=(ig=Y.buttonTooltipText)!=null?ig:"Attach file",Yt=S("div","persona-send-button-tooltip");Yt.textContent=kr,mt.appendChild(Yt),Qe.append(mt),!St&&Ke&&Lt&&(St=da.fromConfig(Y),St.setPreviewsContainer(Lt),Ke.addEventListener("change",async()=>{St&&(Ke!=null&&Ke.files)&&(await St.handleFileSelect(Ke.files),Ke.value="")})),Ce.querySelector(".persona-attachment-drop-overlay")||Ce.appendChild(Dx(Y.dropOverlay))}else{mt.style.display="";let Y=(lg=o.attachments)!=null?lg:{};Ke&&(Ke.accept=((dg=Y.allowedTypes)!=null?dg:en).join(","),Ke.multiple=((cg=Y.maxFiles)!=null?cg:4)>1),St&&St.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else mt&&(mt.style.display="none"),St&&St.clearAttachments(),(pg=Ce.querySelector(".persona-attachment-drop-overlay"))==null||pg.remove();let Xt=(ug=o.sendButton)!=null?ug:{},Yn=(fg=Xt.useIcon)!=null?fg:!1,wn=(mg=Xt.iconText)!=null?mg:"\u2191",Cn=Xt.iconName,Qo=(gg=Xt.tooltipText)!=null?gg:"Send message",Zn=(hg=Xt.showTooltip)!=null?hg:!1,Ze=(xg=Xt.size)!=null?xg:"40px",Dt=Xt.backgroundColor,Bt=Xt.textColor;if(Yn){if(de.style.width=Ze,de.style.height=Ze,de.style.minWidth=Ze,de.style.minHeight=Ze,de.style.fontSize="18px",de.style.lineHeight="1",de.innerHTML="",Bt?de.style.color=Bt:de.style.color="var(--persona-button-primary-fg, #ffffff)",Cn){let Y=parseFloat(Ze)||24,Mt=(Bt==null?void 0:Bt.trim())||"currentColor",qt=he(Cn,Y,Mt,2);qt?de.appendChild(qt):de.textContent=wn}else de.textContent=wn;de.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Dt?(de.style.backgroundColor=Dt,de.classList.remove("persona-bg-persona-primary")):(de.style.backgroundColor="",de.classList.add("persona-bg-persona-primary"))}else de.textContent=(bg=(yg=o.copy)==null?void 0:yg.sendButtonLabel)!=null?bg:"Send",de.style.width="",de.style.height="",de.style.minWidth="",de.style.minHeight="",de.style.fontSize="",de.style.lineHeight="",de.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Dt?(de.style.backgroundColor=Dt,de.classList.remove("persona-bg-persona-accent")):de.classList.add("persona-bg-persona-accent"),Bt?de.style.color=Bt:de.classList.add("persona-text-white");Xt.borderWidth?(de.style.borderWidth=Xt.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Xt.borderColor?de.style.borderColor=Xt.borderColor:de.style.borderColor="",Xt.paddingX?(de.style.paddingLeft=Xt.paddingX,de.style.paddingRight=Xt.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Xt.paddingY?(de.style.paddingTop=Xt.paddingY,de.style.paddingBottom=Xt.paddingY):(de.style.paddingTop="",de.style.paddingBottom="");let $t=Cr==null?void 0:Cr.querySelector(".persona-send-button-tooltip");if(Zn&&Qo)if($t)$t.textContent=Qo,$t.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=Qo,Cr==null||Cr.insertBefore(Y,de)}else $t&&($t.style.display="none");let _t=(Ag=(vg=o.layout)==null?void 0:vg.contentMaxWidth)!=null?Ag:P()?(Sg=(Cg=(wg=o.launcher)==null?void 0:wg.composerBar)==null?void 0:Cg.contentMaxWidth)!=null?Sg:"720px":void 0;_t?(Ye.style.maxWidth=_t,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%",Ct&&(Ct.style.maxWidth=_t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Vt&&(Vt.style.maxWidth=_t,Vt.style.marginLeft="auto",Vt.style.marginRight="auto")):(Ye.style.maxWidth="",Ye.style.marginLeft="",Ye.style.marginRight="",Ye.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),Vt&&(Vt.style.maxWidth="",Vt.style.marginLeft="",Vt.style.marginRight=""));let ft=(Mg=o.statusIndicator)!=null?Mg:{},Ut=(Tg=ft.visible)!=null?Tg:!0;if(xr.style.display=Ut?"":"none",U){let Y=U.getStatus();jt(xr,(qt=>{var at,kt,dr,vr;return qt==="idle"?(at=ft.idleText)!=null?at:or.idle:qt==="connecting"?(kt=ft.connectingText)!=null?kt:or.connecting:qt==="connected"?(dr=ft.connectedText)!=null?dr:or.connected:qt==="error"?(vr=ft.errorText)!=null?vr:or.error:or[qt]})(Y),ft,Y)}xr.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gr=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";xr.classList.add(gr)},open(){B()&&Ot(!0,"api")},close(){B()&&Ot(!1,"api")},toggle(){B()&&Ot(!O,"api")},reconnect(){U.reconnectNow()},clearChat(){Sr=!1,U.clearMessages(),Io.clear(),xn();try{localStorage.removeItem(Qa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qa}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),d!=null&&d.clear)try{let m=d.clear();m instanceof Promise&&m.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},A.syncFromMetadata(),j==null||j.clear(),ee==null||ee.reset(),Ee==null||Ee.update()},setMessage(l){return!xe||U.isStreaming()?!1:(!O&&B()&&Ot(!0,"system"),xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(U.isStreaming())return!1;let m=(l==null?void 0:l.trim())||xe.value.trim();return m?(!O&&B()&&Ot(!0,"system"),xe.value="",xe.style.height="auto",U.sendMessage(m),!0):!1},startVoiceRecognition(){var m,x;return U.isStreaming()?!1:((x=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:x.type)==="runtype"?(U.isVoiceActive()||(!O&&B()&&Ot(!0,"system"),G.manuallyDeactivated=!1,lt(),U.toggleVoice().then(()=>{G.active=U.isVoiceActive(),tt("user"),U.isVoiceActive()&&Ma()})),!0):Bo?!0:nu()?(!O&&B()&&Ot(!0,"system"),G.manuallyDeactivated=!1,lt(),Gs("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?U.isVoiceActive()?(U.toggleVoice().then(()=>{G.active=!1,G.manuallyDeactivated=!0,lt(),tt("user"),Xo()}),!0):!1:Bo?(G.manuallyDeactivated=!0,lt(),bn("user"),!0):!1},injectMessage(l){return!O&&B()&&Ot(!0,"system"),U.injectMessage(l)},injectAssistantMessage(l){!O&&B()&&Ot(!0,"system");let m=U.injectAssistantMessage(l);return Q&&(Q=!1,me&&(clearTimeout(me),me=null),setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)),m},injectUserMessage(l){return!O&&B()&&Ot(!0,"system"),U.injectUserMessage(l)},injectSystemMessage(l){return!O&&B()&&Ot(!0,"system"),U.injectSystemMessage(l)},injectMessageBatch(l){return!O&&B()&&Ot(!0,"system"),U.injectMessageBatch(l)},injectComponentDirective(l){return!O&&B()&&Ot(!0,"system"),U.injectComponentDirective(l)},injectTestMessage(l){!O&&B()&&Ot(!0,"system"),U.injectTestEvent(l)},async connectStream(l,m){return U.connectStream(l,m)},__pushEventStreamEvent(l){j&&(ee==null||ee.processEvent(l.type,l.payload),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ie||!j||Vo()},hideEventStream(){te&&uo()},isEventStreamVisible(){return te},showArtifacts(){so(o)&&(Sr=!1,Lo(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){so(o)&&(Sr=!0,Lo())},upsertArtifact(l){return so(o)?(Sr=!1,U.upsertArtifact(l)):null},selectArtifact(l){so(o)&&U.selectArtifact(l)},clearArtifacts(){so(o)&&U.clearArtifacts()},getArtifacts(){var l;return(l=U==null?void 0:U.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=U==null?void 0:U.getSelectedArtifactId())!=null?l:null},focusInput(){return T&&!O&&!P()||!xe?!1:(xe.focus(),!0)},async resolveApproval(l,m,x){let R=U.getMessages().find(D=>{var V;return D.variant==="approval"&&((V=D.approval)==null?void 0:V.id)===l});if(!(R!=null&&R.approval))throw new Error(`Approval not found: ${l}`);if(R.approval.toolType==="webmcp"){U.resolveWebMcpApproval(R.id,m);return}return U.resolveApproval(R.approval,m,x)},getMessages(){return U.getMessages()},getStatus(){return U.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){b(l)},on(l,m){return i.on(l,m)},off(l,m){i.off(l,m)},isOpen(){return B()&&O},isVoiceActive(){return G.active},toggleReadAloud(l){U.toggleReadAloud(l)},stopReadAloud(){U.stopSpeaking()},getReadAloudState(l){return U.getReadAloudState(l)},onReadAloudChange(l){return U.onReadAloudChange(l)},getState(){return{open:B()&&O,launcherEnabled:T,voiceActive:G.active,streaming:U.isStreaming()}},showCSATFeedback(l){!O&&B()&&Ot(!0,"system");let m=Ye.querySelector(".persona-feedback-container");m&&m.remove();let x=fl({onSubmit:async(C,R)=>{var D;U.isClientTokenMode()&&await U.submitCSATFeedback(C,R),(D=l==null?void 0:l.onSubmit)==null||D.call(l,C,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!O&&B()&&Ot(!0,"system");let m=Ye.querySelector(".persona-feedback-container");m&&m.remove();let x=ml({onSubmit:async(C,R)=>{var D;U.isClientTokenMode()&&await U.submitNPSFeedback(C,R),(D=l==null?void 0:l.onSubmit)==null||D.call(l,C,R)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return U.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return U.submitNPSFeedback(l,m)},destroy(){Gn!=null&&(clearInterval(Gn),Gn=null),it.forEach(l=>l()),fe.remove(),st==null||st.remove(),Zt==null||Zt.destroy(),ir==null||ir.remove(),Ro&&Ve.removeEventListener("click",Ro)}};if((((mf=r==null?void 0:r.debugTools)!=null?mf:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:rr,getMessages:rr.getMessages,getStatus:rr.getStatus,getMetadata:rr.getPersistentMetadata,updateMetadata:rr.updatePersistentMetadata,clearHistory:()=>rr.clearChat(),setVoiceActive:x=>x?rr.startVoiceRecognition():rr.stopVoiceRecognition()};window.AgentWidgetBrowser=m,it.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=q=>{let _=q.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&rr.focusInput()};if(window.addEventListener("persona:focusInput",m),it.push(()=>{window.removeEventListener("persona:focusInput",m)}),ie){let q=ne=>{let re=ne.detail;(!(re!=null&&re.instanceId)||re.instanceId===l)&&rr.showEventStream()},_=ne=>{let re=ne.detail;(!(re!=null&&re.instanceId)||re.instanceId===l)&&rr.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",_),it.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",_)})}let x=q=>{let _=q.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&rr.showArtifacts()},C=q=>{let _=q.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&rr.hideArtifacts()},R=q=>{let _=q.detail;_!=null&&_.instanceId&&_.instanceId!==l||_!=null&&_.artifact&&rr.upsertArtifact(_.artifact)},D=q=>{let _=q.detail;_!=null&&_.instanceId&&_.instanceId!==l||typeof(_==null?void 0:_.id)=="string"&&rr.selectArtifact(_.id)},V=q=>{let _=q.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&rr.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",V),it.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",V)})}let oo=N0(o.persistState);if(oo&&B()){let l=O0(oo.storage),m=`${oo.keyPrefix}widget-open`,x=`${oo.keyPrefix}widget-voice`,C=`${oo.keyPrefix}widget-voice-mode`;if(l){let R=((gf=oo.persist)==null?void 0:gf.openState)&&l.getItem(m)==="true",D=((hf=oo.persist)==null?void 0:hf.voiceState)&&l.getItem(x)==="true",V=((xf=oo.persist)==null?void 0:xf.voiceState)&&l.getItem(C)==="true";if(R&&setTimeout(()=>{rr.open(),setTimeout(()=>{var q;if(D||V)rr.startVoiceRecognition();else if((q=oo.persist)!=null&&q.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(yf=oo.persist)!=null&&yf.openState&&(i.on("widget:opened",()=>{l.setItem(m,"true")}),i.on("widget:closed",()=>{l.setItem(m,"false")})),(bf=oo.persist)!=null&&bf.voiceState&&(i.on("voice:state",q=>{l.setItem(x,q.active?"true":"false")}),i.on("user:message",q=>{l.setItem(C,q.viaVoice?"true":"false")})),oo.clearOnChatClear){let q=()=>{l.removeItem(m),l.removeItem(x),l.removeItem(C)},_=()=>q();window.addEventListener("persona:clear-chat",_),it.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return g&&B()&&setTimeout(()=>{rr.open()},0),Sa(),$s||Ys().then(()=>{U&&(va++,Io.clear(),os(Ye,U.getMessages(),Z))}).catch(()=>{}),rr};var _0=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},U0=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},q0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},V0=(e,t)=>{let r=e.parentElement;if(!r)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!n||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Fx=(e,t)=>{var o,n;let r=(n=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?n:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},kp=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=""},Nx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",kp(e)},Mp=e=>{e.style.transition=""},Tp=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="",e.style.marginLeft=""},Ep=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},xl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},z0=(e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))},$0=(e,t,r,o,n,a)=>{let s=a?t:e;n==="left"?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)},Ox=(e,t,r,o,n,a,s)=>{var h,b,k,E,A,T;let i=Kr(a),c=i.reveal==="push";z0(e,t,r,o,c),$0(e,t,r,o,i.side,c),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",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let d=e.ownerDocument.defaultView,p=(b=(h=a==null?void 0:a.launcher)==null?void 0:h.mobileFullscreen)!=null?b:!0,u=(E=(k=a==null?void 0:a.launcher)==null?void 0:k.mobileBreakpoint)!=null?E:640,g=d!=null?d.innerWidth<=u:!1;if(p&&g&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Tp(t),Mp(o),Nx(o),Ep(r),xl(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((T=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?T:wr),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Nx(o),U0(o,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Tp(t),Mp(o),Ep(r),xl(n,o);let y=i.animate?"transform 180ms ease":"none",w=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=s?"translateX(0)":w;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=y,o.style.transform=v,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Mp(o),kp(o),xl(n,o);let y=_0(i.width,e.clientWidth),w=Math.max(0,e.clientWidth),v=i.animate?"margin-left 180ms ease":"none",M=i.side==="right"?s?-y:0:s?0:-y;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${w+y}px`,t.style.transition=v,t.style.marginLeft=`${M}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${w}px`,r.style.maxWidth=`${w}px`,r.style.minWidth=`${w}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Tp(t),kp(o),Ep(r),xl(n,o);let y=i.reveal==="emerge";y?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let w=s?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",M=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${w}`,o.style.width=w,o.style.maxWidth=w,o.style.minWidth=w,o.style.minHeight="0",q0(o,i.maxHeight),o.style.overflow=y||M?"hidden":"visible",o.style.transition=v,y&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},j0=(e,t)=>{let r=e.ownerDocument.createElement("div");return Fx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){Fx(r,o)},destroy(){r.remove()}}},G0=(e,t)=>{var T,y,w,v;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),d=r.createElement("aside"),p=r.createElement("div"),u=(y=(T=t==null?void 0:t.launcher)==null?void 0:T.enabled)==null||y?(v=(w=t==null?void 0:t.launcher)==null?void 0:w.autoExpand)!=null?v:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",d.appendChild(p),o.insertBefore(s,e),c.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},h=()=>{f(),Kr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Ox(s,i,c,d,p,t,u)}),g.observe(s))},b=!1,k=()=>{Ox(s,i,c,d,p,t,u),h(),u&&!b&&s.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,V0(s,Kr(t)))},E=s.ownerDocument.defaultView,A=()=>{k()};return E==null||E.addEventListener("resize",A),Kr(t).reveal==="push"?(i.appendChild(c),i.appendChild(d),s.appendChild(i)):(s.appendChild(c),s.appendChild(d)),k(),{mode:"docked",host:p,shell:s,syncWidgetState(M){let H=M.launcherEnabled?M.open:!0;u!==H&&(u=H,k())},updateConfig(M){var H,I;t=M,((I=(H=t==null?void 0:t.launcher)==null?void 0:H.enabled)!=null?I:!0)===!1&&(u=!0),k()},destroy(){E==null||E.removeEventListener("resize",A),f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Vs=(e,t)=>nr(t)?G0(e,t):j0(e,t);var Lp={},K0=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 t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},X0=()=>{try{if(typeof Lp!="undefined"&&Lp.url)return new URL("../widget.css",Lp.url).href}catch{}return null},_x=(e,t)=>{let r=X0(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let a=n.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(r){let n=t.createElement("link");n.rel="stylesheet",n.href=r,n.setAttribute("data-persona","true"),e.insertBefore(n,e.firstChild)}else o();else if(!t.head.querySelector("link[data-persona]")&&r){let a=t.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-persona","true"),t.head.appendChild(a)}},Ux=e=>{var k;let t=K0(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Vs(t,n),s,i=[],c=(E,A)=>{var v,M;let y=!((M=(v=A==null?void 0:A.launcher)==null?void 0:v.enabled)!=null?M:!0)||nr(A),w=o.createElement("div");if(w.setAttribute("data-persona-root","true"),y&&(w.style.height="100%",w.style.display="flex",w.style.flexDirection="column",w.style.flex="1",w.style.minHeight="0"),r){let H=E.attachShadow({mode:"open"});H.appendChild(w),_x(H,o)}else E.appendChild(w),_x(E,o);return t.id&&w.setAttribute("data-persona-instance",t.id),w},d=()=>{a.syncWidgetState(s.getState())},p=()=>{i.forEach(E=>E()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},u=()=>{let E=c(a.host,n);s=hl(E,n,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(E=>E()),i=[],s.destroy()};u(),(k=e.onChatReady)==null||k.call(e);let f=E=>{g(),a.destroy(),a=Vs(t,E),n=E,u()},h={update(E){var M,H,I,P,B,O;let A={...n,...E,launcher:{...(M=n==null?void 0:n.launcher)!=null?M:{},...(H=E==null?void 0:E.launcher)!=null?H:{},dock:{...(P=(I=n==null?void 0:n.launcher)==null?void 0:I.dock)!=null?P:{},...(O=(B=E==null?void 0:E.launcher)==null?void 0:B.dock)!=null?O:{}}}},T=nr(n),y=nr(A),w=Fn(n),v=Fn(A);if(T!==y||w!==v){f(A);return}n=A,a.updateConfig(n),s.update(E),d()},destroy(){g(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},b=new Proxy(h,{get(E,A,T){if(A==="host")return a.host;if(A in E)return Reflect.get(E,A,T);let y=s[A];return typeof y=="function"?y.bind(s):y}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=b),b};var jx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Q0=new Set(["button","a","input","select","textarea","details","summary"]),J0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Pp=/\b(product|card|item|listing|result)\b/i,Ip=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Y0=3e3,Z0=100;function Gx(e){let t=typeof e.className=="string"?e.className:"";if(Pp.test(t)||e.id&&Pp.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Pp.test(o.value))return!0}return!1}function Kx(e){var t;return Ip.test(((t=e.textContent)!=null?t:"").trim())}function Xx(e){var r;let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=(r=t[o].getAttribute("href"))!=null?r:"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function ew(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function qx(e){let t=e.match(Ip);return t?t[0]:null}function Vx(e){var o,n,a;let t=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(t&&((n=t.textContent)!=null&&n.trim())){let s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function tw(e){let t=[],r=o=>{let n=o.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;r((n=o.value)!=null?n:"")}),t.slice(0,6)}var rw="commerce-card",ow="result-card";function zx(e){return!Gx(e)||!Kx(e)||!Xx(e)&&!ew(e)?0:5200}function $x(e){var o;return!Gx(e)||Kx(e)||!Xx(e)||((o=e.textContent)!=null?o:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Hp=[{id:rw,scoreElement(e){return zx(e)},shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if(r.interactivity==="static"){let o=r.text.trim();return!!(o.length===0||Ip.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,d,p;if(zx(e)===0)return null;let{title:r,href:o}=Vx(e),n=(p=(d=qx(((c=e.textContent)!=null?c:"").trim()))!=null?d:qx(t.text))!=null?p:"",a=tw(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
113
|
-
`)}},{id:ow,scoreElement(e){return $x(e)},formatSummary(e,t){if($x(e)===0)return null;let{title:r,href:o}=Vx(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
114
|
-
`)}}
|
|
115
|
-
${s.map(
|
|
134
|
+
${nt?"background: transparent !important;":""}
|
|
135
|
+
`}if(!v&&!i){let Rt="max-height: -moz-available !important; max-height: stretch !important;",eo=m?"":"padding-top: 1.25em !important;",Ms=m?"":`z-index: ${r.launcher?.zIndex??zt} !important;`;Se.style.cssText+=Rt+eo+Ms}Nr()};us(),en(e,r),Xa(e,r),Ja(e,r),Zn=()=>{us(),en(e,r),Xa(e,r),Ja(e,r),as?e.style.setProperty("--persona-artifact-welded-outer-radius",as):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let $e=[];$e.push(()=>{document.removeEventListener("keydown",mu)}),$e.push(()=>{Jn!==null&&clearTimeout(Jn)});let ko=null,Lo=null;$e.push(()=>{ko?.(),ko=null,Lo?.(),Lo=null}),Yn&&$e.push(()=>{Yn?.disconnect(),Yn=null}),$e.push(()=>{oa?.(),oa=null,pl(),vt&&(vt.remove(),vt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),Y&&$e.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),Ue?.destroy(),Ue=null,Oe?.destroy(),Oe=null,be=null});let Rr=null,yu=()=>{Rr&&(Rr(),Rr=null),r.colorScheme==="auto"&&(Rr=Hn(()=>{en(e,r)}))};yu(),$e.push(()=>{Rr&&(Rr(),Rr=null)}),$e.push(s);let fs=r.features?.streamAnimation;if(fs?.type&&fs.type!=="none"){let i=Nn(fs.type,fs.plugins);i&&(Wi(i,e),$e.push(()=>Ym(e)))}let ms=yg(xt),Ir=null,V,ul=i=>{if(!V)return;let m=i??V.getMessages(),b=r.features?.suggestReplies?.enabled!==!1?Us(m):null;b?ms.render(b,V,U,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(v=>v.role==="user")?ms.render([],V,U,m):ms.render(r.suggestionChips,V,U,m,r.suggestionChipsConfig)},xo=!1,Br=Vm(),mn=new Map,Hr=new Map,er=new Map,fl=0,Sh=qo()!==null,ro=Li(),uo=0,tr=null,fo=!1,gs=!1,or=0,vo=null,Wr=null,ml=!1,hs=!1,gl=null,ra=!0,hl=!1,yl=null,Th=4,ys=24,Mh=80,bl=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},bu=r.voiceRecognition?.autoResume??!1,Oo=i=>{l.emit("voice:state",{active:Xe.active,source:i,timestamp:Date.now()})},Co=()=>{C(i=>({...i,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},Eh=()=>{if(r.voiceRecognition?.enabled===!1)return;let i=Fp(c.voiceState),m=!!i.active,b=Number(i.timestamp??0);Xe.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-b<Pv&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,r.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Oo("restore"),V.isVoiceActive()&&xn()}):Cs("restore"))},1e3)},kh=()=>V?Hg(V.getMessages()).filter(i=>!i.__skipPersist):[],bs=null,xu=(i,m)=>{typeof console<"u"&&console.error(i,m)},xl=(i,m)=>{let b=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch($=>{xu(m,$)})}catch(Q){return xu(m,Q),null}},v=bs,P=v?v.then(()=>b()??void 0):b();if(!P)return;let W=P.finally(()=>{bs===W&&(bs=null)});bs=W};function vl(i){if(!d?.save)return;let b={messages:i?Hg(i):V?kh():[],metadata:c,artifacts:yo.artifacts,selectedArtifactId:yo.selectedId};xl(()=>d.save(b),"[AgentWidget] Failed to persist state:")}let gn=null,vu=()=>Se.querySelector("#persona-scroll-container")||ie,na=()=>{gn!==null&&(cancelAnimationFrame(gn),gn=null),fo=!1},Cu=()=>{tr!==null&&(cancelAnimationFrame(tr),tr=null),gs=!1,na()},Lh=()=>xo&&wl()&&(Zt()!=="anchor-top"||tu()),Cl=()=>{let i=Er()||"Jump to latest",m=Lh();Bt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),or>0?(kr.textContent=String(or),kr.style.display="",Bt.setAttribute("aria-label",`${i} (${or} new)`)):(kr.textContent="",kr.style.display="none",Bt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},wu=()=>{or!==0&&(or=0,Cl())},wl=()=>Jo()?!ro.isFollowing():!Ar(ie,ys),no=()=>{if(!rs()||ke){Bt.parentNode&&Bt.remove(),Bt.style.display="none";return}Bt.parentNode!==fe&&fe.appendChild(Bt),cn();let m=Ho(ie)>0&&wl();m?Cl():wu(),Bt.style.display=m?"":"none"},aa=()=>{ro.pause()&&(Cu(),no())},rr=()=>{ro.resume(),wu(),no()},nr=(i=!1)=>{Jo()&&ro.isFollowing()&&(!i&&!xo||(tr!==null&&(cancelAnimationFrame(tr),tr=null),gs=!0,tr=requestAnimationFrame(()=>{tr=null,gs=!1,ro.isFollowing()&&Ph(vu(),i?220:140)})))},Au=(i,m,b,v=()=>!0)=>{let P=i.scrollTop,W=m(),Q=W-P;if(na(),Math.abs(Q)<1){fo=!0,i.scrollTop=W,uo=i.scrollTop,fo=!1;return}let $=performance.now();fo=!0;let X=ce=>1-Math.pow(1-ce,3),ae=ce=>{if(!v()){na();return}let oe=m();oe!==W&&(W=oe,Q=W-P);let ye=ce-$,je=Math.min(ye/b,1),yt=X(je),st=P+Q*yt;i.scrollTop=st,uo=i.scrollTop,je<1?gn=requestAnimationFrame(ae):(i.scrollTop=W,uo=i.scrollTop,gn=null,fo=!1)};gn=requestAnimationFrame(ae)},Ph=(i,m=500)=>{let b=Ho(i)-i.scrollTop;if(Math.abs(b)<1){uo=i.scrollTop;return}if(Math.abs(b)>=Mh){na(),fo=!0,i.scrollTop=Ho(i),uo=i.scrollTop,fo=!1;return}Au(i,()=>Ho(i),m,()=>ro.isFollowing())},Su=()=>{let i=vu();fo=!0,i.scrollTop=Ho(i),uo=i.scrollTop,fo=!1,no()},Tu=i=>{let m=0,b=i;for(;b&&b!==ie;)m+=b.offsetTop,b=b.offsetParent;return m},Mu=()=>{if(bh()!=="last-user-turn")return!1;let i=V?.getMessages()??[];if(i.length<2)return!1;let m=[...i].reverse().find(W=>W.role==="user");if(!m)return!1;let b=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ie.querySelector(`[data-message-id="${b}"]`);if(!v)return!1;let P=Math.min(Math.max(0,Tu(v)-Zp()),Ho(ie));return fo=!0,ie.scrollTop=P,uo=ie.scrollTop,fo=!1,Zt()==="follow"&&!Ar(ie,ys)&&ro.pause(),no(),!0},Eu=i=>{Qo.style.height=`${Math.max(0,Math.round(i))}px`,vo&&(vo.spacerHeight=Math.max(0,i))},sa=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),na(),vo=null,Qo.style.height="0px"},Rh=i=>{Wr!==null&&cancelAnimationFrame(Wr),Wr=requestAnimationFrame(()=>{Wr=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ie.querySelector(`[data-message-id="${m}"]`);if(!b)return;let v=Tu(b),P=vo?.spacerHeight??0,W=ie.scrollHeight-P,{targetScrollTop:Q,spacerHeight:$}=Km({anchorOffsetTop:v,topOffset:Zp(),viewportHeight:ie.clientHeight,contentHeight:W});vo={initialSpacerHeight:$,contentHeightAtAnchor:W,spacerHeight:$},Eu($),Au(ie,()=>Q,220)})},Ih=()=>{if(Jo()){if(!ro.isFollowing()||Ar(ie,1))return;nr(!xo);return}if(vo&&vo.initialSpacerHeight>0){let i=ie.scrollHeight-vo.spacerHeight,m=Xm({initialSpacerHeight:vo.initialSpacerHeight,contentHeightAtAnchor:vo.contentHeightAtAnchor,currentContentHeight:i});m!==vo.spacerHeight&&Eu(m)}no()},Bh=i=>{let m=Zt();m==="follow"?(rr(),nr(!0)):m==="anchor-top"&&(ra=!1,hl=!0,Rh(i))},Hh=()=>{if(Zt()==="anchor-top"){if(hl){ra=!1;return}ra=!0,sa(),rr(),nr(!0)}},Wh=i=>{let m=new Map;i.forEach(b=>{let v=bl.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!v&&b.role==="assistant"&&(l.emit("assistant:message",b),!hs&&(Zt()!=="anchor-top"||tu())&&wl()&&(or+=1,Cl(),no(),ru(or===1?"1 new message below.":`${or} new messages below.`))),b.role==="assistant"&&v?.streaming&&b.streaming===!1&&l.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(v?b.approval.status!=="pending"&&l.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):l.emit("approval:requested",{approval:b.approval,message:b}))}),bl.clear(),m.forEach((b,v)=>{bl.set(v,b)})},Dh=(i,m,b)=>{let v=document.createElement("div"),W=(()=>{let D=n.find(Fe=>Fe.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(r.loadingIndicator?.render)return r.loadingIndicator.render})(),Q=(D,Fe)=>Fe==null?!1:typeof Fe=="string"?(D.textContent=Fe,!0):(D.appendChild(Fe),!0),$=new Set,X=new Set,ae=n.some(D=>D.renderAskUserQuestion),ce=[],oe=[],ye=r.enableComponentStreaming!==!1,je=r.approval!==!1,yt=[];if(m.forEach(D=>{$.add(D.id);let Fe=ae&&Vo(D),we=je&&D.variant==="approval"&&!!D.approval,_e=!Fe&&D.role==="assistant"&&!D.variant&&ye&&es(D);!we&&er.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),er.delete(D.id)),!_e&&Hr.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Hr.delete(D.id));let Tt=Vo(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=qm(D,fl)+Tt,wt=Fe||we||_e?null:zm(Br,D.id,ut);if(wt){v.appendChild(wt.cloneNode(!0)),Vo(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),kn(D,r,Le.composerOverlay));return}let bt=null,qt=n.find(pe=>!!(D.variant==="reasoning"&&pe.renderReasoning||D.variant==="tool"&&pe.renderToolCall||!D.variant&&pe.renderMessage)),Or=r.layout?.messages;if(Vo(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){mn.delete(D.id),i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ma(D)&&r.features?.suggestReplies?.enabled!==!1)return;if(Vo(D)&&r.features?.askUserQuestion?.enabled!==!1){let pe=n.find(At=>typeof At.renderAskUserQuestion=="function");if(pe&>.current){let At=mn.get(D.id),Gt=At!==ut,Ft=null;if(Gt){let{payload:Ze,complete:Pt}=zo(D),Be=D.id,et=()=>gt.current?.getMessages().find(ao=>ao.id===Be);Ft=pe.renderAskUserQuestion({message:D,payload:Ze,complete:Pt,resolve:ao=>{let Nr=et();Nr&>.current?.resolveAskUserQuestion(Nr,ao)},dismiss:()=>{let ao=et();ao?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(ao),gt.current?.resolveAskUserQuestion(ao,"(dismissed)"))},config:r})}let nt=At!=null;if(Gt&&Ft===null&&!nt){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),kn(D,r,Le.composerOverlay));return}let ze=document.createElement("div");ze.className="persona-flex",ze.id=`wrapper-${D.id}`,ze.setAttribute("data-wrapper-id",D.id),ze.setAttribute("data-ask-plugin-stub","true"),ze.setAttribute("data-preserve-runtime","true"),v.appendChild(ze),ce.push({messageId:D.id,fingerprint:ut,bubble:Ft});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(X.add(D.toolCall.id),kn(D,r,Le.composerOverlay));return}}else if(we){let pe=n.find(nt=>typeof nt.renderApproval=="function")??a,Gt=er.get(D.id)!==ut,Ft=null;if(Gt&&pe?.renderApproval){let nt=D.id,ze=(Ze,Pt)=>{let Be=gt.current?.getMessages().find(et=>et.id===nt);Be?.approval&&(Be.approval.toolType==="webmcp"?gt.current?.resolveWebMcpApproval(Be.id,Ze):gt.current?.resolveApproval(Be.approval,Ze,Pt))};Ft=pe.renderApproval({message:D,defaultRenderer:()=>ji(D,r),config:r,approve:Ze=>ze("approved",Ze),deny:Ze=>ze("denied",Ze)})}if(Gt&&Ft===null)i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),er.delete(D.id),bt=ji(D,r);else{let nt=document.createElement("div");nt.className="persona-flex",nt.id=`wrapper-${D.id}`,nt.setAttribute("data-wrapper-id",D.id),nt.setAttribute("data-approval-plugin-stub","true"),nt.setAttribute("data-preserve-runtime","true"),v.appendChild(nt),yt.push({messageId:D.id,fingerprint:ut,bubble:Ft});return}}else if(qt)if(D.variant==="reasoning"&&D.reasoning&&qt.renderReasoning){if(!se)return;bt=qt.renderReasoning({message:D,defaultRenderer:()=>Tp(D,r),config:r})}else if(D.variant==="tool"&&D.toolCall&&qt.renderToolCall){if(!xe)return;bt=qt.renderToolCall({message:D,defaultRenderer:()=>Ep(D,r),config:r})}else qt.renderMessage&&(bt=qt.renderMessage({message:D,defaultRenderer:()=>{let pe=qn(D,b,Or,r.messageActions,Ne,{loadingIndicatorRenderer:W,widgetConfig:r});return D.role!=="user"&&Hp(pe,D,r,V),pe},config:r}));if(!bt&&_e){let pe=Qi(D);if(pe){let At=Hr.get(D.id),Gt=At!==ut,Ft=r.wrapComponentDirectiveInBubble!==!1&&Mo.getOptions(pe.component)?.bubbleChrome!==!1,nt=null;if(Gt){let ze=Ji(pe,{config:r,message:D,transform:b});if(ze&&pe.component==="PersonaArtifactInline"){let Ze=ze.hasAttribute("data-artifact-inline")?ze:ze.querySelector("[data-artifact-inline]"),Pt=Ze?.getAttribute("data-artifact-inline")??"",Be=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Pt):Pt,et=Pt?i.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${Be}"]`)??null:null;Ze&&et&&et!==Ze&&Dm(et)&&(Ze===ze?ze=et:Ze.replaceWith(et))}if(ze)if(Ft){let Ze=document.createElement("div");if(Ze.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(" "),Ze.id=`bubble-${D.id}`,Ze.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let Pt=document.createElement("div");Pt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Pt.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ze.appendChild(Pt)}Ze.appendChild(ze),nt=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${D.id}`,Ze.setAttribute("data-message-id",D.id),Ze.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let Pt=document.createElement("div");Pt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Pt.innerHTML=b({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ze.appendChild(Pt)}Ze.appendChild(ze),nt=Ze}}if(nt||At!=null){let ze=document.createElement("div");ze.className="persona-flex",ze.id=`wrapper-${D.id}`,ze.setAttribute("data-wrapper-id",D.id),ze.setAttribute("data-component-directive-stub","true"),ze.setAttribute("data-preserve-runtime","true"),Ft||ze.classList.add("persona-w-full"),v.appendChild(ze),oe.push({messageId:D.id,fingerprint:ut,bubble:nt});return}}}if(!bt)if(D.variant==="reasoning"&&D.reasoning){if(!se)return;bt=Tp(D,r)}else if(D.variant==="tool"&&D.toolCall){if(!xe)return;bt=Ep(D,r)}else if(D.variant==="approval"&&D.approval){if(r.approval===!1)return;bt=ji(D,r)}else{let pe=r.layout?.messages;pe?.renderUserMessage&&D.role==="user"?bt=pe.renderUserMessage({message:D,config:r,streaming:!!D.streaming}):pe?.renderAssistantMessage&&D.role==="assistant"?bt=pe.renderAssistantMessage({message:D,config:r,streaming:!!D.streaming}):bt=qn(D,b,pe,r.messageActions,Ne,{loadingIndicatorRenderer:W,widgetConfig:r}),D.role!=="user"&&bt&&Hp(bt,D,r,V)}let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${D.id}`,ft.setAttribute("data-wrapper-id",D.id),D.role==="user"&&ft.classList.add("persona-justify-end"),bt?.getAttribute("data-persona-component-directive")==="true"&&ft.classList.add("persona-w-full"),ft.appendChild(bt),$m(Br,D.id,ut,ft),v.appendChild(ft)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let we=Fe.getAttribute("data-persona-ask-sheet-for");we&&!X.has(we)&&pr(Le.composerOverlay,we)}),r.features?.toolCallDisplay?.grouped){let D=[],Fe=[];m.forEach(we=>{if(we.variant==="tool"&&we.toolCall&&xe){Fe.push(we);return}we.variant==="reasoning"&&!se||(Fe.length>1&&D.push(Fe),Fe=[])}),Fe.length>1&&D.push(Fe),D.forEach((we,_e)=>{let Tt=we.map(At=>Array.from(v.children).find(Gt=>Gt instanceof HTMLElement&&Gt.getAttribute("data-wrapper-id")===At.id)).filter(At=>!!At);if(Tt.length<2)return;let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-tool-group-${_e}-${we[0].id}`,ut.setAttribute("data-wrapper-id",`tool-group-${_e}-${we[0].id}`);let wt=document.createElement("div");wt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",wt.setAttribute("data-persona-tool-group","true");let bt=document.createElement("div");bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${we.length} tools`,Or=r.toolCall?.renderGroupedSummary?.({messages:we,toolCalls:we.map(At=>At.toolCall).filter(At=>!!At),defaultSummary:qt,config:r});Q(bt,Or)||(bt.textContent=qt);let ft=document.createElement("div");ft.className="persona-tool-group-stack persona-flex persona-flex-col";let pe=r.features?.toolCallDisplay?.groupedMode==="summary";wt.appendChild(bt),pe||wt.appendChild(ft),ut.appendChild(wt),Tt[0].before(ut),Tt.forEach((At,Gt)=>{if(pe){At.remove();return}let Ft=document.createElement("div");Ft.className="persona-tool-group-item persona-relative",Ft.setAttribute("data-persona-tool-group-item","true"),Gt<Tt.length-1&&Ft.setAttribute("data-persona-tool-group-connector","true"),Ft.appendChild(At),ft.appendChild(Ft)})})}jm(Br,$);let st=m.some(D=>D.role==="assistant"&&D.streaming),jt=m[m.length-1],Dt=jt?.role==="assistant"&&!jt.streaming&&jt.variant!=="approval";if(xo&&m.some(D=>D.role==="user")&&!st&&!Dt){let D={config:r,streaming:!0,location:"standalone",defaultRenderer:nn},Fe=n.find(_e=>_e.renderLoadingIndicator),we=null;if(Fe?.renderLoadingIndicator&&(we=Fe.renderLoadingIndicator(D)),we===null&&r.loadingIndicator?.render&&(we=r.loadingIndicator.render(D)),we===null&&(we=nn()),we){let _e=document.createElement("div"),Tt=r.loadingIndicator?.showBubble!==!1;_e.className=Tt?["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(" "),_e.setAttribute("data-typing-indicator","true"),_e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",_e.appendChild(we);let ut=document.createElement("div");ut.className="persona-flex",ut.id="wrapper-typing-indicator",ut.setAttribute("data-wrapper-id","typing-indicator"),ut.appendChild(_e),v.appendChild(ut)}}if(!xo&&m.length>0){let D=m[m.length-1],Fe={config:r,lastMessage:D,messageCount:m.length},we=n.find(Tt=>Tt.renderIdleIndicator),_e=null;if(we?.renderIdleIndicator&&(_e=we.renderIdleIndicator(Fe)),_e===null&&r.loadingIndicator?.renderIdle&&(_e=r.loadingIndicator.renderIdle(Fe)),_e){let Tt=document.createElement("div"),ut=r.loadingIndicator?.showBubble!==!1;Tt.className=ut?["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(" "),Tt.setAttribute("data-idle-indicator","true"),Tt.appendChild(_e);let wt=document.createElement("div");wt.className="persona-flex",wt.id="wrapper-idle-indicator",wt.setAttribute("data-wrapper-id","idle-indicator"),wt.appendChild(Tt),v.appendChild(wt)}}if(Ei(i,v),ce.length>0)for(let{messageId:D,fingerprint:Fe,bubble:we}of ce){let _e=i.querySelector(`#wrapper-${D}`);_e&&we!==null&&(_e.replaceChildren(we),_e.setAttribute("data-bubble-fp",Fe),mn.set(D,Fe))}if(mn.size>0)for(let D of mn.keys())$.has(D)||mn.delete(D);if(oe.length>0)for(let{messageId:D,fingerprint:Fe,bubble:we}of oe){let _e=i.querySelector(`#wrapper-${D}`);_e&&we!==null&&(_e.replaceChildren(we),_e.setAttribute("data-bubble-fp",Fe),Hr.set(D,Fe))}if(Hr.size>0)for(let D of Hr.keys())$.has(D)||Hr.delete(D);if(yt.length>0)for(let{messageId:D,fingerprint:Fe,bubble:we}of yt){let _e=i.querySelector(`#wrapper-${D}`);_e&&we!==null&&(_e.replaceChildren(we),_e.setAttribute("data-bubble-fp",Fe),er.set(D,Fe))}if(er.size>0)for(let D of er.keys())$.has(D)||er.delete(D)},ia=(i,m,b)=>{Dh(i,m,b),pu()},la=null,Fh=()=>{if(la)return;let i=b=>{let v=b.composedPath();v.includes(Se)||lt&&v.includes(lt)||ht(!1,"user")};la=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},ku=()=>{if(!la)return;(e.ownerDocument??document).removeEventListener("pointerdown",la,!0),la=null};$e.push(()=>ku());let da=null,Oh=()=>{if(da)return;let i=b=>{b.key==="Escape"&&(b.isComposing||ht(!1,"user"))};da=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Lu=()=>{if(!da)return;(e.ownerDocument??document).removeEventListener("keydown",da,!0),da=null};$e.push(()=>Lu());let ca=!1,Pu=new Set,Nh=()=>{let i=r.launcher?.composerBar?.peek?.streamAnimation;return i||r.features?.streamAnimation},hn=()=>{if(!q())return;let i=Le.peekBanner,m=Le.peekTextNode;if(!i||!m)return;if(z){i.classList.remove("persona-pill-peek--visible");return}let b=V?.getMessages()??[],v;for(let Dt=b.length-1;Dt>=0;Dt--){let D=b[Dt];if(D.role==="assistant"&&D.content){v=D;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let P=v.content,W=!!v.streaming,Q=Nh(),$=Ii(Q),X=$.type!=="none"?Nn($.type,Q?.plugins):null,ae=X?.isAnimating?.(v)===!0,ce=X!==null&&(W||ae);ce&&X&&!Pu.has(X.name)&&(Wi(X,e),Pu.add(X.name));let oe=ce&&X?.containerClass?X.containerClass:null,ye=m.dataset.personaPeekStreamClass??null;ye&&ye!==oe&&(m.classList.remove(ye),delete m.dataset.personaPeekStreamClass),oe&&ye!==oe&&(m.classList.add(oe),m.dataset.personaPeekStreamClass=oe),ce?(m.style.setProperty("--persona-stream-step",`${$.speed}ms`),m.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let je=ce?Bi(P,$.buffer,X,v,W):P;if(ce&&$.placeholder==="skeleton"&&W&&(!je||!je.trim())){let Dt=document.createElement("div"),D=Va();D.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(D),Ei(m,Dt)}else{let Dt=Math.max(0,je.length-100),D=je.length>100?je.slice(-100):je,Fe=Ro(D);if(!ce||!X){let we=je.length>100?`\u2026${D}`:D;m.textContent!==we&&(m.textContent=we)}else{let we=Fe;(X.wrap==="char"||X.wrap==="word")&&(we=qa(Fe,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:Dt}));let _e=document.createElement("div");if(_e.innerHTML=we,X.useCaret&&D.length>0){let Tt=Hi(),ut=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),wt=ut[ut.length-1];wt?.parentNode?wt.parentNode.insertBefore(Tt,wt.nextSibling):_e.appendChild(Tt)}Ei(m,_e),X.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:$.speed,duration:$.duration})}}let jt=xo||ca;i.classList.toggle("persona-pill-peek--visible",jt)};if(q()){let i=Le.peekBanner;if(i){let v=P=>{P.preventDefault(),P.stopPropagation(),ht(!0,"user")};i.addEventListener("pointerdown",v),$e.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{ca||(ca=!0,hn())},b=()=>{ca&&(ca=!1,hn())};me.addEventListener("pointerenter",m),me.addEventListener("pointerleave",b),$e.push(()=>{me.removeEventListener("pointerenter",m),me.removeEventListener("pointerleave",b)}),lt&&(lt.addEventListener("pointerenter",m),lt.addEventListener("pointerleave",b),$e.push(()=>{lt.removeEventListener("pointerenter",m),lt.removeEventListener("pointerleave",b)}))}let _h=i=>{let m=r.launcher?.composerBar??{},b=m.expandedSize??"anchored",v=m.bottomOffset??"16px",P=m.collapsedMaxWidth,W=m.expandedMaxWidth??"880px",Q=m.expandedTopOffset??"5vh",$=m.modalMaxWidth??"880px",X=m.modalMaxHeight??"min(90vh, 800px)",ae="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",oe=Se.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",lt){let ye=lt.style;ye.bottom=v,ye.width=P??""}if(i&&b!=="fullscreen"){if(b==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=$,oe.maxWidth=ae,oe.maxHeight=X,oe.height=X;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${v} + ${ce})`,oe.top=Q,oe.width=W,oe.maxWidth=ae}},pa=()=>{if(!O())return;if(q()){let ae=(r.launcher?.composerBar??{}).expandedSize??"anchored",ce=z?"expanded":"collapsed";Se.dataset.state=ce,Se.dataset.expandedSize=ae,lt&&(lt.dataset.state=ce,lt.dataset.expandedSize=ae),Se.style.removeProperty("display"),Se.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),_h(z),fe.style.display=z?"flex":"none",us(),z?(Fh(),Oh()):(ku(),Lu()),hn();return}let i=It(r),m=e.ownerDocument.defaultView??window,b=r.launcher?.mobileBreakpoint??640,v=r.launcher?.mobileFullscreen??!0,P=m.innerWidth<=b,W=v&&P&&T,Q=oo(r).reveal;z?(Se.style.removeProperty("display"),Se.style.display=i?"flex":"",Se.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),_t?_t.element.style.display="none":$t&&($t.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!W?(Se.style.removeProperty("display"),Se.style.display="flex",Se.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Se.style.setProperty("display","none","important"),Se.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Se.style.display="",Se.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),_t?_t.element.style.display=i?"none":"":$t&&($t.style.display=i?"none":""))},ht=(i,m="user")=>{if(!O()||z===i)return;let b=z;z=i,pa();let v=(()=>{let W=r.launcher?.sidebarMode??!1,Q=e.ownerDocument.defaultView??window,$=r.launcher?.mobileFullscreen??!0,X=r.launcher?.mobileBreakpoint??640,ae=Q.innerWidth<=X,ce=It(r)&&$&&ae,oe=q()&&(r.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return W||$&&ae&&T||ce||oe})();if(z&&v){if(!ko){let W=e.getRootNode(),Q=W instanceof ShadowRoot?W.host:e.closest(".persona-host");Q&&(ko=mp(Q,r.launcher?.zIndex??zt))}Lo||(Lo=gp(e.ownerDocument))}else z||(ko?.(),ko=null,Lo?.(),Lo=null);z&&(ua(),Mu()||(Zt()==="follow"?nr(!0):Su()));let P={open:z,source:m,timestamp:Date.now()};z&&!b?l.emit("widget:opened",P):!z&&b&&l.emit("widget:closed",P),l.emit("widget:state",{open:z,launcherEnabled:T,voiceActive:Xe.active,streaming:V.isStreaming()})},Al=i=>{dt(i?"stop":"send"),G&&(G.disabled=i),ms.buttons.forEach(m=>{m.disabled=i}),j.dataset.personaComposerStreaming=i?"true":"false",j.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},Sl=()=>{Xe.active||U&&U.focus()};l.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Sl(),200)});let Ru=()=>{J.textContent=r.copy?.welcomeTitle??"Hello \u{1F44B}",x.textContent=r.copy?.welcomeSubtitle??"Ask anything about your account or products.",U.placeholder=r.copy?.inputPlaceholder??"How can I help...";let i=ie.querySelector("[data-persona-intro-card]");if(i){let b=r.copy?.showWelcomeCard!==!1;i.style.display=b?"":"none",b?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(r.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(te.textContent=r.copy?.sendButtonLabel??"Send"),U.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',U.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let i=c.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{C(m=>({...m,sessionId:i}))}});let Dr=null,Uh=()=>{Dr==null&&(Dr=setInterval(()=>{let i=he.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Dr),Dr=null;return}let m=Date.now();i.forEach(b=>{let v=Number(b.getAttribute("data-tool-elapsed"));v&&(b.textContent=Vs(m-v))})},100))},Tl=(i,m)=>{if(Object.is(i,m))return!0;if(i===null||m===null||typeof i!="object"||typeof m!="object")return!1;if(Array.isArray(i)||Array.isArray(m))return!Array.isArray(i)||!Array.isArray(m)||i.length!==m.length?!1:i.every((Q,$)=>Tl(Q,m[$]));let b=i,v=m,P=Object.keys(b),W=Object.keys(v);return P.length===W.length&&P.every(Q=>Object.prototype.hasOwnProperty.call(v,Q)&&Tl(b[Q],v[Q]))},Iu=i=>{let{content:m,rawContent:b,llmContent:v,...P}=i;return P},Ml=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!es(i),qh=(i,m,b)=>{if(i.length!==m.length)return!1;let v=i[b.index],P=m[b.index];return!v||!P||v.id!==b.id||P.id!==b.id?!1:(!Object.is(v.content,P.content)||!Object.is(v.rawContent,P.rawContent)||!Object.is(v.llmContent,P.llmContent))&&Ml(v)&&Ml(P)&&Tl(Iu(v),Iu(P))},Bu=null,yn=null,Fr=null,No=null,xs=i=>{Bu=i;let m,b;yn=null;for(let P=i.length-1;P>=0;P-=1){let W=i[P];if(!m&&W.role==="user"&&(m=W),!b&&W.role==="assistant"&&(b=W),!yn&&Ml(W)&&(yn={index:P,id:W.id}),m&&b&&yn)break}ia(he,i,De),ip(he,yo.artifacts,{suppressTransition:xo}),Uh(),ul(i),nr(!xo),Wh(i),i.length===0&&(sa(),ra=!0,hl=!1),!ml||hs?(ml=!0,gl=m?.id??null,yl=b?.id??null):m&&m.id!==gl?(gl=m.id,Bh(m.id)):b&&b.id!==yl&&Hh(),b&&(yl=b.id);let v=Xe.lastUserMessageId;m&&m.id!==v&&(Xe.lastUserMessageId=m.id,l.emit("user:message",m)),Xe.lastUserMessageWasVoice=!!m?.viaVoice,vl(i),hn()},El=()=>{No!==null&&(cancelAnimationFrame(No),No=null);let i=Fr;Fr=null,i&&xs(i)},Hu=()=>{No!==null&&cancelAnimationFrame(No),No=null,Fr=null},Vh=i=>{let m=Fr??Bu;if(xo&&m&&yn&&qh(m,i,yn)){Fr=i,No===null&&(No=requestAnimationFrame(()=>{No=null;let b=Fr;Fr=null,b&&xs(b)}));return}if(i.length===0){Hu(),xs(i);return}El(),xs(i)};V=new In(r,{onMessagesChanged(i){Vh(i)},onStatusChanged(i){let m=r.statusIndicator??{};Lt(R,(v=>v==="idle"?m.idleText??Wt.idle:v==="connecting"?m.connectingText??Wt.connecting:v==="connected"?m.connectedText??Wt.connected:v==="error"?m.errorText??Wt.error:v==="paused"?m.pausedText??Wt.paused:v==="resuming"?m.resumingText??Wt.resuming:Wt[v])(i),m,i)},onStreamingChanged(i){i||(V?.getMessages().length===0?Hu():El()),xo=i,Al(i),V&&ia(he,V.getMessages(),De),i||nr(!0),no(),ru(i?"Responding\u2026":"Response complete."),hn()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),r.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":_o(),xn();break;case"processing":_o(),Kh();break;case"speaking":_o(),Xh();break;default:i==="idle"&&V.isBargeInActive()?(_o(),xn(),G?.setAttribute("aria-label","End voice session")):(Xe.active=!1,_o(),Oo("system"),Co());break}},onArtifactsState(i){yo=i,i.artifacts.length===0&&(pn=!1),ip(he,i.artifacts,{suppressTransition:xo}),Fo(),vl()},onReconnect(i){let{executionId:m,lastEventId:b}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:m,after:b}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:m,after:b,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:m,after:b})}}),gt.current=V,$e.push(()=>V.cancel());let kl=null;if(V.onReadAloudChange((i,m)=>{du=i,cu=m,pu();let b=i??kl;i&&(kl=i);let v=b?V.getMessages().find(P=>P.id===b)??null:null;l.emit("message:read-aloud",{messageId:b,message:v,state:m,timestamp:Date.now()}),m==="idle"&&(kl=null)}),ml=!0,r.voiceRecognition?.provider?.type==="runtype")try{V.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}r.clientToken&&V.initClientSession().catch(i=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Oe||r.onSSEEvent)&&V.setSSEEventCallback((i,m)=>{r.onSSEEvent?.(i,m),Ke?.processEvent(i,m),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let Wu=()=>{r.resume&&typeof r.reconnectStream=="function"&&V.resumeFromHandle(r.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=Fp(i.metadata),A.syncFromMetadata()),i.messages?.length){hs=!0;try{V.hydrateMessages(i.messages)}finally{hs=!1}}i.artifacts?.length&&V.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Wu()):Wu();let Du=()=>{!q()||z||!(r.launcher?.composerBar?.expandOnSubmit??!0)||ht(!0,"auto")},Fu=i=>{if(i.preventDefault(),V.isStreaming()){V.cancel(),Ke?.reset(),Ue?.update();return}let m=U.value.trim(),b=Mt?.hasAttachments()??!1;if(!m&&!b)return;Du();let v;b&&(v=[],v.push(...Mt.getContentParts()),m&&v.push(Pa(m))),U.value="",U.style.height="auto",vs(),V.sendMessage(m,{contentParts:v}),b&&Mt.clearAttachments()},zh=()=>r.features?.composerHistory!==!1,Ll={...ki},Pl=!1,vs=()=>{Ll={...ki}},$h=()=>V.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),jh=i=>{if(!U)return;Pl=!0,U.value=i,U.dispatchEvent(new Event("input",{bubbles:!0})),Pl=!1;let m=U.value.length;U.setSelectionRange(m,m)},Ou=()=>{Pl||vs()},Nu=i=>{if(U){if(zh()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=U.selectionStart===0&&U.selectionEnd===0,b=Um({direction:i.key==="ArrowUp"?"up":"down",history:$h(),currentValue:U.value,atStart:m,state:Ll});if(Ll=b.state,b.handled){i.preventDefault(),b.value!==void 0&&jh(b.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(V.isStreaming()){i.preventDefault();return}vs(),i.preventDefault(),te.click()}}},_u=i=>{i.key!=="Escape"||i.isComposing||V.isStreaming()&&i.composedPath().includes(fe)&&(V.cancel(),Ke?.reset(),Ue?.update(),vs(),i.preventDefault(),i.stopImmediatePropagation())},Uu=async i=>{if(r.attachments?.enabled!==!0||!Mt)return;let m=Bv(i.clipboardData);m.length!==0&&(i.preventDefault(),await Mt.handleFiles(m))},mo=null,Po=!1,bn=null,Ct=null,qu=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Cs=(i="user")=>{if(Po||V.isStreaming())return;let m=qu();if(!m)return;mo=new m;let v=(r.voiceRecognition??{}).pauseDuration??2e3;mo.continuous=!0,mo.interimResults=!0,mo.lang="en-US";let P=U.value;mo.onresult=W=>{let Q="",$="";for(let ae=0;ae<W.results.length;ae++){let ce=W.results[ae],oe=ce[0].transcript;ce.isFinal?Q+=oe+" ":$=oe}let X=P+Q+$;U.value=X,bn&&clearTimeout(bn),(Q||$)&&(bn=window.setTimeout(()=>{let ae=U.value.trim();ae&&mo&&Po&&(ar(),U.value="",U.style.height="auto",V.sendMessage(ae,{viaVoice:!0}))},v))},mo.onerror=W=>{W.error!=="no-speech"&&ar()},mo.onend=()=>{if(Po){let W=U.value.trim();W&&W!==P.trim()&&(U.value="",U.style.height="auto",V.sendMessage(W,{viaVoice:!0})),ar()}};try{if(mo.start(),Po=!0,Xe.active=!0,i!=="system"&&(Xe.manuallyDeactivated=!1),Oo(i),Co(),G){let W=r.voiceRecognition??{};Ct={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:W.iconName??"mic",iconSize:parseFloat(W.iconSize??r.sendButton?.size??"40")||24};let Q=W.recordingBackgroundColor,$=W.recordingIconColor,X=W.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let ae=G.querySelector("svg");ae&&ae.setAttribute("stroke",$)}X&&(G.style.borderColor=X),G.setAttribute("aria-label","Stop voice recognition")}}catch{ar("system")}},ar=(i="user")=>{if(Po){if(Po=!1,bn&&(clearTimeout(bn),bn=null),mo){try{mo.stop()}catch{}mo=null}if(Xe.active=!1,Oo(i),Co(),G){if(G.classList.remove("persona-voice-recording"),Ct){G.style.backgroundColor=Ct.backgroundColor,G.style.color=Ct.color,G.style.borderColor=Ct.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}G.setAttribute("aria-label","Start voice recognition")}}},Gh=(i,m)=>{let b=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=i?.provider?.type==="runtype",P=i?.provider?.type==="custom";if(!(b||v||P))return null;let Q=y("div","persona-send-button-wrapper"),$=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button",$.setAttribute("aria-label","Start voice recognition");let X=i?.iconName??"mic",ae=m?.size??"40px",ce=i?.iconSize??ae,oe=parseFloat(ce)||24,ye=i?.backgroundColor??m?.backgroundColor,je=i?.iconColor??m?.textColor;$.style.width=ce,$.style.height=ce,$.style.minWidth=ce,$.style.minHeight=ce,$.style.fontSize="18px",$.style.lineHeight="1",je?$.style.color=je:$.style.color="var(--persona-text, #111827)";let st=ne(X,oe,je||"currentColor",1.5);st?$.appendChild(st):$.textContent="\u{1F3A4}",ye?$.style.backgroundColor=ye:$.style.backgroundColor="",i?.borderWidth&&($.style.borderWidth=i.borderWidth,$.style.borderStyle="solid"),i?.borderColor&&($.style.borderColor=i.borderColor),i?.paddingX&&($.style.paddingLeft=i.paddingX,$.style.paddingRight=i.paddingX),i?.paddingY&&($.style.paddingTop=i.paddingY,$.style.paddingBottom=i.paddingY),Q.appendChild($);let jt=i?.tooltipText??"Start voice recognition";if((i?.showTooltip??!1)&&jt){let D=y("div","persona-send-button-tooltip");D.textContent=jt,Q.appendChild(D)}return{micButton:$,micButtonWrapper:Q}},Rl=()=>{if(!G||Ct)return;let i=r.voiceRecognition??{};Ct={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??r.sendButton?.size??"40")||24}},Il=(i,m)=>{if(!G)return;let b=G.querySelector("svg");b&&b.remove();let v=Ct?.iconSize??(parseFloat(r.voiceRecognition?.iconSize??r.sendButton?.size??"40")||24),P=ne(i,v,m,1.5);P&&G.appendChild(P)},ws=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},xn=()=>{if(!G)return;Rl();let i=r.voiceRecognition??{},m=i.recordingBackgroundColor,b=i.recordingIconColor,v=i.recordingBorderColor;if(ws(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b??"var(--persona-voice-recording-indicator, #ffffff)",b){let P=G.querySelector("svg");P&&P.setAttribute("stroke",b)}v&&(G.style.borderColor=v),G.setAttribute("aria-label","Stop voice recognition")},Kh=()=>{if(!G)return;Rl();let i=r.voiceRecognition??{},m=V.getVoiceInterruptionMode(),b=i.processingIconName??"loader",v=i.processingIconColor??Ct?.color??"",P=i.processingBackgroundColor??Ct?.backgroundColor??"",W=i.processingBorderColor??Ct?.borderColor??"";ws(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=P,G.style.borderColor=W;let Q=v||"currentColor";G.style.color=Q,Il(b,Q),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},Xh=()=>{if(!G)return;Rl();let i=r.voiceRecognition??{},m=V.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",v=i.speakingIconName??b,P=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??Ct?.color??"":Ct?.color??""),W=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),Q=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":Ct?.borderColor??"");ws(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=W,G.style.borderColor=Q;let $=P||"currentColor";G.style.color=$,Il(v,$);let X=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",X),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},_o=()=>{G&&(ws(),Ct&&(G.style.backgroundColor=Ct.backgroundColor??"",G.style.color=Ct.color??"",G.style.borderColor=Ct.borderColor??"",Il(Ct.iconName,Ct.color||"currentColor"),Ct=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},As=()=>{if(r.voiceRecognition?.provider?.type==="runtype"){let i=V.getVoiceStatus(),m=V.getVoiceInterruptionMode();if(m==="none"&&(i==="processing"||i==="speaking"))return;if(m==="cancel"&&(i==="processing"||i==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,Co(),Oo("user"),_o()});return}V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Xe.manuallyDeactivated=!V.isVoiceActive(),Co(),Oo("user"),V.isVoiceActive()?xn():_o()});return}if(Po){let i=U.value.trim();Xe.manuallyDeactivated=!0,Co(),ar("user"),i&&(U.value="",U.style.height="auto",V.sendMessage(i))}else Xe.manuallyDeactivated=!1,Co(),Cs("user")};au=As,G&&(G.addEventListener("click",As),$e.push(()=>{r.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),_o()):ar("system"),G&&G.removeEventListener("click",As)}));let Jh=l.on("assistant:complete",()=>{bu&&(Xe.active||Xe.manuallyDeactivated||bu==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(r.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Oo("auto"),V.isVoiceActive()&&xn()}):Cs("auto"))},600))});$e.push(Jh);let Qh=l.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});$e.push(Qh);let Vu=()=>{ht(!z,"user")},_t=null,$t=null;if(T&&!q()){let{instance:i,element:m}=vp({config:r,plugins:n,onToggle:Vu});_t=i,i||($t=m)}_t?e.appendChild(_t.element):$t&&e.appendChild($t),pa(),ul(),Ru(),Al(V.isStreaming()),Mu()||(Zt()==="follow"?nr(!0):Su()),Eh(),E&&(!T||q()?setTimeout(()=>Sl(),0):z&&setTimeout(()=>Sl(),200));let ua=()=>{if(q()){cn(),pa();return}let i=It(r),m=r.launcher?.sidebarMode??!1,b=i||m||(r.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,P=r.launcher?.mobileFullscreen??!0,W=r.launcher?.mobileBreakpoint??640,Q=v.innerWidth<=W,$=P&&Q&&T;try{if($){Zn(),ea=ps();return}let X=!1;F&&(F=!1,Zn(),X=!0);let ae=ps();if(!X&&ae!==ea&&(Zn(),X=!0),ea=ae,X&&cl(),!T&&!i){me.style.height="",me.style.width="";return}if(!m&&!i){let oe=r?.launcher?.width??r?.launcherWidth??lo;me.style.width=oe,me.style.maxWidth=oe}if(cs(),!b){let ce=v.innerHeight,oe=64,ye=r.launcher?.heightOffset??0,je=Math.max(200,ce-oe),yt=Math.min(640,je),st=Math.max(200,yt-ye);me.style.height=`${st}px`}}finally{if(cn(),pa(),z&&T){let ae=(e.ownerDocument.defaultView??window).innerWidth<=(r.launcher?.mobileBreakpoint??640),ce=r.launcher?.sidebarMode??!1,oe=r.launcher?.mobileFullscreen??!0,ye=It(r)&&oe&&ae,je=ce||oe&&ae&&T||ye;if(je&&!Lo){let yt=e.getRootNode(),st=yt instanceof ShadowRoot?yt.host:e.closest(".persona-host");st&&!ko&&(ko=mp(st,r.launcher?.zIndex??zt)),Lo=gp(e.ownerDocument)}else je||(ko?.(),ko=null,Lo?.(),Lo=null)}}};ua();let zu=e.ownerDocument.defaultView??window;if(zu.addEventListener("resize",ua),$e.push(()=>zu.removeEventListener("resize",ua)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{cn()});i.observe(j),$e.push(()=>i.disconnect())}uo=ie.scrollTop;let $u=Ho(ie),Yh=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},Bl=()=>Gm(Yh(),ie),ju=()=>{let i=ie.scrollTop,m=Ho(ie),b=m<$u;if($u=m,!Jo()){uo=i,no();return}let{action:v,nextLastScrollTop:P}=Pi({following:ro.isFollowing(),currentScrollTop:i,lastScrollTop:uo,nearBottom:Ar(ie,ys),userScrollThreshold:Th,isAutoScrolling:fo||gs||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(uo=P,v==="resume"){Bl()||rr();return}v==="pause"&&aa()};if(ie.addEventListener("scroll",ju,{passive:!0}),$e.push(()=>ie.removeEventListener("scroll",ju)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Ih()});i.observe(he),i.observe(ie),$e.push(()=>i.disconnect())}let Gu=()=>{Jo()&&ro.isFollowing()&&Bl()&&aa()},Ku=ie.ownerDocument;Ku.addEventListener("selectionchange",Gu),$e.push(()=>{Ku.removeEventListener("selectionchange",Gu)});let Zh=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Xu=i=>{eu()&&Jo()&&ro.isFollowing()&&Zh.has(i.key)&&aa()},Ju=i=>{if(!eu()||!Jo()||!ro.isFollowing())return;let m=i.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&aa()};ie.addEventListener("keydown",Xu),ie.addEventListener("focusin",Ju),$e.push(()=>{ie.removeEventListener("keydown",Xu),ie.removeEventListener("focusin",Ju)});let Qu=i=>{if(!Jo())return;let m=Ri({following:ro.isFollowing(),deltaY:i.deltaY,nearBottom:Ar(ie,ys),resumeWhenNearBottom:!0});m==="pause"?aa():m==="resume"&&!Bl()&&rr()};ie.addEventListener("wheel",Qu,{passive:!0}),$e.push(()=>ie.removeEventListener("wheel",Qu)),Bt.addEventListener("click",()=>{sa(),ie.scrollTop=ie.scrollHeight,uo=ie.scrollTop,rr(),nr(!0),no()}),$e.push(()=>Bt.remove()),$e.push(()=>{Cu(),sa()});let Yu=()=>{k&&(Ir&&(k.removeEventListener("click",Ir),Ir=null),O()?(k.style.display="",Ir=()=>{ht(!1,"user")},k.addEventListener("click",Ir)):k.style.display="none")};Yu(),(()=>{let{clearChatButton:i}=Le;i&&i.addEventListener("click",()=>{V.clearMessages(),Br.clear(),rr(),pr(Le.composerOverlay);try{localStorage.removeItem(Gn),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gn}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Gn)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),d?.clear&&xl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},A.syncFromMetadata(),Oe?.clear(),Ke?.reset(),Ue?.update()})})(),Te&&Te.addEventListener("submit",Fu),U?.addEventListener("keydown",Nu),U?.addEventListener("input",Ou),U?.addEventListener("paste",Uu);let Zu=e.ownerDocument??document;Zu.addEventListener("keydown",_u,!0);let ef="persona-attachment-drop-active",fa=0,Hl=()=>{fa=0,fe.classList.remove(ef)},vn=()=>r.attachments?.enabled===!0&&Mt!==null,tf=i=>{!el(i.dataTransfer)||!vn()||(fa++,fa===1&&fe.classList.add(ef))},of=i=>{!el(i.dataTransfer)||!vn()||(fa--,fa<=0&&Hl())},rf=i=>{!el(i.dataTransfer)||!vn()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},nf=i=>{if(!el(i.dataTransfer)||!vn())return;i.preventDefault(),i.stopPropagation(),Hl();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&Mt.handleFiles(m)},sr=!0;fe.addEventListener("dragenter",tf,sr),fe.addEventListener("dragleave",of,sr),e.addEventListener("dragover",rf,sr),e.addEventListener("drop",nf,sr);let Ss=e.ownerDocument,af=i=>{vn()&&i.preventDefault()},sf=i=>{vn()&&i.preventDefault()};Ss.addEventListener("dragover",af),Ss.addEventListener("drop",sf),$e.push(()=>{Te&&Te.removeEventListener("submit",Fu),U?.removeEventListener("keydown",Nu),U?.removeEventListener("input",Ou),U?.removeEventListener("paste",Uu),Zu.removeEventListener("keydown",_u,!0)}),$e.push(()=>{fe.removeEventListener("dragenter",tf,sr),fe.removeEventListener("dragleave",of,sr),e.removeEventListener("dragover",rf,sr),e.removeEventListener("drop",nf,sr),Ss.removeEventListener("dragover",af),Ss.removeEventListener("drop",sf),Hl()}),$e.push(()=>{V.cancel()}),_t?$e.push(()=>{_t?.destroy()}):$t&&$e.push(()=>{$t?.remove()});let Ht={update(i){let m=r.toolCall,b=r.messageActions,v=r.layout?.messages,P=r.colorScheme,W=r.loadingIndicator,Q=r.iterationDisplay,$=r.features?.showReasoning,X=r.features?.showToolCalls,ae=r.features?.toolCallDisplay,ce=r.features?.reasoningDisplay,oe=r.features?.streamAnimation?.type;r={...r,...i},us(),en(e,r),Xa(e,r),Ja(e,r),Fo(),r.colorScheme!==P&&yu();let ye=Qa.getForInstance(r.plugins);n.length=0,n.push(...ye),T=r.launcher?.enabled??!0,S=r.launcher?.autoExpand??!1,se=r.features?.showReasoning??!0,xe=r.features?.showToolCalls??!0,de=r.features?.scrollToBottom??{};let je=Zt();ee=r.features?.scrollBehavior??{},je!==Zt()&&(sa(),rr()),nu(),no();let yt=Y;if(Y=r.features?.showEventStreamToggle??!1,Y&&!yt){if(Oe||(be=new Ga(Ae),Oe=new ja(He,be),Ke=Ke??new Ka,be.open().then(()=>Oe?.restore()).catch(()=>{}),V.setSSEEventCallback((Z,ot)=>{r.onSSEEvent?.(Z,ot),Ke?.processEvent(Z,ot),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(ot)})})),!at&&_){let Z=r.features?.eventStream?.classNames,ot="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"+(Z?.toggleButton?" "+Z.toggleButton:"");at=y("button",ot),at.style.width="28px",at.style.height="28px",at.style.color=Qt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let St=ne("activity","18px","currentColor",1.5);St&&at.appendChild(St);let Ge=Le.clearChatButtonWrapper,ct=Le.closeButtonWrapper,Vt=Ge||ct;Vt&&Vt.parentNode===_?_.insertBefore(at,Vt):_.appendChild(at),at.addEventListener("click",()=>{ke?Qn():sl()})}}else!Y&&yt&&(Qn(),at&&(at.remove(),at=null),Oe?.clear(),be?.destroy(),Oe=null,be=null,Ke?.reset(),Ke=null);if(r.launcher?.enabled===!1&&_t&&(_t.destroy(),_t=null),r.launcher?.enabled===!1&&$t&&($t.remove(),$t=null),r.launcher?.enabled!==!1&&!_t&&!$t){let{instance:Z,element:ot}=vp({config:r,plugins:n,onToggle:Vu});_t=Z,Z||($t=ot),e.appendChild(ot)}_t&&_t.update(r),N&&r.launcher?.title!==void 0&&(N.textContent=r.launcher.title),K&&r.launcher?.subtitle!==void 0&&(K.textContent=r.launcher.subtitle);let st=r.layout?.header;if(st?.layout!==w&&_){let Z=st?_n(r,st,{showClose:O(),onClose:()=>ht(!1,"user")}):Ko({config:r,showClose:O(),onClose:()=>ht(!1,"user")});mt.replaceHeader(Z),_=mt.header.element,I=mt.header.iconHolder,N=mt.header.headerTitle,K=mt.header.headerSubtitle,k=mt.header.closeButton,w=st?.layout}else if(st&&(I&&(I.style.display=st.showIcon===!1?"none":""),N&&(N.style.display=st.showTitle===!1?"none":""),K&&(K.style.display=st.showSubtitle===!1?"none":""),k&&(k.style.display=st.showCloseButton===!1?"none":""),Le.clearChatButtonWrapper)){let Z=st.showClearChat;if(Z!==void 0){Le.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ot}=Le;ot&&!ot.classList.contains("persona-absolute")&&(Z?ot.classList.remove("persona-ml-auto"):ot.classList.add("persona-ml-auto"))}}let Dt=r.layout?.showHeader!==!1;_&&(_.style.display=Dt?"":"none");let D=r.layout?.showFooter!==!1;j&&(j.style.display=D?"":"none"),cn(),no(),T!==H?T?ht(S,"auto"):(z=!0,pa()):S!==B&&ht(S,"auto"),B=S,H=T,ua(),Yu();let _e=JSON.stringify(i.toolCall)!==JSON.stringify(m),Tt=JSON.stringify(r.messageActions)!==JSON.stringify(b),ut=JSON.stringify(r.layout?.messages)!==JSON.stringify(v),wt=r.loadingIndicator?.render!==W?.render||r.loadingIndicator?.renderIdle!==W?.renderIdle||r.loadingIndicator?.showBubble!==W?.showBubble,bt=r.iterationDisplay!==Q,qt=(r.features?.showReasoning??!0)!==($??!0)||(r.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(r.features?.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify(r.features?.reasoningDisplay)!==JSON.stringify(ce);(_e||Tt||ut||wt||bt||qt)&&V&&(fl++,ia(he,V.getMessages(),De));let ft=r.features?.streamAnimation?.type;if(ft!==oe&&ft&&ft!=="none"){let Z=Nn(ft,r.features?.streamAnimation?.plugins);Z&&Wi(Z,e)}let pe=r.launcher??{},At=pe.headerIconHidden??!1,Gt=r.layout?.header?.showIcon,Ft=At||Gt===!1,nt=pe.headerIconName,ze=pe.headerIconSize??"48px";if(I){let Z=fe.querySelector(".persona-border-b-persona-divider"),ot=Z?.querySelector(".persona-flex-col");if(Ft)I.style.display="none",Z&&ot&&!Z.contains(ot)&&Z.insertBefore(ot,Z.firstChild);else{if(I.style.display="",I.style.height=ze,I.style.width=ze,Z&&ot&&(Z.contains(I)?I.nextSibling!==ot&&(I.remove(),Z.insertBefore(I,ot)):Z.insertBefore(I,ot)),nt){let Ge=parseFloat(ze)||24,ct=ne(nt,Ge*.6,"currentColor",1);ct?I.replaceChildren(ct):I.textContent=pe.agentIconText??"\u{1F4AC}"}else if(pe.iconUrl){let Ge=I.querySelector("img");if(Ge)Ge.src=pe.iconUrl,Ge.style.height=ze,Ge.style.width=ze;else{let ct=document.createElement("img");ct.src=pe.iconUrl,ct.alt="",ct.className="persona-rounded-xl persona-object-cover",ct.style.height=ze,ct.style.width=ze,I.replaceChildren(ct)}}else{let Ge=I.querySelector("svg"),ct=I.querySelector("img");(Ge||ct)&&I.replaceChildren(),I.textContent=pe.agentIconText??"\u{1F4AC}"}let St=I.querySelector("img");St&&(St.style.height=ze,St.style.width=ze)}}let Ze=r.layout?.header?.showTitle,Pt=r.layout?.header?.showSubtitle;if(N&&(N.style.display=Ze===!1?"none":""),K&&(K.style.display=Pt===!1?"none":""),k){r.layout?.header?.showCloseButton===!1?k.style.display="none":k.style.display="";let ot=pe.closeButtonSize??"32px",St=pe.closeButtonPlacement??"inline";k.style.height=ot,k.style.width=ot;let{closeButtonWrapper:Ge}=Le,ct=St==="top-right",Vt=Ge?.classList.contains("persona-absolute");if(Ge&&ct!==Vt)if(Ge.remove(),ct)Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(Ge);else{let Ve=pe.clearChat?.placement??"inline",Nt=pe.clearChat?.enabled??!0;Ge.className=Nt&&Ve==="inline"?"":"persona-ml-auto";let to=fe.querySelector(".persona-border-b-persona-divider");to&&to.appendChild(Ge)}if(k.style.color=pe.closeButtonColor||Qt.actionIconColor,pe.closeButtonBackgroundColor?(k.style.backgroundColor=pe.closeButtonBackgroundColor,k.classList.remove("hover:persona-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let Ve=pe.closeButtonBorderWidth||"0px",Nt=pe.closeButtonBorderColor||"transparent";k.style.border=`${Ve} solid ${Nt}`,k.classList.remove("persona-border-none")}else k.style.border="",k.classList.add("persona-border-none");pe.closeButtonBorderRadius?(k.style.borderRadius=pe.closeButtonBorderRadius,k.classList.remove("persona-rounded-full")):(k.style.borderRadius="",k.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(k.style.paddingLeft=pe.closeButtonPaddingX,k.style.paddingRight=pe.closeButtonPaddingX):(k.style.paddingLeft="",k.style.paddingRight=""),pe.closeButtonPaddingY?(k.style.paddingTop=pe.closeButtonPaddingY,k.style.paddingBottom=pe.closeButtonPaddingY):(k.style.paddingTop="",k.style.paddingBottom="");let so=pe.closeButtonIconName??"x",wo=pe.closeButtonIconText??"\xD7";k.innerHTML="";let Kt=ne(so,"28px","currentColor",1);Kt?k.appendChild(Kt):k.textContent=wo;let Et=pe.closeButtonTooltipText??"Close chat",io=pe.closeButtonShowTooltip??!0;if(k.setAttribute("aria-label",Et),Ge&&(Ge._cleanupTooltip&&(Ge._cleanupTooltip(),delete Ge._cleanupTooltip),io&&Et)){let Ve=null,Nt=()=>{if(Ve||!k)return;let qr=k.ownerDocument,ya=qr.body;if(!ya)return;Ve=Io(qr,"div","persona-clear-chat-tooltip"),Ve.textContent=Et;let ba=Io(qr,"div");ba.className="persona-clear-chat-tooltip-arrow",Ve.appendChild(ba);let Vr=k.getBoundingClientRect();Ve.style.position="fixed",Ve.style.zIndex=String(vr),Ve.style.left=`${Vr.left+Vr.width/2}px`,Ve.style.top=`${Vr.top-8}px`,Ve.style.transform="translate(-50%, -100%)",ya.appendChild(Ve)},to=()=>{Ve&&Ve.parentNode&&(Ve.parentNode.removeChild(Ve),Ve=null)};Ge.addEventListener("mouseenter",Nt),Ge.addEventListener("mouseleave",to),k.addEventListener("focus",Nt),k.addEventListener("blur",to),Ge._cleanupTooltip=()=>{to(),Ge&&(Ge.removeEventListener("mouseenter",Nt),Ge.removeEventListener("mouseleave",to)),k&&(k.removeEventListener("focus",Nt),k.removeEventListener("blur",to))}}}let{clearChatButton:Be,clearChatButtonWrapper:et}=Le;if(Be){let Z=pe.clearChat??{},ot=Z.enabled??!0,St=r.layout?.header?.showClearChat,Ge=St!==void 0?St:ot,ct=Z.placement??"inline";if(et){et.style.display=Ge?"":"none";let{closeButtonWrapper:Vt}=Le;!q()&&Vt&&!Vt.classList.contains("persona-absolute")&&(Ge?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let so=ct==="top-right",wo=et.classList.contains("persona-absolute");if(!q()&&so!==wo&&Ge){if(et.remove(),so)et.className="persona-absolute persona-top-4 persona-z-50",et.style.right="48px",fe.style.position="relative",fe.appendChild(et);else{et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",et.style.right="";let Et=fe.querySelector(".persona-border-b-persona-divider"),io=Le.closeButtonWrapper;Et&&io&&io.parentElement===Et?Et.insertBefore(et,io):Et&&Et.appendChild(et)}let Kt=Le.closeButtonWrapper;Kt&&!Kt.classList.contains("persona-absolute")&&(so?Kt.classList.add("persona-ml-auto"):Kt.classList.remove("persona-ml-auto"))}}if(Ge){if(!q()){let Ve=Z.size??"32px";Be.style.height=Ve,Be.style.width=Ve}let Vt=Z.iconName??"refresh-cw",so=Z.iconColor??"";Be.style.color=so||Qt.actionIconColor,Be.innerHTML="";let wo=q()?"14px":"20px",Kt=ne(Vt,wo,"currentColor",2);if(Kt&&Be.appendChild(Kt),Z.backgroundColor?(Be.style.backgroundColor=Z.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let Ve=Z.borderWidth||"0px",Nt=Z.borderColor||"transparent";Be.style.border=`${Ve} solid ${Nt}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");Z.borderRadius?(Be.style.borderRadius=Z.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),Z.paddingX?(Be.style.paddingLeft=Z.paddingX,Be.style.paddingRight=Z.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),Z.paddingY?(Be.style.paddingTop=Z.paddingY,Be.style.paddingBottom=Z.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let Et=Z.tooltipText??"Clear chat",io=Z.showTooltip??!0;if(Be.setAttribute("aria-label",Et),et&&(et._cleanupTooltip&&(et._cleanupTooltip(),delete et._cleanupTooltip),io&&Et)){let Ve=null,Nt=()=>{if(Ve||!Be)return;let qr=Be.ownerDocument,ya=qr.body;if(!ya)return;Ve=Io(qr,"div","persona-clear-chat-tooltip"),Ve.textContent=Et;let ba=Io(qr,"div");ba.className="persona-clear-chat-tooltip-arrow",Ve.appendChild(ba);let Vr=Be.getBoundingClientRect();Ve.style.position="fixed",Ve.style.zIndex=String(vr),Ve.style.left=`${Vr.left+Vr.width/2}px`,Ve.style.top=`${Vr.top-8}px`,Ve.style.transform="translate(-50%, -100%)",ya.appendChild(Ve)},to=()=>{Ve&&Ve.parentNode&&(Ve.parentNode.removeChild(Ve),Ve=null)};et.addEventListener("mouseenter",Nt),et.addEventListener("mouseleave",to),Be.addEventListener("focus",Nt),Be.addEventListener("blur",to),et._cleanupTooltip=()=>{to(),et&&(et.removeEventListener("mouseenter",Nt),et.removeEventListener("mouseleave",to)),Be&&(Be.removeEventListener("focus",Nt),Be.removeEventListener("blur",to))}}}}let ao=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ya],Nr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[dn.message,dn.messageAndClick];A=Za({parsers:ao,handlers:Nr,getSessionMetadata:h,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),De=Wg(r,A,Ee),V.updateConfig(r),ia(he,V.getMessages(),De),ul(),Ru(),Al(V.isStreaming());let lf=r.voiceRecognition?.enabled===!0,Ts=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rt=r.voiceRecognition?.provider?.type==="runtype";if(lf&&(Ts||Rt))if(!G||!qe){let Z=Gh(r.voiceRecognition,r.sendButton);Z&&(G=Z.micButton,qe=Z.micButtonWrapper,Pe.insertBefore(qe,We),G.addEventListener("click",As),G.disabled=V.isStreaming())}else{let Z=r.voiceRecognition??{},ot=r.sendButton??{},St=Z.iconName??"mic",Ge=ot.size??"40px",ct=Z.iconSize??Ge,Vt=parseFloat(ct)||24;G.style.width=ct,G.style.height=ct,G.style.minWidth=ct,G.style.minHeight=ct;let so=Z.iconColor??ot.textColor??"currentColor";G.innerHTML="";let wo=ne(St,Vt,so,2);wo?G.appendChild(wo):G.textContent="\u{1F3A4}";let Kt=Z.backgroundColor??ot.backgroundColor;Kt?G.style.backgroundColor=Kt:G.style.backgroundColor="",so?G.style.color=so:G.style.color="var(--persona-text, #111827)",Z.borderWidth?(G.style.borderWidth=Z.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Z.borderColor?G.style.borderColor=Z.borderColor:G.style.borderColor="",Z.paddingX?(G.style.paddingLeft=Z.paddingX,G.style.paddingRight=Z.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Z.paddingY?(G.style.paddingTop=Z.paddingY,G.style.paddingBottom=Z.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Et=qe?.querySelector(".persona-send-button-tooltip"),io=Z.tooltipText??"Start voice recognition";if((Z.showTooltip??!1)&&io)if(Et)Et.textContent=io,Et.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=io,qe?.insertBefore(Nt,G)}else Et&&(Et.style.display="none");qe.style.display="",G.disabled=V.isStreaming()}else G&&qe&&(qe.style.display="none",r.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()&&V.toggleVoice():Po&&ar());if(r.attachments?.enabled===!0)if(!Ie||!ve){let Z=r.attachments??{},St=(r.sendButton??{}).size??"40px";Qe||(Qe=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Qe.style.display="none",Te.insertBefore(Qe,U)),Me||(Me=document.createElement("input"),Me.type="file",Me.accept=(Z.allowedTypes??jo).join(","),Me.multiple=(Z.maxFiles??4)>1,Me.style.display="none",Me.setAttribute("aria-label","Attach files"),Te.insertBefore(Me,U)),Ie=y("div","persona-send-button-wrapper"),ve=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ve.type="button",ve.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let Ge=Z.buttonIconName??"paperclip",ct=St,Vt=parseFloat(ct)||40,so=Math.round(Vt*.6);ve.style.width=ct,ve.style.height=ct,ve.style.minWidth=ct,ve.style.minHeight=ct,ve.style.fontSize="18px",ve.style.lineHeight="1",ve.style.backgroundColor="transparent",ve.style.color="var(--persona-primary, #111827)",ve.style.border="none",ve.style.borderRadius="6px",ve.style.transition="background-color 0.15s ease",ve.addEventListener("mouseenter",()=>{ve.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ve.addEventListener("mouseleave",()=>{ve.style.backgroundColor="transparent"});let wo=ne(Ge,so,"currentColor",1.5);wo?ve.appendChild(wo):ve.textContent="\u{1F4CE}",ve.addEventListener("click",io=>{io.preventDefault(),Me?.click()}),Ie.appendChild(ve);let Kt=Z.buttonTooltipText??"Attach file",Et=y("div","persona-send-button-tooltip");Et.textContent=Kt,Ie.appendChild(Et),tt.append(Ie),!Mt&&Me&&Qe&&(Mt=Zr.fromConfig(Z),Mt.setPreviewsContainer(Qe),Me.addEventListener("change",async()=>{Mt&&Me?.files&&(await Mt.handleFileSelect(Me.files),Me.value="")})),fe.querySelector(".persona-attachment-drop-overlay")||fe.appendChild(Dg(Z.dropOverlay))}else{Ie.style.display="";let Z=r.attachments??{};Me&&(Me.accept=(Z.allowedTypes??jo).join(","),Me.multiple=(Z.maxFiles??4)>1),Mt&&Mt.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}else Ie&&(Ie.style.display="none"),Mt&&Mt.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ot=r.sendButton??{},ma=Ot.useIcon??!1,Es=Ot.iconText??"\u2191",Cn=Ot.iconName,ga=Ot.tooltipText??"Send message",Wl=Ot.showTooltip??!1,_r=Ot.size??"40px",Uo=Ot.backgroundColor,Ur=Ot.textColor;if(ma){if(te.style.width=_r,te.style.height=_r,te.style.minWidth=_r,te.style.minHeight=_r,te.style.fontSize="18px",te.style.lineHeight="1",te.innerHTML="",Ur?te.style.color=Ur:te.style.color="var(--persona-button-primary-fg, #ffffff)",Cn){let Z=parseFloat(_r)||24,ot=Ur?.trim()||"currentColor",St=ne(Cn,Z,ot,2);St?te.appendChild(St):te.textContent=Es}else te.textContent=Es;te.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Uo?(te.style.backgroundColor=Uo,te.classList.remove("persona-bg-persona-primary")):(te.style.backgroundColor="",te.classList.add("persona-bg-persona-primary"))}else te.textContent=r.copy?.sendButtonLabel??"Send",te.style.width="",te.style.height="",te.style.minWidth="",te.style.minHeight="",te.style.fontSize="",te.style.lineHeight="",te.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",Uo?(te.style.backgroundColor=Uo,te.classList.remove("persona-bg-persona-accent")):te.classList.add("persona-bg-persona-accent"),Ur?te.style.color=Ur:te.classList.add("persona-text-white");Ot.borderWidth?(te.style.borderWidth=Ot.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),Ot.borderColor?te.style.borderColor=Ot.borderColor:te.style.borderColor="",Ot.paddingX?(te.style.paddingLeft=Ot.paddingX,te.style.paddingRight=Ot.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),Ot.paddingY?(te.style.paddingTop=Ot.paddingY,te.style.paddingBottom=Ot.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let ha=We?.querySelector(".persona-send-button-tooltip");if(Wl&&ga)if(ha)ha.textContent=ga,ha.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=ga,We?.insertBefore(Z,te)}else ha&&(ha.style.display="none");let ks=r.layout?.contentMaxWidth??(q()?r.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ks?(he.style.maxWidth=ks,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%",Te&&(Te.style.maxWidth=ks,Te.style.marginLeft="auto",Te.style.marginRight="auto"),xt&&(xt.style.maxWidth=ks,xt.style.marginLeft="auto",xt.style.marginRight="auto")):(he.style.maxWidth="",he.style.marginLeft="",he.style.marginRight="",he.style.width="",Te&&(Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight=""),xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""));let ir=r.statusIndicator??{},ey=ir.visible??!0;if(R.style.display=ey?"":"none",V){let Z=V.getStatus();Lt(R,(St=>St==="idle"?ir.idleText??Wt.idle:St==="connecting"?ir.connectingText??Wt.connecting:St==="connected"?ir.connectedText??Wt.connected:St==="error"?ir.errorText??Wt.error:Wt[St])(Z),ir,Z)}R.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ty=ir.align==="left"?"persona-text-left":ir.align==="center"?"persona-text-center":"persona-text-right";R.classList.add(ty)},open(){O()&&ht(!0,"api")},close(){O()&&ht(!1,"api")},toggle(){O()&&ht(!z,"api")},reconnect(){V.reconnectNow()},clearChat(){Do=!1,V.clearMessages(),Br.clear(),rr();try{localStorage.removeItem(Gn),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gn}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Gn)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&xl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},A.syncFromMetadata(),Oe?.clear(),Ke?.reset(),Ue?.update()},setMessage(i){return!U||V.isStreaming()?!1:(!z&&O()&&ht(!0,"system"),U.value=i,U.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(V.isStreaming())return!1;let m=i?.trim()||U.value.trim();return m?(!z&&O()&&ht(!0,"system"),U.value="",U.style.height="auto",V.sendMessage(m),!0):!1},startVoiceRecognition(){return V.isStreaming()?!1:r.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()||(!z&&O()&&ht(!0,"system"),Xe.manuallyDeactivated=!1,Co(),V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Oo("user"),V.isVoiceActive()&&xn()})),!0):Po?!0:qu()?(!z&&O()&&ht(!0,"system"),Xe.manuallyDeactivated=!1,Co(),Cs("user"),!0):!1},stopVoiceRecognition(){return r.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,Co(),Oo("user"),_o()}),!0):!1:Po?(Xe.manuallyDeactivated=!0,Co(),ar("user"),!0):!1},injectMessage(i){return!z&&O()&&ht(!0,"system"),V.injectMessage(i)},injectAssistantMessage(i){!z&&O()&&ht(!0,"system");let m=V.injectAssistantMessage(i);return le&&(le=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),m},injectUserMessage(i){return!z&&O()&&ht(!0,"system"),V.injectUserMessage(i)},injectSystemMessage(i){return!z&&O()&&ht(!0,"system"),V.injectSystemMessage(i)},injectMessageBatch(i){return!z&&O()&&ht(!0,"system"),V.injectMessageBatch(i)},injectComponentDirective(i){return!z&&O()&&ht(!0,"system"),V.injectComponentDirective(i)},injectTestMessage(i){!z&&O()&&ht(!0,"system"),V.injectTestEvent(i)},async connectStream(i,m){return V.connectStream(i,m)},__pushEventStreamEvent(i){Oe&&(Ke?.processEvent(i.type,i.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!Y||!Oe||sl()},hideEventStream(){ke&&Qn()},isEventStreamVisible(){return ke},showArtifacts(){Yt(r)&&(Do=!1,pn=!0,Fo(),Ye?.setMobileOpen(!0))},hideArtifacts(){Yt(r)&&(Do=!0,Fo())},upsertArtifact(i){return Yt(r)?(jr(r.features?.artifacts,i.artifactType)==="panel"&&(Do=!1,pn=!0),V.upsertArtifact(i)):null},selectArtifact(i){Yt(r)&&V.selectArtifact(i)},clearArtifacts(){Yt(r)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return T&&!z&&!q()||!U?!1:(U.focus(),!0)},async resolveApproval(i,m,b){let P=V.getMessages().find(W=>W.variant==="approval"&&W.approval?.id===i);if(!P?.approval)throw new Error(`Approval not found: ${i}`);if(P.approval.toolType==="webmcp"){V.resolveWebMcpApproval(P.id,m);return}return V.resolveApproval(P.approval,m,b)},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){C(i)},on(i,m){return l.on(i,m)},off(i,m){l.off(i,m)},isOpen(){return O()&&z},isVoiceActive(){return Xe.active},toggleReadAloud(i){V.toggleReadAloud(i)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(i){return V.getReadAloudState(i)},onReadAloudChange(i){return V.onReadAloudChange(i)},getState(){return{open:O()&&z,launcherEnabled:T,voiceActive:Xe.active,streaming:V.isStreaming()}},showCSATFeedback(i){!z&&O()&&ht(!0,"system");let m=he.querySelector(".persona-feedback-container");m&&m.remove();let b=Yi({onSubmit:async(v,P)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(v,P),i?.onSubmit?.(v,P)},onDismiss:i?.onDismiss,...i});he.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!z&&O()&&ht(!0,"system");let m=he.querySelector(".persona-feedback-container");m&&m.remove();let b=Zi({onSubmit:async(v,P)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(v,P),i?.onSubmit?.(v,P)},onDismiss:i?.onDismiss,...i});he.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return V.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return V.submitNPSFeedback(i,m)},destroy(){El(),Dr!=null&&(clearInterval(Dr),Dr=null),$e.forEach(i=>i()),Se.remove(),lt?.remove(),_t?.destroy(),$t?.remove(),Ir&&k.removeEventListener("click",Ir)}};if(((o?.debugTools??!1)||!!r.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Ht,getMessages:Ht.getMessages,getStatus:Ht.getStatus,getMetadata:Ht.getPersistentMetadata,updateMetadata:Ht.updatePersistentMetadata,clearHistory:()=>Ht.clearChat(),setVoiceActive:b=>b?Ht.startVoiceRecognition():Ht.stopVoiceRecognition()};window.AgentWidgetBrowser=m,$e.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=$=>{let X=$.detail;(!X?.instanceId||X.instanceId===i)&&Ht.focusInput()};if(window.addEventListener("persona:focusInput",m),$e.push(()=>{window.removeEventListener("persona:focusInput",m)}),Y){let $=ae=>{let ce=ae.detail;(!ce?.instanceId||ce.instanceId===i)&&Ht.showEventStream()},X=ae=>{let ce=ae.detail;(!ce?.instanceId||ce.instanceId===i)&&Ht.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",X),$e.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",X)})}let b=$=>{let X=$.detail;(!X?.instanceId||X.instanceId===i)&&Ht.showArtifacts()},v=$=>{let X=$.detail;(!X?.instanceId||X.instanceId===i)&&Ht.hideArtifacts()},P=$=>{let X=$.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Ht.upsertArtifact(X.artifact)},W=$=>{let X=$.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Ht.selectArtifact(X.id)},Q=$=>{let X=$.detail;(!X?.instanceId||X.instanceId===i)&&Ht.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",Q),$e.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",Q)})}let go=Hv(r.persistState);if(go&&O()){let i=Wv(go.storage),m=`${go.keyPrefix}widget-open`,b=`${go.keyPrefix}widget-voice`,v=`${go.keyPrefix}widget-voice-mode`;if(i){let P=go.persist?.openState&&i.getItem(m)==="true",W=go.persist?.voiceState&&i.getItem(b)==="true",Q=go.persist?.voiceState&&i.getItem(v)==="true";if(P&&setTimeout(()=>{Ht.open(),setTimeout(()=>{if(W||Q)Ht.startVoiceRecognition();else if(go.persist?.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),go.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(m,"true")}),l.on("widget:closed",()=>{i.setItem(m,"false")})),go.persist?.voiceState&&(l.on("voice:state",$=>{i.setItem(b,$.active?"true":"false")}),l.on("user:message",$=>{i.setItem(v,$.viaVoice?"true":"false")})),go.clearOnChatClear){let $=()=>{i.removeItem(m),i.removeItem(b),i.removeItem(v)},X=()=>$();window.addEventListener("persona:clear-chat",X),$e.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(g&&O()&&setTimeout(()=>{Ht.open()},0),hn(),!Sh){let i=An(()=>{V&&(fl++,Br.clear(),ia(he,V.getMessages(),De))});$e.push(i)}return Ht};var Fg=(e,t)=>{let o=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(r)return Math.max(0,parseFloat(r[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(o);return n?Math.max(0,t*parseFloat(n[1])/100):420},Dv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Fv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Ov=(e,t)=>{let o=e.parentElement;if(!o)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(r);let n=r.offsetHeight>0;r.style.height="100%";let a=r.offsetHeight>0;r.remove(),!(!n||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Og=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0"},Up=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=""},Ng=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Up(e)},Op=e=>{e.style.transition=""},Np=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="",e.style.marginLeft=""},_p=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ol=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Nv=(e,t,o,r,n)=>{n?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,r),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(r))},_v=(e,t,o,r,n,a)=>{let s=a?t:e;n==="left"?s.firstElementChild!==r&&s.replaceChildren(r,o):s.lastElementChild!==r&&s.replaceChildren(o,r)},Uv=e=>{let t=yr(e),o=t.components?.panel,r=(n,a)=>n==null||n===""?a:Jt(t,n)??n;return{inset:r(o?.inset,gi),canvasBackground:r(o?.canvasBackground,hi)}},_g=(e,t,o,r)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=r},qv=(e,t,o,r,n,a,s,l)=>{let p=oo(a),d=p.reveal==="push",c=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";Nv(e,t,o,r,d),_v(e,t,o,r,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.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",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=a?.launcher?.mobileFullscreen??!0,C=a?.launcher?.mobileBreakpoint??640,M=f!=null?f.innerWidth<=C:!1;if(h&&M&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Np(t),Op(r),Ng(r),_p(o),ol(n,r),_g(r,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String(a?.launcher?.zIndex??zt),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ng(r),Dv(r,p.maxHeight),_g(r,c&&s,u,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Np(t),Op(r),_p(o),ol(n,r);let A=p.animate?"transform 180ms ease":"none",T=p.side==="right"?"translateX(100%)":"translateX(-100%)",S=s?"translateX(0)":T;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=p.width,r.style.maxWidth=p.width,r.style.minWidth=p.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=A,r.style.transform=S,r.style.pointerEvents=s?"auto":"none",r.style.zIndex="2",p.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Op(r),Up(r),ol(n,r);let A=Fg(p.width,e.clientWidth),T=Math.max(0,e.clientWidth),S=p.animate?"margin-left 180ms ease":"none",E=p.side==="right"?s?-A:0:s?0:-A;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${T+A}px`,t.style.transition=S,t.style.marginLeft=`${E}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${T}px`,o.style.maxWidth=`${T}px`,o.style.minWidth=`${T}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=p.width,r.style.minWidth=p.width,r.style.maxWidth=p.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Np(t),Up(r),_p(o),ol(n,r);let A=p.reveal==="emerge";A?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let T=s?p.width:"0px",S=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",E=!s;if(r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${T}`,r.style.width=T,r.style.maxWidth=T,r.style.minWidth=T,r.style.minHeight="0",Fv(r,p.maxHeight),r.style.overflow=A||E?"hidden":"visible",r.style.transition=S,A){r.style.alignItems=p.side==="right"?"flex-start":"flex-end";let B=c?`calc(${Fg(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;n.style.width=B,n.style.minWidth=B,n.style.maxWidth=B,n.style.boxSizing="border-box"}}},Vv=(e,t)=>{let o=e.ownerDocument.createElement("div");return Og(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(r){Og(o,r)},destroy(){o.remove()}}},zv=(e,t)=>{let{ownerDocument:o}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=o.createElement("div"),l=o.createElement("div"),p=o.createElement("div"),d=o.createElement("aside"),c=o.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),r.insertBefore(s,e),p.appendChild(e);let g=null,f=()=>{g?.disconnect(),g=null},h=null,C=()=>{h=t?.launcher?.detachedPanel===!0?Uv(t):null};C();let M=()=>{qv(s,l,p,d,c,t,u,h)},L=null,A=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=Hn(()=>{C(),M()}))},T=()=>{f(),oo(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{M()}),g.observe(s)))},S=!1,E=()=>{M(),T(),u&&!S&&s.dataset.personaDockMobileFullscreen!=="true"&&(S=!0,Ov(s,oo(t)))},B=s.ownerDocument.defaultView,H=()=>{E()};return B?.addEventListener("resize",H),oo(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),s.appendChild(l)):(s.appendChild(p),s.appendChild(d)),E(),A(),{mode:"docked",host:c,shell:s,syncWidgetState(w){let F=w.launcherEnabled?w.open:!0;u!==F&&(u=F,E())},updateConfig(w){t=w,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),E(),A()},destroy(){B?.removeEventListener("resize",H),L?.(),L=null,f(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),s.remove()}}},ts=(e,t)=>It(t)?zv(e,t):Vv(e,t);var $v=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Ug=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let r=o.cloneNode(!0);e.insertBefore(r,e.firstChild)},qg=e=>{let t=$v(e.target),o=e.useShadowDom===!0,r=t.ownerDocument,n=e.config,a=ts(t,n),s,l=[],p=(M,L)=>{let T=!(L?.launcher?.enabled??!0)||It(L),S=r.createElement("div");if(S.setAttribute("data-persona-root","true"),T&&(S.style.height="100%",S.style.display="flex",S.style.flexDirection="column",S.style.flex="1",S.style.minHeight="0"),o){let E=M.attachShadow({mode:"open"});E.appendChild(S),Ug(E,r)}else M.appendChild(S),Ug(M,r);return t.id&&S.setAttribute("data-persona-instance",t.id),S},d=()=>{a.syncWidgetState(s.getState())},c=()=>{l.forEach(M=>M()),l=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},u=()=>{let M=p(a.host,n);s=tl(M,n,{debugTools:e.debugTools}),c()},g=()=>{l.forEach(M=>M()),l=[],s.destroy()};u(),e.onChatReady?.();let f=M=>{g(),a.destroy(),a=ts(t,M),n=M,u()},h={update(M){let L={...n,...M,launcher:{...n?.launcher??{},...M?.launcher??{},dock:{...n?.launcher?.dock??{},...M?.launcher?.dock??{}}}},A=It(n),T=It(L),S=Tr(n),E=Tr(L);if(A!==T||S!==E){f(L);return}n=L,a.updateConfig(n),s.update(M),d()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(h,{get(M,L,A){if(L==="host")return a.host;if(L in M)return Reflect.get(M,L,A);let T=s[L];return typeof T=="function"?T.bind(s):T}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};var Gg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),jv=new Set(["button","a","input","select","textarea","details","summary"]),Gv=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),qp=/\b(product|card|item|listing|result)\b/i,zp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Kv=3e3,Xv=100;function Kg(e){let t=typeof e.className=="string"?e.className:"";if(qp.test(t)||e.id&&qp.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let r=e.attributes[o];if(r.name.startsWith("data-")&&qp.test(r.value))return!0}return!1}function Xg(e){return zp.test((e.textContent??"").trim())}function Jg(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let r=t[o].getAttribute("href")??"";if(r&&r!=="#"&&!r.toLowerCase().startsWith("javascript:"))return!0}return!1}function Jv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Vg(e){let t=e.match(zp);return t?t[0]:null}function zg(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let r=t.getAttribute("href");return{title:t.textContent.trim(),href:r&&r!=="#"?r:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function Qv(e){let t=[],o=r=>{let n=r.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(r=>o(r.textContent??"")),e.querySelectorAll('[role="button"]').forEach(r=>o(r.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{o(r.value??"")}),t.slice(0,6)}var Yv="commerce-card",Zv="result-card";function $g(e){return!Kg(e)||!Xg(e)||!Jg(e)&&!Jv(e)?0:5200}function jg(e){return!Kg(e)||Xg(e)||!Jg(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var $p=[{id:Yv,scoreElement(e){return $g(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let r=o.text.trim();return!!(r.length===0||zp.test(r)&&r.length<32)}return!0},formatSummary(e,t){if($g(e)===0)return null;let{title:o,href:r}=zg(e),n=Vg((e.textContent??"").trim())??Vg(t.text)??"",a=Qv(e);return[r&&o?`[${o}](${r})${n?`: ${n}`:""}`:o?`${o}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
136
|
+
`)}},{id:Zv,scoreElement(e){return jg(e)},formatSummary(e,t){if(jg(e)===0)return null;let{title:o,href:r}=zg(e);return[r&&o?`[${o}](${r})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
137
|
+
`)}}];function eC(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function tC(e){let t=e.options??{},o=t.maxElements??e.maxElements??80,r=t.excludeSelector??e.excludeSelector??".persona-host",n=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,l=t.mode??"structured",p=t.maxCandidates??Math.max(500,o*10),d=e.rules??$p;return l==="simple"&&e.rules&&e.rules.length>0?(eC(),d=[]):l==="simple"&&(d=[]),{mode:l,maxElements:o,maxCandidates:p,excludeSelector:r,maxTextLength:n,visibleOnly:a,root:s,rules:d}}function Vp(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var oC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function rC(e){let t=e.tagName.toLowerCase(),o=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||o==="textbox"||o==="combobox"||o==="listbox"||o==="spinbutton"?"input":t==="button"||o==="button"||jv.has(t)||o&&Gv.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Qg(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function nC(e){let t={},o=e.id;o&&(t.id=o);let r=e.getAttribute("href");r&&(t.href=r);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let l=e.getAttribute("name");l&&(t.name=l);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function jp(e){let t=e.tagName.toLowerCase();if(e.id){let n=`#${Vp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}}for(let n of oC){let a=e.getAttribute(n);if(a){let s=`${t}[${n}="${Vp(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}}let o=Array.from(e.classList).filter(n=>n&&!n.startsWith("persona-")).slice(0,3);if(o.length>0){let n=`${t}.${o.map(s=>Vp(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(n).length===1)return n}catch{}let a=e.parentElement;if(a){let l=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let p=`${n}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let r=e.parentElement;if(r){let a=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function aC(e){return e==="static"?Xv:Kv}function Yg(e,t){let o=e.tagName.toLowerCase(),r=(e.textContent??"").trim().substring(0,t);return{selector:jp(e),tagName:o,text:r,role:e.getAttribute("role"),interactivity:rC(e),attributes:nC(e)}}function sC(e,t,o,r){let n=aC(t.interactivity),a=null;for(let s of o){let l=s.scoreElement(e,t,r);l>0&&(n+=l,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function iC(e,t){for(let o of e)if(t.el!==o.el&&o.formattingRule?.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function lC(e,t){let o={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=s.currentNode;for(;l&&n.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let d=l,c=d.tagName.toLowerCase();if(Gg.has(c)){l=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Qg(d)){l=s.nextNode();continue}let u=Yg(d,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(M=>M==="role");if(!g&&!f){l=s.nextNode();continue}if(r.has(u.selector)){l=s.nextNode();continue}r.add(u.selector);let{score:h,formattingRule:C}=sC(d,u,e.rules,o);n.push({el:d,domIndex:a,enriched:u,score:h,formattingRule:C}),a+=1}l=s.nextNode()}n.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return u!==g?u-g:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of n){if(p.length>=e.maxElements)break;iC(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let g=d.formattingRule.formatSummary(d.el,d.enriched,o);g&&(c=g)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function dC(e,t){let o=[],r=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&o.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let p=a,d=p.tagName.toLowerCase();if(Gg.has(d)){a=n.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!Qg(p)){a=n.nextNode();continue}let c=Yg(p,e.maxTextLength),u=c.text.length>0,g=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!g){a=n.nextNode();continue}r.has(c.selector)||(r.add(c.selector),o.push(c))}a=n.nextNode()}let s=[],l=[];for(let p of o)p.interactivity!=="static"?s.push(p):l.push(p);return[...s,...l].slice(0,e.maxElements)}function Zg(e={}){let t=tC(e),o=t.root??document.body;return o?t.mode==="simple"?dC(t,o):lC(t,o):[]}var rl=100;function eh(e,t={}){if(e.length===0)return"No page elements found.";let o=t.mode??"structured",r=[];if(o==="structured"){let a=e.map(s=>s.formattedSummary).filter(s=>!!s&&s.length>0);a.length>0&&r.push(`Structured summaries:
|
|
138
|
+
${a.map(s=>`- ${s.split(`
|
|
116
139
|
`).join(`
|
|
117
140
|
`)}`).join(`
|
|
118
|
-
`)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let
|
|
119
|
-
${
|
|
120
|
-
`)}`)}if(n.navigable.length>0){let
|
|
121
|
-
${
|
|
122
|
-
`)}`)}if(n.input.length>0){let
|
|
123
|
-
${
|
|
124
|
-
`)}`)}if(n.static.length>0){let
|
|
125
|
-
${
|
|
126
|
-
`)}`)}return
|
|
141
|
+
`)}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let a of e)o==="structured"&&a.formattedSummary||n[a.interactivity].push(a);if(n.clickable.length>0){let a=n.clickable.map(s=>`- ${s.selector}: "${s.text.substring(0,rl)}" (clickable)`);r.push(`Interactive elements:
|
|
142
|
+
${a.join(`
|
|
143
|
+
`)}`)}if(n.navigable.length>0){let a=n.navigable.map(s=>`- ${s.selector}${s.attributes.href?`[href="${s.attributes.href}"]`:""}: "${s.text.substring(0,rl)}" (navigable)`);r.push(`Navigation links:
|
|
144
|
+
${a.join(`
|
|
145
|
+
`)}`)}if(n.input.length>0){let a=n.input.map(s=>`- ${s.selector}${s.attributes.type?`[type="${s.attributes.type}"]`:""}: "${s.text.substring(0,rl)}" (input)`);r.push(`Form inputs:
|
|
146
|
+
${a.join(`
|
|
147
|
+
`)}`)}if(n.static.length>0){let a=n.static.map(s=>`- ${s.selector}: "${s.text.substring(0,rl)}"`);r.push(`Content:
|
|
148
|
+
${a.join(`
|
|
149
|
+
`)}`)}return r.join(`
|
|
127
150
|
|
|
128
|
-
`)}function
|
|
151
|
+
`)}function th(){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 oh(){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 rh(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let o={...t.palette};return e.colors?.primary&&(o.colors={...o.colors,primary:{50:Wo(e.colors.primary,.95),100:Wo(e.colors.primary,.9),200:Wo(e.colors.primary,.8),300:Wo(e.colors.primary,.7),400:Wo(e.colors.primary,.6),500:e.colors.primary,600:Wo(e.colors.primary,.8),700:Wo(e.colors.primary,.7),800:Wo(e.colors.primary,.6),900:Wo(e.colors.primary,.5),950:Wo(e.colors.primary,.45)}}),{...t,palette:o}}}}function nh(){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 ah(){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 Wo(e,t){let o=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),n=parseInt(e.slice(5,7),16),a=Math.round(o+(255-o)*(1-t)),s=Math.round(r+(255-r)*(1-t)),l=Math.round(n+(255-n)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function sh(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var cC={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"}}},ih={components:{panel:{borderRadius:"0",shadow:"none"}}},Gp={id:"shop",label:"Shopping Assistant",config:{theme:cC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:lo},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?"]}},Kp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:ih}},Xp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:ih}},Jp={shop:Gp,minimal:Kp,fullscreen:Xp};function lh(e){return Jp[e]}var pC=`
|
|
129
152
|
@keyframes persona-stream-wipe {
|
|
130
153
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
131
154
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -161,7 +184,7 @@ ${s.join(`
|
|
|
161
184
|
mask-image: none !important;
|
|
162
185
|
}
|
|
163
186
|
}
|
|
164
|
-
`.trim(),
|
|
187
|
+
`.trim(),uC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:pC};on(uC);var fC=`
|
|
165
188
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
166
189
|
animation: persona-stream-glyph-cycle-fade
|
|
167
190
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -179,7 +202,7 @@ ${s.join(`
|
|
|
179
202
|
opacity: 1 !important;
|
|
180
203
|
}
|
|
181
204
|
}
|
|
182
|
-
`.trim(),
|
|
205
|
+
`.trim(),os="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",mC=10,gC=120,Qp=120,hC=.4,yC=50,bC=e=>{if(!e)return Qp;let o=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return o?parseFloat(o[1]):Qp},hh=e=>{let t=e.closest(".persona-stream-glyph-cycle"),o=bC(t);return gC*o/Qp},Yp=e=>{let t=os[Math.floor(Math.random()*os.length)];return e&&t===e&&(t=os[(os.indexOf(t)+1)%os.length]),t},xC=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let o=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),r=!1;for(let n of Array.from(o)){if(n===e){r=!0;continue}r&&Math.random()<hC&&(n.textContent=Yp())}},dh=new WeakMap,ch=25,ph=.5,vC=6,uh=.25,fh=new WeakMap,mh=new WeakMap,CC=(e,t)=>{if(!e)return ch*ph;let o=fh.get(e);fh.set(e,t);let r=mh.get(e)??ch;if(o!==void 0){let n=t-o;n>1&&(r=r*(1-uh)+n*uh,mh.set(e,r))}return Math.max(vC,r*ph)},Kn=new Map,wC=e=>e.closest("[data-message-id]")?.dataset.messageId??null,AC=e=>{e&&Kn.set(e,(Kn.get(e)??0)+1)},SC=e=>{if(!e)return;let t=Kn.get(e)??0;t<=1?Kn.delete(e):Kn.set(e,t-1)},yh=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Yp();let o=wC(e);o&&(e.dataset.glyphCycleMessageId=o),AC(o);let r=e.closest(".persona-stream-glyph-cycle"),n=Date.now(),a=CC(r,n),s=hh(e),l=mC*s,p=n+l;if(r){let d=dh.get(r);d!==void 0&&(p=Math.max(p,d)),dh.set(r,p+a)}TC(e,t,p)},TC=(e,t,o)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let r=hh(e),n=e.textContent??void 0,a=()=>{if(!e.isConnected)return;if(Date.now()>=o){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,SC(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=Yp(n);e.textContent=s,n=s,xC(e),setTimeout(a,r)};setTimeout(a,r)},gh=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let o of Array.from(t))yh(o)},MC=e=>e.nodeType===1,EC={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:fC,bufferContent(e){if(e.length<yC)return"";let t=0,o=-1,r=0;for(;r<e.length;){if(e[r]==="*"&&e[r+1]==="*"){t+=1,r+=2;continue}/\s/.test(e[r])&&t%2===0&&(o=r),r+=1}return o<0?"":e.slice(0,o)},isAnimating(e){return(Kn.get(e.id)??0)>0},onAttach(e){gh(e);let t=new MutationObserver(o=>{for(let r of o)for(let n of Array.from(r.addedNodes))MC(n)&&(n.classList.contains("persona-stream-char")&&n.closest(".persona-stream-glyph-cycle")?yh(n):gh(n))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};on(EC);var Xo=typeof document<"u"?document.currentScript?.src??null:null;Mf(()=>{let e=Xo?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Xo?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Xo??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});mf(()=>{let e=Xo?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Xo?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Xo??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});va().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});pm(()=>{let e=Xo?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Xo?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Xo??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});return ly(kC);})();
|
|
183
206
|
/*! Bundled license information:
|
|
184
207
|
|
|
185
208
|
lucide/dist/esm/icons/activity.mjs:
|
|
@@ -207,6 +230,7 @@ lucide/dist/esm/icons/circle-x.mjs:
|
|
|
207
230
|
lucide/dist/esm/icons/clipboard-copy.mjs:
|
|
208
231
|
lucide/dist/esm/icons/clipboard.mjs:
|
|
209
232
|
lucide/dist/esm/icons/clock.mjs:
|
|
233
|
+
lucide/dist/esm/icons/code-xml.mjs:
|
|
210
234
|
lucide/dist/esm/icons/copy.mjs:
|
|
211
235
|
lucide/dist/esm/icons/credit-card.mjs:
|
|
212
236
|
lucide/dist/esm/icons/dollar-sign.mjs:
|