@runtypelabs/persona 4.17.1 → 4.18.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/chunk-3I2S3I5P.js +1 -0
- package/dist/chunk-76IELU7F.js +1 -0
- package/dist/chunk-EFJBUH5F.js +1 -0
- package/dist/chunk-PDPVORUF.js +1 -0
- package/dist/chunk-Q735PSZL.js +1 -0
- package/dist/chunk-VK6JOIYJ.js +1 -0
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +4 -4
- package/dist/{context-mentions-BTSTIBFC.js → context-mentions-MJL6S6P2.js} +1 -1
- package/dist/context-mentions.cjs +9 -8
- package/dist/context-mentions.d.cts +1212 -14
- package/dist/context-mentions.d.ts +1212 -14
- package/dist/context-mentions.js +9 -8
- package/dist/event-stream-view-4EZ7BGFK.js +1 -0
- package/dist/event-stream-view.cjs +129 -0
- package/dist/event-stream-view.d.cts +8384 -0
- package/dist/event-stream-view.d.ts +8384 -0
- package/dist/event-stream-view.js +129 -0
- package/dist/history-view-BD6OXLNA.js +898 -0
- package/dist/history-view.cjs +898 -0
- package/dist/history-view.d.cts +1461 -0
- package/dist/history-view.d.ts +1461 -0
- package/dist/history-view.js +898 -0
- package/dist/index.cjs +77 -77
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1987 -17
- package/dist/index.d.ts +1987 -17
- package/dist/index.global.js +67 -66
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +77 -77
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +5 -4
- package/dist/launcher.global.js.map +1 -1
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.d.cts +0 -8
- package/dist/plugin-kit.d.ts +0 -8
- package/dist/plugin-kit.js +1 -1
- package/dist/smart-dom-reader.d.cts +1212 -14
- package/dist/smart-dom-reader.d.ts +1212 -14
- package/dist/theme-editor-preview.cjs +970 -73
- package/dist/theme-editor-preview.d.cts +1331 -15
- package/dist/theme-editor-preview.d.ts +1331 -15
- package/dist/theme-editor-preview.js +81 -81
- package/dist/theme-editor.cjs +7 -7
- package/dist/theme-editor.d.cts +1215 -15
- package/dist/theme-editor.d.ts +1215 -15
- package/dist/theme-editor.js +9 -9
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +226 -7
- package/dist/theme-reference.d.ts +226 -7
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +16 -4
- package/src/client-history-rest.test.ts +1034 -0
- package/src/client-visitor-history.test.ts +596 -0
- package/src/client.ts +1040 -24
- package/src/components/artifact-inline.ts +8 -1
- package/src/components/artifact-pane.test.ts +278 -1
- package/src/components/artifact-pane.ts +135 -67
- package/src/components/artifact-preview.test.ts +14 -1
- package/src/components/artifact-preview.ts +9 -0
- package/src/components/header-builder.ts +3 -0
- package/src/components/header-layouts.test.ts +171 -7
- package/src/components/header-layouts.ts +83 -53
- package/src/components/header-parts.test.ts +154 -1
- package/src/components/header-parts.ts +266 -138
- package/src/components/history-confirm-dialog.ts +177 -0
- package/src/components/history-shell-copy.ts +99 -0
- package/src/components/history-view/announcer.ts +40 -0
- package/src/components/history-view/copy.ts +105 -0
- package/src/components/history-view/css.ts +1078 -0
- package/src/components/history-view/grouping.test.ts +142 -0
- package/src/components/history-view/grouping.ts +142 -0
- package/src/components/history-view/icons.ts +73 -0
- package/src/components/history-view/rows.ts +341 -0
- package/src/components/history-view/state.ts +309 -0
- package/src/components/history-view.test.ts +2660 -0
- package/src/components/history-view.ts +1891 -0
- package/src/components/launcher-surface.test.ts +133 -0
- package/src/components/launcher.test.ts +18 -0
- package/src/components/launcher.ts +7 -7
- package/src/components/panel.ts +17 -7
- package/src/components/welcome.ts +72 -2
- package/src/defaults.ts +36 -3
- package/src/event-stream-view-bundle.test.ts +69 -0
- package/src/event-stream-view-entry.ts +19 -0
- package/src/event-stream-view-loader.ts +31 -0
- package/src/event-stream-view.ts +19 -0
- package/src/generated/runtype-openapi-contract.ts +1 -0
- package/src/history-render.ts +325 -0
- package/src/history-view-bundle.test.ts +78 -0
- package/src/history-view-entry.ts +41 -0
- package/src/history-view-loader.test.ts +30 -0
- package/src/history-view-loader.ts +32 -0
- package/src/history-view.ts +28 -0
- package/src/index-core.ts +50 -2
- package/src/index-global.ts +55 -0
- package/src/internal/demo-history-provider.test.ts +402 -0
- package/src/internal/demo-history-provider.ts +689 -0
- package/src/internal/history-provider-registry.ts +25 -0
- package/src/internal/history-provider.ts +150 -0
- package/src/internal/runtype-history-provider.test.ts +313 -0
- package/src/internal/runtype-history-provider.ts +240 -0
- package/src/plugin-kit.test.ts +16 -0
- package/src/plugin-kit.ts +13 -5
- package/src/plugins/types.ts +177 -1
- package/src/session-history.test.ts +1397 -0
- package/src/session.ts +1200 -26
- package/src/styles/widget-styles.test.ts +133 -0
- package/src/styles/widget.css +227 -8
- package/src/theme-editor/preview-utils.test.ts +19 -0
- package/src/theme-editor/preview-utils.ts +15 -1
- package/src/theme-editor/preview.ts +7 -1
- package/src/theme-editor/role-mappings.ts +4 -1
- package/src/theme-editor/sections.test.ts +168 -1
- package/src/theme-editor/sections.ts +136 -7
- package/src/theme-editor/webmcp/summary.ts +16 -2
- package/src/theme-reference.ts +20 -6
- package/src/types/theme.ts +213 -7
- package/src/types.ts +927 -7
- package/src/ui.artifact-rail-resize.test.ts +235 -0
- package/src/ui.attachments-drop.test.ts +1 -0
- package/src/ui.header-update-stability.test.ts +2 -2
- package/src/ui.history-chunk.test.ts +72 -0
- package/src/ui.history-config-provider.test.ts +318 -0
- package/src/ui.history-controller.test.ts +711 -0
- package/src/ui.history-lifecycle.test.ts +456 -0
- package/src/ui.history-render-hooks.test.ts +904 -0
- package/src/ui.history-shell.test.ts +1887 -0
- package/src/ui.rail-overlay.test.ts +573 -0
- package/src/ui.rail-resize.test.ts +284 -0
- package/src/ui.rebuild-composer.test.ts +21 -0
- package/src/ui.render-welcome.test.ts +42 -0
- package/src/ui.shortcuts.test.ts +166 -0
- package/src/ui.ts +3071 -240
- package/src/utils/__fixtures__/client-conversation-history-wire.json +108 -0
- package/src/utils/artifact-file.ts +15 -0
- package/src/utils/artifact-gate.test.ts +4 -0
- package/src/utils/artifact-gate.ts +13 -17
- package/src/utils/artifact-resize.test.ts +28 -0
- package/src/utils/artifact-resize.ts +9 -2
- package/src/utils/buttons.ts +188 -1
- package/src/utils/config-merge.test.ts +91 -0
- package/src/utils/dropdown.ts +10 -1
- package/src/utils/history-messages.test.ts +284 -0
- package/src/utils/history-messages.ts +284 -0
- package/src/utils/icons.ts +3 -0
- package/src/utils/shortcuts.test.ts +288 -0
- package/src/utils/shortcuts.ts +221 -0
- package/src/utils/theme.test.ts +501 -4
- package/src/utils/theme.ts +42 -3
- package/src/utils/tokens.ts +153 -15
- package/src/utils/tooltip-timing.ts +4 -0
- package/src/utils/tooltip.test.ts +249 -7
- package/src/utils/tooltip.ts +146 -4
- package/src/utils/visitor-store.test.ts +425 -0
- package/src/utils/visitor-store.ts +337 -0
- package/dist/chunk-QJ4LV2KW.js +0 -1
package/dist/index.global.js
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[o]);)o++};return s()},Ev=Eg;_t.parse=Ev});var lh={};ag(lh,{createReconnectController:()=>mC});function mC(e){let t=0,n=null,o=null,r=!1,a=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},s=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||a()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||s()},p=()=>{s()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},f=b=>new Promise(w=>{n=w,o=setTimeout(()=>{o=null,n=null,w()},b)}),g=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let w=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,w=!0);let T=e.buildErrorContent("Connection lost and the response could not be resumed.");T?e.appendMessage({id:`reconnect-failed-${b?.executionId??e.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):w&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},m=async()=>{let b=e.config.reconnect?.backoffMs??fC,w=e.config.reconnect?.maxAttempts??b.length,T=e.config.reconnectStream;if(!T){e.setReconnecting(!1);return}for(;e.getResumable()&&t<w;){t+=1,e.setStatus("resuming");let L=e.getResumable(),A=L.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let C=null;try{let M=await T({executionId:L.executionId,after:L.lastEventId,signal:S.signal});M&&M.ok&&M.body&&(C=M.body)}catch{C=null}if(S.signal.aborted)return;if(C){let M=e.getMessages().find(R=>R.id===L.assistantMessageId)?.content,P=typeof M=="string"?M:"";try{await e.resumeConnect(C,L.assistantMessageId,P)}catch{}if(S.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<w&&(e.setStatus("paused"),await f(b[Math.min(t-1,b.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,d(),m()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:a}}var fC,ch=tv(()=>{"use strict";fC=[1e3,2e3,4e3,8e3,8e3]});var b0={};ag(b0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>id,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>sd,ASK_USER_QUESTION_TOOL_NAME:()=>ss,AgentWidgetClient:()=>vr,AgentWidgetSession:()=>ca,AttachmentManager:()=>Ar,BrowserSpeechEngine:()=>_o,DEFAULT_COMPONENTS:()=>hu,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ol,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>mn,DEFAULT_PALETTE:()=>mu,DEFAULT_SEMANTIC:()=>gu,DEFAULT_WIDGET_CONFIG:()=>rt,PRESETS:()=>wf,PRESET_FULLSCREEN:()=>Cf,PRESET_MINIMAL:()=>vf,PRESET_SHOP:()=>xf,ReadAloudController:()=>wr,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ti,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>od,SUGGEST_REPLIES_TOOL_NAME:()=>On,THEME_ZONES:()=>Mh,VERSION:()=>xr,WEBMCP_TOOL_PREFIX:()=>Dn,WebMcpBridge:()=>na,accessibilityPlugin:()=>Pb,animationsPlugin:()=>Rb,applyFeaturePreferences:()=>of,applyThemeVariables:()=>Sr,attachHeaderToContainer:()=>kr,brandPlugin:()=>Ib,buildComposer:()=>Lr,buildDefaultHeader:()=>Du,buildHeader:()=>fo,buildHeaderWithLayout:()=>ya,buildMinimalHeader:()=>Fu,builtInClientToolsForDispatch:()=>sa,canonicalArtifactDisplayMode:()=>sn,collectEnrichedPageContext:()=>kb,componentRegistry:()=>Nn,createActionManager:()=>Fs,createAgentExperience:()=>Jl,createAskUserQuestionBubble:()=>Ug,createBestAvailableVoiceProvider:()=>Ui,createBubbleWithLayout:()=>py,createCSATFeedback:()=>Gl,createComboButton:()=>ul,createComponentMiddleware:()=>rb,createComponentStreamParser:()=>zl,createDefaultSanitizer:()=>jc,createDirectivePostprocessor:()=>pg,createDropdownMenu:()=>$o,createFlexibleJsonStreamParser:()=>$g,createIconButton:()=>Tt,createImagePart:()=>Yg,createJsonStreamParser:()=>Hi,createLabelButton:()=>po,createLocalStorageAdapter:()=>Vl,createMarkdownProcessor:()=>ns,createMarkdownProcessorFromConfig:()=>hr,createMessageActions:()=>qu,createNPSFeedback:()=>Kl,createPlainTextParser:()=>Ii,createPlugin:()=>Bb,createRegexJsonParser:()=>Wi,createSlashCommandsSource:()=>yb,createStandardBubble:()=>ba,createStaticMentionSource:()=>hb,createTextPart:()=>Oo,createTheme:()=>hs,createThemeObserver:()=>pa,createToggleGroup:()=>ma,createTypingIndicator:()=>Pr,createVoiceProvider:()=>No,createWidgetHostLayout:()=>Ns,createXmlParser:()=>Bi,defaultActionHandlers:()=>Dr,defaultJsonActionParser:()=>Ds,defaultMentionFilter:()=>Yl,defaultParseRules:()=>yf,detectColorScheme:()=>ys,directivePostprocessor:()=>ug,ensureAskUserQuestionSheet:()=>aa,escapeHtml:()=>Vn,extractComponentDirectiveFromMessage:()=>jl,fileToImagePart:()=>Zg,formatEnrichedContext:()=>Lb,generateAssistantMessageId:()=>Fo,generateMessageId:()=>Kg,generateStableSelector:()=>bf,generateUserMessageId:()=>ia,getActiveTheme:()=>Uo,getColorScheme:()=>ll,getDisplayText:()=>Jg,getHeaderLayout:()=>Ou,getImageParts:()=>Qg,getPreset:()=>Fb,hasComponentDirective:()=>Os,hasImages:()=>Oi,headerLayouts:()=>Tl,highContrastPlugin:()=>Hb,initAgentWidget:()=>mb,isAskUserQuestionMessage:()=>so,isComponentDirectiveType:()=>ob,isDockedMountMode:()=>St,isSuggestRepliesMessage:()=>br,isVoiceSupported:()=>us,isWebMcpToolName:()=>Lo,isWelcomeVisible:()=>Xo,latestAgentSuggestions:()=>Ei,listRegisteredStreamAnimations:()=>Lu,loadMarkdownParsers:()=>ts,markdownPostprocessor:()=>$c,mergeWithDefaults:()=>da,normalizeContent:()=>Xg,normalizeMediaType:()=>Po,onMarkdownParsersReady:()=>ea,parseAskUserQuestionPayload:()=>io,parseSuggestRepliesPayload:()=>ad,parseWidgetPreferenceSlice:()=>nf,pickBestVoice:()=>la,pluginRegistry:()=>Bs,reducedMotionPlugin:()=>Wb,registerStreamAnimationPlugin:()=>Er,removeAskUserQuestionSheet:()=>Wo,renderComponentDirective:()=>$l,renderLoadingIndicatorWithFallback:()=>Uu,renderLucideIcon:()=>ae,resolveArtifactDisplay:()=>Jc,resolveArtifactDisplayMode:()=>zn,resolveConfigPreferences:()=>Hs,resolveDockConfig:()=>ln,resolveSanitizer:()=>ta,resolveTokens:()=>sl,resolveWelcomeConfig:()=>mo,stripWebMcpPrefix:()=>xi,themeToCssVariables:()=>il,unregisterStreamAnimationPlugin:()=>ku,validateImageFile:()=>eh,validateTheme:()=>yu});var Zr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,a=null;return{setLoader:c=>{o=c,n&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(o??t)().then(f=>(r=f,f)).catch(f=>{throw a=null,f}),a),provide:c=>{r=c},getSync:()=>r}};var{setLoader:ov,load:rv,provide:M0,getSync:zc}=Zr({fallbackImport:()=>import("./markdown-parsers-entry")}),yi=new Set,av=()=>{let e=[...yi];yi.clear();for(let t of e)try{t()}catch{}},ig=ov,ts=()=>{let e=zc();return e?Promise.resolve(e):rv().then(t=>(av(),t))},ea=e=>zc()?()=>{}:(yi.add(e),ts().catch(()=>{}),()=>{yi.delete(e)});var ao=zc;var sv=e=>{if(e)return e},ns=e=>{let t=null;return n=>{let o=ao();if(!o)return Vn(n);if(!t){let{Marked:r}=o,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let s=sv(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},hr=e=>e?ns({markedOptions:e.options,renderer:e.renderer}):ns(),iv=ns(),$c=e=>iv(e),Vn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),cg=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),lg=e=>`%%FORM_PLACEHOLDER_${e}%%`,dg=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=lg(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let a=lg(t.length);return t.push({token:a,type:r}),a}),n},pg=e=>{let t=hr(e);return n=>{let o=[],r=dg(n,o),a=t(r);return o.forEach(({token:s,type:l})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${cg(l)}"></div>`;a=a.replace(p,c)}),a}},ug=e=>{let t=[],n=dg(e,t),o=$c(n);return t.forEach(({token:r,type:a})=>{let s=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${cg(a)}"></div>`;o=o.replace(s,p)}),o};var lv={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"]},cv=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,jc=()=>{let e=null;return t=>{let n=ao();if(!n)return Vn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!cv.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,lv)}},ta=e=>e===!1?null:typeof e=="function"?e:jc();var fg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mg=e=>e.includes("|"),gg=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},dv=e=>`| ${e.join(" | ")} |`,pv=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,uv=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),hg=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
3
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],
|
|
4
|
-
`):e};var
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var CA=Object.create;var Ql=Object.defineProperty;var wA=Object.getOwnPropertyDescriptor;var SA=Object.getOwnPropertyNames;var AA=Object.getPrototypeOf,MA=Object.prototype.hasOwnProperty;var Jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var TA=(e,t)=>()=>(e&&(t=e(e=0)),t);var lb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),cb=(e,t)=>{for(var n in t)Ql(e,n,{get:t[n],enumerable:!0})},db=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of SA(t))!MA.call(e,r)&&r!==n&&Ql(e,r,{get:()=>t[r],enumerable:!(o=wA(t,r))||o.enumerable});return e};var uo=(e,t,n)=>(n=e!=null?CA(AA(e)):{},db(t||!e||!e.__esModule?Ql(n,"default",{value:e,enumerable:!0}):n,e)),EA=e=>db(Ql({},"__esModule",{value:!0}),e);var du=lb(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.Allow=be.ALL=be.COLLECTION=be.ATOM=be.SPECIAL=be.INF=be._INFINITY=be.INFINITY=be.NAN=be.BOOL=be.NULL=be.OBJ=be.ARR=be.NUM=be.STR=void 0;be.STR=1;be.NUM=2;be.ARR=4;be.OBJ=8;be.NULL=16;be.BOOL=32;be.NAN=64;be.INFINITY=128;be._INFINITY=256;be.INF=be.INFINITY|be._INFINITY;be.SPECIAL=be.NULL|be.BOOL|be.INF|be.NAN;be.ATOM=be.STR|be.NUM|be.SPECIAL;be.COLLECTION=be.ARR|be.OBJ;be.ALL=be.ATOM|be.COLLECTION;be.Allow={STR:be.STR,NUM:be.NUM,ARR:be.ARR,OBJ:be.OBJ,NULL:be.NULL,BOOL:be.BOOL,NAN:be.NAN,INFINITY:be.INFINITY,_INFINITY:be._INFINITY,INF:be.INF,SPECIAL:be.SPECIAL,ATOM:be.ATOM,COLLECTION:be.COLLECTION,ALL:be.ALL};be.default=be.Allow});var rc=lb(Jt=>{"use strict";var XA=Jt&&Jt.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),YA=Jt&&Jt.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&XA(t,e,n)};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.Allow=Jt.MalformedJSON=Jt.PartialJSON=Jt.parseJSON=Jt.parse=void 0;var un=du();Object.defineProperty(Jt,"Allow",{enumerable:!0,get:function(){return un.Allow}});YA(du(),Jt);var nc=class extends Error{};Jt.PartialJSON=nc;var oc=class extends Error{};Jt.MalformedJSON=oc;function Hb(e,t=un.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return JA(e.trim(),t)}Jt.parseJSON=Hb;var JA=(e,t)=>{let n=e.length,o=0,r=y=>{throw new nc(`${y} at position ${o}`)},s=y=>{throw new oc(`${y} at position ${o}`)},i=()=>(f(),o>=n&&r("Unexpected end of input"),e[o]==='"'?l():e[o]==="{"?d():e[o]==="["?u():e.substring(o,o+4)==="null"||un.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||un.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||un.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||un.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||un.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||un.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):p()),l=()=>{let y=o,g=!1;for(o++;o<n&&(e[o]!=='"'||g&&e[o-1]==="\\");)g=e[o]==="\\"?!g:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(y,++o-Number(g)))}catch(b){s(String(b))}else if(un.Allow.STR&t)try{return JSON.parse(e.substring(y,o-Number(g))+'"')}catch{return JSON.parse(e.substring(y,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},d=()=>{o++,f();let y={};try{for(;e[o]!=="}";){if(f(),o>=n&&un.Allow.OBJ&t)return y;let g=l();f(),o++;try{let b=i();y[g]=b}catch(b){if(un.Allow.OBJ&t)return y;throw b}f(),e[o]===","&&o++}}catch{if(un.Allow.OBJ&t)return y;r("Expected '}' at end of object")}return o++,y},u=()=>{o++;let y=[];try{for(;e[o]!=="]";)y.push(i()),f(),e[o]===","&&o++}catch{if(un.Allow.ARR&t)return y;r("Expected ']' at end of array")}return o++,y},p=()=>{if(o===0){e==="-"&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(g){if(un.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}s(String(g))}}let y=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==n&&!(un.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(y,o))}catch{e.substring(y,o)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(y,e.lastIndexOf("e")))}catch(b){s(String(b))}}},f=()=>{for(;o<n&&`
|
|
2
|
+
\r `.includes(e[o]);)o++};return i()},QA=Hb;Jt.parse=QA});var Sx={};cb(Sx,{createReconnectController:()=>V0});function V0(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},i=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},d=()=>{i()},u=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",d),r=!0)},p=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},f=b=>new Promise(v=>{n=v,o=setTimeout(()=>{o=null,n=null,v()},b)}),y=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let v=!1;for(let H of e.getMessages())H.streaming&&(H.streaming=!1,v=!0);let E=e.buildErrorContent("Connection lost and the response could not be resumed.");E?e.appendMessage({id:`reconnect-failed-${b?.executionId??e.nextSequence()}`,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):v&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let b=e.config.reconnect?.backoffMs??q0,v=e.config.reconnect?.maxAttempts??b.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<v;){t+=1,e.setStatus("resuming");let H=e.getResumable(),k=H.lastEventId,M=new AbortController;e.setAbortController(M),e.emitReconnect({phase:"resuming",handle:H,attempt:t});let x=null;try{let w=await E({executionId:H.executionId,after:H.lastEventId,signal:M.signal});w&&w.ok&&w.body&&(x=w.body)}catch{x=null}if(M.signal.aborted)return;if(x){let w=e.getMessages().find(P=>P.id===H.assistantMessageId)?.content,L=typeof w=="string"?w:"";try{await e.resumeConnect(x,H.assistantMessageId,L)}catch{}if(M.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:H});return}e.getResumable().lastEventId!==k&&(t=0)}if(e.getResumable()&&t<v&&(e.setStatus("paused"),await f(b[Math.min(t-1,b.length-1)]??1e3),M.signal.aborted))return}e.getResumable()&&y()};return{begin(){t=0,u(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,p()},wake:s}}var q0,Ax=TA(()=>{"use strict";q0=[1e3,2e3,4e3,8e3,8e3]});var aP={};cb(aP,{ASK_USER_QUESTION_CLIENT_TOOL:()=>vu,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>xu,ASK_USER_QUESTION_TOOL_NAME:()=>hi,AgentWidgetClient:()=>ts,AgentWidgetSession:()=>oa,AttachmentManager:()=>rs,BrowserSpeechEngine:()=>br,DEFAULT_COMPONENTS:()=>Rm,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>_c,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>In,DEFAULT_PALETTE:()=>Lm,DEFAULT_SEMANTIC:()=>Hm,DEFAULT_WIDGET_CONFIG:()=>Ge,HistoryProviderError:()=>Gn,PRESETS:()=>jg,PRESET_FULLSCREEN:()=>zg,PRESET_MINIMAL:()=>Vg,PRESET_SHOP:()=>qg,ReadAloudController:()=>os,SUGGEST_REPLIES_CLIENT_TOOL:()=>lc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>hu,SUGGEST_REPLIES_TOOL_NAME:()=>oo,THEME_ZONES:()=>zx,VERSION:()=>gr,WEBMCP_TOOL_PREFIX:()=>no,WebMcpBridge:()=>Ks,accessibilityPlugin:()=>dw,animationsPlugin:()=>pw,applyFeaturePreferences:()=>Sg,applyThemeVariables:()=>ss,attachHeaderToContainer:()=>us,brandPlugin:()=>uw,buildComposer:()=>fs,buildDefaultHeader:()=>Zm,buildHeader:()=>zo,buildHeaderWithLayout:()=>ga,buildMinimalHeader:()=>eg,builtInClientToolsForDispatch:()=>Qs,canonicalArtifactDisplayMode:()=>wn,collectEnrichedPageContext:()=>lw,componentRegistry:()=>ro,createActionManager:()=>Ji,createAgentExperience:()=>Dd,createAskUserQuestionBubble:()=>jb,createBestAvailableVoiceProvider:()=>Sc,createBubbleWithLayout:()=>Dv,createCSATFeedback:()=>Id,createComboButton:()=>td,createComponentMiddleware:()=>FC,createComponentStreamParser:()=>Ld,createDefaultSanitizer:()=>su,createDirectivePostprocessor:()=>gb,createDropdownMenu:()=>ls,createFlexibleJsonStreamParser:()=>Xb,createIconButton:()=>Tt,createImagePart:()=>xc,createJsonStreamParser:()=>hc,createLabelButton:()=>Vo,createLocalStorageAdapter:()=>kd,createMarkdownProcessor:()=>ui,createMarkdownProcessorFromConfig:()=>Qr,createMessageActions:()=>sg,createNPSFeedback:()=>Wd,createPlainTextParser:()=>mc,createPlugin:()=>gw,createRegexJsonParser:()=>gc,createSlashCommandsSource:()=>JC,createSplitButton:()=>ed,createStandardBubble:()=>ha,createStaticMentionSource:()=>YC,createTextPart:()=>ho,createTheme:()=>Pi,createThemeObserver:()=>ia,createToggleGroup:()=>da,createTypingIndicator:()=>ms,createVoiceProvider:()=>yr,createWidgetHostLayout:()=>Zi,createXmlParser:()=>yc,defaultActionHandlers:()=>vs,defaultJsonActionParser:()=>Yi,defaultMentionFilter:()=>Fd,defaultParseRules:()=>_g,detectColorScheme:()=>Li,directivePostprocessor:()=>hb,ensureAskUserQuestionSheet:()=>Js,escapeHtml:()=>mo,extractComponentDirectiveFromMessage:()=>Rd,fileToImagePart:()=>Zb,formatEnrichedContext:()=>cw,generateAssistantMessageId:()=>hr,generateMessageId:()=>bx,generateStableSelector:()=>Ug,generateUserMessageId:()=>ta,getActiveTheme:()=>xr,getColorScheme:()=>jc,getDisplayText:()=>bc,getHeaderLayout:()=>tg,getImageParts:()=>Qb,getPreset:()=>yw,hasComponentDirective:()=>Qi,hasImages:()=>ea,headerLayouts:()=>pd,highContrastPlugin:()=>mw,initAgentWidget:()=>KC,isAskUserQuestionMessage:()=>No,isComponentDirectiveType:()=>OC,isDockedMountMode:()=>ht,isHistoryProviderError:()=>xx,isSuggestRepliesMessage:()=>es,isVoiceSupported:()=>Ai,isWebMcpToolName:()=>ir,isWelcomeVisible:()=>Tr,latestAgentSuggestions:()=>cc,listRegisteredStreamAnimations:()=>$m,loadMarkdownParsers:()=>pi,markdownPostprocessor:()=>ru,mergeWithDefaults:()=>aa,normalizeContent:()=>Jb,normalizeMediaType:()=>lr,onMarkdownParsersReady:()=>$s,parseAskUserQuestionPayload:()=>_o,parseSuggestRepliesPayload:()=>bu,parseWidgetPreferenceSlice:()=>wg,pickBestVoice:()=>na,pluginRegistry:()=>Xi,reducedMotionPlugin:()=>fw,registerStreamAnimationPlugin:()=>ds,removeAskUserQuestionSheet:()=>pr,renderComponentDirective:()=>Hd,renderLoadingIndicatorWithFallback:()=>rg,renderLucideIcon:()=>ce,resolveArtifactDisplay:()=>cu,resolveArtifactDisplayMode:()=>go,resolveConfigPreferences:()=>Ki,resolveDockConfig:()=>Sn,resolveSanitizer:()=>Gs,resolveTokens:()=>Vc,resolveWelcomeConfig:()=>jo,stripWebMcpPrefix:()=>tc,themeToCssVariables:()=>zc,unregisterStreamAnimationPlugin:()=>jm,validateImageFile:()=>ex,validateTheme:()=>Im});var fo=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:p=>{o=p,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(f=>(r=f,f)).catch(f=>{throw s=null,f}),s),provide:p=>{r=p},getSync:()=>r}};var{setLoader:kA,load:PA,provide:mP,getSync:ou}=fo({fallbackImport:()=>import("./markdown-parsers-entry")}),Zl=new Set,LA=()=>{let e=[...Zl];Zl.clear();for(let t of e)try{t()}catch{}},pb=kA,pi=()=>{let e=ou();return e?Promise.resolve(e):PA().then(t=>(LA(),t))},$s=e=>ou()?()=>{}:(Zl.add(e),pi().catch(()=>{}),()=>{Zl.delete(e)});var Fo=ou;var HA=e=>{if(e)return e},ui=e=>{let t=null;return n=>{let o=Fo();if(!o)return mo(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=HA(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},Qr=e=>e?ui({markedOptions:e.options,renderer:e.renderer}):ui(),RA=ui(),ru=e=>RA(e),mo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),fb=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),ub=e=>`%%FORM_PLACEHOLDER_${e}%%`,mb=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=ub(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=ub(t.length);return t.push({token:s,type:r}),s}),n},gb=e=>{let t=Qr(e);return n=>{let o=[],r=mb(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${fb(l)}"></div>`;s=s.replace(d,p)}),s}},hb=e=>{let t=[],n=mb(e,t),o=ru(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${fb(s)}"></div>`;o=o.replace(i,d)}),o};var IA={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"]},WA=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,su=()=>{let e=null;return t=>{let n=Fo();if(!n)return mo(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!WA.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,IA)}},Gs=e=>e===!1?null:typeof e=="function"?e:su();var yb=/^\s*\|?[\s:|-]*-[\s:|-]*$/,bb=e=>e.includes("|"),xb=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},BA=e=>`| ${e.join(" | ")} |`,DA=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,OA=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),vb=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
3
|
+
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!bb(r)||yb.test(r)||!yb.test(s))continue;let i=xb(r).length;if(i<1)continue;let l=DA(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let d=o+2;for(;d<t.length;d++){let u=t[d];if(u.trim()===""||!bb(u))break;let p=BA(OA(xb(u),i));t[d]!==p&&(t[d]=p,n=!0)}o=d-1}return n?t.join(`
|
|
4
|
+
`):e};var Cb="var(--persona-md-table-scroll-fade, 24px)",wb=new WeakSet;function Ab(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Sb(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":Cb),e.style.setProperty("--persona-fade-r",r<=1?"0px":Cb)}function au(e){wb.has(e)||(wb.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Sb(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Sb)}var no="webmcp:",iu=new Map,Mb=e=>{iu.clear();for(let t of e){let n=t.title?.trim();n&&iu.set(t.name,n)}},fi=e=>iu.get(tc(e)),ec={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},lu=null,Eb=e=>{lu=e};function kb(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${FA(t.join(""))}`}function Tb(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function FA(e){let t=Tb(e,0).toString(36),n=Tb(e,2654435761).toString(36);return`${t}.${n}`}var Ks=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 n;try{n=await t.getTools()}catch(r){return ec.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Mb(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},i=_A(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return to("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return to(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=tc(t),i;try{i=await r.getTools()}catch(b){let v=b instanceof Error?b.message:String(b);return to(`Failed to read WebMCP registry: ${v}`)}Mb(i);let l=i.find(b=>b.name===s);if(!l)return to(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return to(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return to("Aborted by cancel()");let d=fi(s),u={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(u))return to("User declined the tool call.");if(o?.aborted)return to("Aborted by cancel()");let p=new AbortController,f=!1,y=setTimeout(()=>{f=!0,p.abort()},this.timeoutMs),g=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",g,{once:!0}));try{let b=await r.executeTool(l,zA(n),{signal:p.signal});return UA(b)}catch(b){if(f)return to(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return to("Aborted by cancel()");let v=b instanceof Error?b.message:String(b);return to(v)}finally{clearTimeout(y),o&&o.removeEventListener("abort",g)}}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}(lu?await lu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ec.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 n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ec.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 n=this.confirmHandler??qA;try{return await n(t)}catch(o){return ec.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>NA(t,o))}},tc=e=>e.startsWith(no)?e.slice(no.length):e,ir=e=>e.startsWith(no),NA=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},_A=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},UA=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:jA(t)}]}},to=e=>({isError:!0,content:[{type:"text",text:e}]}),qA=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=VA(e.args),n=`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(n)},bv=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)}},xv=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},vv=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function sn(e){return e==="card"?"collapsed":e}function Po(e){return e.split(";",1)[0].trim().toLowerCase()}function Cv(e,t){if(!e)return;let n=Object.entries(e);for(let[r,a]of n)if(Po(r)===t)return{mode:sn(a),selector:Po(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,a]of n)if(Po(r)===o)return{mode:sn(a),selector:o}}function Jc(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:sn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Po(t.file.mimeType):void 0,p=l?Cv(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:sn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:sn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:sn(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:sn(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:sn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function zn(e,t){return Jc(e,t).mode}function rs(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}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var wv="agent_",Av="flow_";function Mg(e){return e.startsWith(wv)?{kind:"agentId",agentId:e}:e.startsWith(Av)?{kind:"flowId",flowId:e}:null}function Tg(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let s=n.slice(0,o),l=n.slice(o+1);if(s==="runtype"){let d=Mg(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 r=Mg(n);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var Ro=ko(wi(),1);var v=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var kg=()=>document.createDocumentFragment(),ke=(e,t={},...n)=>{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 l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let r=n.filter(a=>a!=null);return r.length>0&&o.append(...r),o},Fn=(...e)=>e.filter(Boolean).join(" ");var ss="ask_user_question",as=8,oa="data-persona-ask-sheet-for",kv="Other",Lv="Other\u2026",Pg="Type your own answer here",Rg="Send",Pv="Next",Rv="Back",Iv="Submit all",Wv="Skip",Hv=3,Yc="data-ask-current-index",Zc="data-ask-question-count",Ig="data-ask-answers",ed="data-ask-grouped",Wg="data-ask-layout",Bv=e=>e.layout==="pills"?"pills":"rows",Dv=e=>e.getAttribute(Wg)==="pills"?"pills":"rows",Lg=!1,Hg=e=>e.replace(/["\\]/g,"\\$&"),so=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ss,Ai=e=>e?.features?.askUserQuestion??{},io=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),a=(0,Ro.parse)(r,Ro.STR|Ro.OBJ|Ro.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},is=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>as&&!Lg&&(Lg=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${as}.`)),t.slice(0,as)},Fv=e=>is(e)[0]??null,Ov=(e,t)=>is(e)[t]??null,Bg=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Dg=(e,t,n)=>{if(e!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Nv=(e,t,n,o)=>{let a=v("button",n==="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),n==="rows"){let s=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let d=v("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let p=Dg(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},_v=e=>{let n=v("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 n.setAttribute("aria-hidden","true"),n},Uv=(e,t,n,o)=>{let a=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");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&&!n){for(let c=0;c<Hv;c++)a.appendChild(_v(o));return a}if(p.forEach((c,f)=>{a.appendChild(Nv(c,f,o,s))}),e?.allowFreeText!==!1){let c=o==="rows"?kv:Lv;if(o==="rows"){let f=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(p.length)),f.setAttribute("data-ask-other-row","true");let g=v("span","persona-ask-row-content"),m=document.createElement("input");m.type="text",m.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",m.placeholder=t.freeTextPlaceholder??Pg,m.setAttribute("data-ask-free-text-input","true"),m.setAttribute("aria-label",t.freeTextLabel??c),g.appendChild(m),f.appendChild(g);let b=Dg(o,s,p.length);b&&f.appendChild(b),a.appendChild(f)}else{let f=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,a.appendChild(f)}}return a},Fg=(e,t)=>{let o=v("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 r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Pg,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=v("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Rg,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},qv=e=>{let t=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Rg,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Vv=(e,t,n)=>{let o=v("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 r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Rv,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=v("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??Wv,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??Iv:n.nextLabel??Pv,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},yr=e=>{let t=e.getAttribute(Ig);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Og=(e,t)=>{e.setAttribute(Ig,JSON.stringify(t))},Sn=e=>{let t=Number(e.getAttribute(Yc)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},zv=(e,t)=>{e.setAttribute(Yc,String(Math.max(0,Math.floor(t))))},ra=e=>{let t=Number(e.getAttribute(Zc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Io=e=>e.getAttribute(ed)==="true",$v=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,a)=>{let s=typeof r?.question=="string"?r.question:"";if(s&&Object.prototype.hasOwnProperty.call(n,s)){let l=n[s];(typeof l=="string"||Array.isArray(l))&&(o[a]=l)}}),o},jv=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Si=(e,t)=>{let{payload:n}=io(t),o=is(n),r=yr(e),a={},s=new Set;return o.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(r,p)&&(a[d]=r[p]))}),a},Ng=e=>{let t=yr(e),n=Sn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.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=r.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 o=="string"&&o.length>0&&!s.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},_g=e=>{if(!Io(e))return;let t=yr(e),n=Sn(e),o=t[n],r=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=!r);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}},td=(e,t,n)=>{let o=Ai(n),r=Dv(e),{payload:a,complete:s}=io(t),l=Io(e),p=Sn(e),d=ra(e),c=l?Ov(a,p):Fv(a),f=!!c?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let A=typeof c?.question=="string"?c.question:"";b.textContent=A,b.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let w=e.querySelector('[data-ask-pill-list="true"]');if(w){let A=Uv(c,o,s,r);w.replaceWith(A)}if(r!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Fg(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(qv(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(l){let A=Vv(p,d,o);L?L.replaceWith(A):e.appendChild(A)}else L&&L.remove();Ng(e),_g(e)},Gv=(e,t,n)=>{let o=Ai(t),r=Bv(o),a=e.toolCall.id,s=is(n),l=Math.max(1,s.length),p=l>1,d=$v(e,s),c=p?jv(e,l):0,f=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(oa,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Zc,String(l)),f.setAttribute(Yc,String(c)),f.setAttribute(ed,p?"true":"false"),f.setAttribute(Wg,r),Og(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Bg(f,o);let g=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",g.appendChild(b),f.appendChild(g);let T=v("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");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),r!=="rows"&&f.appendChild(Fg(o,r)),td(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Kv=(e,t,n)=>{let{payload:o}=io(t),r=Math.max(1,is(o).length);r>ra(e)&&(e.setAttribute(Zc,String(r)),r>1&&!Io(e)&&e.setAttribute(ed,"true")),td(e,t,n)},Ug=(e,t)=>{let n=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Ai(t);Bg(n,o);let r=v("span","persona-ask-stub-label"),{complete:a}=io(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},aa=(e,t,n)=>{if(!n||!so(e)||Ai(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${oa}]`).forEach(d=>{d.getAttribute(oa)!==r&&d.remove()});let s=n.querySelector(`[${oa}="${Hg(r)}"]`);if(s){Kv(s,e,t);return}let{payload:l}=io(e),p=Gv(e,t,l);n.appendChild(p)},Wo=(e,t)=>{if(!e)return;let n=t?`[${oa}="${Hg(t)}"]`:`[${oa}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},nd=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),Ho=(e,t)=>{let n=yr(e),o=Sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Og(e,n),Ng(e),_g(e)},Mi=(e,t,n,o)=>{let r=ra(e),a=Math.max(0,Math.min(r-1,o));zv(e,a),td(e,t,n)};var On="suggest_replies";var od={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Ti={name:On,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. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts 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:od,origin:"sdk",annotations:{readOnlyHint:!0}},rd=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),br=e=>e.variant==="tool"&&e.toolCall?.name===On,ad=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let s={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(s.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(s.description=a.description.trim()),[s]});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},Ei=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!br(n))continue;let o=ad(n.toolCall?.args);return o.length>0?o:null}return null},qg=new Set,Xv=(e,t,n)=>{let o=`${e}:${t}:${n}`;qg.has(o)||(qg.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Bo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=s=>{let l=t?.[s],p=n?.[s];l===void 0||p===void 0||l!==p&&Xv(s,p,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,a=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:a}};var sd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:as,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},id={name:ss,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:sd,origin:"sdk",annotations:{readOnlyHint:!0}},sa=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(id),Bo(e).expose&&t.push(Ti),t};var lo=ko(wi(),1),ki=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
|
|
12
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ds=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ii=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Wi=()=>{let e=Yv();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Hi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,lo.parse)(n,lo.STR|lo.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ki(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ki(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},$g=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?ki(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ki(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<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,lo.parse)(a,lo.STR|lo.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Bi=()=>{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 jg="4.17.1";var xr=jg;var eC="https://api.runtype.com/v1/dispatch",Di="https://api.runtype.com";function tC(e){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 r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var cd=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 nC(e){switch(e){case"json":return Hi;case"regex-json":return Wi;case"xml":return Bi;default:return Ii}}var Gg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function oC(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Gg(n);if(!Gg(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=ds(e);return ds(t)!==null&&s===null?t:e}var vr=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??eC,this.headers={"Content-Type":"application/json","X-Persona-Version":xr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??nC(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 na(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,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let a=Tg(o,r);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$/,"")||Di}/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,n=this.routing(),o=n.agentId??n.flowId,r={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":xr},body:JSON.stringify(r)});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$/,"")||Di}/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 r={...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(r)});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,n){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:n})}async submitCSATFeedback(t,n){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:n})}async submitNPSFeedback(t,n){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:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(cd).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},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.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 f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...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:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...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:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Di}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?Sg(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,d=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let g=0;;g++){if(f=await o({...a&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),f.status===409&&g===0&&a&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Di}/resume`,s;r&&(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:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let d=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(s,d,g=>{let m={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",m),fetch(a,{method:"POST",headers:l,body:JSON.stringify(m),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(a,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(cd).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(cd).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let f={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 o.current=f,r(f),f},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.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,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,f=I=>{let B=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,y=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,D=I.tools?I.tools.map(H=>({...H,chunks:H.chunks?[...H.chunks]:void 0})):void 0;return{...I,reasoning:B,toolCall:y,tools:D}},g=I=>{if(I.role!=="assistant"||I.variant)return!0;let B=Array.isArray(I.contentParts)&&I.contentParts.length>0,y=typeof I.rawContent=="string"&&I.rawContent.trim()!=="";return typeof I.content=="string"&&I.content.trim()!==""||B||y||!!I.stopReason},m=I=>{g(I)&&n({type:"message",message:f(I)})},b=null,w=null,T={current:null},L={current:null},A=null,S="",C=new Map,M=new Map,P=new Map,R=new Map,F=new Map,O={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},E=I=>{if(I==null)return null;try{return String(I)}catch{return null}},G=I=>E(I.stepId??I.step_id??I.step??I.parentId??I.flowStepId??I.flow_step_id),Q=I=>E(I.callId??I.call_id??I.requestId??I.request_id??I.toolCallId??I.tool_call_id??I.stepId??I.step_id),Z=o,J=!1,fe=()=>{if(b)return b;let I,B="",y=A;return!J&&Z?(I=Z,J=!0,B=r??""):Z&&y?I=`${Z}_${y}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:I,role:"assistant",content:B,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},m(b),b},ne=(I,B)=>{O.lastId=B,I&&O.byStep.set(I,B)},ge=(I,B)=>{let y=I.reasoningId??I.id,D=G(I);if(y){let N=String(y);return ne(D,N),N}if(D){let N=O.byStep.get(D);if(N)return O.lastId=N,N}if(O.lastId&&!B)return O.lastId;if(!B)return null;let H=`reason-${c()}`;return ne(D,H),H},ie=I=>{let B=R.get(I);if(B)return B;let y={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"streaming",chunks:[]}};return R.set(I,y),m(y),y},ue=(I,B)=>{$.lastId=B,I&&$.byCall.set(I,B)},oe=new Set,me=new Map,Se=new Set,Ce=new Map,Be=I=>{if(!I)return!1;let B=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return B==="emit_artifact_markdown"||B==="emit_artifact_component"},ut=(I,B)=>{let y=I.toolId??I.id,D=Q(I);if(y){let N=String(y);return ue(D,N),N}if(D){let N=$.byCall.get(D);if(N)return $.lastId=N,N}if($.lastId&&!B)return $.lastId;if(!B)return null;let H=`tool-${c()}`;return ue(D,H),H},Je=I=>{let B=F.get(I);if(B)return B;let y={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:I,status:"pending"}};return F.set(I,y),m(y),y},Qe=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let B=Number(I);if(!Number.isNaN(B)&&Number.isFinite(B))return B;let y=Date.parse(I);if(!Number.isNaN(y))return y}return Date.now()},Ne=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},_e=new Map,Ae=new Map,Me=new Map,qe=(I,B,y)=>{let D=Me.get(I);D||(D=[],Me.set(I,D));let H=0,N=D.length;for(;H<N;){let V=H+N>>>1;D[V].seq<B?H=V+1:N=V}D[H]?.seq===B?D[H]={seq:B,text:y}:D.splice(H,0,{seq:B,text:y});let K="";for(let V=0;V<D.length;V++)K+=D[V].text;return K},Jt=(I,B)=>{let y=Ne(B),D=Ae.get(I.id),H=oC(D,y);I.rawContent=H;let N=_e.get(I.id),K=de=>{let Pe=I.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(I.content=de)},V=()=>{if(N){let de=N.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(I.id),Ae.delete(I.id),I.streaming=!1,m(I)};if(!N){K(y),V();return}let X=ds(H);if(X!==null&&X.trim()!==""){K(X),V();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let ze=N.getExtractedText();return ze!==null&&ze.trim()!==""?ze:y},Ve;try{Ve=N.processChunk(H)}catch{K(y),V();return}if(Ve instanceof Promise){Ve.then(de=>{K(ce(de)),V()}).catch(()=>{K(y),V()});return}K(ce(Ve)),V()},gt=null,Bt=(I,B,y,D)=>{I.rawContent=B,_e.has(I.id)||_e.set(I.id,this.createStreamParser());let H=_e.get(I.id),N=B.trim().startsWith("{")||B.trim().startsWith("[");if(N&&Ae.set(I.id,B),H.__isPlainTextParser===!0){I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I);return}let V=H.processChunk(B);if(V instanceof Promise)V.then(X=>{let ce=typeof X=="string"?X:X?.text??null;ce!==null&&ce.trim()!==""?(I.content=ce,m(I)):!N&&!B.trim().startsWith("<")&&(I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I))}).catch(()=>{I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I)});else{let X=typeof V=="string"?V:V?.text??null;X!==null&&X.trim()!==""?(I.content=X,m(I)):!N&&!B.trim().startsWith("<")&&(I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I))}},Tn=(I,B)=>{let y=B??I.content;if(y==null||y===""){I.streaming=!1,m(I);return}let H=Ae.get(I.id)??Ne(y);I.rawContent=H;let N=_e.get(I.id),K=null,V=!1;if(N&&(K=N.getExtractedText(),K===null&&(K=ds(H)),K===null)){let X=N.processChunk(H);X instanceof Promise?(V=!0,X.then(ce=>{let Ve=typeof ce=="string"?ce:ce?.text??null;Ve!==null&&(I.content=Ve,I.streaming=!1,_e.delete(I.id),Ae.delete(I.id),m(I))}).catch(()=>{})):K=typeof X=="string"?X:X?.text??null}if(!V){K!==null&&K.trim()!==""?I.content=K:Ae.has(I.id)||(I.content=Ne(y));let X=_e.get(I.id);if(X){let ce=X.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(I.id)}Ae.delete(I.id),I.streaming=!1,m(I)}},En=(I,B,y)=>{let D=M.get(I);if(D)return D;let H={id:`nested-${B}-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:I,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:B}};return M.set(I,H),m(H),H},et=[],Le,he=new Map,tt=0,Te="agent",be=!1,re=null,xe=null,kn=new Map,ee=this.config.iterationDisplay??"separate";for(Le=()=>{for(let I=0;I<et.length;I++){let B=et[I].payloadType,y=et[I].payload;if(!be&&Te!=="flow"&&typeof y.stepType=="string"&&(Te="flow"),B==="reasoning_start"){let D=typeof y.id=="string"?y.id:null,H=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(D&&H){C.set(D,H),En(D,H,"reasoning");continue}let N=ge(y,!0)??`reason-${c()}`,K=ie(N);K.reasoning=K.reasoning??{id:N,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Qe(y.startedAt??y.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),K.streaming=!0,K.reasoning.status="streaming",m(K)}else if(B==="reasoning_delta"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)&&M.has(D)){let V=M.get(D),X=y.reasoningText??y.text??y.delta??"";X&&y.hidden!==!0&&V.reasoning&&(V.reasoning.chunks.push(String(X)),m(V));continue}let H=ge(y,!1)??ge(y,!0)??`reason-${c()}`,N=ie(H);N.reasoning=N.reasoning??{id:H,status:"streaming",chunks:[]},N.reasoning.startedAt=N.reasoning.startedAt??Qe(y.startedAt??y.timestamp);let K=y.reasoningText??y.text??y.delta??"";if(K&&y.hidden!==!0){let V=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(V!==void 0){let X=qe(H,V,String(K));N.reasoning.chunks=[X]}else N.reasoning.chunks.push(String(K))}if(N.reasoning.status=y.done?"complete":"streaming",y.done){N.reasoning.completedAt=Qe(y.completedAt??y.timestamp);let V=N.reasoning.startedAt??Date.now();N.reasoning.durationMs=Math.max(0,(N.reasoning.completedAt??Date.now())-V)}N.streaming=N.reasoning.status!=="complete",m(N)}else if(B==="reasoning_complete"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)&&M.has(D)){let X=M.get(D);if(X.reasoning){let ce=typeof y.text=="string"?y.text:"";ce&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(ce),X.reasoning.status="complete",X.streaming=!1,m(X)}C.delete(D),M.delete(D);continue}let H=ge(y,!1)??ge(y,!0)??`reason-${c()}`,N=typeof y.text=="string"?y.text:"";!R.get(H)&&(N||y.scope==="loop")&&ie(H);let K=R.get(H);if(K?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),N&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(N),K.reasoning.status="complete",K.reasoning.completedAt=Qe(y.completedAt??y.timestamp);let X=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-X),K.streaming=!1,m(K)}let V=G(y);V&&O.byStep.delete(V)}else if(B==="tool_start"){b&&(b.streaming=!1,m(b),b=null),typeof y.iteration=="number"&&(tt=y.iteration);let D=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??ut(y,!0)??`tool-${c()}`,H=y.toolName??y.name;if(Be(H)){oe.add(D);continue}ue(Q(y),D);let N=Je(D),K=N.toolCall??{id:D,status:"pending"};K.name=H??K.name,K.status="running",y.parameters!==void 0?K.args=y.parameters:y.args!==void 0&&(K.args=y.args),K.startedAt=K.startedAt??Qe(y.startedAt??y.timestamp),K.completedAt=void 0,K.durationMs=void 0,N.toolCall=K,N.streaming=!0,y.executionId&&(N.agentMetadata={executionId:y.executionId,iteration:y.iteration}),m(N)}else if(B==="tool_output_delta"){let D=ut(y,!1)??ut(y,!0)??`tool-${c()}`;if(oe.has(D))continue;let H=Je(D),N=H.toolCall??{id:D,status:"running"};N.startedAt=N.startedAt??Qe(y.startedAt??y.timestamp);let K=y.text??y.delta??y.message??"";K&&(N.chunks=N.chunks??[],N.chunks.push(String(K))),N.status="running",H.toolCall=N,H.streaming=!0;let V=y.agentContext;(V||y.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:V?.executionId??y.executionId,iteration:V?.iteration??y.iteration}),m(H)}else if(B==="tool_complete"){let D=ut(y,!1)??ut(y,!0)??`tool-${c()}`;if(oe.has(D)){oe.delete(D);continue}let H=Je(D),N=H.toolCall??{id:D,status:"running"};N.status="complete",y.result!==void 0&&(N.result=y.result),typeof y.duration=="number"&&(N.duration=y.duration),N.completedAt=Qe(y.completedAt??y.timestamp);let K=y.duration??y.executionTime;if(typeof K=="number")N.durationMs=K;else{let ce=N.startedAt??Date.now();N.durationMs=Math.max(0,(N.completedAt??Date.now())-ce)}H.toolCall=N,H.streaming=!1;let V=y.agentContext;(V||y.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:V?.executionId??y.executionId,iteration:V?.iteration??y.iteration}),m(H);let X=Q(y);X&&$.byCall.delete(X)}else if(B==="await"&&y.toolName){let D=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,H=D??y.toolId??`local-${c()}`,N=Je(H),K=y.toolName,V=y.origin==="webmcp"&&!Lo(K)?`webmcp:${K}`:K,X=Lo(V),ce=N.toolCall??{id:H,status:"pending"};ce.name=V,ce.args=y.parameters,ce.status=X?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(y.startedAt??y.timestamp??y.awaitedAt),X?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,N.toolCall=ce,N.streaming=!1,N.agentMetadata={...N.agentMetadata,executionId:y.executionId??N.agentMetadata?.executionId,awaitingLocalTool:!0,...D?{webMcpToolCallId:D}:{}},m(N)}else if(B==="text_start"){let D=typeof y.id=="string"?y.id:null,H=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(D&&H){C.set(D,H);continue}let N=b;N&&(Te==="flow"?(Tn(N),gt=N):(N.streaming=!1,m(N)),b=null),A=typeof y.id=="string"?y.id:A,S=""}else if(B==="text_delta"){let D=typeof y.id=="string"?y.id:null,H=D?C.get(D):void 0;if(D&&H){let K=typeof y.delta=="string"?y.delta:"",V=(P.get(D)??"")+K;if(P.set(D,V),V.trim()==="")continue;let X=En(D,H);X.agentMetadata={...X.agentMetadata,executionId:y.executionId,parentToolId:H},Bt(X,V,K,void 0);continue}if(A=typeof y.id=="string"?y.id:A,Te==="flow"){let K=typeof y.delta=="string"?y.delta:"";if(S+=K,S.trim()==="")continue;let V=fe();V.agentMetadata={executionId:y.executionId,iteration:y.iteration},Bt(V,S,K,void 0),w=V;continue}let N=fe();N.content+=y.delta??"",N.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:re??void 0,agentName:xe?.agentName},w=N,m(N)}else if(B==="text_complete"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)){let N=M.get(D);N&&Tn(N),C.delete(D),P.delete(D),M.delete(D);continue}let H=b;H&&(Te==="flow"?(Tn(H),gt=H):((H.content??"")===""&&typeof y.text=="string"&&(H.content=y.text),H.streaming=!1,m(H)),b=null),A=null,S=""}else if(B==="step_complete"){let D=y.stepType,H=y.executionType;if(D==="tool"||H==="context")continue;if(y.success===!1){let N=y.error,K=typeof N=="string"&&N!==""?N:N!=null&&typeof N=="object"&&Reflect.has(N,"message")?String(N.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let V=b;V&&V.streaming&&(V.streaming=!1,m(V)),n({type:"status",status:"idle"});continue}{let N=gt;gt=null;let K=y.stopReason,V=y.result?.response;if(N)K&&(N.stopReason=K),V!=null?Jt(N,V):N.streaming!==!1&&(_e.delete(N.id),Ae.delete(N.id),N.streaming=!1,m(N));else{let X=V!=null&&V!=="";if(X||K){let ce=fe();K&&(ce.stopReason=K),X?Tn(ce,V):(ce.streaming=!1,m(ce))}}continue}}else if(B==="execution_start")Te=y.kind==="flow"?"flow":"agent",be=!0,Te==="agent"&&(xe={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Qe(y.startedAt)});else if(B==="turn_start"){let D=typeof y.iteration=="number"?y.iteration:tt;if(D!==tt){if(xe&&(xe.currentIteration=D),ee==="separate"&&D>1){let H=b;H&&(H.streaming=!1,m(H),kn.set(D-1,H),b=null)}tt=D}re=typeof y.id=="string"?y.id:null,w=null}else if(B==="tool_input_delta"){let D=y.toolCallId??$.lastId;if(D){let H=F.get(D);H?.toolCall&&(H.toolCall.chunks=H.toolCall.chunks??[],H.toolCall.chunks.push(y.delta??""),m(H))}}else{if(B==="tool_input_complete")continue;if(B==="turn_complete"){let D=y.stopReason,H=b??w;if(D&&H!==null){let N=y.id;(!N||H.agentMetadata?.turnId===N)&&(H.stopReason=D,m(H))}re===y.id&&(re=null)}else if(B==="media_start"){let D=String(y.id);he.set(D,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(B==="media_delta"){let D=he.get(String(y.id));D&&typeof y.delta=="string"&&D.parts.push(y.delta)}else if(B==="media_complete"){let D=String(y.id),H=he.get(D);he.delete(D);let N=(typeof y.mediaType=="string"?y.mediaType:void 0)??H?.mediaType??"application/octet-stream",K=typeof y.data=="string"?y.data:void 0,V=typeof y.url=="string"?y.url:H&&H.parts.length>0?H.parts.join(""):void 0,X=null;if(K)X={type:"media",data:K,mediaType:N};else if(V){let Pe=N.toLowerCase();X={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:V,mediaType:N}}let ce=y.toolCallId??H?.toolCallId,Ve=X?[X]:[],de=[];for(let Pe of Ve){if(!Pe||typeof Pe!="object")continue;let ze=Pe,Ue=typeof ze.type=="string"?ze.type:void 0,We=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",we=null,nt="";if(Ue==="media"){let wt=typeof ze.data=="string"?ze.data:void 0;if(!wt)continue;nt=We.length>0?We:"application/octet-stream",we=`data:${nt};base64,${wt}`}else if(Ue==="image-url"){let wt=typeof ze.url=="string"?ze.url:void 0;if(!wt)continue;nt=We,we=wt}else if(Ue==="file-url"){let wt=typeof ze.url=="string"?ze.url:void 0;if(!wt)continue;nt=We,we=wt}else continue;if(we)if(Ue==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:we,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:we,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:we,mimeType:nt});else{let wt=nt||"application/octet-stream";de.push({type:"file",data:we,mimeType:wt,filename:tC(wt)})}}if(de.length>0){let Pe=c(),ze=ce,We={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:tt}};m(We);let we=b;we&&(we.streaming=!1,m(we)),b=null,T.current=null}}else if(B==="execution_complete"){let D=y.kind??Te;D==="agent"&&xe&&(xe.status=y.success?"complete":"error",xe.completedAt=Qe(y.completedAt),xe.stopReason=y.stopReason);let H=b;H&&(D==="flow"&&H.streaming!==!1?Tn(H):(H.streaming=!1,m(H)),b=null),A=null,S="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(B==="execution_error"){let D=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(D)})}else if(B!=="ping"){if(B==="approval_start"){let D=y.approvalId??`approval-${c()}`,H={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};m(H)}else if(B==="step_await"&&y.awaitReason==="approval_required"){let D=y.approvalId??`approval-${c()}`,H={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};m(H)}else if(B==="approval_complete"){let D=y.approvalId;if(D){let N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:y.decision??"approved",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};m(N)}}else if(B==="artifact_start"||B==="artifact_delta"||B==="artifact_update"||B==="artifact_complete"){if(B==="artifact_start"){let D=y.artifactType,H=String(y.id),N=typeof y.title=="string"?y.title:void 0,K=y.file,V;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(V={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:H,artifactType:D,title:N,component:typeof y.component=="string"?y.component:void 0,...V?{file:V}:{}});let X=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(Ce.set(H,{markdown:"",title:N,file:V,...X?{props:X}:{}}),!Se.has(H)){Se.add(H);let ce=zn(this.config.features?.artifacts,{artifactType:D,...V?{file:V}:{}}),Ve=typeof y.component=="string"?y.component:void 0,de={id:`artifact-ref-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:rs(ce,{artifactId:H,title:N,artifactType:D,status:"streaming",...V?{file:V}:{},...Ve?{component:Ve}:{}})};me.set(H,de),m(de)}}else if(B==="artifact_delta"){let D=String(y.id),H=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:D,artDelta:H});let N=Ce.get(D);N&&(N.markdown+=H)}else if(B==="artifact_update"){let D=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:D,component:typeof y.component=="string"?y.component:void 0});let H=Ce.get(String(y.id));H&&(H.props={...H.props??{},...D})}else if(B==="artifact_complete"){let D=String(y.id);n({type:"artifact_complete",id:D});let H=me.get(D);if(H){H.streaming=!1;try{let N=JSON.parse(H.rawContent??"{}");if(N.props){N.props.status="complete";let K=Ce.get(D);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)}H.rawContent=JSON.stringify(N)}catch{}Ce.delete(D),m(H),me.delete(D)}}}else if(B==="transcript_insert"){let D=y.message;if(!D||typeof D!="object")continue;let H=String(D.id??`msg-${c()}`),N=D.role,V={id:H,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:c()};if(m(V),V.rawContent)try{let ce=JSON.parse(V.rawContent)?.props?.artifactId;typeof ce=="string"&&Se.add(ce)}catch{}b=null,T.current=null,_e.delete(H),Ae.delete(H)}else if(B==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let D=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(D)});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}else if(B==="step_error"||B==="dispatch_error"||B==="flow_error"){let D=null;if(y.error instanceof Error)D=y.error;else if(B==="dispatch_error"){let H=y.message??y.error;H!=null&&H!==""&&(D=new Error(String(H)))}else{let H=y.error;typeof H=="string"&&H!==""?D=new Error(H):H!=null&&typeof H=="object"&&Reflect.has(H,"message")&&(D=new Error(String(H.message??H)))}if(D){n({type:"error",error:D});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:I,value:B}=await a.read();if(I)break;l+=s.decode(B,{stream:!0});let y=l.split(`
|
|
9
|
+
${e.description}`:"");return window.confirm(n)},VA=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)}},zA=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},jA=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function wn(e){return e==="card"?"collapsed":e}function lr(e){return e.split(";",1)[0].trim().toLowerCase()}function $A(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(lr(r)===t)return{mode:wn(s),selector:lr(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(lr(r)===o)return{mode:wn(s),selector:o}}function cu(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:wn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?lr(t.file.mimeType):void 0,d=l?$A(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:wn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:wn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:wn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:wn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:wn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function go(e,t){return cu(e,t).mode}function mi(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}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var GA="agent_",KA="flow_";function Pb(e){return e.startsWith(GA)?{kind:"agentId",agentId:e}:e.startsWith(KA)?{kind:"flowId",flowId:e}:null}function Lb(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let u=Pb(l);if(u)return u;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=t?.[i];if(!d)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=Pb(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var cr=uo(rc(),1);var S=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Rb=()=>document.createDocumentFragment(),ue=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let d=i[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},jn=(...e)=>e.filter(Boolean).join(" ");var hi="ask_user_question",gi=8,Xs="data-persona-ask-sheet-for",ZA="Other",e0="Other\u2026",Wb="Type your own answer here",Bb="Send",t0="Next",n0="Back",o0="Submit all",r0="Skip",s0=3,pu="data-ask-current-index",uu="data-ask-question-count",Db="data-ask-answers",fu="data-ask-grouped",Ob="data-ask-layout",a0=e=>e.layout==="pills"?"pills":"rows",i0=e=>e.getAttribute(Ob)==="pills"?"pills":"rows",Ib=!1,Fb=e=>e.replace(/["\\]/g,"\\$&"),No=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===hi,sc=e=>e?.features?.askUserQuestion??{},_o=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,cr.parse)(r,cr.STR|cr.OBJ|cr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},yi=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>gi&&!Ib&&(Ib=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${gi}.`)),t.slice(0,gi)},l0=e=>yi(e)[0]??null,c0=(e,t)=>yi(e)[t]??null,Nb=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},_b=(e,t,n)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=S("span","persona-ask-row-check");o.appendChild(r)}else{let r=S("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},d0=(e,t,n,o)=>{let s=S("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let i=S("span","persona-ask-row-content"),l=S("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let u=S("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}s.appendChild(i);let d=_b(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},p0=e=>{let n=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 n.setAttribute("aria-hidden","true"),n},u0=(e,t,n,o)=>{let s=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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<s0;p++)s.appendChild(p0(o));return s}if(d.forEach((p,f)=>{s.appendChild(d0(p,f,o,i))}),e?.allowFreeText!==!1){let p=o==="rows"?ZA:e0;if(o==="rows"){let f=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(d.length)),f.setAttribute("data-ask-other-row","true");let y=S("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Wb,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??p),y.appendChild(g),f.appendChild(y);let b=_b(o,i,d.length);b&&f.appendChild(b),s.appendChild(f)}else{let f=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??p,s.appendChild(f)}}return s},Ub=(e,t)=>{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 r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Wb,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=S("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Bb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},f0=e=>{let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=S("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Bb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},m0=(e,t,n)=>{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 r=S("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??n0,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=S("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??r0,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=S("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??o0:n.nextLabel??t0,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Zr=e=>{let t=e.getAttribute(Db);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},qb=(e,t)=>{e.setAttribute(Db,JSON.stringify(t))},$n=e=>{let t=Number(e.getAttribute(pu)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},g0=(e,t)=>{e.setAttribute(pu,String(Math.max(0,Math.floor(t))))},Ys=e=>{let t=Number(e.getAttribute(uu)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},dr=e=>e.getAttribute(fu)==="true",h0=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},y0=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ac=(e,t)=>{let{payload:n}=_o(t),o=yi(n),r=Zr(e),s={},i=new Set;return o.forEach((l,d)=>{let u=typeof l?.question=="string"?l.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,d)&&(s[u]=r[d]))}),s},Vb=e=>{let t=Zr(e),n=$n(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let u=d.getAttribute("data-option-label")??"",p=r.has(u);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},zb=e=>{if(!dr(e))return;let t=Zr(e),n=$n(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},mu=(e,t,n)=>{let o=sc(n),r=i0(e),{payload:s,complete:i}=_o(t),l=dr(e),d=$n(e),u=Ys(e),p=l?c0(s,d):l0(s),f=!!p?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${u}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let k=typeof p?.question=="string"?p.question:"";b.textContent=k,b.classList.toggle("persona-ask-question-skeleton",!k&&!i)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let k=u0(p,o,i,r);v.replaceWith(k)}if(r!=="rows"){let k=e.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Ub(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!E?e.appendChild(f0(o)):(!f||l)&&E&&E.remove(),e.setAttribute("data-multi-select",f?"true":"false");let H=e.querySelector('[data-ask-nav-row="true"]');if(l){let k=m0(d,u,o);H?H.replaceWith(k):e.appendChild(k)}else H&&H.remove();Vb(e),zb(e)},b0=(e,t,n)=>{let o=sc(t),r=a0(o),s=e.toolCall.id,i=yi(n),l=Math.max(1,i.length),d=l>1,u=h0(e,i),p=d?y0(e,l):0,f=S("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Xs,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(uu,String(l)),f.setAttribute(pu,String(p)),f.setAttribute(fu,d?"true":"false"),f.setAttribute(Ob,r),qb(f,u),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Nb(f,o);let y=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=S("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",y.appendChild(g);let b=S("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",y.appendChild(b),f.appendChild(y);let E=S("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");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),f.appendChild(E),r!=="rows"&&f.appendChild(Ub(o,r)),mu(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},x0=(e,t,n)=>{let{payload:o}=_o(t),r=Math.max(1,yi(o).length);r>Ys(e)&&(e.setAttribute(uu,String(r)),r>1&&!dr(e)&&e.setAttribute(fu,"true")),mu(e,t,n)},jb=(e,t)=>{let n=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=sc(t);Nb(n,o);let r=S("span","persona-ask-stub-label"),{complete:s}=_o(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Js=(e,t,n)=>{if(!n||!No(e)||sc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Xs}]`).forEach(u=>{u.getAttribute(Xs)!==r&&u.remove()});let i=n.querySelector(`[${Xs}="${Fb(r)}"]`);if(i){x0(i,e,t);return}let{payload:l}=_o(e),d=b0(e,t,l);n.appendChild(d)},pr=(e,t)=>{if(!e)return;let n=t?`[${Xs}="${Fb(t)}"]`:`[${Xs}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},gu=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 n=Zr(e),o=$n(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,qb(e,n),Vb(e),zb(e)},ic=(e,t,n,o)=>{let r=Ys(e),s=Math.max(0,Math.min(r-1,o));g0(e,s),mu(e,t,n)};var oo="suggest_replies";var hu={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:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},lc={name:oo,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. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts 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:hu,origin:"sdk",annotations:{readOnlyHint:!0}},yu=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),es=e=>e.variant==="tool"&&e.toolCall?.name===oo,bu=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});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},cc=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!es(n))continue;let o=bu(n.toolCall?.args);return o.length>0?o:null}return null},$b=new Set,v0=(e,t,n)=>{let o=`${e}:${t}:${n}`;$b.has(o)||($b.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},fr=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],d=n?.[i];l===void 0||d===void 0||l!==d&&v0(i,d,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var xu={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:gi,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},vu={name:hi,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:xu,origin:"sdk",annotations:{readOnlyHint:!0}},Qs=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(vu),fr(e).expose&&t.push(lc),t};var Uo=uo(rc(),1),dc=e=>e.replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),mr=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)}},C0=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Gb=e=>e.status==="complete"?C0(e):e.status==="pending"?"Waiting":"",w0=e=>{let n=(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 n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Kb=e=>e.status==="complete"?w0(e):"Using tool...",pc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},xi=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 pc(t)},uc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return pc(t)},Cu=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=xi(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},fc=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&bi(o,n.slice(s,i.index),[]),i[1]!==void 0?bi(o,i[1],["bold"]):i[2]!==void 0?bi(o,i[2],["italic"]):i[3]!==void 0&&bi(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&bi(o,n.slice(s),[]),o},bi=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},S0=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);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 o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},vi=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},mc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},gc=()=>{let e=S0();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},hc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Uo.parse)(n,Uo.STR|Uo.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?dc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=dc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Xb=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?dc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?dc(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=(0,Uo.parse)(s,Uo.STR|Uo.OBJ),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},yc=()=>{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 Yb="4.18.0";var gr=Yb;var Zs="[Image]";function Jb(e){return typeof e=="string"?[{type:"text",text:e}]:e}function bc(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ea(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Qb(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ho(e){return{type:"text",text:e}}function xc(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Zb(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function ex(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var tx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],M0=["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"],qo=[...tx,...M0];function T0(e){return tx.includes(e)||e.startsWith("image/")}function vc(e){return T0(e.type)}function nx(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function ox(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;vc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function rx(e,t=qo,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function E0(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function sx(e,t){let n=E0(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]||n||"FILE"}var k0=["user","assistant","system"],P0=0;function ax(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Cc(e){return typeof e=="string"?e:void 0}function L0(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?ho(t.text):null;case"image":return typeof t.image=="string"?xc(t.image,{mimeType:Cc(t.mimeType),alt:Cc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?nx(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Cc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Cc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function H0(e,t){let n=ax(t),o=e.map(i=>ax(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,u=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,f=p!==null&&n!==null?Math.min(p,n):p??n;for(let y=0;y<d;y+=1)r[s+y]=f!==null?f-(d-y):u!==null?u+y+1:P0+y;s=l+1}return r.map(i=>new Date(i).toISOString())}function ix(e,t){let n=H0(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!k0.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(L0).filter(p=>p!==null),u=bc(d);o.push({id:r.id,role:i,content:u||(ea(d)?Zs:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Ci(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function wi(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var R0="https://api.runtype.com/v1/dispatch",lx="https://api.runtype.com",We=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},cx=32768,wu=49152,dx=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},px=e=>"reason"in e?e.reason:void 0,ux="The identity proof was not admitted; account history is unavailable",fx="The identity proof was rejected",mx="The request carried no visitor credential",gx="The stored visitor belongs to a different signed-in user",hx=(e,t)=>e instanceof We&&e.code===t;function I0(e){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 r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Su=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 W0(e){switch(e){case"json":return hc;case"regex-json":return gc;case"xml":return yc;default:return mc}}var yx=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function B0(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=yx(n);if(!yx(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=vi(e);return vi(t)!==null&&i===null?t:e}var ts=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;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??R0,this.headers={"Content-Type":"application/json","X-Persona-Version":gr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??W0(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 Ks(t.webmcp):null}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Lb(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||lx}getClientApiUrl(t){return`${this.clientApiBase()}/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}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&px(n)===px(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let r=this.routing(),s=r.agentId??r.flowId,i=n?t.conversationId:void 0,l={token:this.config.clientToken,...s&&{flowId:s},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...i?{conversationId:i}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},d=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(l)});if(!d.ok){let p=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&p.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),i)throw new We("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw n&&d.status===401&&p.error==="visitor_required"?new We("visitor_required","Visitor credential no longer resolves"):i&&d.status===404?new We("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):d.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let u=await d.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(r.sessionId),r}await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(t&&n)try{let o=await this.createClientSession({conversationId:t});return this.finishInit(o,t,!1)}catch(o){if(!hx(o,"not_found")&&!hx(o,"visitor_required"))throw o;return this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable())return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new We("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new We("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/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 r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){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:n})}async submitCSATFeedback(t,n){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:n})}async submitNPSFeedback(t,n){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:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new We("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new We("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new We("proof_not_admitted",ux);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new We("invalid_identity_proof",fx);if(r.includes("visitor token required"))throw new We("visitor_token_missing",mx);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new We("visitor_identity_mismatch",gx);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new We("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new We("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new We("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new We("proof_not_admitted",ux);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new We("invalid_identity_proof",fx)):r.includes("visitor token required")?new We("visitor_token_missing",mx):r.includes("visitor_identity_mismatch")?new We("visitor_identity_mismatch",gx):new We("unauthorized",o||"History request was not authorized")}return new We("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new We("identity_contract_violation","Server reported an ignored identity proof on a success response"):new We("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new We("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let i=this.historyInternals.visitorStore,l=!1;for(;;){let d=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new We("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":gr,...u?{"X-Visitor-Token":u}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(p.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),s,o);continue}if(!p.ok)throw await this.historyErrorFor(p,o);let f=p.headers.get("X-History-Identity-Status"),y=await p.json().catch(()=>{});if(i&&i.revision()!==d)throw new We("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(f,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new We("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(dx),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:dx(r),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let u=d.displayContent.length;if(u>cx)throw new We("payload_too_large",`displayContent exceeds the ${cx} character limit`);o+=u}if(o>wu)throw new We("payload_too_large",`Display projection batch exceeds the ${wu} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=wu,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&this.clientSession?.conversationId===t&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(t){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let p=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:p}),p}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([p])=>p!=="sessionId"&&p!=="session_id")):void 0,i=this.isHistoryCapable(),l={sessionId:o.sessionId,messages:t.messages.filter(Su).map(p=>{let f=i?Ci(p):void 0;return{id:p.id,role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,...f!==void 0&&{displayContent:f}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:d,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,p=>{let f={...l,...p};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",f),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(f),signal:t.signal})});if(!d.ok){let p=await d.json().catch(()=>({error:"Chat request failed"}));if(d.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let y=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:y}),y}if(d.status===429){let y=new Error(p.hint||"Message limit reached for this session.");throw n({type:"error",error:y}),y}if(d.status===410&&p.error==="conversation_deleted"){let y=new We("conversation_deleted","This conversation was deleted");throw n({type:"error",error:y}),y}let f=new Error(p.error||"Failed to send message");throw n({type:"error",error:f}),f}if(!d.body){let p=new Error("No response body received");throw n({type:"error",error:p}),p}u(),n({type:"status",status:"connected"});try{await this.streamResponse(d.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!(r instanceof We)&&!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),i=s?kb(n):void 0,l=this.clientToolsFingerprintSessionId===t,d=s&&l&&this.lastSentClientToolsFingerprint===i,u=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,f;for(let y=0;;y++){if(f=await o({...s&&(p||!d)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),f.status===409&&y===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||lx}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(d.sessionId=i),r&&i){let u=[...Qs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:p,commit:f}=await this.sendWithClientToolsDiff(i,u,y=>{let g={...d,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return p.ok&&f(),p}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(d),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Su).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Qs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(t);return i&&(r.context=i),r}async buildPayload(t){let n=t.slice().filter(Su).sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,d]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=d);let s=[...Qs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(t);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let d=l;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return o.current=f,r(f),f},u=p=>o.current?o.current:d(p);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(i.current=l.partId);let p=u(l.partId);l.partId!==void 0&&!p.partId&&(p.partId=l.partId),p.content+=l.text,r(p)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",d=Date.now(),u=0,p=()=>d+u++,f=U=>{let ee=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,A=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,T=U.tools?U.tools.map(B=>({...B,chunks:B.chunks?[...B.chunks]:void 0})):void 0;return{...U,reasoning:ee,toolCall:A,tools:T}},y=U=>{if(U.role!=="assistant"||U.variant)return!0;let ee=Array.isArray(U.contentParts)&&U.contentParts.length>0,A=typeof U.rawContent=="string"&&U.rawContent.trim()!=="";return typeof U.content=="string"&&U.content.trim()!==""||ee||A||!!U.stopReason},g=U=>{y(U)&&n({type:"message",message:f(U)})},b=null,v=null,E={current:null},H={current:null},k=null,M="",x=new Map,w=new Map,L=new Map,P=new Map,D=new Map,q={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},N=U=>{if(U==null)return null;try{return String(U)}catch{return null}},X=U=>N(U.stepId??U.step_id??U.step??U.parentId??U.flowStepId??U.flow_step_id),de=U=>N(U.callId??U.call_id??U.requestId??U.request_id??U.toolCallId??U.tool_call_id??U.stepId??U.step_id),me=o,xe=!1,ye=()=>{if(b)return b;let U,ee="",A=k;return!xe&&me?(U=me,xe=!0,ee=r??""):me&&A?U=`${me}_${A}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:U,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},ne=(U,ee)=>{q.lastId=ee,U&&q.byStep.set(U,ee)},ie=(U,ee)=>{let A=U.reasoningId??U.id,T=X(U);if(A){let W=String(A);return ne(T,W),W}if(T){let W=q.byStep.get(T);if(W)return q.lastId=W,W}if(q.lastId&&!ee)return q.lastId;if(!ee)return null;let B=`reason-${p()}`;return ne(T,B),B},le=U=>{let ee=P.get(U);if(ee)return ee;let A={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:U,status:"streaming",chunks:[]}};return P.set(U,A),g(A),A},I=(U,ee)=>{$.lastId=ee,U&&$.byCall.set(U,ee)},Z=new Set,pe=new Map,Ee=new Set,Ce=new Map,we=U=>{if(!U)return!1;let ee=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},Pe=(U,ee)=>{let A=U.toolId??U.id,T=de(U);if(A){let W=String(A);return I(T,W),W}if(T){let W=$.byCall.get(T);if(W)return $.lastId=W,W}if($.lastId&&!ee)return $.lastId;if(!ee)return null;let B=`tool-${p()}`;return I(T,B),B},Re=U=>{let ee=D.get(U);if(ee)return ee;let A={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:U,status:"pending"}};return D.set(U,A),g(A),A},nt=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let ee=Number(U);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let A=Date.parse(U);if(!Number.isNaN(A))return A}return Date.now()},Je=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},Be=new Map,ot=new Map,vt=new Map,yt=(U,ee,A)=>{let T=vt.get(U);T||(T=[],vt.set(U,T));let B=0,W=T.length;for(;B<W;){let Y=B+W>>>1;T[Y].seq<ee?B=Y+1:W=Y}T[B]?.seq===ee?T[B]={seq:ee,text:A}:T.splice(B,0,{seq:ee,text:A});let O="";for(let Y=0;Y<T.length;Y++)O+=T[Y].text;return O},Dn=(U,ee)=>{let A=Je(ee),T=ot.get(U.id),B=B0(T,A);U.rawContent=B;let W=Be.get(U.id),O=ae=>{let it=U.content??"";ae.trim()!==""&&(it.trim().length===0||ae.startsWith(it)||ae.trimStart().startsWith(it.trim()))&&(U.content=ae)},Y=()=>{if(W){let ae=W.close?.();ae instanceof Promise&&ae.catch(()=>{})}Be.delete(U.id),ot.delete(U.id),U.streaming=!1,g(U)};if(!W){O(A),Y();return}let Q=vi(B);if(Q!==null&&Q.trim()!==""){O(Q),Y();return}let K=ae=>{let it=typeof ae=="string"?ae:ae?.text??null;if(it!==null&&it.trim()!=="")return it;let et=W.getExtractedText();return et!==null&&et.trim()!==""?et:A},G;try{G=W.processChunk(B)}catch{O(A),Y();return}if(G instanceof Promise){G.then(ae=>{O(K(ae)),Y()}).catch(()=>{O(A),Y()});return}O(K(G)),Y()},Me=null,Ke=(U,ee,A,T)=>{U.rawContent=ee,Be.has(U.id)||Be.set(U.id,this.createStreamParser());let B=Be.get(U.id),W=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(W&&ot.set(U.id,ee),B.__isPlainTextParser===!0){U.content=T!==void 0?ee:U.content+A,ot.delete(U.id),Be.delete(U.id),U.rawContent=void 0,g(U);return}let Y=B.processChunk(ee);if(Y instanceof Promise)Y.then(Q=>{let K=typeof Q=="string"?Q:Q?.text??null;K!==null&&K.trim()!==""?(U.content=K,g(U)):!W&&!ee.trim().startsWith("<")&&(U.content=T!==void 0?ee:U.content+A,ot.delete(U.id),Be.delete(U.id),U.rawContent=void 0,g(U))}).catch(()=>{U.content=T!==void 0?ee:U.content+A,ot.delete(U.id),Be.delete(U.id),U.rawContent=void 0,g(U)});else{let Q=typeof Y=="string"?Y:Y?.text??null;Q!==null&&Q.trim()!==""?(U.content=Q,g(U)):!W&&!ee.trim().startsWith("<")&&(U.content=T!==void 0?ee:U.content+A,ot.delete(U.id),Be.delete(U.id),U.rawContent=void 0,g(U))}},rt=(U,ee)=>{let A=ee??U.content;if(A==null||A===""){U.streaming=!1,g(U);return}let B=ot.get(U.id)??Je(A);U.rawContent=B;let W=Be.get(U.id),O=null,Y=!1;if(W&&(O=W.getExtractedText(),O===null&&(O=vi(B)),O===null)){let Q=W.processChunk(B);Q instanceof Promise?(Y=!0,Q.then(K=>{let G=typeof K=="string"?K:K?.text??null;G!==null&&(U.content=G,U.streaming=!1,Be.delete(U.id),ot.delete(U.id),g(U))}).catch(()=>{})):O=typeof Q=="string"?Q:Q?.text??null}if(!Y){O!==null&&O.trim()!==""?U.content=O:ot.has(U.id)||(U.content=Je(A));let Q=Be.get(U.id);if(Q){let K=Q.close?.();K instanceof Promise&&K.catch(()=>{}),Be.delete(U.id)}ot.delete(U.id),U.streaming=!1,g(U)}},Kt=(U,ee,A)=>{let T=w.get(U);if(T)return T;let B={id:`nested-${ee}-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...A?{variant:A}:{},...A==="reasoning"?{reasoning:{id:U,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return w.set(U,B),g(B),B},zt=[],Xn,Ye=new Map,Qe=0,bt="agent",en=!1,wo=null,It=null,Ko=new Map,Cs=this.config.iterationDisplay??"separate";for(Xn=()=>{for(let U=0;U<zt.length;U++){let ee=zt[U].payloadType,A=zt[U].payload;if(!en&&bt!=="flow"&&typeof A.stepType=="string"&&(bt="flow"),ee==="reasoning_start"){let T=typeof A.id=="string"?A.id:null,B=typeof A.parentToolCallId=="string"&&A.parentToolCallId?A.parentToolCallId:null;if(T&&B){x.set(T,B),Kt(T,B,"reasoning");continue}let W=ie(A,!0)??`reason-${p()}`,O=le(W);O.reasoning=O.reasoning??{id:W,status:"streaming",chunks:[]},O.reasoning.startedAt=O.reasoning.startedAt??nt(A.startedAt??A.timestamp),O.reasoning.completedAt=void 0,O.reasoning.durationMs=void 0,(A.scope==="loop"||A.scope==="turn")&&(O.reasoning.scope=A.scope),O.streaming=!0,O.reasoning.status="streaming",g(O)}else if(ee==="reasoning_delta"){let T=typeof A.id=="string"?A.id:null;if(T&&x.has(T)&&w.has(T)){let Y=w.get(T),Q=A.reasoningText??A.text??A.delta??"";Q&&A.hidden!==!0&&Y.reasoning&&(Y.reasoning.chunks.push(String(Q)),g(Y));continue}let B=ie(A,!1)??ie(A,!0)??`reason-${p()}`,W=le(B);W.reasoning=W.reasoning??{id:B,status:"streaming",chunks:[]},W.reasoning.startedAt=W.reasoning.startedAt??nt(A.startedAt??A.timestamp);let O=A.reasoningText??A.text??A.delta??"";if(O&&A.hidden!==!0){let Y=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(Y!==void 0){let Q=yt(B,Y,String(O));W.reasoning.chunks=[Q]}else W.reasoning.chunks.push(String(O))}if(W.reasoning.status=A.done?"complete":"streaming",A.done){W.reasoning.completedAt=nt(A.completedAt??A.timestamp);let Y=W.reasoning.startedAt??Date.now();W.reasoning.durationMs=Math.max(0,(W.reasoning.completedAt??Date.now())-Y)}W.streaming=W.reasoning.status!=="complete",g(W)}else if(ee==="reasoning_complete"){let T=typeof A.id=="string"?A.id:null;if(T&&x.has(T)&&w.has(T)){let Q=w.get(T);if(Q.reasoning){let K=typeof A.text=="string"?A.text:"";K&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(K),Q.reasoning.status="complete",Q.streaming=!1,g(Q)}x.delete(T),w.delete(T);continue}let B=ie(A,!1)??ie(A,!0)??`reason-${p()}`,W=typeof A.text=="string"?A.text:"";!P.get(B)&&(W||A.scope==="loop")&&le(B);let O=P.get(B);if(O?.reasoning){(A.scope==="loop"||A.scope==="turn")&&(O.reasoning.scope=A.scope),W&&O.reasoning.chunks.length===0&&O.reasoning.chunks.push(W),O.reasoning.status="complete",O.reasoning.completedAt=nt(A.completedAt??A.timestamp);let Q=O.reasoning.startedAt??Date.now();O.reasoning.durationMs=Math.max(0,(O.reasoning.completedAt??Date.now())-Q),O.streaming=!1,g(O)}let Y=X(A);Y&&q.byStep.delete(Y)}else if(ee==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof A.iteration=="number"&&(Qe=A.iteration);let T=(typeof A.toolCallId=="string"?A.toolCallId:void 0)??Pe(A,!0)??`tool-${p()}`,B=A.toolName??A.name;if(we(B)){Z.add(T);continue}I(de(A),T);let W=Re(T),O=W.toolCall??{id:T,status:"pending"};O.name=B??O.name,O.status="running",A.parameters!==void 0?O.args=A.parameters:A.args!==void 0&&(O.args=A.args),O.startedAt=O.startedAt??nt(A.startedAt??A.timestamp),O.completedAt=void 0,O.durationMs=void 0,W.toolCall=O,W.streaming=!0,A.executionId&&(W.agentMetadata={executionId:A.executionId,iteration:A.iteration}),g(W)}else if(ee==="tool_output_delta"){let T=Pe(A,!1)??Pe(A,!0)??`tool-${p()}`;if(Z.has(T))continue;let B=Re(T),W=B.toolCall??{id:T,status:"running"};W.startedAt=W.startedAt??nt(A.startedAt??A.timestamp);let O=A.text??A.delta??A.message??"";O&&(W.chunks=W.chunks??[],W.chunks.push(String(O))),W.status="running",B.toolCall=W,B.streaming=!0;let Y=A.agentContext;(Y||A.executionId)&&(B.agentMetadata=B.agentMetadata??{executionId:Y?.executionId??A.executionId,iteration:Y?.iteration??A.iteration}),g(B)}else if(ee==="tool_complete"){let T=Pe(A,!1)??Pe(A,!0)??`tool-${p()}`;if(Z.has(T)){Z.delete(T);continue}let B=Re(T),W=B.toolCall??{id:T,status:"running"};W.status="complete",A.result!==void 0&&(W.result=A.result),typeof A.duration=="number"&&(W.duration=A.duration),W.completedAt=nt(A.completedAt??A.timestamp);let O=A.duration??A.executionTime;if(typeof O=="number")W.durationMs=O;else{let K=W.startedAt??Date.now();W.durationMs=Math.max(0,(W.completedAt??Date.now())-K)}B.toolCall=W,B.streaming=!1;let Y=A.agentContext;(Y||A.executionId)&&(B.agentMetadata=B.agentMetadata??{executionId:Y?.executionId??A.executionId,iteration:Y?.iteration??A.iteration}),g(B);let Q=de(A);Q&&$.byCall.delete(Q)}else if(ee==="await"&&A.toolName){let T=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,B=T??A.toolId??`local-${p()}`,W=Re(B),O=A.toolName,Y=A.origin==="webmcp"&&!ir(O)?`webmcp:${O}`:O,Q=ir(Y),K=W.toolCall??{id:B,status:"pending"};K.name=Y,K.args=A.parameters,K.status=Q?"running":"complete",K.chunks=K.chunks??[],K.startedAt=K.startedAt??nt(A.startedAt??A.timestamp??A.awaitedAt),Q?(K.completedAt=void 0,K.duration=void 0,K.durationMs=void 0):K.completedAt=K.completedAt??K.startedAt,W.toolCall=K,W.streaming=!1,W.agentMetadata={...W.agentMetadata,executionId:A.executionId??W.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(W)}else if(ee==="text_start"){let T=typeof A.id=="string"?A.id:null,B=typeof A.parentToolCallId=="string"&&A.parentToolCallId?A.parentToolCallId:null;if(T&&B){x.set(T,B);continue}let W=b;W&&(bt==="flow"?(rt(W),Me=W):(W.streaming=!1,g(W)),b=null),k=typeof A.id=="string"?A.id:k,M=""}else if(ee==="text_delta"){let T=typeof A.id=="string"?A.id:null,B=T?x.get(T):void 0;if(T&&B){let O=typeof A.delta=="string"?A.delta:"",Y=(L.get(T)??"")+O;if(L.set(T,Y),Y.trim()==="")continue;let Q=Kt(T,B);Q.agentMetadata={...Q.agentMetadata,executionId:A.executionId,parentToolId:B},Ke(Q,Y,O,void 0);continue}if(k=typeof A.id=="string"?A.id:k,bt==="flow"){let O=typeof A.delta=="string"?A.delta:"";if(M+=O,M.trim()==="")continue;let Y=ye();Y.agentMetadata={executionId:A.executionId,iteration:A.iteration},Ke(Y,M,O,void 0),v=Y;continue}let W=ye();W.content+=A.delta??"",W.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:wo??void 0,agentName:It?.agentName},v=W,g(W)}else if(ee==="text_complete"){let T=typeof A.id=="string"?A.id:null;if(T&&x.has(T)){let W=w.get(T);W&&rt(W),x.delete(T),L.delete(T),w.delete(T);continue}let B=b;B&&(bt==="flow"?(rt(B),Me=B):((B.content??"")===""&&typeof A.text=="string"&&(B.content=A.text),B.streaming=!1,g(B)),b=null),k=null,M=""}else if(ee==="step_complete"){let T=A.stepType,B=A.executionType;if(T==="tool"||B==="context")continue;if(A.success===!1){let W=A.error,O=typeof W=="string"&&W!==""?W:W!=null&&typeof W=="object"&&Reflect.has(W,"message")?String(W.message??"Step failed"):"Step failed";n({type:"error",error:new Error(O)});let Y=b;Y&&Y.streaming&&(Y.streaming=!1,g(Y)),n({type:"status",status:"idle"});continue}{let W=Me;Me=null;let O=A.stopReason,Y=A.result?.response;if(W)O&&(W.stopReason=O),Y!=null?Dn(W,Y):W.streaming!==!1&&(Be.delete(W.id),ot.delete(W.id),W.streaming=!1,g(W));else{let Q=Y!=null&&Y!=="";if(Q||O){let K=ye();O&&(K.stopReason=O),Q?rt(K,Y):(K.streaming=!1,g(K))}}continue}}else if(ee==="execution_start")bt=A.kind==="flow"?"flow":"agent",en=!0,bt==="agent"&&(It={executionId:A.executionId,agentId:A.agentId??"virtual",agentName:A.agentName??"",status:"running",currentIteration:0,maxTurns:A.maxTurns??1,startedAt:nt(A.startedAt)});else if(ee==="turn_start"){let T=typeof A.iteration=="number"?A.iteration:Qe;if(T!==Qe){if(It&&(It.currentIteration=T),Cs==="separate"&&T>1){let B=b;B&&(B.streaming=!1,g(B),Ko.set(T-1,B),b=null)}Qe=T}wo=typeof A.id=="string"?A.id:null,v=null}else if(ee==="tool_input_delta"){let T=A.toolCallId??$.lastId;if(T){let B=D.get(T);B?.toolCall&&(B.toolCall.chunks=B.toolCall.chunks??[],B.toolCall.chunks.push(A.delta??""),g(B))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let T=A.stopReason,B=b??v;if(T&&B!==null){let W=A.id;(!W||B.agentMetadata?.turnId===W)&&(B.stopReason=T,g(B))}wo===A.id&&(wo=null)}else if(ee==="media_start"){let T=String(A.id);Ye.set(T,{mediaType:typeof A.mediaType=="string"?A.mediaType:void 0,role:typeof A.role=="string"?A.role:void 0,toolCallId:A.toolCallId,parts:[]})}else if(ee==="media_delta"){let T=Ye.get(String(A.id));T&&typeof A.delta=="string"&&T.parts.push(A.delta)}else if(ee==="media_complete"){let T=String(A.id),B=Ye.get(T);Ye.delete(T);let W=(typeof A.mediaType=="string"?A.mediaType:void 0)??B?.mediaType??"application/octet-stream",O=typeof A.data=="string"?A.data:void 0,Y=typeof A.url=="string"?A.url:B&&B.parts.length>0?B.parts.join(""):void 0,Q=null;if(O)Q={type:"media",data:O,mediaType:W};else if(Y){let it=W.toLowerCase();Q={type:it==="image"||it.startsWith("image/")?"image-url":"file-url",url:Y,mediaType:W}}let K=A.toolCallId??B?.toolCallId,G=Q?[Q]:[],ae=[];for(let it of G){if(!it||typeof it!="object")continue;let et=it,xt=typeof et.type=="string"?et.type:void 0,ge=typeof et.mediaType=="string"?et.mediaType.toLowerCase():"",he=null,tn="";if(xt==="media"){let _e=typeof et.data=="string"?et.data:void 0;if(!_e)continue;tn=ge.length>0?ge:"application/octet-stream",he=`data:${tn};base64,${_e}`}else if(xt==="image-url"){let _e=typeof et.url=="string"?et.url:void 0;if(!_e)continue;tn=ge,he=_e}else if(xt==="file-url"){let _e=typeof et.url=="string"?et.url:void 0;if(!_e)continue;tn=ge,he=_e}else continue;if(he)if(xt==="image-url"||tn.startsWith("image/"))ae.push({type:"image",image:he,...tn.includes("/")?{mimeType:tn}:{}});else if(tn.startsWith("audio/"))ae.push({type:"audio",audio:he,mimeType:tn});else if(tn.startsWith("video/"))ae.push({type:"video",video:he,mimeType:tn});else{let _e=tn||"application/octet-stream";ae.push({type:"file",data:he,mimeType:_e,filename:I0(_e)})}}if(ae.length>0){let it=p(),et=K,ge={id:`agent-media-${typeof et=="string"&&et.length>0?`${et}-${it}`:String(it)}`,role:"assistant",content:"",contentParts:ae,createdAt:new Date().toISOString(),streaming:!1,sequence:it,agentMetadata:{executionId:A.executionId,iteration:typeof A.iteration=="number"?A.iteration:Qe}};g(ge);let he=b;he&&(he.streaming=!1,g(he)),b=null,E.current=null}}else if(ee==="execution_complete"){let T=A.kind??bt;T==="agent"&&It&&(It.status=A.success?"complete":"error",It.completedAt=nt(A.completedAt),It.stopReason=A.stopReason);let B=b;B&&(T==="flow"&&B.streaming!==!1?rt(B):(B.streaming=!1,g(B)),b=null),k=null,M="",Me=null,n({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let T=typeof A.error=="string"?A.error:A.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(ee!=="ping"){if(ee==="approval_start"){let T=A.approvalId??`approval-${p()}`,B={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:T,status:"pending",agentId:It?.agentId??"virtual",executionId:A.executionId??It?.executionId??"",toolName:A.toolName??"",toolType:A.toolType,description:A.description??`Execute ${A.toolName??"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(B)}else if(ee==="step_await"&&A.awaitReason==="approval_required"){let T=A.approvalId??`approval-${p()}`,B={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:T,status:"pending",agentId:It?.agentId??"virtual",executionId:A.executionId??It?.executionId??"",toolName:A.toolName??"",toolType:A.toolType,description:A.description??`Execute ${A.toolName??"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(B)}else if(ee==="approval_complete"){let T=A.approvalId;if(T){let W={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:T,status:A.decision??"approved",agentId:It?.agentId??"virtual",executionId:A.executionId??It?.executionId??"",toolName:A.toolName??"",description:A.description??"",resolvedAt:Date.now()}};g(W)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let T=A.artifactType,B=String(A.id),W=typeof A.title=="string"?A.title:void 0,O=A.file,Y;O&&typeof O=="object"&&!Array.isArray(O)&&typeof O.path=="string"&&typeof O.mimeType=="string"&&(Y={path:O.path,mimeType:O.mimeType,...typeof O.language=="string"?{language:O.language}:{}}),n({type:"artifact_start",id:B,artifactType:T,title:W,component:typeof A.component=="string"?A.component:void 0,...Y?{file:Y}:{}});let Q=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?{...A.props}:void 0;if(Ce.set(B,{markdown:"",title:W,file:Y,...Q?{props:Q}:{}}),!Ee.has(B)){Ee.add(B);let K=go(this.config.features?.artifacts,{artifactType:T,...Y?{file:Y}:{}}),G=typeof A.component=="string"?A.component:void 0,ae={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:mi(K,{artifactId:B,title:W,artifactType:T,status:"streaming",...Y?{file:Y}:{},...G?{component:G}:{}})};pe.set(B,ae),g(ae)}}else if(ee==="artifact_delta"){let T=String(A.id),B=typeof A.delta=="string"?A.delta:String(A.delta??"");n({type:"artifact_delta",id:T,artDelta:B});let W=Ce.get(T);W&&(W.markdown+=B)}else if(ee==="artifact_update"){let T=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:T,component:typeof A.component=="string"?A.component:void 0});let B=Ce.get(String(A.id));B&&(B.props={...B.props??{},...T})}else if(ee==="artifact_complete"){let T=String(A.id);n({type:"artifact_complete",id:T});let B=pe.get(T);if(B){B.streaming=!1;try{let W=JSON.parse(B.rawContent??"{}");if(W.props){W.props.status="complete";let O=Ce.get(T);O?.markdown&&(W.props.markdown=O.markdown),O?.file&&(W.props.file=O.file),W.component==="PersonaArtifactInline"&&O?.props&&Object.keys(O.props).length>0&&(W.props.componentProps=O.props)}B.rawContent=JSON.stringify(W)}catch{}Ce.delete(T),g(B),pe.delete(T)}}}else if(ee==="transcript_insert"){let T=A.message;if(!T||typeof T!="object")continue;let B=String(T.id??`msg-${p()}`),W=T.role,Y={id:B,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:p()};if(g(Y),Y.rawContent)try{let K=JSON.parse(Y.rawContent)?.props?.artifactId;typeof K=="string"&&Ee.add(K)}catch{}b=null,E.current=null,Be.delete(B),ot.delete(B)}else if(ee==="error"){if(A.recoverable===!1&&A.error!=null&&A.error!==""){let T=typeof A.error=="string"?A.error:A.error?.message!=null?String(A.error.message):"Execution error";n({type:"error",error:new Error(T)});let B=b;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let T=null;if(A.error instanceof Error)T=A.error;else if(ee==="dispatch_error"){let B=A.message??A.error;B!=null&&B!==""&&(T=new Error(String(B)))}else{let B=A.error;typeof B=="string"&&B!==""?T=new Error(B):B!=null&&typeof B=="object"&&Reflect.has(B,"message")&&(T=new Error(String(B.message??B)))}if(T){n({type:"error",error:T});let B=b;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"})}}}}}zt.length=0};;){let{done:U,value:ee}=await s.read();if(U)break;l+=i.decode(ee,{stream:!0});let A=l.split(`
|
|
13
13
|
|
|
14
|
-
`);l=
|
|
15
|
-
`),N="message",K="",V=null;for(let de of H)de.startsWith("event:")?N=de.replace("event:","").trim():de.startsWith("data:")?K+=de.replace("data:","").trim():de.startsWith("id:")&&(V=de.slice(3).trim());let X=()=>{V!==null&&V!==""&&n({type:"cursor",id:V})};if(!K){X();continue}let ce;try{ce=JSON.parse(K)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let Ve=N!=="message"?N:ce.type??"message";if(this.onSSEEvent?.(Ve,ce),this.parseSSEEvent){T.current=b;let de=await this.handleCustomSSEEvent(ce,n,T,m,c,L);if(T.current&&T.current!==b&&(b=T.current),de){X();continue}}et.push({payloadType:Ve,payload:ce}),Le(),X()}}Le()}};function Kg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ia(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Fi="[Image]";function Xg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Jg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Oi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Qg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Oo(e){return{type:"text",text:e}}function Yg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Zg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function eh(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var th=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],rC=["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"],co=[...th,...rC];function aC(e){return th.includes(e)||e.startsWith("image/")}function Ni(e){return aC(e.type)}async function nh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ni(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function oh(e,t=co,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function sC(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function rh(e,t){let n=sC(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]||n||"FILE"}var _i=class{constructor(t=24e3,n={}){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 o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.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 n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);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 n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let a=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}r.onended=()=>{let s=this.activeSources.indexOf(r);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 n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<n;a++){let s=r.getInt16(a*2,!0);o[a]=s/32768}return o}};var ah=16e3,iC=24e3,lC=4096,cC=1380533830;function dC(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===cC?new Uint8Array(e,44):new Uint8Array(e)}function pC(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 ps=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,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:ah,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(f=>f.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:ah});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new _i(iC);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${pC(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,a,c,r))},c.onmessage=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let g=f.code?` (code ${f.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,n,o,r){let a=t.createMediaStreamSource(n);this.sourceNode=a;let s=t.createScriptProcessor(lC,1,1);this.processor=s,s.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let f=Math.max(-1,Math.min(1,p[c]));d[c]=f<0?f*32768:f*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!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,n){if(n!==this.callGeneration||!this.playback)return;let o=dC(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(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Cr=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=n=>{let o=Array.from(n.results).map(a=>a[0]).map(a=>a.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("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(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("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 No(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ps(e.runtype);case"browser":if(!Cr.isSupported())throw new Error("Browser speech recognition not supported");return new Cr(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ui(e){if(e?.type==="custom"&&e.custom)return No({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return No({type:"runtype",runtype:e.runtype});if(Cr.isSupported())return No({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function us(e){try{return Ui(e),!0}catch{return!1}}function la(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 n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var _o=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(r.voice=s)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):la(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=s=>{let l=s.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var wr=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,n){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,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{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(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function dd(e){if(!e)return"";let t=uC(e);return sh(t!==null?t:e)}function uC(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[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 sh(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=A.pop()??"";for(let T of A){let B=T.split(`
|
|
15
|
+
`),W="message",O="",Y=null;for(let ae of B)ae.startsWith("event:")?W=ae.replace("event:","").trim():ae.startsWith("data:")?O+=ae.replace("data:","").trim():ae.startsWith("id:")&&(Y=ae.slice(3).trim());let Q=()=>{Y!==null&&Y!==""&&n({type:"cursor",id:Y})};if(!O){Q();continue}let K;try{K=JSON.parse(O)}catch(ae){n({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let G=W!=="message"?W:K.type??"message";if(this.onSSEEvent?.(G,K),this.parseSSEEvent){E.current=b;let ae=await this.handleCustomSSEEvent(K,n,E,g,p,H);if(E.current&&E.current!==b&&(b=E.current),ae){Q();continue}}zt.push({payloadType:G,payload:K}),Xn(),Q()}}Xn()}};function bx(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ta(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function hr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Gn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function xx(e){return e instanceof Gn}var wc=class{constructor(t=24e3,n={}){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 o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.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 n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);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 n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let i=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of i)l()}r.onended=()=>{let i=this.activeSources.indexOf(r);i!==-1&&this.activeSources.splice(i,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 n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}};var vx=16e3,D0=24e3,O0=4096,F0=1380533830;function N0(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===F0?new Uint8Array(e,44):new Uint8Array(e)}function _0(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 Si=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,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:vx,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(f=>f.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:vx});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new wc(D0);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${_0(o)}/ws/agents/${encodeURIComponent(t)}/voice`,p=new WebSocket(u,["runtype.bearer",n]);p.binaryType="arraybuffer",this.ws=p,p.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,p,r))},p.onmessage=f=>this.handleMessage(f,r),p.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},p.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let y=f.code?` (code ${f.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}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,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let i=t.createScriptProcessor(O0,1,1);this.processor=i,i.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),u=new Int16Array(d.length);for(let p=0;p<d.length;p++){let f=Math.max(-1,Math.min(1,d[p]));u[p]=f<0?f*32768:f*32767}o.send(u.buffer)},s.connect(i),i.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!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,n){if(n!==this.callGeneration||!this.playback)return;let o=N0(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(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var ns=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=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("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(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("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 yr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Si(e.runtype);case"browser":if(!ns.isSupported())throw new Error("Browser speech recognition not supported");return new ns(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Sc(e){if(e?.type==="custom"&&e.custom)return yr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return yr({type:"runtype",runtype:e.runtype});if(ns.isSupported())return yr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ai(e){try{return Sc(e),!0}catch{return!1}}function na(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 n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var br=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):na(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var os=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,n){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,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{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(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Au(e){if(!e)return"";let t=U0(e);return Cx(t!==null?t:e)}function U0(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[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 Cx(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 Mu=null,wx=e=>{Mu=e},Tu=()=>Mu?Mu():import("./runtype-tts-entry");var z0=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function j0(e,t){return z0.some(n=>e[n]!==t[n])}var yo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function Eu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="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 n.message?`${o}
|
|
18
18
|
|
|
19
|
-
_Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]}),dh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ph=e=>Lo(e)||e===On,ca=class{constructor(t={},n){this.config=t;this.callbacks=n;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 wr(()=>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 n=t.message.toolCall,o=!!n?.name&&(Lo(n.name)||n.name===On&&Bo(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&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 n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(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(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new vr(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,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 n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||ud().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 us(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 n=_o.isSupported()?new _o({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,s=t.browserFallback!==!1;if(o&&r&&a)return ud().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(s&&n)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=No(n);let r=(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:r,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(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(){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 n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}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,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!hC(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=o,this.client=new vr(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:a,id:s,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:f}=t,m={id:s??(n==="user"?ia():n==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...c!==void 0&&{voiceProcessing:c},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}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 n=[];for(let o of t){let{role:r,content:a,llmContent:s,contentParts:l,id:p,createdAt:d,sequence:c,streaming:f=!1,voiceProcessing:g,rawContent:m}=o,w={id:p??(r==="user"?ia():r==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(w)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,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 applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
|
|
19
|
+
_Details: ${n.message}_`:o}var Mi=e=>({isError:!0,content:[{type:"text",text:e}]}),Mx=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Tx=e=>ir(e)||e===oo,oa=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=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.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new os(()=>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 n=t.message.toolCall,o=!!n?.name&&(ir(n.name)||n.name===oo&&fr(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&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,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(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.historyInternals=this.composeHistoryInternals(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ts(t,this.historyInternals),this.syncVisitorStoreSubscription(),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 n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Tu().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 Ai(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 n=br.isSupported()?new br({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return Tu().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let u=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new d(u,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=yr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let d=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=d.id}if(l){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let d=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=d.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),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(){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;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);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){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}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,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new yo("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let n=this.requireHistoryProvider(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new Gn("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new yo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,i=await o.getPage(t,{context:r});if(s!==this.historyOpenEpoch)throw new yo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new yo("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||t,this.activeConversationRevision=l.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of i.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),i=n??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,d=this.olderPageRequests.get(l);if(d)return d;let u=this.fetchOlderPage(r,t,i,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,u),u}async fetchOlderPage(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=wi(this.messages,i.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=i.nextCursor;for(let d of i.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new yo("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new yo("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new yo("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:t});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new yo("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(t,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(f=>f.id)),d=this.messages.some(f=>l.has(f.id)),u=i.messages[0]?.createdAt,p;if(!d)p=i.messages.map(f=>this.ensureSequence(f));else{let f=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(g=>l.has(g.id)||g.id===f?!0:u!==void 0&&g.createdAt<u);p=wi(y,i.messages).map(g=>this.ensureSequence(g))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let f of i.messages)this.acknowledgedProjections.set(f.id,f.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let n of t){let o=Ci(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Ci(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof We&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof We?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof We&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o},this.handleEvent);return}catch(s){if(!e.isConversationDeleted(s))throw s;let i=await this.recoverFromDeletedConversation(r);if(!i)throw s;this.recordDispatchedProjections([i]),await this.client.dispatch({messages:[i],signal:n.signal,assistantMessageId:o},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!j0(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new ts(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:d,streaming:u=!1,voiceProcessing:p,rawContent:f}=t,g={id:i??(n==="user"?ta():n==="assistant"?hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...f!==void 0&&{rawContent:f}};return this.upsertMessage(g),g}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 n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:d,createdAt:u,sequence:p,streaming:f=!1,voiceProcessing:y,rawContent:g}=o,v={id:d??(r==="user"?ta():r==="assistant"?hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:f,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:d}=t,u={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
20
20
|
|
|
21
|
-
`),
|
|
21
|
+
`),i=[s,n].filter(Boolean).join(`
|
|
22
22
|
|
|
23
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];a&&d.push(Oo(a)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];s&&d.push(Oo(s)),d.push(...r.contentParts),t.contentParts=d}else a&&(t.llmContent=s);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=ia(),a=Fo();this.activeAssistantMessageId=null;let s=n?.contentParts&&Oi(n.contentParts)?Fi:"",l={id:r,role:"user",content:o||s,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(f=>f.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:a},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!f){let g=fd(c,this.config.errorMessage);if(g){let m={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(m)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=Fo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let s=fd(r,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||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==o&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.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(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={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},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,a={...t,status:n,resolvedAt:Date.now()},s=this.messages.find(c=>c.id===r),l={id:r,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},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let f=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}`)}f=c.body}else c instanceof ReadableStream&&(f=c);f?await this.connectStream(f,{allowReentry:!0}):(n==="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 f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof n=="string"?void 0:n;if(s===void 0&&typeof n=="string"){let c=t.toolCall?.args,f=Array.isArray(c?.questions)?c.questions:[];if(f.length===1){let g=typeof f[0]?.question=="string"?f[0].question:"";g&&(s={[g]:n})}}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 n=="string"?n:Object.entries(n).map(([f,g])=>`${f}: ${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((f,g)=>{let m=typeof f?.question=="string"?f.question:"";if(!m)return;let b=c[m],w=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:m,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:w||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[a]:n});if(!c.ok){let f=await c.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==On?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=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:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let f=`${t}:${c}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(f),o.push(f);let g=this.markWebMcpToolRunning(p),m=p.agentMetadata?.webMcpToolCallId??d;if(d===On)return{dedupeKey:f,resumeKey:m,output:rd(),toolMessage:p,startedAt:g,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let w=this.client.executeWebMcpToolCall(d,p.toolCall?.args,b.signal),T;if(!w)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await w}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,fs(A?"Aborted by cancel()":dh(L)),g),this.webMcpInflightKeys.delete(f),null}return b.signal.aborted?(this.markWebMcpToolComplete(p,fs("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:m,output:T,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===On?{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,fs("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(w){this.callbacks.onError?.(w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(b)}return}let a=`${n}:${r}`;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=o===On,c=t.toolCall?.args,f=d?null:this.client.executeWebMcpToolCall(o,c,p),g="execute",m=s;try{let b;if(d?b=rd():f?b=await f:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),p.aborted){this.markWebMcpToolComplete(t,fs("Aborted by cancel()"),s);return}let w=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,w,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,b,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(b){let w=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(g==="execute"||w||p.aborted)&&this.markWebMcpToolComplete(t,fs(w||p.aborted?"Aborted by cancel()":dh(b)),s),w||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let a=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!a.ok){let s=await a.json().catch(()=>null);throw new Error(s?.error??`Resume failed: ${a.status}`)}r?.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 n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=zn(this.config.features?.artifacts,t),r=rs(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(s=>s.id===n);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(s=>s.id===`artifact-ref-${n.id}`);if(!o)continue;let r=zn(this.config.features?.artifacts,n),a=rs(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==a&&(o.rawContent=a,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}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 n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);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){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}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(()=>(ch(),lh)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>fd(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Fo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.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 n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(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 n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!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 r=dd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=dd(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,a)=>{if(a!==o)return r;let s={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(s.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(s.agentMetadata={...s.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,f=n.approval;s.approval={...c,...f,executionId:f.executionId||c.executionId,toolName:f.toolName||c.toolName,description:f.description||c.description,toolType:f.toolType??c.toolType,reason:f.reason??c.reason,parameters:f.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&ph(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,f=this.webMcpInflightKeys.has(c),g=this.webMcpResolvedKeys.has(c),m=r.toolCall?.name,b=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&m!==void 0&&ph(m)&&r.toolCall?.status==="complete";(f||g||b)&&(s.agentMetadata={...s.agentMetadata??{},awaitingLocalTool:!1},s.toolCall=r.toolCall,s.streaming=r.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((n,o)=>{let r=new Date(n.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let s=n.sequence??0,l=o.sequence??0;return s!==l?s-l:n.id.localeCompare(o.id)})}};var md=[["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 gd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var hd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var yd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var bd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var xd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var vd=[["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 Cd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var wd=[["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 Ad=[["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 Sd=[["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 Md=[["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 Td=[["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 Ed=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var kd=[["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 qi=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16"}],["path",{d:"M18 17V9"}],["path",{d:"M13 17V5"}],["path",{d:"M8 17v-3"}]];var Ld=[["path",{d:"M20 6 9 17l-5-5"}]];var Pd=[["path",{d:"m6 9 6 6 6-6"}]];var Rd=[["path",{d:"m15 18-6-6 6-6"}]];var Id=[["path",{d:"m9 18 6-6-6-6"}]];var Wd=[["path",{d:"m18 15-6-6-6 6"}]];var Vi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var zi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Hd=[["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 Bd=[["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 Dd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var $i=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Fd=[["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 Od=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Nd=[["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 _d=[["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 ji=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Gi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ud=[["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 qd=[["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 Vd=[["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 zd=[["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 $d=[["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 jd=[["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 Gd=[["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 Kd=[["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 Xd=[["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 Jd=[["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 Yd=[["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 Ki=[["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 ep=[["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 tp=[["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 np=[["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 op=[["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 rp=[["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 Xi=[["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 ap=[["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 sp=[["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 ip=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var lp=[["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 cp=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"}],["path",{d:"M9 18h6"}],["path",{d:"M10 22h4"}]];var dp=[["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 Ji=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var pp=[["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 up=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var fp=[["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 mp=[["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 gp=[["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 hp=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var yp=[["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 bp=[["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 xp=[["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 vp=[["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 Cp=[["path",{d:"M5 12h14"}]];var wp=[["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 Ap=[["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 Sp=[["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 Mp=[["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 Tp=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Qi=[["path",{d:"M13 21h8"}],["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"}]];var Ep=[["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 kp=[["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 Lp=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Pp=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Rp=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Ip=[["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 Wp=[["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 Hp=[["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 Bp=[["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 Dp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Fp=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Op=[["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 Np=[["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 _p=[["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 Up=[["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 Yi=[["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 qp=[["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 Vp=[["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 zp=[["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 $p=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Zi=[["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 jp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Gp=[["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 Kp=[["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 Xp=[["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 Jp=[["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 Qp=[["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 Yp=[["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 Zp=[["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 eu=[["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 tu=[["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 el=[["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 nu=[["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 ou=[["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 ru=[["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 au=[["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 su=[["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 iu=[["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 lu=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var cu=[["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 yC={activity:md,"arrow-down":gd,"arrow-up":xd,"arrow-up-right":bd,bot:Sd,"chevron-down":Pd,"chevron-up":Wd,"chevron-right":Id,"chevron-left":Rd,check:Ld,clipboard:Bd,"clipboard-copy":Hd,"code-xml":$i,copy:Fd,file:Gd,"file-code":zd,"file-spreadsheet":$d,"file-text":jd,"image-plus":ap,loader:pp,"loader-circle":Ji,mic:xp,paperclip:Mp,"refresh-cw":Wp,search:Dp,send:Fp,"shield-alert":_p,"shield-check":Up,"shield-x":Yi,square:jp,"thumbs-down":Qp,"thumbs-up":Yp,upload:ou,"volume-2":au,x:lu,user:ru,mail:fp,phone:Lp,calendar:Ed,clock:Dd,building:Md,"map-pin":mp,lock:up,key:lp,"credit-card":Od,"at-sign":vd,hash:tp,globe:ep,link:dp,"circle-check":Vi,"circle-x":zi,"triangle-alert":el,info:ip,ban:Cd,shield:qp,"arrow-left":hd,"arrow-right":yd,"external-link":qd,ellipsis:Gi,"ellipsis-vertical":ji,menu:hp,house:Xi,plus:Rp,minus:Cp,pencil:Ep,"pen-line":Qi,trash:tu,"trash-2":eu,save:Bp,download:_d,share:Np,funnel:Ki,settings:Op,"rotate-cw":Hp,maximize:gp,minimize:vp,"shopping-cart":zp,"shopping-bag":Vp,package:Sp,truck:nu,tag:Jp,gift:Zd,receipt:Ip,wallet:iu,store:Kp,"dollar-sign":Nd,percent:kp,play:Pp,pause:Tp,"volume-x":su,camera:kd,image:sp,film:Xd,headphones:np,"message-circle":yp,"message-square":bp,bell:wd,heart:op,star:Gp,eye:Vd,"eye-off":Ud,bookmark:Ad,"calendar-days":Td,history:rp,timer:Zp,folder:Yd,"folder-open":Qd,files:Kd,"chart-column":qi,sparkles:Zi,zap:cu,sun:Xp,moon:Ap,flag:Jd,lightbulb:cp,monitor:wp,smartphone:$p},ae=(e,t=24,n="currentColor",o=2)=>{let r=yC[e];return r?bC(r,t,n,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 bC(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.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))}),r.appendChild(p)}),r}var tl={allowedTypes:co,maxFileSize:10*1024*1024,maxFiles:4};function xC(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vC(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 Ar=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??tl.allowedTypes,maxFileSize:t.maxFileSize??tl.maxFileSize,maxFiles:t.maxFiles??tl.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:tl.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 n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=oh(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await nh(n),a=Ni(n)?URL.createObjectURL(n):null,s={id:xC(),file:n,previewUrl:a,contentPart:r};this.attachments.push(s),this.renderPreview(s)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(a=>a.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.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 n=Ni(t.file),o=v("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",n&&t.previewUrl){let s=v("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=v("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let l=vC(t.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let d=v("span");d.textContent=rh(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 r=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let a=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);a?r.appendChild(a):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var uh=/\s/;function CC(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
24
|
-
`:o===""||
|
|
25
|
-
`||
|
|
26
|
-
`).some(
|
|
27
|
-
`)[0]).startsWith(C.trigger):!1),a=(S,C)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:C}))}catch{}},s=ke("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,f=null,g=null,m=null,b=()=>{if(l)return Promise.resolve(l);if(p)return p;let S=fu().then(C=>(l=C.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:s,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:A,emit:a}),l)).catch(C=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",C),p===S&&(p=null),null));return p=S,S},w=()=>{vh().then(S=>{let C=S.mountInlineComposer({textarea:e.textarea,renderToken:P=>ms(P,{render:t.renderMentionToken}),onMentionRemoved:P=>l?.untrackMention(P)});c=C.input,f=C.destroy;let M=d;M.replaceWith(C.element),d=C.element,m={next:C.element,prev:M},g?.(C.element,M),l?l.rebindComposer(C.input):p&&p.then(P=>P?.rebindComposer(C.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&w();let T=[],L=new Map;for(let S of n){if(!S.showButton)continue;let C=yh({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{b().then(M=>M?.openMenu(S.trigger))}});T.push(C),L.set(S.trigger,C.button)}let A=(S,C,M)=>{let P=L.get(C);P&&(P.setAttribute("aria-expanded",S?"true":"false"),S?P.setAttribute("aria-controls",M):P.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(S=>S.wrapper),contextRow:s,handleInput:S=>{if(l){l.handleInput();return}if(!mh(S))return;let C=d,M=C.selectionStart??0;fh(C.value,M,n)&&b().then(P=>P?.handleInput())},handleKeydown:S=>{if(l?.isMenuOpen())return l.handleKeydown(S);if(S.key==="Backspace"&&l?.hasMentions()&&!m){let C=d,M=C.selectionStart===0&&C.selectionEnd===0;if((C.value.length===0||M)&&l.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(l??await b())?.dispatchInlineCommand(S)??null:null,clear:()=>l?.clear(),prefetch:()=>{fu().catch(()=>{})},onComposerSwap:S=>{g=S,m&&S(m.next,m.prev)},destroy:()=>{l?.destroy(),f?.();for(let S of T)S.wrapper.remove();s.remove()}}}var wh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function gs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];wh(a)&&wh(r)?n[o]=gs(a,r):n[o]=r}return n}var mn="min(440px, calc(100vw - 24px))",ol="440px",PC={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:mn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={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:PC,copy:{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:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],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 Ah(e,t){if(!(!e&&!t))return e?t?gs(e,t):e:t}function da(e){return e?{...rt,...e,theme:Ah(rt.theme,e.theme),darkTheme:Ah(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,s=e.features?.scrollBehavior,l=rt.features?.streamAnimation,p=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,f=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},g=o===void 0&&r===void 0?void 0:{...o,...r},m=a===void 0&&s===void 0?void 0:{...a,...s},b=l===void 0&&p===void 0?void 0:{...l,...p},w=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...m!==void 0?{scrollBehavior:m}:{},...f!==void 0?{artifacts:f}:{},...b!==void 0?{streamAnimation:b}:{},...w!==void 0?{askUserQuestion:w}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var rl="16px",al="transparent",mu={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"}},gu={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"}},hu={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:mn,maxWidth:ol,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:rl,canvasBackground:al},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},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",borderRadius:"palette.radius.md"},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 en(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?en(e,o):o}function sl(e){let t={};function n(o,r){for(let[a,s]of Object.entries(o)){let l=`${r}.${a}`;if(typeof s=="string"){let p=en(e,s);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&n(s,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function yu(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Sh(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Sh(a,r):n[o]=r}return n}function RC(e,t){return t?Sh(e,t):e}function hs(e,t={}){let n={palette:mu,semantic:gu,components:hu},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:RC(n.components,e?.components)};if(t.validate!==!1){let r=yu(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function il(e){let t=sl(e),n={};for(let[E,G]of Object.entries(t)){let Q=E.replace(/\./g,"-");n[`--persona-${Q}`]=G.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--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)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??rl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??al,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let r=n["--persona-components-introCard-background"],a=n["--persona-components-introCard-shadow"],s=(!r||r==="transparent"||r==="none")&&(!a||a==="none"),l=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=s&&l==="1.5rem"?"1.5rem 0":l,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let p=n["--persona-components-markdown-heading-h1-fontSize"];p&&(n["--persona-md-h1-size"]=p);let d=n["--persona-components-markdown-heading-h1-fontWeight"];d&&(n["--persona-md-h1-weight"]=d);let c=n["--persona-components-markdown-heading-h2-fontSize"];c&&(n["--persona-md-h2-size"]=c);let f=n["--persona-components-markdown-heading-h2-fontWeight"];f&&(n["--persona-md-h2-weight"]=f);let g=n["--persona-components-markdown-prose-fontFamily"];g&&g!=="inherit"&&(n["--persona-md-prose-font-family"]=g),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let m=e.components,b=m?.iconButton;b&&(b.background&&(n["--persona-icon-btn-bg"]=b.background),b.border&&(n["--persona-icon-btn-border"]=b.border),b.color&&(n["--persona-icon-btn-color"]=b.color),b.padding&&(n["--persona-icon-btn-padding"]=b.padding),b.borderRadius&&(n["--persona-icon-btn-radius"]=b.borderRadius),b.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=b.hoverBackground),b.hoverColor&&(n["--persona-icon-btn-hover-color"]=b.hoverColor),b.activeBackground&&(n["--persona-icon-btn-active-bg"]=b.activeBackground),b.activeBorder&&(n["--persona-icon-btn-active-border"]=b.activeBorder));let w=m?.labelButton;w&&(w.background&&(n["--persona-label-btn-bg"]=w.background),w.border&&(n["--persona-label-btn-border"]=w.border),w.color&&(n["--persona-label-btn-color"]=w.color),w.padding&&(n["--persona-label-btn-padding"]=w.padding),w.borderRadius&&(n["--persona-label-btn-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-label-btn-hover-bg"]=w.hoverBackground),w.fontSize&&(n["--persona-label-btn-font-size"]=w.fontSize),w.gap&&(n["--persona-label-btn-gap"]=w.gap));let T=m?.toggleGroup;T&&(T.gap&&(n["--persona-toggle-group-gap"]=T.gap),T.borderRadius&&(n["--persona-toggle-group-radius"]=T.borderRadius));let L=m?.artifact;if(L?.toolbar){let E=L.toolbar;E.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=E.iconHoverColor),E.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=E.iconHoverBackground),E.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=E.iconPadding),E.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=E.iconBorderRadius),E.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=E.iconBorder),E.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=E.toggleGroupGap),E.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=E.toggleBorderRadius),E.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=E.toggleGroupPadding),E.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=E.toggleGroupBorder),E.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=E.toggleGroupBorderRadius),E.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=en(e,E.toggleGroupBackground)??E.toggleGroupBackground),E.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=E.copyBackground),E.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=E.copyBorder),E.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=E.copyColor),E.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=E.copyBorderRadius),E.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=E.copyPadding),E.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=E.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??E.copyMenuBackground),E.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=E.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??E.copyMenuBorder),E.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=E.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??E.copyMenuShadow),E.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=E.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??E.copyMenuBorderRadius),E.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=E.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??E.copyMenuItemHoverBackground),E.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=E.iconBackground),E.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=E.toolbarBorder)}if(L?.tab){let E=L.tab;E.background&&(n["--persona-artifact-tab-bg"]=E.background),E.activeBackground&&(n["--persona-artifact-tab-active-bg"]=E.activeBackground),E.activeBorder&&(n["--persona-artifact-tab-active-border"]=E.activeBorder),E.borderRadius&&(n["--persona-artifact-tab-radius"]=E.borderRadius),E.textColor&&(n["--persona-artifact-tab-color"]=E.textColor),E.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=E.hoverBackground),E.listBackground&&(n["--persona-artifact-tab-list-bg"]=E.listBackground),E.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=E.listBorderColor),E.listPadding&&(n["--persona-artifact-tab-list-padding"]=E.listPadding)}if(L?.pane){let E=L.pane;if(E.toolbarBackground){let G=en(e,E.toolbarBackground)??E.toolbarBackground;n["--persona-artifact-toolbar-bg"]=G}}if(L?.card){let E=L.card;E.background&&(n["--persona-artifact-card-bg"]=E.background),E.border&&(n["--persona-artifact-card-border"]=E.border),E.borderRadius&&(n["--persona-artifact-card-radius"]=E.borderRadius),E.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=E.hoverBackground),E.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=E.hoverBorderColor)}if(L?.inline){let E=L.inline;E.background&&(n["--persona-artifact-inline-bg"]=en(e,E.background)??E.background),E.border&&(n["--persona-artifact-inline-border"]=E.border),E.borderRadius&&(n["--persona-artifact-inline-radius"]=E.borderRadius),E.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=en(e,E.chromeBackground)??E.chromeBackground),E.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=en(e,E.chromeBorder)??E.chromeBorder),E.titleColor&&(n["--persona-artifact-inline-title-color"]=en(e,E.titleColor)??E.titleColor),E.mutedColor&&(n["--persona-artifact-inline-muted-color"]=en(e,E.mutedColor)??E.mutedColor),E.frameHeight&&(n["--persona-artifact-inline-frame-height"]=E.frameHeight)}let A=m?.code;A&&(A.keywordColor&&(n["--persona-code-keyword-color"]=A.keywordColor),A.stringColor&&(n["--persona-code-string-color"]=A.stringColor),A.commentColor&&(n["--persona-code-comment-color"]=A.commentColor),A.numberColor&&(n["--persona-code-number-color"]=A.numberColor),A.tagColor&&(n["--persona-code-tag-color"]=A.tagColor),A.attrColor&&(n["--persona-code-attr-color"]=A.attrColor),A.propertyColor&&(n["--persona-code-property-color"]=A.propertyColor),A.lineNumberColor&&(n["--persona-code-line-number-color"]=A.lineNumberColor),A.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=A.gutterBorderColor),A.background&&(n["--persona-code-bg"]=en(e,A.background)??A.background));let S=n["--persona-surface"],C=n["--persona-container"],M=n["--persona-palette-colors-gray-100"]??"#f3f4f6",P=n["--persona-palette-colors-gray-200"]??"#e5e7eb",R=n["--persona-palette-colors-gray-300"]??"#d1d5db",F=!C||C===S,O=F?M:C,$=F?P:C;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??O,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??$,F&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??R),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??O,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??O,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??O,n}var Mh={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 IC={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"}}},Th=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ys=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",WC=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":ys()},ll=e=>WC(e),HC=e=>hs(e),BC=e=>hs({...e,palette:{...e?.palette,colors:{...IC.colors,...e?.palette?.colors}}},{validate:!1}),Uo=e=>{let t=ll(e),n=Th(e?.theme),o=Th(e?.darkTheme);return t==="dark"?BC(gs(n??{},o??{})):HC(n)},DC=e=>il(e),Sr=(e,t)=>{let n=Uo(t),o=DC(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",ll(t))},pa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(ys())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(ys());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};var qo=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function $n(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Eh(e){let t=$n(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function cl(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
23
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let u=[];s&&u.push(ho(s)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(d){let u=[];i&&u.push(ho(i)),u.push(...r.contentParts),t.contentParts=u}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=ta(),s=hr();this.activeAssistantMessageId=null;let i=n?.contentParts&&ea(n.contentParts)?Zs:"",l={id:r,role:"user",content:o||i,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let d=new AbortController;if(this.abortController=d,n?.mentions){let p=this.messages.find(f=>f.id===r)??l;if(await this.applyMentionBundle(p,o,n.mentions.finalize),d.signal.aborted||this.abortController!==d)return;this.callbacks.onMessagesChanged([...this.messages])}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,d,s,r)}catch(p){if(this.status==="resuming"||this.reconnecting)return;let f=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));if(!f){let y=Eu(p,this.config.errorMessage);if(y){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(p instanceof Error?this.callbacks.onError?.(p):this.callbacks.onError?.(new Error(String(p))))}}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=hr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=Eu(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={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},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),l={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,u=d&&typeof d=="object"?d.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),p){let f=null;if(p instanceof Response){if(!p.ok){let y=await p.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);f?await this.connectStream(f,{allowReentry:!0}):(n==="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(p){let f=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let p=t.toolCall?.args,f=Array.isArray(p?.questions)?p.questions:[];if(f.length===1){let y=typeof f[0]?.question=="string"?f[0].question:"";y&&(i={[y]:n})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([f,y])=>`${f}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((f,y)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let b=p[g],v=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:v||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[s]:n});if(!p.ok){let f=await p.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let f=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==oo?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=await Promise.all(n.map(async d=>{let u=d.toolCall?.name,p=d.toolCall?.id;if(!u||!p)return null;let f=`${t}:${p}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(f),o.push(f);let y=this.markWebMcpToolRunning(d),g=d.agentMetadata?.webMcpToolCallId??u;if(u===oo)return{dedupeKey:f,resumeKey:g,output:yu(),toolMessage:d,startedAt:y,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let v=this.client.executeWebMcpToolCall(u,d.toolCall?.args,b.signal),E;if(!v)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await v}catch(H){let k=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));return k||this.callbacks.onError?.(H instanceof Error?H:new Error(String(H))),this.markWebMcpToolComplete(d,Mi(k?"Aborted by cancel()":Mx(H)),y),this.webMcpInflightKeys.delete(f),null}return b.signal.aborted?(this.markWebMcpToolComplete(d,Mi("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:E,toolMessage:d,startedAt:y,completedAt:Date.now()}})),l=[];try{if(l=i.filter(p=>p!==null),l.length===0)return;let d={};for(let p of l)d[p.resumeKey]=p.output;let u=await this.client.resumeFlow(t,d,{signal:s.signal});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of l)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===oo?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let p of l)this.markWebMcpToolComplete(p.toolMessage,Mi("Aborted by cancel()"),p.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);for(let d of r)this.webMcpResolveControllers.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(v){this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(b)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let i=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:d}=l;this.setStreaming(!0);let u=o===oo,p=t.toolCall?.args,f=u?null:this.client.executeWebMcpToolCall(o,p,d),y="execute",g=i;try{let b;if(u?b=yu():f?b=await f:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Mi("Aborted by cancel()"),i);return}let v=t.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,v,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,b,i,g,u?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(b){let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(y==="execute"||v||d.aborted)&&this.markWebMcpToolComplete(t,Mi(v||d.aborted?"Aborted by cancel()":Mx(b)),i),v||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.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 n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=go(this.config.features?.artifacts,t),r=mi(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=go(this.config.features?.artifacts,n),s=mi(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}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 n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);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){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}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(()=>(Ax(),Sx)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Eu(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=hr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.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 n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(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 n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Au(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return na(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Au(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let p=r.approval,f=n.approval;i.approval={...p,...f,executionId:f.executionId||p.executionId,toolName:f.toolName||p.toolName,description:f.description||p.description,toolType:f.toolType??p.toolType,reason:f.reason??p.reason,parameters:f.parameters??p.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,u=n.toolCall?.id;if(l&&Tx(l)&&d&&u&&n.agentMetadata?.awaitingLocalTool===!0){let p=`${d}:${u}`,f=this.webMcpInflightKeys.has(p),y=this.webMcpResolvedKeys.has(p),g=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===u&&g!==void 0&&Tx(g)&&r.toolCall?.status==="complete";(f||y||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),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((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};var ku=[["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 Pu=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Lu=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Hu=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Ru=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Iu=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Wu=[["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 Bu=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Du=[["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 Ou=[["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 Fu=[["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 Nu=[["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 _u=[["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 Uu=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var qu=[["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 Ac=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16"}],["path",{d:"M18 17V9"}],["path",{d:"M13 17V5"}],["path",{d:"M8 17v-3"}]];var Vu=[["path",{d:"M20 6 9 17l-5-5"}]];var zu=[["path",{d:"m6 9 6 6 6-6"}]];var ju=[["path",{d:"m15 18-6-6 6-6"}]];var $u=[["path",{d:"m9 18 6-6-6-6"}]];var Gu=[["path",{d:"m18 15-6-6-6 6"}]];var Mc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Tc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Ku=[["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 Xu=[["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 Yu=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Ec=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Ju=[["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 Qu=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Zu=[["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 ef=[["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 kc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Pc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var tf=[["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 nf=[["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 of=[["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 rf=[["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 sf=[["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 af=[["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 lf=[["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 cf=[["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 df=[["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 pf=[["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 uf=[["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 ff=[["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 Lc=[["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 mf=[["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 gf=[["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 hf=[["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 yf=[["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 bf=[["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 xf=[["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 Hc=[["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 vf=[["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 Cf=[["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 wf=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Sf=[["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 Af=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"}],["path",{d:"M9 18h6"}],["path",{d:"M10 22h4"}]];var Mf=[["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 Rc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Tf=[["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 Ef=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var kf=[["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 Pf=[["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 Lf=[["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 Hf=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Rf=[["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 If=[["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 Wf=[["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 Bf=[["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 Df=[["path",{d:"M5 12h14"}]];var Of=[["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 Ff=[["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 Nf=[["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 Ic=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var _f=[["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 Uf=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Wc=[["path",{d:"M13 21h8"}],["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"}]];var qf=[["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 Vf=[["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 zf=[["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 jf=[["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 $f=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Gf=[["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 Kf=[["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 Xf=[["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 Yf=[["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 Jf=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Qf=[["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 Zf=[["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 em=[["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 tm=[["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 nm=[["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 Bc=[["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 om=[["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 rm=[["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 sm=[["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 am=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Dc=[["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 im=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var lm=[["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 cm=[["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 dm=[["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 pm=[["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 um=[["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 fm=[["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 mm=[["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 gm=[["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 hm=[["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:"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 ym=[["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 bm=[["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 xm=[["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 vm=[["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 Cm=[["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 wm=[["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 Sm=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Am=[["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 $0={activity:ku,"arrow-down":Pu,"arrow-up":Iu,"arrow-up-right":Ru,bot:Fu,"chevron-down":zu,"chevron-up":Gu,"chevron-right":$u,"chevron-left":ju,check:Vu,clipboard:Xu,"clipboard-copy":Ku,"code-xml":Ec,copy:Ju,file:lf,"file-code":rf,"file-spreadsheet":sf,"file-text":af,"image-plus":vf,loader:Tf,"loader-circle":Rc,mic:Wf,paperclip:_f,"refresh-cw":Kf,search:Jf,send:Qf,"shield-alert":tm,"shield-check":nm,"shield-x":Bc,square:im,"thumbs-down":um,"thumbs-up":fm,upload:bm,"volume-2":vm,x:Sm,user:xm,mail:kf,phone:zf,calendar:Uu,clock:Yu,building:Nu,"map-pin":Pf,lock:Ef,key:Sf,"credit-card":Qu,"at-sign":Wu,hash:hf,globe:gf,link:Mf,"circle-check":Mc,"circle-x":Tc,"triangle-alert":Oc,info:wf,ban:Bu,shield:om,"arrow-left":Lu,"arrow-right":Hu,"external-link":nf,ellipsis:Pc,"ellipsis-vertical":kc,menu:Hf,house:Hc,"panel-left":Ic,plus:$f,minus:Df,pencil:qf,"pen-line":Wc,trash:hm,"trash-2":gm,save:Yf,download:ef,share:em,funnel:Lc,settings:Zf,"rotate-cw":Xf,maximize:Lf,minimize:Bf,"shopping-cart":sm,"shopping-bag":rm,package:Nf,truck:ym,tag:pm,gift:mf,receipt:Gf,wallet:wm,store:cm,"dollar-sign":Zu,percent:Vf,play:jf,pause:Uf,"volume-x":Cm,camera:qu,image:Cf,film:df,headphones:yf,"message-circle":Rf,"message-square":If,bell:Du,heart:bf,star:lm,eye:of,"eye-off":tf,bookmark:Ou,"calendar-days":_u,history:xf,timer:mm,folder:ff,"folder-open":uf,files:cf,"chart-column":Ac,sparkles:Dc,zap:Am,sun:dm,moon:Ff,flag:pf,lightbulb:Af,monitor:Of,smartphone:am},ce=(e,t=24,n="currentColor",o=2)=>{let r=$0[e];return r?G0(r,t,n,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 G0(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([u,p])=>{u!=="stroke"&&d.setAttribute(u,String(p))}),r.appendChild(d)}),r}var Fc={allowedTypes:qo,maxFileSize:10*1024*1024,maxFiles:4};function K0(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function X0(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 rs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Fc.allowedTypes,maxFileSize:t.maxFileSize??Fc.maxFileSize,maxFiles:t.maxFiles??Fc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Fc.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 n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=rx(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await ox(n),s=vc(n)?URL.createObjectURL(n):null,i={id:K0(),file:n,previewUrl:s,contentPart:r};this.attachments.push(i),this.renderPreview(i)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.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 n=vc(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",n&&t.previewUrl){let i=S("img");i.src=t.previewUrl,i.alt=t.file.name,i.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",o.appendChild(i)}else{let i=S("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--persona-container, #f3f4f6)",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let l=X0(t.file.type),d=ce(l,20,"var(--persona-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=S("span");u.textContent=sx(t.file.type,t.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--persona-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),o.appendChild(i)}let r=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ce("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Ex=/\s/;function Y0(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
24
|
+
`:o===""||Ex.test(o)}function J0(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return Y0(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
|
|
25
|
+
`||i==="\uFFFC"||!r&&Ex.test(i))return null;s--}return null}function kx(e,t,n){for(let o of n){let r=J0(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Px(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Lx(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Nt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Qt=1e5,ra=Qt+1;var Q0=8,Z0=8,Mm=10,Hx=200,Rx=300,Ix=0,Nc=e=>Math.max(0,e);function Wx(e){e.delayMs!==void 0&&(Hx=Nc(e.delayMs)),e.skipDelayMs!==void 0&&(Rx=Nc(e.skipDelayMs))}var eM=()=>Date.now()<Ix,tM=e=>{Ix=e>0?Date.now()+e:0},Tm=new WeakMap,Bx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,nM=e=>{let t=e.getRootNode?.();return Bx(t)?t:e.ownerDocument.body},Em=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),oM=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Zt(e){Tm.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=Q0,viewportPadding:l=Z0}=e,d=()=>t.ownerDocument,u=()=>d().defaultView??window,p=null,f=null,y=null,g=null,b,v=!1,E=!1,H=!1,k=()=>(typeof o=="function"?o():o).trim(),M=()=>(typeof r=="function"?r():r??"").trim(),x=()=>Nc(e.delayMs??Hx),w=()=>Nc(e.skipDelayMs??Rx),L=()=>{b!==void 0&&(u().clearTimeout(b),b=void 0)},P=()=>{L();let le=p!==null;g?.(),g=null,p?.remove(),p=null,f=null,y=null,le&&tM(w())},D=()=>{if(!p)return;let le=d(),I=u(),Z=t.getBoundingClientRect(),pe=p.getBoundingClientRect(),Ee=le.documentElement.clientWidth||I.innerWidth,Ce=le.documentElement.clientHeight||I.innerHeight,we=Ee-l-pe.width,Pe=Z.left+Z.width/2-pe.width/2,Re=Em(Pe,l,we),nt=Z.top-l,Je=Ce-l-Z.bottom,Be=pe.height+i,ot=nt>=Be||nt>=Je?"top":"bottom",vt=ot==="top"?Z.top-i-pe.height:Z.bottom+i,yt=Ce-l-pe.height,Dn=Em(vt,l,yt),Me=Z.left+Z.width/2,Ke=Math.max(Mm,pe.width-Mm),rt=Em(Me-Re,Mm,Ke);p.dataset.placement=ot,p.style.left=`${Re}px`,p.style.top=`${Dn}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${rt}px`)},q=()=>{if(H||!s||p||!t.isConnected)return;let le=k(),I=nM(t);if(!le||!I)return;let Z=d(),pe=u();p=Z.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(ra);let Ee=pe.getComputedStyle?.(t);if(Ee){for(let Be of oM){let ot=Ee.getPropertyValue(Be).trim();ot&&p.style.setProperty(Be,ot)}Ee.fontFamily&&(p.style.fontFamily=Ee.fontFamily)}f=Z.createElement("span"),f.className="persona-control-tooltip__label",f.textContent=le,p.appendChild(f);let Ce=M();Ce&&(y=Z.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=Ce,p.appendChild(y));let we=Z.createElement("span");we.className="persona-control-tooltip__arrow",p.appendChild(we),I.appendChild(p),D(),p.dataset.state="open";let Pe=()=>{if(!t.isConnected){P();return}f&&(f.textContent=k()),y&&(y.textContent=M()),D()};pe.addEventListener("scroll",Pe,!0),pe.addEventListener("resize",Pe);let Re=t.getRootNode(),nt=Bx(Re)?Re:Z.documentElement,Je=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||P()});Je?.observe(nt,{childList:!0,subtree:!0}),g=()=>{pe.removeEventListener("scroll",Pe,!0),pe.removeEventListener("resize",Pe),Je?.disconnect()}},$=le=>{if(!(H||p)){if(L(),le||x()<=0||eM()){q();return}b=u().setTimeout(()=>{b=void 0,q()},x())}},N=()=>{v||E?$(E):P()},X=()=>{let le=u();(!le.matchMedia||!le.matchMedia("(hover: none)").matches)&&(v=!0,N())},de=()=>{v=!1,N()},me=()=>{try{E=t.matches(":focus-visible")}catch{E=!0}N()},xe=()=>{E=!1,N()},ye=()=>{v=!1,E=!1,P()},ne=le=>{le.key==="Escape"&&ye()};n.addEventListener("mouseenter",X),n.addEventListener("mouseleave",de),t.addEventListener("focus",me),t.addEventListener("blur",xe),t.addEventListener("keydown",ne),t.addEventListener("click",ye);let ie={get isOpen(){return p!==null},show:q,hide:P,reposition:D,destroy:()=>{H||(H=!0,P(),n.removeEventListener("mouseenter",X),n.removeEventListener("mouseleave",de),t.removeEventListener("focus",me),t.removeEventListener("blur",xe),t.removeEventListener("keydown",ne),t.removeEventListener("click",ye),Tm.delete(t))}};return Tm.set(t,ie),ie}function Dx(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),i=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",d=S("div","persona-send-button-wrapper"),u=ue("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),p=ce(i,s,"currentColor",1.5);return p?u.appendChild(p):u.textContent="+",u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),n()}),d.appendChild(u),Zt({anchor:u,trigger:d,text:()=>u.getAttribute("aria-label")??l}),{button:u,wrapper:d}}var{setLoader:rM,load:sM}=fo({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ox=rM,km=sM;var{setLoader:aM,load:iM}=fo({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Fx=aM,Nx=iM;function ki(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=ue("span",{className:jn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ce(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=S("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(ue("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function _x(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Lx(t).filter(M=>M.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(M=>M.sources.some(x=>typeof x.matchCommand=="function")),r=M=>o.some(x=>x.trigger?x.position==="line-start"?M.split(`
|
|
26
|
+
`).some(L=>L.startsWith(x.trigger)):(x.position==="anywhere"?M:M.split(`
|
|
27
|
+
`)[0]).startsWith(x.trigger):!1),s=(M,x)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${M}`,{detail:x}))}catch{}},i=ue("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,d=null,u=e.textarea,p=null,f=null,y=null,g=null,b=()=>{if(l)return Promise.resolve(l);if(d)return d;let M=km().then(x=>(l=x.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:p??void 0,anchor:e.anchor,contextRow:i,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:k,emit:s}),l)).catch(x=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",x),d===M&&(d=null),null));return d=M,M},v=()=>{Nx().then(M=>{let x=M.mountInlineComposer({textarea:e.textarea,renderToken:L=>ki(L,{render:t.renderMentionToken}),onMentionRemoved:L=>l?.untrackMention(L)});p=x.input,f=x.destroy;let w=u;w.replaceWith(x.element),u=x.element,g={next:x.element,prev:w},y?.(x.element,w),l?l.rebindComposer(x.input):d&&d.then(L=>L?.rebindComposer(x.input))}).catch(M=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",M)})};t.display==="inline"&&v();let E=[],H=new Map;for(let M of n){if(!M.showButton)continue;let x=Dx({config:{...t,buttonIconName:M.buttonIconName,buttonTooltipText:M.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{b().then(w=>w?.openMenu(M.trigger))}});E.push(x),H.set(M.trigger,x.button)}let k=(M,x,w)=>{let L=H.get(x);L&&(L.setAttribute("aria-expanded",M?"true":"false"),M?L.setAttribute("aria-controls",w):L.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(M=>M.wrapper),contextRow:i,handleInput:M=>{if(l){l.handleInput();return}if(!Px(M))return;let x=u,w=x.selectionStart??0;kx(x.value,w,n)&&b().then(L=>L?.handleInput())},handleKeydown:M=>{if(l?.isMenuOpen())return l.handleKeydown(M);if(M.key==="Backspace"&&l?.hasMentions()&&!g){let x=u,w=x.selectionStart===0&&x.selectionEnd===0;if((x.value.length===0||w)&&l.removeLastChip())return M.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async M=>r(M)?(l??await b())?.dispatchInlineCommand(M)??null:null,clear:()=>l?.clear(),prefetch:()=>{km().catch(()=>{})},onComposerSwap:M=>{y=M,g&&M(g.next,g.prev)},destroy:()=>{l?.destroy(),f?.();for(let M of E)M.wrapper.remove();i.remove()}}}var Ux=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function sa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Ux(s)&&Ux(r)?n[o]=sa(s,r):n[o]=r}return n}var In="min(440px, calc(100vw - 24px))",_c="440px",lM={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:In,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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",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)"},Ge={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",tooltip:{delayMs:200,skipDelayMs:300},launcher:lM,copy:{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"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],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 qx(e,t){if(!(!e&&!t))return e?t?sa(e,t):e:t}function aa(e){return e?{...Ge,...e,theme:qx(Ge.theme,e.theme),darkTheme:qx(Ge.darkTheme,e.darkTheme),launcher:{...Ge.launcher,...e.launcher,dock:{...Ge.launcher?.dock,...e.launcher?.dock},clearChat:{...Ge.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...Ge.tooltip,...e.tooltip},copy:{...Ge.copy,...e.copy},sendButton:{...Ge.sendButton,...e.sendButton},statusIndicator:{...Ge.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ge.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=Ge.features?.artifacts,n=e.features?.artifacts,o=Ge.features?.scrollToBottom,r=e.features?.scrollToBottom,s=Ge.features?.scrollBehavior,i=e.features?.scrollBehavior,l=Ge.features?.streamAnimation,d=e.features?.streamAnimation,u=Ge.features?.askUserQuestion,p=e.features?.askUserQuestion,f=Ge.features?.history,y=e.features?.history,g=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},v=s===void 0&&i===void 0?void 0:{...s,...i},E=l===void 0&&d===void 0?void 0:{...l,...d},H=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},k=f===void 0&&y===void 0?void 0:{...f,...y,copy:{...f?.copy,...y?.copy}};return{...Ge.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...v!==void 0?{scrollBehavior:v}:{},...g!==void 0?{artifacts:g}:{},...E!==void 0?{streamAnimation:E}:{},...H!==void 0?{askUserQuestion:H}:{},...k!==void 0?{history:k}:{}}})(),suggestionChips:e.suggestionChips??Ge.suggestionChips,suggestionChipsConfig:{...Ge.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ge.layout,...e.layout,header:{...Ge.layout?.header,...e.layout?.header},messages:{...Ge.layout?.messages,...e.layout?.messages,avatar:{...Ge.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...Ge.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...Ge.layout?.slots,...e.layout?.slots}},markdown:{...Ge.markdown,...e.markdown,options:{...Ge.markdown?.options,...e.markdown?.options}},messageActions:{...Ge.messageActions,...e.messageActions}}:Ge}var Uc="16px",qc="transparent",Lm={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"}},Hm={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"}},Rm={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:In,maxWidth:_c,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Uc,canvasBackground:qc},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},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",borderRadius:"palette.radius.md"},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 fn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?fn(e,o):o}function Vc(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let d=fn(e,i);d!==void 0&&(t[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Im(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Vx(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Vx(s,r):n[o]=r}return n}function cM(e,t){return t?Vx(e,t):e}function Pi(e,t={}){let n={palette:Lm,semantic:Hm,components:Rm},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:cM(n.components,e?.components)};if(t.validate!==!1){let r=Im(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}var Pm=e=>e.trim()==="0"?"0px":e;function zc(e){let t=Vc(e),n={};for(let[I,Z]of Object.entries(t)){let pe=I.replace(/\./g,"-");n[`--persona-${pe}`]=Z.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--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)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-surface"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-primary"];let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Uc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??qc,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"];let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],n["--persona-header-control-size"]=n["--persona-components-header-controlSize"]??"32px",n["--persona-header-control-icon-size"]=n["--persona-components-header-controlIconSize"]??"20px";let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let u=n["--persona-components-history-railHeader-border"];u&&(n["--persona-history-rail-header-border"]=u);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[I,Z]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let pe=n[`--persona-components-history-overlay-${I}`];pe&&(n[`--persona-history-overlay-${Z}`]=pe)}for(let[I,Z]of[["background","bg"],["borderRadius","radius"]]){let pe=n[`--persona-components-history-menu-${I}`];pe&&(n[`--persona-history-menu-${Z}`]=pe)}let f=e.components?.history?.motion;if(f){let I=Ee=>{if(Ee===void 0)return;let Ce=String(Ee).trim();return/^\d+(\.\d+)?$/.test(Ce)?`${Ce}ms`:Ce},Z=I(f.enterDurationMs);Z!==void 0&&(n["--persona-history-enter-ms"]=Z);let pe=I(f.exitDurationMs);pe!==void 0&&(n["--persona-history-exit-ms"]=pe),f.enterEasing&&(n["--persona-history-enter-easing"]=f.enterEasing),f.exitEasing&&(n["--persona-history-exit-easing"]=f.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let I of["scrim","shadow"]){let Z=n[`--persona-components-history-confirm-${I}`];Z&&(n[`--persona-history-confirm-${I}`]=Z)}for(let[I,Z]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let pe=n[`--persona-components-tooltip-${I}`];pe&&(n[`--persona-tooltip-${Z}`]=pe)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[I,Z]of[["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let pe=n[`--persona-components-messageActions-${I}`];pe&&(n[`--persona-message-action-${Z}`]=pe)}n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let g=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],v=(!g||g==="transparent"||g==="none")&&(!b||b==="none"),E=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=v&&E==="1.5rem"?"1.5rem 0":E,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let H=n["--persona-components-markdown-heading-h1-fontSize"];H&&(n["--persona-md-h1-size"]=H);let k=n["--persona-components-markdown-heading-h1-fontWeight"];k&&(n["--persona-md-h1-weight"]=k);let M=n["--persona-components-markdown-heading-h2-fontSize"];M&&(n["--persona-md-h2-size"]=M);let x=n["--persona-components-markdown-heading-h2-fontWeight"];x&&(n["--persona-md-h2-weight"]=x);let w=n["--persona-components-markdown-prose-fontFamily"];w&&w!=="inherit"&&(n["--persona-md-prose-font-family"]=w),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let L=e.components,P=L?.iconButton;P&&(P.background&&(n["--persona-icon-btn-bg"]=P.background),P.border&&(n["--persona-icon-btn-border"]=P.border),P.color&&(n["--persona-icon-btn-color"]=P.color),P.padding&&(n["--persona-icon-btn-padding"]=P.padding),P.borderRadius&&(n["--persona-icon-btn-radius"]=P.borderRadius),P.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=P.hoverBackground),P.hoverColor&&(n["--persona-icon-btn-hover-color"]=P.hoverColor),P.activeBackground&&(n["--persona-icon-btn-active-bg"]=P.activeBackground),P.activeBorder&&(n["--persona-icon-btn-active-border"]=P.activeBorder));let D=L?.labelButton;D&&(D.background&&(n["--persona-label-btn-bg"]=D.background),D.border&&(n["--persona-label-btn-border"]=D.border),D.color&&(n["--persona-label-btn-color"]=D.color),D.padding&&(n["--persona-label-btn-padding"]=D.padding),D.borderRadius&&(n["--persona-label-btn-radius"]=D.borderRadius),D.hoverBackground&&(n["--persona-label-btn-hover-bg"]=D.hoverBackground),D.fontSize&&(n["--persona-label-btn-font-size"]=D.fontSize),D.gap&&(n["--persona-label-btn-gap"]=D.gap));let q=L?.toggleGroup;q&&(q.gap&&(n["--persona-toggle-group-gap"]=q.gap),q.borderRadius&&(n["--persona-toggle-group-radius"]=q.borderRadius));let $=L?.artifact;if($?.toolbar){let I=$.toolbar;I.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=I.iconHoverColor),I.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=I.iconHoverBackground),I.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=I.iconPadding),I.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=I.iconBorderRadius),I.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=I.iconBorder),I.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Pm(I.toggleGroupGap)),I.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=I.toggleBorderRadius),I.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Pm(I.toggleGroupPadding)),I.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=I.toggleGroupBorder),I.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=I.toggleGroupBorderRadius),I.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=fn(e,I.toggleGroupBackground)??I.toggleGroupBackground),I.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=I.copyBackground),I.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=I.copyBorder),I.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=I.copyColor),I.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Pm(I.copyBorderRadius)),I.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=I.copyPadding),I.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=I.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??I.copyMenuBackground),I.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=I.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??I.copyMenuBorder),I.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=I.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??I.copyMenuShadow),I.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=I.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??I.copyMenuBorderRadius),I.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=I.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??I.copyMenuItemHoverBackground),I.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=I.iconBackground),I.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=I.toolbarBorder)}if($?.tab){let I=$.tab;I.background&&(n["--persona-artifact-tab-bg"]=I.background),I.activeBackground&&(n["--persona-artifact-tab-active-bg"]=I.activeBackground),I.activeBorder&&(n["--persona-artifact-tab-active-border"]=I.activeBorder),I.borderRadius&&(n["--persona-artifact-tab-radius"]=I.borderRadius),I.textColor&&(n["--persona-artifact-tab-color"]=I.textColor),I.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=I.hoverBackground),I.listBackground&&(n["--persona-artifact-tab-list-bg"]=I.listBackground),I.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=I.listBorderColor),I.listPadding&&(n["--persona-artifact-tab-list-padding"]=I.listPadding)}if($?.pane){let I=$.pane;if(I.toolbarBackground){let Z=fn(e,I.toolbarBackground)??I.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Z}}if($?.card){let I=$.card;I.background&&(n["--persona-artifact-card-bg"]=I.background),I.border&&(n["--persona-artifact-card-border"]=I.border),I.borderRadius&&(n["--persona-artifact-card-radius"]=I.borderRadius),I.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=I.hoverBackground),I.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=I.hoverBorderColor)}if($?.inline){let I=$.inline;I.background&&(n["--persona-artifact-inline-bg"]=fn(e,I.background)??I.background),I.border&&(n["--persona-artifact-inline-border"]=I.border),I.borderRadius&&(n["--persona-artifact-inline-radius"]=I.borderRadius),I.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=fn(e,I.chromeBackground)??I.chromeBackground),I.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=fn(e,I.chromeBorder)??I.chromeBorder),I.titleColor&&(n["--persona-artifact-inline-title-color"]=fn(e,I.titleColor)??I.titleColor),I.mutedColor&&(n["--persona-artifact-inline-muted-color"]=fn(e,I.mutedColor)??I.mutedColor),I.frameHeight&&(n["--persona-artifact-inline-frame-height"]=I.frameHeight)}let N=L?.code;N&&(N.keywordColor&&(n["--persona-code-keyword-color"]=N.keywordColor),N.stringColor&&(n["--persona-code-string-color"]=N.stringColor),N.commentColor&&(n["--persona-code-comment-color"]=N.commentColor),N.numberColor&&(n["--persona-code-number-color"]=N.numberColor),N.tagColor&&(n["--persona-code-tag-color"]=N.tagColor),N.attrColor&&(n["--persona-code-attr-color"]=N.attrColor),N.propertyColor&&(n["--persona-code-property-color"]=N.propertyColor),N.lineNumberColor&&(n["--persona-code-line-number-color"]=N.lineNumberColor),N.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=N.gutterBorderColor),N.background&&(n["--persona-code-bg"]=fn(e,N.background)??N.background));let X=n["--persona-surface"],de=n["--persona-container"],me=n["--persona-palette-colors-gray-100"]??"#f3f4f6",xe=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ye=n["--persona-palette-colors-gray-300"]??"#d1d5db",ne=!de||de===X,ie=ne?me:de,le=ne?xe:de;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??ie,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??le,ne&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ye),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??ie,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??ie,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??ie,n}var zx={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 dM={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"}}},pM={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},jx=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Li=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",uM=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Li()},jc=e=>uM(e),fM=e=>Pi(e),mM=e=>{let t=sa(pM,e??{})??{};return Pi({...t,palette:{...t.palette,colors:{...dM.colors,...t.palette?.colors}}},{validate:!1})},xr=e=>{let t=jc(e),n=jx(e?.theme),o=jx(e?.darkTheme);return t==="dark"?mM(sa(n??{},o??{})):fM(n)},gM=e=>zc(e),ss=(e,t)=>{let n=xr(t),o=gM(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",jc(t))},ia=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Li())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Li());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};var vr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var $x=null;var Wm=()=>{if($x!==null)return $x;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},hM="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",$c=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Gc=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return $c("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?($c("unsupported",e),null):(n==="space"&&(o.key=" "),o)},yM=e=>hM.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Gx=(e,t)=>{let n=Gc(e);if(!n)return"";let o=Wm(),r=yM(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Kc=e=>Gx(e,!1),Hi=e=>Gx(e,!0),bM=(e,t)=>t.key?.toLowerCase()===e.key&&(Wm()?t.metaKey:t.ctrlKey)===e.mod&&!(Wm()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,xM=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},Kx=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(bM(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&xM(i))){s.preventDefault();try{l.run(s)}catch(d){$c(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let i=Gc(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,d=t.get(l);return d?($c(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",Hi(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};function bo(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Xx(e){let t=bo(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Xc(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
28
28
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
|
|
29
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
30
|
-
`).length,
|
|
31
|
-
`);for(let
|
|
32
|
-
`)),n=v("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Dh(e,t,n){let o=e.length<=_C?UC(t,n):null,r=o?XC(e,o):[{type:"plain",value:e}];return JC(r)}function $o(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=v("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(nl)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",r==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let T=document.createElement("hr");s.appendChild(T)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",m.id),m.destructive&&b.setAttribute("data-destructive",""),m.icon){let T=ae(m.icon,16,"currentColor",1.5);T&&b.appendChild(T)}let w=document.createElement("span");w.textContent=m.label,b.appendChild(w),b.addEventListener("click",T=>{T.stopPropagation(),c(),n(m.id)}),s.appendChild(b)}let l=null;function p(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,r==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function d(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=b=>{!s.contains(b.target)&&!o.contains(b.target)&&c()};document.addEventListener("click",m,!0),l=()=>document.removeEventListener("click",m,!0)})}function c(){s.classList.add("persona-hidden"),l?.(),l=null}function f(){s.classList.contains("persona-hidden")?d():c()}function g(){c(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:c,toggle:f,destroy:g}}function Tt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=v("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),s&&p.addEventListener("click",s),l)for(let[c,f]of Object.entries(l))p.setAttribute(c,f);return p}function po(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:a,className:s,onClick:l,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,s&&(d+=" "+s);let c=v("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let g=ae(t,a??14,"currentColor",2);g&&c.appendChild(g)}let f=v("span");if(f.textContent=n,c.appendChild(f),l&&c.addEventListener("click",l),p)for(let[g,m]of Object.entries(p))c.setAttribute(g,m);return c}function ma(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=v("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let s=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===s?"true":"false")}for(let c of t){let f;c.icon?f=Tt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{s=c.id,p(),o(c.id)}}):(f=v("button","persona-icon-btn"+(c.className?" "+c.className:"")),f.type="button",f.setAttribute("aria-label",c.label),f.title=c.label,f.textContent=c.label,f.addEventListener("click",()=>{s=c.id,p(),o(c.id)})),f.setAttribute("aria-pressed",c.id===s?"true":"false"),l.push({id:c.id,btn:f}),a.appendChild(f)}function d(c){s=c,p()}return{element:a,setSelected:d}}function ul(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,d=v("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=v("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let f=ae(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),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=$o({items:o,onSelect:m=>{d.setAttribute("aria-expanded","false"),r(m)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",m=>{m.stopPropagation();let b=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),g.toggle()}),d.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),d.click())}),{element:d,setLabel:m=>{c.textContent=m,d.setAttribute("aria-label",m)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let m=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",m?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var fl="persona-artifact-custom-action-btn";function ga(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+fl+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+fl+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=v("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=po({icon:e.icon,label:e.label,className:fl+(n?" persona-artifact-doc-copy-btn":"")}):o=Tt({icon:e.icon,label:e.label,className:fl+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function bs(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 Fh(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?$n(n.path):o,a=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Vo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.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",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),a&&c.setAttribute("data-open-artifact",a);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.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 g=document.createElement("div");g.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let w=t?.config?.features?.artifacts,T={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},L=fa(T,w,"card");Tr(b,L,w)}else a&&ua(a),b.textContent=d;if(g.append(m,b),c.append(f,g),s==="complete"){let w=t?.config?.features?.artifacts?.cardActions;if(w&&w.length>0){let L={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let A of w)try{if(A.visible===void 0||A.visible(L)){let S=ga(A);S.setAttribute("data-artifact-custom-action",A.id),S.className=`${S.className} persona-flex-shrink-0`,c.append(S)}}catch{}}let T=po({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",a),c.append(T)}return c}var ml=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Fh(e,t)});if(l)return l}return Fh(e,t)};var jo=new WeakMap;function Cu(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let a=jo.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function qh(e){return jo.has(e)}function QC(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let s=e.componentProps,l=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let a=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...a?{file:a}:{},...r?{presentation:r}:{}}}function Oh(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?$n(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Vo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function YC(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 Nh=180,ZC=240,ew=.8,tw=300,nw=500,ow="cubic-bezier(0.2, 0, 0, 1)",_h=240,rw=.35;function aw(e,t,n){let{swap:o,onSettled:r}=n,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"){o(),r();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:Nh,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of s)L.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(nw,Math.max(tw,ZC+d*ew))),f=Math.round(c*rw),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,m=g?g.animate([{opacity:0},{opacity:1}],{duration:_h,delay:f,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:ow});e.style.height=`${p}px`;let w=!1,T=()=>{w||(w=!0,l(),r())};Promise.allSettled([b.finished,m?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(c,f+_h)+120)},Nh)}function sw(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var xs="--persona-artifact-inline-body-height";function iw(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,a=320,s=t?.height;typeof s=="number"||s==="auto"?(r=s,a=s):s&&typeof s=="object"&&(r=s.streaming??320,a=s.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,f=t?.fadeMask;f===!0?(d=!0,c=!0):f===!1?(d=!1,c=!1):f&&typeof f=="object"?(d=f.top===!0,c=f.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let g=t?.transition==="none"?"none":"auto",m=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:a,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:g,completeDisplay:m}}function Uh(e,t){let n=QC(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=sw(o),p=o?.inlineActions??[],d=iw(o),c=d.completeDisplay==="card",f=null,g=n,m=v("div","persona-artifact-inline persona-w-full persona-max-w-full");m.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&m.setAttribute("data-artifact-inline",n.id);let b=ie=>ml(YC(ie),t),w=ie=>{m.classList.add("persona-artifact-inline--card"),m.style.removeProperty(xs),m.replaceChildren(b(ie)),jo.set(m,ue=>{m.replaceChildren(b(ue))})};if(c&&n.status==="complete")return w(n),m;let T=gl(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode}),L=v("div","persona-artifact-inline-body");L.appendChild(T.el);let A=ie=>{let ue=ie.status!=="complete",oe=ue?d.streamingHeight:d.completeHeight,me=typeof oe=="number";me?m.style.setProperty(xs,`${oe}px`):m.style.removeProperty(xs);let Se=!!T.el.querySelector(".persona-code-pre"),Ce=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",Se),L.classList.toggle("persona-artifact-inline-body--sized",me&&Ce),L.classList.toggle("persona-artifact-inline-body--cap",!ue&&!Ce&&typeof d.completeHeight=="number")},S=n.status,C=(ie,ue)=>{S!=="complete"&&ie.status==="complete"?(typeof d.completeHeight=="number"?m.style.setProperty(xs,`${d.completeHeight}px`):m.style.removeProperty(xs),zh(L,ue?.suppressTransition?"none":d.transition,ie.id,()=>{T.update(ie),A(ie)})):T.update(ie),A(ie),S=ie.status};A(n);let M=d.overflow==="clip"&&s&&!!n.id;if(M&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${Oh(n).title} in panel`)),!r)return m.appendChild(L),jo.set(m,C),m;let P=v("div","persona-artifact-inline-chrome");P.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let R=v("div","persona-artifact-inline-chrome-lead"),F=v("span","persona-flex persona-items-center persona-flex-shrink-0"),O=ae("file-text",16,"currentColor",2);O&&F.appendChild(O);let $=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),E=v("span","persona-artifact-inline-type");R.append(F,$,E);let G=v("div","persona-artifact-inline-chrome-actions"),Q=v("span","persona-flex persona-items-center persona-gap-1"),Z=()=>f??d.viewMode,J=l?ma({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:Z(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ie=>{let ue=ie==="source"?"source":"rendered";ue!==Z()&&(f=ue,T.update(g),A(g))}}):null,fe=a?Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;fe&&n.id&&fe.setAttribute("data-copy-artifact",n.id);let ne=s?Tt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ne&&n.id&&ne.setAttribute("data-expand-artifact-inline",n.id),G.appendChild(Q),J&&G.appendChild(J.element),fe&&G.appendChild(fe),ne&&G.appendChild(ne),P.append(R,G),m.append(P,L);let ge=ie=>{let{title:ue,typeLabel:oe}=Oh(ie);$.textContent=ue,$.title=ue,M&&L.setAttribute("aria-label",`Open ${ue} in panel`);let me=ie.status!=="complete";if(me){E.classList.contains("persona-artifact-inline-status")||(E.className="persona-artifact-inline-status",E.removeAttribute("data-preserve-animation"),E.replaceChildren());let Se=fa(ie,o,"inline-chrome");Tr(E,Se,o)}else ua(ie.id),E.className="persona-artifact-inline-type",E.removeAttribute("data-preserve-animation"),E.replaceChildren(),E.textContent=oe;if(fe&&fe.classList.toggle("persona-hidden",me),J){let Se=ie.artifactType==="markdown"?ie.file:void 0,Ce=!1;if(!me&&Se&&d.viewMode!=="source"){let Be=Mr(Se);Be==="markdown"?Ce=!0:(Be==="html"||Be==="svg")&&(Ce=o?.filePreview?.enabled!==!1)}J.element.classList.toggle("persona-hidden",!Ce),J.setSelected(Z())}if(Q.replaceChildren(),!me&&p.length>0){let Se=bs(ie);if(Se)for(let Ce of p)try{if(Ce.visible===void 0||Ce.visible(Se)){let Be=ga(Ce,{documentChrome:!0});Be.setAttribute("data-artifact-custom-action",Ce.id),Be.classList.add("persona-flex-shrink-0"),Q.appendChild(Be)}}catch{}}};return ge(n),jo.set(m,(ie,ue)=>{if(c&&S!=="complete"&&ie.status==="complete"){let oe=m.isConnected?m.getBoundingClientRect().height:0;S="complete";let me=ie,Se=!1,Ce=Be=>{me=Be,Se=!0};jo.set(m,Ce),aw(m,oe,{swap:()=>{w(me),Se=!1,jo.set(m,Ce)},onSettled:()=>{Se?w(me):jo.set(m,Be=>{m.replaceChildren(b(Be))})}});return}(ie.status!=="complete"||ie.id!==g.id)&&(f=null),g=ie,C(ie,ue),ge(ie)}),m}var Vh=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Uh(e,t)});if(l)return l}return Uh(e,t)};var wu=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):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(([n,o])=>{this.register(n,o)})}},Nn=new wu;Nn.register("PersonaArtifactCard",ml,{bubbleChrome:!1});Nn.register("PersonaArtifactInline",Vh,{bubbleChrome:!1});function vs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?cl(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Au=!1;function lw(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function zh(e,t,n,o){let r=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 r!="function"||Au||a){o();return}Au=!0;let s=lw(n);e.style.setProperty("view-transition-name",s);let l=()=>{Au=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var cw="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",dw="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function pw(e){let t=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function uw(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 fw=220;function mw(){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 gw(e){return`
|
|
33
|
-
<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 hw(e,t,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let s=n.renderIndicator({artifactId:e,config:t});if(s)return o.appendChild(s),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(Lh());let a=null;return n.label!==!1&&(a=v("div","persona-artifact-frame-loading-text"),a.textContent=n.label,r.appendChild(a)),o.appendChild(r),{el:o,revealLabel:()=>{a&&a.classList.add("persona-artifact-frame-loading-text--visible")}}}function yw(e,t,n,o,r,a){let s=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(S=>clearTimeout(S)),d.clear()},f=(S,C)=>{let M=setTimeout(()=>{d.delete(M),S()},C);d.add(M)},g=()=>{s&&s.parentElement&&s.remove(),s=null},m=()=>{if(s||p)return;let S=hw(r,a,o);s=S.el,e.appendChild(s),l=Date.now(),o.label!==!1&&f(S.revealLabel,o.labelDelayMs)},b=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),f(g,fw))},w=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",A)},T=()=>{if(p||(p=!0,w(),c(),!s))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-l));S>0?f(b,S):b()};function L(S){if(n===null)return;let C=S.data;!C||C.persona!=="artifact-preview-ready"||C.token!==n||S.source===t.contentWindow&&T()}function A(){let S=C=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>C()):setTimeout(C,0)};S(()=>S(()=>T()))}return f(m,o.delayMs),f(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",A),()=>{p=!0,c(),w(),g()}}function gl(e,t){let{config:n}=t,o=t.registry??Nn,r=t.bodyLayout,a=n.markdown?hr(n.markdown):null,s=ta(n.sanitize),l=e,p=!1,d=ne=>{let ge=ao()!==null;a&&!ge&&!p&&(p=!0,ea(()=>fe(l)));let ie=a?a(ne):Vn(ne);return a&&ge&&s?s(ie):ie},c=v("div","persona-artifact-preview-body"),f=null,g=null,m=null,b=()=>{m&&(m(),m=null),f=null,g=null},w=null,T=null,L=null,A=!1,S=()=>{w=null,T=null,L=null,A=!1},C=null,M=null,P=()=>{C=null,M=null},R=40,F=0,O=ne=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ne()):setTimeout(ne,0),$=ne=>ne.scrollHeight-ne.clientHeight-ne.scrollTop<=R,E=ne=>{if(!r)return;let ge=ne.scrollHeight-ne.clientHeight>1,ie=ne.scrollHeight-ne.clientHeight-ne.scrollTop;ne.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&ne.scrollTop>1),ne.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&ie>1)},G=ne=>{F||(F=O(()=>{F=0,ne.scrollTop=ne.scrollHeight,E(ne)}))},Q=(ne,ge,ie,ue)=>{let oe=!!r,me=ie.id+"|"+(oe?"w":"p");if(!w||L!==me||w.parentElement!==c){b(),P(),c.replaceChildren();let Be=v("pre",cw+" persona-code-pre"),ut=v("code","persona-code");if(Be.appendChild(ut),oe){let Je=v("div","persona-artifact-source-window");if(Je.appendChild(Be),c.appendChild(Je),!(r?.overflow==="clip")&&typeof Je.addEventListener=="function"){let Ne=()=>Je.scrollHeight-Je.clientHeight>1;Je.addEventListener("scroll",()=>{$(Je)&&(A=!1),E(Je)},{passive:!0}),Je.addEventListener("wheel",_e=>{Ne()&&_e.deltaY<0&&(A=!0)},{passive:!0}),Je.addEventListener("touchmove",()=>{Ne()&&(A=!0)},{passive:!0})}w=Je}else c.appendChild(Be),w=Be;T=ut,L=me}let Se=oe?w:null;Se&&(Se.classList.toggle("persona-artifact-source-window--fixed",ue),Se.classList.toggle("persona-artifact-source-window--clip",ue&&r?.overflow==="clip"));let Ce=Se?$(Se):!0;if(T.replaceChildren(Dh(ne,ge?.language,ge?.path)),Se){let Be=ie.status!=="complete";ue&&Be&&r?.followOutput&&!A&&Ce?G(Se):Be||(A=!1),E(Se)}},Z=ne=>{b(),S(),P(),c.replaceChildren();let ge=v("div",dw);ge.innerHTML=d(ne),c.appendChild(ge)},J=ne=>{let ge=ne.id,ie=n.features?.artifacts,ue=fa(ne,ie,"status-body");if(C&&M===ge&&C.parentElement===c){let Se=C.querySelector(".persona-artifact-status-view-text");Se&&Tr(Se,ue,ie);return}b(),S(),c.replaceChildren();let oe=v("div","persona-artifact-status-view"),me=v("div","persona-artifact-status-view-text");Tr(me,ue,ie),oe.appendChild(me),c.appendChild(oe),C=oe,M=ge},fe=ne=>{l=ne;let ge=t.resolveViewMode?.(ne)??r?.viewMode??"rendered",ie=ne.artifactType==="markdown"?ne.file:void 0,ue=ne.status!=="complete";ue||ua(ne.id);let oe=ue?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof oe=="number";if(r?.streamingView==="status"&&ue){J(ne);return}if(ie){let Ce=cl(ne.markdown??""),Be=Mr(ie),ut=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ue&&ge==="rendered"&&ut&&(Be==="html"||Be==="svg")){let Qe=ne.id+"\0"+Ce;if(f&&g===Qe&&f.parentElement===c)return;S(),P(),b(),c.replaceChildren();let Ne=n.features?.artifacts?.filePreview,_e=Ne?.iframeSandbox??"allow-scripts";!Ne?.dangerouslyAllowSameOrigin&&_e.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."),_e=_e.split(/\s+/).filter(gt=>gt&>!=="allow-same-origin").join(" "));let Ae=uw(Ne?.loading),Me=v("div","persona-artifact-frame"),qe=v("iframe","persona-artifact-iframe");qe.setAttribute("sandbox",_e),qe.setAttribute("data-artifact-id",ne.id);let Jt=null;Ae.enabled&&Ae.injectReadySignal?(Jt=mw(),qe.srcdoc=Ce+gw(Jt)):qe.srcdoc=Ce,Me.appendChild(qe),c.appendChild(Me),Ae.enabled&&(m=yw(Me,qe,Jt,Ae,ne.id,n)),f=Me,g=Qe;return}if(b(),!ue&&Be==="markdown"&&ge==="rendered"){Z(Ce);return}Q(Ce,{language:ie.language,path:ie.path},ne,me);return}if(ne.artifactType==="markdown"){if(ge==="source"){b(),Q(ne.markdown??"",void 0,ne,me);return}Z(ne.markdown??"");return}b(),S(),P(),c.replaceChildren();let Se=ne.component?o.get(ne.component):void 0;if(Se){let Be={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ut=Se(ne.props??{},Be);if(ut){c.appendChild(ut);return}}catch{}}c.appendChild(pw(ne))};return fe(e),{el:c,update(ne){fe(ne)}}}var $h=(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 n(g,m,b={}){g=c(g);let w=f(m),T=d(g,w,b),L=r(T,()=>l(T,g,w,A=>A.morphStyle==="innerHTML"?(a(A,g,w),Array.from(g.childNodes)):o(A,g,w)));return T.pantry.remove(),L}function o(g,m,b){let w=f(m);return a(g,w,b,m,m.nextSibling),Array.from(w.childNodes)}function r(g,m){if(!g.config.restoreFocus)return m();let b=document.activeElement;if(!(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement))return m();let{id:w,selectionStart:T,selectionEnd:L}=b,A=m();return w&&w!==document.activeElement?.getAttribute("id")&&(b=g.target.querySelector(`[id="${w}"]`),b?.focus()),b&&!b.selectionEnd&&L&&b.setSelectionRange(T,L),A}let a=(function(){function g(C,M,P,R=null,F=null){M instanceof HTMLTemplateElement&&P instanceof HTMLTemplateElement&&(M=M.content,P=P.content),R||(R=M.firstChild);for(let O of P.childNodes){if(R&&R!=F){let E=b(C,O,R,F);if(E){E!==R&&T(C,R,E),s(E,O,C),R=E.nextSibling;continue}}if(O instanceof Element){let E=O.getAttribute("id");if(C.persistentIds.has(E)){let G=L(M,E,R,C);s(G,O,C),R=G.nextSibling;continue}}let $=m(M,O,R,C);$&&(R=$.nextSibling)}for(;R&&R!=F;){let O=R;R=R.nextSibling,w(C,O)}}function m(C,M,P,R){if(R.callbacks.beforeNodeAdded(M)===!1)return null;if(R.idMap.has(M)){let F=document.createElement(M.tagName);return C.insertBefore(F,P),s(F,M,R),R.callbacks.afterNodeAdded(F),F}else{let F=document.importNode(M,!0);return C.insertBefore(F,P),R.callbacks.afterNodeAdded(F),F}}let b=(function(){function C(R,F,O,$){let E=null,G=F.nextSibling,Q=0,Z=O;for(;Z&&Z!=$;){if(P(Z,F)){if(M(R,Z,F))return Z;E===null&&(R.idMap.has(Z)||(E=Z))}if(E===null&&G&&P(Z,G)&&(Q++,G=G.nextSibling,Q>=2&&(E=void 0)),R.activeElementAndParents.includes(Z))break;Z=Z.nextSibling}return E||null}function M(R,F,O){let $=R.idMap.get(F),E=R.idMap.get(O);if(!E||!$)return!1;for(let G of $)if(E.has(G))return!0;return!1}function P(R,F){let O=R,$=F;return O.nodeType===$.nodeType&&O.tagName===$.tagName&&(!O.getAttribute?.("id")||O.getAttribute?.("id")===$.getAttribute?.("id"))}return C})();function w(C,M){if(C.idMap.has(M))S(C.pantry,M,null);else{if(C.callbacks.beforeNodeRemoved(M)===!1)return;M.parentNode?.removeChild(M),C.callbacks.afterNodeRemoved(M)}}function T(C,M,P){let R=M;for(;R&&R!==P;){let F=R;R=R.nextSibling,w(C,F)}return R}function L(C,M,P,R){let F=R.target.getAttribute?.("id")===M&&R.target||R.target.querySelector(`[id="${M}"]`)||R.pantry.querySelector(`[id="${M}"]`);return A(F,R),S(C,F,P),F}function A(C,M){let P=C.getAttribute("id");for(;C=C.parentNode;){let R=M.idMap.get(C);R&&(R.delete(P),R.size||M.idMap.delete(C))}}function S(C,M,P){if(C.moveBefore)try{C.moveBefore(M,P)}catch{C.insertBefore(M,P)}else C.insertBefore(M,P)}return g})(),s=(function(){function g(A,S,C){return C.ignoreActive&&A===document.activeElement?null:(C.callbacks.beforeNodeMorphed(A,S)===!1||(A instanceof HTMLHeadElement&&C.head.ignore||(A instanceof HTMLHeadElement&&C.head.style!=="morph"?p(A,S,C):(m(A,S,C),L(A,C)||a(C,A,S))),C.callbacks.afterNodeMorphed(A,S)),A)}function m(A,S,C){let M=S.nodeType;if(M===1){let P=A,R=S,F=P.attributes,O=R.attributes;for(let $ of O)T($.name,P,"update",C)||P.getAttribute($.name)!==$.value&&P.setAttribute($.name,$.value);for(let $=F.length-1;0<=$;$--){let E=F[$];if(E&&!R.hasAttribute(E.name)){if(T(E.name,P,"remove",C))continue;P.removeAttribute(E.name)}}L(P,C)||b(P,R,C)}(M===8||M===3)&&A.nodeValue!==S.nodeValue&&(A.nodeValue=S.nodeValue)}function b(A,S,C){if(A instanceof HTMLInputElement&&S instanceof HTMLInputElement&&S.type!=="file"){let M=S.value,P=A.value;w(A,S,"checked",C),w(A,S,"disabled",C),S.hasAttribute("value")?P!==M&&(T("value",A,"update",C)||(A.setAttribute("value",M),A.value=M)):T("value",A,"remove",C)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&S instanceof HTMLOptionElement)w(A,S,"selected",C);else if(A instanceof HTMLTextAreaElement&&S instanceof HTMLTextAreaElement){let M=S.value,P=A.value;if(T("value",A,"update",C))return;M!==P&&(A.value=M),A.firstChild&&A.firstChild.nodeValue!==M&&(A.firstChild.nodeValue=M)}}function w(A,S,C,M){let P=S[C],R=A[C];if(P!==R){let F=T(C,A,"update",M);F||(A[C]=S[C]),P?F||A.setAttribute(C,""):T(C,A,"remove",M)||A.removeAttribute(C)}}function T(A,S,C,M){return A==="value"&&M.ignoreActiveValue&&S===document.activeElement?!0:M.callbacks.beforeAttributeUpdated(A,S,C)===!1}function L(A,S){return!!S.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function l(g,m,b,w){if(g.head.block){let T=m.querySelector("head"),L=b.querySelector("head");if(T&&L){let A=p(T,L,g);return Promise.all(A).then(()=>{let S=Object.assign(g,{head:{block:!1,ignore:!0}});return w(S)})}}return w(g)}function p(g,m,b){let w=[],T=[],L=[],A=[],S=new Map;for(let M of m.children)S.set(M.outerHTML,M);for(let M of g.children){let P=S.has(M.outerHTML),R=b.head.shouldReAppend(M),F=b.head.shouldPreserve(M);P||F?R?T.push(M):(S.delete(M.outerHTML),L.push(M)):b.head.style==="append"?R&&(T.push(M),A.push(M)):b.head.shouldRemove(M)!==!1&&T.push(M)}A.push(...S.values());let C=[];for(let M of A){let P=document.createRange().createContextualFragment(M.outerHTML).firstChild;if(b.callbacks.beforeNodeAdded(P)!==!1){if("href"in P&&P.href||"src"in P&&P.src){let R,F=new Promise(function(O){R=O});P.addEventListener("load",function(){R()}),C.push(F)}g.appendChild(P),b.callbacks.afterNodeAdded(P),w.push(P)}}for(let M of T)b.callbacks.beforeNodeRemoved(M)!==!1&&(g.removeChild(M),b.callbacks.afterNodeRemoved(M));return b.head.afterHeadMorphed(g,{added:w,kept:L,removed:T}),C}let d=(function(){function g(C,M,P){let{persistentIds:R,idMap:F}=A(C,M),O=m(P),$=O.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:C,newContent:M,config:O,morphStyle:$,ignoreActive:O.ignoreActive,ignoreActiveValue:O.ignoreActiveValue,restoreFocus:O.restoreFocus,idMap:F,persistentIds:R,pantry:b(),activeElementAndParents:w(C),callbacks:O.callbacks,head:O.head}}function m(C){let M=Object.assign({},t);return Object.assign(M,C),M.callbacks=Object.assign({},t.callbacks,C.callbacks),M.head=Object.assign({},t.head,C.head),M}function b(){let C=document.createElement("div");return C.hidden=!0,document.body.insertAdjacentElement("afterend",C),C}function w(C){let M=[],P=document.activeElement;if(P?.tagName!=="BODY"&&C.contains(P))for(;P&&(M.push(P),P!==C);)P=P.parentElement;return M}function T(C){let M=Array.from(C.querySelectorAll("[id]"));return C.getAttribute?.("id")&&M.push(C),M}function L(C,M,P,R){for(let F of R){let O=F.getAttribute("id");if(M.has(O)){let $=F;for(;$;){let E=C.get($);if(E==null&&(E=new Set,C.set($,E)),E.add(O),$===P)break;$=$.parentElement}}}}function A(C,M){let P=T(C),R=T(M),F=S(P,R),O=new Map;L(O,F,C,P);let $=M.__idiomorphRoot||M;return L(O,F,$,R),{persistentIds:F,idMap:O}}function S(C,M){let P=new Set,R=new Map;for(let{id:O,tagName:$}of C)R.has(O)?P.add(O):R.set(O,$);let F=new Set;for(let{id:O,tagName:$}of M)F.has(O)?P.add(O):R.get(O)===$&&F.add(O);for(let O of P)F.delete(O);return F}return g})(),{normalizeElement:c,normalizeParent:f}=(function(){let g=new WeakSet;function m(L){return L instanceof Document?L.documentElement:L}function b(L){if(L==null)return document.createElement("div");if(typeof L=="string")return b(T(L));if(g.has(L))return L;if(L instanceof Node){if(L.parentNode)return new w(L);{let A=document.createElement("div");return A.append(L),A}}else{let A=document.createElement("div");for(let S of[...L])A.append(S);return A}}class w{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],S=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;S&&S!=this.nextSibling;)A.push(S),S=S.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((S,C)=>{if(C instanceof Element){C.matches(A)&&S.push(C);let M=C.querySelectorAll(A);for(let P=0;P<M.length;P++)S.push(M[P])}return S},[])}insertBefore(A,S){return this.realParentNode.insertBefore(A,S)}moveBefore(A,S){return this.realParentNode.moveBefore(A,S)}get __idiomorphRoot(){return this.originalNode}}function T(L){let A=new DOMParser,S=L.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(S.match(/<\/html>/)||S.match(/<\/head>/)||S.match(/<\/body>/)){let C=A.parseFromString(L,"text/html");if(S.match(/<\/html>/))return g.add(C),C;{let M=C.firstChild;return M&&g.add(M),M}}else{let M=A.parseFromString("<body><template>"+L+"</template></body>","text/html").body.querySelector("template").content;return g.add(M),M}}return{normalizeElement:m,normalizeParent:b}})();return{morph:n,defaults:t}})();var hl=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;$h.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.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=r.textContent??"",l=a.textContent??"";if(s!==l)return}return!1}}}}})};var jh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Su={index:-1,draft:""};function Gh(e){let{direction:t,history:n,currentValue:o,atStart:r,state:a}=e,s=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!r)return{handled:!1,state:a};if(!s){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(a.index>0){let l=a.index-1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<n.length-1){let l=a.index+1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function Kh(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 Xh(){return new Map}function Jh(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Qh(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Yh(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Zh(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function yl(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function jn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function uo(e,t){return jn(e)-e.scrollTop<=t}function bl(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function xl(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function ey(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Mu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function ty(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},bw=["pre","code","a","script","style"],vl=e=>({type:e?.type??Cs.type,placeholder:e?.placeholder??Cs.placeholder,speed:e?.speed??Cs.speed,duration:e?.duration??Cs.duration,buffer:e?.buffer??Cs.buffer}),oy=[{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"}],ws=new Map;for(let e of oy)ws.set(e.name,e);var Er=e=>{ws.set(e.name,e)},ku=e=>{oy.some(t=>t.name===e)||ws.delete(e)},Lu=()=>Array.from(ws.keys()),ha=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:ws.get(e)??null,Cl=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.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(`
|
|
34
|
-
`);return a<0?"":e.slice(0,a)}return e},xw=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},vw=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Tu=/\s/,Cw=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},ww=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=0;for(;l<a.length;)if(Tu.test(a[l])){let p=l;for(;p<a.length&&Tu.test(a[p]);)p+=1;s.appendChild(o.createTextNode(a.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<a.length&&!Tu.test(a[d]);)p.appendChild(xw(o,a[d],t,n.value)),n.value+=1,d+=1;s.appendChild(p),l=d}r.replaceChild(s,e)},Aw=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=a.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?s.appendChild(o.createTextNode(p)):(s.appendChild(vw(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},As=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((o?.skipTags??bw).map(f=>f.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)Cw(p,a)||l.push(p),p=s.nextNode();let d={value:o?.startIndex??0},c=t==="char"?ww:Aw;for(let f of l)c(f,n,d);return r.innerHTML},wl=(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},Ss=(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 n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},ny=new WeakMap,Sw=(e,t)=>{if(!e.styles)return;let n=ny.get(t);if(n||(n=new Set,ny.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Eu=new WeakMap,Mw=(e,t)=>{if(!e.onAttach)return;let n=Eu.get(t);if(n||(n=new Map,Eu.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},ry=e=>{let t=Eu.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Al=(e,t)=>{Sw(e,t),Mw(e,t)};function Pu(e,t=Ut){let n=e.style.position,o=e.style.zIndex,r=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=n),e.style.zIndex=o,e.style.isolation=r}}var Ms=0,Go=null;function Ru(e=document){if(Ms++,Ms===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Go={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Ms=Math.max(0,Ms-1),Ms===0&&Go)){let n=e.body,o=e.defaultView??window;n.style.overflow=Go.originalOverflow,n.style.position=Go.originalPosition,n.style.top=Go.originalTop,n.style.width=Go.originalWidth,o.scrollTo(0,Go.scrollY),Go=null}}}var Ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Ko=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",ln=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ts.side,width:t?.width??Ts.width,animate:t?.animate??Ts.animate,reveal:t?.reveal??Ts.reveal,maxHeight:t?.maxHeight??Ts.maxHeight}};var Iu=e=>e==="followUp"?"follow-up":e,Wu=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},Tw=e=>{switch(e){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'}},ay=new WeakSet,Ew=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,kw=e=>{Ew()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Hu=e=>{var A,S,C;let{item:t,index:n,surface:o,source:r,variant:a,streaming:s,config:l,plugins:p,chipsConfig:d,session:c,getTextarea:f,eventTarget:g}=e,m=o==="followUp",b=t.behavior,w=()=>{if(c.isStreaming())return;let M={suggestion:{...t},surface:o,source:r,behavior:b},P=g.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:M,bubbles:!0,composed:!0,cancelable:!0}));if(m&&g.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!P)return;for(let F of p)if(F.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:a,config:l})===!1)return;let R=f();if(b==="fill"){R.value=t.prompt,R.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),R.focus();return}R.value="",c.sendMessage(t.prompt)},T=()=>{let M=v("button",`persona-suggestion persona-suggestion--${a}`);if(M.type="button",M.disabled=s,M.dataset.suggestionId=t.id,M.dataset.emphasis=t.emphasis,M.dataset.behavior=b,a==="chip"&&(d?.fontFamily&&(M.style.fontFamily=Tw(d.fontFamily)),d?.fontWeight&&(M.style.fontWeight=d.fontWeight),d?.paddingX&&(M.style.paddingLeft=d.paddingX,M.style.paddingRight=d.paddingX),d?.paddingY&&(M.style.paddingTop=d.paddingY,M.style.paddingBottom=d.paddingY)),t.icon){let R=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);R&&(R.classList.add("persona-suggestion__icon"),t.iconColor&&(R.style.color=t.iconColor),M.appendChild(R))}let P=v("span","persona-suggestion__copy");if(P.appendChild(ke("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&P.appendChild(ke("span",{className:"persona-suggestion__description",text:t.description})),M.appendChild(P),a!=="chip"){let R=ae("arrow-right",16,"currentColor",1.8);R&&(R.classList.add("persona-suggestion__arrow"),M.appendChild(R))}return M.addEventListener("click",w),M},L=null;for(let M of p)if(M.renderSuggestion&&(L=M.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:a,streaming:s,config:l,defaultRenderer:T,select:w}),L))break;return L??(L=T()),(A=L.dataset).suggestionId||(A.suggestionId=t.id),(S=L.dataset).behavior||(S.behavior=b),(C=L.dataset).emphasis||(C.emphasis=t.emphasis),L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",s?"true":"false"),L},Es=e=>{let t=[],n=[],o=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){a();return}let f=getComputedStyle(e).direction==="rtl",g=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),m=4,b=g<=m,w=g>=c-m,T=f?!w:!b,L=f?!b:!w;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",L)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&s();return}r=requestAnimationFrame(s)};e.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,f,g,m,b,w)=>{e.replaceChildren(),t.length=0,n.length=0;let T=w?.source??"config",L=w?.surface??(T==="config"?"starter":"followUp"),A=L==="followUp",S=w?.variant??"chip",C=w?.behavior??"send",M=w?.overflow??"wrap",P=w?.config??{},R=w?.plugins??[],F=typeof w?.maxItems=="number"?Math.max(0,Math.floor(w.maxItems)):void 0,O=A?"followUps":"starters";!ay.has(P)&&P.debug===!0&&S!=="chip"&&P.suggestions?.[O]?.overflow!==void 0&&(ay.add(P),console.info(`[persona] suggestions.${O}.overflow applies to the "chip" variant only; the "${S}" variant manages its own stacking.`));let $=fe=>fe.map(Wu).filter(ne=>ne!==null).map(ne=>({...ne,behavior:ne.behavior??C})),E=$(c??[]);R.forEach(fe=>{fe.transformSuggestions&&(E=$(fe.transformSuggestions({suggestions:E.map(ne=>({...ne})),surface:L,source:T,config:P})))});let G=F===void 0?E:E.slice(0,F);if(!G.length){e.hidden=!0,o=null,a();return}if(!A&&(m??f.getMessages()).some(ne=>ne.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Iu(L),e.dataset.variant=S,e.dataset.overflow=M;let Q=document.createDocumentFragment(),Z=f.isStreaming();G.forEach((fe,ne)=>{let ge=Hu({item:fe,index:ne,surface:L,source:T,variant:S,streaming:Z,config:P,plugins:R,chipsConfig:b,session:f,getTextarea:()=>g,eventTarget:e});Q.appendChild(ge),n.push(ge),[...ge instanceof HTMLButtonElement?[ge]:[],...Array.from(ge.querySelectorAll("button"))].forEach(ue=>{t.includes(ue)||(ue.disabled=Z,t.push(ue))})}),e.appendChild(Q),s(),l();let J=JSON.stringify({normalized:G,surface:L,variant:S,source:T});J!==o&&(o=J,kw(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:G.map(fe=>({...fe})),surface:L,source:T,variant:S},bubbles:!0,composed:!0})),A&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:G.map(fe=>fe.prompt)},bubbles:!0,composed:!0})))}}};var gn={"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 Lw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Sl=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Lw,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=v("div",o),d=s.closeButtonTooltipText??"Close chat",c=s.closeButtonShowTooltip??!0,f=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),b=ke("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:s.closeButtonColor||Xt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${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}}),w=ae(f,a,"currentColor",1);return w?(w.style.display="block",b.appendChild(w)):b.textContent=g,p.appendChild(b),qt({anchor:b,trigger:p,text:()=>b.getAttribute("aria-label")??d,enabled:c}),{button:b,wrapper:p}},Pw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ml=(e,t={})=>{let{wrapperClassName:n=Pw,buttonSize:o,iconSize:r="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=o??s.size??"32px",p=s.iconName??"refresh-cw",d=s.iconColor??"",c=s.backgroundColor??"",f=s.borderWidth??"",g=s.borderColor??"",m=s.borderRadius??"",b=s.paddingX??"",w=s.paddingY??"",T=s.tooltipText??"Clear chat",L=s.showTooltip??!0,A=v("div",n),S=!!(f||g),C=ke("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:l,width:l,color:d||Xt.actionIconColor,backgroundColor:c||void 0,border:S?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),M=ae(p,r,"currentColor",1);return M&&(M.style.display="block",C.appendChild(M)),A.appendChild(C),qt({anchor:C,trigger:A,text:()=>C.getAttribute("aria-label")??T,enabled:L}),{button:C,wrapper:A}};var Xt={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))"},Bu={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},Rw={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},fo=e=>{let{config:t,showClose:n=!0}=e,o=ke("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)))"}}),r=t?.launcher??{},a=r.headerIconSize??"48px",s=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=ke("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 M=parseFloat(a)||24,P=ae(p,M*.6,"currentColor",1);P?d.replaceChildren(P):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let M=v("img");M.src=t.launcher.iconUrl,M.alt="",M.className="persona-rounded-xl persona-object-cover",M.style.height=a,M.style.width=a,d.replaceChildren(M)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=ke("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor,...Bu}}),g=ke("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor,...Rw}});c.append(f,g),l?o.append(c):o.append(d,c);let m=r.clearChat??{},b=m.enabled??!0,w=m.placement??"inline",T=null,L=null;if(b){let P=Ml(t,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=P.button,L=P.wrapper,w==="top-right"&&(L.style.right="48px"),w==="inline"&&o.appendChild(L)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&w==="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:S,wrapper:C}=Sl(t,{showClose:n,wrapperClassName:A});return s!=="top-right"&&o.appendChild(C),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:g,closeButton:S,closeButtonWrapper:C,clearChatButton:T,clearChatButtonWrapper:L}},kr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Du=e=>{let t=fo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function Iw(e,t,n){if(t?.length)for(let o of t){let r=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Xt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let a=ae(o.icon,16,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=v("div","persona-relative");a.appendChild(r);let s=$o({items:o.menuItems,onSelect:l=>n?.(l),anchor:a,position:"bottom-right"});a.appendChild(s.element),r.addEventListener("click",l=>{l.stopPropagation(),s.toggle()}),e.appendChild(a)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Fu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=v("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=r?.titleMenu,d,c;if(p)d=ul({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Xt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=v("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Xt.titleColor,Object.assign(c.style,Bu),c.textContent=s.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let C=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||C()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),C())})}let S=r?.titleRowHover;S&&(d.style.borderRadius=S.borderRadius??"10px",d.style.padding=S.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=S.background??"",d.style.borderColor=S.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f=s.closeButtonSize??"32px",g=v("div",""),m=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=s.closeButtonColor||Xt.actionIconColor;let b=s.closeButtonIconName??"x",w=ae(b,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m);let T=v("div","persona-flex persona-items-center persona-gap-1");p||Iw(T,r?.trailingActions,r?.onAction??a),T.appendChild(g),l.appendChild(T);let L=v("div");L.style.display="none";let A=v("span");return A.style.display="none",{header:l,iconHolder:L,headerTitle:c,headerSubtitle:A,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Tl={default:Du,minimal:Fu},Ou=e=>Tl[e]??Tl.default,ya=(e,t,n)=>{if(t?.render){let s=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=v("div");l.style.display="none";let p=v("span"),d=v("span"),c=v("button");c.style.display="none";let f=v("div");return f.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",a=Ou(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.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 El=e=>{let t=v("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-text 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 n=3,o=20,r=()=>{let p=t.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let d=p.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},a=`${n*o}px`;t.style.maxHeight=a,t.style.overflowY="auto";let s=()=>{let p=t.style.maxHeight;if(p!==a){let c=parseFloat(p);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return a=`${d}px`,t.style.maxHeight=a,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,s());t.style.height=`${p}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:l}},kl=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=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,f=t.size??"40px",g=t.backgroundColor,m=t.textColor,b=v("div","persona-send-button-wrapper"),w=ke("button",{className:Fn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),T=null,L=null;if(n){let C=parseFloat(t.iconSize??"")||Math.round((parseFloat(f)||24)*.5),M=t.iconStrokeWidth??2,P=m?.trim()||"currentColor";r?(T=ae(r,C,P,M),T?w.appendChild(T):w.textContent=o):w.textContent=o,L=ae(a,C,P,M)}else w.textContent=p;w.setAttribute("aria-label",s),b.appendChild(w),qt({anchor:w,trigger:b,text:()=>w.getAttribute("aria-label")??"",enabled:c});let A="send";return{button:w,wrapper:b,setMode:C=>{if(C===A)return;A=C;let M=C==="stop"?l:s;if(w.setAttribute("aria-label",M),n){if(T&&L){let P=C==="stop"?L:T;w.replaceChildren(P)}}else w.textContent=C==="stop"?d:p}}},Ll=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))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,f=t.iconColor??e?.sendButton?.textColor,g=v("div","persona-send-button-wrapper"),m=ke("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":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:f||"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}}),w=ae(l,d,f||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",g.appendChild(m);let T=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return qt({anchor:m,trigger:g,text:()=>m.getAttribute("aria-label")??T,enabled:L}),{button:m,wrapper:g}},Pl=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=v("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 r=v("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??co).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let a=t.buttonIconName??"paperclip",s=n,l=parseFloat(s)||40,p=Math.round(l*.6),d=v("div","persona-send-button-wrapper"),c=ke("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"}}),f=ae(a,p,"currentColor",1.5);f?c.appendChild(f):c.textContent="\u{1F4CE}",c.addEventListener("click",m=>{m.preventDefault(),r.click()}),d.appendChild(c);let g=t.buttonTooltipText??"Attach file";return qt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??g}),{button:c,wrapper:d,input:r,previewsContainer:o}},Rl=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let s=v("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=a;return o},Il=()=>ke("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Lr=e=>{let{config:t}=e,n=ke("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=Il(),r=ke("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=El(t);s();let l=kl(t),p=Ll(t),d=Pl(t),c=Rl(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(a);let f=ke("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&g.append(d.wrapper),p&&m.append(p.wrapper),m.append(l.wrapper),f.append(g,m),r.append(f),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&a.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,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:f,leftActions:g,rightActions:m,setSendButtonMode:l.setMode}};var sy=()=>{let e=ke("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=v("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),a=ae("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},Wl=e=>{let{config:t}=e,n=ke("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Il(),r=Rl(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=El(t);a.style.maxHeight="100px",s();let l=kl(t),p=Ll(t),d=Pl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=ke("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=v("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&f.append(d.wrapper);let g=v("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),c.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(f,a,g),d&&n.append(d.previewsContainer),n.append(o,c,r);let m=c;return{footer:n,suggestions:o,composerForm:c,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:f,rightActions:g,setSendButtonMode:l.setMode}};var Ww=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}},Hw=(e,t)=>{if(!e)return null;let n=Ww(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Bw=(e,t)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Dw=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Nu=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(":"))},_u=320,dy=320,Fw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ow=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Nw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),_w=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Uw=e=>{if(!e||e.length===0)return null;let t=ke("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=ke("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),a=ae(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(ke("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},qw=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ms(o.ref,{readonly:!0,render:t}))}return n},iy="\uE000",ly="\uE001",Vw=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${iy}${r}:${g}${ly}`,s=t.map((g,m)=>g.kind==="text"?g.text:a(m)).join(""),l=n(s);if(!t.every((g,m)=>g.kind==="text"||l.includes(a(m)))){e.replaceChildren(qw(t,o));return}e.innerHTML=l;let d=new RegExp(`${iy}${r}:(\\d+)${ly}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let g=c.nextNode();g;g=c.nextNode())f.push(g);for(let g of f){let m=g;for(let b=d.exec(m.data);b;b=d.exec(m.data)){let w=t[Number(b[1])],T=m.splitText(b.index);T.data=T.data.slice(b[0].length),w?.kind==="mention"&&T.parentNode?.insertBefore(ms(w.ref,{readonly:!0,render:o}),T),m=T}}},zw=(e,t,n)=>{if(e.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,a=!1,s=()=>{a||(a=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let d=v("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=`${_u}px`,d.style.maxHeight=`${dy}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;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&s())}),d.addEventListener("load",()=>{c=!0}),Dw(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(s(),null):o}catch{return n?.(),null}},$w=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Nu(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${_u}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jw=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Nu(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${_u}px`,r.style.maxHeight=`${dy}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Gw=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Nu(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Pr=()=>{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 n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="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 r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Uu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Pr};if(t){let r=t(o);if(r!==null)return r}return Pr()},Kw=(e,t)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},cy=(e,t,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},ks=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},qu=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,a=t.showDownvote??!0,s=t.showReadAloud??!1;if(!o&&!r&&!a&&!s){let b=v("div");return b.style.display="none",b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id),b}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],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${f} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let m=(b,w,T)=>{let L=Tt({icon:b,label:w,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",T),L};return o&&g.appendChild(m("copy","Copy message","copy")),s&&g.appendChild(m("volume-2","Read aloud","read-aloud")),r&&g.appendChild(m("thumbs-up","Upvote","upvote")),a&&g.appendChild(m("thumbs-down","Downvote","downvote")),g},ba=(e,t,n,o,r,a)=>{let s=n??{},l=s.layout??"bubble",p=s.avatar,d=s.timestamp,c=p?.show??!1,f=d?.show??!1,g=p?.position??"left",m=d?.position??"below",b=ks(e.role,l),w=v("div",b.join(" "));w.id=`bubble-${e.id}`,w.setAttribute("data-message-id",e.id),w.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(w.style.backgroundColor="transparent",w.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Fw(e),L=e.content?.trim()??"",S=T.length>0&&L===Fi,C=vl(a?.widgetConfig?.features?.streamAnimation),M=a?.widgetConfig?.features?.streamAnimation?.plugins,P=e.role==="assistant"&&C.type!=="none"?ha(C.type,M):null,R=e.role==="assistant"&&P?.isAnimating?.(e)===!0,F=e.role==="assistant"&&P!==null&&(!!e.streaming||R);F&&P?.bubbleClass&&w.classList.add(P.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),e.streaming&&O.classList.add("persona-content-streaming"),F&&P&&(P.containerClass&&O.classList.add(P.containerClass),O.style.setProperty("--persona-stream-step",`${C.speed}ms`),O.style.setProperty("--persona-stream-duration",`${C.duration}ms`));let $=F?Cl(e.content??"",C.buffer,P,e,!!e.streaming):e.content??"",E=()=>{let oe=t({text:$,message:e,streaming:!!e.streaming,raw:e.rawContent});return F&&P?.wrap==="char"?As(oe,"char",e.id,{skipTags:P.skipTags}):F&&P?.wrap==="word"?As(oe,"word",e.id,{skipTags:P.skipTags}):oe},G=null;if(S?(G=document.createElement("div"),G.innerHTML=E(),G.style.display="none",O.appendChild(G)):e.contentSegments?.length?Vw(O,e.contentSegments,oe=>t({text:oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):O.innerHTML=E(),F&&P?.useCaret&&!S&&L){let oe=wl(),me=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),Se=me[me.length-1];if(Se?.parentNode)Se.parentNode.insertBefore(oe,Se.nextSibling);else{let Ce=O.lastElementChild;Ce?Ce.appendChild(oe):O.appendChild(oe)}}if(f&&m==="inline"&&e.createdAt){let oe=cy(e,d,"span");oe.classList.add("persona-timestamp-inline");let me=O.lastElementChild;me?me.appendChild(oe):O.appendChild(oe)}if(T.length>0){let oe=zw(T,!S&&!!L,()=>{S&&G&&(G.style.display="")});oe?w.appendChild(oe):S&&G&&(G.style.display="")}let Q=Ow(e);if(Q.length>0){let oe=$w(Q);oe&&w.appendChild(oe)}let Z=Nw(e);if(Z.length>0){let oe=jw(Z);oe&&w.appendChild(oe)}let J=_w(e);if(J.length>0){let oe=Gw(J);oe&&w.appendChild(oe)}let fe=e.contentSegments?.length?null:Uw(e.contextMentions);if(fe&&w.appendChild(fe),w.appendChild(O),f&&m==="below"&&e.createdAt){let oe=cy(e,d);oe.classList.add("persona-mt-1"),w.appendChild(oe)}let ne=e.role==="assistant"?Hw(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let oe=!!($&&$.trim()),me=C.placeholder==="skeleton",Se=me&&C.buffer==="line"&&oe;if(oe)Se&&w.appendChild(Ss());else if(me)w.appendChild(Ss());else{let Ce=Uu("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ce&&w.appendChild(Ce)}}if(ne&&e.stopReason&&!e.streaming&&(L||(O.style.display="none"),w.appendChild(Bw(e.stopReason,ne))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let oe=qu(e,o,r);w.appendChild(oe)}if(!c||e.role==="system")return w;let ie=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=Kw(p,e.role);return g==="right"||g==="left"&&e.role==="user"?ie.append(w,ue):ie.append(ue,w),ie},py=(e,t,n,o,r,a)=>{let s=n??{};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}):ba(e,t,n,o,r,a)};var Xw=40,Jw=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ae(t.name,Xw);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(ke("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(ke("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},uy=(e,t,n={})=>{let o=ke("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle");return{host:ke("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,a,t),iconHolder:o,title:r,subtitle:a,starterSuggestions:t}},xa=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},Bl=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",Jw(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Qw="data-persona-welcome-plugin",fy="data-persona-welcome-overlay",Hl="persona-welcome-overlay-active",Vu=new WeakMap,my=(e,t,n)=>{n.setAttribute(Qw,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(fy,""),e.classList.contains(Hl)||(Vu.set(e,e.scrollTop),e.classList.add(Hl),e.scrollTop=0)},gy=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(fy),e.classList.contains(Hl)&&(e.classList.remove(Hl),e.scrollTop=Vu.get(e)??e.scrollTop,Vu.delete(e))},hy=()=>{let e=ke("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Dl=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ke("div",{className:ks("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(ke("div",{className:"persona-flex"},r)),e.hidden=!1},Yw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yy=(e,t)=>{if(Yw()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,t(n))};return n.finished.then(r).catch(r),n};var Zw="Hello \u{1F44B}",eA="I can answer questions and help you get things done here.",by=new WeakSet,Mn=(e,t)=>!!e&&e[t]!==void 0,tA=(e,t)=>{!e||e.debug!==!0||!t.length||by.has(e)||(by.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},mo=e=>{let t=e?.welcome,n=e?.copy,o=Mn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Mn(t,"dismiss")?t.dismiss:"never",a=[];return Mn(t,"title")&&Mn(n,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Mn(t,"subtitle")&&Mn(n,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Mn(t,"variant")&&Mn(n,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Mn(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Mn(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),tA(e,a),{title:Mn(t,"title")?t.title:n?.welcomeTitle??Zw,subtitle:Mn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??eA,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},Xo=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var xy=e=>{let t=e?.launcher?.enabled??!0,n=St(e);if(Ko(e)){let c=e?.launcher?.composerBar??{},f=v("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Ut);let g=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",f.appendChild(g);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=c.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:f,panel:g,pillRoot:m}}if(n){let c=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),f=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(f),{wrapper:c,panel:f}}if(!t){let c=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=v("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,f.style.width="100%",c.appendChild(f),{wrapper:c,panel:f}}let r=e?.launcher??{},a=r.position&&gn[r.position]?gn[r.position]:gn["bottom-right"],s=v("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Ut);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??mn;return l.style.width=d,l.style.maxWidth=d,s.appendChild(l),{wrapper:s,panel:l}},zu=e=>{let t=ke("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Iu(e)}});return t.hidden=!0,t},vy=(e,t)=>{let n=zu("starter"),o=uy(e,n,{flatShadow:St(e)}),r=mo(e);Bl(o,r),xa(t,o.host,Xo(r,e?.initialMessages));let a=hy();return Dl(a,r.message,e),{welcome:o,greetingHost:a}},nA=(e,t)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Sl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,s=null,l=null;if(a){let R=Ml(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=R.button,l=R.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=ke("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=ke("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{welcome:c,greetingHost:f}=vy(e,d),{host:g,title:m,subtitle:b}=c,w=c.starterSuggestions,T=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),L=zu("followUp"),A=qo(e,!0);A&&(T.style.maxWidth=A,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),d.append(g,f,T,L);let S=ke("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"}}),C=Wl({config:e}),{root:M,textNode:P}=sy();return n.append(p,r,d,S),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:T,starterSuggestions:w,transcriptSuggestions:L,composerOverlay:S,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:g,welcomeIconHolder:c.iconHolder,greetingHost:f,introTitle:m,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:p,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode,peekBanner:M,peekTextNode:P}},Cy=(e,t=!0)=>{if(Ko(e))return nA(e,t);let n=ke("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=o?ya(e,o,{showClose:t}):fo({config:e,showClose:t}),s=ke("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{welcome:l,greetingHost:p}=vy(e,s),{host:d,title:c,subtitle:f}=l,g=l.starterSuggestions,m=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=zu("followUp"),w=qo(e,!1);w&&(m.style.maxWidth=w,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),s.append(d,p,m,b);let T=Lr({config:e}),L=e?.layout?.showFooter!==!1;r?kr(n,a,e):(a.header.style.display="none",kr(n,a,e)),n.append(s);let A=ke("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 L||(T.footer.style.display="none"),n.append(T.footer),n.append(A),{container:n,body:s,messagesWrapper:m,starterSuggestions:g,transcriptSuggestions:b,composerOverlay:A,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:p,introTitle:c,introSubtitle:f,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:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var $u=(e,t)=>{let n=v("button");n.type="button",n.innerHTML=`
|
|
29
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function as(e){let t=Xx(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Cr(e){switch(as(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Xx(e.path);return t?t.toUpperCase():"File"}}}function Yc(e){let t=e.markdown??"";return e.file?{filename:bo(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Xc(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}function Jc(e){let t=new Blob([e.content],{type:e.mime}),n=URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=e.filename,o.click(),URL.revokeObjectURL(n)}var Bm="http://www.w3.org/2000/svg";function Yx(e){let t=document.createElementNS(Bm,"svg");t.setAttribute("class",jn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Bm,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Bm,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var wr=(e,t,n)=>{let o=n;for(let r of t){let s=S("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Jx(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),wr(e,t,0)}var Dm="persona-artifact-status-label",Qx="persona-artifact-status-detail",Zx="data-artifact-status-label",Om=new Map,ev=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function la(e){e&&Om.delete(e)}function vM(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Cr(t):e.artifactType==="component"?"Component":"Document"}function ca(e,t,n){let o=vM(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=e.id,l=Om.get(i);e.status!=="complete"&&l===void 0&&(l=ev(),Om.set(i,l));let d=l===void 0?0:Math.max(0,ev()-l),u=e.artifactType==="component",p=!u&&typeof e.markdown=="string"?e.markdown:"",f=u?0:p.length,y=u||p===""?0:p.split(`
|
|
30
|
+
`).length,g=e.artifactType==="markdown"?e.file:void 0,b={artifactId:i,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:f,lines:y,elapsedMs:d,content:()=>u?"":p,surface:n};try{let v=s(b);return typeof v=="string"?{label:v}:v&&typeof v=="object"&&typeof v.label=="string"?{label:v.label,detail:typeof v.detail=="string"?v.detail:void 0}:{label:r}}catch{return{label:r}}}function CM(e){e.className=Dm,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 is(e,t,n){let o=e.querySelector(`:scope > .${Dm}`);o||(o=S("span",Dm),e.appendChild(o)),o.getAttribute(Zx)!==t.label&&(CM(o),Jx(o,t.label,n),o.setAttribute(Zx,t.label));let r=e.querySelector(`:scope > .${Qx}`),s=t.detail;s?(r||(r=S("span",Qx),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var wM={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"},SM=15e4,Qc={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 AM(e,t){let n=(e||"").trim().toLowerCase();if(n&&Qc[n])return Qc[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Qc[r])return Qc[r]}}return null}function Zc(e,t){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:e.slice(r,i)})};for(;o<e.length;){let i=!1;for(let l of t){l.re.lastIndex=o;let d=l.re.exec(e);if(d&&d.index===o&&d[0].length>0){s(o);let u=l.map?l.map(d[0]):l.type;n.push({type:u,value:d[0]}),o+=d[0].length,r=o,i=!0;break}}i||(o+=1)}return s(e.length),n}var MM=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"]),TM=[{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=>MM.has(e)?"keyword":"plain"}];function tv(e){return Zc(e,TM)}var EM=[{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 kM(e){let t=Zc(e,EM);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var PM=[{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 nv(e){let t=Zc(e,PM),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<t.length&&t[i].value.trim()==="";)i+=1;let l=t[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var LM=[{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 HM(e){let t=[],n=(s,i)=>{i&&t.push({type:s,value:i})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let i=e.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let i=e.indexOf(">",r),l=i===-1?o:i+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let i=e.indexOf(">",r),l=i===-1?o:i+1,d=e.slice(r,l);for(let p of Zc(d,LM))t.push(p);r=l;let u=/^<\s*(script|style)\b/i.exec(d);if(u&&!/\/>\s*$/.test(d)){let p=u[1].toLowerCase(),y=new RegExp("</\\s*"+p+"\\s*>","i").exec(e.slice(r)),g=y?r+y.index:o,b=e.slice(r,g),v=p==="script"?tv(b):nv(b);for(let E of v)t.push(E);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let i=s===-1?o:s;n("plain",e.slice(r,i)),r=i}}return t}function RM(e,t){switch(t){case"html":return HM(e);case"css":return nv(e);case"js":return tv(e);case"json":return kM(e)}}function IM(e){let t=Rb(),n=S("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=wM[r];if(i){let l=S("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
|
|
31
|
+
`);for(let i=0;i<s.length;i+=1)i>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
32
|
+
`)),n=S("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function ov(e,t,n){let o=e.length<=SM?AM(t,n):null,r=o?RM(e,o):[{type:"plain",value:e}];return IM(r)}function ls(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=S("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(ra)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of t){if(b.dividerBefore){let H=document.createElement("hr");l.appendChild(H)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",b.id),b.destructive&&v.setAttribute("data-destructive",""),b.icon){let H=ce(b.icon,16,"currentColor",1.5);H&&v.appendChild(H)}let E=document.createElement("span");E.textContent=b.label,v.appendChild(E),v.addEventListener("click",H=>{H.stopPropagation(),f(),n(b.id)}),l.appendChild(v)}let d=null;function u(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function p(){let b=l.classList.contains("persona-hidden");u(),l.classList.remove("persona-hidden"),b&&i?.(!0),requestAnimationFrame(()=>{let v=E=>{!l.contains(E.target)&&!o.contains(E.target)&&f()};document.addEventListener("click",v,!0),d=()=>document.removeEventListener("click",v,!0)})}function f(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,b&&i?.(!1)}function y(){l.classList.contains("persona-hidden")?p():f()}function g(){f(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:f,toggle:y,destroy:g}}function Tt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=e,d=S("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let u=ce(t,o??16,"currentColor",r??2);if(u&&d.appendChild(u),i&&d.addEventListener("click",i),l)for(let[p,f]of Object.entries(l))d.setAttribute(p,f);return d}function Vo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:d}=e,u="persona-label-btn";o!=="default"&&(u+=" persona-label-btn--"+o),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=S("button",u);if(p.type="button",p.setAttribute("aria-label",n),t){let y=ce(t,s??14,"currentColor",2);y&&p.appendChild(y)}let f=S("span");if(f.textContent=n,p.appendChild(f),l&&p.addEventListener("click",l),d)for(let[y,g]of Object.entries(d))p.setAttribute(y,g);return p}function da(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=S("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function d(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let f;p.icon?f=Tt({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,d(),o(p.id)}}):(f=S("button","persona-icon-btn"+(p.className?" "+p.className:"")),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{i=p.id,d(),o(p.id)})),f.setAttribute("aria-pressed",p.id===i?"true":"false"),l.push({id:p.id,btn:f}),s.appendChild(f)}function u(p){i=p,d()}return{element:s,setSelected:u}}function ed(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:d="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:f,className:y,primaryClassName:g,chevronClassName:b}=e,v=S("div","persona-split-btn"+(y?" "+y:"")),E={label:t,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},H=r&&n?Tt({...E,icon:n,size:o??14}):Vo({...E,icon:n,iconSize:o??14}),k=Tt({icon:"chevron-down",label:p,size:f??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});v.append(H,k);let M=null,x=()=>{if(M)return M;let w=(typeof u=="function"?u():u)??void 0;return M=ls({items:s,onSelect:i,anchor:v,position:d,portal:w,onOpenChange:L=>{k.setAttribute("aria-expanded",L?"true":"false")}}),w||v.appendChild(M.element),M};return v.isConnected?x():requestAnimationFrame(()=>{M||x()}),k.addEventListener("click",w=>{w.stopPropagation(),x().toggle()}),{element:v,primaryButton:H,chevronButton:k,openMenu:()=>x().show(),closeMenu:()=>M?.hide(),toggleMenu:()=>x().toggle(),destroy:()=>{M?.destroy(),v.remove()}}}function td(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:d}=e,u=S("div","persona-combo-btn"+(l?" "+l:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=S("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let f=ce(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",u.appendChild(f)),d&&(u.style.borderRadius=d.borderRadius??"10px",u.style.padding=d.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=d.background??"",u.style.borderColor=d.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let y=ls({items:o,onSelect:b=>{u.setAttribute("aria-expanded","false"),r(b)},anchor:u,position:s,portal:i});i||u.appendChild(y.element);let g=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",b=>{if(b.stopPropagation(),g())return;let v=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",v?"false":"true"),y.toggle()}),u.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u.click())}),{element:u,setLabel:b=>{p.textContent=b,u.setAttribute("aria-label",b)},open:()=>{u.setAttribute("aria-expanded","true"),y.show()},close:()=>{u.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let b=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",b?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),u.remove()}}}var nd="persona-artifact-custom-action-btn";function pa(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+nd+(n?" persona-artifact-doc-copy-btn":"");o=S("button",r)}else{let r="persona-icon-btn "+nd+(n?" persona-artifact-doc-icon-btn":"");o=S("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=S("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Vo({icon:e.icon,label:e.label,className:nd+(n?" persona-artifact-doc-copy-btn":"")}):o=Tt({icon:e.icon,label:e.label,className:nd+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ri(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 rv(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?bo(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",i=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",d=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,u=n?Cr(n):l==="component"?"Component":"Document",p=document.createElement("div");p.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",p.tabIndex=0,p.setAttribute("role","button"),p.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&p.setAttribute("data-open-artifact",s);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.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 y=document.createElement("div");y.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=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let v=t?.config?.features?.artifacts,E={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},H=ca(E,v,"card");is(b,H,v)}else s&&la(s),b.textContent=u;if(y.append(g,b),p.append(f,y),i==="complete"){let v=t?.config?.features?.artifacts?.cardActions;if(v&&v.length>0){let H={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let k of v)try{if(k.visible===void 0||k.visible(H)){let M=pa(k);M.setAttribute("data-artifact-custom-action",k.id),M.className=`${M.className} persona-flex-shrink-0`,p.append(M)}}catch{}}let E=Vo({label:"Download",className:"persona-flex-shrink-0"});E.title=`Download ${r}`,E.setAttribute("data-download-artifact",s),p.append(E)}return p}var od=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>rv(e,t)});if(l)return l}return rv(e,t)};var Sr=new WeakMap;function Fm(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Sr.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function cv(e){return Sr.has(e)}function WM(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let i=e.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function sv(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?bo(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Cr(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function BM(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 av=180,DM=240,OM=.8,FM=300,NM=500,_M="cubic-bezier(0.2, 0, 0, 1)",iv=240,UM=.35;function qM(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let i=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:av,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let H of i)H.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let d=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!d||Math.abs(d-t)<1){l(),r();return}let u=Math.abs(t-d),p=Math.round(Math.min(NM,Math.max(FM,DM+u*OM))),f=Math.round(p*UM),y=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=y?y.animate([{opacity:0},{opacity:1}],{duration:iv,delay:f,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${d}px`}],{duration:p,easing:_M});e.style.height=`${d}px`;let v=!1,E=()=>{v||(v=!0,l(),r())};Promise.allSettled([b.finished,g?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(p,f+iv)+120)},av)}function VM(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Ii="--persona-artifact-inline-body-height";function zM(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,i=t?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:t?.followOutput!==!1,u,p,f=t?.fadeMask;f===!0?(u=!0,p=!0):f===!1?(u=!1,p=!1):f&&typeof f=="object"?(u=f.top===!0,p=f.bottom===!0):l==="clip"?(u=!1,p=!0):(u=!0,p=!0);let y=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:l,fadeTop:u,fadeBottom:p,transition:y,completeDisplay:g}}function lv(e,t){let n=WM(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=VM(o),d=o?.inlineActions??[],u=zM(o),p=u.completeDisplay==="card",f=null,y=n,g=S("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let b=I=>od(BM(I),t),v=null,E=I=>{v?.destroy(),v=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Ii),g.replaceChildren(b(I)),Sr.set(g,Z=>{g.replaceChildren(b(Z))})};if(p&&n.status==="complete")return E(n),g;let H=rd(n,{config:t.config,bodyLayout:u,resolveViewMode:()=>f??u.viewMode});v=H;let k=S("div","persona-artifact-inline-body");k.appendChild(H.el);let M=I=>{let Z=I.status!=="complete",pe=Z?u.streamingHeight:u.completeHeight,Ee=typeof pe=="number";Ee?g.style.setProperty(Ii,`${pe}px`):g.style.removeProperty(Ii);let Ce=!!H.el.querySelector(".persona-code-pre"),we=!!H.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");k.classList.toggle("persona-artifact-content-flush",Ce),k.classList.toggle("persona-artifact-inline-body--sized",Ee&&we),k.classList.toggle("persona-artifact-inline-body--cap",!Z&&!we&&typeof u.completeHeight=="number")},x=n.status,w=(I,Z)=>{x!=="complete"&&I.status==="complete"?(typeof u.completeHeight=="number"?g.style.setProperty(Ii,`${u.completeHeight}px`):g.style.removeProperty(Ii),pv(k,Z?.suppressTransition?"none":u.transition,I.id,()=>{H.update(I),M(I)})):H.update(I),M(I),x=I.status};M(n);let L=u.overflow==="clip"&&i&&!!n.id;if(L&&(k.setAttribute("data-expand-artifact-inline",n.id),k.setAttribute("role","button"),k.setAttribute("tabindex","0"),k.classList.add("persona-cursor-pointer"),k.setAttribute("aria-label",`Open ${sv(n).title} in panel`)),!r)return g.appendChild(k),Sr.set(g,w),g;let P=S("div","persona-artifact-inline-chrome");P.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let D=S("div","persona-artifact-inline-chrome-lead"),q=S("span","persona-flex persona-items-center persona-flex-shrink-0"),$=ce("file-text",16,"currentColor",2);$&&q.appendChild($);let N=S("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),X=S("span","persona-artifact-inline-type");D.append(q,N,X);let de=S("div","persona-artifact-inline-chrome-actions"),me=S("span","persona-flex persona-items-center persona-gap-1"),xe=()=>f??u.viewMode,ye=l?da({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:xe(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:I=>{let Z=I==="source"?"source":"rendered";Z!==xe()&&(f=Z,H.update(y),M(y))}}):null,ne=s?Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ne&&n.id&&ne.setAttribute("data-copy-artifact",n.id);let ie=i?Tt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ie&&n.id&&ie.setAttribute("data-expand-artifact-inline",n.id),de.appendChild(me),ye&&de.appendChild(ye.element),ne&&de.appendChild(ne),ie&&de.appendChild(ie),P.append(D,de),g.append(P,k);let le=I=>{let{title:Z,typeLabel:pe}=sv(I);N.textContent=Z,N.title=Z,L&&k.setAttribute("aria-label",`Open ${Z} in panel`);let Ee=I.status!=="complete";if(Ee){X.classList.contains("persona-artifact-inline-status")||(X.className="persona-artifact-inline-status",X.removeAttribute("data-preserve-animation"),X.replaceChildren());let Ce=ca(I,o,"inline-chrome");is(X,Ce,o)}else la(I.id),X.className="persona-artifact-inline-type",X.removeAttribute("data-preserve-animation"),X.replaceChildren(),X.textContent=pe;if(ne&&ne.classList.toggle("persona-hidden",Ee),ye){let Ce=I.artifactType==="markdown"?I.file:void 0,we=!1;if(!Ee&&Ce&&u.viewMode!=="source"){let Pe=as(Ce);Pe==="markdown"?we=!0:(Pe==="html"||Pe==="svg")&&(we=o?.filePreview?.enabled!==!1)}ye.element.classList.toggle("persona-hidden",!we),ye.setSelected(xe())}if(me.replaceChildren(),!Ee&&d.length>0){let Ce=Ri(I);if(Ce)for(let we of d)try{if(we.visible===void 0||we.visible(Ce)){let Pe=pa(we,{documentChrome:!0});Pe.setAttribute("data-artifact-custom-action",we.id),Pe.classList.add("persona-flex-shrink-0"),me.appendChild(Pe)}}catch{}}};return le(n),Sr.set(g,(I,Z)=>{if(p&&x!=="complete"&&I.status==="complete"){let pe=g.isConnected?g.getBoundingClientRect().height:0;x="complete";let Ee=I,Ce=!1,we=Pe=>{Ee=Pe,Ce=!0};Sr.set(g,we),qM(g,pe,{swap:()=>{E(Ee),Ce=!1,Sr.set(g,we)},onSettled:()=>{Ce?E(Ee):Sr.set(g,Pe=>{g.replaceChildren(b(Pe))})}});return}(I.status!=="complete"||I.id!==y.id)&&(f=null),y=I,w(I,Z),le(I)}),g}var dv=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>lv(e,t)});if(l)return l}return lv(e,t)};var Nm=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):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(([n,o])=>{this.register(n,o)})}},ro=new Nm;ro.register("PersonaArtifactCard",od,{bubbleChrome:!1});ro.register("PersonaArtifactInline",dv,{bubbleChrome:!1});function Wi(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Xc(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var _m=!1;function jM(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function pv(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||_m||s){o();return}_m=!0;let i=jM(n);e.style.setProperty("view-transition-name",i);let l=()=>{_m=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var $M="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",GM="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function KM(e){let t=S("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=S("div","persona-font-semibold persona-text-sm persona-mb-2");n.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(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function XM(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 YM=220;function JM(){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 QM(e){return`
|
|
33
|
+
<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 ZM(e,t,n){let o=S("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:e,config:t});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=S("div","persona-artifact-frame-loading-indicator");r.appendChild(Yx());let s=null;return n.label!==!1&&(s=S("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function eT(e,t,n,o,r,s){let i=null,l=0,d=!1,u=new Set,p=()=>{u.forEach(M=>clearTimeout(M)),u.clear()},f=(M,x)=>{let w=setTimeout(()=>{u.delete(w),M()},x);u.add(w)},y=()=>{i&&i.parentElement&&i.remove(),i=null},g=()=>{if(i||d)return;let M=ZM(r,s,o);i=M.el,e.appendChild(i),l=Date.now(),o.label!==!1&&f(M.revealLabel,o.labelDelayMs)},b=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),f(y,YM))},v=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",H):t.removeEventListener("load",k)},E=()=>{if(d||(d=!0,v(),p(),!i))return;let M=Math.max(0,o.minVisibleMs-(Date.now()-l));M>0?f(b,M):b()};function H(M){if(n===null)return;let x=M.data;!x||x.persona!=="artifact-preview-ready"||x.token!==n||M.source===t.contentWindow&&E()}function k(){let M=x=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>x()):setTimeout(x,0)};M(()=>M(()=>E()))}return f(g,o.delayMs),f(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",H):t.addEventListener("load",k),()=>{d=!0,p(),v(),y()}}function rd(e,t){let{config:n}=t,o=t.registry??ro,r=t.bodyLayout,s=n.markdown?Qr(n.markdown):null,i=Gs(n.sanitize),l=e,d=!1,u=ne=>{let ie=Fo()!==null;s&&!ie&&!d&&(d=!0,$s(()=>ye(l)));let le=s?s(ne):mo(ne);return s&&ie&&i?i(le):le},p=S("div","persona-artifact-preview-body"),f=null,y=null,g=null,b=()=>{g&&(g(),g=null),f=null,y=null},v=null,E=null,H=null,k=!1,M=()=>{v=null,E=null,H=null,k=!1},x=null,w=null,L=()=>{x=null,w=null},P=40,D=0,q=ne=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ne()):setTimeout(ne,0),$=ne=>ne.scrollHeight-ne.clientHeight-ne.scrollTop<=P,N=ne=>{if(!r)return;let ie=ne.scrollHeight-ne.clientHeight>1,le=ne.scrollHeight-ne.clientHeight-ne.scrollTop;ne.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ie&&ne.scrollTop>1),ne.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ie&&le>1)},X=ne=>{D||(D=q(()=>{D=0,ne.scrollTop=ne.scrollHeight,N(ne)}))},de=(ne,ie,le,I)=>{let Z=!!r,pe=le.id+"|"+(Z?"w":"p");if(!v||H!==pe||v.parentElement!==p){b(),L(),p.replaceChildren();let we=S("pre",$M+" persona-code-pre"),Pe=S("code","persona-code");if(we.appendChild(Pe),Z){let Re=S("div","persona-artifact-source-window");if(Re.appendChild(we),p.appendChild(Re),!(r?.overflow==="clip")&&typeof Re.addEventListener=="function"){let Je=()=>Re.scrollHeight-Re.clientHeight>1;Re.addEventListener("scroll",()=>{$(Re)&&(k=!1),N(Re)},{passive:!0}),Re.addEventListener("wheel",Be=>{Je()&&Be.deltaY<0&&(k=!0)},{passive:!0}),Re.addEventListener("touchmove",()=>{Je()&&(k=!0)},{passive:!0})}v=Re}else p.appendChild(we),v=we;E=Pe,H=pe}let Ee=Z?v:null;Ee&&(Ee.classList.toggle("persona-artifact-source-window--fixed",I),Ee.classList.toggle("persona-artifact-source-window--clip",I&&r?.overflow==="clip"));let Ce=Ee?$(Ee):!0;if(E.replaceChildren(ov(ne,ie?.language,ie?.path)),Ee){let we=le.status!=="complete";I&&we&&r?.followOutput&&!k&&Ce?X(Ee):we||(k=!1),N(Ee)}},me=ne=>{b(),M(),L(),p.replaceChildren();let ie=S("div",GM);ie.innerHTML=u(ne),p.appendChild(ie)},xe=ne=>{let ie=ne.id,le=n.features?.artifacts,I=ca(ne,le,"status-body");if(x&&w===ie&&x.parentElement===p){let Ee=x.querySelector(".persona-artifact-status-view-text");Ee&&is(Ee,I,le);return}b(),M(),p.replaceChildren();let Z=S("div","persona-artifact-status-view"),pe=S("div","persona-artifact-status-view-text");is(pe,I,le),Z.appendChild(pe),p.appendChild(Z),x=Z,w=ie},ye=ne=>{l=ne;let ie=t.resolveViewMode?.(ne)??r?.viewMode??"rendered",le=ne.artifactType==="markdown"?ne.file:void 0,I=ne.status!=="complete";I||la(ne.id);let Z=I?r?.streamingHeight:r?.completeHeight,pe=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&I){xe(ne);return}if(le){let Ce=Xc(ne.markdown??""),we=as(le),Pe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!I&&ie==="rendered"&&Pe&&(we==="html"||we==="svg")){let nt=ne.id+"\0"+Ce;if(f&&y===nt&&f.parentElement===p)return;M(),L(),b(),p.replaceChildren();let Je=n.features?.artifacts?.filePreview,Be=Je?.iframeSandbox??"allow-scripts";!Je?.dangerouslyAllowSameOrigin&&Be.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."),Be=Be.split(/\s+/).filter(Me=>Me&&Me!=="allow-same-origin").join(" "));let ot=XM(Je?.loading),vt=S("div","persona-artifact-frame"),yt=S("iframe","persona-artifact-iframe");yt.setAttribute("sandbox",Be),yt.setAttribute("data-artifact-id",ne.id);let Dn=null;ot.enabled&&ot.injectReadySignal?(Dn=JM(),yt.srcdoc=Ce+QM(Dn)):yt.srcdoc=Ce,vt.appendChild(yt),p.appendChild(vt),ot.enabled&&(g=eT(vt,yt,Dn,ot,ne.id,n)),f=vt,y=nt;return}if(b(),!I&&we==="markdown"&&ie==="rendered"){me(Ce);return}de(Ce,{language:le.language,path:le.path},ne,pe);return}if(ne.artifactType==="markdown"){if(ie==="source"){b(),de(ne.markdown??"",void 0,ne,pe);return}me(ne.markdown??"");return}b(),M(),L(),p.replaceChildren();let Ee=ne.component?o.get(ne.component):void 0;if(Ee){let we={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Pe=Ee(ne.props??{},we);if(Pe){p.appendChild(Pe);return}}catch{}}p.appendChild(KM(ne))};return ye(e),{el:p,update(ne){ye(ne)},destroy(){b()}}}var uv=(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:y=>y.getAttribute("im-preserve")==="true",shouldReAppend:y=>y.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function n(y,g,b={}){y=p(y);let v=f(g),E=u(y,v,b),H=r(E,()=>l(E,y,v,k=>k.morphStyle==="innerHTML"?(s(k,y,v),Array.from(y.childNodes)):o(k,y,v)));return E.pantry.remove(),H}function o(y,g,b){let v=f(g);return s(y,v,b,g,g.nextSibling),Array.from(v.childNodes)}function r(y,g){if(!y.config.restoreFocus)return g();let b=document.activeElement;if(!(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement))return g();let{id:v,selectionStart:E,selectionEnd:H}=b,k=g();return v&&v!==document.activeElement?.getAttribute("id")&&(b=y.target.querySelector(`[id="${v}"]`),b?.focus()),b&&!b.selectionEnd&&H&&b.setSelectionRange(E,H),k}let s=(function(){function y(x,w,L,P=null,D=null){w instanceof HTMLTemplateElement&&L instanceof HTMLTemplateElement&&(w=w.content,L=L.content),P||(P=w.firstChild);for(let q of L.childNodes){if(P&&P!=D){let N=b(x,q,P,D);if(N){N!==P&&E(x,P,N),i(N,q,x),P=N.nextSibling;continue}}if(q instanceof Element){let N=q.getAttribute("id");if(x.persistentIds.has(N)){let X=H(w,N,P,x);i(X,q,x),P=X.nextSibling;continue}}let $=g(w,q,P,x);$&&(P=$.nextSibling)}for(;P&&P!=D;){let q=P;P=P.nextSibling,v(x,q)}}function g(x,w,L,P){if(P.callbacks.beforeNodeAdded(w)===!1)return null;if(P.idMap.has(w)){let D=document.createElement(w.tagName);return x.insertBefore(D,L),i(D,w,P),P.callbacks.afterNodeAdded(D),D}else{let D=document.importNode(w,!0);return x.insertBefore(D,L),P.callbacks.afterNodeAdded(D),D}}let b=(function(){function x(P,D,q,$){let N=null,X=D.nextSibling,de=0,me=q;for(;me&&me!=$;){if(L(me,D)){if(w(P,me,D))return me;N===null&&(P.idMap.has(me)||(N=me))}if(N===null&&X&&L(me,X)&&(de++,X=X.nextSibling,de>=2&&(N=void 0)),P.activeElementAndParents.includes(me))break;me=me.nextSibling}return N||null}function w(P,D,q){let $=P.idMap.get(D),N=P.idMap.get(q);if(!N||!$)return!1;for(let X of $)if(N.has(X))return!0;return!1}function L(P,D){let q=P,$=D;return q.nodeType===$.nodeType&&q.tagName===$.tagName&&(!q.getAttribute?.("id")||q.getAttribute?.("id")===$.getAttribute?.("id"))}return x})();function v(x,w){if(x.idMap.has(w))M(x.pantry,w,null);else{if(x.callbacks.beforeNodeRemoved(w)===!1)return;w.parentNode?.removeChild(w),x.callbacks.afterNodeRemoved(w)}}function E(x,w,L){let P=w;for(;P&&P!==L;){let D=P;P=P.nextSibling,v(x,D)}return P}function H(x,w,L,P){let D=P.target.getAttribute?.("id")===w&&P.target||P.target.querySelector(`[id="${w}"]`)||P.pantry.querySelector(`[id="${w}"]`);return k(D,P),M(x,D,L),D}function k(x,w){let L=x.getAttribute("id");for(;x=x.parentNode;){let P=w.idMap.get(x);P&&(P.delete(L),P.size||w.idMap.delete(x))}}function M(x,w,L){if(x.moveBefore)try{x.moveBefore(w,L)}catch{x.insertBefore(w,L)}else x.insertBefore(w,L)}return y})(),i=(function(){function y(k,M,x){return x.ignoreActive&&k===document.activeElement?null:(x.callbacks.beforeNodeMorphed(k,M)===!1||(k instanceof HTMLHeadElement&&x.head.ignore||(k instanceof HTMLHeadElement&&x.head.style!=="morph"?d(k,M,x):(g(k,M,x),H(k,x)||s(x,k,M))),x.callbacks.afterNodeMorphed(k,M)),k)}function g(k,M,x){let w=M.nodeType;if(w===1){let L=k,P=M,D=L.attributes,q=P.attributes;for(let $ of q)E($.name,L,"update",x)||L.getAttribute($.name)!==$.value&&L.setAttribute($.name,$.value);for(let $=D.length-1;0<=$;$--){let N=D[$];if(N&&!P.hasAttribute(N.name)){if(E(N.name,L,"remove",x))continue;L.removeAttribute(N.name)}}H(L,x)||b(L,P,x)}(w===8||w===3)&&k.nodeValue!==M.nodeValue&&(k.nodeValue=M.nodeValue)}function b(k,M,x){if(k instanceof HTMLInputElement&&M instanceof HTMLInputElement&&M.type!=="file"){let w=M.value,L=k.value;v(k,M,"checked",x),v(k,M,"disabled",x),M.hasAttribute("value")?L!==w&&(E("value",k,"update",x)||(k.setAttribute("value",w),k.value=w)):E("value",k,"remove",x)||(k.value="",k.removeAttribute("value"))}else if(k instanceof HTMLOptionElement&&M instanceof HTMLOptionElement)v(k,M,"selected",x);else if(k instanceof HTMLTextAreaElement&&M instanceof HTMLTextAreaElement){let w=M.value,L=k.value;if(E("value",k,"update",x))return;w!==L&&(k.value=w),k.firstChild&&k.firstChild.nodeValue!==w&&(k.firstChild.nodeValue=w)}}function v(k,M,x,w){let L=M[x],P=k[x];if(L!==P){let D=E(x,k,"update",w);D||(k[x]=M[x]),L?D||k.setAttribute(x,""):E(x,k,"remove",w)||k.removeAttribute(x)}}function E(k,M,x,w){return k==="value"&&w.ignoreActiveValue&&M===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(k,M,x)===!1}function H(k,M){return!!M.ignoreActiveValue&&k===document.activeElement&&k!==document.body}return y})();function l(y,g,b,v){if(y.head.block){let E=g.querySelector("head"),H=b.querySelector("head");if(E&&H){let k=d(E,H,y);return Promise.all(k).then(()=>{let M=Object.assign(y,{head:{block:!1,ignore:!0}});return v(M)})}}return v(y)}function d(y,g,b){let v=[],E=[],H=[],k=[],M=new Map;for(let w of g.children)M.set(w.outerHTML,w);for(let w of y.children){let L=M.has(w.outerHTML),P=b.head.shouldReAppend(w),D=b.head.shouldPreserve(w);L||D?P?E.push(w):(M.delete(w.outerHTML),H.push(w)):b.head.style==="append"?P&&(E.push(w),k.push(w)):b.head.shouldRemove(w)!==!1&&E.push(w)}k.push(...M.values());let x=[];for(let w of k){let L=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(b.callbacks.beforeNodeAdded(L)!==!1){if("href"in L&&L.href||"src"in L&&L.src){let P,D=new Promise(function(q){P=q});L.addEventListener("load",function(){P()}),x.push(D)}y.appendChild(L),b.callbacks.afterNodeAdded(L),v.push(L)}}for(let w of E)b.callbacks.beforeNodeRemoved(w)!==!1&&(y.removeChild(w),b.callbacks.afterNodeRemoved(w));return b.head.afterHeadMorphed(y,{added:v,kept:H,removed:E}),x}let u=(function(){function y(x,w,L){let{persistentIds:P,idMap:D}=k(x,w),q=g(L),$=q.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:x,newContent:w,config:q,morphStyle:$,ignoreActive:q.ignoreActive,ignoreActiveValue:q.ignoreActiveValue,restoreFocus:q.restoreFocus,idMap:D,persistentIds:P,pantry:b(),activeElementAndParents:v(x),callbacks:q.callbacks,head:q.head}}function g(x){let w=Object.assign({},t);return Object.assign(w,x),w.callbacks=Object.assign({},t.callbacks,x.callbacks),w.head=Object.assign({},t.head,x.head),w}function b(){let x=document.createElement("div");return x.hidden=!0,document.body.insertAdjacentElement("afterend",x),x}function v(x){let w=[],L=document.activeElement;if(L?.tagName!=="BODY"&&x.contains(L))for(;L&&(w.push(L),L!==x);)L=L.parentElement;return w}function E(x){let w=Array.from(x.querySelectorAll("[id]"));return x.getAttribute?.("id")&&w.push(x),w}function H(x,w,L,P){for(let D of P){let q=D.getAttribute("id");if(w.has(q)){let $=D;for(;$;){let N=x.get($);if(N==null&&(N=new Set,x.set($,N)),N.add(q),$===L)break;$=$.parentElement}}}}function k(x,w){let L=E(x),P=E(w),D=M(L,P),q=new Map;H(q,D,x,L);let $=w.__idiomorphRoot||w;return H(q,D,$,P),{persistentIds:D,idMap:q}}function M(x,w){let L=new Set,P=new Map;for(let{id:q,tagName:$}of x)P.has(q)?L.add(q):P.set(q,$);let D=new Set;for(let{id:q,tagName:$}of w)D.has(q)?L.add(q):P.get(q)===$&&D.add(q);for(let q of L)D.delete(q);return D}return y})(),{normalizeElement:p,normalizeParent:f}=(function(){let y=new WeakSet;function g(H){return H instanceof Document?H.documentElement:H}function b(H){if(H==null)return document.createElement("div");if(typeof H=="string")return b(E(H));if(y.has(H))return H;if(H instanceof Node){if(H.parentNode)return new v(H);{let k=document.createElement("div");return k.append(H),k}}else{let k=document.createElement("div");for(let M of[...H])k.append(M);return k}}class v{constructor(k){this.originalNode=k,this.realParentNode=k.parentNode,this.previousSibling=k.previousSibling,this.nextSibling=k.nextSibling}get childNodes(){let k=[],M=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;M&&M!=this.nextSibling;)k.push(M),M=M.nextSibling;return k}querySelectorAll(k){return this.childNodes.reduce((M,x)=>{if(x instanceof Element){x.matches(k)&&M.push(x);let w=x.querySelectorAll(k);for(let L=0;L<w.length;L++)M.push(w[L])}return M},[])}insertBefore(k,M){return this.realParentNode.insertBefore(k,M)}moveBefore(k,M){return this.realParentNode.moveBefore(k,M)}get __idiomorphRoot(){return this.originalNode}}function E(H){let k=new DOMParser,M=H.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(M.match(/<\/html>/)||M.match(/<\/head>/)||M.match(/<\/body>/)){let x=k.parseFromString(H,"text/html");if(M.match(/<\/html>/))return y.add(x),x;{let w=x.firstChild;return w&&y.add(w),w}}else{let w=k.parseFromString("<body><template>"+H+"</template></body>","text/html").body.querySelector("template").content;return y.add(w),w}}return{normalizeElement:g,normalizeParent:b}})();return{morph:n,defaults:t}})();var sd=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;uv.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var fv=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Um={index:-1,draft:""};function mv(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function gv(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 hv(){return new Map}function yv(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function bv(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function xv(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function vv(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Cv(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function xo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function cs(e,t){return xo(e)-e.scrollTop<=t}function wv(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:u=!1}=e,p=n-o;return i||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Sv(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Av(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function qm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function Mv(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Bi={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},tT=["pre","code","a","script","style"],ad=e=>({type:e?.type??Bi.type,placeholder:e?.placeholder??Bi.placeholder,speed:e?.speed??Bi.speed,duration:e?.duration??Bi.duration,buffer:e?.buffer??Bi.buffer}),Ev=[{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"}],Di=new Map;for(let e of Ev)Di.set(e.name,e);var ds=e=>{Di.set(e.name,e)},jm=e=>{Ev.some(t=>t.name===e)||Di.delete(e)},$m=()=>Array.from(Di.keys()),ua=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Di.get(e)??null,id=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
34
|
+
`);return s<0?"":e.slice(0,s)}return e},nT=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},oT=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Vm=/\s/,rT=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},sT=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Vm.test(s[l])){let d=l;for(;d<s.length&&Vm.test(s[d]);)d+=1;i.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=l;for(;u<s.length&&!Vm.test(s[u]);)d.appendChild(nT(o,s[u],t,n.value)),n.value+=1,u+=1;i.appendChild(d),l=u}r.replaceChild(i,e)},aT=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?i.appendChild(o.createTextNode(d)):(i.appendChild(oT(o,d,t,n.value)),n.value+=1));r.replaceChild(i,e)},Oi=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??tT).map(f=>f.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=i.nextNode();for(;d;)rT(d,s)||l.push(d),d=i.nextNode();let u={value:o?.startIndex??0},p=t==="char"?sT:aT;for(let f of l)p(f,n,u);return r.innerHTML},ld=(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},Fi=(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 n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Tv=new WeakMap,iT=(e,t)=>{if(!e.styles)return;let n=Tv.get(t);if(n||(n=new Set,Tv.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},zm=new WeakMap,lT=(e,t)=>{if(!e.onAttach)return;let n=zm.get(t);if(n||(n=new Map,zm.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},kv=e=>{let t=zm.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},cd=(e,t)=>{iT(e,t),lT(e,t)};function Gm(e,t=Qt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Ni=0,Ar=null;function Km(e=document){if(Ni++,Ni===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ar={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Ni=Math.max(0,Ni-1),Ni===0&&Ar)){let n=e.body,o=e.defaultView??window;n.style.overflow=Ar.originalOverflow,n.style.position=Ar.originalPosition,n.style.top=Ar.originalTop,n.style.width=Ar.originalWidth,o.scrollTo(0,Ar.scrollY),Ar=null}}}var _i={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},ht=e=>(e?.launcher?.mountMode??"floating")==="docked",Mr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Sn=e=>{let t=e?.launcher?.dock;return{side:t?.side??_i.side,width:t?.width??_i.width,animate:t?.animate??_i.animate,reveal:t?.reveal??_i.reveal,maxHeight:t?.maxHeight??_i.maxHeight}};var Xm=e=>e==="followUp"?"follow-up":e,Ym=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},cT=e=>{switch(e){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'}},Pv=new WeakSet,dT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,pT=e=>{dT()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Jm=e=>{var k,M,x;let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:d,chipsConfig:u,session:p,getTextarea:f,eventTarget:y}=e,g=o==="followUp",b=t.behavior,v=()=>{if(p.isStreaming())return;let w={suggestion:{...t},surface:o,source:r,behavior:b},L=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:w,bubbles:!0,composed:!0,cancelable:!0}));if(g&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!L)return;for(let D of d)if(D.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let P=f();if(b==="fill"){P.value=t.prompt,P.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),P.focus();return}P.value="",p.sendMessage(t.prompt)},E=()=>{let w=S("button",`persona-suggestion persona-suggestion--${s}`);if(w.type="button",w.disabled=i,w.dataset.suggestionId=t.id,w.dataset.emphasis=t.emphasis,w.dataset.behavior=b,s==="chip"&&(u?.fontFamily&&(w.style.fontFamily=cT(u.fontFamily)),u?.fontWeight&&(w.style.fontWeight=u.fontWeight),u?.paddingX&&(w.style.paddingLeft=u.paddingX,w.style.paddingRight=u.paddingX),u?.paddingY&&(w.style.paddingTop=u.paddingY,w.style.paddingBottom=u.paddingY)),t.icon){let P=ce(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);P&&(P.classList.add("persona-suggestion__icon"),t.iconColor&&(P.style.color=t.iconColor),w.appendChild(P))}let L=S("span","persona-suggestion__copy");if(L.appendChild(ue("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&L.appendChild(ue("span",{className:"persona-suggestion__description",text:t.description})),w.appendChild(L),s!=="chip"){let P=ce("arrow-right",16,"currentColor",1.8);P&&(P.classList.add("persona-suggestion__arrow"),w.appendChild(P))}return w.addEventListener("click",v),w},H=null;for(let w of d)if(w.renderSuggestion&&(H=w.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:E,select:v}),H))break;return H??(H=E()),(k=H.dataset).suggestionId||(k.suggestionId=t.id),(M=H.dataset).behavior||(M.behavior=b),(x=H.dataset).emphasis||(x.emphasis=t.emphasis),H instanceof HTMLButtonElement||H.setAttribute("aria-disabled",i?"true":"false"),H},Ui=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){s();return}let f=getComputedStyle(e).direction==="rtl",y=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),g=4,b=y<=g,v=y>=p-g,E=f?!v:!b,H=f?!b:!v;e.toggleAttribute("data-scroll-left",E),e.toggleAttribute("data-scroll-right",H)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,f,y,g,b,v)=>{e.replaceChildren(),t.length=0,n.length=0;let E=v?.source??"config",H=v?.surface??(E==="config"?"starter":"followUp"),k=H==="followUp",M=v?.variant??"chip",x=v?.behavior??"send",w=v?.overflow??"wrap",L=v?.config??{},P=v?.plugins??[],D=typeof v?.maxItems=="number"?Math.max(0,Math.floor(v.maxItems)):void 0,q=k?"followUps":"starters";!Pv.has(L)&&L.debug===!0&&M!=="chip"&&L.suggestions?.[q]?.overflow!==void 0&&(Pv.add(L),console.info(`[persona] suggestions.${q}.overflow applies to the "chip" variant only; the "${M}" variant manages its own stacking.`));let $=ye=>ye.map(Ym).filter(ne=>ne!==null).map(ne=>({...ne,behavior:ne.behavior??x})),N=$(p??[]);P.forEach(ye=>{ye.transformSuggestions&&(N=$(ye.transformSuggestions({suggestions:N.map(ne=>({...ne})),surface:H,source:E,config:L})))});let X=D===void 0?N:N.slice(0,D);if(!X.length){e.hidden=!0,o=null,s();return}if(!k&&(g??f.getMessages()).some(ne=>ne.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Xm(H),e.dataset.variant=M,e.dataset.overflow=w;let de=document.createDocumentFragment(),me=f.isStreaming();X.forEach((ye,ne)=>{let ie=Jm({item:ye,index:ne,surface:H,source:E,variant:M,streaming:me,config:L,plugins:P,chipsConfig:b,session:f,getTextarea:()=>y,eventTarget:e});de.appendChild(ie),n.push(ie),[...ie instanceof HTMLButtonElement?[ie]:[],...Array.from(ie.querySelectorAll("button"))].forEach(I=>{t.includes(I)||(I.disabled=me,t.push(I))})}),e.appendChild(de),i(),l();let xe=JSON.stringify({normalized:X,surface:H,variant:M,source:E});xe!==o&&(o=xe,pT(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:X.map(ye=>({...ye})),surface:H,source:E,variant:M},bubbles:!0,composed:!0})),k&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:X.map(ye=>ye.prompt)},bubbles:!0,composed:!0})))}}};var Wn={"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 uT="persona-header-control",fT="persona-header-control--glyph",mT="persona-header-control--sparse",gT=20,hT={x:[1.4,1.05]},Lv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",yT="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",dd=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=hT[t]??[1,1.5],l=!o;e.classList.toggle(fT,l),e.classList.toggle(mT,l&&s!==1);let d=parseFloat(o??"")||gT,u=ce(t,`${Math.round(d*s)}px`,"currentColor",i);u?(u.style.display="block",l||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},ps=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=Lv,size:l,iconSize:d,color:u,backgroundColor:p,borderWidth:f,borderColor:y,borderRadius:g,paddingX:b,paddingY:v,hidden:E,extraClassName:H,attrs:k}=e,M=S("div",i),x=!!(f||y),w=ue("button",{className:jn(uT,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!x&&"persona-border-none",!g&&"persona-rounded-full",H),attrs:{type:"button","aria-label":t,...k},style:{width:l,height:l,minWidth:l,minHeight:l,display:E?"none":void 0,color:u||mn.actionIconColor,backgroundColor:p,border:x?`${f||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:g,paddingLeft:b,paddingRight:b,paddingTop:v,paddingBottom:v}});return r?dd(w,r,{iconSize:d,iconText:s}):s&&(w.textContent=s),M.appendChild(w),Zt({anchor:w,trigger:M,text:()=>w.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:w,wrapper:M}},fa=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Lv,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=ps({ariaLabel:l,tooltip:d,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:u,wrapper:p}},ma=(e,t={})=>{let{wrapperClassName:n=yT,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",d=i.showTooltip??!0,{button:u,wrapper:p}=ps({ariaLabel:l,tooltip:d,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var mn={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))",minHeight:"var(--persona-header-min-height, auto)"},Qm={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},bT={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},zo=e=>{let{config:t,showClose:n=!0}=e,o=ue("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:{minHeight:mn.minHeight,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)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,u=ue("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let w=parseFloat(s)||24,L=ce(d,w*.6,"currentColor",1);L?u.replaceChildren(L):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let w=S("img");w.src=t.launcher.iconUrl,w.alt="",w.className="persona-rounded-xl persona-object-cover",w.style.height=s,w.style.width=s,u.replaceChildren(w)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=ue("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:mn.titleColor,...Qm}}),y=ue("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:mn.subtitleColor,...bT}});p.append(f,y),l?o.append(p):o.append(u,p);let g=r.clearChat??{},b=g.enabled??!0,v=g.placement??"inline",E=null,H=null;if(b){let L=ma(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=L.button,H=L.wrapper,v==="top-right"&&(H.style.right="48px"),v==="inline"&&o.appendChild(H)}let k=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:M,wrapper:x}=fa(t,{showClose:n,wrapperClassName:k});return i!=="top-right"&&o.appendChild(x),{header:o,iconHolder:u,headerTitle:f,headerSubtitle:y,closeButton:M,closeButtonWrapper:x,clearChatButton:E,clearChatButtonWrapper:H}},us=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Zm=e=>{let t=zo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function xT(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=ps({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Kc(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let i=Hi(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=ls({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var eg=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=S("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=mn.minHeight,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 d=r?.titleMenu,u,p;if(d){let x=td({label:i.title??"Chat Assistant",menuItems:d.menuItems,onSelect:w=>{let L=D=>{D===!1&&x.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:w}}))},P=d.onSelect(w);P instanceof Promise?P.then(L,()=>{}):L(P)},hover:d.hover,className:""});u=x.element,u.style.color=mn.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=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=mn.titleColor,Object.assign(p.style,Qm),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let w=r.onTitleClick;u.addEventListener("click",L=>{L.target.closest("button")||w()}),u.addEventListener("keydown",L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),w())})}let x=r?.titleRowHover;x&&(u.style.borderRadius=x.borderRadius??"10px",u.style.padding=x.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=x.background??"",u.style.borderColor=x.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}l.appendChild(u);let f="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:g}=fa(t,{showClose:n,wrapperClassName:f});o&&y.addEventListener("click",o);let b=S("div","persona-flex persona-items-center persona-gap-1");d||xT(b,r?.trailingActions,r?.onAction??s);let v=i.clearChat??{},E=null,H=null;if(v.enabled??!0){let x=v.placement??"inline",w=ma(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":f});E=w.button,H=w.wrapper,x==="top-right"?H.style.right="48px":b.appendChild(H)}b.appendChild(g),l.appendChild(b);let k=S("div");k.style.display="none";let M=S("span");return M.style.display="none",{header:l,iconHolder:k,headerTitle:p,headerSubtitle:M,closeButton:y,closeButtonWrapper:g,clearChatButton:E,clearChatButtonWrapper:H}},pd={default:Zm,minimal:eg},tg=e=>pd[e]??pd.default,ga=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=S("div");l.style.display="none";let d=S("span"),u=S("span"),p=S("button");p.style.display="none";let f=S("div");return f.style.display="none",{header:i,iconHolder:l,headerTitle:d,headerSubtitle:u,closeButton:p,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=tg(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ud=e=>{let t=S("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-text 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 n=3,o=20,r=()=>{let d=t.ownerDocument?.defaultView;if(!d?.getComputedStyle)return o;let u=d.getComputedStyle(t).lineHeight;if(!u||!u.trim().endsWith("px"))return o;let p=parseFloat(u);return Number.isFinite(p)&&p>0?p:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let i=()=>{let d=t.style.maxHeight;if(d!==s){let p=parseFloat(d);if(Number.isFinite(p)&&p>0)return p}let u=n*r();return s=`${u}px`,t.style.maxHeight=s,u},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,i());t.style.height=`${d}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:l}},fd=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,f=t.size??"40px",y=t.backgroundColor,g=t.textColor,b=S("div","persona-send-button-wrapper"),v=ue("button",{className:jn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!y&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),E=null,H=null;if(n){let x=parseFloat(t.iconSize??"")||Math.round((parseFloat(f)||24)*.5),w=t.iconStrokeWidth??2,L=g?.trim()||"currentColor";r?(E=ce(r,x,L,w),E?v.appendChild(E):v.textContent=o):v.textContent=o,H=ce(s,x,L,w)}else v.textContent=d;v.setAttribute("aria-label",i),b.appendChild(v),Zt({anchor:v,trigger:b,text:()=>v.getAttribute("aria-label")??"",enabled:p});let k="send";return{button:v,wrapper:b,setMode:x=>{if(x===k)return;k=x;let w=x==="stop"?l:i;if(v.setAttribute("aria-label",w),n){if(E&&H){let L=x==="stop"?H:E;v.replaceChildren(L)}}else v.textContent=x==="stop"?u:d}}},md=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let i=e?.sendButton?.size??"40px",l=t.iconName??"mic",d=t.iconSize??i,u=parseFloat(d)||24,p=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,y=S("div","persona-send-button-wrapper"),g=ue("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":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"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}}),v=ce(l,u,f||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",y.appendChild(g);let E=t.tooltipText??"Start voice recognition",H=t.showTooltip??!1;return Zt({anchor:g,trigger:y,text:()=>g.getAttribute("aria-label")??E,enabled:H}),{button:g,wrapper:y}},gd=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"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 r=S("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??qo).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",i=n,l=parseFloat(i)||40,d=Math.round(l*.6),u=S("div","persona-send-button-wrapper"),p=ue("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:i,height:i,minWidth:i,minHeight:i,fontSize:"18px",lineHeight:"1"}}),f=ce(s,d,"currentColor",1.5);f?p.appendChild(f):p.textContent="\u{1F4CE}",p.addEventListener("click",g=>{g.preventDefault(),r.click()}),u.appendChild(p);let y=t.buttonTooltipText??"Attach file";return Zt({anchor:p,trigger:u,text:()=>p.getAttribute("aria-label")??y}),{button:p,wrapper:u,input:r,previewsContainer:o}},hd=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let i=S("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=s,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=s;return o},yd=()=>ue("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var fs=e=>{let{config:t}=e,n=ue("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=yd(),r=ue("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:i}=ud(t);i();let l=fd(t),d=md(t),u=gd(t),p=hd(t);u&&(u.previewsContainer.style.gap="8px",r.append(u.previewsContainer,u.input)),r.append(s);let f=ue("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=S("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=S("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return u&&y.append(u.wrapper),d&&g.append(d.wrapper),g.append(l.wrapper),f.append(y,g),r.append(f),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&s.focus()}),n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:f,leftActions:y,rightActions:g,setSendButtonMode:l.setMode}};var Hv=()=>{let e=ue("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"),n=ce("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=S("span","persona-pill-peek__text"),r=S("span","persona-pill-peek__caret"),s=ce("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},bd=e=>{let{config:t}=e,n=ue("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=yd(),r=hd(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=ud(t);s.style.maxHeight="100px",i();let l=fd(t),d=md(t),u=gd(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=ue("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=S("div","persona-widget-composer__left-actions persona-pill-composer__left");u&&f.append(u.wrapper);let y=S("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&y.append(d.wrapper),y.append(l.wrapper),p.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&s.focus()}),u&&p.append(u.input),p.append(f,s,y),u&&n.append(u.previewsContainer),n.append(o,p,r);let g=p;return{footer:n,suggestions:o,composerForm:p,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:g,leftActions:f,rightActions:y,setSendButtonMode:l.setMode}};var vT=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}},CT=(e,t)=>{if(!e)return null;let n=vT(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},wT=(e,t)=>{let n=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},ST=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ng=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(":"))},og=320,Bv=320,AT=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),MT=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),TT=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ET=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),kT=e=>{if(!e||e.length===0)return null;let t=ue("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=ue("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=S("span","persona-mention-chip-icon"),s=ce(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(ue("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},PT=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ki(o.ref,{readonly:!0,render:t}))}return n},Rv="\uE000",Iv="\uE001",LT=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${Rv}${r}:${y}${Iv}`,i=t.map((y,g)=>y.kind==="text"?y.text:s(g)).join(""),l=n(i);if(!t.every((y,g)=>y.kind==="text"||l.includes(s(g)))){e.replaceChildren(PT(t,o));return}e.innerHTML=l;let u=new RegExp(`${Rv}${r}:(\\d+)${Iv}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let y=p.nextNode();y;y=p.nextNode())f.push(y);for(let y of f){let g=y;for(let b=u.exec(g.data);b;b=u.exec(g.data)){let v=t[Number(b[1])],E=g.splitText(b.index);E.data=E.data.slice(b[0].length),v?.kind==="mention"&&E.parentNode?.insertBefore(ki(v.ref,{readonly:!0,render:o}),E),g=E}}},HT=(e,t,n)=>{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 r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let u=S("img");u.alt=l.alt?.trim()||`Attached image ${d+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${og}px`,u.style.maxHeight=`${Bv}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),ST(l.image)?(u.src=l.image,o.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},RT=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 n=0;return e.forEach(o=>{if(!ng(o.audio))return;let r=S("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${og}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},IT=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 n=0;return e.forEach(o=>{if(!ng(o.video))return;let r=S("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${og}px`,r.style.maxHeight=`${Bv}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},WT=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 n=0;return e.forEach(o=>{if(!ng(o.data))return;let r=S("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ms=()=>{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 n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="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 r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},rg=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:ms};if(t){let r=t(o);if(r!==null)return r}return ms()},BT=(e,t)=>{let n=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 r=S("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Wv=(e,t,n="div")=>{let o=S(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},qi=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},sg=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,i=t.showReadAloud??!1;if(!o&&!r&&!s&&!i){let b=S("div");return b.style.display="none",b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id),b}let l=t.visibility??"hover",d=t.align??"right",u=t.layout??"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],y=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${f} ${l==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id);let g=(b,v,E)=>{let H=Tt({icon:b,label:v,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",E),H};return o&&y.appendChild(g("copy","Copy message","copy")),i&&y.appendChild(g("volume-2","Read aloud","read-aloud")),r&&y.appendChild(g("thumbs-up","Upvote","upvote")),s&&y.appendChild(g("thumbs-down","Downvote","downvote")),y},ha=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",d=i.avatar,u=i.timestamp,p=d?.show??!1,f=u?.show??!1,y=d?.position??"left",g=u?.position??"below",b=qi(e.role,l),v=S("div",b.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(v.style.backgroundColor="transparent",v.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=AT(e),H=e.content?.trim()??"",M=E.length>0&&H===Zs,x=ad(s?.widgetConfig?.features?.streamAnimation),w=s?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&x.type!=="none"?ua(x.type,w):null,P=e.role==="assistant"&&L?.isAnimating?.(e)===!0,D=e.role==="assistant"&&L!==null&&(!!e.streaming||P);D&&L?.bubbleClass&&v.classList.add(L.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),D&&L&&(L.containerClass&&q.classList.add(L.containerClass),q.style.setProperty("--persona-stream-step",`${x.speed}ms`),q.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let $=D?id(e.content??"",x.buffer,L,e,!!e.streaming):e.content??"",N=()=>{let Z=t({text:$,message:e,streaming:!!e.streaming,raw:e.rawContent});return D&&L?.wrap==="char"?Oi(Z,"char",e.id,{skipTags:L.skipTags}):D&&L?.wrap==="word"?Oi(Z,"word",e.id,{skipTags:L.skipTags}):Z},X=null;if(M?(X=document.createElement("div"),X.innerHTML=N(),X.style.display="none",q.appendChild(X)):e.contentSegments?.length?LT(q,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=N(),D&&L?.useCaret&&!M&&H){let Z=ld(),pe=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ee=pe[pe.length-1];if(Ee?.parentNode)Ee.parentNode.insertBefore(Z,Ee.nextSibling);else{let Ce=q.lastElementChild;Ce?Ce.appendChild(Z):q.appendChild(Z)}}if(f&&g==="inline"&&e.createdAt){let Z=Wv(e,u,"span");Z.classList.add("persona-timestamp-inline");let pe=q.lastElementChild;pe?pe.appendChild(Z):q.appendChild(Z)}if(E.length>0){let Z=HT(E,!M&&!!H,()=>{M&&X&&(X.style.display="")});Z?v.appendChild(Z):M&&X&&(X.style.display="")}let de=MT(e);if(de.length>0){let Z=RT(de);Z&&v.appendChild(Z)}let me=TT(e);if(me.length>0){let Z=IT(me);Z&&v.appendChild(Z)}let xe=ET(e);if(xe.length>0){let Z=WT(xe);Z&&v.appendChild(Z)}let ye=e.contentSegments?.length?null:kT(e.contextMentions);if(ye&&v.appendChild(ye),v.appendChild(q),f&&g==="below"&&e.createdAt){let Z=Wv(e,u);Z.classList.add("persona-mt-1"),v.appendChild(Z)}let ne=e.role==="assistant"?CT(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!($&&$.trim()),pe=x.placeholder==="skeleton",Ee=pe&&x.buffer==="line"&&Z;if(Z)Ee&&v.appendChild(Fi());else if(pe)v.appendChild(Fi());else{let Ce=rg("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ce&&v.appendChild(Ce)}}if(ne&&e.stopReason&&!e.streaming&&(H||(q.style.display="none"),v.appendChild(wT(e.stopReason,ne))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=sg(e,o,r);v.appendChild(Z)}if(!p||e.role==="system")return v;let le=S("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),I=BT(d,e.role);return y==="right"||y==="left"&&e.role==="user"?le.append(v,I):le.append(I,v),le},Dv=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ha(e,t,n,o,r,s)};var DT=40,OT=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ce(t.name,DT);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(ue("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(ue("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},Ov=(e,t,n={})=>{let o=ue("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=S("h2","persona-welcome-title"),s=S("p","persona-welcome-subtitle");return{host:ue("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,t),iconHolder:o,title:r,subtitle:s,starterSuggestions:t}},ya=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},vd=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",OT(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},FT="data-persona-welcome-plugin",Fv="data-persona-welcome-overlay",xd="persona-welcome-overlay-active",ag=new WeakMap,ig=(e,t,n)=>{n.setAttribute(FT,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Fv,""),e.classList.contains(xd)||(ag.set(e,e.scrollTop),e.classList.add(xd),e.scrollTop=0)},lg=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Fv),e.classList.contains(xd)&&(e.classList.remove(xd),e.scrollTop=ag.get(e)??e.scrollTop,ag.delete(e))},Nv=()=>{let e=ue("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Cd=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ue("div",{className:qi("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(ue("div",{className:"persona-flex"},r)),e.hidden=!1},NT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,_v=(e,t)=>{if(NT()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let v=e.previousElementSibling,E=e.nextElementSibling,k=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,v?n.top-v.getBoundingClientRect().bottom-r:n.top-k),i=Math.max(0,E?E.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),u=parseFloat(d.paddingTop)||0,p=parseFloat(d.paddingBottom)||0,f=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${s}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,g=()=>{y||(y=!0,e.style.overflow=l,t(f))};return f.finished.then(g).catch(g),f};var _T="Hello \u{1F44B}",UT="I can answer questions and help you get things done here.",Uv=new WeakSet,Kn=(e,t)=>!!e&&e[t]!==void 0,qT=(e,t)=>{!e||e.debug!==!0||!t.length||Uv.has(e)||(Uv.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},jo=e=>{let t=e?.welcome,n=e?.copy,o=Kn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Kn(t,"dismiss")?t.dismiss:"never",s=[];return Kn(t,"title")&&Kn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Kn(t,"subtitle")&&Kn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Kn(t,"variant")&&Kn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Kn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Kn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),qT(e,s),{title:Kn(t,"title")?t.title:n?.welcomeTitle??_T,subtitle:Kn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??UT,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},Tr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var qv="16px",cg="10px",dg="14px",Vv=e=>{let t=e?.launcher?.enabled??!0,n=ht(e);if(Mr(e)){let p=e?.launcher?.composerBar??{},f=S("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=p.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Qt);let y=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",f.appendChild(y);let g=S("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Qt),{wrapper:f,panel:y,pillRoot:g}}if(n){let p=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),f=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(f),{wrapper:p,panel:f}}if(!t){let p=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return p.style.width=y,f.style.width="100%",p.appendChild(f),{wrapper:p,panel:f}}let r=e?.launcher??{},s=r.position&&Wn[r.position]?Wn[r.position]:Wn["bottom-right"],i=S("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Qt);let l=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??In;return l.style.width=u,l.style.maxWidth=u,i.appendChild(l),{wrapper:i,panel:l}},pg=e=>{let t=ue("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Xm(e)}});return t.hidden=!0,t},zv=(e,t)=>{let n=pg("starter"),o=Ov(e,n,{flatShadow:ht(e)}),r=jo(e);vd(o,r),ya(t,o.host,Tr(r,e?.initialMessages));let s=Nv();return Cd(s,r.message,e),{welcome:o,greetingHost:s}},VT=(e,t)=>{let n=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=fa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:qv,iconSize:cg});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let P=ma(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:qv,iconSize:dg});i=P.button,l=P.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=ue("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=ue("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"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:f}=zv(e,u),{host:y,title:g,subtitle:b}=p,v=p.starterSuggestions,E=S("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),H=pg("followUp"),k=vr(e,!0);k&&(E.style.maxWidth=k,E.style.marginLeft="auto",E.style.marginRight="auto",E.style.width="100%"),u.append(y,f,E,H);let M=ue("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"}}),x=bd({config:e}),{root:w,textNode:L}=Hv();return n.append(d,r,u,M),l&&n.appendChild(l),{container:n,body:u,messagesWrapper:E,starterSuggestions:v,transcriptSuggestions:H,composerOverlay:M,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:y,welcomeIconHolder:p.iconHolder,greetingHost:f,introTitle:g,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:d,footer:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode,peekBanner:w,peekTextNode:L}},jv=(e,t=!0)=>{if(Mr(e))return VT(e,t);let n=ue("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?ga(e,o,{showClose:t}):zo({config:e,showClose:t}),i=ue("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=zv(e,i),{host:u,title:p,subtitle:f}=l,y=l.starterSuggestions,g=S("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=pg("followUp"),v=vr(e,!1);v&&(g.style.maxWidth=v,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),i.append(u,d,g,b);let E=fs({config:e}),H=e?.layout?.showFooter!==!1;r?us(n,s,e):(s.header.style.display="none",us(n,s,e)),n.append(i);let k=ue("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||(E.footer.style.display="none"),n.append(E.footer),n.append(k),{container:n,body:i,messagesWrapper:g,starterSuggestions:y,transcriptSuggestions:b,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,welcomeHost:u,welcomeIconHolder:l.iconHolder,greetingHost:d,introTitle:p,introSubtitle:f,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer: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}};var ug=(e,t)=>{let n=S("button");n.type="button",n.innerHTML=`
|
|
35
35
|
<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>
|
|
36
36
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
37
37
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
38
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-
|
|
39
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
38
|
+
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>
|
|
39
|
+
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
40
40
|
</span>
|
|
41
41
|
<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>
|
|
42
|
-
`,n.addEventListener("click",t);let o=
|
|
43
|
-
`):""},
|
|
44
|
-
`);let r=
|
|
45
|
-
`):""},Ku=(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)"},mA=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=fA(e,o?.previewMaxLines??3),s=n?zg(n):"";if(!n)return{summary:s,previewText:a,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=s;return r==="tool-name"?d=n.name?.trim()||s:r==="tool-preview"&&a&&(d=a),l&&p.activeTextTemplate?d=ld(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=ld(n,p.completeTextTemplate,d)),{summary:d,previewText:a,isActive:l}},ky=(e,t,n)=>{let o=Ca.has(e),r=n?.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",o?"true":"false");let d=a.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",f=ae(o?"chevron-up":"chevron-down",16,c,2);f?d.appendChild(f):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Xu=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","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.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.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))",!n)return r;let a=t?.features?.toolCallDisplay??{},s=a.expandable!==!1,l=s&&Ca.has(e.id),{summary:p,previewText:d,isActive:c}=mA(e,t),f=v("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",s&&(f.setAttribute("aria-expanded",l?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let g=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),w=()=>{let E=v("span","");return E.setAttribute("data-tool-elapsed",b),E.textContent=cs(n),E},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:a.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:cs(n),createElapsedElement:w});typeof T=="string"&&T.trim()?(m.textContent=T,g.appendChild(m)):T instanceof HTMLElement?g.appendChild(T):(m.textContent=p,g.appendChild(m));let L=a.loadingAnimation??"none",A=o.activeTextTemplate,S=o.completeTextTemplate,C=c?A:S,M=T instanceof HTMLElement,P=(E,G)=>{m.textContent="";let Q=n.name?.trim()||"tool",Z=Ri(E,Q),J=0;for(let fe of Z){let ne=fe.styles.length>0?(()=>{let ge=v("span",fe.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(ge),ge})():m;if(fe.isDuration&&c)ne.appendChild(w());else{let ge=fe.isDuration?cs(n):fe.text;G?J=zo(ne,ge,J):ne.appendChild(document.createTextNode(ge))}}};if(!M)if(c&&L!=="none"){let E=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${E}ms`),C&&P(C,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${E}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),C)P(C,!0);else{let G=m.textContent||p;m.textContent="",zo(m,G,0)}}else C&&P(C,!1);let R=null;if(s){R=v("div","persona-flex persona-items-center");let E=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,E,2);G?R.appendChild(G):R.textContent=l?"Hide":"Show";let Q=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(R),f.append(g,Q)}else f.append(g);let F=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!l&&c&&a.activePreview&&d){let E=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});uA(F,E)||(F.textContent=d),F.style.display=""}if(!l&&c&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(f,F),r;let O=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(O.style.display=l?"":"none",o.contentBackgroundColor&&(O.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(O.style.color=o.contentTextColor),o.contentPaddingX&&(O.style.paddingLeft=o.contentPaddingX,O.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(O.style.paddingTop=o.contentPaddingY,O.style.paddingBottom=o.contentPaddingY),n.name){let E=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?E.style.color=o.contentTextColor:o.headerTextColor&&(E.style.color=o.headerTextColor),E.textContent=n.name,O.appendChild(E)}if(n.args!==void 0){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Arguments";let Q=v("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=Do(n.args),E.append(G,Q),O.appendChild(E)}if(n.chunks&&n.chunks.length){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Activity";let Q=v("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=n.chunks.join(""),E.append(G,Q),O.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Result";let Q=v("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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=Do(n.result),E.append(G,Q),O.appendChild(E)}if(n.status==="complete"&&typeof n.duration=="number"){let E=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(E.style.color=o.contentTextColor),E.textContent=`Duration: ${n.duration}ms`,O.appendChild(E)}return(()=>{if(f.setAttribute("aria-expanded",l?"true":"false"),R){R.innerHTML="";let E=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,E,2);G?R.appendChild(G):R.textContent=l?"Hide":"Show"}O.style.display=l?"":"none",F.style.display=l?"none":F.textContent||F.childNodes.length?"":"none"})(),r.append(f,F,O),r};var Rr=new Map,Fl=e=>{let n=(e.startsWith(Dn)?e.slice(Dn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ly=e=>e?.approval!==!1?e?.approval:void 0,Py=(e,t)=>{let n=Ly(t)?.detailsDisplay??"collapsed";return Rr.get(e)??n==="expanded"},Ry=(e,t,n)=>{let o=Ly(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let s=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},Iy=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Py(e,n);Ry(o,a,n),r.style.display=a?"":"none"};var Ol=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=v("div",["persona-approval-bubble","persona-w-full","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=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",a.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",a.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return a;let s=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ae(p,20,d,2);c&&l.appendChild(c);let f=v("div","persona-flex-1 persona-min-w-0"),g=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(m.style.color=o.titleColor),m.textContent=o?.title??"Approval Required",g.appendChild(m),!r){let R=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");R.setAttribute("data-approval-status",n.status),n.status==="approved"?(R.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",R.style.color="var(--persona-palette-colors-success-700, #15803d)",R.textContent="Approved"):n.status==="denied"?(R.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",R.style.color="var(--persona-palette-colors-error-700, #b91c1c)",R.textContent="Denied"):n.status==="timeout"&&(R.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",R.style.color="var(--persona-palette-colors-warning-700, #b45309)",R.textContent="Timeout"),g.appendChild(R)}f.appendChild(g);let w=n.toolType==="webmcp"||n.toolName.startsWith(Dn)?os(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...w?{displayTitle:w}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,A=T||(L?n.description:`The assistant wants to use \u201C${w??Fl(n.toolName)}\u201D.`),S=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=A,f.appendChild(S),n.reason){let R=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");R.setAttribute("data-approval-reason","true"),o?.reasonColor?R.style.color=o.reasonColor:o?.descriptionColor&&(R.style.color=o.descriptionColor);let F=v("span","persona-font-medium");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,R.appendChild(F),R.appendChild(document.createTextNode(n.reason)),f.appendChild(R)}let C=o?.detailsDisplay??"collapsed",M=!!n.description&&!L,P=M||!!n.parameters;if(C!=="hidden"&&P){let R=Py(e.id,t),F=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");F.type="button",F.setAttribute("data-expand-header","true"),F.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(F.style.color=o.descriptionColor);let O=v("span");O.setAttribute("data-approval-details-label","true");let $=v("span","persona-inline-flex persona-items-center");$.setAttribute("data-approval-details-chevron","true"),F.append(O,$),Ry(F,R,t),f.appendChild(F);let E=v("div");if(E.setAttribute("data-approval-details","true"),E.style.display=R?"":"none",M){let G=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,E.appendChild(G)}if(n.parameters){let G=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(G.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=Do(n.parameters),E.appendChild(G)}f.appendChild(E)}if(r){let R=v("div","persona-flex persona-gap-2 persona-mt-2");R.setAttribute("data-approval-buttons","true");let F=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");F.type="button",F.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",F.style.color=o?.approveButtonTextColor??"#ffffff",F.setAttribute("data-approval-action","approve");let O=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);O&&(O.style.marginRight="4px",F.appendChild(O));let $=document.createTextNode(o?.approveLabel??"Approve");F.appendChild($);let E=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");E.type="button",E.style.backgroundColor=o?.denyButtonColor??"transparent",E.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",E.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,E.setAttribute("data-approval-action","deny");let G=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",E.appendChild(G));let Q=document.createTextNode(o?.denyLabel??"Deny");E.appendChild(Q),R.append(F,E),f.appendChild(R)}return s.append(l,f),a.appendChild(s),a};function gA(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Wy(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:l,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,f=e.container??gA(t),g=!1,m=null,b=()=>{if(!g)return;let L=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${L.width}px`),s&&(n.style.maxWidth=`${L.width}px`);let A=n.getBoundingClientRect(),S=l?.()??null,C=S!=null?L.top+S:L.top,M=o==="top-start"||o==="top-end"?C-r-A.height:L.bottom+r,R=o==="bottom-end"||o==="top-end"?L.right-A.width:L.left,F=s?.()??null;if(F!=null){let O=Math.max(L.left,L.right-A.width);R=Math.min(Math.max(L.left+F,L.left),O)}n.style.top=`${M}px`,n.style.left=`${R}px`},w=()=>{g&&(g=!1,m&&(m(),m=null),n.remove())},T=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),f.appendChild(n),b();let L=(t.ownerDocument??document).defaultView??window,A=t.ownerDocument??document,S=()=>{if(!t.isConnected){w(),c?.("anchor-removed");return}b()},C=P=>{let R=typeof P.composedPath=="function"?P.composedPath():[];R.includes(n)||R.includes(t)||(w(),c?.("outside"))},M=L.setTimeout(()=>{A.addEventListener("pointerdown",C,!0)},0);L.addEventListener("scroll",S,!0),L.addEventListener("resize",S),m=()=>{L.clearTimeout(M),A.removeEventListener("pointerdown",C,!0),L.removeEventListener("scroll",S,!0),L.removeEventListener("resize",S)},d?.()};return{get isOpen(){return g},open:T,close:w,toggle:()=>g?w():T(),reposition:b,destroy:w}}function Hy(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var hA=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),By=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Ir=(e,t)=>{By(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},yA=e=>e?.approval!==!1?e?.approval:void 0,bA=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Rr.get(e)??n==="expanded"},Ju=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},xA=(e,t)=>{let n=v("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Dn)?os(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let s=r??Fl(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=s,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},vA=e=>{let t=v("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?Fl(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},CA=(e,t,n,o,r,a,s)=>{let l=v("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"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",f=d||c,g=f&&bA(t.id,o),m=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",w=v("button","persona-approval-head");w.type="button",f?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",g?"true":"false"),w.setAttribute("aria-label",g?b:m)):w.setAttribute("data-static","true");let T=v("span","persona-approval-logo"),L=ae("shield-check",16,"currentColor",2);L&&T.appendChild(L),w.appendChild(T);let A=xA(n,o);if(f){let F=v("span","persona-approval-toggle");F.setAttribute("aria-hidden","true");let O=ae("chevron-down",14,"currentColor",2);O&&F.appendChild(O),A.append(" "),A.appendChild(F)}w.appendChild(A),l.appendChild(w);let S=v("div","persona-approval-body");if(f){let F=v("div","persona-approval-details");if(F.setAttribute("data-role","params"),F.hidden=!g,d){let O=v("p","persona-approval-desc");o?.descriptionColor&&(O.style.color=o.descriptionColor),O.textContent=n.description,F.appendChild(O)}if(c){let O=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(O.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(O.style.color=o.parameterTextColor),O.textContent=Do(n.parameters),F.appendChild(O)}S.appendChild(F)}if(n.reason){let F=v("p","persona-approval-reason");o?.reasonColor?F.style.color=o.reasonColor:o?.descriptionColor&&(F.style.color=o.descriptionColor);let O=v("span","persona-approval-reason-label");O.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,F.append(O,document.createTextNode(n.reason)),S.appendChild(F)}let C=v("div","persona-approval-actions"),M=null,P=F=>{o?.approveButtonColor&&(F.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(F.style.color=o.approveButtonTextColor)},R=v("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),o?.denyButtonColor&&(R.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(R.style.color=o.denyButtonTextColor),R.append(o?.denyLabel??"Deny"),s){let F=v("div","persona-approval-split"),O=v("button","persona-approval-primary");O.type="button",O.setAttribute("data-action","always"),P(O),O.append(o?.approveLabel??"Always allow",Ju("\u23CE"));let $=v("button","persona-approval-caret");$.type="button",$.setAttribute("data-action","toggle-menu"),$.setAttribute("aria-label","More options"),P($);let E=ae("chevron-down",15,"currentColor",2);E&&$.appendChild(E),F.append(O,$),C.append(F,R),R.append(Ju("Esc"));let G=v("div","persona-approval-menu"),Q=v("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Ju("\u2318\u23CE")),G.appendChild(Q),M=Wy({anchor:F,content:G,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,M),Q.addEventListener("click",()=>{Ir(e,t.id),r()})}else{let F=v("button","persona-approval-primary persona-approval-primary--solo");F.type="button",F.setAttribute("data-action","allow"),P(F),F.append(o?.approveLabel??"Allow"),C.append(F,R)}return S.appendChild(C),l.appendChild(S),l.addEventListener("click",F=>{let O=F.target instanceof Element?F.target.closest("[data-action]"):null;if(!O)return;let $=O.getAttribute("data-action");if($==="toggle-params"){let E=l.querySelector('[data-role="params"]');if(E){let G=E.hidden;E.hidden=!G,w.setAttribute("aria-expanded",G?"true":"false"),w.setAttribute("aria-label",G?b:m),Rr.set(t.id,G)}return}if($==="toggle-menu"){M?.toggle();return}if($==="always"){Ir(e,t.id),r({remember:!0});return}if($==="allow"){Ir(e,t.id),r();return}if($==="deny"){Ir(e,t.id),a();return}}),l},Dy=()=>{let e=hA();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:a,config:s})=>{let l=o?.approval;if(!l)return null;let p=yA(s);if(l.status!=="pending"){if(Ir(e,o.id),l.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return vA(l)}By(e,o.id);let d=p?.enableAlwaysAllow===!0,c=CA(e,o,l,p,r,a,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=g=>{Hy(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Ir(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Ir(e,o);e.latestPendingApprovalId=null}}};var Ls=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}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 n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)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,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.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 Ps=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{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=()=>{n(s.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{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=()=>{n(a.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{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=()=>{n(a.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}};var wA=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),AA=new Set(["step_start","execution_start"]),SA=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),MA=new Set(["step_complete","agent_turn_complete"]),TA=new Set(["flow_complete","agent_complete"]),Fy=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ny=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Wr=(e,t)=>{let n=e[t];return Ny(n)?n:void 0};function Qu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Nl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function EA(e,t){return typeof t.type=="string"?t.type:e}function kA(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 LA(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 Oy(e){let t=Wr(e,"result"),n=[Wr(e,"tokens"),Wr(e,"totalTokens"),t?Wr(t,"tokens"):void 0,Wr(e,"usage"),t?Wr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=hn(o.output)??hn(o.outputTokens)??hn(o.completionTokens);if(r!==void 0)return r}return hn(e.outputTokens)??hn(e.completionTokens)??(t?hn(t.outputTokens)??hn(t.completionTokens):void 0)}function PA(e){let t=Wr(e,"result");return hn(e.executionTime)??hn(e.executionTimeMs)??hn(e.execution_time)??hn(e.duration)??(t?hn(t.executionTime)??hn(t.executionTimeMs):void 0)}function RA(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=RA){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 n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Nl(this.metric.outputTokens,n)}}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,n){if(!Ny(n)){Fy.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=EA(t,n),r=this.now();if(wA.has(o)){this.startRun(r);return}if(AA.has(o)){this.run||this.startRun(r);return}if(SA.has(o)){if(!LA(o,n))return;let a=kA(n);if(!a)return;this.run||this.startRun(r);let s=this.run;s.firstDeltaAt??(s.firstDeltaAt=r),s.visibleCharCount+=a.length;let l=s.exactOutputTokens+Qu(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Nl(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(MA.has(o)){if(!this.run)return;let a=this.run,s=Oy(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+Qu(a.visibleCharCount),d=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Nl(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(TA.has(o)){if(!this.run)return;let a=this.run,s=Oy(n),l=s??a.exactOutputTokens+Qu(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Nl(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Fy.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:PA(n)??o-t.startedAt}};function wa(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var IA={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)"}},WA={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},HA=["flowName","stepName","reasoningText","text","name","tool","toolName"],BA=100;function DA(e,t){let n={...IA,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return WA}function FA(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function OA(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${a}`}function NA(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),a=n;for(let s of r)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 _A(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function UA(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 qA(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function VA(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 zA(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let a=t.find(l=>l.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let l=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>s(),parsedPayload:r});if(l)return l}return s();function s(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Yu(e,t,n,o,r,a,s,l){let p=r.has(e.id),d=v("div","persona-border-b persona-border-persona-divider persona-text-xs");wa(d,o.classNames?.eventRow);let c=s.find(g=>g.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let g=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return d.appendChild(g),d}return d.appendChild(f()),d;function f(){let g=v("div",""),m=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");m.setAttribute("data-event-id",e.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);w&&b.appendChild(w);let T=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";T.textContent=L==="relative"?FA(e.timestamp,n):OA(e.timestamp);let A=null;o.showSequenceNumbers!==!1&&(A=v("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 S=DA(e.type,o.badgeColors),C=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");C.style.backgroundColor=S.bg,C.style.color=S.text,C.style.borderColor=S.text+"50",C.textContent=e.type;let M=o.descriptionFields??HA,P=NA(e.payload,M),R=null;P&&(R=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),R.textContent=P);let F=v("div","persona-flex-1 persona-min-w-0"),O=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),$=ae("clipboard","12px","currentColor",1.5);return $&&O.appendChild($),O.addEventListener("click",async E=>{E.stopPropagation(),await _A(UA(e)),O.innerHTML="";let G=ae("check","12px","currentColor",1.5);G&&O.appendChild(G),setTimeout(()=>{O.innerHTML="";let Q=ae("clipboard","12px","currentColor",1.5);Q&&O.appendChild(Q)},1500)}),m.appendChild(b),m.appendChild(T),A&&m.appendChild(A),m.appendChild(C),R&&m.appendChild(R),m.appendChild(F),m.appendChild(O),g.appendChild(m),p&&g.appendChild(zA(e,s,l)),g}}function _y(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:a=[],getThroughput:s}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",f=r?.features?.eventStream??{},g=a.find(b=>b.renderEventStreamView);if(g?.renderEventStreamView&&r){let b=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return m();function m(){let b=f.classNames,w=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");wa(w,b?.panel);let T=[],L="",A="",S=null,C=[],M={},P=0,R=yl(),F=0,O=0,$=!1,E=null,G=!1,Q=0,Z=new Set,J=new Map,fe="",ne="",ge=null,ie,ue,oe,me,Se=null,Ce=null,Be=null;function ut(){let V=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),X=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(wa(X,b?.headerBar),s){Ce=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),Ce.style.cursor="help",Se=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Se.textContent="-- tok/s",Be=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Be.style.display="none",Be.style.pointerEvents="none";let wt=Ce,yn=Be,Us=()=>{if(!yn.textContent)return;let bn=wt.getBoundingClientRect(),it=V.getBoundingClientRect();yn.style.left=`${bn.left-it.left}px`,yn.style.top=`${bn.bottom-it.top+4}px`,yn.style.display="block"},te=()=>{yn.style.display="none"};Ce.addEventListener("mouseenter",Us),Ce.addEventListener("mouseleave",te),Ce.appendChild(Se)}let ce=v("div","persona-flex-1");ie=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ve=v("option","");Ve.value="",Ve.textContent="All events (0)",ie.appendChild(Ve),ue=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ue.type="button",ue.title="Copy All";let Pe=ae("clipboard-copy","12px","currentColor",1.5);Pe&&ue.appendChild(Pe);let ze=v("span","persona-event-copy-all persona-text-xs");ze.textContent="Copy All",ue.appendChild(ze),Ce&&X.appendChild(Ce),X.appendChild(ce),X.appendChild(ie),X.appendChild(ue);let Ue=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");wa(Ue,b?.searchBar);let We=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),we=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");We&&we.appendChild(We),oe=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),wa(oe,b?.searchInput),oe.type="text",oe.placeholder="Search event payloads...",me=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let nt=ae("x","12px","currentColor",2);return nt&&me.appendChild(nt),Ue.appendChild(we),Ue.appendChild(oe),Ue.appendChild(me),V.appendChild(X),V.appendChild(Ue),Be&&V.appendChild(Be),V}let Je,Qe=a.find(V=>V.renderEventStreamToolbar);Qe?.renderEventStreamToolbar&&r?Je=Qe.renderEventStreamToolbar({config:r,defaultRenderer:()=>ut(),eventCount:t.getSize(),filteredCount:0,onFilterChange:X=>{L=X,Le(),Te()},onSearchChange:X=>{A=X,Le(),Te()}})??ut():Je=ut();let Ne=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ne.style.display="none";function _e(){if(!s||!Se||!Ce)return;let V=s(),X=qA(V);Se.textContent=X;let ce=VA(V);Be&&(Be.textContent=ce,ce||(Be.style.display="none")),Ce.setAttribute("aria-label",ce?`Throughput: ${X}, ${ce}`:`Throughput: ${X}`)}let Ae=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Me=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Me.style.height="100%";let qe=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");wa(qe,b?.scrollIndicator),qe.style.display="none",qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Jt=ae(d,"14px","currentColor",2);Jt&&qe.appendChild(Jt);let gt=v("span","");gt.textContent=c,qe.appendChild(gt);let Bt=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Bt.style.display="none",Ae.appendChild(Me),Ae.appendChild(Bt),Ae.appendChild(qe),w.setAttribute("tabindex","0"),w.appendChild(Je),w.appendChild(Ne),w.appendChild(Ae);function Tn(){let V=t.getAll(),X={};for(let Ue of V)X[Ue.type]=(X[Ue.type]||0)+1;let ce=Object.keys(X).sort(),Ve=ce.length!==C.length||!ce.every((Ue,We)=>Ue===C[We]),de=!Ve&&ce.some(Ue=>X[Ue]!==M[Ue]),Pe=V.length!==Object.values(M).reduce((Ue,We)=>Ue+We,0);if(!Ve&&!de&&!Pe||(C=ce,M=X,!ie))return;let ze=ie.value;if(ie.options[0].textContent=`All events (${V.length})`,Ve){for(;ie.options.length>1;)ie.remove(1);for(let Ue of ce){let We=v("option","");We.value=Ue,We.textContent=`${Ue} (${X[Ue]||0})`,ie.appendChild(We)}ze&&ce.includes(ze)?ie.value=ze:ze&&(ie.value="",L="")}else for(let Ue=1;Ue<ie.options.length;Ue++){let We=ie.options[Ue];We.textContent=`${We.value} (${X[We.value]||0})`}}function En(){let V=t.getAll();if(L&&(V=V.filter(X=>X.type===L)),A){let X=A.toLowerCase();V=V.filter(ce=>ce.type.toLowerCase().includes(X)||ce.payload.toLowerCase().includes(X))}return V}function et(){return L!==""||A!==""}function Le(){P=0,F=0,R.resume(),qe.style.display="none"}function he(V){Z.has(V)?Z.delete(V):Z.add(V),ge=V;let X=Me.scrollTop,ce=R.isFollowing();G=!0,R.pause(),Te(),Me.scrollTop=X,ce&&R.resume(),G=!1}function tt(){return uo(Me,50)}function Te(){O=Date.now(),$=!1,_e(),Tn();let V=t.getEvictedCount();V>0?(Ne.textContent=`${V.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",T=En();let X=T.length,ce=t.getSize()>0;X===0&&ce&&et()?(Bt.textContent=A?`No events matching '${A}'`:"No events matching filter",Bt.style.display="",Me.style.display="none"):(Bt.style.display="none",Me.style.display=""),ue&&(ue.title=et()?`Copy Filtered (${X})`:"Copy All"),p&&!R.isFollowing()&&X>P&&(F+=X-P,gt.textContent=c?`${c}${F>0?` (${F})`:""}`:"",qe.style.display=""),P=X;let Ve=t.getAll(),de=Ve.length>0?Ve[0].timestamp:0,Pe=new Set(T.map(We=>We.id));for(let We of Z)Pe.has(We)||Z.delete(We);let ze=L!==fe||A!==ne,Ue=J.size===0&&T.length>0;if(ze||Ue||T.length===0){Me.innerHTML="",J.clear();let We=document.createDocumentFragment();for(let we=0;we<T.length;we++){let nt=Yu(T[we],we,de,f,Z,he,a,r);J.set(T[we].id,nt),We.appendChild(nt)}Me.appendChild(We),fe=L,ne=A,ge=null}else{if(ge!==null){let we=J.get(ge);if(we&&we.parentNode===Me){let nt=T.findIndex(wt=>wt.id===ge);if(nt>=0){let wt=Yu(T[nt],nt,de,f,Z,he,a,r);Me.insertBefore(wt,we),we.remove(),J.set(ge,wt)}}ge=null}let We=new Set(T.map(we=>we.id));for(let[we,nt]of J)We.has(we)||(nt.remove(),J.delete(we));for(let we=0;we<T.length;we++){let nt=T[we];if(!J.has(nt.id)){let wt=Yu(nt,we,de,f,Z,he,a,r);J.set(nt.id,wt),Me.appendChild(wt)}}}R.isFollowing()&&(Me.scrollTop=Me.scrollHeight)}function be(){if(Date.now()-O>=BA){E!==null&&(cancelAnimationFrame(E),E=null),Te();return}$||($=!0,E=requestAnimationFrame(()=>{E=null,Te()}))}let re=(V,X)=>{if(!ue)return;ue.innerHTML="";let ce=ae(V,"12px","currentColor",1.5);ce&&ue.appendChild(ce);let Ve=v("span","persona-text-xs");Ve.textContent="Copy All",ue.appendChild(Ve),setTimeout(()=>{ue.innerHTML="";let de=ae("clipboard-copy","12px","currentColor",1.5);de&&ue.appendChild(de);let Pe=v("span","persona-text-xs");Pe.textContent="Copy All",ue.appendChild(Pe),ue.disabled=!1},X)},xe=async()=>{if(ue){ue.disabled=!0;try{let V;et()?V=T:n?(V=await n(),V.length===0&&(V=t.getAll())):V=t.getAll();let X=V.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(X,null,2)),re("check",1500)}catch{re("x",1500)}}},kn=()=>{ie&&(L=ie.value,Le(),Te())},ee=()=>{!oe||!me||(me.style.display=oe.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{A=oe.value,Le(),Te()},150))},I=()=>{!oe||!me||(oe.value="",A="",me.style.display="none",S&&clearTimeout(S),Le(),Te())},B=()=>{if(G)return;let V=Me.scrollTop,{action:X,nextLastScrollTop:ce}=bl({following:R.isFollowing(),currentScrollTop:V,lastScrollTop:Q,nearBottom:tt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=ce,X==="resume"?(R.resume(),F=0,qe.style.display="none"):X==="pause"&&(R.pause(),p&&(gt.textContent=c,qe.style.display=""))},y=V=>{let X=xl({following:R.isFollowing(),deltaY:V.deltaY,nearBottom:tt(),resumeWhenNearBottom:!0});X==="pause"?(R.pause(),p&&(gt.textContent=c,qe.style.display="")):X==="resume"&&(R.resume(),F=0,qe.style.display="none")},D=()=>{p&&(Me.scrollTop=Me.scrollHeight,R.resume(),F=0,qe.style.display="none")},H=V=>{let X=V.target;if(!X||X.closest("button"))return;let ce=X.closest("[data-event-id]");if(!ce)return;let Ve=ce.getAttribute("data-event-id");Ve&&he(Ve)},N=V=>{if((V.metaKey||V.ctrlKey)&&V.key==="f"){V.preventDefault(),oe?.focus(),oe?.select();return}V.key==="Escape"&&(oe&&document.activeElement===oe?(I(),oe.blur(),w.focus()):o&&o())};ue&&ue.addEventListener("click",xe),ie&&ie.addEventListener("change",kn),oe&&oe.addEventListener("input",ee),me&&me.addEventListener("click",I),Me.addEventListener("scroll",B),Me.addEventListener("wheel",y,{passive:!0}),Me.addEventListener("click",H),qe.addEventListener("click",D),w.addEventListener("keydown",N);function K(){S&&clearTimeout(S),E!==null&&(cancelAnimationFrame(E),E=null),$=!1,J.clear(),ue&&ue.removeEventListener("click",xe),ie&&ie.removeEventListener("change",kn),oe&&oe.removeEventListener("input",ee),me&&me.removeEventListener("click",I),Me.removeEventListener("scroll",B),Me.removeEventListener("wheel",y),Me.removeEventListener("click",H),qe.removeEventListener("click",D),w.removeEventListener("keydown",N)}return{element:w,update:be,destroy:K}}}function Uy(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},p=f=>{let g=f;return a.findIndex(m=>m===g||m.contains(g))},d=f=>{let g=p(f.target);if(g<0)return;let m=g;if(f.key===r)m=Math.min(g+1,a.length-1);else if(f.key===o)m=Math.max(g-1,0);else if(f.key==="Home")m=0;else if(f.key==="End")m=a.length-1;else return;f.preventDefault(),m!==g&&t.onSelect(m)},c=f=>{let g=p(f.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(f,g){if(a=f,f.forEach((m,b)=>{m.setAttribute("role","tab");let w=b===g;m.setAttribute("aria-selected",w?"true":"false"),m.tabIndex=w||g<0&&b===0?0:-1}),s){let m=(g>=0?f[g]:void 0)??f[0];m&&typeof m.focus=="function"&&(l(m),m.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function qy(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",a=n?.toolbarTitle??"Artifacts",s=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:c,end:f}=d(n?.tabFade),g=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{g?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),G?.hide()};g&&g.addEventListener("click",()=>{m(),t.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let w=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");w.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&w.classList.add("persona-artifact-toolbar-document");let T=v("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=a;let L=Tt({icon:"x",label:s});L.addEventListener("click",()=>{m(),t.onDismiss?.()});let A="rendered",S=ma({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{A=ee==="source"?"source":"rendered",re()}}),C=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=n?.documentToolbarShowCopyLabel===!0,P=n?.documentToolbarShowCopyChevron===!0,R=n?.documentToolbarCopyMenuItems,F=!!(P&&R&&R.length>0),O=null,$,E=null,G=null;if(r&&(M||P)&&!F){if($=M?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let ee=ae("chevron-down",14,"currentColor",2);ee&&$.appendChild(ee)}}else r&&F?(O=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=M?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=Tt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),O.append($,E)):r?$=Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):($=Tt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&$.classList.add("persona-hidden"));let Q=r?Tt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Tt({icon:"refresh-cw",label:"Refresh"}),Z=r?Tt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Tt({icon:"x",label:s}),J=Tt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&J.classList.add("persona-hidden");let fe=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ne=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ee=Ae.find(D=>D.id===Me)??Ae[Ae.length-1],I=ee?.id??null,B=ee?.artifactType==="markdown"?ee.markdown??"":"",y=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:B,jsonPayload:y,id:I}},ie=async()=>{let ee=Ae.find(I=>I.id===Me)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(vs(ee))}catch{}};if($.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&F){let{markdown:I,jsonPayload:B,id:y}=ge();try{await ee({actionId:"primary",artifactId:y,markdown:I,jsonPayload:B})}catch{}return}await ie()}),E&&R?.length){let ee=()=>b.closest("[data-persona-root]")??document.body,I=()=>{G=$o({items:R.map(B=>({id:B.id,label:B.label})),onSelect:async B=>{let{markdown:y,jsonPayload:D,id:H}=ge(),N=n?.onDocumentToolbarCopyMenuSelect;try{N?await N({actionId:B,artifactId:H,markdown:y,jsonPayload:D}):B==="markdown"||B==="md"?await navigator.clipboard.writeText(y):B==="json"||B==="source"?await navigator.clipboard.writeText(D):await navigator.clipboard.writeText(y||D)}catch{}},anchor:O??E,position:"bottom-right",portal:ee()})};b.isConnected?I():requestAnimationFrame(I),E.addEventListener("click",B=>{B.stopPropagation(),G?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}re()}),Z.addEventListener("click",()=>{m(),t.onDismiss?.()});let ue=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)w.replaceChildren(),O?C.append(O,Q,Z):C.append($,Q,Z),C.insertBefore(fe,Z),C.insertBefore(J,Z),w.append(S.element,ue,C);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append($,fe,J,L),w.appendChild(T),w.appendChild(ee)}l&&(w.style.paddingLeft=l,w.style.paddingRight=l);let oe=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&oe.style.setProperty("--persona-artifact-tab-fade-size",p);let me=e.features?.artifacts?.renderTabBar,Se=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Ce=Uy(oe,{onSelect:ee=>t.onSelect(Ae[ee].id)}),Be=ee=>{let I=ee.scrollWidth-ee.clientWidth,B=I>1,y=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",c&&B&&y>1),ee.classList.toggle("persona-artifact-tab-fade-end",f&&B&&y<I-1)},ut=0,Je=()=>{if(ut)return;let ee=()=>{ut=0,Be(oe)};ut=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};oe.addEventListener("scroll",()=>Je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Be(oe)).observe(oe);let Qe=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ne=()=>{Qe.scrollLeft=0},_e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ne):setTimeout(Ne,0)};if(l){for(let ee of[oe,Se])ee.style.paddingLeft=l,ee.style.paddingRight=l;Qe.style.padding=l}b.appendChild(w),b.appendChild(oe),b.appendChild(Se),b.appendChild(Qe);let Ae=[],Me=null,qe=!1,Jt=!1,gt=!0,Bt=!1,Tn=null,En="",et=null,Le=!1,he=ee=>ee.artifactType==="markdown"&&!!ee.file||r?A:"rendered",tt=ee=>{r||(ee&&!Le?(w.insertBefore(S.element,T),Le=!0):!ee&&Le&&(S.element.remove(),Le=!1))},Te=()=>Me&&Ae.find(ee=>ee.id===Me)||Ae[Ae.length-1],be=()=>{let ee=bs(Te());if(!ee){fe.replaceChildren();return}let I=ne.filter(B=>B.visible===void 0||B.visible(ee)).map(B=>ga(B,{documentChrome:r,onClick:()=>{let y=bs(Te());if(y)try{Promise.resolve(B.onClick(y)).catch(()=>{})}catch{}}}));fe.replaceChildren(...I)},re=()=>{be();let ee=r&&Ae.length<=1,I=!!me;if(oe.classList.toggle("persona-hidden",ee||I),Se.classList.toggle("persona-hidden",ee||!I),I&&me){let D=Ae.map(H=>H.id).join("|")+" "+(Me??"");if(D!==En){En=D;let H=me({records:Ae,selectedId:Me,onSelect:t.onSelect});Se.firstElementChild!==H&&Se.replaceChildren(H)}}else{Ce.beforeRender(),oe.replaceChildren();let D=[],H=-1;for(let[N,K]of Ae.entries()){let V=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");V.type="button";let X=K.artifactType==="markdown"?K.file:void 0,ce=X?$n(X.path):K.title||K.id.slice(0,8),Ve=X?.path||K.title||ce;V.textContent=ce,V.title=Ve,V.setAttribute("aria-label",Ve),K.id===Me&&(V.classList.add("persona-bg-persona-container","persona-border-persona-border"),H=N),V.addEventListener("click",()=>t.onSelect(K.id)),oe.appendChild(V),D.push(V)}if(Ce.render(D,H),H>=0&&Me!==Tn){Tn=Me;let N=D[H];typeof N.scrollIntoView=="function"&&N.scrollIntoView({block:"nearest",inline:"nearest"})}Be(oe)}let B=Me&&Ae.find(D=>D.id===Me)||Ae[Ae.length-1];if(!B){Qe.replaceChildren(),et=null,tt(!1);return}let y=B.artifactType==="markdown"?B.file:void 0;if(tt(!!y&&Mr(y)!=="other"),r){let D=y?Vo(y):B.artifactType==="markdown"?"MD":B.component??"Component",H=(B.title||"Document").trim(),N=y?$n(y.path):H.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ue.textContent=`${N} \xB7 ${D}`}else T.textContent=y?$n(y.path):a;et?(et.el.parentElement!==Qe&&Qe.replaceChildren(et.el),et.update(B)):(et=gl(B,{config:e,resolveViewMode:he}),Qe.replaceChildren(et.el)),Qe.classList.toggle("persona-artifact-content-flush",!!Qe.querySelector(".persona-code-pre"))},xe=()=>{let ee=Ae.length>0;if(b.classList.toggle("persona-hidden",!ee),g){let y=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&y&&qe?(g.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},kn=()=>{Bt=!1,re(),xe()};return{element:b,backdrop:g,update(ee){let I=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,B=I!==Me;Ae=ee.artifacts,Me=I,Ae.length>0&&(qe=!0),Bt=!0,gt&&kn(),B&&Ne()},setMobileOpen(ee){qe=ee,!ee&&g?(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):xe()},setExpanded(ee){ee!==Jt&&(Jt=ee,_e());let I=ae(ee?"minimize":"maximize",16,"currentColor",2);I&&J.replaceChildren(I);let B=ee?"Collapse artifacts panel":"Expand artifacts panel";J.setAttribute("aria-label",B),J.title=B},setExpandToggleVisible(ee){J.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||$.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){ne=ee,be()},setTabFade(ee){let I=d(ee);I.start===c&&I.end===f||(c=I.start,f=I.end,Be(oe))},setRenderTabBar(ee){ee!==me&&(me=ee,En="",re())},setVisible(ee){ee!==gt&&(gt=ee,ee&&Bt&&kn())}}}function tn(e){return e?.features?.artifacts?.enabled===!0}function Vy(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"),!tn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function $A(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 zy=["panel","seamless","detached"];function Zu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&zy.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function ef(e){return!e||!tn(e)?!1:Zu(e)==="detached"}function Is(e,t){if(!tn(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-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),$A(e),Vy(e,t);return}let n=t.features?.artifacts?.layout,o=Zu(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=n?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=n?.documentToolbarIconColor?.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Vy(e,t)}function Ws(e,t){for(let l of zy)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"),!tn(t))return;let n=t.features?.artifacts?.layout,o=Zu(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=n?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=n?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}function $y(e,t){return!t||!tn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var jA=new Set(["__proto__","prototype","constructor"]),GA=new Set(["collapsed","card","panel","inline"]),jy=new Set(["markdown","component"]),KA=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ul=e=>!jA.has(e),tf=e=>typeof e=="string"&&GA.has(e),Br=e=>Object.keys(e).length>0;function Gn(e,t,n,o){e.push({path:t,code:n,message:o})}var XA="Ignored because this key is not part of the persisted preference schema.",_l="Ignored an unsupported value.",JA="Expected collapsed, panel, or inline.",QA='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Gy={kind:"mode",message:_l},Aa={kind:"string",message:"Expected a CSS length string."},go={kind:"boolean"},YA={paneWidth:Aa,paneMaxWidth:Aa,paneMinWidth:Aa,expandedPanelWidth:Aa,resizableMinWidth:Aa,resizableMaxWidth:Aa,expandLauncherPanelWhenOpen:go,resizable:go},ZA={kind:"object",message:"Expected a preference object.",children:{showToolCalls:go,showReasoning:go,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:_l},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:_l},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:_l},expandable:go,grouped:go}},reasoningDisplay:{kind:"object",children:{expandable:go,activePreview:go}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Gy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Gy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jy}}},filePreview:{kind:"object",children:{enabled:go}},layout:{kind:"object",children:YA}}}}};function Ky(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Gn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Gn(o,n,"invalid_value",t.message);case"mode":return tf(e)?sn(e):Gn(o,n,"invalid_value",t.message);case"modeMap":{if(!Hr(e))return Gn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[s,l]of Object.entries(e)){let p=r?s:Po(s);Ul(s)&&(r?r.has(s):KA.test(p))?tf(l)?a[p]=sn(l):Gn(o,`${n}.${s}`,"invalid_value",JA):Gn(o,`${n}.${s}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":QA)}return Br(a)?a:void 0}case"object":{if(t.bareMode&&tf(e))return sn(e);if(!Hr(e))return Gn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Ul(l)||!r.includes(l))&&Gn(o,a(l),"unknown_key",XA);let s={};for(let l of r){let p=t.children[l],d=Ky(e[l],p,a(l),o);if(p.deprecated&&e[l]!==void 0&&Gn(o,a(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,f=s[c];s[c]=Hr(f)&&Hr(d)?{...f,...d}:d}return Br(s)?s:void 0}}}function nf(e){let t=[];return{preferences:(e===null?void 0:Ky(e,ZA,"",t))??{},issues:t}}function Sa(e){if(Array.isArray(e))return e.map(Sa);if(!Hr(e))return e;let t={};for(let[n,o]of Object.entries(e))Ul(n)&&o!==void 0&&(t[n]=Sa(o));return t}function Xy(e,t){let n=Sa(e);for(let[o,r]of Object.entries(t)){if(!Ul(o)||r===void 0)continue;let a=n[o];n[o]=Hr(a)&&Hr(r)?Xy(a,r):Sa(r)}return n}function eS(e){let t={},n;for(let r of e){let a=nf(r).preferences;n=Jy(n,a.artifacts?.display),t=Xy(t,a)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function tS(e,t){if(t===void 0)return e===void 0?void 0:Sa(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},a={...o?{default:o}:{},...Br(r)?{byMediaType:r}:{}};return Br(a)?a:void 0}function Jy(e,t){if(t===void 0)return e===void 0?void 0:Sa(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},a=tS(n.files,t.files),s={...o?{default:o}:{},...Br(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Br(s)?s:void 0}function of(e={},t){let n=eS(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},a={...r};if(n.artifacts.display!==void 0){let s=Jy(r.display,n.artifacts.display);s!==void 0&&(a.display=s)}n.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(a.layout={...r.layout,...n.artifacts.layout}),o.artifacts=a}return o}function Hs(e){let t=e.preferences;return!t||!Br(t)?e:{...e,features:of(e.features??{},[t])}}function nS(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function oS(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 rS(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function aS(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function rf(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Qy(e,t,n,o,r,a){let s=nS(r,200),l=aS(t,n,o,200);l=Math.max(s,l);let p=oS(a);return p!==null&&(l=Math.min(l,p)),rS(e,s,l)}var Yy={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"}},af=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(a=>{if(a.dataset.enhanced==="true")return;let s=a.dataset.tvForm??"init";a.dataset.enhanced="true";let l=Yy[s]??Yy.init;a.classList.add("persona-form-card","persona-space-y-4");let p=v("div","persona-space-y-1"),d=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,p.appendChild(b)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let w=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");w.htmlFor=`${t.id}-${s}-${b.name}`;let T=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=b.label,w.appendChild(T);let L=b.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}-${b.name}`,A.name=b.name,A.placeholder=b.placeholder??"",b.required&&(A.required=!0),w.appendChild(A),c.appendChild(w)});let f=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=l.submitLabel??"Submit",f.appendChild(g),f.appendChild(m),c.appendChild(f),a.replaceChildren(p,c),c.addEventListener("submit",async b=>{b.preventDefault();let w=n.formEndpoint??"/form",T=new FormData(c),L={};T.forEach((A,S)=>{L[S]=A}),L.type=s,m.disabled=!0,g.textContent="Submitting\u2026";try{let A=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let S=await A.json();g.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(A){g.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var sf=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 n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(a=>a.id));return[...n.filter(a=>!o.has(a.id)),...t].sort((a,s)=>(s.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Bs=new sf;var Zy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sS=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),eb=(e,t,n)=>{if(!Zy(e)||!Zy(t)||sS.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let a=n?`${n}.${r}`:r;o[r]=eb(e[r],t[r],a)}return o};function ql(e,t){let n=eb(e,t,"");return da(n)}var tb=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>n(r,a)),n=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:n,emit:(r,a)=>{e.get(r)?.forEach(s=>{try{s(a)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var iS=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},lS=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let a=t[r];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Ds=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=iS(e),n=lS(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...a}=o;return{type:String(r),payload:a,raw:o}}catch{return null}},lf=e=>typeof e=="string"?e:e==null?"":String(e),Dr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:lf(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=lf(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:lf(n.text)}}},nb=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fs=e=>{let t=new Set(nb(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(nb(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<"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),o();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)},f=d(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var cS=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}},dS=e=>e.map(t=>({...t,streaming:!1})),pS=e=>e.map(t=>({...t,status:"complete"})),Vl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?cS(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?dS(n.messages):void 0,artifacts:n.artifacts?pS(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ma=ko(wi(),1);function uS(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function fS(e,t){if(!uS(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function zl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Ma.parse)(n,Ma.STR|Ma.OBJ),a=fS(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ob(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function $l(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=Nn.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:n,updateProps:l=>{r&&r(l)}};try{return a(e.props,s)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function rb(){let e=zl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ab(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 Os(e){let t=ab(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function jl(e){let t=ab(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var mS=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gl(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=mS}=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 f=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,m.appendChild(b);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,m.appendChild(w),g.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let P=1;P<=5;P++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${P} star${P>1?"s":""}: ${d[P-1]}`),R.title=d[P-1],R.dataset.rating=String(P),R.innerHTML=`
|
|
42
|
+
`,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=ht(s),d=n.querySelector("[data-role='launcher-title']");if(d){let M=i.title??"Chat Assistant";d.textContent=M,d.setAttribute("title",M)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let M=i.subtitle??"Here to help you get answers fast";u.textContent=M,u.setAttribute("title",M)}let p=n.querySelector(".persona-flex-col");p&&(i.textHidden||l?p.style.display="none":p.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let M=i.agentIconSize??"40px";if(f.style.height=M,f.style.width=M,i.agentIconBackgroundColor?(f.style.backgroundColor=i.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",i.agentIconName){let x=parseFloat(M)||24,w=ce(i.agentIconName,x*.6,"var(--persona-text-inverse, #ffffff)",1.5);w?(f.appendChild(w),f.style.display=""):(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let M=i.agentIconSize??"40px";y.style.height=M,y.style.width=M,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let M=i.callToActionIconSize??"32px";g.style.height=M,g.style.width=M,i.callToActionIconBackgroundColor?(g.style.backgroundColor=i.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(g.style.color=i.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let x=0;if(i.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=i.callToActionIconPadding,x=(parseFloat(i.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),i.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",i.callToActionIconName){let w=parseFloat(M)||24,L=Math.max(w-x,8),P=ce(i.callToActionIconName,L,"currentColor",1.5);P?g.appendChild(P):g.textContent=i.callToActionIconText??"\u2197"}else g.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&Wn[i.position]?Wn[i.position]:Wn["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="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-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${v} ${b}`,l||(n.style.zIndex=String(i.zIndex??Qt));let H="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",k="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=i.border??H,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:k,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},zT="teaser-dismissed",Gv=new Set,$v=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${zT}`},jT=(e,t)=>{if(Gv.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},$T=(e,t)=>{if(Gv.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},GT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,KT=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||ht(e??{})?null:t},Kv=(e,t)=>{let n=S("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,d=null,u=!1,p=!1,f=!1,y=!1,g=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{d!==null&&(clearTimeout(d),d=null)},v=()=>{!s||!u||(u=!1,s.hidden=!0)},E=xe=>{b(),f=!0,v(),$T($v(o),xe&&g())},H=xe=>{!r||f||E(xe==="user"&&u)},k=()=>{d=null,!(!s||f||y)&&(p=!0,u=!0,s.hidden=!1,!(GT()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},M=()=>{!r||!s||f||p||y||jT($v(o),g())||(b(),d=setTimeout(k,Math.max(0,r.delayMs??0)))},x=()=>{E(g()),t()},w=xe=>{xe.stopPropagation(),E(g())},P=ug(e,()=>{H("user"),t()}),D=()=>{b(),l?.removeEventListener("click",x),i?.removeEventListener("click",w),s?.remove(),s=null,l=null,i=null,u=!1},q=()=>{l=ue("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",x),i=ue("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",w),s=ue("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,P.element)},$=()=>{let xe=o.launcher?.position??"bottom-right",ye=Wn[xe]??Wn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",P.element.style.position="";return}n.className=jn("persona-launcher-surface",ye),n.setAttribute("data-teaser",xe),n.style.zIndex=String(o.launcher?.zIndex??Qt),P.element.style.position="static"},N=xe=>{let ye=KT(xe);if(r=ye,!ye){D();return}s||q(),l.textContent=ye.text,i.hidden=ye.dismissible===!1,i.setAttribute("aria-label",ye.dismissLabel??"Dismiss message"),M()},X=xe=>{o=xe,P.update(xe),N(xe),$()},de=(xe,ye="user")=>{y=xe,xe&&H(ye)},me=()=>{D(),P.destroy(),n.remove()};return n.appendChild(P.element),e&&(N(e),$()),{element:n,launcher:P,get teaser(){return s?{element:s,show:k,dismiss:E}:null},setPanelOpen:de,update:X,destroy:me}};var Xv=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Vv(e),s=jv(e,t),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},u={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:i,panelElements:s,transcript:l,header:d,composer:u,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{u.footer.replaceWith(y),u.footer=y}}},fg=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>ug(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Kv(e,n);return{instance:r,element:r.element}};var XT=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},YT=(e,t,n)=>`${XT(e)}plugin:${t}:${n}`,Yv=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=i=>YT(e(),r,i);return{get:i=>{let l=s(i),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let d=s(i),u=o();if(u)try{u.setItem(d,l);return}catch{n=!0}t.set(d,l)},remove:i=>{let l=s(i);t.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};var ba=new Set,JT=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),QT=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
43
|
+
`):""},Jv=(e,t)=>{let n=ba.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=ce(n?"chevron-up":"chevron-down",16,"currentColor",2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},mg=(e,t)=>{let n=e.reasoning,o=S("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,i=s&&ba.has(e.id),l=n.status!=="complete",d=QT(e,r.previewMaxLines??3),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","reasoning");let p=S("div","persona-flex persona-flex-col persona-text-left"),f=S("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",g=t?.reasoning??{},b=String(n.startedAt??Date.now()),v=()=>{let me=S("span","");return me.setAttribute("data-tool-elapsed",b),me.textContent=uc(n),me},E=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:uc(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(f.textContent=E,p.appendChild(f)):E instanceof HTMLElement?p.appendChild(E):(f.textContent=y,p.appendChild(f));let H=S("span","persona-text-xs persona-text-persona-primary");H.textContent=Gb(n),p.appendChild(H);let k=r.loadingAnimation??"none",M=g.activeTextTemplate,x=g.completeTextTemplate,w=l?M:x,L=E instanceof HTMLElement,P=(me,xe)=>{f.textContent="";let ye=fc(me,""),ne=0;for(let ie of ye){let le=ie.styles.length>0?(()=>{let I=S("span",ie.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(I),I})():f;if(ie.isDuration&&l)le.appendChild(v());else{let I=ie.isDuration?uc(n):ie.text;xe?ne=wr(le,I,ne):le.appendChild(document.createTextNode(I))}}};if(!L&&w)if(H.style.display="none",f.style.display="",l&&k!=="none"){let me=g.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),k==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${me}ms`),P(w,!1)):(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${me}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),P(w,!0))}else P(w,!1);else if(!L&&l&&k!=="none"){f.style.display="";let me=g.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),k==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${me}ms`);else{f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${me}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let xe=f.textContent||y;f.textContent="",wr(f,xe,0)}n.status==="complete"&&(f.style.display="none")}else L||(n.status==="complete"?f.style.display="none":f.style.display="");let D=null;if(s){D=S("div","persona-flex persona-items-center");let xe=ce(i?"chevron-up":"chevron-down",16,"currentColor",2);xe?D.appendChild(xe):D.textContent=i?"Hide":"Show";let ye=S("div","persona-flex persona-items-center persona-ml-auto");ye.append(D),u.append(p,ye)}else u.append(p);let q=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&d){let me=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}});JT(q,me)||(q.textContent=d),q.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(u,q),o;let $=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=i?"":"none";let N=n.chunks.join(""),X=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return X.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(X),(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),D){D.innerHTML="";let xe=ce(i?"chevron-up":"chevron-down",16,"currentColor",2);xe?D.appendChild(xe):D.textContent=i?"Hide":"Show"}$.style.display=i?"":"none",q.style.display=i?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(u,q,$),o};var xa=new Set,ZT=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),eE=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
44
|
+
`);let r=mr(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
45
|
+
`):""},gg=(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)"},tE=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=eE(e,o?.previewMaxLines??3),i=n?Kb(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",d=t?.toolCall??{},u=i;return r==="tool-name"?u=n.name?.trim()||i:r==="tool-preview"&&s&&(u=s),l&&d.activeTextTemplate?u=Cu(n,d.activeTextTemplate,u):!l&&d.completeTextTemplate&&(u=Cu(n,d.completeTextTemplate,u)),{summary:u,previewText:s,isActive:l}},Qv=(e,t,n)=>{let o=xa.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(u){u.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",f=ce(o?"chevron-up":"chevron-down",16,p,2);f?u.appendChild(f):u.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},hg=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=S("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","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.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.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))",!n)return r;let s=t?.features?.toolCallDisplay??{},i=s.expandable!==!1,l=i&&xa.has(e.id),{summary:d,previewText:u,isActive:p}=tE(e,t),f=S("button",i?"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");f.type="button",i&&(f.setAttribute("aria-expanded",l?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let y=S("div","persona-flex persona-flex-col persona-text-left"),g=S("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),v=()=>{let N=S("span","");return N.setAttribute("data-tool-elapsed",b),N.textContent=xi(n),N},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:u,collapsedMode:s.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:xi(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(g.textContent=E,y.appendChild(g)):E instanceof HTMLElement?y.appendChild(E):(g.textContent=d,y.appendChild(g));let H=s.loadingAnimation??"none",k=o.activeTextTemplate,M=o.completeTextTemplate,x=p?k:M,w=E instanceof HTMLElement,L=(N,X)=>{g.textContent="";let de=n.name?.trim()||"tool",me=fc(N,de),xe=0;for(let ye of me){let ne=ye.styles.length>0?(()=>{let ie=S("span",ye.styles.map(le=>`persona-tool-text-${le}`).join(" "));return g.appendChild(ie),ie})():g;if(ye.isDuration&&p)ne.appendChild(v());else{let ie=ye.isDuration?xi(n):ye.text;X?xe=wr(ne,ie,xe):ne.appendChild(document.createTextNode(ie))}}};if(!w)if(p&&H!=="none"){let N=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),H==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${N}ms`),x&&L(x,!1);else if(g.classList.add(`persona-tool-loading-${H}`),g.style.setProperty("--persona-tool-anim-duration",`${N}ms`),H==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),x)L(x,!0);else{let X=g.textContent||d;g.textContent="",wr(g,X,0)}}else x&&L(x,!1);let P=null;if(i){P=S("div","persona-flex persona-items-center");let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",X=ce(l?"chevron-up":"chevron-down",16,N,2);X?P.appendChild(X):P.textContent=l?"Hide":"Show";let de=S("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(P),f.append(y,de)}else f.append(y);let D=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!l&&p&&s.activePreview&&u){let N=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:u,isActive:p,config:t??{}});ZT(D,N)||(D.textContent=u),D.style.display=""}if(!l&&p&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(f,D),r;let q=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=l?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let N=S("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?N.style.color=o.contentTextColor:o.headerTextColor&&(N.style.color=o.headerTextColor),N.textContent=n.name,q.appendChild(N)}if(n.args!==void 0){let N=S("div","persona-space-y-1"),X=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Arguments";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",gg(de,o),de.textContent=mr(n.args),N.append(X,de),q.appendChild(N)}if(n.chunks&&n.chunks.length){let N=S("div","persona-space-y-1"),X=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Activity";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",gg(de,o),de.textContent=n.chunks.join(""),N.append(X,de),q.appendChild(N)}if(n.status==="complete"&&n.result!==void 0){let N=S("div","persona-space-y-1"),X=S("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Result";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",gg(de,o),de.textContent=mr(n.result),N.append(X,de),q.appendChild(N)}if(n.status==="complete"&&typeof n.duration=="number"){let N=S("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(N.style.color=o.contentTextColor),N.textContent=`Duration: ${n.duration}ms`,q.appendChild(N)}return(()=>{if(f.setAttribute("aria-expanded",l?"true":"false"),P){P.innerHTML="";let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",X=ce(l?"chevron-up":"chevron-down",16,N,2);X?P.appendChild(X):P.textContent=l?"Hide":"Show"}q.style.display=l?"":"none",D.style.display=l?"none":D.textContent||D.childNodes.length?"":"none"})(),r.append(f,D,q),r};var gs=new Map,wd=e=>{let n=(e.startsWith(no)?e.slice(no.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Zv=e=>e?.approval!==!1?e?.approval:void 0,eC=(e,t)=>{let n=Zv(t)?.detailsDisplay??"collapsed";return gs.get(e)??n==="expanded"},tC=(e,t,n)=>{let o=Zv(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=ce(t?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},nC=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=eC(e,n);tC(o,s,n),r.style.display=s?"":"none"};var Sd=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=S("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let i=S("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=S("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",u=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",p=ce(d,20,u,2);p&&l.appendChild(p);let f=S("div","persona-flex-1 persona-min-w-0"),y=S("div","persona-flex persona-items-center persona-gap-2"),g=S("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",y.appendChild(g),!r){let P=S("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");P.setAttribute("data-approval-status",n.status),n.status==="approved"?(P.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",P.style.color="var(--persona-palette-colors-success-700, #15803d)",P.textContent="Approved"):n.status==="denied"?(P.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",P.style.color="var(--persona-palette-colors-error-700, #b91c1c)",P.textContent="Denied"):n.status==="timeout"&&(P.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",P.style.color="var(--persona-palette-colors-warning-700, #b45309)",P.textContent="Timeout"),y.appendChild(P)}f.appendChild(y);let v=n.toolType==="webmcp"||n.toolName.startsWith(no)?fi(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),H=!n.toolName,k=E||(H?n.description:`The assistant wants to use \u201C${v??wd(n.toolName)}\u201D.`),M=S("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(M.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(M.style.color=o.descriptionColor),M.textContent=k,f.appendChild(M),n.reason){let P=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");P.setAttribute("data-approval-reason","true"),o?.reasonColor?P.style.color=o.reasonColor:o?.descriptionColor&&(P.style.color=o.descriptionColor);let D=S("span","persona-font-medium");D.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,P.appendChild(D),P.appendChild(document.createTextNode(n.reason)),f.appendChild(P)}let x=o?.detailsDisplay??"collapsed",w=!!n.description&&!H,L=w||!!n.parameters;if(x!=="hidden"&&L){let P=eC(e.id,t),D=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");D.type="button",D.setAttribute("data-expand-header","true"),D.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(D.style.color=o.descriptionColor);let q=S("span");q.setAttribute("data-approval-details-label","true");let $=S("span","persona-inline-flex persona-items-center");$.setAttribute("data-approval-details-chevron","true"),D.append(q,$),tC(D,P,t),f.appendChild(D);let N=S("div");if(N.setAttribute("data-approval-details","true"),N.style.display=P?"":"none",w){let X=S("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(X.style.color=o.descriptionColor),X.textContent=n.description,N.appendChild(X)}if(n.parameters){let X=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?.parameterBackgroundColor&&(X.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(X.style.color=o.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=mr(n.parameters),N.appendChild(X)}f.appendChild(N)}if(r){let P=S("div","persona-flex persona-gap-2 persona-mt-2");P.setAttribute("data-approval-buttons","true");let D=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");D.type="button",D.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",D.style.color=o?.approveButtonTextColor??"#ffffff",D.setAttribute("data-approval-action","approve");let q=ce("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",D.appendChild(q));let $=document.createTextNode(o?.approveLabel??"Approve");D.appendChild($);let N=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");N.type="button",N.style.backgroundColor=o?.denyButtonColor??"transparent",N.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",N.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,N.setAttribute("data-approval-action","deny");let X=ce("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",N.appendChild(X));let de=document.createTextNode(o?.denyLabel??"Deny");N.appendChild(de),P.append(D,N),f.appendChild(P)}return i.append(l,f),s.appendChild(i),s};function nE(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function oC(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:d=2147483e3,onOpen:u,onDismiss:p}=e,f=e.container??nE(t),y=!1,g=null,b=()=>{if(!y)return;let H=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${H.width}px`),i&&(n.style.maxWidth=`${H.width}px`);let k=n.getBoundingClientRect(),M=l?.()??null,x=M!=null?H.top+M:H.top,w=o==="top-start"||o==="top-end"?x-r-k.height:H.bottom+r,P=o==="bottom-end"||o==="top-end"?H.right-k.width:H.left,D=i?.()??null;if(D!=null){let q=Math.max(H.left,H.right-k.width);P=Math.min(Math.max(H.left+D,H.left),q)}n.style.top=`${w}px`,n.style.left=`${P}px`},v=()=>{y&&(y=!1,g&&(g(),g=null),n.remove())},E=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),f.appendChild(n),b();let H=(t.ownerDocument??document).defaultView??window,k=t.ownerDocument??document,M=()=>{if(!t.isConnected){v(),p?.("anchor-removed");return}b()},x=L=>{let P=typeof L.composedPath=="function"?L.composedPath():[];P.includes(n)||P.includes(t)||(v(),p?.("outside"))},w=H.setTimeout(()=>{k.addEventListener("pointerdown",x,!0)},0);H.addEventListener("scroll",M,!0),H.addEventListener("resize",M),g=()=>{H.clearTimeout(w),k.removeEventListener("pointerdown",x,!0),H.removeEventListener("scroll",M,!0),H.removeEventListener("resize",M)},u?.()};return{get isOpen(){return y},open:E,close:v,toggle:()=>y?v():E(),reposition:b,destroy:v}}function rC(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var oE=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),sC=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},hs=(e,t)=>{sC(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},rE=e=>e?.approval!==!1?e?.approval:void 0,sE=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return gs.get(e)??n==="expanded"},yg=e=>{let t=S("span","persona-approval-kbd");return t.textContent=e,t},aE=(e,t)=>{let n=S("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(no)?fi(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let i=r??wd(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=i,n.appendChild(d),l){n.append(" from ");let u=document.createElement("strong");u.textContent=l,n.appendChild(u)}return n},iE=e=>{let t=S("div","persona-approval-resolved"),n=ce("ban",15,"currentColor",2);n&&t.appendChild(n);let o=S("span","persona-approval-resolved-name");return o.textContent=e.toolName?wd(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},lE=(e,t,n,o,r,s,i)=>{let l=S("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"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",u=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",f=u||p,y=f&&sE(t.id,o),g=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",v=S("button","persona-approval-head");v.type="button",f?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",y?"true":"false"),v.setAttribute("aria-label",y?b:g)):v.setAttribute("data-static","true");let E=S("span","persona-approval-logo"),H=ce("shield-check",16,"currentColor",2);H&&E.appendChild(H),v.appendChild(E);let k=aE(n,o);if(f){let D=S("span","persona-approval-toggle");D.setAttribute("aria-hidden","true");let q=ce("chevron-down",14,"currentColor",2);q&&D.appendChild(q),k.append(" "),k.appendChild(D)}v.appendChild(k),l.appendChild(v);let M=S("div","persona-approval-body");if(f){let D=S("div","persona-approval-details");if(D.setAttribute("data-role","params"),D.hidden=!y,u){let q=S("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,D.appendChild(q)}if(p){let q=S("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=mr(n.parameters),D.appendChild(q)}M.appendChild(D)}if(n.reason){let D=S("p","persona-approval-reason");o?.reasonColor?D.style.color=o.reasonColor:o?.descriptionColor&&(D.style.color=o.descriptionColor);let q=S("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,D.append(q,document.createTextNode(n.reason)),M.appendChild(D)}let x=S("div","persona-approval-actions"),w=null,L=D=>{o?.approveButtonColor&&(D.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(D.style.color=o.approveButtonTextColor)},P=S("button","persona-approval-deny");if(P.type="button",P.setAttribute("data-action","deny"),o?.denyButtonColor&&(P.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(P.style.color=o.denyButtonTextColor),P.append(o?.denyLabel??"Deny"),i){let D=S("div","persona-approval-split"),q=S("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),L(q),q.append(o?.approveLabel??"Always allow",yg("\u23CE"));let $=S("button","persona-approval-caret");$.type="button",$.setAttribute("data-action","toggle-menu"),$.setAttribute("aria-label","More options"),L($);let N=ce("chevron-down",15,"currentColor",2);N&&$.appendChild(N),D.append(q,$),x.append(D,P),P.append(yg("Esc"));let X=S("div","persona-approval-menu"),de=S("button","persona-approval-menu-item");de.type="button",de.append("Allow once",yg("\u2318\u23CE")),X.appendChild(de),w=oC({anchor:D,content:X,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,w),de.addEventListener("click",()=>{hs(e,t.id),r()})}else{let D=S("button","persona-approval-primary persona-approval-primary--solo");D.type="button",D.setAttribute("data-action","allow"),L(D),D.append(o?.approveLabel??"Allow"),x.append(D,P)}return M.appendChild(x),l.appendChild(M),l.addEventListener("click",D=>{let q=D.target instanceof Element?D.target.closest("[data-action]"):null;if(!q)return;let $=q.getAttribute("data-action");if($==="toggle-params"){let N=l.querySelector('[data-role="params"]');if(N){let X=N.hidden;N.hidden=!X,v.setAttribute("aria-expanded",X?"true":"false"),v.setAttribute("aria-label",X?b:g),gs.set(t.id,X)}return}if($==="toggle-menu"){w?.toggle();return}if($==="always"){hs(e,t.id),r({remember:!0});return}if($==="allow"){hs(e,t.id),r();return}if($==="deny"){hs(e,t.id),s();return}}),l},aC=()=>{let e=oE();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:i})=>{let l=o?.approval;if(!l)return null;let d=rE(i);if(l.status!=="pending"){if(hs(e,o.id),l.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return iE(l)}sC(e,o.id);let u=d?.enableAlwaysAllow===!0,p=lE(e,o,l,d,r,s,u);if(u){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=y=>{rC(y)||o.id===e.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),hs(e,o.id),y.key==="Escape"?s():y.metaKey||y.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])hs(e,o);e.latestPendingApprovalId=null}}};var Vi=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}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 n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)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,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.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 zi=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(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 r of t)o.put(r)}catch{}}};var cE=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),dE=new Set(["step_start","execution_start"]),pE=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),uE=new Set(["step_complete","agent_turn_complete"]),fE=new Set(["flow_complete","agent_complete"]),iC=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),cC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ys=(e,t)=>{let n=e[t];return cC(n)?n:void 0};function bg(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ad(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function mE(e,t){return typeof t.type=="string"?t.type:e}function gE(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 hE(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 lC(e){let t=ys(e,"result"),n=[ys(e,"tokens"),ys(e,"totalTokens"),t?ys(t,"tokens"):void 0,ys(e,"usage"),t?ys(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=Bn(o.output)??Bn(o.outputTokens)??Bn(o.completionTokens);if(r!==void 0)return r}return Bn(e.outputTokens)??Bn(e.completionTokens)??(t?Bn(t.outputTokens)??Bn(t.completionTokens):void 0)}function yE(e){let t=ys(e,"result");return Bn(e.executionTime)??Bn(e.executionTimeMs)??Bn(e.execution_time)??Bn(e.duration)??(t?Bn(t.executionTime)??Bn(t.executionTimeMs):void 0)}function bE(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ji=class{constructor(t=bE){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 n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ad(this.metric.outputTokens,n)}}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,n){if(!cC(n)){iC.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=mE(t,n),r=this.now();if(cE.has(o)){this.startRun(r);return}if(dE.has(o)){this.run||this.startRun(r);return}if(pE.has(o)){if(!hE(o,n))return;let s=gE(n);if(!s)return;this.run||this.startRun(r);let i=this.run;i.firstDeltaAt??(i.firstDeltaAt=r),i.visibleCharCount+=s.length;let l=i.exactOutputTokens+bg(i.visibleCharCount),d=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ad(l,d),outputTokens:l,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(uE.has(o)){if(!this.run)return;let s=this.run,i=lC(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+bg(s.visibleCharCount),u=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ad(d,u),outputTokens:d,durationMs:u,source:l?"usage":"estimate"};return}if(fE.has(o)){if(!this.run)return;let s=this.run,i=lC(n),l=i??s.exactOutputTokens+bg(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ad(l,u),outputTokens:l,durationMs:u,source:d},this.run=null;return}if(iC.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:yE(n)??o-t.startedAt}};var{setLoader:xE,load:vE}=fo({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),dC=xE,pC=vE;function uC(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},d=f=>{let y=f;return s.findIndex(g=>g===y||g.contains(y))},u=f=>{let y=d(f.target);if(y<0)return;let g=y;if(f.key===r)g=Math.min(y+1,s.length-1);else if(f.key===o)g=Math.max(y-1,0);else if(f.key==="Home")g=0;else if(f.key==="End")g=s.length-1;else return;f.preventDefault(),g!==y&&t.onSelect(g)},p=f=>{let y=d(f.target);y>=0&&l(s[y])};return e.addEventListener("keydown",u),e.addEventListener("focusin",p),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(f,y){if(s=f,f.forEach((g,b)=>{g.setAttribute("role","tab");let v=b===y;g.setAttribute("aria-selected",v?"true":"false"),g.tabIndex=v||y<0&&b===0?0:-1}),i){let g=(y>=0?f[y]:void 0)??f[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",u),e.removeEventListener("focusin",p)}}}function fC(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),u=T=>({start:T===!1?!1:typeof T=="object"&&T?T.start!==!1:!0,end:T===!1?!1:typeof T=="object"&&T?T.end!==!1:!0}),{start:p,end:f}=u(n?.tabFade),y=typeof document<"u"?S("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{y?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),N?.closeMenu()};y&&y.addEventListener("click",()=>{g(),t.onDismiss?.()});let b=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");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let v=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");v.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&v.classList.add("persona-artifact-toolbar-document");let E=S("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=s;let H=Tt({icon:"x",label:i});H.addEventListener("click",()=>{g(),t.onDismiss?.()});let k="rendered",M=da({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:T=>{k=T==="source"?"source":"rendered",U()}}),x=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=n?.documentToolbarShowCopyLabel===!0,L=n?.documentToolbarShowCopyChevron===!0,P=n?.documentToolbarCopyMenuItems,D=!!(L&&P&&P.length>0),q=null,$,N=null;if(r&&(w||L)&&!D){if($=w?Vo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let T=ce("chevron-down",14,"currentColor",2);T&&$.appendChild(T)}}else r&&D?(N=ed({label:"Copy",icon:"copy",iconSize:14,iconOnly:!w,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(P??[]).map(T=>({id:T.id,label:T.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:T=>{Ee(T)}}),q=N.element,$=N.primaryButton):r?$=Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):($=Tt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&$.classList.add("persona-hidden"));let X=r?Tt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Tt({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||X.classList.add("persona-hidden");let de=r?Tt({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Tt({icon:"x",label:i}),me=Tt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&me.classList.add("persona-hidden");let xe=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ye=e.features?.artifacts?.toolbarActions??[],ne=()=>{let T=Me.find(G=>G.id===Ke)??Me[Me.length-1],B=T?.id??null,W=T?.artifactType==="markdown"?T.markdown??"":"",O=T?JSON.stringify({component:T.component,props:T.props},null,2):"",{filename:Y,mime:Q,content:K}=Yc({title:T?.title,markdown:T?.markdown??"",file:T?.file});return{markdown:W,jsonPayload:O,id:B,file:T?.file,suggestedFilename:Y,mime:Q,content:K}},ie=()=>{let{suggestedFilename:T,mime:B,content:W}=ne();W&&Jc({filename:T,mime:B,content:W})},le=T=>{let{id:B,...W}=ne();return{actionId:T,artifactId:B,...W}},I=async()=>{let T=Me.find(B=>B.id===Ke)??Me[Me.length-1];try{return await navigator.clipboard.writeText(Wi(T)),!0}catch{return!1}},Z=null,pe=()=>{Z?.();let T=$.querySelector("svg"),B=Number(T?.getAttribute("width"))||16,W=ce("check",B,"currentColor",2);if(!T||!W)return;T.replaceWith(W);let O=$.querySelector("span");O&&(O.textContent="Copied");let Y=setTimeout(()=>Z?.(),2e3);Z=()=>{clearTimeout(Y),W.replaceWith(T),O&&(O.textContent="Copy"),Z=null}};$.addEventListener("click",async()=>{let T=n?.onDocumentToolbarCopyMenuSelect;if(T&&D){try{if(await T(le("primary"))===!1){await I()&&pe();return}pe()}catch{}return}await I()&&pe()});async function Ee(T){let B=n?.onDocumentToolbarCopyMenuSelect;try{if(B&&await B(le(T))!==!1)return;if(T==="download"){ie();return}let{markdown:W,jsonPayload:O}=ne();T==="markdown"||T==="md"?await navigator.clipboard.writeText(W):T==="json"||T==="source"?await navigator.clipboard.writeText(O):await navigator.clipboard.writeText(W||O),pe()}catch{}}X.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}U()}),de.addEventListener("click",()=>{g(),t.onDismiss?.()});let Ce=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");if(r)v.replaceChildren(),q?x.append(q,X,de):x.append($,X,de),x.insertBefore(xe,de),x.insertBefore(me,de),v.append(M.element,Ce,x);else{let T=S("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");T.append($,xe,me,H),v.appendChild(E),v.appendChild(T)}l&&(v.style.paddingLeft=l,v.style.paddingRight=l);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");d&&we.style.setProperty("--persona-artifact-tab-fade-size",d);let Pe=e.features?.artifacts?.renderTabBar,Re=S("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),nt=uC(we,{onSelect:T=>t.onSelect(Me[T].id)}),Je=T=>{let B=T.scrollWidth-T.clientWidth,W=B>1,O=Math.abs(T.scrollLeft);T.classList.toggle("persona-artifact-tab-fade-start",p&&W&&O>1),T.classList.toggle("persona-artifact-tab-fade-end",f&&W&&O<B-1)},Be=0,ot=()=>{if(Be)return;let T=()=>{Be=0,Je(we)};Be=typeof requestAnimationFrame=="function"?requestAnimationFrame(T):setTimeout(T,0)};we.addEventListener("scroll",()=>ot(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Je(we)).observe(we);let vt=S("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),yt=()=>{vt.scrollLeft=0},Dn=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(yt):setTimeout(yt,0)};if(l){for(let T of[we,Re])T.style.paddingLeft=l,T.style.paddingRight=l;vt.style.padding=l}b.appendChild(v),b.appendChild(we),b.appendChild(Re),b.appendChild(vt);let Me=[],Ke=null,rt=!1,Kt=!1,zt=!0,Xn=!1,Ye=null,Qe="",bt=null,en=!1,wo=T=>T.artifactType==="markdown"&&!!T.file||r?k:"rendered",It=T=>{r||(T&&!en?(v.insertBefore(M.element,E),en=!0):!T&&en&&(M.element.remove(),en=!1))},Ko=()=>Ke&&Me.find(T=>T.id===Ke)||Me[Me.length-1],Cs=()=>{let T=Ri(Ko());if(!T){xe.replaceChildren();return}let B=ye.filter(W=>W.visible===void 0||W.visible(T)).map(W=>pa(W,{documentChrome:r,onClick:()=>{let O=Ri(Ko());if(O)try{Promise.resolve(W.onClick(O)).catch(()=>{})}catch{}}}));xe.replaceChildren(...B)},U=()=>{Cs();let T=r&&Me.length<=1,B=!!Pe;if(we.classList.toggle("persona-hidden",T||B),Re.classList.toggle("persona-hidden",T||!B),B&&Pe){let Y=Me.map(Q=>Q.id).join("|")+" "+(Ke??"");if(Y!==Qe){Qe=Y;let Q=Pe({records:Me,selectedId:Ke,onSelect:t.onSelect});Re.firstElementChild!==Q&&Re.replaceChildren(Q)}}else{nt.beforeRender(),we.replaceChildren();let Y=[],Q=-1;for(let[K,G]of Me.entries()){let ae=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");ae.type="button";let it=G.artifactType==="markdown"?G.file:void 0,et=it?bo(it.path):G.title||G.id.slice(0,8),xt=it?.path||G.title||et;ae.textContent=et,ae.title=xt,ae.setAttribute("aria-label",xt),G.id===Ke&&(ae.classList.add("persona-bg-persona-container","persona-border-persona-border"),Q=K),ae.addEventListener("click",()=>t.onSelect(G.id)),we.appendChild(ae),Y.push(ae)}if(nt.render(Y,Q),Q>=0&&Ke!==Ye){Ye=Ke;let K=Y[Q];typeof K.scrollIntoView=="function"&&K.scrollIntoView({block:"nearest",inline:"nearest"})}Je(we)}let W=Ke&&Me.find(Y=>Y.id===Ke)||Me[Me.length-1];if(!W){vt.replaceChildren(),bt?.destroy(),bt=null,It(!1);return}let O=W.artifactType==="markdown"?W.file:void 0;if(It(!!O&&as(O)!=="other"),r){let Y=O?Cr(O):W.artifactType==="markdown"?"MD":W.component??"Component",Q=(W.title||"Document").trim(),K=O?bo(O.path):Q.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ce.textContent=`${K} \xB7 ${Y}`}else E.textContent=O?bo(O.path):s;bt?(bt.el.parentElement!==vt&&vt.replaceChildren(bt.el),bt.update(W)):(bt=rd(W,{config:e,resolveViewMode:wo}),vt.replaceChildren(bt.el)),vt.classList.toggle("persona-artifact-content-flush",!!vt.querySelector(".persona-code-pre"))},ee=()=>{let T=Me.length>0;if(b.classList.toggle("persona-hidden",!T),y){let O=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;T&&O&&rt?(y.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},A=()=>{Xn=!1,U(),ee()};return{element:b,backdrop:y,update(T){let B=T.selectedId??T.artifacts[T.artifacts.length-1]?.id??null,W=B!==Ke;Me=T.artifacts,Ke=B,Me.length>0&&(rt=!0),Xn=!0,zt&&A(),W&&yt()},setMobileOpen(T){rt=T,!T&&y?(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ee()},setExpanded(T){T!==Kt&&(Kt=T,Dn());let B=ce(T?"minimize":"maximize",16,"currentColor",2);B&&me.replaceChildren(B);let W=T?"Collapse artifacts panel":"Expand artifacts panel";me.setAttribute("aria-label",W),me.title=W},setExpandToggleVisible(T){me.classList.toggle("persona-hidden",!T)},setCopyButtonVisible(T){r||$.classList.toggle("persona-hidden",!T)},setRefreshButtonVisible(T){X.classList.toggle("persona-hidden",!T)},setCustomActions(T){ye=T,Cs()},setTabFade(T){let B=u(T);B.start===p&&B.end===f||(p=B.start,f=B.end,Je(we))},setRenderTabBar(T){T!==Pe&&(Pe=T,Qe="",U())},setVisible(T){T!==zt&&(zt=T,T&&Xn&&A())},destroy(){bt?.destroy(),bt=null}}}function gn(e){return e?.features?.artifacts?.enabled===!0}function mC(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"),!gn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function CE(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 gC=["panel","seamless","detached"];function xg(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&gC.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function vg(e){return!e||!gn(e)?!1:xg(e)==="detached"}function $i(e,t){if(!gn(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-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),CE(e),mC(e,t);return}let n=t.features?.artifacts?.layout,o=xg(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of i){let u=l?.trim();u?e.style.setProperty(d,u):e.style.removeProperty(d)}mC(e,t)}function Gi(e,t){for(let l of gC)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"),!gn(t))return;let n=t.features?.artifacts?.layout,o=xg(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function hC(e,t){return!t||!gn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var wE=new Set(["__proto__","prototype","constructor"]),SE=new Set(["collapsed","card","panel","inline"]),yC=new Set(["markdown","component"]),AE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,bs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Td=e=>!wE.has(e),Cg=e=>typeof e=="string"&&SE.has(e),xs=e=>Object.keys(e).length>0;function vo(e,t,n,o){e.push({path:t,code:n,message:o})}var ME="Ignored because this key is not part of the persisted preference schema.",Md="Ignored an unsupported value.",TE="Expected collapsed, panel, or inline.",EE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',bC={kind:"mode",message:Md},va={kind:"string",message:"Expected a CSS length string."},$o={kind:"boolean"},kE={paneWidth:va,paneMaxWidth:va,paneMinWidth:va,expandedPanelWidth:va,resizableMinWidth:va,resizableMaxWidth:va,expandLauncherPanelWhenOpen:$o,resizable:$o},PE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:$o,showReasoning:$o,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Md},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Md},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Md},expandable:$o,grouped:$o}},reasoningDisplay:{kind:"object",children:{expandable:$o,activePreview:$o}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:bC,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:bC,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:yC,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:yC}}},filePreview:{kind:"object",children:{enabled:$o}},layout:{kind:"object",children:kE}}}}};function xC(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:vo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:vo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:vo(o,n,"invalid_value",t.message);case"mode":return Cg(e)?wn(e):vo(o,n,"invalid_value",t.message);case"modeMap":{if(!bs(e))return vo(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let d=r?i:lr(i);Td(i)&&(r?r.has(i):AE.test(d))?Cg(l)?s[d]=wn(l):vo(o,`${n}.${i}`,"invalid_value",TE):vo(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":EE)}return xs(s)?s:void 0}case"object":{if(t.bareMode&&Cg(e))return wn(e);if(!bs(e))return vo(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Td(l)||!r.includes(l))&&vo(o,s(l),"unknown_key",ME);let i={};for(let l of r){let d=t.children[l],u=xC(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&vo(o,s(l),"deprecated_key",d.deprecated),u===void 0)continue;let p=d.alias??l,f=i[p];i[p]=bs(f)&&bs(u)?{...f,...u}:u}return xs(i)?i:void 0}}}function wg(e){let t=[];return{preferences:(e===null?void 0:xC(e,PE,"",t))??{},issues:t}}function Ca(e){if(Array.isArray(e))return e.map(Ca);if(!bs(e))return e;let t={};for(let[n,o]of Object.entries(e))Td(n)&&o!==void 0&&(t[n]=Ca(o));return t}function vC(e,t){let n=Ca(e);for(let[o,r]of Object.entries(t)){if(!Td(o)||r===void 0)continue;let s=n[o];n[o]=bs(s)&&bs(r)?vC(s,r):Ca(r)}return n}function LE(e){let t={},n;for(let r of e){let s=wg(r).preferences;n=CC(n,s.artifacts?.display),t=vC(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function HE(e,t){if(t===void 0)return e===void 0?void 0:Ca(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...xs(r)?{byMediaType:r}:{}};return xs(s)?s:void 0}function CC(e,t){if(t===void 0)return e===void 0?void 0:Ca(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=HE(n.files,t.files),i={...o?{default:o}:{},...xs(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return xs(i)?i:void 0}function Sg(e={},t){let n=LE(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=CC(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Ki(e){let t=e.preferences;return!t||!xs(t)?e:{...e,features:Sg(e.features??{},[t])}}function RE(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function IE(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 WE(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function BE(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Ag(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function wC(e,t,n,o,r,s,i=200){let l=RE(r,200),d=BE(t,n,o,i);d=Math.max(l,d);let u=IE(s);return u!==null&&(d=Math.min(d,u)),WE(e,l,d)}var SC={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"}},Mg=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=SC[i]??SC.init;s.classList.add("persona-form-card","persona-space-y-4");let d=S("div","persona-space-y-1"),u=S("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(u.textContent=l.title,d.appendChild(u),l.description){let b=S("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,d.appendChild(b)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let v=S("label","persona-form-field persona-flex persona-flex-col persona-gap-1");v.htmlFor=`${t.id}-${i}-${b.name}`;let E=S("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=b.label,v.appendChild(E);let H=b.type??"text",k;H==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=H),k.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",k.id=`${t.id}-${i}-${b.name}`,k.name=b.name,k.placeholder=b.placeholder??"",b.required&&(k.required=!0),v.appendChild(k),p.appendChild(v)});let f=S("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=S("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=l.submitLabel??"Submit",f.appendChild(y),f.appendChild(g),p.appendChild(f),s.replaceChildren(d,p),p.addEventListener("submit",async b=>{b.preventDefault();let v=n.formEndpoint??"/form",E=new FormData(p),H={};E.forEach((k,M)=>{H[M]=k}),H.type=i,g.disabled=!0,y.textContent="Submitting\u2026";try{let k=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let M=await k.json();y.textContent=M.message??"Thanks! We'll be in touch soon.",M.success&&M.nextPrompt&&await o.sendMessage(String(M.nextPrompt))}catch(k){y.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Tg=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 n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Xi=new Tg;var AC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),DE=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),MC=(e,t,n)=>{if(!AC(e)||!AC(t)||DE.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=MC(e[r],t[r],s)}return o};function Ed(e,t){let n=MC(e,t,"");return aa(n)}var TC=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var OE=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},FE=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Yi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=OE(e),n=FE(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Eg=e=>typeof e=="string"?e:e==null?"":String(e),vs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Eg(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Eg(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Eg(n.text)}}},EC=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ji=e=>{let t=new Set(EC(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(EC(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.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=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let d={action:l,message:s.message};e.emit("action:detected",d);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",d)},f=u(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let y=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:y,resubmit:f.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var NE=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}},_E=e=>e.map(t=>({...t,streaming:!1})),UE=e=>e.map(t=>({...t,status:"complete"})),kd=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?NE(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?_E(n.messages):void 0,artifacts:n.artifacts?UE(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var qE=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},kC=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return qE(e)},VE=async(e,t)=>{let n=await kC(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await kC(`${e}\0${t}`)}`}};var PC=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,d=0,u=null,p=null,f=new Set,y=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},g=()=>{let L=y();if(!L)return u;try{return L.getItem(o)}catch{return i=!0,u}},b=(L,P)=>{if(l||L===u)return;let D=u;u=L,d+=1;let q={previousToken:D,token:L,source:P,revision:d};for(let $ of f)$(q)},v=L=>{l||L.key!==null&&L.key!==o||b(L.key===null?null:L.newValue??null,"external")},E=(async()=>{let L=await VE(e,t);o=L.storageKey,r=L.leaseKey,s=L.lockName,u=g(),!n&&typeof window<"u"&&window.addEventListener("storage",v)})(),H=L=>new Promise(P=>setTimeout(P,L)),k=()=>{let L=y();if(!L)return null;try{let P=L.getItem(r);if(!P)return null;let D=JSON.parse(P);return typeof D?.expiresAt=="number"&&typeof D?.ownerNonce=="string"?D:null}catch{return null}},M=L=>{let P=y();if(P)try{k()?.ownerNonce===L&&P.removeItem(r)}catch{}},x=L=>new Promise(P=>{let D=setTimeout(q,L);function q(){clearTimeout(D),window.removeEventListener("storage",$),P()}function $(N){(N.key===null||N.key===r)&&q()}window.addEventListener("storage",$)}),w=async L=>{let P=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,D=Date.now()+15e3;for(;Date.now()<D;){let q=y();if(!q)break;let $=Date.now(),N=k();if(N&&N.expiresAt>$&&N.ownerNonce!==P){await x(Math.min(N.expiresAt-$,500));continue}try{q.setItem(r,JSON.stringify({ownerNonce:P,expiresAt:$+1e4}))}catch{i=!0;break}if(await H(20+Math.random()*40),k()?.ownerNonce!==P){await x(500);continue}p=P;try{return await L()}finally{p=null,M(P)}}return L()};return{ready:E,async get(){return await E,b(g(),"external"),u},async set(L){await E;let P=y();if(P)try{P.setItem(o,L)}catch{i=!0}b(L,"local")},async clear(){await E;let L=y();if(L)try{L.removeItem(o)}catch{i=!0}b(null,"local")},revision(){return d},subscribe(L){return f.add(L),()=>{f.delete(L)}},async withFirstInitLock(L){await E;let P=globalThis.navigator?.locks;return P?.request?P.request(s,()=>L()):y()?w(L):L()},matches(L,P,D){return L===e&&P===t&&D===n},destroy(){l=!0,f.clear(),typeof window<"u"&&window.removeEventListener("storage",v),p&&M(p)}}};var{setLoader:zE,load:jE}=fo({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),LC=zE,kg=jE;var Pg=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Go=e=>Object.freeze({...e}),HC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),RC=e=>e?Go(e):null;function IC(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,d=[],u=()=>{for(let x of d.splice(0))try{x()}catch(w){Pg("renderHistoryView cleanup",w)}},p=(x,w)=>{for(let L of t){let P=L[x];if(P)try{let D=P(w);if(D)return D}catch(D){Pg(x,D)}}return null},f=()=>({presentation:e.getPresentation(),config:n}),y={header:x=>i?p("renderHistoryHeader",Object.freeze({...f(),returnSurface:e.getReturnSurface(),identityStatus:Go(x.identityStatus),pendingAction:RC(x.pendingAction),copy:Go(x.copy),actions:Object.freeze({close:v.close,startNewConversation:v.startNewConversation}),defaultRenderer:x.defaultRenderer})):null,conversation:x=>i?p("renderHistoryConversation",Object.freeze({...f(),conversation:HC(x.conversation),active:x.active,pending:x.pending,open:x.open,requestDelete:x.requestDelete,defaultRenderer:x.defaultRenderer})):null,state:x=>i?p("renderHistoryState",Object.freeze({...f(),state:Go(x.state),identityStatus:Go(x.identityStatus),copy:Go(x.copy),...x.retry?{retry:x.retry}:{},...x.startNewConversation?{startNewConversation:x.startNewConversation}:{},defaultRenderer:x.defaultRenderer})):null},g=t.flatMap(x=>(x.railSections??[]).map(w=>({...w,placement:w.placement??"above-conversations",items:[],render:L=>w.render(Object.freeze({collapsed:L,presentation:e.getPresentation(),actions:v}))}))),b=e.createView({slots:y,renderDom:!1,onModelChange:()=>M(),railSections:g}),v=Object.freeze({...b.operations,close:e.close}),E=()=>(i=!0,b.setDomRenderEnabled(!0),b.element),H=x=>Object.freeze({conversations:Object.freeze(x.conversations.map(HC)),activeConversationId:x.activeConversationId,state:Go(x.state),pendingAction:RC(x.pendingAction),identityStatus:Go(x.identityStatus),nextCursor:x.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Go(b.copy),actions:v,defaultRenderer:E,requestRender:()=>M(),onCleanup:w=>{d.push(w)}}),k=()=>{i=!1;let x=null;for(let L of t)if(L.renderHistoryView){try{x=L.renderHistoryView(H(b.getModel()))}catch(P){Pg("renderHistoryView",P),x=null}if(x)break}let w=!x||x.contains(b.element);return i=w,b.setDomRenderEnabled(w),x??b.element};function M(){if(!(!s||o||r)){r=!0;try{u();let x=k();if(x===l)return;let w=l;l=x,e.onElementChanged(x,w)}finally{r=!1}}}return s=!0,M(),{view:b,get element(){return l??b.element},requestRender:M,dispose:()=>{o=!0,u()}}}var $E=null;function WC(){return $E}var GE=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),KE=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),Lg=e=>KE.get(e)??"Conversation history is unavailable right now.";function XE(e){if(e instanceof Gn)return e;if(e instanceof We){let t=GE.get(e.code)??"unavailable";return new Gn(t,Lg(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new Gn("unavailable",Lg("unavailable"))}function BC(e){let t=()=>e.getClient?.()??e.client,n=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new Gn("unsupported_scope",Lg("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(u){throw XE(u)}},i=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await e.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return t().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return t().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await t().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let u=await t().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),p=ix(u.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:u.summary,messages:wi([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>i(await t().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>t().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>t().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var YE=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],DC={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function Hg(e){if(!e)return DC;let t={...DC};for(let n of YE){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var JE="button:not([disabled])";function Pd(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=ue("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=ue("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=ue("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},ue("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),ue("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),ue("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,i));for(let u of[s,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let d=ue("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(u=>{let p=!1,f=g=>{p||(p=!0,d.removeEventListener("keydown",y,!0),d.remove(),t?.focus(),u(g))};function y(g){if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),f(!1);return}if(g.key!=="Tab")return;let b=Array.from(l.querySelectorAll(JE));if(b.length===0)return;let v=b[0],E=b[b.length-1],H=document.activeElement;g.shiftKey&&(H===v||!l.contains(H))?(g.preventDefault(),E.focus()):!g.shiftKey&&H===E&&(g.preventDefault(),v.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",g=>{g.target===d&&f(!1)}),s.addEventListener("click",()=>f(!1)),i.addEventListener("click",()=>f(!0)),e.host.appendChild(d),s.focus()})}var wa=uo(rc(),1);function QE(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function ZE(e,t){if(!QE(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Ld(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,wa.parse)(n,wa.STR|wa.OBJ),s=ZE(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function OC(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Hd(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=ro.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function FC(){let e=Ld();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function NC(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 Qi(e){let t=NC(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Rd(e){let t=NC(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var ek=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Id(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:u=ek}=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 f=null,y=document.createElement("div");y.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,g.appendChild(b);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,g.appendChild(v),y.appendChild(g);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let H=[];for(let L=1;L<=5;L++){let P=document.createElement("button");P.type="button",P.className="persona-feedback-rating-btn persona-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${u[L-1]}`),P.title=u[L-1],P.dataset.rating=String(L),P.innerHTML=`
|
|
46
46
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
47
47
|
<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>
|
|
48
48
|
</svg>
|
|
49
|
-
`,R.addEventListener("click",()=>{f=P,L.forEach((F,O)=>{let $=O<P;F.classList.toggle("selected",$),F.setAttribute("aria-checked",O===P-1?"true":"false")})}),L.push(R),T.appendChild(R)}g.appendChild(T);let A=null;if(p){let P=document.createElement("div");P.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"),P.appendChild(A),g.appendChild(P)}let S=document.createElement("div");S.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=l,C.addEventListener("click",()=>{n?.(),c.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=s,M.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let P=A?.value.trim()||void 0;await t(f,P),c.remove()}catch(P){M.disabled=!1,M.textContent=s,console.error("[CSAT Feedback] Failed to submit:",P)}}),S.appendChild(C),S.appendChild(M),g.appendChild(S),c.appendChild(g),c}function Kl(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="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,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,b.appendChild(w);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,b.appendChild(T),m.appendChild(b);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 S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=d;let C=document.createElement("span");C.className="persona-feedback-label-high",C.textContent=c,A.appendChild(S),A.appendChild(C);let M=document.createElement("div");M.className="persona-feedback-numbers";let P=[];for(let E=0;E<=10;E++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${E} out of 10`),G.textContent=String(E),G.dataset.rating=String(E),E<=6?G.classList.add("persona-feedback-detractor"):E<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{g=E,P.forEach((Q,Z)=>{Q.classList.toggle("selected",Z===E),Q.setAttribute("aria-checked",Z===E?"true":"false")})}),P.push(G),M.appendChild(G)}L.appendChild(A),L.appendChild(M),m.appendChild(L);let R=null;if(p){let E=document.createElement("div");E.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=a,R.rows=3,R.setAttribute("aria-label","Additional comments"),E.appendChild(R),m.appendChild(E)}let F=document.createElement("div");F.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=l,O.addEventListener("click",()=>{n?.(),f.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=s,$.addEventListener("click",async()=>{if(g===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let E=R?.value.trim()||void 0;await t(g,E),f.remove()}catch(E){$.disabled=!1,$.textContent=s,console.error("[NPS Feedback] Failed to submit:",E)}}),F.appendChild(O),F.appendChild($),m.appendChild(F),f.appendChild(m),f}var Ta="persona-chat-history",gS=30*1e3,hS=641,yS={"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 bS(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=yS[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Xl(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 xS(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 vS(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var cf=e=>!e||typeof e!="object"?{}:{...e},sb=e=>e.map(t=>({...t,streaming:!1})),ib=(e,t,n)=>{let o=e?.markdown?hr(e.markdown):null,r=ta(e?.sanitize);return e?.postprocessMessage&&r&&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&&n&&n())}let p=ao()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...a,text:s,raw:l??a.text??""});d=r?r(c):c}else if(o){let c=a.streaming?hg(s):s,f=o(c);d=r&&p?r(f):f}else d=Vn(s);return d}};function lb(e){let t=v("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 n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,s=ae(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=v("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var CS=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];n[o]=a?{...a,...r}:r}return n},wS=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:CS(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Jl=(e,t,n)=>{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=da(t),r=o.features;o=Hs(o);let a=Bs.getForInstance(o.plugins),s=!1,l=Ty(()=>o),{plugin:p,teardown:d}=Dy();o.components&&Nn.registerAll(o.components);let c=tb(),g=o.persistState===!1?null:o.storageAdapter??Vl(),m={},b=null,w=!1,T=i=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(i);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:x}=u;return x&&(w=!0),h}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return i};if(g?.load)try{let i=g.load();if(i&&typeof i.then=="function")b=i.then(u=>T(u??{messages:[],metadata:{}}));else{let h=T(i??{messages:[],metadata:{}});h.metadata&&(m=cf(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=T({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let L=()=>m,A=i=>{m=i({...m})??{},yc()},S=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ds],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dr.message,Dr.messageAndClick],M=Fs({parsers:S,handlers:C,getSessionMetadata:L,updateSessionMetadata:A,emit:c.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let P=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,F=o.autoFocusInput??!1,O=R,$=P,E=o.layout?.header?.layout,G=!1,Q=()=>Ko(o),Z=()=>P||Q(),J=Q()?!1:P?R:!0,fe=!1,ne=null,ge=()=>{fe=!0,ne&&clearTimeout(ne),ne=setTimeout(()=>{fe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),fe=!1)},1e4)},ie=ib(o,M,ge),ue=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,Se=o.features?.scrollToBottom??{},Ce=o.features?.scrollBehavior??{},ut=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Je=me?new Ps(ut):null,Qe=o.features?.eventStream?.maxEvents??2e3,Ne=me?new Ls(Qe,Je):null,_e=me?new Rs:null,Ae=null,Me=!1,qe=null,Jt=0;Je?.open().then(()=>Ne?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let gt={onCopy:i=>{c.emit("message:copy",i),q?.isClientTokenMode()&&q.submitMessageFeedback(i.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{c.emit("message:feedback",i),q?.isClientTokenMode()&&q.submitMessageFeedback(i.messageId,i.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(i)}},Bt=o.statusIndicator??{},Tn=i=>i==="idle"?Bt.idleText??Ht.idle:i==="connecting"?Bt.connectingText??Ht.connecting:i==="connected"?Bt.connectedText??Ht.connected:i==="error"?Bt.errorText??Ht.error:i==="paused"?Bt.pausedText??Ht.paused:i==="resuming"?Bt.resumingText??Ht.resuming:Ht[i];function En(i,u,h,x){if(x==="idle"&&h.idleLink){i.textContent="";let k=document.createElement("a");k.href=h.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=u,k.style.color="inherit",k.style.textDecoration="none",i.appendChild(k)}else i.textContent=u}let et=My({config:o,showClose:Z()}),{wrapper:Le,panel:he,pillRoot:tt}=et.shell,Te=et.panelElements,{container:be,body:re,messagesWrapper:xe,starterSuggestions:kn,transcriptSuggestions:ee,suggestions:I,textarea:B,sendButton:y,sendButtonWrapper:D,composerForm:H,statusText:N,welcomeHost:K,welcomeIconHolder:V,greetingHost:X,introTitle:ce,introSubtitle:Ve,closeButton:de,iconHolder:Pe,headerTitle:ze,headerSubtitle:Ue,header:We,footer:we,actionsRow:nt,rightActions:wt}=Te,yn=Te.leftActions,Us=Te.setSendButtonMode,te=Te.micButton,bn=Te.micButtonWrapper,it=Te.attachmentButton,xn=Te.attachmentButtonWrapper,Et=Te.attachmentInput,Ln=Te.attachmentPreviewsContainer;be.classList.add("persona-relative"),re.classList.add("persona-relative");let Gb=12,ka=()=>Se.label??"",Kb=()=>Se.iconName??"arrow-down",Xb=()=>Se.enabled!==!1,cn=()=>Ce.mode??"anchor-top",ho=()=>cn()==="follow"||cn()==="anchor-top"&&Oa,La=()=>Ce.anchorTopOffset??16,Jb=()=>Ce.restorePosition??"bottom",Mf=()=>Ce.pauseOnInteraction===!0,Tf=()=>Ce.showActivityWhilePinned!==!1,Ef=()=>Ce.announce===!0,ec=()=>Ce.scrollbar??"on-scroll",Pt=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let Pa=v("span","persona-flex persona-items-center"),tc=v("span",""),Jo=v("span","");Jo.setAttribute("data-persona-scroll-to-bottom-count",""),Jo.style.display="none",Pt.append(Pa,tc,Jo),be.appendChild(Pt);let vn=v("div","persona-stream-anchor-spacer");vn.setAttribute("aria-hidden","true"),vn.setAttribute("data-persona-anchor-spacer",""),vn.style.flexShrink="0",vn.style.pointerEvents="none",vn.style.height="0px",vn.style.display="none",re.appendChild(vn);let Qo=v("div","persona-sr-only");Qo.setAttribute("aria-live","polite"),Qo.setAttribute("aria-atomic","true"),Qo.setAttribute("role","status"),Qo.setAttribute("data-persona-live-region",""),Object.assign(Qo.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"}),be.appendChild(Qo);let Ra=null,qs=null,kf=i=>{!Ef()||!i||(qs=i,Ra===null&&(Ra=setTimeout(()=>{Ra=null,qs&&Ef()&&(Qo.textContent=qs),qs=null},400)))},Yo=()=>{let u=we.style.display==="none"?0:we.offsetHeight;Pt.style.bottom=`${u+Gb}px`};Yo();let Lf=()=>{let i=!!ka();Pt.setAttribute("aria-label",ka()||"Jump to latest"),Pt.title=ka(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Pa.innerHTML="";let u=ae(Kb(),"14px","currentColor",2);u?(Pa.appendChild(u),Pa.style.display=""):Pa.style.display="none",tc.textContent=ka(),tc.style.display=i?"":"none"};Lf();let bt=null,Qt=null,Pf=null,Rf=a.find(i=>i.renderHeader);if(Rf?.renderHeader){let i=Rf.renderHeader({config:o,defaultRenderer:()=>{let u=fo({config:o,showClose:Z()});return kr(be,u,o),u.header},onClose:()=>lt(!1,"user")});if(i){let u=be.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(i),We=i,et.header.element=i)}}let nc=()=>{if(!Ne)return;if(Me=!0,!Ae&&Ne&&(Ae=_y({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Ia(),config:o,plugins:a,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Ae&&(re.style.display="none",we.parentNode?.insertBefore(Ae.element,we),Ae.update()),Ye){Ye.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(h=>h&&Ye.classList.add(h))}let i=()=>{if(!Me)return;let u=Date.now();u-Jt>=200&&(Ae?.update(),Jt=u),qe=requestAnimationFrame(i)};Jt=0,qe=requestAnimationFrame(i),Vt(),c.emit("eventStream:opened",{timestamp:Date.now()})},Ia=()=>{if(Me){if(Me=!1,Ae&&Ae.element.remove(),re.style.display="",Ye){Ye.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(u=>u&&Ye.classList.remove(u))}qe!==null&&(cancelAnimationFrame(qe),qe=null),Vt(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Ye=null;if(me){let i=o.features?.eventStream?.classNames,u="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:"");Ye=v("button",u),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Xt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let h=ae("activity","18px","currentColor",1.5);h&&Ye.appendChild(h);let x=Te.clearChatButtonWrapper,k=Te.closeButtonWrapper,W=x||k;W&&W.parentNode===We?We.insertBefore(Ye,W):We.appendChild(Ye),Ye.addEventListener("click",()=>{Me?Ia():nc()})}let If=i=>{let u=o.attachments;if(!u?.enabled)return;let h=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!h){h=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let k=i.querySelector("[data-persona-composer-form]");k?.parentNode?k.parentNode.insertBefore(h,k):i.insertBefore(h,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let k=v("input");k.type="file",k.setAttribute("data-persona-composer-attachment-input",""),k.accept=(u.allowedTypes??co).join(","),k.multiple=(u.maxFiles??4)>1,k.style.display="none",k.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),i.appendChild(k)}},oc=a.find(i=>i.renderComposer),rc=!1,Wf=i=>{if(!oc?.renderComposer)return null;let u=o.composer,h=s?q.isStreaming():!1;return oc.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Gx(),storage:l(oc.id),onSubmit:x=>{if(!q||q.isStreaming())return;let k=x.trim(),W=bt?.hasAttachments()??!1;if(!k&&!W)return;Hm();let z;W&&(z=[],z.push(...bt.getContentParts()),k&&z.push(Oo(k))),q.sendMessage(k,{contentParts:z}),W&&bt.clearAttachments()},streaming:h,disabled:h,openAttachmentPicker:()=>{Et?.click()},models:u?.models,selectedModelId:u?.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Pf?.()}:void 0})},Hf=Wf(()=>Lr({config:o}).footer);Hf&&(et.replaceComposer(Hf),we=et.composer.footer,rc=!0);let Bf=i=>{let u=(...pe)=>{for(let le of pe){let ye=i.querySelector(le);if(ye)return ye}return null},h=i.querySelector("[data-persona-composer-form]"),x=i.querySelector("[data-persona-composer-input]"),k=i.querySelector("[data-persona-composer-submit]"),W=i.querySelector("[data-persona-composer-mic]"),z=i.querySelector("[data-persona-composer-status]");h&&(H=h),x&&(B=x),k&&(y=k),W&&(te=W,bn=W.parentElement),z&&(N=z);let U=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(I=U);let j=u("[data-persona-composer-attachment-button]",".persona-attachment-button");j&&(it=j,xn=j.parentElement),Et=u("[data-persona-composer-attachment-input]",'input[type="file"]'),Ln=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let Y=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");Y&&(nt=Y),yn=u(".persona-widget-composer__left-actions")};If(we),Bf(we);let Wa=qo(o,Q());Wa&&(xe.style.maxWidth=Wa,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",X.style.maxWidth=Wa,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%",kn.style.maxWidth=Wa,ee.style.maxWidth=Wa,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%");let Df=()=>{let i=qo(o,Q());if(!(!i||Q()))for(let u of[H,I,Ln,N])u&&(u.style.maxWidth=i,u.style.marginLeft="auto",u.style.marginRight="auto")};Df();let Ff=()=>{!o.attachments?.enabled||!Et||!Ln||(bt?bt.remountPreviews(Ln):(bt=Ar.fromConfig(o.attachments),bt.setPreviewsContainer(Ln)),Et.addEventListener("change",i=>{let u=i.target;bt?.handleFileSelect(u.files),u.value=""}),be.querySelector(".persona-attachment-drop-overlay")||be.appendChild(lb(o.attachments.dropOverlay)))};Ff();let Qb=()=>Qt?.prefetch(),Of=()=>{if(!(!o.contextMentions?.enabled||!B)&&(Qt=Ch({config:o,textarea:B,anchor:H??B,getMessages:()=>q.getMessages(),liveRegionHost:be}),Qt)){let i=B;i.parentElement?.insertBefore(Qt.contextRow,i);let u=Qt.affordanceButtons;for(let h=u.length-1;h>=0;h--){let x=u[h];yn?yn.insertBefore(x,yn.firstChild):H?.appendChild(x)}}};Of(),(()=>{let i=o.layout?.slots??{},u=x=>{switch(x){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return xe;case"footer-top":return I;case"composer":return H;case"footer-bottom":return N;default:return null}},h=(x,k)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")We.insertBefore(k,We.firstChild);else if(x==="header-right")We.appendChild(k);else{let W=We.querySelector(".persona-flex-col");W?W.parentNode?.insertBefore(k,W.nextSibling):We.appendChild(k)}break;case"body-top":{let W=re.querySelector("[data-persona-intro-card]");W?W.replaceWith(k):re.insertBefore(k,re.firstChild);break}case"body-bottom":re.appendChild(k);break;case"footer-top":I.replaceWith(k);break;case"footer-bottom":N.replaceWith(k);break;default:break}};for(let[x,k]of Object.entries(i))if(k)try{let W=k({config:o,defaultContent:()=>u(x)});W&&h(x,W)}catch(W){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,W)}})();let Nf=i=>{let h=i.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let k=x.getAttribute("data-message-id");if(!k)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")va.has(k)?va.delete(k):va.add(k),Ey(k,x);else if(W==="tool")Ca.has(k)?Ca.delete(k):Ca.add(k),ky(k,x,o);else if(W==="approval"){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",j=Rr.get(k)??U;Rr.set(k,!j),Iy(k,x,o)}ar.delete(k)};xe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),xe.addEventListener("keydown",i=>{let u=i.target;(i.key==="Enter"||i.key===" ")&&u.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),xe.addEventListener("copy",i=>{let{clipboardData:u}=i;if(!u)return;let h=xe.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let k=x.toString(),W=jh(k);!W||W===k||(u.setData("text/plain",W),i.preventDefault())});let ac=new Map,_f=null,Uf="idle",Yb={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Zb=(i,u)=>{let{icon:h,label:x}=Yb[u];i.setAttribute("aria-label",x),i.title=x,i.setAttribute("aria-pressed",u==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",u!=="idle"),i.classList.toggle("persona-message-action-loading",u==="loading");let k=ae(h,14,"currentColor",2);k&&(i.innerHTML="",i.appendChild(k))},qf=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let x=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Zb(u,x&&x===_f?Uf:"idle")})};xe.addEventListener("click",i=>{let h=i.target.closest(".persona-message-action-btn[data-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let k=x.getAttribute("data-actions-for");if(!k)return;let W=h.getAttribute("data-action");if(W==="copy"){let U=q.getMessages().find(j=>j.id===k);if(U&>.onCopy){let j=U.content||"";navigator.clipboard.writeText(j).then(()=>{h.classList.add("persona-message-action-success");let Y=ae("check",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let pe=ae("copy",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))},2e3)}).catch(Y=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",Y)}),gt.onCopy(U)}}else if(W==="read-aloud")q.toggleReadAloud(k);else if(W==="upvote"||W==="downvote"){let U=(ac.get(k)??null)===W,j=W==="upvote"?"thumbs-up":"thumbs-down";if(U){ac.delete(k),h.classList.remove("persona-message-action-active");let Y=ae(j,14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))}else{let Y=W==="upvote"?"downvote":"upvote",pe=x.querySelector(`[data-action="${Y}"]`);if(pe){pe.classList.remove("persona-message-action-active");let ct=ae(Y==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(pe.innerHTML="",pe.appendChild(ct))}ac.set(k,W),h.classList.add("persona-message-action-active");let le=ae(j,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(le)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ge=q.getMessages().find(ht=>ht.id===k);Ge&>.onFeedback&>.onFeedback({type:W,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",i=>{let h=i.target.closest("button[data-approval-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let k=x.getAttribute("data-message-id");if(!k)return;let W=h.getAttribute("data-approval-action");if(!W)return;let z=W==="approve"?"approved":"denied",j=q.getMessages().find(pe=>pe.id===k);if(!j?.approval)return;let Y=x.querySelector("[data-approval-buttons]");Y&&Y.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),j.approval.toolType==="webmcp"?q.resolveWebMcpApproval(k,z):q.resolveApproval(j.approval,z)});let Ke=null,Ha=null,Zo=()=>{},Ba="none",Vs=null,Pn={artifacts:[],selectedId:null},Xn=!1,Rn=!1,Da=!1,Fr=!1,Vf=()=>Fr||Pn.artifacts.some(i=>zn(o.features?.artifacts,i)==="panel"),zs=()=>Pn.artifacts.length>0&&!Xn&&Vf(),at={current:null},sc=(i,u)=>{let h=q.getArtifactById(u),x=h?.markdown,k=h?.title||"artifact",W=h?.file,z=h?.artifactType??"markdown";if(!x){let Y=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(Y){let le=q.getMessages().find(ye=>ye.id===Y);if(le?.rawContent)try{let ye=JSON.parse(le.rawContent);x=ye?.props?.markdown,k=ye?.props?.title||k,ye?.props?.file&&typeof ye.props.file=="object"&&(W=ye.props.file),!h&&typeof ye?.props?.artifactType=="string"&&(z=ye.props.artifactType)}catch{}}}return{markdown:x,title:k,file:W,artifactType:z}};xe.addEventListener("click",i=>{let h=i.target.closest("[data-download-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:W,title:z,file:U}=sc(h,x);if(!W)return;let{filename:j,mime:Y,content:pe}=kh({title:z,markdown:W,file:U}),le=new Blob([pe],{type:Y}),ye=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=ye,Ge.download=j,Ge.click(),URL.revokeObjectURL(ye)}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-artifact-custom-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let k=h.closest("[data-artifact-inline]"),W=k?null:h.closest("[data-open-artifact]"),z=k?k.getAttribute("data-artifact-inline"):W?.getAttribute("data-open-artifact")??null,j=(k?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ht=>ht.id===x);if(!j)return;let{markdown:Y,title:pe,file:le,artifactType:ye}=sc(h,z??""),Ge={artifactId:z,title:pe,artifactType:ye,markdown:Y,file:le};try{Promise.resolve(j.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-copy-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let k=q.getArtifactById(x),W="";if(k)W=vs(k);else{let{markdown:z,file:U,artifactType:j}=sc(h,x);j==="markdown"&&(W=vs({id:x,artifactType:"markdown",status:"complete",markdown:z??"",...U?{file:U}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let z=ae("check",16,"currentColor",2);z&&(h.replaceChildren(z),setTimeout(()=>{let U=ae("copy",16,"currentColor",2);U&&h.replaceChildren(U)},1500))}).catch(()=>{})}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-expand-artifact-inline]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Xn=!1,Fr=!0,Rn=!0,Da=!0,q.selectArtifact(x),Jn())}),xe.addEventListener("click",i=>{let u=i.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let h=u.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(i.preventDefault(),i.stopPropagation(),Xn=!1,Fr=!0,q.selectArtifact(x),Jn())}),xe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let u=i.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),u.click())});let Or=Te.composerOverlay,Nr=(i,u,h)=>{let x=u.trim();if(!x||!at.current)return;let k=i.getAttribute("data-tool-call-id")??"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Wo(Or,k);let z=at.current.getMessages().find(U=>U.toolCall?.id===k);z?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(z,h.structured??x):at.current.sendMessage(x)},er=i=>{let u=at.current;if(!u)return;let h=i.getAttribute("data-tool-call-id")??"",x=u.getMessages().find(k=>k.toolCall?.id===h);x&&u.persistAskUserQuestionProgress(x,{answers:Si(i,x),currentIndex:Sn(i)})},zf=i=>Object.entries(i).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),ic=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let u=Sn(i),h=ra(i);if(u>=h-1)return;let x=at.current?.getMessages().find(k=>k.toolCall?.id===i.getAttribute("data-tool-call-id"));x&&(Mi(i,x,o,u+1),er(i))};Or.addEventListener("click",i=>{let h=i.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let k=h.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),k==="dismiss"){let W=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),Wo(Or,W);let z=at.current?.getMessages().find(U=>U.toolCall?.id===W);z?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(z),at.current?.resolveAskUserQuestion(z,"(dismissed)"));return}if(k==="pick"){let W=h.getAttribute("data-option-label");if(!W)return;let z=x.getAttribute("data-multi-select")==="true",U=Io(x);if(U&&z){let j=yr(x)[Sn(x)],Y=new Set(Array.isArray(j)?j:[]);Y.has(W)?Y.delete(W):Y.add(W),Ho(x,Array.from(Y)),er(x);return}if(U){Ho(x,W),er(x),ic(x);return}if(z){let j=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",j?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!j);let Y=x.querySelector('[data-ask-user-action="submit-multi"]');Y&&(Y.disabled=nd(x).length===0);return}Nr(x,W,{source:"pick",values:[W]});return}if(k==="submit-multi"){let W=nd(x);if(W.length===0)return;Nr(x,W.join(", "),{source:"multi",values:W});return}if(k==="open-free-text"){let W=x.querySelector('[data-ask-free-text-row="true"]');W&&(W.classList.remove("persona-hidden"),W.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(k==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(k==="submit-free-text"){let z=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!z.trim())return;if(Io(x)){Ho(x,z.trim()),er(x),ic(x);return}Nr(x,z,{source:"free-text"});return}if(k==="next"||k==="back"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(le=>le.toolCall?.id===W);if(!z)return;let j=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(j){let le=yr(x)[Sn(x)];(typeof le!="string"||le!==j)&&Ho(x,j)}let Y=k==="next"?1:-1,pe=Sn(x)+Y;Mi(x,z,o,pe),er(x);return}if(k==="submit-all"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(le=>le.toolCall?.id===W);if(!z)return;let j=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";j&&Ho(x,j);let Y=Si(x,z);at.current.persistAskUserQuestionProgress(z,{answers:Y,currentIndex:Sn(x)});let pe=zf(Y);Nr(x,pe||"(submitted)",{source:"submit-all",structured:Y});return}if(k==="skip"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(ye=>ye.toolCall?.id===W);if(!z)return;let U=Io(x),j=Sn(x),Y=ra(x),pe=j>=Y-1;if(!U){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),Wo(Or,W),z.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(z),at.current.resolveAskUserQuestion(z,"(dismissed)"));return}Ho(x,"");let le=x.querySelector('[data-ask-free-text-input="true"]');if(le&&(le.value=""),pe){let ye=Si(x,z),Ge=zf(ye);Nr(x,Ge||"(skipped)",{source:"submit-all",structured:ye});return}Mi(x,z,o,j+1),er(x);return}}),Or.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let h=i.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;i.preventDefault();let k=h.value;if(k.trim()){if(Io(x)){Ho(x,k.trim()),er(x),ic(x);return}Nr(x,k,{source:"free-text"})}});let $f=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let u=i.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let h=Or.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(i.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];W&&(i.preventDefault(),W.click())};document.addEventListener("keydown",$f);let yo=null,xt=null,Fa=null,$s=null,lc=()=>{},jf=!1,js="",Gs="";function cc(){$s?.(),$s=null}let Gf=()=>{if(!yo||!xt)return;let i=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,h=u.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||h){xt.style.removeProperty("position"),xt.style.removeProperty("left"),xt.style.removeProperty("top"),xt.style.removeProperty("bottom"),xt.style.removeProperty("width"),xt.style.removeProperty("z-index");return}let x=yo.firstElementChild;if(!x||x===xt)return;let k=10;xt.style.position="absolute",xt.style.top="0",xt.style.bottom="0",xt.style.width=`${k}px`,xt.style.zIndex="5";let W=rf(yo,u),z=x.offsetWidth+W/2-k/2;xt.style.left=`${Math.max(0,z)}px`},Ks=()=>{},ex=()=>{let i=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!u||i.innerWidth>h?!1:P||St(o)},Xs=()=>!tn(o)||!zs()||e.classList.contains("persona-artifact-narrow-host")||ex()||(e.ownerDocument.defaultView??window).innerWidth<hS?"none":ef(o)?"detached":"welded",Jn=()=>{if(!Ke||!tn(o))return;Is(e,o),Ws(e,o),Ks();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=he.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=i);let h=zs();Ke.setVisible(h),Ke.update(Pn),Xn?(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),Rn=!1,Da=!1):Pn.artifacts.length>0&&Vf()?(Ke.element.classList.remove("persona-hidden"),Ke.setMobileOpen(!0)):(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),Rn=!1,Da=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ke.setExpandToggleVisible(x),Ke.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ke.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ke.setTabFade(o.features?.artifacts?.layout?.tabFade),Ke.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Da&&(Rn=!1),Rn!==jf){let W=Ke.element;Rn?(js=W.style.width,Gs=W.style.maxWidth,W.style.removeProperty("width"),W.style.removeProperty("max-width")):(js&&(W.style.width=js),Gs&&(W.style.maxWidth=Gs),js="",Gs=""),jf=Rn}e.classList.toggle("persona-artifact-expanded",Rn),Ke.setExpanded(Rn);let k=Xs();k!==Ba&&(Ba=k,Zo()),lc()};if(tn(o)){he.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(be),Ke=qy(o,{onSelect:h=>at.current?.selectArtifact(h),onDismiss:()=>{Xn=!0,Jn()},onToggleExpand:()=>{let h=!Rn,x=Pn.selectedId??Pn.artifacts[Pn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(Rn=h,h||(Da=!1),Jn())}}),Ke.element.classList.add("persona-hidden"),yo=u,u.appendChild(i),u.appendChild(Ke.element),Ke.backdrop&&he.appendChild(Ke.backdrop),he.appendChild(u),lc=()=>{if(!yo||!Ke)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Fa?.(),Fa=null,cc(),xt&&(xt.remove(),xt=null),Ke.element.style.removeProperty("width"),Ke.element.style.removeProperty("maxWidth");return}if(!xt){let x=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let k=e.ownerDocument,W=k.defaultView??window,z=U=>{if(!Ke||U.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||W.innerWidth<=640)return;U.preventDefault(),cc();let j=U.clientX,Y=Ke.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,le=Ge=>{let ht=yo.getBoundingClientRect().width,ct=e.classList.contains("persona-artifact-welded-split"),un=rf(yo,W),Mt=ct?0:x.getBoundingClientRect().width||6,It=Y-(Ge.clientX-j),_=Qy(It,ht,un,Mt,pe?.resizableMinWidth,pe?.resizableMaxWidth);Ke.element.style.width=`${_}px`,Ke.element.style.maxWidth="none",Gf()},ye=()=>{k.removeEventListener("pointermove",le),k.removeEventListener("pointerup",ye),k.removeEventListener("pointercancel",ye),$s=null;try{x.releasePointerCapture(U.pointerId)}catch{}};$s=ye,k.addEventListener("pointermove",le),k.addEventListener("pointerup",ye),k.addEventListener("pointercancel",ye);try{x.setPointerCapture(U.pointerId)}catch{}};x.addEventListener("pointerdown",z),xt=x,yo.insertBefore(x,Ke.element),Fa=()=>{x.removeEventListener("pointerdown",z)}}if(xt){let x=zs();xt.classList.toggle("persona-hidden",!x),Gf()}},Ks=()=>{if(!P||!Ke||(o.launcher?.sidebarMode??!1)||St(o)&&ln(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(k&&x.innerWidth<=W||!$y(o,P))return;let z=o.launcher?.width??o.launcherWidth??mn,U=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";zs()?(he.style.width=U,he.style.maxWidth=U):(he.style.width=z,he.style.maxWidth=z)},typeof ResizeObserver<"u"&&(Ha=new ResizeObserver(()=>{Jn()}),Ha.observe(he))}else he.appendChild(be);Q()&&tt&&(Te.peekBanner&&tt.appendChild(Te.peekBanner),tt.appendChild(we)),e.appendChild(Le),tt&&e.appendChild(tt);let dc=()=>{if(Q()){he.style.width="100%",he.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},an=Le.dataset.state==="expanded",fi=Lt.expandedSize??"anchored";if(!(an&&fi!=="fullscreen")){be.style.background="",be.style.border="",be.style.borderRadius="",be.style.overflow="",be.style.boxShadow="";return}let Ya=o.theme?.components?.panel,mi=Uo(o),Qr=(oo,gr)=>oo==null||oo===""?gr:en(mi,oo)??oo,gi="1px solid var(--persona-border)",Vc="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";be.style.background="var(--persona-surface, #ffffff)",be.style.border=Qr(Ya?.border,gi),be.style.borderRadius=Qr(Ya?.borderRadius,mr),be.style.boxShadow=Qr(Ya?.shadow,Vc),be.style.overflow="hidden";return}let i=St(o),u=o.launcher?.sidebarMode??!1,h=i||u||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,z=Uo(o),U=(Lt,an)=>Lt==null||Lt===""?an:en(z,Lt)??Lt,j=e.ownerDocument.defaultView??window,Y=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,le=j.innerWidth<=pe,ye=Y&&le&&P,Ge=i&&Y&&le,ht=o.launcher?.position??"bottom-left",ct=ht==="bottom-left"||ht==="top-left",un=o.launcher?.zIndex??Ut,Mt="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=k&&!ye&&!Ge;Re?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Fe=Re?Mt:u||ye?"none":Mt,Ee=Re?It:ye?"none":u?ct?"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))":x?"none":It;i&&!ye&&!Re&&(Ee="none",Fe="none");let At=Re?_:u||ye?"0":_,dt=U(W?.border,Fe),Ot=U(W?.shadow,Ee),pt=U(W?.borderRadius,At),rn=Xs(),Wt=rn==="detached",Ie=rn==="welded";e.classList.toggle("persona-artifact-detached-split",Wt),e.classList.toggle("persona-artifact-welded-split",Ie);let Oe="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)))))",Ct=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&tn(o)&&ef(o)&&x&&!i;e.classList.toggle("persona-artifact-chat-flush",Ct);let st=Wt||Ct?"none":Ot,ft=Wt?Mt:Ie?"none":dt,Xe=Wt?_:pt;Ct&&(ft="none",Xe="0");let He=W?.borderRadius!=null&&W.borderRadius!=="",yt=Ct&&!He?"0":pt,jt=re.scrollTop;e.style.cssText="",Le.style.cssText="",he.style.cssText="",be.style.cssText="",re.style.cssText="",we.style.cssText="",Me&&(re.style.display="none"),(h||x)&&(e.style.minWidth="0");let An=()=>{if(jt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===jt)return;let an=re.scrollHeight-re.clientHeight;an<=0||(re.scrollTop=Math.min(jt,an))})};if(ye){Le.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"),Le.style.cssText=`
|
|
49
|
+
`,P.addEventListener("click",()=>{f=L,H.forEach((D,q)=>{let $=q<L;D.classList.toggle("selected",$),D.setAttribute("aria-checked",q===L-1?"true":"false")})}),H.push(P),E.appendChild(P)}y.appendChild(E);let k=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),L.appendChild(k),y.appendChild(L)}let M=document.createElement("div");M.className="persona-feedback-actions";let x=document.createElement("button");x.type="button",x.className="persona-feedback-btn persona-feedback-btn-skip",x.textContent=l,x.addEventListener("click",()=>{n?.(),p.remove()});let w=document.createElement("button");return w.type="button",w.className="persona-feedback-btn persona-feedback-btn-submit",w.textContent=i,w.addEventListener("click",async()=>{if(f===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}w.disabled=!0,w.textContent="Submitting...";try{let L=k?.value.trim()||void 0;await t(f,L),p.remove()}catch(L){w.disabled=!1,w.textContent=i,console.error("[CSAT Feedback] Failed to submit:",L)}}),M.appendChild(x),M.appendChild(w),y.appendChild(M),p.appendChild(y),p}function Wd(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let y=null,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,b.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,b.appendChild(E),g.appendChild(b);let H=document.createElement("div");H.className="persona-feedback-rating persona-feedback-rating-nps",H.setAttribute("role","radiogroup"),H.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=u;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=p,k.appendChild(M),k.appendChild(x);let w=document.createElement("div");w.className="persona-feedback-numbers";let L=[];for(let N=0;N<=10;N++){let X=document.createElement("button");X.type="button",X.className="persona-feedback-rating-btn persona-feedback-number-btn",X.setAttribute("role","radio"),X.setAttribute("aria-checked","false"),X.setAttribute("aria-label",`Rating ${N} out of 10`),X.textContent=String(N),X.dataset.rating=String(N),N<=6?X.classList.add("persona-feedback-detractor"):N<=8?X.classList.add("persona-feedback-passive"):X.classList.add("persona-feedback-promoter"),X.addEventListener("click",()=>{y=N,L.forEach((de,me)=>{de.classList.toggle("selected",me===N),de.setAttribute("aria-checked",me===N?"true":"false")})}),L.push(X),w.appendChild(X)}H.appendChild(k),H.appendChild(w),g.appendChild(H);let P=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),N.appendChild(P),g.appendChild(N)}let D=document.createElement("div");D.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=l,q.addEventListener("click",()=>{n?.(),f.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=i,$.addEventListener("click",async()=>{if(y===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let N=P?.value.trim()||void 0;await t(y,N),f.remove()}catch(N){$.disabled=!1,$.textContent=i,console.error("[NPS Feedback] Failed to submit:",N)}}),D.appendChild(q),D.appendChild($),g.appendChild(D),f.appendChild(g),f}var Sa="persona-chat-history",ok=30*1e3,rk=641,sk={"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 ak(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=sk[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Bd(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 ik(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 lk(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Rg=e=>!e||typeof e!="object"?{}:{...e},_C=e=>e.map(t=>({...t,streaming:!1})),UC=(e,t,n)=>{let o=e?.markdown?Qr(e.markdown):null,r=Gs(e?.sanitize);return e?.postprocessMessage&&r&&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."),s=>{let i=s.text??"",l=s.message.rawContent??null;if(t){let p=t.process({text:i,raw:l??i,message:s.message,streaming:s.streaming});p!==null&&(i=p.text,p.persist||(s.message.__skipPersist=!0),p.resubmit&&!s.streaming&&n&&n())}let d=Fo()!==null,u;if(e?.postprocessMessage){let p=e.postprocessMessage({...s,text:i,raw:l??s.text??""});u=r?r(p):p}else if(o){let p=s.streaming?vb(i):i,f=o(p);u=r&&d?r(f):f}else u=mo(i);return u}};function qC(e){let t=S("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 n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,i=ce(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=S("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var ck=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},dk=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:ck(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Dd=(e,t,n)=>{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=aa(t),r=()=>{Wx({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Ki(o);let i=Xi.getForInstance(o.plugins),l=Kx(e),d=[],u=!1,p=Yv(()=>o),{plugin:f,teardown:y}=aC();o.components&&ro.registerAll(o.components);let g=TC(),v=o.persistState===!1?null:o.storageAdapter??kd(),E={},H=null,k,M=new Promise(a=>{k=a}),x=!1,w=a=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(a);if(c&&typeof c=="object"&&"state"in c){let{state:m,open:h}=c;return h&&(x=!0),m}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return a};if(v?.load)try{let a=v.load();if(a&&typeof a.then=="function")H=a.then(c=>w(c??{messages:[],metadata:{}}));else{let m=w(a??{messages:[],metadata:{}});m.metadata&&(E=Rg(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=w({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}H||k();let L=()=>E,P=a=>{E=a({...E})??{},tp()},D=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Yi],q=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[vs.message,vs.messageAndClick],$=Ji({parsers:D,handlers:q,getSessionMetadata:L,updateSessionMetadata:P,emit:g.emit,documentRef:typeof document<"u"?document:null});$.syncFromMetadata();let N=o.launcher?.enabled??!0,X=o.launcher?.autoExpand??!1,de=o.autoFocusInput??!1,me=X,xe=N,ye=o.layout?.header?.layout,ne=!1,ie=()=>Mr(o),le=()=>N||ie(),I=ie()?!1:N?X:!0,Z=!1,pe=null,Ee=()=>{Z=!0,pe&&clearTimeout(pe),pe=setTimeout(()=>{Z&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},Ce=UC(o,$,Ee),we=o.features?.showReasoning??!0,Pe=o.features?.showToolCalls??!0,Re=o.features?.showEventStreamToggle??!1,nt=o.features?.scrollToBottom??{},Je=o.features?.scrollBehavior??{},Be=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",vt=`${Be()}event-stream`,yt=Re?new zi(vt):null,Dn=o.features?.eventStream?.maxEvents??2e3,Me=Re?new Vi(Dn,yt):null,Ke=Re?new ji:null,rt=null,Kt=!1,zt=null,Xn=0,Ye=!1,Qe=null,bt=()=>{},en=()=>{},wo=()=>{},It=()=>{},Ko=()=>{},Cs=()=>Kt||Ye&&Qe==="panel";yt?.open().then(()=>Me?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let U={onCopy:a=>{g.emit("message:copy",a),F?.isClientTokenMode()&&F.submitMessageFeedback(a.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{g.emit("message:feedback",a),F?.isClientTokenMode()&&F.submitMessageFeedback(a.messageId,a.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(a)}},ee=o.statusIndicator??{},A=a=>a==="idle"?ee.idleText??Nt.idle:a==="connecting"?ee.connectingText??Nt.connecting:a==="connected"?ee.connectedText??Nt.connected:a==="error"?ee.errorText??Nt.error:a==="paused"?ee.pausedText??Nt.paused:a==="resuming"?ee.resumingText??Nt.resuming:Nt[a];function T(a,c,m,h){if(h==="idle"&&m.idleLink){a.textContent="";let C=document.createElement("a");C.href=m.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=c,C.style.color="inherit",C.style.textDecoration="none",a.appendChild(C)}else a.textContent=c}let B=Xv({config:o,showClose:le()}),{wrapper:W,panel:O,pillRoot:Y}=B.shell,Q=B.panelElements,{container:K,body:G,messagesWrapper:ae,starterSuggestions:it,transcriptSuggestions:et,suggestions:xt,textarea:ge,sendButton:he,sendButtonWrapper:tn,composerForm:_e,statusText:rn,welcomeHost:hn,welcomeIconHolder:Ew,greetingHost:An,introTitle:kw,introSubtitle:Pw,closeButton:Ie,iconHolder:Ct,headerTitle:Xo,headerSubtitle:Er,header:Se,footer:Oe,actionsRow:Lw,rightActions:Hw}=Q,ws=Q.leftActions,Kg=Q.setSendButtonMode,oe=Q.micButton,So=Q.micButtonWrapper,pt=Q.attachmentButton,On=Q.attachmentButtonWrapper,Et=Q.attachmentInput,Yn=Q.attachmentPreviewsContainer;K.classList.add("persona-relative"),G.classList.add("persona-relative");let Rw=12,Ma=()=>nt.label??"",Iw=()=>nt.iconName??"arrow-down",Ww=()=>nt.enabled!==!1,Mn=()=>Je.mode??"anchor-top",Yo=()=>Mn()==="follow"||Mn()==="anchor-top"&&Ba,Ta=()=>Je.anchorTopOffset??16,Bw=()=>Je.restorePosition??"bottom",Xg=()=>Je.pauseOnInteraction===!0,Yg=()=>Je.showActivityWhilePinned!==!1,Jg=()=>Je.announce===!0,_d=()=>Je.scrollbar??"on-scroll",Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let Ea=S("span","persona-flex persona-items-center"),Ud=S("span",""),kr=S("span","");kr.setAttribute("data-persona-scroll-to-bottom-count",""),kr.style.display="none",Wt.append(Ea,Ud,kr),K.appendChild(Wt);let Fn=S("div","persona-stream-anchor-spacer");Fn.setAttribute("aria-hidden","true"),Fn.setAttribute("data-persona-anchor-spacer",""),Fn.style.flexShrink="0",Fn.style.pointerEvents="none",Fn.style.height="0px",Fn.style.display="none",G.appendChild(Fn);let Ao=S("div","persona-sr-only");Ao.setAttribute("aria-live","polite"),Ao.setAttribute("aria-atomic","true"),Ao.setAttribute("role","status"),Ao.setAttribute("data-persona-live-region",""),Object.assign(Ao.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"}),K.appendChild(Ao);let ka=null,tl=null,Qg=a=>{!Jg()||!a||(tl=a,ka===null&&(ka=setTimeout(()=>{ka=null,tl&&Jg()&&(Ao.textContent=tl),tl=null},400)))},Pr=()=>{let c=Oe.style.display==="none"?0:Oe.offsetHeight;Wt.style.bottom=`${c+Rw}px`};Pr();let Zg=()=>{let a=!!Ma();Wt.setAttribute("aria-label",Ma()||"Jump to latest"),Wt.title=Ma(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Ea.innerHTML="";let c=ce(Iw(),"14px","currentColor",2);c?(Ea.appendChild(c),Ea.style.display=""):Ea.style.display="none",Ud.textContent=Ma(),Ud.style.display=a?"":"none"};Zg();let ut=null,sn=null,eh=null,th=i.find(a=>a.renderHeader);if(th?.renderHeader){let a=th.renderHeader({config:o,defaultRenderer:()=>{let c=zo({config:o,showClose:le()});return us(K,c,o),c.header},onClose:()=>st(!1,"user")});if(a){let c=Se;c&&(c.replaceWith(a),Se=a,B.header.element=a)}}let nh=()=>{rt&&(G.style.display="none",Oe.parentNode?.insertBefore(rt.element,Oe),rt.update())},qd=()=>{if(!Me)return;if(Kt=!0,rt?nh():pC().then(c=>{rt||!Kt||!Me||(rt=c.createEventStreamView({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>Ss(),config:o,plugins:i,getThroughput:()=>Ke?.getMetric()??{status:"idle"}}),nh())}).catch(()=>{Ss()}),je){je.style.boxShadow=`inset 0 0 0 1.5px ${mn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(m=>m&&je.classList.add(m))}let a=()=>{if(!Kt)return;let c=Date.now();c-Xn>=200&&(rt?.update(),Xn=c),zt=requestAnimationFrame(a)};Xn=0,zt=requestAnimationFrame(a),Ut(),g.emit("eventStream:opened",{timestamp:Date.now()})},Ss=()=>{if(Kt){if(Kt=!1,rt&&rt.element.remove(),G.style.display="",je){je.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(c=>c&&je.classList.remove(c))}zt!==null&&(cancelAnimationFrame(zt),zt=null),Ut(),g.emit("eventStream:closed",{timestamp:Date.now()})}},je=null;if(Re){let a=o.features?.eventStream?.classNames,c="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"+(a?.toggleButton?" "+a.toggleButton:"");je=S("button",c),je.style.width="28px",je.style.height="28px",je.style.color=mn.actionIconColor,je.type="button",je.setAttribute("aria-label","Event Stream"),je.title="Event Stream";let m=ce("activity","18px","currentColor",1.5);m&&je.appendChild(m);let h=Q.clearChatButtonWrapper,C=Q.closeButtonWrapper,R=h||C;R&&R.parentNode===Se?Se.insertBefore(je,R):Se.appendChild(je),je.addEventListener("click",()=>{Kt?Ss():qd()})}let oh=a=>{let c=o.attachments;if(!c?.enabled)return;let m=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!m){m=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let C=a.querySelector("[data-persona-composer-form]");C?.parentNode?C.parentNode.insertBefore(m,C):a.insertBefore(m,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let C=S("input");C.type="file",C.setAttribute("data-persona-composer-attachment-input",""),C.accept=(c.allowedTypes??qo).join(","),C.multiple=(c.maxFiles??4)>1,C.style.display="none",C.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),a.appendChild(C)}},Vd=i.find(a=>a.renderComposer),Pa=!1,rh=a=>{if(!Vd?.renderComposer)return null;let c=o.composer,m=u?F.isStreaming():!1;return Vd.renderComposer({config:o,defaultRenderer:a,requestRender:()=>hA(),storage:p(Vd.id),onSubmit:h=>{if(!F||F.isStreaming())return;let C=h.trim(),R=ut?.hasAttachments()??!1;if(!C&&!R)return;Fy();let z;R&&(z=[],z.push(...ut.getContentParts()),C&&z.push(ho(C))),F.sendMessage(C,{contentParts:z}),R&&ut.clearAttachments()},streaming:m,disabled:m,openAttachmentPicker:()=>{Et?.click()},models:c?.models,selectedModelId:c?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{eh?.()}:void 0})},sh=rh(()=>fs({config:o}).footer);sh&&(B.replaceComposer(sh),Oe=B.composer.footer,Pa=!0);let ah=a=>{let c=(...te)=>{for(let se of te){let fe=a.querySelector(se);if(fe)return fe}return null},m=a.querySelector("[data-persona-composer-form]"),h=a.querySelector("[data-persona-composer-input]"),C=a.querySelector("[data-persona-composer-submit]"),R=a.querySelector("[data-persona-composer-mic]"),z=a.querySelector("[data-persona-composer-status]");m&&(_e=m),h&&(ge=h),C&&(he=C),R&&(oe=R,So=R.parentElement),z&&(rn=z);let V=c("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(xt=V);let J=c("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(pt=J,On=J.parentElement),Et=c("[data-persona-composer-attachment-input]",'input[type="file"]'),Yn=c("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let j=c("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");j&&(Lw=j),ws=c(".persona-widget-composer__left-actions")};oh(Oe),ah(Oe);let La=vr(o,ie());La&&(ae.style.maxWidth=La,ae.style.marginLeft="auto",ae.style.marginRight="auto",ae.style.width="100%",An.style.maxWidth=La,An.style.marginLeft="auto",An.style.marginRight="auto",An.style.width="100%",it.style.maxWidth=La,et.style.maxWidth=La,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%");let ih=()=>{let a=vr(o,ie());if(!(!a||ie()))for(let c of[_e,xt,Yn,rn])c&&(c.style.maxWidth=a,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};ih();let lh=()=>{!o.attachments?.enabled||!Et||!Yn||(ut?ut.remountPreviews(Yn):(ut=rs.fromConfig(o.attachments),ut.setPreviewsContainer(Yn)),Et.addEventListener("change",a=>{let c=a.target;ut?.handleFileSelect(c.files),c.value=""}),K.querySelector(".persona-attachment-drop-overlay")||K.appendChild(qC(o.attachments.dropOverlay)))};lh();let Dw=()=>sn?.prefetch(),ch=()=>{if(!(!o.contextMentions?.enabled||!ge)&&(sn=_x({config:o,textarea:ge,anchor:_e??ge,getMessages:()=>F.getMessages(),liveRegionHost:K}),sn)){let a=ge;a.parentElement?.insertBefore(sn.contextRow,a);let c=sn.affordanceButtons;for(let m=c.length-1;m>=0;m--){let h=c[m];ws?ws.insertBefore(h,ws.firstChild):_e?.appendChild(h)}}};ch(),(()=>{let a=o.layout?.slots??{},c=h=>{switch(h){case"body-top":return G.querySelector("[data-persona-intro-card]");case"messages":return ae;case"footer-top":return xt;case"composer":return _e;case"footer-bottom":return rn;default:return null}},m=(h,C)=>{switch(h){case"header-left":case"header-center":case"header-right":if(h==="header-left")Se.insertBefore(C,Se.firstChild);else if(h==="header-right")Se.appendChild(C);else{let R=Se.querySelector(".persona-flex-col");R?R.parentNode?.insertBefore(C,R.nextSibling):Se.appendChild(C)}break;case"body-top":{let R=G.querySelector("[data-persona-intro-card]");R?R.replaceWith(C):G.insertBefore(C,G.firstChild);break}case"body-bottom":G.appendChild(C);break;case"footer-top":xt.replaceWith(C);break;case"footer-bottom":rn.replaceWith(C);break;default:break}};for(let[h,C]of Object.entries(a))if(C)try{let R=C({config:o,defaultContent:()=>c(h)});R&&m(h,R)}catch(R){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${h}":`,R)}})();let dh=a=>{let m=a.target.closest('button[data-expand-header="true"]');if(!m)return;let h=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let R=m.getAttribute("data-bubble-type");if(R==="reasoning")ba.has(C)?ba.delete(C):ba.add(C),Jv(C,h);else if(R==="tool")xa.has(C)?xa.delete(C):xa.add(C),Qv(C,h,o);else if(R==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=gs.get(C)??V;gs.set(C,!J),nC(C,h,o)}En.delete(C)};ae.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),dh(a))}),ae.addEventListener("keydown",a=>{let c=a.target;(a.key==="Enter"||a.key===" ")&&c.closest('button[data-expand-header="true"]')&&(a.preventDefault(),dh(a))}),ae.addEventListener("copy",a=>{let{clipboardData:c}=a;if(!c)return;let m=ae.getRootNode(),h=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!h||h.isCollapsed)return;let C=h.toString(),R=fv(C);!R||R===C||(c.setData("text/plain",R),a.preventDefault())});let zd=new Map,ph=null,uh="idle",Ow={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Fw=(a,c)=>{let{icon:m,label:h}=Ow[c];a.setAttribute("aria-label",h),a.title=h,a.setAttribute("aria-pressed",c==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",c!=="idle"),a.classList.toggle("persona-message-action-loading",c==="loading");let C=ce(m,14,"currentColor",2);C&&(a.innerHTML="",a.appendChild(C))},fh=()=>{ae.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let h=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Fw(c,h&&h===ph?uh:"idle")})};ae.addEventListener("click",a=>{let m=a.target.closest(".persona-message-action-btn[data-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let h=m.closest("[data-actions-for]");if(!h)return;let C=h.getAttribute("data-actions-for");if(!C)return;let R=m.getAttribute("data-action");if(R==="copy"){let V=F.getMessages().find(J=>J.id===C);if(V&&U.onCopy){let J=V.content||"";navigator.clipboard.writeText(J).then(()=>{m.classList.add("persona-message-action-success");let j=ce("check",14,"currentColor",2);j&&(m.innerHTML="",m.appendChild(j)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let te=ce("copy",14,"currentColor",2);te&&(m.innerHTML="",m.appendChild(te))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),U.onCopy(V)}}else if(R==="read-aloud")F.toggleReadAloud(C);else if(R==="upvote"||R==="downvote"){let V=(zd.get(C)??null)===R,J=R==="upvote"?"thumbs-up":"thumbs-down";if(V){zd.delete(C),m.classList.remove("persona-message-action-active");let j=ce(J,14,"currentColor",2);j&&(m.innerHTML="",m.appendChild(j))}else{let j=R==="upvote"?"downvote":"upvote",te=h.querySelector(`[data-action="${j}"]`);if(te){te.classList.remove("persona-message-action-active");let $t=ce(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$t&&(te.innerHTML="",te.appendChild($t))}zd.set(C,R),m.classList.add("persona-message-action-active");let se=ce(J,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(se)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let $e=F.getMessages().find(gt=>gt.id===C);$e&&U.onFeedback&&U.onFeedback({type:R,messageId:$e.id,message:$e})}}}),ae.addEventListener("click",a=>{let m=a.target.closest("button[data-approval-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let h=m.closest(".persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let R=m.getAttribute("data-approval-action");if(!R)return;let z=R==="approve"?"approved":"denied",J=F.getMessages().find(te=>te.id===C);if(!J?.approval)return;let j=h.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?F.resolveWebMcpApproval(C,z):F.resolveApproval(J.approval,z)});let De=null,Ha=null,Lr=()=>{},Ra="none",nl=null,Jn={artifacts:[],selectedId:null},Mo=!1,Qn=!1,Ia=!1,As=!1,mh=()=>As||Jn.artifacts.some(a=>go(o.features?.artifacts,a)==="panel"),ol=()=>Jn.artifacts.length>0&&!Mo&&mh(),tt={current:null},jd=(a,c)=>{let m=F.getArtifactById(c),h=m?.markdown,C=m?.title||"artifact",R=m?.file,z=m?.artifactType??"markdown";if(!h){let j=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let se=F.getMessages().find(fe=>fe.id===j);if(se?.rawContent)try{let fe=JSON.parse(se.rawContent);h=fe?.props?.markdown,C=fe?.props?.title||C,fe?.props?.file&&typeof fe.props.file=="object"&&(R=fe.props.file),!m&&typeof fe?.props?.artifactType=="string"&&(z=fe.props.artifactType)}catch{}}}return{markdown:h,title:C,file:R,artifactType:z}};ae.addEventListener("click",a=>{let m=a.target.closest("[data-download-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let h=m.getAttribute("data-download-artifact");if(!h||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:h})===!0)return;let{markdown:R,title:z,file:V}=jd(m,h);R&&Jc(Yc({title:z,markdown:R,file:V}))}),ae.addEventListener("click",a=>{let m=a.target.closest("[data-artifact-custom-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let h=m.getAttribute("data-artifact-custom-action");if(!h)return;let C=m.closest("[data-artifact-inline]"),R=C?null:m.closest("[data-open-artifact]"),z=C?C.getAttribute("data-artifact-inline"):R?.getAttribute("data-open-artifact")??null,J=(C?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===h);if(!J)return;let{markdown:j,title:te,file:se,artifactType:fe}=jd(m,z??""),$e={artifactId:z,title:te,artifactType:fe,markdown:j,file:se};try{Promise.resolve(J.onClick($e)).catch(()=>{})}catch{}}),ae.addEventListener("click",a=>{let m=a.target.closest("[data-copy-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let h=m.getAttribute("data-copy-artifact");if(!h)return;let C=F.getArtifactById(h),R="";if(C)R=Wi(C);else{let{markdown:z,file:V,artifactType:J}=jd(m,h);J==="markdown"&&(R=Wi({id:h,artifactType:"markdown",status:"complete",markdown:z??"",...V?{file:V}:{}}))}R&&navigator.clipboard.writeText(R).then(()=>{let z=ce("check",16,"currentColor",2);z&&(m.replaceChildren(z),setTimeout(()=>{let V=ce("copy",16,"currentColor",2);V&&m.replaceChildren(V)},1500))}).catch(()=>{})}),ae.addEventListener("click",a=>{let m=a.target.closest("[data-expand-artifact-inline]");if(!m)return;a.preventDefault(),a.stopPropagation();let h=m.getAttribute("data-expand-artifact-inline");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(Mo=!1,As=!0,Qn=!0,Ia=!0,F.selectArtifact(h),To())}),ae.addEventListener("click",a=>{let c=a.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let m=c.closest("[data-open-artifact]");if(!m)return;let h=m.getAttribute("data-open-artifact");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(a.preventDefault(),a.stopPropagation(),Mo=!1,As=!0,F.selectArtifact(h),To())}),ae.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let c=a.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),c.click())});let Ms=Q.composerOverlay,Ts=(a,c,m)=>{let h=c.trim();if(!h||!tt.current)return;let C=a.getAttribute("data-tool-call-id")??"",R=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:h,answers:m.structured,values:m.values??(m.source==="multi"?h.split(", "):[h]),isFreeText:R,source:m.source},bubbles:!0,composed:!0})),pr(Ms,C);let z=tt.current.getMessages().find(V=>V.toolCall?.id===C);z?.agentMetadata?.awaitingLocalTool?tt.current.resolveAskUserQuestion(z,m.structured??h):tt.current.sendMessage(h)},Hr=a=>{let c=tt.current;if(!c)return;let m=a.getAttribute("data-tool-call-id")??"",h=c.getMessages().find(C=>C.toolCall?.id===m);h&&c.persistAskUserQuestionProgress(h,{answers:ac(a,h),currentIndex:$n(a)})},gh=a=>Object.entries(a).map(([c,m])=>`${c}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),$d=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=$n(a),m=Ys(a);if(c>=m-1)return;let h=tt.current?.getMessages().find(C=>C.toolCall?.id===a.getAttribute("data-tool-call-id"));h&&(ic(a,h,o,c+1),Hr(a))};Ms.addEventListener("click",a=>{let m=a.target.closest("[data-ask-user-action]");if(!m)return;let h=m.closest("[data-persona-ask-sheet-for]");if(!h)return;let C=m.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),C==="dismiss"){let R=h.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),pr(Ms,R);let z=tt.current?.getMessages().find(V=>V.toolCall?.id===R);z?.agentMetadata?.awaitingLocalTool&&(tt.current?.markAskUserQuestionResolved(z),tt.current?.resolveAskUserQuestion(z,"(dismissed)"));return}if(C==="pick"){let R=m.getAttribute("data-option-label");if(!R)return;let z=h.getAttribute("data-multi-select")==="true",V=dr(h);if(V&&z){let J=Zr(h)[$n(h)],j=new Set(Array.isArray(J)?J:[]);j.has(R)?j.delete(R):j.add(R),ur(h,Array.from(j)),Hr(h);return}if(V){ur(h,R),Hr(h),$d(h);return}if(z){let J=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",J?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!J);let j=h.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=gu(h).length===0);return}Ts(h,R,{source:"pick",values:[R]});return}if(C==="submit-multi"){let R=gu(h);if(R.length===0)return;Ts(h,R.join(", "),{source:"multi",values:R});return}if(C==="open-free-text"){let R=h.querySelector('[data-ask-free-text-row="true"]');R&&(R.classList.remove("persona-hidden"),R.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(C==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(C==="submit-free-text"){let z=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!z.trim())return;if(dr(h)){ur(h,z.trim()),Hr(h),$d(h);return}Ts(h,z,{source:"free-text"});return}if(C==="next"||C==="back"){if(!tt.current)return;let R=h.getAttribute("data-tool-call-id")??"",z=tt.current.getMessages().find(se=>se.toolCall?.id===R);if(!z)return;let J=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let se=Zr(h)[$n(h)];(typeof se!="string"||se!==J)&&ur(h,J)}let j=C==="next"?1:-1,te=$n(h)+j;ic(h,z,o,te),Hr(h);return}if(C==="submit-all"){if(!tt.current)return;let R=h.getAttribute("data-tool-call-id")??"",z=tt.current.getMessages().find(se=>se.toolCall?.id===R);if(!z)return;let J=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&ur(h,J);let j=ac(h,z);tt.current.persistAskUserQuestionProgress(z,{answers:j,currentIndex:$n(h)});let te=gh(j);Ts(h,te||"(submitted)",{source:"submit-all",structured:j});return}if(C==="skip"){if(!tt.current)return;let R=h.getAttribute("data-tool-call-id")??"",z=tt.current.getMessages().find(fe=>fe.toolCall?.id===R);if(!z)return;let V=dr(h),J=$n(h),j=Ys(h),te=J>=j-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),pr(Ms,R),z.agentMetadata?.awaitingLocalTool&&(tt.current.markAskUserQuestionResolved(z),tt.current.resolveAskUserQuestion(z,"(dismissed)"));return}ur(h,"");let se=h.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),te){let fe=ac(h,z),$e=gh(fe);Ts(h,$e||"(skipped)",{source:"submit-all",structured:fe});return}ic(h,z,o,J+1),Hr(h);return}}),Ms.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let m=a.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let h=m.closest("[data-persona-ask-sheet-for]");if(!h)return;a.preventDefault();let C=m.value;if(C.trim()){if(dr(h)){ur(h,C.trim()),Hr(h),$d(h);return}Ts(h,C,{source:"free-text"})}});let hh=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let c=a.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let m=Ms.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let h=Number(a.key),R=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[h-1];R&&(a.preventDefault(),R.click())};document.addEventListener("keydown",hh);let so=null,ft=null,Wa=null,rl=null,Gd=()=>{},yh=!1,sl="",al="";function Kd(){rl?.(),rl=null}let Nw=()=>{let a=Ga&&Os?.isConnected?Os:null,c=a?a.getBoundingClientRect().width:0;return c<=0?200:c+360},bh=()=>{if(!so||!ft)return;let a=e.classList.contains("persona-artifact-welded-split"),c=e.ownerDocument.defaultView??window,m=c.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||m){ft.style.removeProperty("position"),ft.style.removeProperty("left"),ft.style.removeProperty("top"),ft.style.removeProperty("bottom"),ft.style.removeProperty("width"),ft.style.removeProperty("z-index");return}let h=so.firstElementChild;if(!h||h===ft)return;let C=10;ft.style.position="absolute",ft.style.top="0",ft.style.bottom="0",ft.style.width=`${C}px`,ft.style.zIndex="5";let R=Ag(so,c),z=h.offsetWidth+R/2-C/2;ft.style.left=`${Math.max(0,z)}px`},il=()=>{},_w=()=>{let a=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!c||a.innerWidth>m?!1:N||ht(o)},ll=()=>!gn(o)||!ol()||e.classList.contains("persona-artifact-narrow-host")||_w()||(e.ownerDocument.defaultView??window).innerWidth<rk?"none":vg(o)?"detached":"welded",To=()=>{if(!De||!gn(o))return;$i(e,o),Gi(e,o),il();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=O.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=a);let m=ol();De.setVisible(m),De.update(Jn),Mo?(De.setMobileOpen(!1),De.element.classList.add("persona-hidden"),De.backdrop?.classList.add("persona-hidden"),Qn=!1,Ia=!1):Jn.artifacts.length>0&&mh()?(De.element.classList.remove("persona-hidden"),De.setMobileOpen(!0)):(De.setMobileOpen(!1),De.element.classList.add("persona-hidden"),De.backdrop?.classList.add("persona-hidden"),Qn=!1,Ia=!1);let h=o.features?.artifacts?.layout?.showExpandToggle===!0;if(De.setExpandToggleVisible(h),De.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),De.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),De.setCustomActions(o.features?.artifacts?.toolbarActions??[]),De.setTabFade(o.features?.artifacts?.layout?.tabFade),De.setRenderTabBar(o.features?.artifacts?.renderTabBar),!h&&!Ia&&(Qn=!1),Qn!==yh){let R=De.element;Qn?(sl=R.style.width,al=R.style.maxWidth,R.style.removeProperty("width"),R.style.removeProperty("max-width")):(sl&&(R.style.width=sl),al&&(R.style.maxWidth=al),sl="",al=""),yh=Qn}e.classList.toggle("persona-artifact-expanded",Qn),De.setExpanded(Qn);let C=ll();C!==Ra&&(Ra=C,Lr()),Gd()};if(gn(o)){O.style.position="relative";let a=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(K),De=fC(o,{onSelect:m=>tt.current?.selectArtifact(m),onDismiss:()=>{Mo=!0,To()},onToggleExpand:()=>{let m=!Qn,h=Jn.selectedId??Jn.artifacts[Jn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:h,expanded:m})!==!0&&(Qn=m,m||(Ia=!1),To())}}),De.element.classList.add("persona-hidden"),so=c,c.appendChild(a),c.appendChild(De.element),De.backdrop&&O.appendChild(De.backdrop),O.appendChild(c),Gd=()=>{if(!so||!De)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Wa?.(),Wa=null,Kd(),ft&&(ft.remove(),ft=null),De.element.style.removeProperty("width"),De.element.style.removeProperty("maxWidth");return}if(!ft){let h=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");h.setAttribute("role","separator"),h.setAttribute("aria-orientation","vertical"),h.setAttribute("aria-label","Resize artifacts panel"),h.tabIndex=0;let C=e.ownerDocument,R=C.defaultView??window,z=V=>{if(!De||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||R.innerWidth<=640)return;V.preventDefault(),Kd();let J=V.clientX,j=De.element.getBoundingClientRect().width,te=o.features?.artifacts?.layout,se=$e=>{let gt=so.getBoundingClientRect().width,$t=e.classList.contains("persona-artifact-welded-split"),vn=Ag(so,R),At=$t?0:h.getBoundingClientRect().width||6,kt=j-($e.clientX-J),_=wC(kt,gt,vn,At,te?.resizableMinWidth,te?.resizableMaxWidth,Nw());De.element.style.width=`${_}px`,De.element.style.maxWidth="none",bh()},fe=()=>{C.removeEventListener("pointermove",se),C.removeEventListener("pointerup",fe),C.removeEventListener("pointercancel",fe),rl=null;try{h.releasePointerCapture(V.pointerId)}catch{}};rl=fe,C.addEventListener("pointermove",se),C.addEventListener("pointerup",fe),C.addEventListener("pointercancel",fe);try{h.setPointerCapture(V.pointerId)}catch{}};h.addEventListener("pointerdown",z),ft=h,so.insertBefore(h,De.element),Wa=()=>{h.removeEventListener("pointerdown",z)}}if(ft){let h=ol();ft.classList.toggle("persona-hidden",!h),bh()}},il=()=>{if(!N||!De||(o.launcher?.sidebarMode??!1)||ht(o)&&Sn(o).reveal==="emerge")return;let h=e.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=R||!hC(o,N))return;let z=o.launcher?.width??o.launcherWidth??In,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ol()?(O.style.width=V,O.style.maxWidth=V):(O.style.width=z,O.style.maxWidth=z)},typeof ResizeObserver<"u"&&(Ha=new ResizeObserver(()=>{To()}),Ha.observe(O))}else O.appendChild(K);ie()&&Y&&(Q.peekBanner&&Y.appendChild(Q.peekBanner),Y.appendChild(Oe)),e.appendChild(W),Y&&e.appendChild(Y);let Xd=()=>{if(ie()){O.style.width="100%",O.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},pn=W.dataset.state==="expanded",ii=Lt.expandedSize??"anchored";if(!(pn&&ii!=="fullscreen")){K.style.background="",K.style.border="",K.style.borderRadius="",K.style.overflow="",K.style.boxShadow="";return}let li=o.theme?.components?.panel,ib=xr(o),Kl=(Yr,Yl)=>Yr==null||Yr===""?Yl:fn(ib,Yr)??Yr,Ot="1px solid var(--persona-border)",nu="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Xl="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";K.style.background="var(--persona-surface, #ffffff)",K.style.border=Kl(li?.border,Ot),K.style.borderRadius=Kl(li?.borderRadius,Xl),K.style.boxShadow=Kl(li?.shadow,nu),K.style.overflow="hidden";return}let a=ht(o),c=o.launcher?.sidebarMode??!1,m=a||c||(o.launcher?.fullHeight??!1),h=o.launcher?.enabled===!1,C=o.launcher?.detachedPanel===!0,R=o.theme?.components?.panel,z=xr(o),V=(Lt,pn)=>Lt==null||Lt===""?pn:fn(z,Lt)??Lt,J=e.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640,se=J.innerWidth<=te,fe=j&&se&&N,$e=a&&j&&se,gt=o.launcher?.position??"bottom-left",$t=gt==="bottom-left"||gt==="top-left",vn=o.launcher?.zIndex??Qt,At="var(--persona-panel-border, 1px solid var(--persona-border))",kt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=C&&!fe&&!$e;ke?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Le=ke?At:c||fe?"none":At,ve=ke?kt:fe?"none":c?$t?"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))":h?"none":kt;a&&!fe&&!ke&&(ve="none",Le="none");let Mt=ke?_:c||fe?"0":_,lt=V(R?.border,Le),Gt=V(R?.shadow,ve),at=V(R?.borderRadius,Mt),cn=ll(),Xt=cn==="detached",qt=cn==="welded";e.classList.toggle("persona-artifact-detached-split",Xt),e.classList.toggle("persona-artifact-welded-split",qt);let He="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)))))",Ae=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&gn(o)&&vg(o)&&h&&!a;e.classList.toggle("persona-artifact-chat-flush",Ae);let Bt=Xt||Ae?"none":Gt,ct=Xt?At:qt?"none":lt,qe=Xt?_:at;Ae&&(ct="none",qe="0");let Dt=R?.borderRadius!=null&&R.borderRadius!=="",Pt=Ae&&!Dt?"0":at,nn=G.scrollTop;e.style.cssText="",W.style.cssText="",O.style.cssText="",K.style.cssText="",G.style.cssText="",Pa||(Oe.style.cssText=""),Kt&&(G.style.display="none"),(m||h)&&(e.style.minWidth="0");let zn=()=>{if(nn<=0)return;(G.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(G.scrollTop===nn)return;let pn=G.scrollHeight-G.clientHeight;pn<=0||(G.scrollTop=Math.min(nn,pn))})};if(fe){W.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"),W.style.cssText=`
|
|
50
50
|
position: fixed !important;
|
|
51
51
|
inset: 0 !important;
|
|
52
52
|
width: 100% !important;
|
|
@@ -56,9 +56,9 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
56
56
|
padding: 0 !important;
|
|
57
57
|
display: flex !important;
|
|
58
58
|
flex-direction: column !important;
|
|
59
|
-
z-index: ${
|
|
59
|
+
z-index: ${vn} !important;
|
|
60
60
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
61
|
-
`,
|
|
61
|
+
`,O.style.cssText=`
|
|
62
62
|
position: relative !important;
|
|
63
63
|
display: flex !important;
|
|
64
64
|
flex-direction: column !important;
|
|
@@ -71,7 +71,7 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
71
71
|
padding: 0 !important;
|
|
72
72
|
box-shadow: none !important;
|
|
73
73
|
border-radius: 0 !important;
|
|
74
|
-
`,
|
|
74
|
+
`,K.style.cssText=`
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
77
|
flex: 1 1 0% !important;
|
|
@@ -82,7 +82,7 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
82
82
|
overflow: hidden !important;
|
|
83
83
|
border-radius: 0 !important;
|
|
84
84
|
border: none !important;
|
|
85
|
-
`,
|
|
85
|
+
`,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Oe.style.flexShrink="0",ne=!0,zn();return}let on=o?.launcher?.width??o?.launcherWidth??In;if(!c&&!a)h&&m?(O.style.width="100%",O.style.maxWidth="100%"):(O.style.width=on,O.style.maxWidth=on);else if(a)if(Sn(o).reveal==="emerge"&&!C){let pn=Sn(o).width;O.style.width=pn,O.style.maxWidth=pn}else O.style.width="100%",O.style.maxWidth="100%";if(il(),O.style.boxShadow=Bt,O.style.borderRadius=Pt,Xt?O.style.border="none":qt&&(O.style.border=lt),K.style.border=ct,K.style.borderRadius=qe,K.style.boxShadow=Xt&&!Ae?He:"",Ae&&(K.style.background="transparent",G.style.background="transparent",Oe.style.background="transparent",Oe.style.borderTop="none"),qt){let Lt=o.features?.artifacts?.layout;nl=Lt?.unifiedSplitOuterRadius?.trim()||Lt?.paneBorderRadius?.trim()||at}else nl=null;if(a&&!fe&&!ke&&!Xt&&!qt&&R?.border===void 0&&(K.style.border="none",Sn(o).side==="right"?K.style.borderLeft="1px solid var(--persona-border)":K.style.borderRight="1px solid var(--persona-border)"),a&&!fe&&qt&&R?.border===void 0&&(Sn(o).side==="right"?O.style.borderLeft="1px solid var(--persona-border)":O.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",h&&(e.style.width="100%"),W.style.display="flex",W.style.flexDirection="column",W.style.flex="1 1 0%",W.style.minHeight="0",W.style.maxHeight="100%",W.style.height="100%",h&&(W.style.overflow="hidden"),O.style.display="flex",O.style.flexDirection="column",O.style.flex="1 1 0%",O.style.minHeight="0",O.style.maxHeight="100%",O.style.height="100%",Xt||(O.style.overflow="hidden"),K.style.display="flex",K.style.flexDirection="column",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.maxHeight="100%",K.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Oe.style.flexShrink="0"),h&&(ke||Xt||Ae)&&!a&&(Ae||(W.style.padding="var(--persona-panel-inset)"),W.style.background="var(--persona-panel-canvas-bg)"),W.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"),!c&&!h&&!a&&(Wn[gt]??Wn["bottom-right"]).split(" ").forEach(pn=>W.classList.add(pn)),c){let Lt=o.launcher?.sidebarWidth??"420px";C?W.style.cssText=`
|
|
86
86
|
position: fixed !important;
|
|
87
87
|
top: var(--persona-panel-inset) !important;
|
|
88
88
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -93,9 +93,9 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
93
93
|
padding: 0 !important;
|
|
94
94
|
display: flex !important;
|
|
95
95
|
flex-direction: column !important;
|
|
96
|
-
z-index: ${
|
|
97
|
-
${
|
|
98
|
-
`:
|
|
96
|
+
z-index: ${vn} !important;
|
|
97
|
+
${$t?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
98
|
+
`:W.style.cssText=`
|
|
99
99
|
position: fixed !important;
|
|
100
100
|
top: 0 !important;
|
|
101
101
|
bottom: 0 !important;
|
|
@@ -106,9 +106,9 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
106
106
|
padding: 0 !important;
|
|
107
107
|
display: flex !important;
|
|
108
108
|
flex-direction: column !important;
|
|
109
|
-
z-index: ${
|
|
110
|
-
${
|
|
111
|
-
`,
|
|
109
|
+
z-index: ${vn} !important;
|
|
110
|
+
${$t?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
111
|
+
`,O.style.cssText=`
|
|
112
112
|
position: relative !important;
|
|
113
113
|
display: flex !important;
|
|
114
114
|
flex-direction: column !important;
|
|
@@ -119,10 +119,10 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
119
119
|
min-height: 0 !important;
|
|
120
120
|
margin: 0 !important;
|
|
121
121
|
padding: 0 !important;
|
|
122
|
-
box-shadow: ${
|
|
123
|
-
border-radius: ${
|
|
124
|
-
${
|
|
125
|
-
`,
|
|
122
|
+
box-shadow: ${Bt} !important;
|
|
123
|
+
border-radius: ${Pt} !important;
|
|
124
|
+
${Xt?"border: none !important;":qt?`border: ${lt} !important;`:""}
|
|
125
|
+
`,O.style.setProperty("width","100%","important"),O.style.setProperty("max-width","100%","important"),K.style.cssText=`
|
|
126
126
|
display: flex !important;
|
|
127
127
|
flex-direction: column !important;
|
|
128
128
|
flex: 1 1 0% !important;
|
|
@@ -131,32 +131,32 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
131
131
|
min-height: 0 !important;
|
|
132
132
|
max-height: 100% !important;
|
|
133
133
|
overflow: hidden !important;
|
|
134
|
-
border-radius: ${
|
|
135
|
-
border: ${
|
|
136
|
-
${
|
|
137
|
-
${
|
|
138
|
-
`,
|
|
134
|
+
border-radius: ${qe} !important;
|
|
135
|
+
border: ${ct} !important;
|
|
136
|
+
${Xt&&!Ae?`box-shadow: ${He} !important;`:""}
|
|
137
|
+
${Ae?"background: transparent !important;":""}
|
|
138
|
+
`,Pa||(Oe.style.cssText=`
|
|
139
139
|
flex-shrink: 0 !important;
|
|
140
140
|
border-top: none !important;
|
|
141
141
|
padding: 8px 16px 12px 16px !important;
|
|
142
|
-
${
|
|
143
|
-
`}if(!x&&!i){let Lt="max-height: -moz-available !important; max-height: stretch !important;",an=u?"":"padding-top: 1.25em !important;",fi=u?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Le.style.cssText+=Lt+an+fi}An()},pc=()=>{e.style.setProperty("--persona-content-max-width",qo(o,Q()))},Kf=()=>{if(Q())return;let i=St(o),u=o.launcher?.sidebarMode??!1;if(i||u||(o.launcher?.fullHeight??!1)||!P)return;let x=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(k&&x.innerWidth<=W)return;let z=x.innerHeight,U=64,j=o.launcher?.heightOffset??0,Y=Math.max(200,z-U),pe=Math.min(640,Y);he.style.height=`${Math.max(200,pe-j)}px`};dc(),Sr(e,o),Is(e,o),Ws(e,o),pc(),Zo=()=>{dc(),Kf(),Sr(e,o),Is(e,o),Ws(e,o),pc(),Vs?e.style.setProperty("--persona-artifact-welded-outer-radius",Vs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let De=[];De.push(()=>{document.removeEventListener("keydown",$f)}),De.push(()=>{Ra!==null&&clearTimeout(Ra)});let _n=null,Un=null;De.push(()=>{_n?.(),_n=null,Un?.(),Un=null}),Ha&&De.push(()=>{Ha?.disconnect(),Ha=null}),De.push(()=>{Fa?.(),Fa=null,cc(),xt&&(xt.remove(),xt=null),Ke?.element.style.removeProperty("width"),Ke?.element.style.removeProperty("maxWidth")}),me&&De.push(()=>{qe!==null&&(cancelAnimationFrame(qe),qe=null),Ae?.destroy(),Ae=null,Ne?.destroy(),Ne=null,Je=null});let tr=null,Xf=()=>{tr&&(tr(),tr=null),o.colorScheme==="auto"&&(tr=pa(()=>{Sr(e,o)}))};Xf(),De.push(()=>{tr&&(tr(),tr=null)}),De.push(d);let Js=o.features?.streamAnimation;if(Js?.type&&Js.type!=="none"){let i=ha(Js.type,Js.plugins);i&&(Al(i,e),De.push(()=>ry(e)))}let Qn=Es(I),Jf=Es(kn),Qf=Es(ee),nr=[Qn,Jf,Qf];De.push(()=>{nr.forEach(i=>i.destroy())});let or=null,q,rr=null,Yf=!1,Zf=0,em=null,tm=i=>i.reduce((u,h)=>h.role==="user"?u+1:u,0),nm=i=>{for(let u=i.length-1;u>=0;u--)if(br(i[u]))return i[u].id??null;return null},om=!1,tx=()=>{om||o.debug!==!0||(om=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},rm=!1,am=!1,sm=(i,u)=>{rm||o.debug!==!0||!u.enabled||u.expose||Yf||am&&(q.isStreaming()||i.some(br)||(rm=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},_r=i=>{if(!q)return;let u=i??q.getMessages(),h=Y=>{Y.render([],q,B,u)},x=Y=>{nr.forEach(pe=>{pe!==Y&&h(pe)})};rr&&(tm(u)>Zf||nm(u)!==em)&&(rr=null);let k=Bo(o);sm(u,k);let W=k.enabled?Ei(u):null,z=rr??W,U=rr?"host":"agent";if(z){let Y=o.suggestions?.followUps,pe=Y?.placement??(Y?"auto":"composer"),ye=(pe==="auto"?Q()?"composer":"after-message":pe)==="after-message"?Qf:Qn;x(ye),ye.render(z,q,B,u,o.suggestionChipsConfig,{source:U,surface:"followUp",variant:Y?.variant??"chip",behavior:Y?.behavior??"send",overflow:Y?.overflow??"wrap",maxItems:Y?.maxItems??4,config:o,plugins:a});return}if(u.some(Y=>Y.role==="user")){nr.forEach(h);return}let j=o.suggestions?.starters;if(j){let Y=Xo(mo(o),u),pe=j.placement??"auto",le=pe==="auto"?Y?"welcome":"composer":pe;if(le==="welcome"&&!Y){tx(),nr.forEach(h);return}let ye=le==="welcome"?Jf:Qn;x(ye),ye.render(j.items??o.suggestionChips,q,B,u,o.suggestionChipsConfig,{surface:"starter",variant:j.variant??"card",behavior:j.behavior??"send",overflow:j.overflow??"wrap",maxItems:j.maxItems??4,config:o,plugins:a});return}x(Qn),Qn.render(o.suggestionChips,q,B,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a})},im=()=>{rr&&(rr=null,_r())},nx=i=>{let u=Array.isArray(i)?[...i]:[];if(!u.length){im();return}let h=q?q.getMessages():[];rr=u,Yf=!0,Zf=tm(h),em=nm(h),_r(h)},In=!1,ar=Xh(),Ur=new Map,sr=new Map,bo=new Map,uc=0,ox=ao()!==null,dn=yl(),pn=0,xo=null,on=!1,Qs=!1,vo=0,Dt=null,ir=null,fc=!1,Ys=!1,lr=null,Oa=!0,Zs=!1,qr=null,ei=!1,cr=()=>{ei=!0,ix()},mc=null,rx=4,Yn=24,ax=80,sx=1e3,Zn=null,lm=()=>{e.setAttribute("data-persona-scrollbar",ec()),ec()!=="on-scroll"&&(Zn!==null&&clearTimeout(Zn),Zn=null,re.removeAttribute("data-persona-scrollbar-visible"))},ix=()=>{ec()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Zn!==null&&clearTimeout(Zn),Zn=setTimeout(()=>{Zn=null,uo(re,Yn)&&re.removeAttribute("data-persona-scrollbar-visible")},sx))};lm(),De.push(()=>{Zn!==null&&clearTimeout(Zn)});let gc=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},cm=o.voiceRecognition?.autoResume??!1,eo=i=>{c.emit("voice:state",{active:je.active,source:i,timestamp:Date.now()})},Wn=()=>{A(i=>({...i,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},lx=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=cf(m.voiceState),u=!!i.active,h=Number(i.timestamp??0);je.manuallyDeactivated=!!i.manuallyDeactivated,u&&Date.now()-h<gS&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("restore"),q.isVoiceActive()&&Kr()}):ci("restore"))},1e3)},cx=()=>q?sb(q.getMessages()).filter(i=>!i.__skipPersist):[],ti=null,dm=(i,u)=>{typeof console<"u"&&console.error(i,u)},hc=(i,u)=>{let h=()=>{try{let z=i();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(U=>{dm(u,U)})}catch(z){return dm(u,z),null}},x=ti,k=x?x.then(()=>h()??void 0):h();if(!k)return;let W=k.finally(()=>{ti===W&&(ti=null)});ti=W};function yc(i){if(!g?.save)return;let h={messages:i?sb(i):q?cx():[],metadata:m,artifacts:Pn.artifacts,selectedArtifactId:Pn.selectedId};hc(()=>g.save(h),"[AgentWidget] Failed to persist state:")}let Vr=null,pm=()=>Le.querySelector("#persona-scroll-container")||re,zr=()=>{Vr!==null&&(cancelAnimationFrame(Vr),Vr=null),on=!1},um=()=>{xo!==null&&(cancelAnimationFrame(xo),xo=null),Qs=!1,zr()},dx=()=>In&&xc()&&(cn()!=="anchor-top"||Tf()),bc=()=>{let i=ka()||"Jump to latest",u=dx();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),vo>0?(Jo.textContent=String(vo),Jo.style.display="",Pt.setAttribute("aria-label",`${i} (${vo} new)`)):(Jo.textContent="",Jo.style.display="none",Pt.setAttribute("aria-label",u?`${i} (response streaming below)`:i))},fm=()=>{vo!==0&&(vo=0,bc())},px=()=>{let i=Dt?.spacerHeight??0;return i<=0?uo(re,Yn):ri(i)-re.scrollTop-re.clientHeight<=Yn},xc=()=>ho()?!dn.isFollowing():!px(),vc=()=>!!q&&q.getMessages().length>0,Vt=()=>{if(!Xb()||Me){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==be&&be.appendChild(Pt),Yo();let u=jn(re)>0&&xc()&&vc();u?bc():fm(),Pt.style.display=u?"":"none"},Na=()=>{dn.pause()&&(um(),Vt())},Co=()=>{dn.resume(),fm(),Vt()},wo=(i=!1)=>{ho()&&vc()&&dn.isFollowing()&&(!i&&!In||(xo!==null&&(cancelAnimationFrame(xo),xo=null),Qs=!0,xo=requestAnimationFrame(()=>{xo=null,Qs=!1,dn.isFollowing()&&ux(pm(),i?220:140)})))},mm=(i,u,h,x=()=>!0)=>{let k=i.scrollTop,W=u(),z=W-k;if(zr(),Math.abs(z)<1){on=!0,i.scrollTop=W,pn=i.scrollTop,on=!1;return}let U=performance.now();on=!0;let j=pe=>1-Math.pow(1-pe,3),Y=pe=>{if(!x()){zr();return}let le=u();le!==W&&(W=le,z=W-k);let ye=pe-U,Ge=Math.min(ye/h,1),ht=j(Ge),ct=k+z*ht;i.scrollTop=ct,pn=i.scrollTop,Ge<1?Vr=requestAnimationFrame(Y):(i.scrollTop=W,pn=i.scrollTop,Vr=null,on=!1)};Vr=requestAnimationFrame(Y)},ux=(i,u=500)=>{let h=jn(i)-i.scrollTop;if(Math.abs(h)<1){pn=i.scrollTop;return}if(Math.abs(h)>=ax){zr(),on=!0,i.scrollTop=jn(i),pn=i.scrollTop,on=!1;return}mm(i,()=>jn(i),u,()=>dn.isFollowing())},gm=()=>{if(!vc()){Vt();return}let i=pm();on=!0,i.scrollTop=jn(i),pn=i.scrollTop,on=!1,Vt()},dr=i=>{let u=0,h=i;for(;h&&h!==re;)u+=h.offsetTop,h=h.offsetParent;return u},fx=()=>{let i=re.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??re.ownerDocument.getSelection()},ni=()=>ey(fx(),re),hm=()=>{if(Jb()!=="last-user-turn")return!1;let i=q?.getMessages()??[];if(i.length<2)return!1;let u=[...i].reverse().find(W=>W.role==="user");if(!u)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=re.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let k=Math.min(Math.max(0,dr(x)-La()),jn(re));return on=!0,re.scrollTop=k,pn=re.scrollTop,on=!1,cn()==="follow"&&!uo(re,Yn)&&dn.pause(),Vt(),!0},oi=i=>{let u=Math.max(0,Math.round(i));vn.style.height=`${u}px`,vn.style.display=u>0?"":"none",Dt&&(Dt.spacerHeight=Math.max(0,i))},ri=i=>{let u=parseFloat(getComputedStyle(re).paddingBottom)||0,h=0;for(let k of Array.from(re.children)){if(k===vn||k.offsetHeight===0)continue;let W=dr(k)+k.offsetHeight;W>h&&(h=W)}let x=re.scrollHeight-i;return h>0?Math.min(h+u,x):x},mx=()=>{if(!Dt||Dt.spacerHeight<=0)return;let i=ri(Dt.spacerHeight),u=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-i+Yn);u<Dt.spacerHeight&&(oi(u),Vt())},_a=()=>{ir!==null&&(cancelAnimationFrame(ir),ir=null),zr(),Dt=null,vn.style.height="0px",vn.style.display="none"},ym=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Cc=i=>re.querySelector(`[data-message-id="${ym(i)}"]`),bm=i=>{ir!==null&&cancelAnimationFrame(ir),ir=requestAnimationFrame(()=>{ir=null;let u=ym(i),h=re.querySelector(`[data-message-id="${u}"]`);if(!h)return;let x=dr(h),k=Dt?.spacerHeight??0,W=ri(k),{targetScrollTop:z,spacerHeight:U}=Mu({anchorOffsetTop:x,topOffset:La(),viewportHeight:re.clientHeight,contentHeight:W,slack:Yn});Dt={initialSpacerHeight:U,contentHeightAtAnchor:W,spacerHeight:U},oi(U),mm(re,()=>h.isConnected?Math.max(0,dr(h)-La()):z,220)})},xm=()=>{if(cn()!=="anchor-top"||!Dt||!qr)return;let i=Cc(qr);if(!i)return;zr();let u=Dt.spacerHeight,h=ri(u),{targetScrollTop:x,spacerHeight:k}=Mu({anchorOffsetTop:dr(i),topOffset:La(),viewportHeight:re.clientHeight,contentHeight:h,slack:Yn});Dt={initialSpacerHeight:k,contentHeightAtAnchor:h,spacerHeight:k},oi(k),on=!0,re.scrollTop=x,pn=re.scrollTop,on=!1,Vt()},gx=()=>{if(ho()){if(!dn.isFollowing()||uo(re,1))return;wo(!In);return}if(Dt&&Dt.initialSpacerHeight>0){let i=re.scrollHeight-Dt.spacerHeight,u=ty({initialSpacerHeight:Dt.initialSpacerHeight,contentHeightAtAnchor:Dt.contentHeightAtAnchor,currentContentHeight:i});u!==Dt.spacerHeight&&oi(u)}Vt()},hx=i=>{let u=cn();u==="follow"?(Co(),wo(!0)):u==="anchor-top"&&(Oa=!1,Zs=!0,ei=!1,qr=i,bm(i))},yx=()=>{if(cn()==="anchor-top"){if(Zs){Oa=!1;return}Oa=!0,_a(),Co(),wo(!0)}},bx=96,xx=i=>{if(lr===null)return!0;let u=Cc(lr),h=Cc(i);if(!u||!h)return!0;let x=dr(h)-dr(u);return La()+x>re.clientHeight-bx},vx=i=>{if(cn()!=="anchor-top"||!Zs||ei||ni())return;let u=lr===null;for(let h of i){if(!u){h.id===lr&&(u=!0);continue}if(Zh(h)){if(h.id===qr||!xx(h.id))return;qr=h.id,bm(h.id);return}}},Cx=i=>{let u=new Map;i.forEach(h=>{let x=gc.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(c.emit("assistant:message",h),!Ys&&(cn()!=="anchor-top"||Tf())&&xc()&&(vo+=1,bc(),Vt(),kf(vo===1?"1 new message below.":`${vo} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&c.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&c.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):c.emit("approval:requested",{approval:h.approval,message:h}))}),gc.clear(),u.forEach((h,x)=>{gc.set(x,h)})},ai=(i,u)=>{let h=u==="user"?"user":"assistant",x=o.layout?.messages?.[h],k=x?.width??"content",W=x?.maxWidth??(k==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${u}`,`persona-message-width-${k}`),i.classList.toggle("persona-justify-end",u==="user"),i.setAttribute("data-message-role",u),i.setAttribute("data-message-width",k),i.style.setProperty("--persona-message-row-max-width",W)},pr=(i,u)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${i}`,h.setAttribute("data-wrapper-id",i),ai(h,u),h},wx=(i,u,h)=>{let x=document.createElement("div"),W=(()=>{let _=a.find(Re=>Re.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),z=(_,Re)=>Re==null?!1:typeof Re=="string"?(_.textContent=Re,!0):(_.appendChild(Re),!0),U=new Set,j=new Map,Y=new Set,pe=a.some(_=>_.renderAskUserQuestion),le=[],ye=[],Ge=o.enableComponentStreaming!==!1,ht=o.approval!==!1,ct=[];if(u.forEach(_=>{U.add(_.id),j.set(_.id,_.role);let Re=pe&&so(_),Fe=ht&&_.variant==="approval"&&!!_.approval,Ee=!Re&&_.role==="assistant"&&!_.variant&&Ge&&Os(_);!Fe&&bo.has(_.id)&&(i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(_.id)),!Ee&&sr.has(_.id)&&(i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),sr.delete(_.id));let At=so(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=Kh(_,uc)+At,Ot=Re||Fe||Ee?null:Jh(ar,_.id,dt);if(Ot){x.appendChild(Ot.cloneNode(!0)),so(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}let pt=null,rn=a.find(Oe=>!!(_.variant==="reasoning"&&Oe.renderReasoning||_.variant==="tool"&&Oe.renderToolCall||!_.variant&&Oe.renderMessage)),Wt=o.layout?.messages;if(so(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){Ur.delete(_.id),i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(br(_)&&Bo(o).enabled)return;if(so(_)&&o.features?.askUserQuestion?.enabled!==!1){let Oe=a.find(zt=>typeof zt.renderAskUserQuestion=="function");if(Oe&&at.current){let zt=Ur.get(_.id),$t=zt!==dt,Ct=null;if($t){let{payload:Xe,complete:He}=io(_),yt=_.id,jt=()=>at.current?.getMessages().find(An=>An.id===yt);Ct=Oe.renderAskUserQuestion({message:_,payload:Xe,complete:He,resolve:An=>{let Qa=jt();Qa&&at.current?.resolveAskUserQuestion(Qa,An)},dismiss:()=>{let An=jt();An?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(An),at.current?.resolveAskUserQuestion(An,"(dismissed)"))},config:o})}let st=zt!=null;if($t&&Ct===null&&!st){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}let ft=pr(_.id,_.role);ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),le.push({messageId:_.id,fingerprint:dt,bubble:Ct});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}}else if(Fe){let Oe=a.find(st=>typeof st.renderApproval=="function")??p,$t=bo.get(_.id)!==dt,Ct=null;if($t&&Oe?.renderApproval){let st=_.id,ft=(Xe,He)=>{let yt=at.current?.getMessages().find(jt=>jt.id===st);yt?.approval&&(yt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(yt.id,Xe):at.current?.resolveApproval(yt.approval,Xe,He))};Ct=Oe.renderApproval({message:_,defaultRenderer:()=>Ol(_,o),config:o,approve:Xe=>ft("approved",Xe),deny:Xe=>ft("denied",Xe)})}if($t&&Ct===null)i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(_.id),pt=Ol(_,o);else{let st=pr(_.id,_.role);st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),x.appendChild(st),ct.push({messageId:_.id,fingerprint:dt,bubble:Ct});return}}else if(rn)if(_.variant==="reasoning"&&_.reasoning&&rn.renderReasoning){if(!ue)return;pt=rn.renderReasoning({message:_,defaultRenderer:()=>Gu(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&rn.renderToolCall){if(!oe)return;pt=rn.renderToolCall({message:_,defaultRenderer:()=>Xu(_,o),config:o})}else rn.renderMessage&&(pt=rn.renderMessage({message:_,defaultRenderer:()=>{let Oe=ba(_,h,Wt,o.messageActions,gt,{loadingIndicatorRenderer:W,widgetConfig:o});return _.role!=="user"&&af(Oe,_,o,q),Oe},config:o}));if(!pt&&Ee){let Oe=jl(_);if(Oe){let zt=sr.get(_.id),$t=zt!==dt,Ct=o.wrapComponentDirectiveInBubble!==!1&&Nn.getOptions(Oe.component)?.bubbleChrome!==!1,st=null;if($t){let ft=$l(Oe,{config:o,message:_,transform:h});if(ft&&Oe.component==="PersonaArtifactInline"){let Xe=ft.hasAttribute("data-artifact-inline")?ft:ft.querySelector("[data-artifact-inline]"),He=Xe?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,jt=He?i.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Xe&&jt&&jt!==Xe&&qh(jt)&&(Xe===ft?ft=jt:Xe.replaceWith(jt))}if(ft)if(Ct){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${_.id}`,Xe.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(He)}Xe.appendChild(ft),st=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${_.id}`,Xe.setAttribute("data-message-id",_.id),Xe.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(He)}Xe.appendChild(ft),st=Xe}}if(st||zt!=null){let ft=pr(_.id,_.role);ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),ye.push({messageId:_.id,fingerprint:dt,bubble:st});return}}}if(!pt)if(_.variant==="reasoning"&&_.reasoning){if(!ue)return;pt=Gu(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!oe)return;pt=Xu(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;pt=Ol(_,o)}else{let Oe=o.layout?.messages;Oe?.renderUserMessage&&_.role==="user"?pt=Oe.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):Oe?.renderAssistantMessage&&_.role==="assistant"?pt=Oe.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):pt=ba(_,h,Oe,o.messageActions,gt,{loadingIndicatorRenderer:W,widgetConfig:o}),_.role!=="user"&&pt&&af(pt,_,o,q)}let Ie=pr(_.id,_.role);Ie.appendChild(pt),Qh(ar,_.id,dt,Ie),x.appendChild(Ie)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Fe=Re.getAttribute("data-persona-ask-sheet-for");Fe&&!Y.has(Fe)&&Wo(Te.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let _=[],Re=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(Ee=>{if(Ee.variant==="tool"&&Ee.toolCall&&oe){Re.push(Ee);return}Ee.variant==="reasoning"&&!ue||((Re.length>1||Fe&&Re.length>0)&&_.push(Re),Re=[])}),(Re.length>1||Fe&&Re.length>0)&&_.push(Re),_.forEach(Ee=>{let At=Ee.map(Oe=>Array.from(x.children).find(zt=>zt instanceof HTMLElement&&zt.getAttribute("data-wrapper-id")===Oe.id)).filter(Oe=>!!Oe);if(At.length<(Fe?1:2))return;let dt=pr(`tool-group-${Ee[0].id}`,"assistant");dt.setAttribute("data-persona-tool-group-row","true");let Ot=document.createElement("div");Ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ot.setAttribute("data-persona-tool-group","true");let pt=document.createElement("div");pt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",pt.id=`tool-group-summary-${Ee[0].id}`;let rn=`Called ${Ee.length} ${Ee.length===1?"tool":"tools"}`,Wt=o.toolCall?.renderGroupedSummary?.({messages:Ee,toolCalls:Ee.map(Oe=>Oe.toolCall).filter(Oe=>!!Oe),defaultSummary:rn,config:o});z(pt,Wt)||(pt.textContent=rn);let Ie=document.createElement("div");Ie.className="persona-tool-group-stack persona-flex persona-flex-col",Ie.id=`tool-group-stack-${Ee[0].id}`,Ie.setAttribute("data-persona-tool-group-stack","true"),Ot.appendChild(pt),Fe||Ot.appendChild(Ie),dt.appendChild(Ot),At[0].before(dt),At.forEach((Oe,zt)=>{if(Fe){Oe.remove();return}Oe.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),zt<At.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Oe),Ie.appendChild($t)})})}Yh(ar,U);let un=u.some(_=>_.role==="assistant"&&_.streaming),Mt=u[u.length-1],It=Mt?.role==="assistant"&&!Mt.streaming&&Mt.variant!=="approval";if(In&&u.some(_=>_.role==="user")&&!un&&!It){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:Pr},Re=a.find(Ee=>Ee.renderLoadingIndicator),Fe=null;if(Re?.renderLoadingIndicator&&(Fe=Re.renderLoadingIndicator(_)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(_)),Fe===null&&(Fe=Pr()),Fe){let Ee=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1,dt=o.layout?.messages?.layout??"bubble";Ee.className=At?ks("assistant",dt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ee.setAttribute("data-typing-indicator","true"),At&&(Ee.style.color="var(--persona-message-assistant-text, var(--persona-text))",dt!=="flat"&&(Ee.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ee.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ee.appendChild(Fe);let Ot=pr("typing-indicator","assistant");Ot.appendChild(Ee),x.appendChild(Ot)}}if(!In&&u.length>0){let _=u[u.length-1],Re={config:o,lastMessage:_,messageCount:u.length},Fe=a.find(At=>At.renderIdleIndicator),Ee=null;if(Fe?.renderIdleIndicator&&(Ee=Fe.renderIdleIndicator(Re)),Ee===null&&o.loadingIndicator?.renderIdle&&(Ee=o.loadingIndicator.renderIdle(Re)),Ee){let At=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;At.className=dt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Ee);let Ot=pr("idle-indicator","assistant");Ot.appendChild(At),x.appendChild(Ot)}}if(vg(x),hl(i,x),Gc(i),le.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of le){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),Ur.set(_,Re)))}if(Ur.size>0)for(let _ of Ur.keys())U.has(_)||Ur.delete(_);if(ye.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of ye){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),sr.set(_,Re)))}if(sr.size>0)for(let _ of sr.keys())U.has(_)||sr.delete(_);if(ct.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of ct){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),bo.set(_,Re)))}if(bo.size>0)for(let _ of bo.keys())U.has(_)||bo.delete(_)},Ua=(i,u,h)=>{wx(i,u,h),qf()},qa=null,Ax=()=>{if(qa)return;let i=h=>{let x=h.composedPath();x.includes(Le)||tt&&x.includes(tt)||lt(!1,"user")};qa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},vm=()=>{if(!qa)return;(e.ownerDocument??document).removeEventListener("pointerdown",qa,!0),qa=null};De.push(()=>vm());let Va=null,Sx=()=>{if(Va)return;let i=h=>{h.key==="Escape"&&(h.isComposing||lt(!1,"user"))};Va=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Cm=()=>{if(!Va)return;(e.ownerDocument??document).removeEventListener("keydown",Va,!0),Va=null};De.push(()=>Cm());let za=!1,wm=new Set,Mx=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},$r=()=>{if(!Q())return;let i=Te.peekBanner,u=Te.peekTextNode;if(!i||!u)return;if(J){i.classList.remove("persona-pill-peek--visible");return}let h=q?.getMessages()??[],x;for(let Mt=h.length-1;Mt>=0;Mt--){let It=h[Mt];if(It.role==="assistant"&&It.content){x=It;break}}if(!x){i.classList.remove("persona-pill-peek--visible");return}let k=x.content,W=!!x.streaming,z=Mx(),U=vl(z),j=U.type!=="none"?ha(U.type,z?.plugins):null,Y=j?.isAnimating?.(x)===!0,pe=j!==null&&(W||Y);pe&&j&&!wm.has(j.name)&&(Al(j,e),wm.add(j.name));let le=pe&&j?.containerClass?j.containerClass:null,ye=u.dataset.personaPeekStreamClass??null;ye&&ye!==le&&(u.classList.remove(ye),delete u.dataset.personaPeekStreamClass),le&&ye!==le&&(u.classList.add(le),u.dataset.personaPeekStreamClass=le),pe?(u.style.setProperty("--persona-stream-step",`${U.speed}ms`),u.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Ge=pe?Cl(k,U.buffer,j,x,W):k;if(pe&&U.placeholder==="skeleton"&&W&&(!Ge||!Ge.trim())){let Mt=document.createElement("div"),It=Ss();It.classList.add("persona-pill-peek__skeleton"),Mt.appendChild(It),hl(u,Mt)}else{let Mt=Math.max(0,Ge.length-100),It=Ge.length>100?Ge.slice(-100):Ge,_=Vn(It);if(!pe||!j){let Re=Ge.length>100?`\u2026${It}`:It;u.textContent!==Re&&(u.textContent=Re)}else{let Re=_;(j.wrap==="char"||j.wrap==="word")&&(Re=As(_,j.wrap,`peek-${x.id}`,{skipTags:j.skipTags,startIndex:Mt}));let Fe=document.createElement("div");if(Fe.innerHTML=Re,j.useCaret&&It.length>0){let Ee=wl(),At=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=At[At.length-1];dt?.parentNode?dt.parentNode.insertBefore(Ee,dt.nextSibling):Fe.appendChild(Ee)}hl(u,Fe),j.onAfterRender?.({container:u,bubble:i,messageId:x.id,message:x,speed:U.speed,duration:U.duration})}}let un=In||za;i.classList.toggle("persona-pill-peek--visible",un)};if(Q()){let i=Te.peekBanner;if(i){let x=k=>{k.preventDefault(),k.stopPropagation(),lt(!0,"user")};i.addEventListener("pointerdown",x),De.push(()=>{i.removeEventListener("pointerdown",x)})}let u=()=>{za||(za=!0,$r())},h=()=>{za&&(za=!1,$r())};he.addEventListener("pointerenter",u),he.addEventListener("pointerleave",h),De.push(()=>{he.removeEventListener("pointerenter",u),he.removeEventListener("pointerleave",h)}),tt&&(tt.addEventListener("pointerenter",u),tt.addEventListener("pointerleave",h),De.push(()=>{tt.removeEventListener("pointerenter",u),tt.removeEventListener("pointerleave",h)}))}let Tx=i=>{let u=o.launcher?.composerBar??{},h=u.expandedSize??"anchored",x=u.bottomOffset??"16px",k=u.collapsedMaxWidth,W=u.expandedMaxWidth??"880px",z=u.expandedTopOffset??"5vh",U=u.modalMaxWidth??"880px",j=u.modalMaxHeight??"min(90vh, 800px)",Y="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",le=Le.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",tt){let ye=tt.style;ye.bottom=x,ye.width=k??""}if(i&&h!=="fullscreen"){if(h==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=U,le.maxWidth=Y,le.maxHeight=j,le.height=j;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${x} + ${pe})`,le.top=z,le.width=W,le.maxWidth=Y}},$a=()=>{if(!Z())return;if(Q()){let Y=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=J?"expanded":"collapsed";Le.dataset.state=pe,Le.dataset.expandedSize=Y,tt&&(tt.dataset.state=pe,tt.dataset.expandedSize=Y),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Tx(J),be.style.display=J?"flex":"none",Zo(),J?(Ax(),Sx()):(vm(),Cm()),$r();return}let i=St(o),u=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,k=u.innerWidth<=h,W=x&&k&&P,z=ln(o).reveal;J?(Le.style.removeProperty("display"),Le.style.display=i?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),kt?(kt.setPanelOpen(!0),kt.element.style.display="none"):Yt&&(Yt.style.display="none")):(i?i&&(z==="overlay"||z==="push")&&!W?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),kt?(kt.setPanelOpen(!1),kt.element.style.display=i?"none":""):Yt&&(Yt.style.display=i?"none":""))},lt=(i,u="user")=>{if(!Z()||J===i)return;let h=J;J=i,$a();let x=(()=>{let W=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,j=o.launcher?.mobileBreakpoint??640,Y=z.innerWidth<=j,pe=St(o)&&U&&Y,le=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return W||U&&Y&&P||pe||le})();if(J&&x){if(!_n){let W=e.getRootNode(),z=W instanceof ShadowRoot?W.host:e.closest(".persona-host");z&&(_n=Pu(z,o.launcher?.zIndex??Ut))}Un||(Un=Ru(e.ownerDocument))}else J||(_n?.(),_n=null,Un?.(),Un=null);J&&(Xa(),hm()||(cn()==="follow"?wo(!0):gm()));let k={open:J,source:u,timestamp:Date.now()};J&&!h?c.emit("widget:opened",k):!J&&h&&c.emit("widget:closed",k),c.emit("widget:state",{open:J,launcherEnabled:P,voiceActive:je.active,streaming:q.isStreaming()})},si=i=>{Us(i?"stop":"send"),te&&(te.disabled=i),nr.forEach(u=>{u.elements.forEach(h=>{h.toggleAttribute("data-disabled",i),h instanceof HTMLButtonElement||h.setAttribute("aria-disabled",i?"true":"false")}),u.buttons.forEach(h=>{h.disabled=i})}),Tc.forEach(u=>{u.toggleAttribute("data-disabled",i),u instanceof HTMLButtonElement?u.disabled=i:u.setAttribute("aria-disabled",i?"true":"false"),u.querySelectorAll("button").forEach(h=>{h.disabled=i})}),we.dataset.personaComposerStreaming=i?"true":"false",we.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=i)})},wc=()=>{je.active||B&&B.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>wc(),200)});let Ac=!K.hidden,Ao=null,Am=!b,Sm=null,Mm,Tm=null,ja=null,Sc=i=>{let u=mo(o),h=`${u.variant}|${u.dismiss}|${u.title}|${u.subtitle}`;(h!==Sm||u.icon!==Mm)&&(Sm=h,Mm=u.icon,Bl({host:K,iconHolder:V,title:ce,subtitle:Ve,starterSuggestions:kn},u));let x=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;x!==Tm&&(Tm=x,Dl(X,u.message,o));let k=i??(q?q.getMessages():o.initialMessages),W=Xo(u,k),z=W!==Ac;if(Ac=W,ja){Ao?.cancel(),Ao=null,xa(re,K,!0);return}if(z&&!W&&u.dismiss==="on-first-message"&&Am){Ao=yy(K,U=>{Ao===U&&(Ao=null),!Ac&&!ja&&(xa(re,K,!1),xm()),U?.cancel()});return}if(Ao){if(!W)return;Ao.cancel(),Ao=null}xa(re,K,W),z&&!W&&xm()},Mc=[],Tc=[],Ec=!1,Em=null,km,Lm=()=>{Tc.length=0;let i=Mc.splice(0,Mc.length);for(let u of i)try{u()}catch(h){console.warn("[persona] renderWelcome cleanup threw",h)}};De.push(Lm);let Ex=(i,u)=>{let h=Wu(i,u);if(!h)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let x=o.suggestions?.starters,k=Hu({item:{...h,behavior:h.behavior??x?.behavior??"send"},index:u,surface:"starter",source:"config",variant:x?.variant??"card",streaming:s?q.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:q,getTextarea:()=>B,eventTarget:K});return Tc.push(k),k},kc=()=>{if(Ec)return;Ec=!0;let i=mo(o);Em=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,km=i.icon;try{Lm(),gy(re,K,ja),ja=null;let u=q?q.getMessages():o.initialMessages,h=Xo(i,u),x=0,k=null;for(let W of a)if(W.renderWelcome&&(k=W.renderWelcome({config:i,variant:i.variant,visible:h,defaultRenderer:()=>K,sendMessage:z=>{if(!q||q.isStreaming())return;let U=z.trim();U&&q.sendMessage(U)},requestRender:()=>kc(),renderStarter:z=>Ex(z,x++),storage:l(W.id),onCleanup:z=>{Mc.push(z)}}),k))break;k&&k!==K&&(ja=k,my(re,K,k))}finally{Ec=!1}Sc()},kx=()=>{let i=mo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Em&&i.icon===km||kc()},Lc=()=>{Sc(),rc||(B.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!q?.isStreaming()&&(y.textContent=o.copy?.sendButtonLabel??"Send")),B.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',B.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=m.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{A(u=>({...u,sessionId:i}))}});let ur=null,Lx=()=>{ur==null&&(ur=setInterval(()=>{let i=xe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(ur),ur=null;return}let u=Date.now();i.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=Li(u-x))})},100))},Pc=(i,u)=>{if(Object.is(i,u))return!0;if(i===null||u===null||typeof i!="object"||typeof u!="object")return!1;if(Array.isArray(i)||Array.isArray(u))return!Array.isArray(i)||!Array.isArray(u)||i.length!==u.length?!1:i.every((z,U)=>Pc(z,u[U]));let h=i,x=u,k=Object.keys(h),W=Object.keys(x);return k.length===W.length&&k.every(z=>Object.prototype.hasOwnProperty.call(x,z)&&Pc(h[z],x[z]))},Pm=i=>{let{content:u,rawContent:h,llmContent:x,...k}=i;return k},Rc=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Os(i),Px=(i,u,h)=>{if(i.length!==u.length)return!1;let x=i[h.index],k=u[h.index];return!x||!k||x.id!==h.id||k.id!==h.id?!1:(!Object.is(x.content,k.content)||!Object.is(x.rawContent,k.rawContent)||!Object.is(x.llmContent,k.llmContent))&&Rc(x)&&Rc(k)&&Pc(Pm(x),Pm(k))},Rm=null,jr=null,fr=null,to=null,ii=i=>{Rm=i;let u,h;jr=null;for(let k=i.length-1;k>=0;k-=1){let W=i[k];if(!u&&W.role==="user"&&(u=W),!h&&W.role==="assistant"&&(h=W),!jr&&Rc(W)&&(jr={index:k,id:W.id}),u&&h&&jr)break}Ua(xe,i,ie),Cu(xe,Pn.artifacts,{suppressTransition:In}),Lx(),Sc(i),_r(i),wo(!In),Cx(i),i.length===0&&(_a(),Oa=!0,Zs=!1,qr=null,ei=!1),!fc||Ys?(fc=!0,lr=u?.id??null,mc=h?.id??null):u&&u.id!==lr?(lr=u.id,hx(u.id)):h&&h.id!==mc&&yx(),h&&(mc=h.id),vx(i);let x=je.lastUserMessageId;u&&u.id!==x&&(je.lastUserMessageId=u.id,c.emit("user:message",u)),je.lastUserMessageWasVoice=!!u?.viaVoice,yc(i),$r()},Ic=()=>{to!==null&&(cancelAnimationFrame(to),to=null);let i=fr;fr=null,i&&ii(i)},Im=()=>{to!==null&&cancelAnimationFrame(to),to=null,fr=null},Rx=i=>{let u=fr??Rm;if(In&&u&&jr&&Px(u,i,jr)){fr=i,to===null&&(to=requestAnimationFrame(()=>{to=null;let h=fr;fr=null,h&&ii(h)}));return}if(i.length===0){Im(),ii(i);return}Ic(),ii(i)};q=new ca(o,{onMessagesChanged(i){Rx(i)},onStatusChanged(i){let u=o.statusIndicator??{};En(N,(x=>x==="idle"?u.idleText??Ht.idle:x==="connecting"?u.connectingText??Ht.connecting:x==="connected"?u.connectedText??Ht.connected:x==="error"?u.errorText??Ht.error:x==="paused"?u.pausedText??Ht.paused:x==="resuming"?u.resumingText??Ht.resuming:Ht[x])(i),u,i)},onStreamingChanged(i){i||(q?.getMessages().length===0?Im():Ic()),In=i,si(i),q&&Ua(xe,q.getMessages(),ie),i||(wo(!0),mx(),am=!0,q&&sm(q.getMessages(),Bo(o))),Vt(),kf(i?"Responding\u2026":"Response complete."),$r()},onVoiceStatusChanged(i){if(c.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":no(),Kr();break;case"processing":no(),qx();break;case"speaking":no(),Vx();break;default:i==="idle"&&q.isBargeInActive()?(no(),Kr(),te?.setAttribute("aria-label","End voice session")):(je.active=!1,no(),eo("system"),Wn());break}},onArtifactsState(i){Pn=i,i.artifacts.length===0&&(Fr=!1),Cu(xe,i.artifacts,{suppressTransition:In}),Jn(),yc()},onReconnect(i){let{executionId:u,lastEventId:h}=i.handle;i.phase==="paused"?c.emit("stream:paused",{executionId:u,after:h}):i.phase==="resuming"?c.emit("stream:resuming",{executionId:u,after:h,attempt:i.attempt??1}):c.emit("stream:resumed",{executionId:u,after:h})}}),at.current=q,De.push(()=>q.cancel());let Wc=null;if(q.onReadAloudChange((i,u)=>{_f=i,Uf=u,qf();let h=i??Wc;i&&(Wc=i);let x=h?q.getMessages().find(k=>k.id===h)??null:null;c.emit("message:read-aloud",{messageId:h,message:x,state:u,timestamp:Date.now()}),u==="idle"&&(Wc=null)}),s=!0,fc=!0,o.voiceRecognition?.provider?.type==="runtype")try{q.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&q.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ne||o.onSSEEvent)&&q.setSSEEventCallback((i,u)=>{o.onSSEEvent?.(i,u),_e?.processEvent(i,u),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(u)})});let Wm=()=>{o.resume&&typeof o.reconnectStream=="function"&&q.resumeFromHandle(o.resume)};b?b.then(i=>{if(i){if(i.metadata&&(m=cf(i.metadata),M.syncFromMetadata()),i.messages?.length){Ys=!0;try{q.hydrateMessages(i.messages)}finally{Ys=!1}}i.artifacts?.length&&q.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Am=!0,Wm()}):Wm();let Hm=()=>{!Q()||J||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},Ix=(i,u)=>i?u?{refs:[...i.refs,...u.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([i.finalize(),u.finalize()]),k=[];return h.status==="fulfilled"?k.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?k.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),wS(k)}}:i:u,Wx=()=>{let u=B.getInlineMessageFields?.();return u&&u.contentSegments.some(x=>x.kind==="mention")?u.contentSegments:void 0},Ga=!1,Hx=async i=>{let u=B.value.trim(),h=bt?.hasAttachments()??!1,x=u?await(Qt?.takeInlineCommand(u)??Promise.resolve(null)):null;if(x?.kind==="action"){B.value="",B.style.height="auto",Ka(),Qt?.clear();return}let k=Qt?.collectForSubmit()??null,W=x?.kind==="server"?x.mentions:null,z=Ix(k,W),U=x?.kind==="prompt"?x.sendText:u,j=!!k&&k.refs.length>0;if(!U&&!h&&!j&&!W)return;Hm();let Y;h&&(Y=[],Y.push(...bt.getContentParts()),U&&Y.push(Oo(U)));let pe=x?.kind==="prompt"?void 0:Wx();B.value="",B.style.height="auto",Ka(),q.sendMessage(U,{contentParts:Y,mentions:z??void 0,contentSegments:pe,viaVoice:i?.viaVoice}),h&&bt.clearAttachments(),k&&Qt?.clear()},Hc=async i=>{if(!Ga){Ga=!0;try{await Hx(i)}finally{Ga=!1}}},li=i=>{if(i.preventDefault(),q.isStreaming()){q.cancel(),_e?.reset(),Ae?.update();return}Ga||Hc()},Bx=()=>o.features?.composerHistory!==!1,Bc={...Su},Dc=!1,Ka=()=>{Bc={...Su}},Dx=()=>q.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Fx=i=>{if(!B)return;Dc=!0,B.value=i,B.dispatchEvent(new Event("input",{bubbles:!0})),Dc=!1;let u=B.value.length;B.setSelectionRange(u,u)},Ox=i=>{Dc||(i.isComposing||Qt?.handleInput(i.inputType??void 0),Ka())},Nx=i=>{if(B&&!(!i.isComposing&&Qt?.handleKeydown(i))){if(Bx()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let u=B.selectionStart===0&&B.selectionEnd===0,h=Gh({direction:i.key==="ArrowUp"?"up":"down",history:Dx(),currentValue:B.value,atStart:u,state:Bc});if(Bc=h.state,h.handled){i.preventDefault(),h.value!==void 0&&Fx(h.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(q.isStreaming()){i.preventDefault();return}if(Ga){i.preventDefault();return}Ka(),i.preventDefault(),y.click()}}},Bm=i=>{i.key!=="Escape"||i.isComposing||q.isStreaming()&&i.composedPath().includes(be)&&(q.cancel(),_e?.reset(),Ae?.update(),Ka(),i.preventDefault(),i.stopImmediatePropagation())},_x=async i=>{if(o.attachments?.enabled!==!0||!bt)return;let u=bS(i.clipboardData);u.length!==0&&(i.preventDefault(),await bt.handleFiles(u))},Cn=null,qn=!1,Gr=null,vt=null,Dm=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ci=(i="user")=>{if(qn||q.isStreaming())return;let u=Dm();if(!u)return;Cn=new u;let x=(o.voiceRecognition??{}).pauseDuration??2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let k=B.value;Cn.onresult=W=>{let z="",U="";for(let Y=0;Y<W.results.length;Y++){let pe=W.results[Y],le=pe[0].transcript;pe.isFinal?z+=le+" ":U=le}let j=k+z+U;B.value=j,Gr&&clearTimeout(Gr),(z||U)&&(Gr=window.setTimeout(()=>{B.value.trim()&&Cn&&qn&&(So(),Hc({viaVoice:!0}))},x))},Cn.onerror=W=>{W.error!=="no-speech"&&So()},Cn.onend=()=>{if(qn){let W=B.value.trim();W&&W!==k.trim()&&Hc({viaVoice:!0}),So()}};try{if(Cn.start(),qn=!0,je.active=!0,i!=="system"&&(je.manuallyDeactivated=!1),eo(i),Wn(),te){let W=o.voiceRecognition??{};vt={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:W.iconName??"mic",iconSize:parseFloat(W.iconSize??o.sendButton?.size??"40")||24};let z=W.recordingBackgroundColor,U=W.recordingIconColor,j=W.recordingBorderColor;if(te.classList.add("persona-voice-recording"),te.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let Y=te.querySelector("svg");Y&&Y.setAttribute("stroke",U)}j&&(te.style.borderColor=j),te.setAttribute("aria-label","Stop voice recognition")}}catch{So("system")}},So=(i="user")=>{if(qn){if(qn=!1,Gr&&(clearTimeout(Gr),Gr=null),Cn){try{Cn.stop()}catch{}Cn=null}if(je.active=!1,eo(i),Wn(),te){if(te.classList.remove("persona-voice-recording"),vt){te.style.backgroundColor=vt.backgroundColor,te.style.color=vt.color,te.style.borderColor=vt.borderColor;let u=te.querySelector("svg");u&&u.setAttribute("stroke",vt.color||"currentColor"),vt=null}te.setAttribute("aria-label","Start voice recognition")}}},Ux=(i,u)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=i?.provider?.type==="runtype",k=i?.provider?.type==="custom";if(!(h||x||k))return null;let z=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button";let j=i?.tooltipText??"Start voice recognition";U.setAttribute("aria-label",j);let Y=i?.iconName??"mic",pe=u?.size??"40px",le=i?.iconSize??pe,ye=parseFloat(le)||24,Ge=i?.backgroundColor??u?.backgroundColor,ht=i?.iconColor??u?.textColor;U.style.width=le,U.style.height=le,U.style.minWidth=le,U.style.minHeight=le,U.style.fontSize="18px",U.style.lineHeight="1",ht?U.style.color=ht:U.style.color="var(--persona-text, #111827)";let un=ae(Y,ye,ht||"currentColor",1.5);un?U.appendChild(un):U.textContent="\u{1F3A4}",Ge?U.style.backgroundColor=Ge:U.style.backgroundColor="",i?.borderWidth&&(U.style.borderWidth=i.borderWidth,U.style.borderStyle="solid"),i?.borderColor&&(U.style.borderColor=i.borderColor),i?.paddingX&&(U.style.paddingLeft=i.paddingX,U.style.paddingRight=i.paddingX),i?.paddingY&&(U.style.paddingTop=i.paddingY,U.style.paddingBottom=i.paddingY),z.appendChild(U);let Mt=i?.showTooltip??!1;return qt({anchor:U,trigger:z,text:()=>U.getAttribute("aria-label")??j,enabled:Mt}),{micButton:U,micButtonWrapper:z}},Fc=()=>{if(!te||vt)return;let i=o.voiceRecognition??{};vt={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Oc=(i,u)=>{if(!te)return;let h=te.querySelector("svg");h&&h.remove();let x=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),k=ae(i,x,u,1.5);k&&te.appendChild(k)},di=()=>{te&&te.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Kr=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=i.recordingBackgroundColor,h=i.recordingIconColor,x=i.recordingBorderColor;if(di(),te.classList.add("persona-voice-recording"),te.style.backgroundColor=u??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let k=te.querySelector("svg");k&&k.setAttribute("stroke",h)}x&&(te.style.borderColor=x),te.setAttribute("aria-label","Stop voice recognition")},qx=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=q.getVoiceInterruptionMode(),h=i.processingIconName??"loader",x=i.processingIconColor??vt?.color??"",k=i.processingBackgroundColor??vt?.backgroundColor??"",W=i.processingBorderColor??vt?.borderColor??"";di(),te.classList.add("persona-voice-processing"),te.style.backgroundColor=k,te.style.borderColor=W;let z=x||"currentColor";te.style.color=z,Oc(h,z),te.setAttribute("aria-label","Processing voice input"),u==="none"&&(te.style.cursor="default")},Vx=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=q.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",x=i.speakingIconName??h,k=i.speakingIconColor??(u==="barge-in"?i.recordingIconColor??vt?.color??"":vt?.color??""),W=i.speakingBackgroundColor??(u==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),z=i.speakingBorderColor??(u==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");di(),te.classList.add("persona-voice-speaking"),te.style.backgroundColor=W,te.style.borderColor=z;let U=k||"currentColor";te.style.color=U,Oc(x,U);let j=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";te.setAttribute("aria-label",j),u==="none"&&(te.style.cursor="default"),u==="barge-in"&&te.classList.add("persona-voice-recording")},no=()=>{te&&(di(),vt&&(te.style.backgroundColor=vt.backgroundColor??"",te.style.color=vt.color??"",te.style.borderColor=vt.borderColor??"",Oc(vt.iconName,vt.color||"currentColor"),vt=null),te.style.cursor="",te.setAttribute("aria-label","Start voice recognition"))},Xr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=q.getVoiceStatus(),u=q.getVoiceInterruptionMode();if(u==="none"&&(i==="processing"||i==="speaking"))return;if(u==="cancel"&&(i==="processing"||i==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Wn(),eo("user"),no()});return}q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),je.manuallyDeactivated=!q.isVoiceActive(),Wn(),eo("user"),q.isVoiceActive()?Kr():no()});return}if(qn){let i=B.value.trim();je.manuallyDeactivated=!0,Wn(),So("user"),i&&(B.value="",B.style.height="auto",q.sendMessage(i))}else je.manuallyDeactivated=!1,Wn(),ci("user")};Pf=Xr,te&&(te.addEventListener("click",Xr),De.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),no()):So("system"),te&&te.removeEventListener("click",Xr)}));let zx=c.on("assistant:complete",()=>{cm&&(je.active||je.manuallyDeactivated||cm==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("auto"),q.isVoiceActive()&&Kr()}):ci("auto"))},600))});De.push(zx);let $x=c.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});De.push($x);let Fm=()=>{lt(!J,"user")},kt=null,Yt=null;if(P&&!Q()){let{instance:i,element:u}=ju({config:o,plugins:a,onToggle:Fm});kt=i,i||(Yt=u)}kt?e.appendChild(kt.element):Yt&&e.appendChild(Yt),$a(),_r(),Lc(),kc(),si(q.isStreaming()),hm()||(cn()==="follow"?wo(!0):gm()),lx(),F&&(!P||Q()?setTimeout(()=>wc(),0):J&&setTimeout(()=>wc(),200));let Xa=()=>{if(Q()){Yo(),$a();return}let i=St(o),u=o.launcher?.sidebarMode??!1,h=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,W=h.innerWidth<=k,z=x&&W&&P;try{if(z){Zo(),Ba=Xs();return}let U=!1;G&&(G=!1,Zo(),U=!0);let j=Xs();if(!U&&j!==Ba&&(Zo(),U=!0),Ba=j,U&&lc(),!P&&!i){he.style.height="",he.style.width="";return}if(!u&&!i){let pe=o?.launcher?.width??o?.launcherWidth??mn;he.style.width=pe,he.style.maxWidth=pe}Ks(),Kf()}finally{if(Yo(),$a(),J&&P){let j=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Y=o.launcher?.sidebarMode??!1,pe=o.launcher?.mobileFullscreen??!0,le=St(o)&&pe&&j,ye=Y||pe&&j&&P||le;if(ye&&!Un){let Ge=e.getRootNode(),ht=Ge instanceof ShadowRoot?Ge.host:e.closest(".persona-host");ht&&!_n&&(_n=Pu(ht,o.launcher?.zIndex??Ut)),Un=Ru(e.ownerDocument)}else ye||(_n?.(),_n=null,Un?.(),Un=null)}}};Xa();let Om=e.ownerDocument.defaultView??window;if(Om.addEventListener("resize",Xa),De.push(()=>Om.removeEventListener("resize",Xa)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Yo()});i.observe(we),De.push(()=>i.disconnect())}pn=re.scrollTop;let Nm=jn(re),_m=()=>{let i=re.scrollTop,u=jn(re),h=u<Nm;if(Nm=u,!ho()){pn=i,Vt();return}let{action:x,nextLastScrollTop:k}=bl({following:dn.isFollowing(),currentScrollTop:i,lastScrollTop:pn,nearBottom:uo(re,Yn),userScrollThreshold:rx,isAutoScrolling:on||Qs||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=k,x==="resume"){ni()||Co();return}x==="pause"&&Na()};if(re.addEventListener("scroll",_m,{passive:!0}),De.push(()=>re.removeEventListener("scroll",_m)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{gx(),Gc(xe)});i.observe(xe),i.observe(re),De.push(()=>i.disconnect())}let Um=()=>{ho()&&dn.isFollowing()&&ni()&&Na()},qm=re.ownerDocument;qm.addEventListener("selectionchange",Um),De.push(()=>{qm.removeEventListener("selectionchange",Um)});let jx=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Vm=i=>{jx.has(i.key)&&(cr(),Mf()&&ho()&&dn.isFollowing()&&Na())},zm=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(cr(),Mf()&&ho()&&dn.isFollowing()&&Na())};re.addEventListener("keydown",Vm),re.addEventListener("focusin",zm),De.push(()=>{re.removeEventListener("keydown",Vm),re.removeEventListener("focusin",zm)});let $m=i=>{if(i.deltaY!==0&&cr(),!ho())return;let u=xl({following:dn.isFollowing(),deltaY:i.deltaY,nearBottom:uo(re,Yn),resumeWhenNearBottom:!0});u==="pause"?Na():u==="resume"&&!ni()&&Co()};re.addEventListener("wheel",$m,{passive:!0}),re.addEventListener("touchmove",cr,{passive:!0}),re.addEventListener("pointerdown",cr,{passive:!0}),De.push(()=>{re.removeEventListener("touchmove",cr),re.removeEventListener("pointerdown",cr)}),De.push(()=>re.removeEventListener("wheel",$m)),Pt.addEventListener("click",()=>{_a(),re.scrollTop=re.scrollHeight,pn=re.scrollTop,Co(),wo(!0),Vt()}),De.push(()=>Pt.remove()),De.push(()=>{um(),_a()});let jm=()=>{de&&(or&&(de.removeEventListener("click",or),or=null),Z()?(de.style.display="",or=()=>{lt(!1,"user")},de.addEventListener("click",or)):de.style.display="none")};jm(),(()=>{let{clearChatButton:i}=Te;i&&i.addEventListener("click",()=>{q.clearMessages(),ar.clear(),Co(),Wo(Te.composerOverlay);try{localStorage.removeItem(Ta),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ta}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ta)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(u),g?.clear&&hc(()=>g.clear(),"[AgentWidget] Failed to clear storage adapter:"),m={},M.syncFromMetadata(),Ne?.clear(),_e?.reset(),Ae?.update()})})(),H&&H.addEventListener("submit",li);let Gm=[["keydown",Nx],["input",Ox],["paste",_x],["focus",Qb]],Nc=i=>{if(i)for(let[u,h]of Gm)i.addEventListener(u,h)},_c=i=>{if(i)for(let[u,h]of Gm)i.removeEventListener(u,h)};Nc(B);let Km=()=>{Qt?.onComposerSwap((i,u)=>{_c(u),B=i,Nc(i)})};Km();let Uc=!1;function Gx(){if(!Uc){Uc=!0;try{let i=B?.value??"",u=we.ownerDocument??document,h=B?u.activeElement===B:!1;_c(B),H?.removeEventListener("submit",li),te?.removeEventListener("click",Xr),Qt?.destroy(),Qt=null;let x=null,k=()=>(x=Q()?Wl({config:o}):Lr({config:o}),x.footer),W=Wf(k)??k();et.replaceComposer(W),we=et.composer.footer;let z=x!==null&&W===x.footer;rc=!z,Us=z?x.setSendButtonMode:()=>{},If(we),Bf(we),Df(),Ff(),Of(),Km(),H&&H.addEventListener("submit",li),Nc(B),te?.addEventListener("click",Xr);let U=nr.indexOf(Qn);Qn.destroy(),Qn=Es(I),U>=0&&(nr[U]=Qn),B&&(B.value=i),Lc(),_r(),si(q.isStreaming()),Zo(),Yo(),h&&B?.focus()}finally{Uc=!1}}}let Xm=e.ownerDocument??document;Xm.addEventListener("keydown",Bm,!0);let Jm="persona-attachment-drop-active",Ja=0,qc=()=>{Ja=0,be.classList.remove(Jm)},Jr=()=>o.attachments?.enabled===!0&&bt!==null,Qm=i=>{!Xl(i.dataTransfer)||!Jr()||(Ja++,Ja===1&&be.classList.add(Jm))},Ym=i=>{!Xl(i.dataTransfer)||!Jr()||(Ja--,Ja<=0&&qc())},Zm=i=>{!Xl(i.dataTransfer)||!Jr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},eg=i=>{if(!Xl(i.dataTransfer)||!Jr())return;i.preventDefault(),i.stopPropagation(),qc();let u=Array.from(i.dataTransfer.files??[]);u.length!==0&&bt.handleFiles(u)},Mo=!0;be.addEventListener("dragenter",Qm,Mo),be.addEventListener("dragleave",Ym,Mo),e.addEventListener("dragover",Zm,Mo),e.addEventListener("drop",eg,Mo);let pi=e.ownerDocument,tg=i=>{Jr()&&i.preventDefault()},ng=i=>{Jr()&&i.preventDefault()};pi.addEventListener("dragover",tg),pi.addEventListener("drop",ng),De.push(()=>{H&&H.removeEventListener("submit",li),_c(B),Xm.removeEventListener("keydown",Bm,!0),Qt?.destroy()}),De.push(()=>{be.removeEventListener("dragenter",Qm,Mo),be.removeEventListener("dragleave",Ym,Mo),e.removeEventListener("dragover",Zm,Mo),e.removeEventListener("drop",eg,Mo),pi.removeEventListener("dragover",tg),pi.removeEventListener("drop",ng),qc()}),De.push(()=>{q.cancel()}),kt?De.push(()=>{kt?.destroy()}):Yt&&De.push(()=>{Yt?.remove()});let Rt={update(i){let u=o.toolCall,h=o.messageActions,x=o.layout?.messages,k=o.colorScheme,W=o.loadingIndicator,z=o.iterationDisplay,U=o.features?.showReasoning,j=o.features?.showToolCalls,Y=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,le=o.features?.streamAnimation?.type;o=ql({...o,features:r},i),r=o.features,o=Hs(o),dc(),Sr(e,o),Is(e,o),Ws(e,o),Jn(),o.colorScheme!==k&&Xf();let ye=Bs.getForInstance(o.plugins);a.length=0,a.push(...ye),P=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,ue=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,Se=o.features?.scrollToBottom??{};let Ge=cn();Ce=o.features?.scrollBehavior??{},Ge!==cn()&&(_a(),Co()),lm(),Lf(),Vt();let ht=me;if(me=o.features?.showEventStreamToggle??!1,me&&!ht){if(Ne||(Je=new Ps(ut),Ne=new Ls(Qe,Je),_e=_e??new Rs,Je.open().then(()=>Ne?.restore()).catch(()=>{}),q.setSSEEventCallback((se,$e)=>{o.onSSEEvent?.(se,$e),_e?.processEvent(se,$e),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify($e)})})),!Ye&&We){let se=o.features?.eventStream?.classNames,$e="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"+(se?.toggleButton?" "+se.toggleButton:"");Ye=v("button",$e),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Xt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let mt=ae("activity","18px","currentColor",1.5);mt&&Ye.appendChild(mt);let Ze=Te.clearChatButtonWrapper,ot=Te.closeButtonWrapper,Gt=Ze||ot;Gt&&Gt.parentNode===We?We.insertBefore(Ye,Gt):We.appendChild(Ye),Ye.addEventListener("click",()=>{Me?Ia():nc()})}}else!me&&ht&&(Ia(),Ye&&(Ye.remove(),Ye=null),Ne?.clear(),Je?.destroy(),Ne=null,Je=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&kt&&(kt.destroy(),kt=null),o.launcher?.enabled===!1&&Yt&&(Yt.remove(),Yt=null),o.launcher?.enabled!==!1&&!kt&&!Yt){let{instance:se,element:$e}=ju({config:o,plugins:a,onToggle:Fm});kt=se,se||(Yt=$e),e.appendChild($e)}kt&&kt.update(o),ze&&o.launcher?.title!==void 0&&(ze.textContent=o.launcher.title),Ue&&o.launcher?.subtitle!==void 0&&(Ue.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==E&&We){let se=ct?ya(o,ct,{showClose:Z(),onClose:()=>lt(!1,"user")}):fo({config:o,showClose:Z(),onClose:()=>lt(!1,"user")});et.replaceHeader(se),We=et.header.element,Pe=et.header.iconHolder,ze=et.header.headerTitle,Ue=et.header.headerSubtitle,de=et.header.closeButton,E=ct?.layout}else if(ct){if(Pe&&(Pe.style.display=ct.showIcon===!1?"none":""),ze&&(ze.style.display=ct.showTitle===!1?"none":""),Ue&&(Ue.style.display=ct.showSubtitle===!1?"none":""),de){let se=Z()&&ct.showCloseButton!==!1;de.style.display=se?"":"none"}if(Te.clearChatButtonWrapper){let se=ct.showClearChat;if(se!==void 0){Te.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:$e}=Te;$e&&!$e.classList.contains("persona-absolute")&&(se?$e.classList.remove("persona-ml-auto"):$e.classList.add("persona-ml-auto"))}}}let Mt=o.layout?.showHeader!==!1;We&&(We.style.display=Mt?"":"none");let It=o.layout?.showFooter!==!1;we&&(we.style.display=It?"":"none"),Yo(),Vt(),P!==$?P?lt(R,"auto"):(J=!0,$a()):R!==O&<(R,"auto"),O=R,$=P,Xa(),jm();let Fe=JSON.stringify(o.toolCall)!==JSON.stringify(u),Ee=JSON.stringify(o.messageActions)!==JSON.stringify(h),At=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),dt=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,Ot=o.iterationDisplay!==z,pt=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==(j??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Y)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(Fe||Ee||At||dt||Ot||pt)&&q&&(uc++,Ua(xe,q.getMessages(),ie));let Wt=o.features?.streamAnimation?.type;if(Wt!==le&&Wt&&Wt!=="none"){let se=ha(Wt,o.features?.streamAnimation?.plugins);se&&Al(se,e)}let Ie=o.launcher??{},Oe=Ie.headerIconHidden??!1,zt=o.layout?.header?.showIcon,$t=Oe||zt===!1,Ct=Ie.headerIconName,st=Ie.headerIconSize??"48px";if(Pe){let se=be.querySelector(".persona-border-b-persona-divider"),$e=se?.querySelector(".persona-flex-col");if($t)Pe.style.display="none",se&&$e&&!se.contains($e)&&se.insertBefore($e,se.firstChild);else{if(Pe.style.display="",Pe.style.height=st,Pe.style.width=st,se&&$e&&(se.contains(Pe)?Pe.nextSibling!==$e&&(Pe.remove(),se.insertBefore(Pe,$e)):se.insertBefore(Pe,$e)),Ct){let Ze=parseFloat(st)||24,ot=ae(Ct,Ze*.6,"currentColor",1);ot?Pe.replaceChildren(ot):Pe.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let Ze=Pe.querySelector("img");if(Ze)Ze.src=Ie.iconUrl,Ze.style.height=st,Ze.style.width=st;else{let ot=document.createElement("img");ot.src=Ie.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=st,ot.style.width=st,Pe.replaceChildren(ot)}}else{let Ze=Pe.querySelector("svg"),ot=Pe.querySelector("img");(Ze||ot)&&Pe.replaceChildren(),Pe.textContent=Ie.agentIconText??"\u{1F4AC}"}let mt=Pe.querySelector("img");mt&&(mt.style.height=st,mt.style.width=st)}}let ft=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(ze&&(ze.style.display=ft===!1?"none":""),Ue&&(Ue.style.display=Xe===!1?"none":""),de){let se=Z()&&o.layout?.header?.showCloseButton!==!1;de.style.display=se?"":"none";let $e=Ie.closeButtonSize??"32px",mt=Ie.closeButtonPlacement??"inline";de.style.height=$e,de.style.width=$e;let{closeButtonWrapper:Ze}=Te,ot=mt==="top-right",Gt=Ze?.classList.contains("persona-absolute");if(Ze&&ot!==Gt)if(Ze.remove(),ot)Ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",be.style.position="relative",be.appendChild(Ze);else{let Eo=Ie.clearChat?.placement??"inline",Za=Ie.clearChat?.enabled??!0;Ze.className=Za&&Eo==="inline"?"":"persona-ml-auto";let og=be.querySelector(".persona-border-b-persona-divider");og&&og.appendChild(Ze)}if(de.style.color=Ie.closeButtonColor||Xt.actionIconColor,Ie.closeButtonBackgroundColor?(de.style.backgroundColor=Ie.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let Eo=Ie.closeButtonBorderWidth||"0px",Za=Ie.closeButtonBorderColor||"transparent";de.style.border=`${Eo} solid ${Za}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(de.style.borderRadius=Ie.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(de.style.paddingLeft=Ie.closeButtonPaddingX,de.style.paddingRight=Ie.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Ie.closeButtonPaddingY?(de.style.paddingTop=Ie.closeButtonPaddingY,de.style.paddingBottom=Ie.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let fn=Ie.closeButtonIconName??"x",Hn=Ie.closeButtonIconText??"\xD7";de.innerHTML="";let Nt=ae(fn,"28px","currentColor",1);Nt?(Nt.style.display="block",de.appendChild(Nt)):de.textContent=Hn;let Kt=Ie.closeButtonTooltipText??"Close chat",ro=Ie.closeButtonShowTooltip??!0;de.setAttribute("aria-label",Kt),Ze&&qt({anchor:de,trigger:Ze,text:()=>de?.getAttribute("aria-label")??Kt,enabled:ro})}let{clearChatButton:He,clearChatButtonWrapper:yt}=Te;if(He){let se=Ie.clearChat??{},$e=se.enabled??!0,mt=o.layout?.header?.showClearChat,Ze=mt!==void 0?mt:$e,ot=se.placement??"inline";if(yt){yt.style.display=Ze?"":"none";let{closeButtonWrapper:Gt}=Te;!Q()&&Gt&&!Gt.classList.contains("persona-absolute")&&(Ze?Gt.classList.remove("persona-ml-auto"):Gt.classList.add("persona-ml-auto"));let fn=ot==="top-right",Hn=yt.classList.contains("persona-absolute");if(!Q()&&fn!==Hn&&Ze){if(yt.remove(),fn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",be.style.position="relative",be.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Kt=be.querySelector(".persona-border-b-persona-divider"),ro=Te.closeButtonWrapper;Kt&&ro&&ro.parentElement===Kt?Kt.insertBefore(yt,ro):Kt&&Kt.appendChild(yt)}let Nt=Te.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(fn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(Ze){if(!Q()){let Eo=se.size??"32px";He.style.height=Eo,He.style.width=Eo}let Gt=se.iconName??"refresh-cw",fn=se.iconColor??"";He.style.color=fn||Xt.actionIconColor,He.innerHTML="";let Hn=Q()?"14px":"20px",Nt=ae(Gt,Hn,"currentColor",1);if(Nt&&(Nt.style.display="block",He.appendChild(Nt)),se.backgroundColor?(He.style.backgroundColor=se.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let Eo=se.borderWidth||"0px",Za=se.borderColor||"transparent";He.style.border=`${Eo} solid ${Za}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");se.borderRadius?(He.style.borderRadius=se.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),se.paddingX?(He.style.paddingLeft=se.paddingX,He.style.paddingRight=se.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),se.paddingY?(He.style.paddingTop=se.paddingY,He.style.paddingBottom=se.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Kt=se.tooltipText??"Clear chat",ro=se.showTooltip??!0;He.setAttribute("aria-label",Kt),yt&&qt({anchor:He,trigger:yt,text:()=>He?.getAttribute("aria-label")??Kt,enabled:ro})}}let jt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ds],An=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dr.message,Dr.messageAndClick];M=Fs({parsers:jt,handlers:An,getSessionMetadata:L,updateSessionMetadata:A,emit:c.emit,documentRef:typeof document<"u"?document:null}),ie=ib(o,M,ge),q.updateConfig(o),Ua(xe,q.getMessages(),ie),_r(),Lc(),kx(),si(q.isStreaming());let Qa=o.voiceRecognition?.enabled===!0,ui=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Lt=o.voiceRecognition?.provider?.type==="runtype";if(Qa&&(ui||Lt))if(!te||!bn){let se=Ux(o.voiceRecognition,o.sendButton);se&&(te=se.micButton,bn=se.micButtonWrapper,wt.insertBefore(bn,D),te.addEventListener("click",Xr),te.disabled=q.isStreaming())}else{let se=o.voiceRecognition??{},$e=o.sendButton??{},mt=se.iconName??"mic",Ze=$e.size??"40px",ot=se.iconSize??Ze,Gt=parseFloat(ot)||24;te.style.width=ot,te.style.height=ot,te.style.minWidth=ot,te.style.minHeight=ot;let fn=se.iconColor??$e.textColor;te.innerHTML="";let Hn=ae(mt,Gt,fn||"currentColor",1.5);Hn?te.appendChild(Hn):te.textContent="\u{1F3A4}";let Nt=se.backgroundColor??$e.backgroundColor;Nt?te.style.backgroundColor=Nt:te.style.backgroundColor="",fn?te.style.color=fn:te.style.color="var(--persona-text, #111827)",se.borderWidth?(te.style.borderWidth=se.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),se.borderColor?te.style.borderColor=se.borderColor:te.style.borderColor="",se.paddingX?(te.style.paddingLeft=se.paddingX,te.style.paddingRight=se.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),se.paddingY?(te.style.paddingTop=se.paddingY,te.style.paddingBottom=se.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Kt=se.tooltipText??"Start voice recognition",ro=se.showTooltip??!1;te.setAttribute("aria-label",Kt),bn&&qt({anchor:te,trigger:bn,text:()=>te?.getAttribute("aria-label")??Kt,enabled:ro}),bn.style.display="",te.disabled=q.isStreaming()}else te&&bn&&(bn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()&&q.toggleVoice():qn&&So());if(o.attachments?.enabled===!0){if(!xn||!it){let se=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Ln||(Ln=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ln.style.display="none",H.insertBefore(Ln,B)),Et||(Et=document.createElement("input"),Et.type="file",Et.accept=(se.allowedTypes??co).join(","),Et.multiple=(se.maxFiles??4)>1,Et.style.display="none",Et.setAttribute("aria-label","Attach files"),H.insertBefore(Et,B)),xn=v("div","persona-send-button-wrapper"),it=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let Ze=se.buttonIconName??"paperclip",ot=mt,Gt=parseFloat(ot)||40,fn=Math.round(Gt*.6);it.style.width=ot,it.style.height=ot,it.style.minWidth=ot,it.style.minHeight=ot,it.style.fontSize="18px",it.style.lineHeight="1";let Hn=ae(Ze,fn,"currentColor",1.5);Hn?it.appendChild(Hn):it.textContent="\u{1F4CE}",it.addEventListener("click",Kt=>{Kt.preventDefault(),Et?.click()}),xn.appendChild(it);let Nt=se.buttonTooltipText??"Attach file";qt({anchor:it,trigger:xn,text:()=>it?.getAttribute("aria-label")??Nt}),yn?yn.append(xn):H.appendChild(xn),!bt&&Et&&Ln&&(bt=Ar.fromConfig(se),bt.setPreviewsContainer(Ln),Et.addEventListener("change",async()=>{bt&&Et?.files&&(await bt.handleFileSelect(Et.files),Et.value="")}))}else{xn.style.display="";let se=o.attachments??{};Et&&(Et.accept=(se.allowedTypes??co).join(","),Et.multiple=(se.maxFiles??4)>1),bt&&bt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(be.querySelector(".persona-attachment-drop-overlay")?.remove(),be.appendChild(lb(o.attachments?.dropOverlay)),it){let se=o.attachments??{},$e=se.buttonTooltipText??"Attach file";it.setAttribute("aria-label",$e),it.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,Ze=ae(se.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);Ze?it.appendChild(Ze):it.textContent="\u{1F4CE}",xn&&qt({anchor:it,trigger:xn,text:()=>it?.getAttribute("aria-label")??$e})}}else xn&&(xn.style.display="none"),bt&&bt.clearAttachments(),be.querySelector(".persona-attachment-drop-overlay")?.remove();let Ft=o.sendButton??{},Ya=Ft.useIcon??!1,mi=Ft.iconText??"\u2191",Qr=Ft.iconName,gi=Ft.tooltipText??"Send message",Vc=Ft.showTooltip??!1,mr=Ft.size??"40px",oo=Ft.backgroundColor,gr=Ft.textColor;if(Ya){if(y.style.width=mr,y.style.height=mr,y.style.minWidth=mr,y.style.minHeight=mr,y.style.fontSize="18px",y.style.lineHeight="1",gr?y.style.color=gr:y.style.color="var(--persona-button-primary-fg, #ffffff)",!q.isStreaming())if(y.innerHTML="",Qr){let se=parseFloat(mr)||24,$e=gr?.trim()||"currentColor",mt=ae(Qr,se,$e,2);mt?y.appendChild(mt):y.textContent=mi}else y.textContent=mi;y.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",oo?(y.style.backgroundColor=oo,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary"))}else y.textContent=o.copy?.sendButtonLabel??"Send",y.style.width="",y.style.height="",y.style.minWidth="",y.style.minHeight="",y.style.fontSize="",y.style.lineHeight="",y.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",oo?(y.style.backgroundColor=oo,y.classList.remove("persona-bg-persona-accent")):y.classList.add("persona-bg-persona-accent"),gr?y.style.color=gr:y.classList.add("persona-text-white");Ft.borderWidth?(y.style.borderWidth=Ft.borderWidth,y.style.borderStyle="solid"):(y.style.borderWidth="",y.style.borderStyle=""),Ft.borderColor?y.style.borderColor=Ft.borderColor:y.style.borderColor="",Ft.paddingX?(y.style.paddingLeft=Ft.paddingX,y.style.paddingRight=Ft.paddingX):(y.style.paddingLeft="",y.style.paddingRight=""),Ft.paddingY?(y.style.paddingTop=Ft.paddingY,y.style.paddingBottom=Ft.paddingY):(y.style.paddingTop="",y.style.paddingBottom=""),q.isStreaming()||y.setAttribute("aria-label",gi),D&&qt({anchor:y,trigger:D,text:()=>y.getAttribute("aria-label")??gi,enabled:Vc});let Yr=qo(o,Q());pc(),Yr?(xe.style.maxWidth=Yr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",X.style.maxWidth=Yr,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%",H&&(H.style.maxWidth=Yr,H.style.marginLeft="auto",H.style.marginRight="auto"),I&&(I.style.maxWidth=Yr,I.style.marginLeft="auto",I.style.marginRight="auto"),N.style.maxWidth=Yr,N.style.marginLeft="auto",N.style.marginRight="auto"):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight="",X.style.width="",H&&(H.style.maxWidth="",H.style.marginLeft="",H.style.marginRight=""),I&&(I.style.maxWidth="",I.style.marginLeft="",I.style.marginRight=""),N.style.maxWidth="",N.style.marginLeft="",N.style.marginRight="");let To=o.statusIndicator??{},Kx=To.visible??!0;if(N.style.display=Kx?"":"none",q){let se=q.getStatus();En(N,(mt=>mt==="idle"?To.idleText??Ht.idle:mt==="connecting"?To.connectingText??Ht.connecting:mt==="connected"?To.connectedText??Ht.connected:mt==="error"?To.errorText??Ht.error:Ht[mt])(se),To,se)}N.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Xx=To.align==="left"?"persona-text-left":To.align==="center"?"persona-text-center":"persona-text-right";N.classList.add(Xx)},open(){Z()&<(!0,"api")},close(){Z()&<(!1,"api")},toggle(){Z()&<(!J,"api")},reconnect(){q.reconnectNow()},clearChat(){Xn=!1,q.clearMessages(),ar.clear(),Co();try{localStorage.removeItem(Ta),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ta}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ta)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),g?.clear&&hc(()=>g.clear(),"[AgentWidget] Failed to clear storage adapter:"),m={},M.syncFromMetadata(),Ne?.clear(),_e?.reset(),Ae?.update()},setMessage(i){return!B||q.isStreaming()?!1:(!J&&Z()&<(!0,"system"),B.value=i,B.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(q.isStreaming())return!1;let u=i?.trim()||B.value.trim();return u?(!J&&Z()&<(!0,"system"),B.value="",B.style.height="auto",q.sendMessage(u),!0):!1},startVoiceRecognition(){return q.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()||(!J&&Z()&<(!0,"system"),je.manuallyDeactivated=!1,Wn(),q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("user"),q.isVoiceActive()&&Kr()})),!0):qn?!0:Dm()?(!J&&Z()&<(!0,"system"),je.manuallyDeactivated=!1,Wn(),ci("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Wn(),eo("user"),no()}),!0):!1:qn?(je.manuallyDeactivated=!0,Wn(),So("user"),!0):!1},injectMessage(i){return!J&&Z()&<(!0,"system"),q.injectMessage(i)},injectAssistantMessage(i){!J&&Z()&<(!0,"system");let u=q.injectAssistantMessage(i);return fe&&(fe=!1,ne&&(clearTimeout(ne),ne=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),u},injectUserMessage(i){return!J&&Z()&<(!0,"system"),q.injectUserMessage(i)},injectSystemMessage(i){return!J&&Z()&<(!0,"system"),q.injectSystemMessage(i)},injectMessageBatch(i){return!J&&Z()&<(!0,"system"),q.injectMessageBatch(i)},injectComponentDirective(i){return!J&&Z()&<(!0,"system"),q.injectComponentDirective(i)},injectTestMessage(i){!J&&Z()&<(!0,"system"),q.injectTestEvent(i)},async connectStream(i,u){return q.connectStream(i,u)},__pushEventStreamEvent(i){Ne&&(_e?.processEvent(i.type,i.payload),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!me||!Ne||nc()},hideEventStream(){Me&&Ia()},isEventStreamVisible(){return Me},showArtifacts(){tn(o)&&(Xn=!1,Fr=!0,Jn(),Ke?.setMobileOpen(!0))},hideArtifacts(){tn(o)&&(Xn=!0,Jn())},upsertArtifact(i){return tn(o)?(zn(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Xn=!1,Fr=!0),q.upsertArtifact(i)):null},selectArtifact(i){tn(o)&&q.selectArtifact(i)},clearArtifacts(){tn(o)&&q.clearArtifacts()},getArtifacts(){return q?.getArtifacts()??[]},getSelectedArtifactId(){return q?.getSelectedArtifactId()??null},focusInput(){return P&&!J&&!Q()||!B?!1:(B.focus(),!0)},async resolveApproval(i,u,h){let k=q.getMessages().find(W=>W.variant==="approval"&&W.approval?.id===i);if(!k?.approval)throw new Error(`Approval not found: ${i}`);if(k.approval.toolType==="webmcp"){q.resolveWebMcpApproval(k.id,u);return}return q.resolveApproval(k.approval,u,h)},setFollowUpSuggestions(i){nx(i)},clearFollowUpSuggestions(){im()},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...m}},updatePersistentMetadata(i){A(i)},on(i,u){return c.on(i,u)},off(i,u){c.off(i,u)},isOpen(){return Z()&&J},isVoiceActive(){return je.active},toggleReadAloud(i){q.toggleReadAloud(i)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(i){return q.getReadAloudState(i)},onReadAloudChange(i){return q.onReadAloudChange(i)},getState(){return{open:Z()&&J,launcherEnabled:P,voiceActive:je.active,streaming:q.isStreaming()}},showCSATFeedback(i){!J&&Z()&<(!0,"system");let u=xe.querySelector(".persona-feedback-container");u&&u.remove();let h=Gl({onSubmit:async(x,k)=>{q.isClientTokenMode()&&await q.submitCSATFeedback(x,k),i?.onSubmit?.(x,k)},onDismiss:i?.onDismiss,...i});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!J&&Z()&<(!0,"system");let u=xe.querySelector(".persona-feedback-container");u&&u.remove();let h=Kl({onSubmit:async(x,k)=>{q.isClientTokenMode()&&await q.submitNPSFeedback(x,k),i?.onSubmit?.(x,k)},onDismiss:i?.onDismiss,...i});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,u){return q.submitCSATFeedback(i,u)},async submitNPSFeedback(i,u){return q.submitNPSFeedback(i,u)},destroy(){Ic(),ur!=null&&(clearInterval(ur),ur=null),De.forEach(i=>i()),Le.remove(),tt?.remove(),kt?.destroy(),Yt?.remove(),or&&de.removeEventListener("click",or)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,u={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:h=>h?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,De.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",u),De.push(()=>{window.removeEventListener("persona:focusInput",u)}),me){let U=Y=>{let pe=Y.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.showEventStream()},j=Y=>{let pe=Y.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",j),De.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",j)})}let h=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.showArtifacts()},x=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.hideArtifacts()},k=U=>{let j=U.detail;j?.instanceId&&j.instanceId!==i||j?.artifact&&Rt.upsertArtifact(j.artifact)},W=U=>{let j=U.detail;j?.instanceId&&j.instanceId!==i||typeof j?.id=="string"&&Rt.selectArtifact(j.id)},z=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",z),De.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",z)})}let wn=xS(o.persistState);if(wn&&Z()){let i=vS(wn.storage),u=`${wn.keyPrefix}widget-open`,h=`${wn.keyPrefix}widget-voice`,x=`${wn.keyPrefix}widget-voice-mode`;if(i){let k=wn.persist?.openState&&i.getItem(u)==="true",W=wn.persist?.voiceState&&i.getItem(h)==="true",z=wn.persist?.voiceState&&i.getItem(x)==="true";if(k&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open(),setTimeout(()=>{if(W||z)Rt.startVoiceRecognition();else if(wn.persist?.focusInput){let U=e.querySelector("textarea");U&&U.focus()}},100)},0)),wn.persist?.openState&&(c.on("widget:opened",()=>{i.setItem(u,"true")}),c.on("widget:closed",()=>{i.setItem(u,"false")})),wn.persist?.voiceState&&(c.on("voice:state",U=>{i.setItem(h,U.active?"true":"false")}),c.on("user:message",U=>{i.setItem(x,U.viaVoice?"true":"false")})),wn.clearOnChatClear){let U=()=>{i.removeItem(u),i.removeItem(h),i.removeItem(x)},j=()=>U();window.addEventListener("persona:clear-chat",j),De.push(()=>{window.removeEventListener("persona:clear-chat",j)})}}}if(w&&Z()&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open()},0)),$r(),!ox){let i=ea(()=>{q&&(uc++,ar.clear(),Ua(xe,q.getMessages(),ie))});De.push(i)}return Rt};var cb=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},AS=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},SS=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},MS=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!r||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.")},db=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},ff=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=""},pb=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ff(e)},df=e=>{e.style.transition=""},pf=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=""},uf=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ql=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},TS=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},ES=(e,t,n,o,r,a)=>{let s=a?t:e;r==="left"?s.firstElementChild!==o&&s.replaceChildren(o,n):s.lastElementChild!==o&&s.replaceChildren(n,o)},kS=e=>{let t=Uo(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:en(t,r)??r;return{inset:o(n?.inset,rl),canvasBackground:o(n?.canvasBackground,al)}},ub=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},LS=(e,t,n,o,r,a,s,l)=>{let p=ln(a),d=p.reveal==="push",c=l!=null,f=l?.inset??"",g=l?.canvasBackground??"";TS(e,t,n,o,d),ES(e,t,n,o,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",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let m=e.ownerDocument.defaultView,b=a?.launcher?.mobileFullscreen??!0,w=a?.launcher?.mobileBreakpoint??640,T=m!=null?m.innerWidth<=w:!1;if(b&&T&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),pf(t),df(o),pb(o),uf(n),Ql(r,o),ub(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.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(a?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.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",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),pb(o),AS(o,p.maxHeight),ub(o,c&&s,f,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",pf(t),df(o),uf(n),Ql(r,o);let A=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",C=s?"translateX(0)":S;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=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=A,o.style.transform=C,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",df(o),ff(o),Ql(r,o);let A=cb(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),C=p.animate?"margin-left 180ms ease":"none",M=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=`${S+A}px`,t.style.transition=C,t.style.marginLeft=`${M}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.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="",pf(t),ff(o),uf(n),Ql(r,o);let A=p.reveal==="emerge";A?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?p.width:"0px",C=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",M=!s;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",SS(o,p.maxHeight),o.style.overflow=A||M?"hidden":"visible",o.style.transition=C,A){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let P=c?`calc(${cb(p.width,e.clientWidth)}px - (2 * ${f}))`:p.width;r.style.width=P,r.style.minWidth=P,r.style.maxWidth=P,r.style.boxSizing="border-box"}}},PS=(e,t)=>{let n=e.ownerDocument.createElement("div");return db(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){db(n,o)},destroy(){n.remove()}}},RS=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),f=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),o.insertBefore(s,e),p.appendChild(e);let g=null,m=()=>{g?.disconnect(),g=null},b=null,w=()=>{b=t?.launcher?.detachedPanel===!0?kS(t):null};w();let T=()=>{LS(s,l,p,d,c,t,f,b)},L=null,A=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=pa(()=>{w(),T()}))},S=()=>{m(),ln(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{T()}),g.observe(s)))},C=!1,M=()=>{T(),S(),f&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,MS(s,ln(t)))},P=s.ownerDocument.defaultView,R=()=>{M()};return P?.addEventListener("resize",R),ln(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),s.appendChild(l)):(s.appendChild(p),s.appendChild(d)),M(),A(),{mode:"docked",host:c,shell:s,syncWidgetState(F){let O=F.launcherEnabled?F.open:!0;f!==O&&(f=O,M())},updateConfig(F){t=F,(t?.launcher?.enabled??!0)===!1&&(f=!0),w(),M(),A()},destroy(){P?.removeEventListener("resize",R),L?.(),L=null,m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Ns=(e,t)=>St(t)?RS(e,t):PS(e,t);var IS=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},fb=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},mb=e=>{let t=IS(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=Ns(t,r),s,l=[],p=(T,L)=>{let S=!(L?.launcher?.enabled??!0)||St(L),C=o.createElement("div");if(C.setAttribute("data-persona-root","true"),S&&(C.style.height="100%",C.style.display="flex",C.style.flexDirection="column",C.style.flex="1",C.style.minHeight="0",C.style.minWidth="0"),n){let M=T.attachShadow({mode:"open"});M.appendChild(C),fb(M,o)}else T.appendChild(C),fb(T,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},d=()=>{a.syncWidgetState(s.getState())},c=()=>{l.forEach(T=>T()),l=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},f=()=>{let T=p(a.host,r);s=Jl(T,r,{debugTools:e.debugTools}),c()},g=()=>{l.forEach(T=>T()),l=[],s.destroy()};f(),e.onChatReady?.();let m=T=>{g(),a.destroy(),a=Ns(t,T),r=T,f()},b={update(T){let L=ql(r??{},T),A=St(r),S=St(L),C=Ko(r),M=Ko(L);if(A!==S||C!==M){m(L);return}r=L,a.updateConfig(r),s.update(T),d()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},w=new Proxy(b,{get(T,L,A){if(L==="host")return a.host;if(L in T)return Reflect.get(T,L,A);let S=s[L];return typeof S=="function"?S.bind(s):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w};function WS(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function HS(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(a=>a.toLowerCase().startsWith(o))?1:WS(o,n)?2:3}function gb(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Yl(e,t){let n=t.trim();if(!n)return[...e].sort(gb);let o=[];for(let r of e){let a=HS(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:gb(r.item,a.item)),o.map(r=>r.item)}function BS(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function hb(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Yl(e.items,t),resolve:e.resolve}}function yb(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>Yl(t,BS(r).name),resolve:(r,a)=>{let s=n.get(r.id);return s?s.kind==="server"?{context:(typeof s.data=="function"?s.data(a.args):s.data)??{}}:{insertText:typeof s.prompt=="function"?s.prompt(a.args):s.prompt??""}:{}}}}var wb=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),DS=new Set(["button","a","input","select","textarea","details","summary"]),FS=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),mf=/\b(product|card|item|listing|result)\b/i,hf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,OS=3e3,NS=100;function Ab(e){let t=typeof e.className=="string"?e.className:"";if(mf.test(t)||e.id&&mf.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&mf.test(o.value))return!0}return!1}function Sb(e){return hf.test((e.textContent??"").trim())}function Mb(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function _S(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bb(e){let t=e.match(hf);return t?t[0]:null}function xb(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 o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function US(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var qS="commerce-card",VS="result-card";function vb(e){return!Ab(e)||!Sb(e)||!Mb(e)&&!_S(e)?0:5200}function Cb(e){return!Ab(e)||Sb(e)||!Mb(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var yf=[{id:qS,scoreElement(e){return vb(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||hf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(vb(e)===0)return null;let{title:n,href:o}=xb(e),r=bb((e.textContent??"").trim())??bb(t.text)??"",a=US(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
144
|
-
`)}},{id:
|
|
145
|
-
`)}}];function
|
|
146
|
-
${
|
|
142
|
+
${Ae?"background: transparent !important;":""}
|
|
143
|
+
`)}if(!h&&!a){let Lt="max-height: -moz-available !important; max-height: stretch !important;",pn=c?"":"padding-top: 1.25em !important;",ii=c?"":`z-index: ${o.launcher?.zIndex??Qt} !important;`;W.style.cssText+=Lt+pn+ii}zn()},Yd=()=>{e.style.setProperty("--persona-content-max-width",vr(o,ie()))},xh=()=>{if(ie())return;let a=ht(o),c=o.launcher?.sidebarMode??!1;if(a||c||(o.launcher?.fullHeight??!1)||!N)return;let h=e.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=R)return;let z=h.innerHeight,V=64,J=o.launcher?.heightOffset??0,j=Math.max(200,z-V),te=Math.min(640,j);O.style.height=`${Math.max(200,te-J)}px`};Xd(),ss(e,o),$i(e,o),Gi(e,o),Yd(),Lr=()=>{Xd(),xh(),ss(e,o),$i(e,o),Gi(e,o),Yd(),nl?e.style.setProperty("--persona-artifact-welded-outer-radius",nl):e.style.removeProperty("--persona-artifact-welded-outer-radius"),en(),bt()};let Te=[];Te.push(()=>{d.forEach(a=>a()),l.destroy()}),Te.push(()=>{document.removeEventListener("keydown",hh)}),Te.push(()=>{ka!==null&&clearTimeout(ka)});let ao=null,io=null;Te.push(()=>{ao?.(),ao=null,io?.(),io=null}),Ha&&Te.push(()=>{Ha?.disconnect(),Ha=null}),Te.push(()=>{Wa?.(),Wa=null,Kd(),ft&&(ft.remove(),ft=null),De?.element.style.removeProperty("width"),De?.element.style.removeProperty("maxWidth"),De?.destroy()}),Re&&Te.push(()=>{zt!==null&&(cancelAnimationFrame(zt),zt=null),rt?.destroy(),rt=null,Me?.destroy(),Me=null,yt=null});let Rr=null,vh=()=>{Rr&&(Rr(),Rr=null),o.colorScheme==="auto"&&(Rr=ia(()=>{ss(e,o)}))};vh(),Te.push(()=>{Rr&&(Rr(),Rr=null)}),Te.push(y);let cl=o.features?.streamAnimation;if(cl?.type&&cl.type!=="none"){let a=ua(cl.type,cl.plugins);a&&(cd(a,e),Te.push(()=>kv(e)))}let Eo=Ui(xt),Ch=Ui(it),wh=Ui(et),Ir=[Eo,Ch,wh];Te.push(()=>{Ir.forEach(a=>a.destroy())});let Wr=null,F,Br=null,Sh=!1,Ah=0,Mh=null,Th=a=>a.reduce((c,m)=>m.role==="user"?c+1:c,0),Eh=a=>{for(let c=a.length-1;c>=0;c--)if(es(a[c]))return a[c].id??null;return null},kh=!1,Uw=()=>{kh||o.debug!==!0||(kh=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Ph=!1,Lh=!1,Hh=(a,c)=>{Ph||o.debug!==!0||!c.enabled||c.expose||Sh||Lh&&(F.isStreaming()||a.some(es)||(Ph=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Es=a=>{if(!F)return;let c=a??F.getMessages(),m=j=>{j.render([],F,ge,c)},h=j=>{Ir.forEach(te=>{te!==j&&m(te)})};Br&&(Th(c)>Ah||Eh(c)!==Mh)&&(Br=null);let C=fr(o);Hh(c,C);let R=C.enabled?cc(c):null,z=Br??R,V=Br?"host":"agent";if(z){let j=o.suggestions?.followUps,te=j?.placement??(j?"auto":"composer"),fe=(te==="auto"?ie()?"composer":"after-message":te)==="after-message"?wh:Eo;h(fe),fe.render(z,F,ge,c,o.suggestionChipsConfig,{source:V,surface:"followUp",variant:j?.variant??"chip",behavior:j?.behavior??"send",overflow:j?.overflow??"wrap",maxItems:j?.maxItems??4,config:o,plugins:i});return}if(c.some(j=>j.role==="user")){Ir.forEach(m);return}let J=o.suggestions?.starters;if(J){let j=Tr(jo(o),c),te=J.placement??"auto",se=te==="auto"?j?"welcome":"composer":te;if(se==="welcome"&&!j){Uw(),Ir.forEach(m);return}let fe=se==="welcome"?Ch:Eo;h(fe),fe.render(J.items??o.suggestionChips,F,ge,c,o.suggestionChipsConfig,{surface:"starter",variant:J.variant??"card",behavior:J.behavior??"send",overflow:J.overflow??"wrap",maxItems:J.maxItems??4,config:o,plugins:i});return}h(Eo),Eo.render(o.suggestionChips,F,ge,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:i})},Rh=()=>{Br&&(Br=null,Es())},qw=a=>{let c=Array.isArray(a)?[...a]:[];if(!c.length){Rh();return}let m=F?F.getMessages():[];Br=c,Sh=!0,Ah=Th(m),Mh=Eh(m),Es(m)},Tn=!1,En=hv(),ks=new Map,Dr=new Map,Jo=new Map,Jd=0,Vw=Fo()!==null,kn=Cv(),Pn=0,Qo=null,yn=!1,dl=!1,Zo=0,_t=null,Or=null,Qd=!1,Ps=!1,Fr=null,Ba=!0,pl=!1,Ls=null,ul=!1,Nr=()=>{ul=!0,Gw()},Zd=null,zw=4,ko=24,jw=80,$w=1e3,Po=null,Ih=()=>{e.setAttribute("data-persona-scrollbar",_d()),_d()!=="on-scroll"&&(Po!==null&&clearTimeout(Po),Po=null,G.removeAttribute("data-persona-scrollbar-visible"))},Gw=()=>{_d()==="on-scroll"&&(G.setAttribute("data-persona-scrollbar-visible",""),Po!==null&&clearTimeout(Po),Po=setTimeout(()=>{Po=null,cs(G,ko)&&G.removeAttribute("data-persona-scrollbar-visible")},$w))};Ih(),Te.push(()=>{Po!==null&&clearTimeout(Po)});let ep=new Map,Fe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Wh=o.voiceRecognition?.autoResume??!1,Lo=a=>{g.emit("voice:state",{active:Fe.active,source:a,timestamp:Date.now()})},Zn=()=>{P(a=>({...a,voiceState:{active:Fe.active,timestamp:Date.now(),manuallyDeactivated:Fe.manuallyDeactivated}}))},Kw=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Rg(E.voiceState),c=!!a.active,m=Number(a.timestamp??0);Fe.manuallyDeactivated=!!a.manuallyDeactivated,c&&Date.now()-m<ok&&setTimeout(()=>{Fe.active||(Fe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?F.toggleVoice().then(()=>{Fe.active=F.isVoiceActive(),Lo("restore"),F.isVoiceActive()&&qs()}):zl("restore"))},1e3)},Xw=()=>F?_C(F.getMessages()).filter(a=>!a.__skipPersist):[],fl=null,Bh=(a,c)=>{typeof console<"u"&&console.error(a,c)},ml=(a,c)=>{let m=()=>{try{let z=a();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(V=>{Bh(c,V)})}catch(z){return Bh(c,z),null}},h=fl,C=h?h.then(()=>m()??void 0):m();if(!C)return;let R=C.finally(()=>{fl===R&&(fl=null)});fl=R};function tp(a){if(!v?.save)return;let m={messages:a?_C(a):F?Xw():[],metadata:E,artifacts:Jn.artifacts,selectedArtifactId:Jn.selectedId};ml(()=>v.save(m),"[AgentWidget] Failed to persist state:")}let Hs=null,Dh=()=>W.querySelector("#persona-scroll-container")||G,Rs=()=>{Hs!==null&&(cancelAnimationFrame(Hs),Hs=null),yn=!1},Oh=()=>{Qo!==null&&(cancelAnimationFrame(Qo),Qo=null),dl=!1,Rs()},Yw=()=>Tn&&op()&&(Mn()!=="anchor-top"||Yg()),np=()=>{let a=Ma()||"Jump to latest",c=Yw();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Zo>0?(kr.textContent=String(Zo),kr.style.display="",Wt.setAttribute("aria-label",`${a} (${Zo} new)`)):(kr.textContent="",kr.style.display="none",Wt.setAttribute("aria-label",c?`${a} (response streaming below)`:a))},Fh=()=>{Zo!==0&&(Zo=0,np())},Jw=()=>{let a=_t?.spacerHeight??0;return a<=0?cs(G,ko):bl(a)-G.scrollTop-G.clientHeight<=ko},op=()=>Yo()?!kn.isFollowing():!Jw(),rp=()=>!!F&&F.getMessages().length>0,Ut=()=>{if(!Ww()||Cs()){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==K&&K.appendChild(Wt),Pr();let c=xo(G)>0&&op()&&rp();c?np():Fh(),Wt.style.display=c?"":"none"},Da=()=>{kn.pause()&&(Oh(),Ut())},bn=()=>{kn.resume(),Fh(),Ut()},er=(a=!1)=>{Yo()&&rp()&&kn.isFollowing()&&(!a&&!Tn||(Qo!==null&&(cancelAnimationFrame(Qo),Qo=null),dl=!0,Qo=requestAnimationFrame(()=>{Qo=null,dl=!1,kn.isFollowing()&&Qw(Dh(),a?220:140)})))},Nh=(a,c,m,h=()=>!0)=>{let C=a.scrollTop,R=c(),z=R-C;if(Rs(),Math.abs(z)<1){yn=!0,a.scrollTop=R,Pn=a.scrollTop,yn=!1;return}let V=performance.now();yn=!0;let J=te=>1-Math.pow(1-te,3),j=te=>{if(!h()){Rs();return}let se=c();se!==R&&(R=se,z=R-C);let fe=te-V,$e=Math.min(fe/m,1),gt=J($e),$t=C+z*gt;a.scrollTop=$t,Pn=a.scrollTop,$e<1?Hs=requestAnimationFrame(j):(a.scrollTop=R,Pn=a.scrollTop,Hs=null,yn=!1)};Hs=requestAnimationFrame(j)},Qw=(a,c=500)=>{let m=xo(a)-a.scrollTop;if(Math.abs(m)<1){Pn=a.scrollTop;return}if(Math.abs(m)>=jw){Rs(),yn=!0,a.scrollTop=xo(a),Pn=a.scrollTop,yn=!1;return}Nh(a,()=>xo(a),c,()=>kn.isFollowing())},gl=()=>{if(!rp()){Ut();return}let a=Dh();yn=!0,a.scrollTop=xo(a),Pn=a.scrollTop,yn=!1,Ut()},_r=a=>{let c=0,m=a;for(;m&&m!==G;)c+=m.offsetTop,m=m.offsetParent;return c},Zw=()=>{let a=G.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??G.ownerDocument.getSelection()},hl=()=>Av(Zw(),G),sp=()=>{if(Bw()!=="last-user-turn")return!1;let a=F?.getMessages()??[];if(a.length<2)return!1;let c=[...a].reverse().find(R=>R.role==="user");if(!c)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=G.querySelector(`[data-message-id="${m}"]`);if(!h)return!1;let C=Math.min(Math.max(0,_r(h)-Ta()),xo(G));return yn=!0,G.scrollTop=C,Pn=G.scrollTop,yn=!1,Mn()==="follow"&&!cs(G,ko)&&kn.pause(),Ut(),!0},yl=a=>{let c=Math.max(0,Math.round(a));Fn.style.height=`${c}px`,Fn.style.display=c>0?"":"none",_t&&(_t.spacerHeight=Math.max(0,a))},bl=a=>{let c=parseFloat(getComputedStyle(G).paddingBottom)||0,m=0;for(let C of Array.from(G.children)){if(C===Fn||C.offsetHeight===0)continue;let R=_r(C)+C.offsetHeight;R>m&&(m=R)}let h=G.scrollHeight-a;return m>0?Math.min(m+c,h):h},eS=()=>{if(!_t||_t.spacerHeight<=0)return;let a=bl(_t.spacerHeight),c=Math.max(0,Math.round(G.scrollTop)+G.clientHeight-a+ko);c<_t.spacerHeight&&(yl(c),Ut())},eo=()=>{Or!==null&&(cancelAnimationFrame(Or),Or=null),Rs(),_t=null,Fn.style.height="0px",Fn.style.display="none"},_h=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),ap=a=>G.querySelector(`[data-message-id="${_h(a)}"]`),Uh=a=>{Or!==null&&cancelAnimationFrame(Or),Or=requestAnimationFrame(()=>{Or=null;let c=_h(a),m=G.querySelector(`[data-message-id="${c}"]`);if(!m)return;let h=_r(m),C=_t?.spacerHeight??0,R=bl(C),{targetScrollTop:z,spacerHeight:V}=qm({anchorOffsetTop:h,topOffset:Ta(),viewportHeight:G.clientHeight,contentHeight:R,slack:ko});_t={initialSpacerHeight:V,contentHeightAtAnchor:R,spacerHeight:V},yl(V),Nh(G,()=>m.isConnected?Math.max(0,_r(m)-Ta()):z,220)})},Ho=()=>{if(Mn()!=="anchor-top"||!_t||!Ls)return;let a=ap(Ls);if(!a)return;Rs();let c=_t.spacerHeight,m=bl(c),{targetScrollTop:h,spacerHeight:C}=qm({anchorOffsetTop:_r(a),topOffset:Ta(),viewportHeight:G.clientHeight,contentHeight:m,slack:ko});_t={initialSpacerHeight:C,contentHeightAtAnchor:m,spacerHeight:C},yl(C),yn=!0,G.scrollTop=h,Pn=G.scrollTop,yn=!1,Ut()},tS=()=>{if(Yo()){if(!kn.isFollowing()||cs(G,1))return;er(!Tn);return}if(_t&&_t.initialSpacerHeight>0){let a=G.scrollHeight-_t.spacerHeight,c=Mv({initialSpacerHeight:_t.initialSpacerHeight,contentHeightAtAnchor:_t.contentHeightAtAnchor,currentContentHeight:a});c!==_t.spacerHeight&&yl(c)}Ut()},nS=a=>{let c=Mn();c==="follow"?(bn(),er(!0)):c==="anchor-top"&&(Ba=!1,pl=!0,ul=!1,Ls=a,Uh(a))},oS=()=>{if(Mn()==="anchor-top"){if(pl){Ba=!1;return}Ba=!0,eo(),bn(),er(!0)}},rS=96,sS=a=>{if(Fr===null)return!0;let c=ap(Fr),m=ap(a);if(!c||!m)return!0;let h=_r(m)-_r(c);return Ta()+h>G.clientHeight-rS},aS=a=>{if(Mn()!=="anchor-top"||!pl||ul||hl())return;let c=Fr===null;for(let m of a){if(!c){m.id===Fr&&(c=!0);continue}if(vv(m)){if(m.id===Ls||!sS(m.id))return;Ls=m.id,Uh(m.id);return}}},iS=a=>{let c=new Map;a.forEach(m=>{let h=ep.get(m.id);c.set(m.id,{streaming:m.streaming,role:m.role}),!h&&m.role==="assistant"&&(g.emit("assistant:message",m),!Ps&&(Mn()!=="anchor-top"||Yg())&&op()&&(Zo+=1,np(),Ut(),Qg(Zo===1?"1 new message below.":`${Zo} new messages below.`))),m.role==="assistant"&&h?.streaming&&m.streaming===!1&&g.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(h?m.approval.status!=="pending"&&g.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):g.emit("approval:requested",{approval:m.approval,message:m}))}),ep.clear(),c.forEach((m,h)=>{ep.set(h,m)})},xl=(a,c)=>{let m=c==="user"?"user":"assistant",h=o.layout?.messages?.[m],C=h?.width??"content",R=h?.maxWidth??(C==="full"?"100%":"85%");a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${c}`,`persona-message-width-${C}`),a.classList.toggle("persona-justify-end",c==="user"),a.setAttribute("data-message-role",c),a.setAttribute("data-message-width",C),a.style.setProperty("--persona-message-row-max-width",R)},Ur=(a,c)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),xl(m,c),m},lS=(a,c,m)=>{let h=document.createElement("div"),R=(()=>{let _=i.find(ke=>ke.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),z=(_,ke)=>ke==null?!1:typeof ke=="string"?(_.textContent=ke,!0):(_.appendChild(ke),!0),V=new Set,J=new Map,j=new Set,te=i.some(_=>_.renderAskUserQuestion),se=[],fe=[],$e=o.enableComponentStreaming!==!1,gt=o.approval!==!1,$t=[];if(c.forEach(_=>{V.add(_.id),J.set(_.id,_.role);let ke=te&&No(_),Le=gt&&_.variant==="approval"&&!!_.approval,ve=!ke&&_.role==="assistant"&&!_.variant&&$e&&Qi(_);!Le&&Jo.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Jo.delete(_.id)),!ve&&Dr.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Dr.delete(_.id));let Mt=No(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",lt=gv(_,Jd)+Mt,Gt=ke||Le||ve?null:yv(En,_.id,lt);if(Gt){h.appendChild(Gt.cloneNode(!0)),No(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(j.add(_.toolCall.id),Js(_,o,Q.composerOverlay));return}let at=null,cn=i.find(He=>!!(_.variant==="reasoning"&&He.renderReasoning||_.variant==="tool"&&He.renderToolCall||!_.variant&&He.renderMessage)),Xt=o.layout?.messages;if(No(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){ks.delete(_.id),a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(es(_)&&fr(o).enabled)return;if(No(_)&&o.features?.askUserQuestion?.enabled!==!1){let He=i.find(dn=>typeof dn.renderAskUserQuestion=="function");if(He&&tt.current){let dn=ks.get(_.id),Vt=dn!==lt,Ae=null;if(Vt){let{payload:qe,complete:Dt}=_o(_),Pt=_.id,nn=()=>tt.current?.getMessages().find(zn=>zn.id===Pt);Ae=He.renderAskUserQuestion({message:_,payload:qe,complete:Dt,resolve:zn=>{let Ve=nn();Ve&&tt.current?.resolveAskUserQuestion(Ve,zn)},dismiss:()=>{let zn=nn();zn?.agentMetadata?.awaitingLocalTool&&(tt.current?.markAskUserQuestionResolved(zn),tt.current?.resolveAskUserQuestion(zn,"(dismissed)"))},config:o})}let Bt=dn!=null;if(Vt&&Ae===null&&!Bt){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(j.add(_.toolCall.id),Js(_,o,Q.composerOverlay));return}let ct=Ur(_.id,_.role);ct.setAttribute("data-ask-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),h.appendChild(ct),se.push({messageId:_.id,fingerprint:lt,bubble:Ae});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(j.add(_.toolCall.id),Js(_,o,Q.composerOverlay));return}}else if(Le){let He=i.find(Bt=>typeof Bt.renderApproval=="function")??f,Vt=Jo.get(_.id)!==lt,Ae=null;if(Vt&&He?.renderApproval){let Bt=_.id,ct=(qe,Dt)=>{let Pt=tt.current?.getMessages().find(nn=>nn.id===Bt);Pt?.approval&&(Pt.approval.toolType==="webmcp"?tt.current?.resolveWebMcpApproval(Pt.id,qe):tt.current?.resolveApproval(Pt.approval,qe,Dt))};Ae=He.renderApproval({message:_,defaultRenderer:()=>Sd(_,o),config:o,approve:qe=>ct("approved",qe),deny:qe=>ct("denied",qe)})}if(Vt&&Ae===null)a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Jo.delete(_.id),at=Sd(_,o);else{let Bt=Ur(_.id,_.role);Bt.setAttribute("data-approval-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),h.appendChild(Bt),$t.push({messageId:_.id,fingerprint:lt,bubble:Ae});return}}else if(cn)if(_.variant==="reasoning"&&_.reasoning&&cn.renderReasoning){if(!we)return;at=cn.renderReasoning({message:_,defaultRenderer:()=>mg(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&cn.renderToolCall){if(!Pe)return;at=cn.renderToolCall({message:_,defaultRenderer:()=>hg(_,o),config:o})}else cn.renderMessage&&(at=cn.renderMessage({message:_,defaultRenderer:()=>{let He=ha(_,m,Xt,o.messageActions,U,{loadingIndicatorRenderer:R,widgetConfig:o});return _.role!=="user"&&Mg(He,_,o,F),He},config:o}));if(!at&&ve){let He=Rd(_);if(He){let dn=Dr.get(_.id),Vt=dn!==lt,Ae=o.wrapComponentDirectiveInBubble!==!1&&ro.getOptions(He.component)?.bubbleChrome!==!1,Bt=null;if(Vt){let ct=Hd(He,{config:o,message:_,transform:m});if(ct&&He.component==="PersonaArtifactInline"){let qe=ct.hasAttribute("data-artifact-inline")?ct:ct.querySelector("[data-artifact-inline]"),Dt=qe?.getAttribute("data-artifact-inline")??"",Pt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Dt):Dt,nn=Dt?a.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${Pt}"]`)??null:null;qe&&nn&&nn!==qe&&cv(nn)&&(qe===ct?ct=nn:qe.replaceWith(nn))}if(ct)if(Ae){let qe=document.createElement("div");if(qe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),qe.id=`bubble-${_.id}`,qe.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=m({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),qe.appendChild(Dt)}qe.appendChild(ct),Bt=qe}else{let qe=document.createElement("div");if(qe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",qe.id=`bubble-${_.id}`,qe.setAttribute("data-message-id",_.id),qe.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=m({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),qe.appendChild(Dt)}qe.appendChild(ct),Bt=qe}}if(Bt||dn!=null){let ct=Ur(_.id,_.role);ct.setAttribute("data-component-directive-stub","true"),ct.setAttribute("data-preserve-runtime","true"),h.appendChild(ct),fe.push({messageId:_.id,fingerprint:lt,bubble:Bt});return}}}if(!at)if(_.variant==="reasoning"&&_.reasoning){if(!we)return;at=mg(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!Pe)return;at=hg(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;at=Sd(_,o)}else{let He=o.layout?.messages;He?.renderUserMessage&&_.role==="user"?at=He.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):He?.renderAssistantMessage&&_.role==="assistant"?at=He.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):at=ha(_,m,He,o.messageActions,U,{loadingIndicatorRenderer:R,widgetConfig:o}),_.role!=="user"&&at&&Mg(at,_,o,F)}let qt=Ur(_.id,_.role);qt.appendChild(at),bv(En,_.id,lt,qt),h.appendChild(qt)}),Q.composerOverlay&&Q.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let Le=ke.getAttribute("data-persona-ask-sheet-for");Le&&!j.has(Le)&&pr(Q.composerOverlay,Le)}),o.features?.toolCallDisplay?.grouped){let _=[],ke=[],Le=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(ve=>{if(ve.variant==="tool"&&ve.toolCall&&Pe){ke.push(ve);return}ve.variant==="reasoning"&&!we||((ke.length>1||Le&&ke.length>0)&&_.push(ke),ke=[])}),(ke.length>1||Le&&ke.length>0)&&_.push(ke),_.forEach(ve=>{let Mt=ve.map(He=>Array.from(h.children).find(dn=>dn instanceof HTMLElement&&dn.getAttribute("data-wrapper-id")===He.id)).filter(He=>!!He);if(Mt.length<(Le?1:2))return;let lt=Ur(`tool-group-${ve[0].id}`,"assistant");lt.setAttribute("data-persona-tool-group-row","true");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 at=document.createElement("div");at.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",at.id=`tool-group-summary-${ve[0].id}`;let cn=`Called ${ve.length} ${ve.length===1?"tool":"tools"}`,Xt=o.toolCall?.renderGroupedSummary?.({messages:ve,toolCalls:ve.map(He=>He.toolCall).filter(He=>!!He),defaultSummary:cn,config:o});z(at,Xt)||(at.textContent=cn);let qt=document.createElement("div");qt.className="persona-tool-group-stack persona-flex persona-flex-col",qt.id=`tool-group-stack-${ve[0].id}`,qt.setAttribute("data-persona-tool-group-stack","true"),Gt.appendChild(at),Le||Gt.appendChild(qt),lt.appendChild(Gt),Mt[0].before(lt),Mt.forEach((He,dn)=>{if(Le){He.remove();return}He.style.setProperty("--persona-message-row-max-width","100%");let Vt=document.createElement("div");Vt.className="persona-tool-group-item persona-relative",Vt.setAttribute("data-persona-tool-group-item","true"),dn<Mt.length-1&&Vt.setAttribute("data-persona-tool-group-connector","true"),Vt.appendChild(He),qt.appendChild(Vt)})})}xv(En,V);let vn=c.some(_=>_.role==="assistant"&&_.streaming),At=c[c.length-1],kt=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(Tn&&c.some(_=>_.role==="user")&&!vn&&!kt){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:ms},ke=i.find(ve=>ve.renderLoadingIndicator),Le=null;if(ke?.renderLoadingIndicator&&(Le=ke.renderLoadingIndicator(_)),Le===null&&o.loadingIndicator?.render&&(Le=o.loadingIndicator.render(_)),Le===null&&(Le=ms()),Le){let ve=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1,lt=o.layout?.messages?.layout??"bubble";ve.className=Mt?qi("assistant",lt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),ve.setAttribute("data-typing-indicator","true"),Mt&&(ve.style.color="var(--persona-message-assistant-text, var(--persona-text))",lt!=="flat"&&(ve.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),ve.appendChild(Le);let Gt=Ur("typing-indicator","assistant");Gt.appendChild(ve),h.appendChild(Gt)}}if(!Tn&&c.length>0){let _=c[c.length-1],ke={config:o,lastMessage:_,messageCount:c.length},Le=i.find(Mt=>Mt.renderIdleIndicator),ve=null;if(Le?.renderIdleIndicator&&(ve=Le.renderIdleIndicator(ke)),ve===null&&o.loadingIndicator?.renderIdle&&(ve=o.loadingIndicator.renderIdle(ke)),ve){let Mt=document.createElement("div"),lt=o.loadingIndicator?.showBubble!==!1;Mt.className=lt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(ve);let Gt=Ur("idle-indicator","assistant");Gt.appendChild(Mt),h.appendChild(Gt)}}if(Ab(h),sd(a,h),au(a),se.length>0)for(let{messageId:_,fingerprint:ke,bubble:Le}of se){let ve=a.querySelector(`#wrapper-${_}`);ve&&(xl(ve,J.get(_)??"assistant"),Le!==null&&(ve.replaceChildren(Le),ve.setAttribute("data-bubble-fp",ke),ks.set(_,ke)))}if(ks.size>0)for(let _ of ks.keys())V.has(_)||ks.delete(_);if(fe.length>0)for(let{messageId:_,fingerprint:ke,bubble:Le}of fe){let ve=a.querySelector(`#wrapper-${_}`);ve&&(xl(ve,J.get(_)??"assistant"),Le!==null&&(ve.replaceChildren(Le),ve.setAttribute("data-bubble-fp",ke),Dr.set(_,ke)))}if(Dr.size>0)for(let _ of Dr.keys())V.has(_)||Dr.delete(_);if($t.length>0)for(let{messageId:_,fingerprint:ke,bubble:Le}of $t){let ve=a.querySelector(`#wrapper-${_}`);ve&&(xl(ve,J.get(_)??"assistant"),Le!==null&&(ve.replaceChildren(Le),ve.setAttribute("data-bubble-fp",ke),Jo.set(_,ke)))}if(Jo.size>0)for(let _ of Jo.keys())V.has(_)||Jo.delete(_)},Oa=(a,c,m)=>{lS(a,c,m),fh()},Fa=null,cS=()=>{if(Fa)return;let a=m=>{let h=m.composedPath();h.includes(W)||Y&&h.includes(Y)||st(!1,"user")};Fa=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},qh=()=>{if(!Fa)return;(e.ownerDocument??document).removeEventListener("pointerdown",Fa,!0),Fa=null};Te.push(()=>qh());let Na=null,dS=()=>{if(Na)return;let a=m=>{m.key==="Escape"&&(m.isComposing||st(!1,"user"))};Na=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},Vh=()=>{if(!Na)return;(e.ownerDocument??document).removeEventListener("keydown",Na,!0),Na=null};Te.push(()=>Vh());let _a=!1,zh=new Set,pS=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},Is=()=>{if(!ie())return;let a=Q.peekBanner,c=Q.peekTextNode;if(!a||!c)return;if(I){a.classList.remove("persona-pill-peek--visible");return}let m=F?.getMessages()??[],h;for(let At=m.length-1;At>=0;At--){let kt=m[At];if(kt.role==="assistant"&&kt.content){h=kt;break}}if(!h){a.classList.remove("persona-pill-peek--visible");return}let C=h.content,R=!!h.streaming,z=pS(),V=ad(z),J=V.type!=="none"?ua(V.type,z?.plugins):null,j=J?.isAnimating?.(h)===!0,te=J!==null&&(R||j);te&&J&&!zh.has(J.name)&&(cd(J,e),zh.add(J.name));let se=te&&J?.containerClass?J.containerClass:null,fe=c.dataset.personaPeekStreamClass??null;fe&&fe!==se&&(c.classList.remove(fe),delete c.dataset.personaPeekStreamClass),se&&fe!==se&&(c.classList.add(se),c.dataset.personaPeekStreamClass=se),te?(c.style.setProperty("--persona-stream-step",`${V.speed}ms`),c.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let $e=te?id(C,V.buffer,J,h,R):C;if(te&&V.placeholder==="skeleton"&&R&&(!$e||!$e.trim())){let At=document.createElement("div"),kt=Fi();kt.classList.add("persona-pill-peek__skeleton"),At.appendChild(kt),sd(c,At)}else{let At=Math.max(0,$e.length-100),kt=$e.length>100?$e.slice(-100):$e,_=mo(kt);if(!te||!J){let ke=$e.length>100?`\u2026${kt}`:kt;c.textContent!==ke&&(c.textContent=ke)}else{let ke=_;(J.wrap==="char"||J.wrap==="word")&&(ke=Oi(_,J.wrap,`peek-${h.id}`,{skipTags:J.skipTags,startIndex:At}));let Le=document.createElement("div");if(Le.innerHTML=ke,J.useCaret&&kt.length>0){let ve=ld(),Mt=Le.querySelectorAll(".persona-stream-char, .persona-stream-word"),lt=Mt[Mt.length-1];lt?.parentNode?lt.parentNode.insertBefore(ve,lt.nextSibling):Le.appendChild(ve)}sd(c,Le),J.onAfterRender?.({container:c,bubble:a,messageId:h.id,message:h,speed:V.speed,duration:V.duration})}}let vn=Tn||_a;a.classList.toggle("persona-pill-peek--visible",vn)};if(ie()){let a=Q.peekBanner;if(a){let h=C=>{C.preventDefault(),C.stopPropagation(),st(!0,"user")};a.addEventListener("pointerdown",h),Te.push(()=>{a.removeEventListener("pointerdown",h)})}let c=()=>{_a||(_a=!0,Is())},m=()=>{_a&&(_a=!1,Is())};O.addEventListener("pointerenter",c),O.addEventListener("pointerleave",m),Te.push(()=>{O.removeEventListener("pointerenter",c),O.removeEventListener("pointerleave",m)}),Y&&(Y.addEventListener("pointerenter",c),Y.addEventListener("pointerleave",m),Te.push(()=>{Y.removeEventListener("pointerenter",c),Y.removeEventListener("pointerleave",m)}))}let uS=a=>{let c=o.launcher?.composerBar??{},m=c.expandedSize??"anchored",h=c.bottomOffset??"16px",C=c.collapsedMaxWidth,R=c.expandedMaxWidth??"880px",z=c.expandedTopOffset??"5vh",V=c.modalMaxWidth??"880px",J=c.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",te="var(--persona-pill-area-height, 80px)",se=W.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Y){let fe=Y.style;fe.bottom=h,fe.width=C??""}if(a&&m!=="fullscreen"){if(m==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=V,se.maxWidth=j,se.maxHeight=J,se.height=J;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${h} + ${te})`,se.top=z,se.width=R,se.maxWidth=j}},Ua=()=>{if(!le())return;if(ie()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",te=I?"expanded":"collapsed";W.dataset.state=te,W.dataset.expandedSize=j,Y&&(Y.dataset.state=te,Y.dataset.expandedSize=j),W.style.removeProperty("display"),W.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),uS(I),K.style.display=I?"flex":"none",Lr(),I?(cS(),dS()):(qh(),Vh()),Is();return}let a=ht(o),c=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,h=o.launcher?.mobileFullscreen??!0,C=c.innerWidth<=m,R=h&&C&&N,z=Sn(o).reveal;I?(W.style.removeProperty("display"),W.style.display=a?"flex":"",W.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-95","persona-opacity-0"),O.classList.add("persona-scale-100","persona-opacity-100"),wt?(wt.setPanelOpen(!0),wt.element.style.display="none"):ln&&(ln.style.display="none")):(a?a&&(z==="overlay"||z==="push")&&!R?(W.style.removeProperty("display"),W.style.display="flex",W.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(W.style.setProperty("display","none","important"),W.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(W.style.display="",W.classList.add("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-100","persona-opacity-100"),O.classList.add("persona-scale-95","persona-opacity-0")),wt?(wt.setPanelOpen(!1),wt.element.style.display=a?"none":""):ln&&(ln.style.display=a?"none":""))},st=(a,c="user")=>{if(!le()||I===a)return;let m=I;I=a,Ua();let h=(()=>{let R=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,j=z.innerWidth<=J,te=ht(o)&&V&&j,se=ie()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return R||V&&j&&N||te||se})();if(I&&h){if(!ao){let R=e.getRootNode(),z=R instanceof ShadowRoot?R.host:e.closest(".persona-host");z&&(ao=Gm(z,o.launcher?.zIndex??Qt))}io||(io=Km(e.ownerDocument))}else I||(ao?.(),ao=null,io?.(),io=null);I&&(si(),sp()||(Mn()==="follow"?er(!0):gl()));let C={open:I,source:c,timestamp:Date.now()};I&&!m?g.emit("widget:opened",C):!I&&m&&g.emit("widget:closed",C),g.emit("widget:state",{open:I,launcherEnabled:N,voiceActive:Fe.active,streaming:F.isStreaming()})},qa=a=>{Kg(a?"stop":"send"),oe&&(oe.disabled=a),Ir.forEach(c=>{c.elements.forEach(m=>{m.toggleAttribute("data-disabled",a),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",a?"true":"false")}),c.buttons.forEach(m=>{m.disabled=a})}),dp.forEach(c=>{c.toggleAttribute("data-disabled",a),c instanceof HTMLButtonElement?c.disabled=a:c.setAttribute("aria-disabled",a?"true":"false"),c.querySelectorAll("button").forEach(m=>{m.disabled=a})}),Oe.dataset.personaComposerStreaming=a?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(c=>{(c instanceof HTMLButtonElement||c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)&&(c.disabled=a)})},qr=()=>{Fe.active||ge&&ge.focus()};g.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>qr(),200)});let Vr=null,Va=!1,ip=!hn.hidden,tr=null,jh=!H,$h=null,Gh,Kh=null,Ws=null,lp=!1,za=a=>{let c=jo(o),m=`${c.variant}|${c.dismiss}|${c.title}|${c.subtitle}`;(m!==$h||c.icon!==Gh)&&($h=m,Gh=c.icon,vd({host:hn,iconHolder:Ew,title:kw,subtitle:Pw,starterSuggestions:it},c));let h=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;h!==Kh&&(Kh=h,Cd(An,c.message,o));let C=a??(F?F.getMessages():o.initialMessages),R=Va,z=!R&&Tr(c,C),V=z!==ip;if(ip=z,Ws){tr?.cancel(),tr=null,R!==lp&&(lp=R,R?lg(G,hn,null):ig(G,hn,Ws)),ya(G,hn,!R);return}if(V&&!z&&!R&&c.dismiss==="on-first-message"&&jh){tr=_v(hn,j=>{tr===j&&(tr=null),!ip&&!Ws&&(ya(G,hn,!1),Ho()),j?.cancel()});return}if(tr){if(!z&&!R)return;tr.cancel(),tr=null}let J=!hn.hidden;ya(G,hn,z),!z&&J&&Ho()},cp=[],dp=[],pp=!1,Xh=null,Yh,Jh=()=>{dp.length=0;let a=cp.splice(0,cp.length);for(let c of a)try{c()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Te.push(Jh);let fS=(a,c)=>{let m=Ym(a,c);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),S("span");let h=o.suggestions?.starters,C=Jm({item:{...m,behavior:m.behavior??h?.behavior??"send"},index:c,surface:"starter",source:"config",variant:h?.variant??"card",streaming:u?F.isStreaming():!1,config:o,plugins:i,chipsConfig:o.suggestionChipsConfig,session:F,getTextarea:()=>ge,eventTarget:hn});return dp.push(C),C},up=()=>{if(pp)return;pp=!0;let a=jo(o);Xh=`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,Yh=a.icon;try{Jh(),lg(G,hn,Ws),Ws=null,lp=!1;let c=F?F.getMessages():o.initialMessages,m=Tr(a,c),h=0,C=null;for(let R of i)if(R.renderWelcome&&(C=R.renderWelcome({config:a,variant:a.variant,visible:m,defaultRenderer:()=>hn,sendMessage:z=>{if(!F||F.isStreaming())return;let V=z.trim();V&&F.sendMessage(V)},requestRender:()=>up(),renderStarter:z=>fS(z,h++),storage:p(R.id),onCleanup:z=>{cp.push(z)}}),C))break;C&&C!==hn&&(Ws=C,ig(G,hn,C))}finally{pp=!1}za()},mS=()=>{let a=jo(o);`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===Xh&&a.icon===Yh||up()},fp=()=>{za(),Pa||(ge.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!F?.isStreaming()&&(he.textContent=o.copy?.sendButtonLabel??"Send")),ge.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ge.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},gS=!!o.setStoredConversationId,ja=a=>P(c=>{let m={...c};return delete m[a],m}),vl=a=>{let c=E[a];return typeof c=="string"?c:null};o.clientToken&&(o={...o,getStoredSessionId:()=>vl("sessionId"),setStoredSessionId:a=>{P(c=>({...c,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ja("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>vl("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{P(c=>({...c,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ja("conversationId"))});let Qh=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,Zh=a=>PC(a,Be(),o.persistState===!1),ey=Qh(),Ro=ey?Zh(ey):null,zr={...Ro?{visitorStore:Ro}:{},historyBootstrapReady:M,getStoredMessageCursor:()=>vl("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){ja("historyMessageCursor");return}P(c=>({...c,historyMessageCursor:a}))},getPendingDisplayProjections:()=>{let a=E.pendingDisplayProjections;if(!a||typeof a!="object")return null;let c=a;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(m=>typeof m=="string")}},setPendingDisplayProjections:a=>{if(!a){ja("pendingDisplayProjections");return}P(c=>({...c,pendingDisplayProjections:a}))},...gS?{}:{getStoredConversationRevision:()=>vl("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){ja("conversationRevision");return}P(c=>({...c,conversationRevision:a}))}}},hS=()=>{let a=Qh();if(a&&Ro?.matches(a,Be(),o.persistState===!1)||!a&&!Ro)return;Ro?.destroy(),Ro=a?Zh(a):null;let c={...zr};Ro?c.visitorStore=Ro:delete c.visitorStore,zr=c,F.setHistoryInternals(zr)},jr=null,yS=()=>{jr==null&&(jr=setInterval(()=>{let a=ae.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(jr),jr=null;return}let c=Date.now();a.forEach(m=>{let h=Number(m.getAttribute("data-tool-elapsed"));h&&(m.textContent=pc(c-h))})},100))},mp=(a,c)=>{if(Object.is(a,c))return!0;if(a===null||c===null||typeof a!="object"||typeof c!="object")return!1;if(Array.isArray(a)||Array.isArray(c))return!Array.isArray(a)||!Array.isArray(c)||a.length!==c.length?!1:a.every((z,V)=>mp(z,c[V]));let m=a,h=c,C=Object.keys(m),R=Object.keys(h);return C.length===R.length&&C.every(z=>Object.prototype.hasOwnProperty.call(h,z)&&mp(m[z],h[z]))},ty=a=>{let{content:c,rawContent:m,llmContent:h,...C}=a;return C},gp=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Qi(a),bS=(a,c,m)=>{if(a.length!==c.length)return!1;let h=a[m.index],C=c[m.index];return!h||!C||h.id!==m.id||C.id!==m.id?!1:(!Object.is(h.content,C.content)||!Object.is(h.rawContent,C.rawContent)||!Object.is(h.llmContent,C.llmContent))&&gp(h)&&gp(C)&&mp(ty(h),ty(C))},hp=null,Bs=null,$r=null,Io=null,Cl=a=>{hp=a;let c,m;Bs=null;for(let C=a.length-1;C>=0;C-=1){let R=a[C];if(!c&&R.role==="user"&&(c=R),!m&&R.role==="assistant"&&(m=R),!Bs&&gp(R)&&(Bs={index:C,id:R.id}),c&&m&&Bs)break}Oa(ae,a,Ce),Fm(ae,Jn.artifacts,{suppressTransition:Tn}),yS(),za(a),Es(a),er(!Tn),iS(a),a.length===0&&(eo(),Ba=!0,pl=!1,Ls=null,ul=!1),!Qd||Ps?(Qd=!0,Fr=c?.id??null,Zd=m?.id??null):c&&c.id!==Fr?(Fr=c.id,nS(c.id)):m&&m.id!==Zd&&oS(),m&&(Zd=m.id),aS(a);let h=Fe.lastUserMessageId;c&&c.id!==h&&(Fe.lastUserMessageId=c.id,g.emit("user:message",c)),Fe.lastUserMessageWasVoice=!!c?.viaVoice,tp(a),Is()},yp=()=>{Io!==null&&(cancelAnimationFrame(Io),Io=null);let a=$r;$r=null,a&&Cl(a)},ny=()=>{Io!==null&&cancelAnimationFrame(Io),Io=null,$r=null},xS=a=>{let c=$r??hp;if(Tn&&c&&Bs&&bS(c,a,Bs)){$r=a,Io===null&&(Io=requestAnimationFrame(()=>{Io=null;let m=$r;$r=null,m&&Cl(m)}));return}if(a.length===0){ny(),Cl(a);return}yp(),Cl(a)};F=new oa(o,{onMessagesChanged(a){xS(a)},onStatusChanged(a){let c=o.statusIndicator??{};T(rn,(h=>h==="idle"?c.idleText??Nt.idle:h==="connecting"?c.connectingText??Nt.connecting:h==="connected"?c.connectedText??Nt.connected:h==="error"?c.errorText??Nt.error:h==="paused"?c.pausedText??Nt.paused:h==="resuming"?c.resumingText??Nt.resuming:Nt[h])(a),c,a),Ko()},onStreamingChanged(a){a||(F?.getMessages().length===0?ny():yp()),Tn=a,qa(a),Ko(),F&&Oa(ae,F.getMessages(),Ce),a||(er(!0),eS(),Lh=!0,F&&Hh(F.getMessages(),fr(o))),Ut(),Qg(a?"Responding\u2026":"Response complete."),Is()},onVoiceStatusChanged(a){if(g.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Oo(),qs();break;case"processing":Oo(),pA();break;case"speaking":Oo(),uA();break;default:a==="idle"&&F.isBargeInActive()?(Oo(),qs(),oe?.setAttribute("aria-label","End voice session")):(Fe.active=!1,Oo(),Lo("system"),Zn());break}},onArtifactsState(a){Jn=a,a.artifacts.length===0&&(As=!1),Fm(ae,a.artifacts,{suppressTransition:Tn}),To(),tp()},onHistoryStateChanged(a){wo(a)},onHistoryNotice(a){It(a)},onReconnect(a){let{executionId:c,lastEventId:m}=a.handle;a.phase==="paused"?g.emit("stream:paused",{executionId:c,after:m}):a.phase==="resuming"?g.emit("stream:resuming",{executionId:c,after:m,attempt:a.attempt??1}):g.emit("stream:resumed",{executionId:c,after:m})}},zr),tt.current=F,Te.push(()=>F.cancel()),Te.push(()=>{F.destroy(),Ro?.destroy()});let bp=null;if(F.onReadAloudChange((a,c)=>{ph=a,uh=c,fh();let m=a??bp;a&&(bp=a);let h=m?F.getMessages().find(C=>C.id===m)??null:null;g.emit("message:read-aloud",{messageId:m,message:h,state:c,timestamp:Date.now()}),c==="idle"&&(bp=null)}),u=!0,Qd=!0,o.voiceRecognition?.provider?.type==="runtype")try{F.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let vS=720,CS=250,Ue=Hg(o.features?.history?.copy),Ln=null,xp=!1,Xe=null,wl=null,Sl="conversation",vp=null,an=null,lo=null,Al=F.getHistoryState(),Cp=null,Ml=0,wp=null,Tl=null,El=null,Sp=`persona-history-${Math.random().toString(36).slice(2,8)}`,Ap=()=>o.features?.history?.enabled===!0,co=()=>Ap()&&!!Ln&&!xp,oy=()=>{let a=F.getStatus();return Tn||a==="paused"||a==="resuming"},Mp=()=>{let a=o.features?.history?.scope;if(a)return a;let c=o.getIdentityProof?"verified-user":"browser",m=Ln?.capabilities.scopes;return!m||m.includes(c)?c:m[0]??c},Ds=()=>wl?.scope??Mp(),ry=()=>F.getClientSession()?.targetId??null,sy=a=>`${a.state}:${"reason"in a?a.reason:""}`,wS=a=>{let c=sy(a);c!==Cp&&(Cp=c,g.emit("history:identityStatusChanged",{status:a,timestamp:Date.now()}))},kl=a=>{a&&(Ao.textContent="",Ao.textContent=a)},ay=null,iy=null,SS=()=>{if(!Ap())return null;let a=WC();if(a)return a();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(ay!==c&&(ay=c,iy=c()),iy):F.isClientTokenMode()?BC({client:F.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:m=>F.bindActivatedSession(m),getClient:()=>F.getClient()}):null},ly=()=>{Tl?.(),Tl=null,El?.(),El=null,xp=!1,Ln=SS();let a={...zr};Ln?a.historyProvider=Ln:delete a.historyProvider,zr=a,F.setHistoryInternals(zr),Ln&&(Tl=Ln.subscribeAvailability?.(c=>{xp=!c,c||xn({restoreFocus:!1}),or()})??null,El=Ln.subscribeIdentityStatus(c=>wS(c)),Cp=sy(Ln.getIdentityStatus()))},Tp=()=>{let a=o.features?.history?.presentation??"panel";if(a==="panel"||a==="auto"&&!(!N||ht(o)))return"panel";let c=so??K;return(c.getBoundingClientRect().width||c.clientWidth)>=vS?"rail":"panel"},Nn=(a,c)=>{c?(a.setAttribute("aria-hidden","true"),a.setAttribute("inert","")):(a.removeAttribute("aria-hidden"),a.removeAttribute("inert"))},Pl="data-persona-history-suppressed",Hn=null,nr=null,Gr=null,$a=null,Ep=null,cy="",dy=()=>Se===Ep?cy:o.layout?.showHeader===!1?"none":"",AS=()=>Qe==="panel"&&!!Gr&&$a===Gr.element&&o.layout?.showHeader!==!1&&dy()!=="none",MS=()=>{for(let a of Array.from(Se.children))a!==Hn&&a.setAttribute(Pl,"")},TS=()=>{for(let a of Array.from(K.querySelectorAll(`[${Pl}]`)))a.removeAttribute(Pl)},ES=()=>{let a=Gr;if(!a)return;if(Array.from(Se.children).some(h=>h!==Hn&&!h.hasAttribute(Pl))){nr&&nr!==Se&&(nr.style.removeProperty("min-height"),nr=null);let h=Se.offsetHeight;h>0&&(Se.style.minHeight=`${h}px`,nr=Se)}Hn||(Hn=S("div","persona-history-header-host")),a.setHeaderPlacement("external");let m=a.getHeaderElement();m.parentNode!==Hn&&Hn.replaceChildren(m),Hn.parentNode!==Se&&Se.appendChild(Hn),MS()},py=()=>{nr&&(nr.style.removeProperty("min-height"),nr=null),Hn&&(Gr?.setHeaderPlacement("inline"),Hn.remove(),Hn=null,TS())},Ll=null,kp=()=>{if(Ll){if(G.style.display="none",Nn(G,!0),Oe.hidden=!0,Nn(Oe,!0),AS()){ES(),Se.style.display=dy(),Nn(Se,!1);return}py(),Se.style.display="none",Nn(Se,!0)}};bt=kp;let kS=a=>{let c=G.style.display,m=Oe.hidden,h=Oe,C=Se,R=Se.style.display;Ep=C,cy=R,Ll=()=>{Ll=null,py(),Ep=null,G.style.display=c,Nn(G,!1),h.hidden=m,Nn(h,!1),Oe!==h&&(Oe.hidden=!1,Nn(Oe,!1)),C.style.display=R,Nn(C,!1),Se!==C&&(Se.style.display=o.layout?.showHeader===!1?"none":"",Nn(Se,!1))},Oe.parentNode?.insertBefore(a,Oe),kp()},Ga=null,Os=null,Ka=null,uy=()=>[Se,Q.closeButtonWrapper,Q.clearChatButtonWrapper,G,Oe],PS=52,Hl=()=>o.features?.history?.rail?.collapsible!==!1,Fs=()=>o.features?.history?.rail?.side==="right"?"right":"left",Pp=200,Lp=400,Hp=a=>Math.min(Lp,Math.max(Pp,Math.round(a))),LS=()=>o.features?.history?.rail?.resizable===!0,Xa,HS=()=>{if(Xa===void 0&&(Xa=null,o.persistState!==!1))try{let a=Number(window.localStorage.getItem(`${Be()}rail-width`));a&&(Xa=a)}catch{}return Xa},Ya=()=>Hp(HS()??o.features?.history?.rail?.width??260),RS=a=>{if(Xa=a,o.persistState!==!1)try{window.localStorage.setItem(`${Be()}rail-width`,String(a))}catch{}},Rl=()=>Hl()&&o.features?.history?.rail?.collapsedBehavior==="overlay",jt=!1,fy=a=>{let c=S("img");return c.src=a,c.alt="",c.setAttribute("aria-hidden","true"),c},IS=()=>{let a=o.features?.history?.rail?.brand;if(!a)return;let c=!1,m;return h=>{if(a.render)try{return a.render({collapsed:h})??null}catch(C){return c||(c=!0,console.warn("[persona] history rail brand threw",C)),null}return m===void 0&&(a.iconUrl?m=fy(a.iconUrl):m=a.icon?ce(a.icon,20):null),m?m.cloneNode(!0):null}},WS=()=>o.features?.history?.rail?.sections?.map(a=>{let c=!1,m=h=>{c||(c=!0,console.warn("[persona] history rail section threw",a.id,h))};return{id:a.id,title:a.title,placement:a.placement??"above-conversations",items:a.items.map(h=>{let C;return{id:h.id,label:h.label,badge:h.badge,iconNode:()=>{if(C!==void 0)return C;try{h.renderIcon?C=h.renderIcon()??null:h.iconUrl?C=fy(h.iconUrl):C=h.icon?ce(h.icon,20):null}catch(R){m(R),C=null}return C},onSelect:()=>{try{h.onSelect()}catch(R){m(R)}}}})}})??[],BS=a=>{let c=WS();for(let m of a)c.some(h=>h.id===m.id)?console.warn("[persona] duplicate history rail section id",m.id):c.push(m);return c.length?c:void 0},Ja=null,my=()=>`${Be()}rail-collapsed`,Rp=()=>{if(Ja===null&&(Ja=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let a=window.localStorage.getItem(my());a&&(Ja=a==="1")}catch{}return Ja},Ip=a=>{if(Ja=a,o.persistState!==!1)try{window.localStorage.setItem(my(),a?"1":"0")}catch{}},Qa=()=>Qe==="rail"&&Hl()&&!Rl()&&Rp(),Wp=()=>{},gy=()=>{if(Rl()){Wp();return}Ip(!Rp()),Xe?.view.setCollapsed(Qa()),en(),Ho()},Bp=()=>{let a=o.features?.history?.rail?.collapseShortcut;return!a||!Gc(a)?null:{combo:a,hint:Kc(a),aria:Hi(a)}},hy=()=>{d.forEach(c=>c()),d=[];let a=Bp();a&&d.push(l.register({id:"history-rail-collapse",combo:a.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Ye&&Qe==="rail"&&Hl()||Za(),run:()=>Rl()?Wp():gy()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let m=e.querySelector(`[data-persona-header-action="${c.id}"]`);m?m.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of i)for(let m of c.shortcuts??[])d.push(l.register({...m,id:`${c.id}:${m.id}`}))};hy();let DS=300,Il="var(--persona-history-overlay-margin,8px)",_n=null,Wo=null,Bo=null,Ns=null,Kr=!1,Dp=0,yy=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Za=()=>co()&&Rl()&&(Qe??Tp())==="rail",OS=()=>Ye&&!jt,ei=()=>{Ns!==null&&clearTimeout(Ns),Ns=null},FS=()=>{kg().catch(()=>{})},by=()=>{ei(),jt&&(Ns=setTimeout(()=>{Ns=null,!(Kr||!jt)&&(Bo?.contains(document.activeElement)||xn({restoreFocus:!1}))},DS))},NS=(a,c)=>{let m=Bo?.getBoundingClientRect();if(!m)return!1;let h=_n?.getBoundingClientRect(),C=h?Math.min(h.top,m.top):m.top;return a>=m.left&&a<=m.right&&c>=C&&c<=m.bottom||!!h&&a>=h.left&&a<=h.right&&c>=h.top&&c<=h.bottom},Op=a=>{jt&&(Kr=NS(a.clientX,a.clientY),Kr?ei():Ns===null&&by())},xy=a=>{Ye||!Za()||(jt=!0,ti({invoker:_n,keyboard:a?.keyboard===!0}).then(()=>{Ye?!Kr&&document.activeElement!==_n&&xn():jt=!1}))},vy=()=>{let a=$a?.querySelector('[data-persona-history-focus="collapse"]');a&&(a.setAttribute("aria-label",jt?Ue.expandLabel:Ue.collapseLabel),a.setAttribute("aria-expanded",jt?"false":"true"))},Cy=()=>{Ip(!1);let a=Xe;if(!jt||!a){ti({invoker:_n});return}let c=document.activeElement===_n;jt=!1,_p(),a.element.remove(),Up(a.element),vy(),c&&Bl(),Ho(),or()},_S=()=>{Ip(!0),xn()};Wp=()=>{!Ye||jt?Cy():_S()};let US=()=>{let a=Bp(),c=ps({ariaLabel:Ue.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":Sp,...a?{"aria-keyshortcuts":a.aria}:{}}}),m=c.button;m.addEventListener("mouseenter",()=>{Kr=!0,ei(),!(yy()||Date.now()<Dp)&&xy()}),m.addEventListener("mouseleave",()=>{Kr=!1,Dp=0,by()}),m.addEventListener("focus",()=>{Ye||FS()}),m.addEventListener("click",h=>{co()&&(h.detail!==0&&yy()&&!Ye?xy():Cy())}),_n=m,Wo=c.wrapper},Fp=()=>{if(Wo&&!Wo.isConnected&&(Wo=null,_n=null),!Za()){Wo?.remove(),Wo=null,_n=null;return}_n||US();let a=Wo,c=_n;if(!a||!c)return;let m=Fs()!=="right"?Se.firstChild:null;(m??Se.lastChild)!==a&&Se.insertBefore(a,m),a.style.display=OS()?"none":"",c.setAttribute("aria-label",Ue.expandLabel),c.setAttribute("aria-expanded",Ye?"true":"false"),Bo&&en()},wy=a=>{if(!jt)return;let c=a.target;c instanceof Node&&(Bo?.contains(c)||Wo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",wy,!0),Te.push(()=>{document.removeEventListener("pointerdown",wy,!0),document.removeEventListener("pointermove",Op),_s?.(),ei()});let Np=null,_s=null,Sy=16,Ay=a=>{RS(Hp(a)),en(),Ho()},qS=()=>{let a=S("div","persona-rail-resizer");return a.tabIndex=0,a.setAttribute("role","separator"),a.setAttribute("aria-orientation","vertical"),a.setAttribute("aria-valuemin",String(Pp)),a.setAttribute("aria-valuemax",String(Lp)),a.addEventListener("pointerdown",c=>{let m=Os;if(!m||c.button!==0)return;c.preventDefault(),_s?.();let h=c.clientX,C=m.getBoundingClientRect().width||Ya(),R=Fs()==="right"?-1:1,z=C,V=e.ownerDocument;m.style.transition="none";let J=te=>{z=Hp(C+R*(te.clientX-h)),m.style.flex=`0 0 ${z}px`,a.setAttribute("aria-valuenow",String(z))},j=()=>{_s=null,V.removeEventListener("pointermove",J),V.removeEventListener("pointerup",j),V.removeEventListener("pointercancel",j),m.style.removeProperty("transition");try{a.releasePointerCapture(c.pointerId)}catch{}Ay(z)};_s=j,V.addEventListener("pointermove",J),V.addEventListener("pointerup",j),V.addEventListener("pointercancel",j);try{a.setPointerCapture(c.pointerId)}catch{}}),a.addEventListener("keydown",c=>{let m=Fs()==="right"?-Sy:Sy,h=Ya(),C=c.key==="ArrowRight"?h+m:c.key==="ArrowLeft"?h-m:c.key==="Home"?Pp:c.key==="End"?Lp:null;C!==null&&(c.preventDefault(),Ay(C))}),a},VS=(a,c)=>{if(!LS()||Qa()){_s?.(),Np?.remove();return}let m=Np??qS();Np=m,m.setAttribute("aria-label",Ue.resizeLabel),m.setAttribute("aria-valuenow",String(Ya())),m.nextElementSibling!==c&&a.insertBefore(m,c)};en=()=>{Xe?.view.setRailSide(Fs());let a=Fs()==="right",c=Bo;if(c){let V=_n?_n.getBoundingClientRect().bottom-K.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(V))}px + ${Il})`,c.style.width=`${Ya()}px`,c.style.left=a?"":Il,c.style.right=a?Il:""}let m=Os,h=Ga,C=Ka;if(!m||!h||!C)return;m.style.flex=`0 0 ${Qa()?PS:Ya()}px`;let R="1px solid var(--persona-divider,#e5e7eb)";m.style.borderRight=a?"":R,m.style.borderLeft=a?R:"";let z=a?C:m;h.firstElementChild!==z&&h.append(z,a?m:C),VS(h,a?m:C)};let zS=a=>{let c=S("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let m=S("div","persona-history-rail-conversation");m.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let h=S("div","persona-history-rail-host");h.style.cssText="display:flex;min-height:0;overflow:hidden",K.insertBefore(c,Se.parentNode===K?Se:G);for(let C of uy())C?.parentNode===K&&m.appendChild(C);c.append(h,m),h.appendChild(a),Ga=c,Os=h,Ka=m,en()},jS=a=>{let c=S("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Il};display:flex;overflow:hidden;z-index:${ra-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,K.style.position="relative",K.appendChild(c),c.appendChild(a),document.addEventListener("pointermove",Op),Bo=c,en(),vy()},_p=()=>{Ll?.(),Bo&&(Kr&&(Dp=Date.now()+150),document.removeEventListener("pointermove",Op),Bo.remove(),Bo=null);let a=Ga;if(a){_s?.();for(let c of uy())c&&a.contains(c)&&K.insertBefore(c,a);a.remove(),Ga=null,Os=null,Ka=null}},My=a=>{$a=a,a.id=Sp,a.style.flex="1 1 auto",a.style.minHeight="0"},Up=a=>{My(a),Qe!=="rail"?kS(a):jt?jS(a):zS(a)},Wl=()=>{if(Fp(),Dy(),!Ye||!Xe)return;let a=Tp();if(a===Qe)return;let c=document.activeElement,m=c instanceof HTMLElement&&(Xe.element.contains(c)||Hn?.contains(c)===!0)?c:null;_p(),Xe.element.remove(),Xe.view.setHeaderPlacement("inline"),Qe=a,Xe.view.setPresentation(a),Xe.view.setCollapsed(Qa()),Xe.requestRender(),Xe.element.isConnected||Up(Xe.element),m?.isConnected?m.focus():Bl(),Ut(),Ho(),or()},Ty=(a,c)=>Hn?.querySelector(c)??a.querySelector(c),Bl=()=>{let a=Xe?.element??$a;if(!a)return;let c=Ty(a,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let m=Ty(a,".persona-history-title")??a;m.tabIndex=-1,m.focus()},ti=async a=>{if(!co()||Ye)return;let c=Ln;if(!c)return;if(!jt&&Za()&&Rp()){Fp();return}Dl();let m=++Ml;Sl=a?.returnSurface??"conversation",vp=a?.invoker??an;let h;try{h=await kg()}catch{kl(Ue.openHistoryLabel);return}if(m!==Ml||Ye)return;wl={scope:Mp()},Qe=Tp(),Ye=!0;let C=Qe==="panel"&&o.layout?.showHeader!==!1&&Se.style.display!=="none"?"external":"inline",R=o.features?.history?.rowAvatar,z=Bp(),V=z?{hint:z.hint,aria:z.aria}:null,J={provider:c,context:wl,targetId:ry(),presentation:Qe,collapsible:Hl(),collapsed:Qa(),railSide:Fs(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:IS(),onToggleCollapse:gy,...V?{collapseShortcut:V}:{},headerPlacement:C,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:R===!1?!1:typeof R=="string"?R:o.launcher?.iconUrl,activeConversationId:F.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:j=>Vp(j,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:j=>Xr(j),attachTooltip:Zt,onStartNew:()=>zp({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:j=>By(j),onRequestClearHistory:()=>JS(),...c.resetDevice?{onRequestResetIdentity:()=>QS()}:{}};Xe=IC({plugins:i,config:o,getPresentation:()=>Qe??"panel",getReturnSurface:()=>Sl,close:()=>xn(),createView:({slots:j,renderDom:te,onModelChange:se,railSections:fe})=>(Gr=h.createHistoryView({...J,railSections:BS(fe),slots:j,renderDom:te,onModelChange:se,onAnnounce:kl}),Gr),onElementChanged:(j,te)=>{if(!te?.isConnected)return Up(j);My(j),te.replaceWith(j),kp()}}),Xe.view.setNewConversationRequired(Al.recovery==="new_conversation_required"),a?.focus!==!1&&(Qe!=="rail"||a?.keyboard===!0)&&Bl(),Ut(),Ho(),or(),g.emit("history:opened",{presentation:Qe,returnSurface:Sl,timestamp:Date.now()})},Dl=()=>{},xn=a=>{if(!Ye)return;Ml+=1;let c=Sl,m=vp,h=Xe,C=a?.restoreFocus!==!1;Ye=!1;let R=!1,z=null,V=()=>{if(!R){if(R=!0,Dl=()=>{},z!==null&&clearTimeout(z),jt=!1,ei(),_p(),h?.dispose(),h?.view.destroy(),h?.element.remove(),Xe===h&&(Xe=null,Gr=null,$a=null,Qe=null,wl=null,vp=null),Ut(),Ho(),or(),C){let j=m??an;j?.isConnected?j.focus():qr()}g.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},J=h&&h.element===h.view.element?h.view.playExit():null;if(!J){V();return}Dl=V,z=setTimeout(V,CS),J.then(V)},Ey=a=>{if(!(a.key!=="Escape"||!Ye||!Xe)){if(Qe==="rail"){let c=a.target;if(!(c instanceof Node)||!(Xe.element.contains(c)||jt&&Wo?.contains(c)===!0))return}a.preventDefault(),a.stopPropagation(),xn()}};K.addEventListener("keydown",Ey),Te.push(()=>K.removeEventListener("keydown",Ey));let Ol=null,ky=!1,ni=()=>{if(!Xo)return;let a=o.layout?.header?.titleSource==="conversation",c=a&&Ol?.trim()||null;Xo.textContent=c??o.launcher?.title??"Chat Assistant";let m=Xo.closest(".persona-combo-btn");if(!m)return;let h=!a||F.getActiveConversationId()!==null;m.setAttribute("data-persona-menu-locked",h?"false":"true"),m.setAttribute("aria-haspopup",h?"true":"false"),h||m.setAttribute("aria-expanded","false"),m.style.cursor=h?"pointer":"default";let C=m.querySelector("svg");C&&(C.style.display=h?"":"none")},$S=a=>{a!==Ol&&(Ol=a,ni())},Xr=a=>{ky=a?.starred===!0,$S(a&&a.title.trim()||null),ni()};ni(),K.addEventListener("persona:title-menu-builtin",a=>{let c=a.detail?.actionId,m=F.getActiveConversationId();m&&(c==="delete"?By(m):c==="star"&&F.canUpdateConversations()&&jp(m,{starred:!ky}).catch(()=>{}))});let Fl=0,GS=250,Nl=null,_l=()=>{Nl&&clearTimeout(Nl),Nl=null};Te.push(_l);let Py=()=>{_l();let a=Vr;a&&(Va=!0,a.hidden=!1,ae.style.display="none",za())},Ul=()=>{Fl+=1,_l(),Vr&&(Vr.remove(),Vr=null,Va=!1,ae.style.removeProperty("display"),Nn(Oe,!1),za())},KS=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ae.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},qp=(a,c)=>ue("div",{className:jn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:a}}),Ly=()=>ue("div",{className:"persona-conversation-loading-body"},qp("58%",!1),qp("72%",!0),qp("44%",!1)),Hy=a=>{Vr?.remove(),Vr=a,a.hidden=!Va,G.insertBefore(a,ae),_l(),Va||(Nl=setTimeout(Py,GS)),Nn(Oe,!0)},XS=()=>{let a={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Ly},c=null,m=i.find(h=>h.renderLoadingIndicator);m?.renderLoadingIndicator&&(c=m.renderLoadingIndicator(a)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(a)),Hy(ue("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ue.openConversationLoadingLabel}},c??Ly()))},YS=a=>{let c=()=>{Vp(a,{focusComposer:!0}).catch(()=>{})},m=co()?()=>{Ul(),ti()}:void 0,h=(V,J)=>{let j=ue("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:V});return j.addEventListener("click",J),j},C=()=>ue("div",{className:"persona-conversation-loading-error-body"},ue("p",{className:"persona-conversation-loading-error-title",text:Ue.openConversationErrorTitle}),ue("div",{className:"persona-conversation-loading-error-actions"},h(Ue.openConversationRetryLabel,c),m?h(Ue.openConversationBackLabel,m):null)),R=Object.freeze({conversationId:a,config:o,copy:Object.freeze({title:Ue.openConversationErrorTitle,retryLabel:Ue.openConversationRetryLabel,backLabel:Ue.openConversationBackLabel}),retry:c,...m?{back:m}:{},defaultRenderer:C}),z=null;for(let V of i)if(V.renderHistoryOpenError){try{z=V.renderHistoryOpenError(R)}catch(J){console.warn("[persona] renderHistoryOpenError threw",J),z=null}if(z)break}Hy(ue("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},z??C())),Py()};g.on("history:closed",()=>{Vr&&Nn(Oe,!0)});let Vp=async(a,{focusComposer:c=!1}={})=>{let m=Ds(),h=!!Xe;Xe?.view.setActiveConversationId(a),Ul();let C=Fl;XS(),Ye&&(Qe==="panel"||jt)&&xn({restoreFocus:!1}),Ps=!0;try{await F.openConversation(a,{scope:m})}catch(R){throw C===Fl&&YS(a),R}finally{Ps=!1}C===Fl&&(Ul(),En.clear(),eo(),bn(),sp()||gl(),KS(),Do(),h||Xr(null),g.emit("history:conversationOpened",{conversationId:a,title:Ol,scope:m,timestamp:Date.now()}),c&&qr())},zp=async({focusComposer:a=!1}={})=>{Ul(),await F.startNewConversation({scope:Ds()}),Xr(null),En.clear(),eo(),bn(),gl(),Do();let c=F.getActiveConversationId();Xe?.view.setActiveConversationId(c),g.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Ye&&(Qe==="panel"||jt)&&xn({restoreFocus:!1}),a&&qr()},jp=async(a,c)=>{let m=await F.updateConversation(a,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return Xe?.view.applyConversationSummary(m),!Xe&&a===F.getActiveConversationId()&&Xr(m),m},Ry=async a=>{let c=Ds(),m=F.getActiveConversationId()===a;await F.deleteConversation(a,{scope:c}),Xe?.view.removeConversationSummary(a),m&&(Xr(null),En.clear(),eo(),bn(),Do()),g.emit("history:conversationDeleted",{conversationId:a,scope:c,wasActive:m,timestamp:Date.now()})},Iy=async a=>{let c=a?.scope??Ds(),m=a?.allTargets?null:a?.targetId??ry(),h=await F.clearConversationHistory({...m?{targetId:m}:{},scope:c});return Xr(null),En.clear(),eo(),bn(),Do(),g.emit("history:cleared",{deleted:h.deleted,scope:c,targetId:m,timestamp:Date.now()}),h},Wy=async()=>{if(!Ln?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let a=!1;try{a=(await F.resetHistoryDevice()).remoteRevocationConfirmed}finally{Xr(null),F.clearArtifacts(),En.clear(),hp=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),E={},$.syncFromMetadata(),v?.clear&&ml(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),eo(),bn(),Do(),xn({restoreFocus:!1}),qr(),I||wt?.launcher.element.focus()}return kl(a?Ue.identityResetNotice:Ue.identityResetUnconfirmedNotice),g.emit("history:identityReset",{remoteRevocationConfirmed:a,timestamp:Date.now()}),{remoteRevocationConfirmed:a}},$p=()=>so?O:K,By=async a=>await Pd({host:$p(),title:Ue.deleteConversationConfirmTitle,description:Ue.deleteConversationConfirm,confirmLabel:Ue.deleteConversationConfirmLabel,cancelLabel:Ue.confirmCancelLabel})?(await Ry(a),"deleted"):"cancelled",JS=async()=>{let a=Ds()==="verified-user";return await Pd({host:$p(),title:Ue.clearHistoryConfirmTitle,description:a?Ue.clearHistoryVerifiedConfirm:Ue.clearHistoryConfirm,confirmLabel:Ue.clearHistoryConfirmLabel,cancelLabel:Ue.confirmCancelLabel})?(await Iy(),"cleared"):"cancelled"},QS=async()=>{if(!await Pd({host:$p(),title:Ue.resetIdentityConfirmTitle,description:Ue.resetIdentityConfirm,confirmLabel:Ue.resetIdentityConfirmLabel,cancelLabel:Ue.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Wy();return{outcome:"reset",remoteRevocationConfirmed:c}},Un=S("button","persona-history-earlier");Un.type="button",Un.textContent=Ue.showEarlierMessagesLabel,Un.setAttribute("data-persona-history-earlier",""),Object.assign(Un.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Do=()=>{if(!(co()&&!!Al.nextMessageCursor&&!!F.getActiveConversationId())){Un.remove();return}Un.textContent=Ue.showEarlierMessagesLabel,Un.parentNode!==G&&G.insertBefore(Un,G.firstChild)};Un.addEventListener("click",()=>{let a=F.getActiveConversationId(),c=Al.nextMessageCursor;if(!a||!c||Un.disabled)return;Un.disabled=!0;let m=G.scrollHeight,h=G.scrollTop;F.loadOlderMessages(a,c,{scope:Ds()}).then(()=>{G.scrollTop=h+(G.scrollHeight-m),Ho()}).catch(()=>{}).finally(()=>{Un.disabled=!1,Do()})});let ZS=()=>{let a=ps({ariaLabel:Ue.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return a.button.addEventListener("click",c=>{if(!(!co()||oy())){if(Ye){xn();return}ti({invoker:a.button,keyboard:c.detail===0})}}),a},Dy=()=>{if(!co()){lo?.remove(),an=null,lo=null;return}if(lo&&!lo.isConnected&&(an=null,lo=null),!an&&Se){let h=ZS();an=h.button,lo=h.wrapper;let C=Q.clearChatButtonWrapper||Q.closeButtonWrapper;C?.parentNode&&Se.contains(C)?C.parentNode.insertBefore(lo,C):Se.appendChild(lo)}if(!an||!lo)return;let a=Za()||Ye&&Qe==="rail";if(lo.style.display=a?"none":"",a){document.activeElement===an&&Bl();return}let c=oy();an.disabled=c,an.setAttribute("aria-disabled",c?"true":"false");let m=c?Ue.openHistoryBusyLabel:Ue.openHistoryLabel;an.setAttribute("aria-label",m),(o.features?.history?.presentation??"panel")==="panel"?(an.removeAttribute("aria-expanded"),an.removeAttribute("aria-controls")):(an.setAttribute("aria-expanded",Ye?"true":"false"),an.setAttribute("aria-controls",Sp))},ql=!1,eA=()=>{let a=Q.clearChatButton;if(a){if(co()){ql||(wp=a.getAttribute("aria-label")??"",ql=!0),a.setAttribute("aria-label",Ue.newConversationLabel),a.removeAttribute("title");return}ql&&(ql=!1,wp&&a.setAttribute("aria-label",wp))}},or=()=>{Ue=Hg(o.features?.history?.copy),Dy(),Fp(),eA(),Do()};Ko=or,wo=a=>{Al=a,Xe?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),qa(a.sendBlocked||Tn),Do()},It=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(En.clear(),eo(),bn()),kl(a.message),Xe?.view.refresh()},ly(),or(),Te.push(()=>{Tl?.(),El?.(),Ml+=1,Dl(),Xe?.dispose(),Xe?.view.destroy(),Xe=null}),o.clientToken&&F.initClientSession().then(()=>{if(co())return F.reconcileBootConversation({scope:Mp()})}).then(()=>{Do()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Me||o.onSSEEvent)&&F.setSSEEventCallback((a,c)=>{o.onSSEEvent?.(a,c),Ke?.processEvent(a,c),Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(c)})});let Oy=()=>{o.resume&&typeof o.reconnectStream=="function"&&F.resumeFromHandle(o.resume)};H?H.then(a=>{if(a){if(a.metadata&&(E=Rg(a.metadata),$.syncFromMetadata()),a.messages?.length){Ps=!0;try{F.hydrateMessages(a.messages)}finally{Ps=!1}}a.artifacts?.length&&F.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{jh=!0,k(),Oy()}):Oy();let Fy=()=>{!ie()||I||!(o.launcher?.composerBar?.expandOnSubmit??!0)||st(!0,"auto")},tA=(a,c)=>a?c?{refs:[...a.refs,...c.refs],finalize:async()=>{let[m,h]=await Promise.allSettled([a.finalize(),c.finalize()]),C=[];return m.status==="fulfilled"?C.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),h.status==="fulfilled"?C.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),dk(C)}}:a:c,nA=()=>{let c=ge.getInlineMessageFields?.();return c&&c.contentSegments.some(h=>h.kind==="mention")?c.contentSegments:void 0},oi=!1,oA=async a=>{let c=ge.value.trim(),m=ut?.hasAttachments()??!1,h=c?await(sn?.takeInlineCommand(c)??Promise.resolve(null)):null;if(h?.kind==="action"){ge.value="",ge.style.height="auto",ri(),sn?.clear();return}let C=sn?.collectForSubmit()??null,R=h?.kind==="server"?h.mentions:null,z=tA(C,R),V=h?.kind==="prompt"?h.sendText:c,J=!!C&&C.refs.length>0;if(!V&&!m&&!J&&!R)return;Fy();let j;m&&(j=[],j.push(...ut.getContentParts()),V&&j.push(ho(V)));let te=h?.kind==="prompt"?void 0:nA();ge.value="",ge.style.height="auto",ri(),F.sendMessage(V,{contentParts:j,mentions:z??void 0,contentSegments:te,viaVoice:a?.viaVoice}),m&&ut.clearAttachments(),C&&sn?.clear()},Gp=async a=>{if(!oi){oi=!0;try{await oA(a)}finally{oi=!1}}},Vl=a=>{if(a.preventDefault(),F.isStreaming()){F.cancel(),Ke?.reset(),rt?.update();return}oi||Gp()},rA=()=>o.features?.composerHistory!==!1,Kp={...Um},Xp=!1,ri=()=>{Kp={...Um}},sA=()=>F.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),aA=a=>{if(!ge)return;Xp=!0,ge.value=a,ge.dispatchEvent(new Event("input",{bubbles:!0})),Xp=!1;let c=ge.value.length;ge.setSelectionRange(c,c)},iA=a=>{Xp||(a.isComposing||sn?.handleInput(a.inputType??void 0),ri())},lA=a=>{if(ge&&!(!a.isComposing&&sn?.handleKeydown(a))){if(rA()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let c=ge.selectionStart===0&&ge.selectionEnd===0,m=mv({direction:a.key==="ArrowUp"?"up":"down",history:sA(),currentValue:ge.value,atStart:c,state:Kp});if(Kp=m.state,m.handled){a.preventDefault(),m.value!==void 0&&aA(m.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(F.isStreaming()){a.preventDefault();return}if(oi){a.preventDefault();return}ri(),a.preventDefault(),he.click()}}},Ny=a=>{a.key!=="Escape"||a.isComposing||F.isStreaming()&&a.composedPath().includes(K)&&(F.cancel(),Ke?.reset(),rt?.update(),ri(),a.preventDefault(),a.stopImmediatePropagation())},cA=async a=>{if(o.attachments?.enabled!==!0||!ut)return;let c=ak(a.clipboardData);c.length!==0&&(a.preventDefault(),await ut.handleFiles(c))},qn=null,po=!1,Us=null,mt=null,_y=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,zl=(a="user")=>{if(po||F.isStreaming())return;let c=_y();if(!c)return;qn=new c;let h=(o.voiceRecognition??{}).pauseDuration??2e3;qn.continuous=!0,qn.interimResults=!0,qn.lang="en-US";let C=ge.value;qn.onresult=R=>{let z="",V="";for(let j=0;j<R.results.length;j++){let te=R.results[j],se=te[0].transcript;te.isFinal?z+=se+" ":V=se}let J=C+z+V;ge.value=J,Us&&clearTimeout(Us),(z||V)&&(Us=window.setTimeout(()=>{ge.value.trim()&&qn&&po&&(rr(),Gp({viaVoice:!0}))},h))},qn.onerror=R=>{R.error!=="no-speech"&&rr()},qn.onend=()=>{if(po){let R=ge.value.trim();R&&R!==C.trim()&&Gp({viaVoice:!0}),rr()}};try{if(qn.start(),po=!0,Fe.active=!0,a!=="system"&&(Fe.manuallyDeactivated=!1),Lo(a),Zn(),oe){let R=o.voiceRecognition??{};mt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:R.iconName??"mic",iconSize:parseFloat(R.iconSize??o.sendButton?.size??"40")||24};let z=R.recordingBackgroundColor,V=R.recordingIconColor,J=R.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let j=oe.querySelector("svg");j&&j.setAttribute("stroke",V)}J&&(oe.style.borderColor=J),oe.setAttribute("aria-label","Stop voice recognition")}}catch{rr("system")}},rr=(a="user")=>{if(po){if(po=!1,Us&&(clearTimeout(Us),Us=null),qn){try{qn.stop()}catch{}qn=null}if(Fe.active=!1,Lo(a),Zn(),oe){if(oe.classList.remove("persona-voice-recording"),mt){oe.style.backgroundColor=mt.backgroundColor,oe.style.color=mt.color,oe.style.borderColor=mt.borderColor;let c=oe.querySelector("svg");c&&c.setAttribute("stroke",mt.color||"currentColor"),mt=null}oe.setAttribute("aria-label","Start voice recognition")}}},dA=(a,c)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),h=a?.provider?.type==="runtype",C=a?.provider?.type==="custom";if(!(m||h||C))return null;let z=S("div","persona-send-button-wrapper"),V=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button";let J=a?.tooltipText??"Start voice recognition";V.setAttribute("aria-label",J);let j=a?.iconName??"mic",te=c?.size??"40px",se=a?.iconSize??te,fe=parseFloat(se)||24,$e=a?.backgroundColor??c?.backgroundColor,gt=a?.iconColor??c?.textColor;V.style.width=se,V.style.height=se,V.style.minWidth=se,V.style.minHeight=se,V.style.fontSize="18px",V.style.lineHeight="1",gt?V.style.color=gt:V.style.color="var(--persona-text, #111827)";let vn=ce(j,fe,gt||"currentColor",1.5);vn?V.appendChild(vn):V.textContent="\u{1F3A4}",$e?V.style.backgroundColor=$e:V.style.backgroundColor="",a?.borderWidth&&(V.style.borderWidth=a.borderWidth,V.style.borderStyle="solid"),a?.borderColor&&(V.style.borderColor=a.borderColor),a?.paddingX&&(V.style.paddingLeft=a.paddingX,V.style.paddingRight=a.paddingX),a?.paddingY&&(V.style.paddingTop=a.paddingY,V.style.paddingBottom=a.paddingY),z.appendChild(V);let At=a?.showTooltip??!1;return Zt({anchor:V,trigger:z,text:()=>V.getAttribute("aria-label")??J,enabled:At}),{micButton:V,micButtonWrapper:z}},Yp=()=>{if(!oe||mt)return;let a=o.voiceRecognition??{};mt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},Jp=(a,c)=>{if(!oe)return;let m=oe.querySelector("svg");m&&m.remove();let h=mt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),C=ce(a,h,c,1.5);C&&oe.appendChild(C)},jl=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},qs=()=>{if(!oe)return;Yp();let a=o.voiceRecognition??{},c=a.recordingBackgroundColor,m=a.recordingIconColor,h=a.recordingBorderColor;if(jl(),oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let C=oe.querySelector("svg");C&&C.setAttribute("stroke",m)}h&&(oe.style.borderColor=h),oe.setAttribute("aria-label","Stop voice recognition")},pA=()=>{if(!oe)return;Yp();let a=o.voiceRecognition??{},c=F.getVoiceInterruptionMode(),m=a.processingIconName??"loader",h=a.processingIconColor??mt?.color??"",C=a.processingBackgroundColor??mt?.backgroundColor??"",R=a.processingBorderColor??mt?.borderColor??"";jl(),oe.classList.add("persona-voice-processing"),oe.style.backgroundColor=C,oe.style.borderColor=R;let z=h||"currentColor";oe.style.color=z,Jp(m,z),oe.setAttribute("aria-label","Processing voice input"),c==="none"&&(oe.style.cursor="default")},uA=()=>{if(!oe)return;Yp();let a=o.voiceRecognition??{},c=F.getVoiceInterruptionMode(),m=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",h=a.speakingIconName??m,C=a.speakingIconColor??(c==="barge-in"?a.recordingIconColor??mt?.color??"":mt?.color??""),R=a.speakingBackgroundColor??(c==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":mt?.backgroundColor??""),z=a.speakingBorderColor??(c==="barge-in"?a.recordingBorderColor??"":mt?.borderColor??"");jl(),oe.classList.add("persona-voice-speaking"),oe.style.backgroundColor=R,oe.style.borderColor=z;let V=C||"currentColor";oe.style.color=V,Jp(h,V);let J=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",J),c==="none"&&(oe.style.cursor="default"),c==="barge-in"&&oe.classList.add("persona-voice-recording")},Oo=()=>{oe&&(jl(),mt&&(oe.style.backgroundColor=mt.backgroundColor??"",oe.style.color=mt.color??"",oe.style.borderColor=mt.borderColor??"",Jp(mt.iconName,mt.color||"currentColor"),mt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},Vs=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=F.getVoiceStatus(),c=F.getVoiceInterruptionMode();if(c==="none"&&(a==="processing"||a==="speaking"))return;if(c==="cancel"&&(a==="processing"||a==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{Fe.active=!1,Fe.manuallyDeactivated=!0,Zn(),Lo("user"),Oo()});return}F.toggleVoice().then(()=>{Fe.active=F.isVoiceActive(),Fe.manuallyDeactivated=!F.isVoiceActive(),Zn(),Lo("user"),F.isVoiceActive()?qs():Oo()});return}if(po){let a=ge.value.trim();Fe.manuallyDeactivated=!0,Zn(),rr("user"),a&&(ge.value="",ge.style.height="auto",F.sendMessage(a))}else Fe.manuallyDeactivated=!1,Zn(),zl("user")};eh=Vs,oe&&(oe.addEventListener("click",Vs),Te.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),Oo()):rr("system"),oe&&oe.removeEventListener("click",Vs)}));let fA=g.on("assistant:complete",()=>{Wh&&(Fe.active||Fe.manuallyDeactivated||Wh==="assistant"&&!Fe.lastUserMessageWasVoice||setTimeout(()=>{!Fe.active&&!Fe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?F.toggleVoice().then(()=>{Fe.active=F.isVoiceActive(),Lo("auto"),F.isVoiceActive()&&qs()}):zl("auto"))},600))});Te.push(fA);let mA=g.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});Te.push(mA);let Uy=()=>{st(!I,"user")},wt=null,ln=null;if(N&&!ie()){let{instance:a,element:c}=fg({config:o,plugins:i,onToggle:Uy});wt=a,a||(ln=c)}wt?e.appendChild(wt.element):ln&&e.appendChild(ln),Ua(),Es(),fp(),up(),qa(F.isStreaming()),sp()||(Mn()==="follow"?er(!0):gl()),Kw(),de&&(!N||ie()?setTimeout(()=>qr(),0):I&&setTimeout(()=>qr(),200));let si=()=>{if(ie()){Pr(),Ua();return}let a=ht(o),c=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,h=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640,R=m.innerWidth<=C,z=h&&R&&N;try{if(z){Lr(),Ra=ll();return}let V=!1;ne&&(ne=!1,Lr(),V=!0);let J=ll();if(!V&&J!==Ra&&(Lr(),V=!0),Ra=J,V&&Gd(),!N&&!a){O.style.height="",O.style.width="";return}if(!c&&!a){let te=o?.launcher?.width??o?.launcherWidth??In;O.style.width=te,O.style.maxWidth=te}il(),xh()}finally{if(Pr(),Ua(),I&&N){let J=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,te=o.launcher?.mobileFullscreen??!0,se=ht(o)&&te&&J,fe=j||te&&J&&N||se;if(fe&&!io){let $e=e.getRootNode(),gt=$e instanceof ShadowRoot?$e.host:e.closest(".persona-host");gt&&!ao&&(ao=Gm(gt,o.launcher?.zIndex??Qt)),io=Km(e.ownerDocument)}else fe||(ao?.(),ao=null,io?.(),io=null)}}};si();let $l=e.ownerDocument.defaultView??window;if($l.addEventListener("resize",si),Te.push(()=>$l.removeEventListener("resize",si)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Pr()});a.observe(Oe),Te.push(()=>a.disconnect());let c=new ResizeObserver(()=>{Wl()});c.observe(K),Te.push(()=>c.disconnect())}$l.addEventListener("resize",Wl),Te.push(()=>$l.removeEventListener("resize",Wl)),Pn=G.scrollTop;let qy=xo(G),Vy=()=>{let a=G.scrollTop,c=xo(G),m=c<qy;if(qy=c,!Yo()){Pn=a,Ut();return}let{action:h,nextLastScrollTop:C}=wv({following:kn.isFollowing(),currentScrollTop:a,lastScrollTop:Pn,nearBottom:cs(G,ko),userScrollThreshold:zw,isAutoScrolling:yn||dl||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Pn=C,h==="resume"){hl()||bn();return}h==="pause"&&Da()};if(G.addEventListener("scroll",Vy,{passive:!0}),Te.push(()=>G.removeEventListener("scroll",Vy)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{tS(),au(ae)});a.observe(ae),a.observe(G),Te.push(()=>a.disconnect())}let zy=()=>{Yo()&&kn.isFollowing()&&hl()&&Da()},jy=G.ownerDocument;jy.addEventListener("selectionchange",zy),Te.push(()=>{jy.removeEventListener("selectionchange",zy)});let gA=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),$y=a=>{gA.has(a.key)&&(Nr(),Xg()&&Yo()&&kn.isFollowing()&&Da())},Gy=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(Nr(),Xg()&&Yo()&&kn.isFollowing()&&Da())};G.addEventListener("keydown",$y),G.addEventListener("focusin",Gy),Te.push(()=>{G.removeEventListener("keydown",$y),G.removeEventListener("focusin",Gy)});let Ky=a=>{if(a.deltaY!==0&&Nr(),!Yo())return;let c=Sv({following:kn.isFollowing(),deltaY:a.deltaY,nearBottom:cs(G,ko),resumeWhenNearBottom:!0});c==="pause"?Da():c==="resume"&&!hl()&&bn()};G.addEventListener("wheel",Ky,{passive:!0}),G.addEventListener("touchmove",Nr,{passive:!0}),G.addEventListener("pointerdown",Nr,{passive:!0}),Te.push(()=>{G.removeEventListener("touchmove",Nr),G.removeEventListener("pointerdown",Nr)}),Te.push(()=>G.removeEventListener("wheel",Ky)),Wt.addEventListener("click",()=>{eo(),G.scrollTop=G.scrollHeight,Pn=G.scrollTop,bn(),er(!0),Ut()}),Te.push(()=>Wt.remove()),Te.push(()=>{Oh(),eo()});let Xy=()=>{Ie&&(Wr&&(Ie.removeEventListener("click",Wr),Wr=null),le()?(Ie.style.display="",Wr=()=>{st(!1,"user")},Ie.addEventListener("click",Wr)):Ie.style.display="none")};Xy(),(()=>{let{clearChatButton:a}=Q;a&&a.addEventListener("click",()=>{if(co()){zp({focusComposer:!0}).catch(m=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",m)});return}F.clearMessages(),En.clear(),bn(),pr(Q.composerOverlay);try{localStorage.removeItem(Sa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Sa}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Sa)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 c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),v?.clear&&ml(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),E={},$.syncFromMetadata(),Me?.clear(),Ke?.reset(),rt?.update()})})(),_e&&_e.addEventListener("submit",Vl);let Yy=[["keydown",lA],["input",iA],["paste",cA],["focus",Dw]],Qp=a=>{if(a)for(let[c,m]of Yy)a.addEventListener(c,m)},Zp=a=>{if(a)for(let[c,m]of Yy)a.removeEventListener(c,m)};Qp(ge);let Jy=()=>{sn?.onComposerSwap((a,c)=>{Zp(c),ge=a,Qp(a)})};Jy();let eu=!1;function hA(){if(!eu){eu=!0;try{let a=ge?.value??"",c=Oe.ownerDocument??document,m=ge?c.activeElement===ge:!1;Zp(ge),_e?.removeEventListener("submit",Vl),oe?.removeEventListener("click",Vs),sn?.destroy(),sn=null;let h=null,C=()=>(h=ie()?bd({config:o}):fs({config:o}),h.footer),R=rh(C)??C();B.replaceComposer(R),Oe=B.composer.footer;let z=h!==null&&R===h.footer;Pa=!z,Kg=z?h.setSendButtonMode:()=>{},oh(Oe),ah(Oe),ih(),lh(),ch(),Jy(),_e&&_e.addEventListener("submit",Vl),Qp(ge),oe?.addEventListener("click",Vs);let V=Ir.indexOf(Eo);Eo.destroy(),Eo=Ui(xt),V>=0&&(Ir[V]=Eo),ge&&(ge.value=a),fp(),Es(),qa(F.isStreaming()),Lr(),Pr(),m&&ge?.focus()}finally{eu=!1}}}let Qy=e.ownerDocument??document;Qy.addEventListener("keydown",Ny,!0);let Zy="persona-attachment-drop-active",ai=0,tu=()=>{ai=0,K.classList.remove(Zy)},zs=()=>o.attachments?.enabled===!0&&ut!==null,eb=a=>{!Bd(a.dataTransfer)||!zs()||(ai++,ai===1&&K.classList.add(Zy))},tb=a=>{!Bd(a.dataTransfer)||!zs()||(ai--,ai<=0&&tu())},nb=a=>{!Bd(a.dataTransfer)||!zs()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},ob=a=>{if(!Bd(a.dataTransfer)||!zs())return;a.preventDefault(),a.stopPropagation(),tu();let c=Array.from(a.dataTransfer.files??[]);c.length!==0&&ut.handleFiles(c)},sr=!0;K.addEventListener("dragenter",eb,sr),K.addEventListener("dragleave",tb,sr),e.addEventListener("dragover",nb,sr),e.addEventListener("drop",ob,sr);let Gl=e.ownerDocument,rb=a=>{zs()&&a.preventDefault()},sb=a=>{zs()&&a.preventDefault()};Gl.addEventListener("dragover",rb),Gl.addEventListener("drop",sb),Te.push(()=>{_e&&_e.removeEventListener("submit",Vl),Zp(ge),Qy.removeEventListener("keydown",Ny,!0),sn?.destroy()}),Te.push(()=>{K.removeEventListener("dragenter",eb,sr),K.removeEventListener("dragleave",tb,sr),e.removeEventListener("dragover",nb,sr),e.removeEventListener("drop",ob,sr),Gl.removeEventListener("dragover",rb),Gl.removeEventListener("drop",sb),tu()}),Te.push(()=>{F.cancel()}),wt?Te.push(()=>{wt?.destroy()}):ln&&Te.push(()=>{ln?.remove()});let St={update(a){let c=o.toolCall,m=o.messageActions,h=o.layout?.messages,C=o.colorScheme,R=o.loadingIndicator,z=o.iterationDisplay,V=o.features?.showReasoning,J=o.features?.showToolCalls,j=o.features?.toolCallDisplay,te=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,fe=o.features?.history?.enabled===!0,$e=o.features?.history?.provider,gt=o.getIdentityProof,$t=o.clientToken;o=Ed({...o,features:s},a),s=o.features,o=Ki(o),r(),Xd(),ss(e,o),$i(e,o),Gi(e,o),en(),To(),o.colorScheme!==C&&vh();let vn=Xi.getForInstance(o.plugins);i.length=0,i.push(...vn),hy(),N=o.launcher?.enabled??!0,X=o.launcher?.autoExpand??!1,we=o.features?.showReasoning??!0,Pe=o.features?.showToolCalls??!0,nt=o.features?.scrollToBottom??{};let At=Mn();Je=o.features?.scrollBehavior??{},At!==Mn()&&(eo(),bn()),Ih(),Zg(),Ut();let kt=Re;if(Re=o.features?.showEventStreamToggle??!1,Re&&!kt){if(Me||(yt=new zi(vt),Me=new Vi(Dn,yt),Ke=Ke??new ji,yt.open().then(()=>Me?.restore()).catch(()=>{}),F.setSSEEventCallback((re,Ne)=>{o.onSSEEvent?.(re,Ne),Ke?.processEvent(re,Ne),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Ne)})})),!je&&Se){let re=o.features?.eventStream?.classNames,Ne="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"+(re?.toggleButton?" "+re.toggleButton:"");je=S("button",Ne),je.style.width="28px",je.style.height="28px",je.style.color=mn.actionIconColor,je.type="button",je.setAttribute("aria-label","Event Stream"),je.title="Event Stream";let ze=ce("activity","18px","currentColor",1.5);ze&&je.appendChild(ze);let dt=Q.clearChatButtonWrapper,Ze=Q.closeButtonWrapper,Yt=dt||Ze;Yt&&Yt.parentNode===Se?Se.insertBefore(je,Yt):Se.appendChild(je),je.addEventListener("click",()=>{Kt?Ss():qd()})}}else!Re&&kt&&(Ss(),je&&(je.remove(),je=null),Me?.clear(),yt?.destroy(),Me=null,yt=null,Ke?.reset(),Ke=null);if(o.launcher?.enabled===!1&&wt&&(wt.destroy(),wt=null),o.launcher?.enabled===!1&&ln&&(ln.remove(),ln=null),o.launcher?.enabled!==!1&&!wt&&!ln){let{instance:re,element:Ne}=fg({config:o,plugins:i,onToggle:Uy});wt=re,re||(ln=Ne),e.appendChild(Ne)}wt&&wt.update(o),ni(),Er&&o.launcher?.subtitle!==void 0&&(Er.textContent=o.launcher.subtitle);let _=o.layout?.header;if(_?.layout!==ye&&Se){let re=_?ga(o,_,{showClose:le(),onClose:()=>st(!1,"user")}):zo({config:o,showClose:le(),onClose:()=>st(!1,"user")});B.replaceHeader(re),Se=B.header.element,Ct=B.header.iconHolder,Xo=B.header.headerTitle,Er=B.header.headerSubtitle,Ie=B.header.closeButton,ye=_?.layout,ni()}else if(_){if(Ct&&(Ct.style.display=_.showIcon===!1?"none":""),Xo&&(Xo.style.display=_.showTitle===!1?"none":""),Er&&(Er.style.display=_.showSubtitle===!1?"none":""),Ie){let re=le()&&_.showCloseButton!==!1;Ie.style.display=re?"":"none"}if(Q.clearChatButtonWrapper){let re=_.showClearChat;if(re!==void 0){Q.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Ne}=Q;Ne&&!Ne.classList.contains("persona-absolute")&&(re?Ne.classList.remove("persona-ml-auto"):Ne.classList.add("persona-ml-auto"))}}}let Le=o.layout?.showHeader!==!1;Se&&(Se.style.display=Le?"":"none");let ve=o.layout?.showFooter!==!1;Oe&&(Oe.style.display=ve?"":"none"),Pr(),Ut(),N!==xe?N?st(X,"auto"):(I=!0,Ua()):X!==me&&st(X,"auto"),me=X,xe=N,si(),Xy();let Gt=JSON.stringify(o.toolCall)!==JSON.stringify(c),at=JSON.stringify(o.messageActions)!==JSON.stringify(m),cn=JSON.stringify(o.layout?.messages)!==JSON.stringify(h),Xt=o.loadingIndicator?.render!==R?.render||o.loadingIndicator?.renderIdle!==R?.renderIdle||o.loadingIndicator?.showBubble!==R?.showBubble,qt=o.iterationDisplay!==z,He=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(te);(Gt||at||cn||Xt||qt||He)&&F&&(Jd++,Oa(ae,F.getMessages(),Ce));let Vt=o.features?.streamAnimation?.type;if(Vt!==se&&Vt&&Vt!=="none"){let re=ua(Vt,o.features?.streamAnimation?.plugins);re&&cd(re,e)}let Ae=o.launcher??{},Bt=Ae.headerIconHidden??!1,ct=o.layout?.header?.showIcon,qe=Bt||ct===!1,Dt=Ae.headerIconName,Pt=Ae.headerIconSize??"48px";if(Ct){let re=Se,Ne=re?.querySelector(".persona-flex-col");if(qe)Ct.style.display="none",re&&Ne&&!re.contains(Ne)&&re.insertBefore(Ne,re.firstChild);else{if(Ct.style.display="",Ct.style.height=Pt,Ct.style.width=Pt,re&&Ne&&(re.contains(Ct)?Ct.nextSibling!==Ne&&(Ct.remove(),re.insertBefore(Ct,Ne)):re.insertBefore(Ct,Ne)),Dt){let dt=parseFloat(Pt)||24,Ze=ce(Dt,dt*.6,"currentColor",1);Ze?Ct.replaceChildren(Ze):Ct.textContent=Ae.agentIconText??"\u{1F4AC}"}else if(Ae.iconUrl){let dt=Ct.querySelector("img");if(dt)dt.src=Ae.iconUrl,dt.style.height=Pt,dt.style.width=Pt;else{let Ze=document.createElement("img");Ze.src=Ae.iconUrl,Ze.alt="",Ze.className="persona-rounded-xl persona-object-cover",Ze.style.height=Pt,Ze.style.width=Pt,Ct.replaceChildren(Ze)}}else{let dt=Ct.querySelector("svg"),Ze=Ct.querySelector("img");(dt||Ze)&&Ct.replaceChildren(),Ct.textContent=Ae.agentIconText??"\u{1F4AC}"}let ze=Ct.querySelector("img");ze&&(ze.style.height=Pt,ze.style.width=Pt)}}let nn=o.layout?.header?.showTitle,zn=o.layout?.header?.showSubtitle;if(Xo&&(Xo.style.display=nn===!1?"none":""),Er&&(Er.style.display=zn===!1?"none":""),Ie){let re=le()&&o.layout?.header?.showCloseButton!==!1;if(Ie.style.display=re?"":"none",!ie()){let Ht=Ae.closeButtonSize??"";Ie.style.height=Ht,Ie.style.width=Ht,Ie.style.minWidth=Ht,Ie.style.minHeight=Ht}let Ne=Ae.closeButtonPlacement??"inline",{closeButtonWrapper:ze}=Q,dt=Ne==="top-right",Ze=ze?.classList.contains("persona-absolute");if(ze&&dt!==Ze)if(ze.remove(),dt){ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Ht=Ka??K;Ht.style.position="relative",Ht.appendChild(ze)}else{let Ht=Ae.clearChat?.placement??"inline",Ft=Ae.clearChat?.enabled??!0;ze.className=Ft&&Ht==="inline"?"":"persona-ml-auto",Se&&Se.appendChild(ze)}if(Ie.style.color=Ae.closeButtonColor||mn.actionIconColor,Ae.closeButtonBackgroundColor?(Ie.style.backgroundColor=Ae.closeButtonBackgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),Ae.closeButtonBorderWidth||Ae.closeButtonBorderColor){let Ht=Ae.closeButtonBorderWidth||"0px",Ft=Ae.closeButtonBorderColor||"transparent";Ie.style.border=`${Ht} solid ${Ft}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");Ae.closeButtonBorderRadius?(Ie.style.borderRadius=Ae.closeButtonBorderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),Ae.closeButtonPaddingX?(Ie.style.paddingLeft=Ae.closeButtonPaddingX,Ie.style.paddingRight=Ae.closeButtonPaddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),Ae.closeButtonPaddingY?(Ie.style.paddingTop=Ae.closeButtonPaddingY,Ie.style.paddingBottom=Ae.closeButtonPaddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom=""),dd(Ie,Ae.closeButtonIconName??"x",{iconSize:ie()?cg:void 0,iconText:Ae.closeButtonIconText??"\xD7"});let Yt=Ae.closeButtonTooltipText??"Close chat",Cn=Ae.closeButtonShowTooltip??!0;Ie.setAttribute("aria-label",Yt),ze&&Zt({anchor:Ie,trigger:ze,text:()=>Ie?.getAttribute("aria-label")??Yt,enabled:Cn})}let{clearChatButton:Ve,clearChatButtonWrapper:on}=Q;if(Ve){let re=Ae.clearChat??{},Ne=re.enabled??!0,ze=o.layout?.header?.showClearChat,dt=ze!==void 0?ze:Ne,Ze=re.placement??"inline";if(on){on.style.display=dt?"":"none";let{closeButtonWrapper:Yt}=Q;!ie()&&Yt&&!Yt.classList.contains("persona-absolute")&&(dt?Yt.classList.remove("persona-ml-auto"):Yt.classList.add("persona-ml-auto"));let Cn=Ze==="top-right",Ht=on.classList.contains("persona-absolute");if(!ie()&&Cn!==Ht&&dt){if(on.remove(),Cn){on.className="persona-absolute persona-top-4 persona-z-50",on.style.right="48px";let Rn=Ka??K;Rn.style.position="relative",Rn.appendChild(on)}else{on.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",on.style.right="";let Rn=Q.closeButtonWrapper;Se&&Rn&&Rn.parentElement===Se?Se.insertBefore(on,Rn):Se&&Se.appendChild(on)}let Ft=Q.closeButtonWrapper;Ft&&!Ft.classList.contains("persona-absolute")&&(Cn?Ft.classList.add("persona-ml-auto"):Ft.classList.remove("persona-ml-auto"))}}if(dt){if(!ie()){let Ft=re.size??"";Ve.style.height=Ft,Ve.style.width=Ft,Ve.style.minWidth=Ft,Ve.style.minHeight=Ft}let Yt=re.iconColor??"";if(Ve.style.color=Yt||mn.actionIconColor,dd(Ve,re.iconName??"refresh-cw",{iconSize:ie()?dg:void 0}),re.backgroundColor?(Ve.style.backgroundColor=re.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let Ft=re.borderWidth||"0px",Rn=re.borderColor||"transparent";Ve.style.border=`${Ft} solid ${Rn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");re.borderRadius?(Ve.style.borderRadius=re.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),re.paddingX?(Ve.style.paddingLeft=re.paddingX,Ve.style.paddingRight=re.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),re.paddingY?(Ve.style.paddingTop=re.paddingY,Ve.style.paddingBottom=re.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Cn=re.tooltipText??"Clear chat",Ht=re.showTooltip??!0;Ve.setAttribute("aria-label",Cn),on&&Zt({anchor:Ve,trigger:on,text:()=>Ve?.getAttribute("aria-label")??Cn,enabled:Ht})}}let Lt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Yi],pn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[vs.message,vs.messageAndClick];$=Ji({parsers:Lt,handlers:pn,getSessionMetadata:L,updateSessionMetadata:P,emit:g.emit,documentRef:typeof document<"u"?document:null}),Ce=UC(o,$,Ee),hS(),F.updateConfig(o),(o.features?.history?.enabled===!0!==fe||o.features?.history?.provider!==$e||o.getIdentityProof!==gt||o.clientToken!==$t)&&(xn({restoreFocus:!1}),ly()),or(),Wl(),Oa(ae,F.getMessages(),Ce),Es(),fp(),mS(),qa(F.isStreaming());let ii=o.voiceRecognition?.enabled===!0,ab=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),li=o.voiceRecognition?.provider?.type==="runtype";if(ii&&(ab||li))if(!oe||!So){let re=dA(o.voiceRecognition,o.sendButton);re&&(oe=re.micButton,So=re.micButtonWrapper,Hw.insertBefore(So,tn),oe.addEventListener("click",Vs),oe.disabled=F.isStreaming())}else{let re=o.voiceRecognition??{},Ne=o.sendButton??{},ze=re.iconName??"mic",dt=Ne.size??"40px",Ze=re.iconSize??dt,Yt=parseFloat(Ze)||24;oe.style.width=Ze,oe.style.height=Ze,oe.style.minWidth=Ze,oe.style.minHeight=Ze;let Cn=re.iconColor??Ne.textColor;oe.innerHTML="";let Ht=ce(ze,Yt,Cn||"currentColor",1.5);Ht?oe.appendChild(Ht):oe.textContent="\u{1F3A4}";let Ft=re.backgroundColor??Ne.backgroundColor;Ft?oe.style.backgroundColor=Ft:oe.style.backgroundColor="",Cn?oe.style.color=Cn:oe.style.color="var(--persona-text, #111827)",re.borderWidth?(oe.style.borderWidth=re.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),re.borderColor?oe.style.borderColor=re.borderColor:oe.style.borderColor="",re.paddingX?(oe.style.paddingLeft=re.paddingX,oe.style.paddingRight=re.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),re.paddingY?(oe.style.paddingTop=re.paddingY,oe.style.paddingBottom=re.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let Rn=re.tooltipText??"Start voice recognition",vA=re.showTooltip??!1;oe.setAttribute("aria-label",Rn),So&&Zt({anchor:oe,trigger:So,text:()=>oe?.getAttribute("aria-label")??Rn,enabled:vA}),So.style.display="",oe.disabled=F.isStreaming()}else oe&&So&&(So.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?F.isVoiceActive()&&F.toggleVoice():po&&rr());if(o.attachments?.enabled===!0){if(!On||!pt){let re=o.attachments??{},ze=(o.sendButton??{}).size??"40px";Yn||(Yn=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Yn.style.display="none",_e.insertBefore(Yn,ge)),Et||(Et=document.createElement("input"),Et.type="file",Et.accept=(re.allowedTypes??qo).join(","),Et.multiple=(re.maxFiles??4)>1,Et.style.display="none",Et.setAttribute("aria-label","Attach files"),_e.insertBefore(Et,ge)),On=S("div","persona-send-button-wrapper"),pt=S("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),pt.type="button",pt.setAttribute("aria-label",re.buttonTooltipText??"Attach file");let dt=re.buttonIconName??"paperclip",Ze=ze,Yt=parseFloat(Ze)||40,Cn=Math.round(Yt*.6);pt.style.width=Ze,pt.style.height=Ze,pt.style.minWidth=Ze,pt.style.minHeight=Ze,pt.style.fontSize="18px",pt.style.lineHeight="1";let Ht=ce(dt,Cn,"currentColor",1.5);Ht?pt.appendChild(Ht):pt.textContent="\u{1F4CE}",pt.addEventListener("click",Rn=>{Rn.preventDefault(),Et?.click()}),On.appendChild(pt);let Ft=re.buttonTooltipText??"Attach file";Zt({anchor:pt,trigger:On,text:()=>pt?.getAttribute("aria-label")??Ft}),ws?ws.append(On):_e.appendChild(On),!ut&&Et&&Yn&&(ut=rs.fromConfig(re),ut.setPreviewsContainer(Yn),Et.addEventListener("change",async()=>{ut&&Et?.files&&(await ut.handleFileSelect(Et.files),Et.value="")}))}else{On.style.display="";let re=o.attachments??{};Et&&(Et.accept=(re.allowedTypes??qo).join(","),Et.multiple=(re.maxFiles??4)>1),ut&&ut.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}if(K.querySelector(".persona-attachment-drop-overlay")?.remove(),K.appendChild(qC(o.attachments?.dropOverlay)),pt){let re=o.attachments??{},Ne=re.buttonTooltipText??"Attach file";pt.setAttribute("aria-label",Ne),pt.textContent="";let ze=parseFloat(o.sendButton?.size??"40px")||40,dt=ce(re.buttonIconName??"paperclip",Math.round(ze*.6),"currentColor",1.5);dt?pt.appendChild(dt):pt.textContent="\u{1F4CE}",On&&Zt({anchor:pt,trigger:On,text:()=>pt?.getAttribute("aria-label")??Ne})}}else On&&(On.style.display="none"),ut&&ut.clearAttachments(),K.querySelector(".persona-attachment-drop-overlay")?.remove();let Ot=o.sendButton??{},nu=Ot.useIcon??!1,Xl=Ot.iconText??"\u2191",Yr=Ot.iconName,Yl=Ot.tooltipText??"Send message",yA=Ot.showTooltip??!1,ci=Ot.size??"40px",Jl=Ot.backgroundColor,di=Ot.textColor;if(nu){if(he.style.width=ci,he.style.height=ci,he.style.minWidth=ci,he.style.minHeight=ci,he.style.fontSize="18px",he.style.lineHeight="1",di?he.style.color=di:he.style.color="var(--persona-button-primary-fg, #ffffff)",!F.isStreaming())if(he.innerHTML="",Yr){let re=parseFloat(ci)||24,Ne=di?.trim()||"currentColor",ze=ce(Yr,re,Ne,2);ze?he.appendChild(ze):he.textContent=Xl}else he.textContent=Xl;he.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Jl?(he.style.backgroundColor=Jl,he.classList.remove("persona-bg-persona-primary")):(he.style.backgroundColor="",he.classList.add("persona-bg-persona-primary"))}else he.textContent=o.copy?.sendButtonLabel??"Send",he.style.width="",he.style.height="",he.style.minWidth="",he.style.minHeight="",he.style.fontSize="",he.style.lineHeight="",he.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Jl?(he.style.backgroundColor=Jl,he.classList.remove("persona-bg-persona-accent")):he.classList.add("persona-bg-persona-accent"),di?he.style.color=di:he.classList.add("persona-text-white");Ot.borderWidth?(he.style.borderWidth=Ot.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),Ot.borderColor?he.style.borderColor=Ot.borderColor:he.style.borderColor="",Ot.paddingX?(he.style.paddingLeft=Ot.paddingX,he.style.paddingRight=Ot.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),Ot.paddingY?(he.style.paddingTop=Ot.paddingY,he.style.paddingBottom=Ot.paddingY):(he.style.paddingTop="",he.style.paddingBottom=""),F.isStreaming()||he.setAttribute("aria-label",Yl),tn&&Zt({anchor:he,trigger:tn,text:()=>he.getAttribute("aria-label")??Yl,enabled:yA});let js=vr(o,ie());Yd(),js?(ae.style.maxWidth=js,ae.style.marginLeft="auto",ae.style.marginRight="auto",ae.style.width="100%",An.style.maxWidth=js,An.style.marginLeft="auto",An.style.marginRight="auto",An.style.width="100%",_e&&(_e.style.maxWidth=js,_e.style.marginLeft="auto",_e.style.marginRight="auto"),xt&&(xt.style.maxWidth=js,xt.style.marginLeft="auto",xt.style.marginRight="auto"),rn.style.maxWidth=js,rn.style.marginLeft="auto",rn.style.marginRight="auto"):(ae.style.maxWidth="",ae.style.marginLeft="",ae.style.marginRight="",ae.style.width="",An.style.maxWidth="",An.style.marginLeft="",An.style.marginRight="",An.style.width="",_e&&(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight=""),xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""),rn.style.maxWidth="",rn.style.marginLeft="",rn.style.marginRight="");let ar=o.statusIndicator??{},bA=ar.visible??!0;if(rn.style.display=bA?"":"none",F){let re=F.getStatus();T(rn,(ze=>ze==="idle"?ar.idleText??Nt.idle:ze==="connecting"?ar.connectingText??Nt.connecting:ze==="connected"?ar.connectedText??Nt.connected:ze==="error"?ar.errorText??Nt.error:Nt[ze])(re),ar,re)}rn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let xA=ar.align==="left"?"persona-text-left":ar.align==="center"?"persona-text-center":"persona-text-right";rn.classList.add(xA),bt()},open(){le()&&st(!0,"api")},close(){le()&&st(!1,"api")},toggle(){le()&&st(!I,"api")},reconnect(){F.reconnectNow()},clearChat(){Mo=!1,F.clearMessages(),En.clear(),bn();try{localStorage.removeItem(Sa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Sa}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Sa)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),v?.clear&&ml(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),E={},$.syncFromMetadata(),Me?.clear(),Ke?.reset(),rt?.update()},setMessage(a){return!ge||F.isStreaming()?!1:(!I&&le()&&st(!0,"system"),ge.value=a,ge.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(F.isStreaming())return!1;let c=a?.trim()||ge.value.trim();return c?(!I&&le()&&st(!0,"system"),ge.value="",ge.style.height="auto",F.sendMessage(c),!0):!1},startVoiceRecognition(){return F.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(F.isVoiceActive()||(!I&&le()&&st(!0,"system"),Fe.manuallyDeactivated=!1,Zn(),F.toggleVoice().then(()=>{Fe.active=F.isVoiceActive(),Lo("user"),F.isVoiceActive()&&qs()})),!0):po?!0:_y()?(!I&&le()&&st(!0,"system"),Fe.manuallyDeactivated=!1,Zn(),zl("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{Fe.active=!1,Fe.manuallyDeactivated=!0,Zn(),Lo("user"),Oo()}),!0):!1:po?(Fe.manuallyDeactivated=!0,Zn(),rr("user"),!0):!1},injectMessage(a){return!I&&le()&&st(!0,"system"),F.injectMessage(a)},injectAssistantMessage(a){!I&&le()&&st(!0,"system");let c=F.injectAssistantMessage(a);return Z&&(Z=!1,pe&&(clearTimeout(pe),pe=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),c},injectUserMessage(a){return!I&&le()&&st(!0,"system"),F.injectUserMessage(a)},injectSystemMessage(a){return!I&&le()&&st(!0,"system"),F.injectSystemMessage(a)},injectMessageBatch(a){return!I&&le()&&st(!0,"system"),F.injectMessageBatch(a)},injectComponentDirective(a){return!I&&le()&&st(!0,"system"),F.injectComponentDirective(a)},injectTestMessage(a){!I&&le()&&st(!0,"system"),F.injectTestEvent(a)},async connectStream(a,c){return F.connectStream(a,c)},__pushEventStreamEvent(a){Me&&(Ke?.processEvent(a.type,a.payload),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!Re||!Me||qd()},hideEventStream(){Kt&&Ss()},isEventStreamVisible(){return Kt},listConversations(a){return F.listConversations(a)},getActiveConversationId(){return F.getActiveConversationId()},openConversation(a,c){return Vp(a,{focusComposer:c?.focus===!0})},startNewConversation(a){return zp({focusComposer:a?.focus===!0})},deleteConversation(a){return Ry(a)},renameConversation(a,c){return jp(a,{title:c})},setConversationStarred(a,c){return jp(a,{starred:c})},clearConversationHistory(a){return Iy(a)},resetHistoryIdentity(){return Wy()},getHistoryIdentityStatus(){return Ln?Ln.getIdentityStatus():Ap()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return ti({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})},hideHistory(a){xn(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return Ye},showArtifacts(){gn(o)&&(Mo=!1,As=!0,To(),De?.setMobileOpen(!0))},hideArtifacts(){gn(o)&&(Mo=!0,To())},upsertArtifact(a){return gn(o)?(go(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(Mo=!1,As=!0),F.upsertArtifact(a)):null},selectArtifact(a){gn(o)&&F.selectArtifact(a)},clearArtifacts(){gn(o)&&F.clearArtifacts()},getArtifacts(){return F?.getArtifacts()??[]},getSelectedArtifactId(){return F?.getSelectedArtifactId()??null},focusInput(){return N&&!I&&!ie()||!ge?!1:(ge.focus(),!0)},async resolveApproval(a,c,m){let C=F.getMessages().find(R=>R.variant==="approval"&&R.approval?.id===a);if(!C?.approval)throw new Error(`Approval not found: ${a}`);if(C.approval.toolType==="webmcp"){F.resolveWebMcpApproval(C.id,c);return}return F.resolveApproval(C.approval,c,m)},setFollowUpSuggestions(a){qw(a)},clearFollowUpSuggestions(){Rh()},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...E}},updatePersistentMetadata(a){P(a)},on(a,c){return g.on(a,c)},off(a,c){g.off(a,c)},isOpen(){return le()&&I},isVoiceActive(){return Fe.active},toggleReadAloud(a){F.toggleReadAloud(a)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(a){return F.getReadAloudState(a)},onReadAloudChange(a){return F.onReadAloudChange(a)},getState(){return{open:le()&&I,launcherEnabled:N,voiceActive:Fe.active,streaming:F.isStreaming()}},showCSATFeedback(a){!I&&le()&&st(!0,"system");let c=ae.querySelector(".persona-feedback-container");c&&c.remove();let m=Id({onSubmit:async(h,C)=>{F.isClientTokenMode()&&await F.submitCSATFeedback(h,C),a?.onSubmit?.(h,C)},onDismiss:a?.onDismiss,...a});ae.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!I&&le()&&st(!0,"system");let c=ae.querySelector(".persona-feedback-container");c&&c.remove();let m=Wd({onSubmit:async(h,C)=>{F.isClientTokenMode()&&await F.submitNPSFeedback(h,C),a?.onSubmit?.(h,C)},onDismiss:a?.onDismiss,...a});ae.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,c){return F.submitCSATFeedback(a,c)},async submitNPSFeedback(a,c){return F.submitNPSFeedback(a,c)},destroy(){yp(),jr!=null&&(clearInterval(jr),jr=null),Te.forEach(a=>a()),W.remove(),Y?.remove(),wt?.destroy(),ln?.remove(),Wr&&Ie.removeEventListener("click",Wr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,c={controller:St,getMessages:St.getMessages,getStatus:St.getStatus,getMetadata:St.getPersistentMetadata,updateMetadata:St.updatePersistentMetadata,clearHistory:()=>St.clearChat(),setVoiceActive:m=>m?St.startVoiceRecognition():St.stopVoiceRecognition()};window.AgentWidgetBrowser=c,Te.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=j=>{let te=j.detail;(!te?.instanceId||te.instanceId===a)&&St.focusInput()};if(window.addEventListener("persona:focusInput",c),Te.push(()=>{window.removeEventListener("persona:focusInput",c)}),Re){let j=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===a)&&St.showEventStream()},te=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===a)&&St.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",te),Te.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",te)})}let m=j=>{let te=j.detail;(!te?.instanceId||te.instanceId===a)&&St.showHistory()},h=j=>{let te=j.detail;(!te?.instanceId||te.instanceId===a)&&St.hideHistory()};window.addEventListener("persona:showHistory",m),window.addEventListener("persona:hideHistory",h),Te.push(()=>{window.removeEventListener("persona:showHistory",m),window.removeEventListener("persona:hideHistory",h)});let C=j=>{let te=j.detail;(!te?.instanceId||te.instanceId===a)&&St.showArtifacts()},R=j=>{let te=j.detail;(!te?.instanceId||te.instanceId===a)&&St.hideArtifacts()},z=j=>{let te=j.detail;te?.instanceId&&te.instanceId!==a||te?.artifact&&St.upsertArtifact(te.artifact)},V=j=>{let te=j.detail;te?.instanceId&&te.instanceId!==a||typeof te?.id=="string"&&St.selectArtifact(te.id)},J=j=>{let te=j.detail;(!te?.instanceId||te.instanceId===a)&&St.clearArtifacts()};window.addEventListener("persona:showArtifacts",C),window.addEventListener("persona:hideArtifacts",R),window.addEventListener("persona:upsertArtifact",z),window.addEventListener("persona:selectArtifact",V),window.addEventListener("persona:clearArtifacts",J),Te.push(()=>{window.removeEventListener("persona:showArtifacts",C),window.removeEventListener("persona:hideArtifacts",R),window.removeEventListener("persona:upsertArtifact",z),window.removeEventListener("persona:selectArtifact",V),window.removeEventListener("persona:clearArtifacts",J)})}let Vn=ik(o.persistState);if(Vn&&le()){let a=lk(Vn.storage),c=`${Vn.keyPrefix}widget-open`,m=`${Vn.keyPrefix}widget-voice`,h=`${Vn.keyPrefix}widget-voice-mode`;if(a){let C=Vn.persist?.openState&&a.getItem(c)==="true",R=Vn.persist?.voiceState&&a.getItem(m)==="true",z=Vn.persist?.voiceState&&a.getItem(h)==="true";if(C&&(wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{St.open(),setTimeout(()=>{if(R||z)St.startVoiceRecognition();else if(Vn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0)),Vn.persist?.openState&&(g.on("widget:opened",()=>{a.setItem(c,"true")}),g.on("widget:closed",()=>{a.setItem(c,"false")})),Vn.persist?.voiceState&&(g.on("voice:state",V=>{a.setItem(m,V.active?"true":"false")}),g.on("user:message",V=>{a.setItem(h,V.viaVoice?"true":"false")})),Vn.clearOnChatClear){let V=()=>{a.removeItem(c),a.removeItem(m),a.removeItem(h)},J=()=>V();window.addEventListener("persona:clear-chat",J),Te.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(x&&le()&&(wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{St.open()},0)),Is(),!Vw){let a=$s(()=>{F&&(Jd++,En.clear(),Oa(ae,F.getMessages(),Ce))});Te.push(a)}return St};var VC=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},pk=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},uk=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},fk=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&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.")},zC=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Dg=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=""},jC=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Dg(e)},Ig=e=>{e.style.transition=""},Wg=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=""},Bg=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Od=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},mk=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},gk=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},hk=e=>{let t=xr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:fn(t,r)??r;return{inset:o(n?.inset,Uc),canvasBackground:o(n?.canvasBackground,qc)}},$C=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},yk=(e,t,n,o,r,s,i,l)=>{let d=Sn(s),u=d.reveal==="push",p=l!=null,f=l?.inset??"",y=l?.canvasBackground??"";mk(e,t,n,o,u),gk(e,t,n,o,d.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=i?"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",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,v=s?.launcher?.mobileBreakpoint??640,E=g!=null?g.innerWidth<=v:!1;if(b&&E&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Wg(t),Ig(o),jC(o),Bg(n),Od(r,o),$C(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.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(s?.launcher?.zIndex??Qt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",u&&(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",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),jC(o),pk(o,d.maxHeight),$C(o,p&&i,f,y),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Wg(t),Ig(o),Bg(n),Od(r,o);let k=d.animate?"transform 180ms ease":"none",M=d.side==="right"?"translateX(100%)":"translateX(-100%)",x=i?"translateX(0)":M;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=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=k,o.style.transform=x,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ig(o),Dg(o),Od(r,o);let k=VC(d.width,e.clientWidth),M=Math.max(0,e.clientWidth),x=d.animate?"margin-left 180ms ease":"none",w=d.side==="right"?i?-k:0:i?0:-k;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=`${M+k}px`,t.style.transition=x,t.style.marginLeft=`${w}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${M}px`,n.style.maxWidth=`${M}px`,n.style.minWidth=`${M}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Wg(t),Dg(o),Bg(n),Od(r,o);let k=d.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let M=i?d.width:"0px",x=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",w=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${M}`,o.style.width=M,o.style.maxWidth=M,o.style.minWidth=M,o.style.minHeight="0",uk(o,d.maxHeight),o.style.overflow=k||w?"hidden":"visible",o.style.transition=x,k){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let L=p?`calc(${VC(d.width,e.clientWidth)}px - (2 * ${f}))`:d.width;r.style.width=L,r.style.minWidth=L,r.style.maxWidth=L,r.style.boxSizing="border-box"}}},bk=(e,t)=>{let n=e.ownerDocument.createElement("div");return zC(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){zC(n,o)},destroy(){n.remove()}}},xk=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,i=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),u=n.createElement("aside"),p=n.createElement("div"),f=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),o.insertBefore(i,e),d.appendChild(e);let y=null,g=()=>{y?.disconnect(),y=null},b=null,v=()=>{b=t?.launcher?.detachedPanel===!0?hk(t):null};v();let E=()=>{yk(i,l,d,u,p,t,f,b)},H=null,k=()=>{H?.(),H=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(H=ia(()=>{v(),E()}))},M=()=>{g(),Sn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{E()}),y.observe(i)))},x=!1,w=()=>{E(),M(),f&&!x&&i.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,fk(i,Sn(t)))},L=i.ownerDocument.defaultView,P=()=>{w()};return L?.addEventListener("resize",P),Sn(t).reveal==="push"?(l.appendChild(d),l.appendChild(u),i.appendChild(l)):(i.appendChild(d),i.appendChild(u)),w(),k(),{mode:"docked",host:p,shell:i,syncWidgetState(D){let q=D.launcherEnabled?D.open:!0;f!==q&&(f=q,w())},updateConfig(D){t=D,(t?.launcher?.enabled??!0)===!1&&(f=!0),v(),w(),k()},destroy(){L?.removeEventListener("resize",P),H?.(),H=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},Zi=(e,t)=>ht(t)?xk(e,t):bk(e,t);var vk=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},GC=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},KC=e=>{let t=vk(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Zi(t,r),i,l=[],d=(E,H)=>{let M=!(H?.launcher?.enabled??!0)||ht(H),x=o.createElement("div");if(x.setAttribute("data-persona-root","true"),M&&(x.style.height="100%",x.style.display="flex",x.style.flexDirection="column",x.style.flex="1",x.style.minHeight="0",x.style.minWidth="0"),n){let w=E.attachShadow({mode:"open"});w.appendChild(x),GC(w,o)}else E.appendChild(x),GC(E,o);return t.id&&x.setAttribute("data-persona-instance",t.id),x},u=()=>{s.syncWidgetState(i.getState())},p=()=>{l.forEach(E=>E()),l=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},f=()=>{let E=d(s.host,r);i=Dd(E,r,{debugTools:e.debugTools}),p()},y=()=>{l.forEach(E=>E()),l=[],i.destroy()};f(),e.onChatReady?.();let g=E=>{y(),s.destroy(),s=Zi(t,E),r=E,f()},b={update(E){let H=Ed(r??{},E),k=ht(r),M=ht(H),x=Mr(r),w=Mr(H);if(k!==M||x!==w){g(H);return}r=H,s.updateConfig(r),i.update(E),u()},destroy(){y(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},v=new Proxy(b,{get(E,H,k){if(H==="host")return s.host;if(H in E)return Reflect.get(E,H,k);let M=i[H];return typeof M=="function"?M.bind(i):M}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=v),v};function Ck(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function wk(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:Ck(o,n)?2:3}function XC(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Fd(e,t){let n=t.trim();if(!n)return[...e].sort(XC);let o=[];for(let r of e){let s=wk(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:XC(r.item,s.item)),o.map(r=>r.item)}function Sk(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function YC(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Fd(e.items,t),resolve:e.resolve}}function JC(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>Fd(t,Sk(r).name),resolve:(r,s)=>{let i=n.get(r.id);return i?i.kind==="server"?{context:(typeof i.data=="function"?i.data(s.args):i.data)??{}}:{insertText:typeof i.prompt=="function"?i.prompt(s.args):i.prompt??""}:{}}}}var nw=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Ak=new Set(["button","a","input","select","textarea","details","summary"]),Mk=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Og=/\b(product|card|item|listing|result)\b/i,Ng=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Tk=3e3,Ek=100;function ow(e){let t=typeof e.className=="string"?e.className:"";if(Og.test(t)||e.id&&Og.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Og.test(o.value))return!0}return!1}function rw(e){return Ng.test((e.textContent??"").trim())}function sw(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function kk(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function QC(e){let t=e.match(Ng);return t?t[0]:null}function ZC(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 o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Pk(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var Lk="commerce-card",Hk="result-card";function ew(e){return!ow(e)||!rw(e)||!sw(e)&&!kk(e)?0:5200}function tw(e){return!ow(e)||rw(e)||!sw(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var _g=[{id:Lk,scoreElement(e){return ew(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Ng.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(ew(e)===0)return null;let{title:n,href:o}=ZC(e),r=QC((e.textContent??"").trim())??QC(t.text)??"",s=Pk(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
144
|
+
`)}},{id:Hk,scoreElement(e){return tw(e)},formatSummary(e,t){if(tw(e)===0)return null;let{title:n,href:o}=ZC(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
145
|
+
`)}}];function Rk(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Ik(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,l=t.mode??"structured",d=t.maxCandidates??Math.max(500,n*10),u=e.rules??_g;return l==="simple"&&e.rules&&e.rules.length>0?(Rk(),u=[]):l==="simple"&&(u=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:u}}function Fg(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Wk=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Bk(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Ak.has(t)||n&&Mk.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function aw(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 Dk(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let i=e.getAttribute("value");i&&(t.value=i);let l=e.getAttribute("name");l&&(t.name=l);let d=e.getAttribute("role");d&&(t.role=d);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Ug(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Fg(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of Wk){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${Fg(s)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(i=>Fg(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let d=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function Ok(e){return e==="static"?Ek:Tk}function iw(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Ug(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:Bk(e),attributes:Dk(e)}}function Fk(e,t,n,o){let r=Ok(t.interactivity),s=null;for(let i of n){let l=i.scoreElement(e,t,o);l>0&&(r+=l,i.formatSummary&&!s&&(s=i))}return{score:r,formattingRule:s}}function Nk(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function _k(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=i.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let u=l,p=u.tagName.toLowerCase();if(nw.has(p)){l=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!aw(u)){l=i.nextNode();continue}let f=iw(u,e.maxTextLength),y=f.text.length>0,g=Object.keys(f.attributes).length>0&&!Object.keys(f.attributes).every(E=>E==="role");if(!y&&!g){l=i.nextNode();continue}if(o.has(f.selector)){l=i.nextNode();continue}o.add(f.selector);let{score:b,formattingRule:v}=Fk(u,f,e.rules,n);r.push({el:u,domIndex:s,enriched:f,score:b,formattingRule:v}),s+=1}l=i.nextNode()}r.sort((u,p)=>{let f=u.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return f!==y?f-y:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let d=[];for(let u of r){if(d.length>=e.maxElements)break;Nk(d,u)||d.push(u)}return d.sort((u,p)=>{let f=u.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return f!==y?f-y:f===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),d.map(u=>{let p;if(u.formattingRule?.formatSummary){let y=u.formattingRule.formatSummary(u.el,u.enriched,n);y&&(p=y)}let f={...u.enriched};return p&&(f.formattedSummary=p),f})}function Uk(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,u=d.tagName.toLowerCase();if(nw.has(u)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!aw(d)){s=r.nextNode();continue}let p=iw(d,e.maxTextLength),f=p.text.length>0,y=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!f&&!y){s=r.nextNode();continue}o.has(p.selector)||(o.add(p.selector),n.push(p))}s=r.nextNode()}let i=[],l=[];for(let d of n)d.interactivity!=="static"?i.push(d):l.push(d);return[...i,...l].slice(0,e.maxElements)}function lw(e={}){let t=Ik(e),n=t.root??document.body;return n?t.mode==="simple"?Uk(t,n):_k(t,n):[]}var Nd=100;function cw(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
|
|
146
|
+
${s.map(i=>`- ${i.split(`
|
|
147
147
|
`).join(`
|
|
148
148
|
`)}`).join(`
|
|
149
|
-
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let
|
|
150
|
-
${
|
|
151
|
-
`)}`)}if(r.navigable.length>0){let
|
|
152
|
-
${
|
|
153
|
-
`)}`)}if(r.input.length>0){let
|
|
154
|
-
${
|
|
155
|
-
`)}`)}if(r.static.length>0){let
|
|
156
|
-
${
|
|
149
|
+
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Nd)}" (clickable)`);o.push(`Interactive elements:
|
|
150
|
+
${s.join(`
|
|
151
|
+
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Nd)}" (navigable)`);o.push(`Navigation links:
|
|
152
|
+
${s.join(`
|
|
153
|
+
`)}`)}if(r.input.length>0){let s=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Nd)}" (input)`);o.push(`Form inputs:
|
|
154
|
+
${s.join(`
|
|
155
|
+
`)}`)}if(r.static.length>0){let s=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Nd)}"`);o.push(`Content:
|
|
156
|
+
${s.join(`
|
|
157
157
|
`)}`)}return o.join(`
|
|
158
158
|
|
|
159
|
-
`)}function
|
|
159
|
+
`)}function dw(){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 pw(){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 uw(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Co(e.colors.primary,.95),100:Co(e.colors.primary,.9),200:Co(e.colors.primary,.8),300:Co(e.colors.primary,.7),400:Co(e.colors.primary,.6),500:e.colors.primary,600:Co(e.colors.primary,.8),700:Co(e.colors.primary,.7),800:Co(e.colors.primary,.6),900:Co(e.colors.primary,.5),950:Co(e.colors.primary,.45)}}),{...t,palette:n}}}}function fw(){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 mw(){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 Co(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),i=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function gw(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var qk={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"}}},hw={components:{panel:{borderRadius:"0",shadow:"none"}}},qg={id:"shop",label:"Shopping Assistant",config:{theme:qk,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:In},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Vg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:hw}},zg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:hw}},jg={shop:qg,minimal:Vg,fullscreen:zg};function yw(e){return jg[e]}var Vk=`
|
|
160
160
|
@keyframes persona-stream-wipe {
|
|
161
161
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
162
162
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -192,7 +192,7 @@ ${a.join(`
|
|
|
192
192
|
mask-image: none !important;
|
|
193
193
|
}
|
|
194
194
|
}
|
|
195
|
-
`.trim(),
|
|
195
|
+
`.trim(),zk={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:Vk};ds(zk);var jk=`
|
|
196
196
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
197
197
|
animation: persona-stream-glyph-cycle-fade
|
|
198
198
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -210,7 +210,7 @@ ${a.join(`
|
|
|
210
210
|
opacity: 1 !important;
|
|
211
211
|
}
|
|
212
212
|
}
|
|
213
|
-
`.trim(),
|
|
213
|
+
`.trim(),el="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",$k=10,Gk=120,$g=120,Kk=.4,Xk=50,Yk=e=>{if(!e)return $g;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):$g},Mw=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=Yk(t);return Gk*n/$g},Gg=e=>{let t=el[Math.floor(Math.random()*el.length)];return e&&t===e&&(t=el[(el.indexOf(t)+1)%el.length]),t},Jk=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<Kk&&(r.textContent=Gg())}},bw=new WeakMap,xw=25,vw=.5,Qk=6,Cw=.25,ww=new WeakMap,Sw=new WeakMap,Zk=(e,t)=>{if(!e)return xw*vw;let n=ww.get(e);ww.set(e,t);let o=Sw.get(e)??xw;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-Cw)+r*Cw,Sw.set(e,o))}return Math.max(Qk,o*vw)},Aa=new Map,eP=e=>e.closest("[data-message-id]")?.dataset.messageId??null,tP=e=>{e&&Aa.set(e,(Aa.get(e)??0)+1)},nP=e=>{if(!e)return;let t=Aa.get(e)??0;t<=1?Aa.delete(e):Aa.set(e,t-1)},Tw=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=Gg();let n=eP(e);n&&(e.dataset.glyphCycleMessageId=n),tP(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=Zk(o,r),i=Mw(e),l=$k*i,d=r+l;if(o){let u=bw.get(o);u!==void 0&&(d=Math.max(d,u)),bw.set(o,d+s)}oP(e,t,d)},oP=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=Mw(e),r=e.textContent??void 0,s=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,nP(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let i=Gg(r);e.textContent=i,r=i,Jk(e),setTimeout(s,o)};setTimeout(s,o)},Aw=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))Tw(n)},rP=e=>e.nodeType===1,sP={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:jk,bufferContent(e){if(e.length<Xk)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(Aa.get(e.id)??0)>0},onAttach(e){Aw(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))rP(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?Tw(r):Aw(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ds(sP);var Rt=typeof document<"u"?document.currentScript?.src??null:null;Eb(()=>{let e=Rt?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Rt?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Rt??"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)});pb(()=>{let e=Rt?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Rt?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Rt??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});pi().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});wx(()=>{let e=Rt?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Rt?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Rt??"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)});Ox(()=>{let e=Rt?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===Rt?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${Rt??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});Fx(()=>{let e=Rt?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===Rt?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${Rt??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});LC(()=>{let e=Rt?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===Rt?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${Rt??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});dC(()=>{let e=Rt?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===Rt?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${Rt??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return EA(aP);})();
|
|
214
214
|
/*! Bundled license information:
|
|
215
215
|
|
|
216
216
|
lucide/dist/esm/icons/activity.mjs:
|
|
@@ -287,6 +287,7 @@ lucide/dist/esm/icons/minus.mjs:
|
|
|
287
287
|
lucide/dist/esm/icons/monitor.mjs:
|
|
288
288
|
lucide/dist/esm/icons/moon.mjs:
|
|
289
289
|
lucide/dist/esm/icons/package.mjs:
|
|
290
|
+
lucide/dist/esm/icons/panel-left.mjs:
|
|
290
291
|
lucide/dist/esm/icons/paperclip.mjs:
|
|
291
292
|
lucide/dist/esm/icons/pause.mjs:
|
|
292
293
|
lucide/dist/esm/icons/pen-line.mjs:
|