@runtypelabs/persona 4.26.0 → 4.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approval-ui.d.cts +6 -0
- package/dist/approval-ui.d.ts +6 -0
- package/dist/artifacts-ui.d.cts +6 -0
- package/dist/artifacts-ui.d.ts +6 -0
- package/dist/chunk-GKPCIQPB.js +1 -0
- package/dist/{client-history-YPEG45Q4.js → client-history-GOZWBDA5.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +6 -0
- package/dist/context-mentions.d.ts +6 -0
- package/dist/event-stream-view.d.cts +6 -0
- package/dist/event-stream-view.d.ts +6 -0
- package/dist/forms-ui.d.cts +6 -0
- package/dist/forms-ui.d.ts +6 -0
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +6 -0
- package/dist/session-reconnect.d.ts +6 -0
- package/dist/smart-dom-reader.d.cts +6 -0
- package/dist/smart-dom-reader.d.ts +6 -0
- package/dist/theme-editor-preview.cjs +14 -14
- package/dist/theme-editor-preview.d.cts +6 -0
- package/dist/theme-editor-preview.d.ts +6 -0
- package/dist/theme-editor-preview.js +5 -5
- package/dist/theme-editor.d.cts +6 -0
- package/dist/theme-editor.d.ts +6 -0
- package/dist/voice-runtime-XLU6YK2N.js +17 -0
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +6 -0
- package/dist/voice-runtime.d.ts +6 -0
- package/dist/voice-runtime.js +3 -3
- package/package.json +1 -1
- package/src/approval-paused-tool-settle.test.ts +108 -4
- package/src/session.ts +51 -10
- package/src/session.voice.test.ts +1 -0
- package/src/types.ts +6 -0
- package/src/voice/runtype-voice-provider.ts +19 -9
- package/src/voice/voice-delegation.ts +1 -1
- package/src/voice/voice.test.ts +81 -2
- package/dist/chunk-QPPJUSZH.js +0 -1
- package/dist/voice-runtime-UOQOFAFY.js +0 -17
package/dist/index.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var e,t=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,i=(e=function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof require<"u"?require:typeof Proxy<"u"&&new Proxy(e,{get:(e,t)=>(typeof require<"u"?require:e)[t]}),(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports)),l=(e,t,a,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of o(t))!s.call(e,l)&&l!==a&&r(e,l,{get:()=>t[l],enumerable:!(i=n(t,l))||i.enumerable});return e},d=(e,n,o)=>(o=null!=e?t(a(e)):{},l(!n&&e&&e.__esModule?o:r(o,"default",{value:e,enumerable:!0}),e)),c=i(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}),p=i(e=>{var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"!==n&&!Object.prototype.hasOwnProperty.call(r,n)&&t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var n=c();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),r(c(),e);var o=class extends Error{};e.PartialJSON=o;var a=class extends Error{};function s(e,t=n.Allow.ALL){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return i(e.trim(),t)}e.MalformedJSON=a,e.parseJSON=s;var i=(e,t)=>{let r=e.length,s=0,i=e=>{throw new o(`${e} at position ${s}`)},l=e=>{throw new a(`${e} at position ${s}`)},d=()=>(m(),s>=r&&i("Unexpected end of input"),'"'===e[s]?c():"{"===e[s]?p():"["===e[s]?u():"null"===e.substring(s,s+4)||n.Allow.NULL&t&&r-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||n.Allow.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||n.Allow.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||n.Allow.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||n.Allow._INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||n.Allow.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):h()),c=()=>{let o=s,a=!1;for(s++;s<r&&('"'!==e[s]||a&&"\\"===e[s-1]);)a="\\"===e[s]&&!a,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(o,++s-Number(a)))}catch(e){l(String(e))}else if(n.Allow.STR&t)try{return JSON.parse(e.substring(o,s-Number(a))+'"')}catch{return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{s++,m();let o={};try{for(;"}"!==e[s];){if(m(),s>=r&&n.Allow.OBJ&t)return o;let a=c();m(),s++;try{let e=d();o[a]=e}catch(e){if(n.Allow.OBJ&t)return o;throw e}m(),","===e[s]&&s++}}catch{if(n.Allow.OBJ&t)return o;i("Expected '}' at end of object")}return s++,o},u=()=>{s++;let r=[];try{for(;"]"!==e[s];)r.push(d()),m(),","===e[s]&&s++}catch{if(n.Allow.ARR&t)return r;i("Expected ']' at end of array")}return s++,r},h=()=>{if(0===s){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(n.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let o=s;for("-"===e[s]&&s++;e[s]&&-1===",]}".indexOf(e[s]);)s++;s==r&&!(n.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(o,s))}catch{"-"===e.substring(o,s)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(e){l(String(e))}}},m=()=>{for(;s<r&&" \n\r\t".includes(e[s]);)s++};return d()},l=s;e.parse=l}),u={};((e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})})(u,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Sr,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Cr,ASK_USER_QUESTION_TOOL_NAME:()=>zt,AgentWidgetClient:()=>vn,AgentWidgetSession:()=>uo,AttachmentManager:()=>fo,BrowserSpeechEngine:()=>Vn,DEFAULT_COMPONENTS:()=>Qa,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>_,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>j,DEFAULT_PALETTE:()=>Ua,DEFAULT_SEMANTIC:()=>Ga,DEFAULT_WIDGET_CONFIG:()=>ee,HistoryProviderError:()=>wn,PRESETS:()=>jp,PRESET_FULLSCREEN:()=>qp,PRESET_MINIMAL:()=>zp,PRESET_SHOP:()=>Fp,ReadAloudController:()=>Un,SUGGEST_REPLIES_CLIENT_TOOL:()=>fr,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>gr,SUGGEST_REPLIES_TOOL_NAME:()=>mr,THEME_ZONES:()=>us,VERSION:()=>qr,WEBMCP_TOOL_PREFIX:()=>St,applyFeaturePreferences:()=>Gd,applyThemeVariables:()=>Cs,attachHeaderToContainer:()=>Oi,buildComposer:()=>Xi,buildDefaultHeader:()=>Ui,buildHeader:()=>Di,buildHeaderWithLayout:()=>Yi,buildMinimalHeader:()=>Ki,builtInClientToolsForDispatch:()=>kr,canonicalArtifactDisplayMode:()=>$n,collectEnrichedPageContext:()=>$p,componentRegistry:()=>sd,createActionManager:()=>mc,createAgentExperience:()=>Xc,createAskUserQuestionBubble:()=>pr,createBubbleWithLayout:()=>pl,createCSATFeedback:()=>Fc,createComboButton:()=>Vi,createComponentMiddleware:()=>Hc,createComponentStreamParser:()=>Bc,createDefaultSanitizer:()=>ot,createDirectivePostprocessor:()=>et,createDropdownMenu:()=>Fi,createFlexibleJsonStreamParser:()=>Fr,createIconButton:()=>zi,createImagePart:()=>en,createJsonStreamParser:()=>Or,createLabelButton:()=>qi,createLocalStorageAdapter:()=>yc,createMarkdownProcessor:()=>Ue,createMarkdownProcessorFromConfig:()=>Ke,createMessageActions:()=>dl,createNPSFeedback:()=>zc,createPlainTextParser:()=>Wr,createRegexJsonParser:()=>Dr,createSplitButton:()=>_i,createStandardBubble:()=>cl,createTextPart:()=>Zr,createTheme:()=>as,createThemeObserver:()=>Ss,createToggleGroup:()=>ji,createTypingIndicator:()=>tl,createWidgetHostLayout:()=>ip,createXmlParser:()=>zr,defaultActionHandlers:()=>uc,defaultJsonActionParser:()=>cc,defaultParseRules:()=>Mp,detectColorScheme:()=>vs,directivePostprocessor:()=>tt,ensureAskUserQuestionSheet:()=>ur,escapeHtml:()=>Ye,extractComponentDirectiveFromMessage:()=>Dc,fileToImagePart:()=>tn,formatEnrichedContext:()=>Dp,generateAssistantMessageId:()=>Ot,generateMessageId:()=>Wt,generateStableSelector:()=>Bp,generateUserMessageId:()=>Dt,getActiveTheme:()=>xs,getAgentWidgetHandles:()=>cp,getColorScheme:()=>ws,getDisplayText:()=>Yr,getHeaderLayout:()=>Gi,getImageParts:()=>Qr,getPreset:()=>_p,hasComponentDirective:()=>Wc,hasImages:()=>Xr,headerLayouts:()=>Ji,initAgentWidget:()=>pp,isAskUserQuestionMessage:()=>Qt,isComponentDirectiveType:()=>Nc,isDockedMountMode:()=>vi,isHistoryProviderError:()=>xn,isSuggestRepliesMessage:()=>yr,isWebMcpToolName:()=>Lt,isWelcomeVisible:()=>kl,latestAgentSuggestions:()=>vr,listRegisteredStreamAnimations:()=>Ys,loadMarkdownParsers:()=>je,markdownPostprocessor:()=>Ge,mergeWithDefaults:()=>re,normalizeContent:()=>Gr,normalizeMediaType:()=>Wn,onMarkdownParsersReady:()=>_e,parseAskUserQuestionPayload:()=>er,parseSuggestRepliesPayload:()=>br,parseWidgetPreferenceSlice:()=>Vd,pickBestVoice:()=>_n,pluginRegistry:()=>ac,registerIcons:()=>ve,registerStreamAnimationPlugin:()=>Js,removeAskUserQuestionSheet:()=>hr,renderComponentDirective:()=>Rc,renderLoadingIndicatorWithFallback:()=>rl,renderLucideIcon:()=>xe,resolveArtifactDisplay:()=>Dn,resolveArtifactDisplayMode:()=>On,resolveConfigPreferences:()=>Yd,resolveDockConfig:()=>xi,resolveSanitizer:()=>at,resolveTokens:()=>ts,resolveWelcomeConfig:()=>Sl,stripWebMcpPrefix:()=>Et,themeToCssVariables:()=>ps,unregisterStreamAnimationPlugin:()=>Gs,validateImageFile:()=>rn,validateTheme:()=>rs});var h=[["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"}]],m=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]],g=[["path",{d:"M20 6 9 17l-5-5"}]],f=[["path",{d:"m6 9 6 6 6-6"}]],y=[["path",{d:"m18 15-6-6-6 6"}]],b=[["circle",{cx:"12",cy:"12",r:"10"}]],v=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]],w=[["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"}]],x=[["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"}]],C=[["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"}]],S=[["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"}]],k=[["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"}]],A=[["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"}]],M=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]],I=(e,t=24,r="currentColor",n=2)=>{if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],r=e[1];if(!r)return;let n=document.createElementNS("http://www.w3.org/2000/svg",t);Object.entries(r).forEach(([e,t])=>{"stroke"!==e&&n.setAttribute(e,String(t))}),o.appendChild(n)}),o},T=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function E(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];T(t)&&T(n)?r[e]=E(t,n):r[e]=n}return r}var L=Symbol("persona.defaultsProvenance"),P=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function B(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let n=t?`${t}.${e}`:e;return P(r)?B(r,n):[n]})}function N(e,t){for(let r of t.split(".")){if(!P(e)||!Object.prototype.hasOwnProperty.call(e,r))return"absent";if(void 0===(e=e[r]))return"clear"}return"explicit"}function R(e,t){return e?.[L]??t.filter(t=>"explicit"===N(e,t))}function H(e,t){return Object.defineProperty(e,L,{value:t,enumerable:!0,configurable:!0}),e}function $(e,t,r){return H(e,R(t,B(r)))}var W=Symbol("persona.panelAliasProvenance"),D=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),O=(e,t)=>D(e,t)&&void 0!==e[t],F=e=>{let t=e?.[W];return t?{...t}:(e=>({launcherWidth:O(e?.launcher,"width"),legacyLauncherWidth:O(e,"launcherWidth"),sidebarWidth:O(e?.launcher,"sidebarWidth"),dockWidth:O(e?.launcher?.dock,"width")}))(e)},z=(e,t)=>(Object.defineProperty(e,W,{value:t,enumerable:!0,configurable:!0}),e),q=(e,t)=>z(e,F(t)),j="min(440px, calc(100vw - 24px))",_="440px",V="40px",U="How can I help...",K={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},J={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},G={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:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"💬",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:j,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:V,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)"},copy:{inputPlaceholder:U,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"↑",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting…",connectedText:"Streaming…",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",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:K,reasoningDisplay:J,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other…",freeTextPlaceholder:"Type your answer…",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},Y={},X={launcher:{variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function Q(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function Z(e){let t="v5"===Q(e)?X:Y;return E(G,t)}var ee=Z();function te(e,t){if(e||t)return e?t?E(e,t):e:t}function re(e){let t=Z(e);return e?$(q({...t,...e,theme:te(t.theme,e.theme),darkTheme:te(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let r=t.features?.artifacts,n=e.features?.artifacts,o=t.features?.scrollToBottom,a=e.features?.scrollToBottom,s=t.features?.scrollBehavior,i=e.features?.scrollBehavior,l=t.features?.streamAnimation,d=e.features?.streamAnimation,c=t.features?.askUserQuestion,p=e.features?.askUserQuestion,u=t.features?.history,h=e.features?.history,m=void 0===r&&void 0===n?void 0:{...r,...n,layout:{...r?.layout,...n?.layout}},g=void 0===o&&void 0===a?void 0:{...o,...a},f=void 0===s&&void 0===i?void 0:{...s,...i},y=void 0===l&&void 0===d?void 0:{...l,...d},b=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},v=void 0===u&&void 0===h?void 0:{...u,...h,copy:{...u?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...void 0!==g?{scrollToBottom:g}:{},...void 0!==f?{scrollBehavior:f}:{},...void 0!==m?{artifacts:m}:{},...void 0!==y?{streamAnimation:y}:{},...void 0!==b?{askUserQuestion:b}:{},...void 0!==v?{history:v}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,X):$(q(t),void 0,X)}var ne=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},oe=(e,t={},...r)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),void 0!==t.text&&(n.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);if(t.style){let e=n.style,r=t.style;for(let t of Object.keys(r)){let n=r[t];null!=n&&(e[t]=n)}}let o=r.filter(e=>null!=e);return o.length>0&&n.append(...o),n},ae=(...e)=>e.filter(Boolean).join(" "),se=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,n=null,o=null,a=null;return{setLoader:e=>{n=e,r&&(o=null,a=null)},load:()=>o?Promise.resolve(o):a||(a=(n??t)().then(e=>(o=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{o=e},getSync:()=>o}},{setLoader:ie,load:le}=se({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),de=ie,ce=le,pe={activity:h,"arrow-down":[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]],"arrow-up":[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]],"arrow-up-right":[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]],bot:[["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"}]],"chevron-down":f,"chevron-up":y,"chevron-right":[["path",{d:"m9 18 6-6-6-6"}]],"chevron-left":[["path",{d:"m15 18-6-6 6-6"}]],check:g,clipboard:[["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"}]],"clipboard-copy":[["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"}]],"code-xml":[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]],copy:w,file:k,"file-code":x,"file-spreadsheet":C,"file-text":S,"image-plus":[["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"}]],loader:[["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"}]],"loader-circle":[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]],mic:[["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"}]],paperclip:[["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"}]],quote:[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]],"refresh-cw":[["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"}]],search:[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]],send:[["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"}]],"shield-alert":[["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"}]],"shield-check":[["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"}]],"shield-x":[["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"}]],square:[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]],"thumbs-down":[["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"}]],"thumbs-up":[["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"}]],upload:[["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"}]],"volume-2":[["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"}]],x:M,"at-sign":[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]],"arrow-left":[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]],"arrow-right":m,"external-link":[["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"}]],ellipsis:[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]],"ellipsis-vertical":[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]],menu:[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]],"panel-left":[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]],plus:[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]],minus:[["path",{d:"M5 12h14"}]],pencil:[["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"}]],trash:[["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"}]],"trash-2":[["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"}]],download:[["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"}]],maximize:[["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"}]],minimize:[["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"}]],"message-square":A,star:[["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"}]],eye:[["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"}]],history:[["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"}]]},ue=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],he=new Map(Object.entries(pe)),me=new Set,ge=!1,fe=new Set,ye=e=>{let t=[...fe];e&&fe.clear();for(let e of t)try{e()}catch{}},be=()=>{let e=0;for(let t of[...me]){let r=he.get(t.name);if(!r)continue;me.delete(t),e++;let n=I(r,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},ve=e=>{for(let[t,r]of Object.entries(e))he.set(t,r);be()>0&&!ge&&ye(!1)},we=!1,xe=(e,t=24,r="currentColor",n=2)=>{let o=he.get(e);if(o)return I(o,t,r,n);if(ue.includes(e)){we&&(we=!1);let o=((e,t,r)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(r)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n})(t,r,n);if(me.size>=500){let e=me.values().next().value;e&&me.delete(e)}return me.add({el:o,name:e,size:t,color:r,strokeWidth:n}),ce().then(e=>{if(!ge){for(let[t,r]of Object.entries(e.EXTRA_LUCIDE_ICONS))he.has(t)||he.set(t,r);ge=!0,be(),ye(!0)}}).catch(e=>{we=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)}),o}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null},Ce=["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"],Se=(e,t)=>{let r=ne("div",["persona-message-bubble",e,...Ce].join(" "));return r.id=`bubble-${t}`,r.setAttribute("data-message-id",t),r},ke=e=>{let t=ne("button",e.expandable?"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");return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},Ae=(e,t,r)=>{e.innerHTML="";let n=I(t?y:f,16,r,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Me=(e,t,r)=>{if(!r.expandable)return e.append(t),null;let n=ne("div","persona-flex persona-items-center");Ae(n,r.expanded,r.iconColor);let o=ne("div",r.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return o.append(n),e.append(t,o),n},Ie=e=>{let t=ne("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let r=e.renderPreview?.();((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(t,r)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Te=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Ae(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Ee=(e,t,r)=>{let n=r.stateSet.has(e),o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),s=t.querySelector(`[data-persona-collapsed-preview="${r.previewKind}"]`);if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");i&&Ae(i,n,r.iconColor),a.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")};function Le(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[r]:{..."tool"===t?K:J,...!0===e?.future?.v5Defaults?X.features?.[r]:{},...e?.features?.[r]}}}}function Pe(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return e?.features?.[r]?.variant??(e?.future?.v5Defaults?"row":"card")}function Be(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Ne(e,t,r,n){if("row"!==Pe(r,n))return e;e.className=`persona-message-bubble persona-${n}-bubble persona-activity-row`,e.dataset.activityKind=n,"tool"===n&&void 0===r.toolCall?.shadow&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let o=e.querySelector(":scope > button");if(!o)return e;o.className="persona-activity-header";let a="tool"===n?t.toolCall:t.reasoning,s="complete"!==a?.status,i=t.approval?.status??t.toolCall?.approvalStatus,l="denied"===i?"denied":"pending"===i?"awaiting-approval":!1===t.toolCall?.success?"error":s?"pending"===a?.status?"pending":"running":"done";e.dataset.activityState=l;let d=ne("span","persona-activity-icon");d.dataset.activityIcon=l;let c="reasoning"===n?r.features?.reasoningDisplay?.iconName:void 0,p=c?xe(c,16,"currentColor",2):"pending"===l?I(b,16,"currentColor",2):"awaiting-approval"===l?I(v,16,"currentColor",2):xe({pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"}[l],16,"currentColor",2);p&&d.appendChild(p),o.querySelector(".persona-reasoning-header-icon")?.remove();let u="tool"===n?"toolCallDisplay":"reasoningDisplay",h=r.features?.[u]?.iconVisibility??(r.future?.v5Defaults?"active":"always");if(("always"===h||"active"===h&&"done"!==l)&&o.prepend(d),"tool"===n&&a){let e=ne("span","persona-activity-duration");s&&a.startedAt&&e.setAttribute("data-tool-elapsed",String(a.startedAt));let r=("tool"===n?t.toolCall?.duration:void 0)??a.durationMs??(void 0!==a.completedAt&&void 0!==a.startedAt?a.completedAt-a.startedAt:void 0);e.textContent=void 0===r?"":Be(r),o.appendChild(e)}o.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),o.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let m=e.querySelector(":scope > .persona-border-t");return m?.classList.add("persona-activity-body"),m&&(m.id=`activity-details-${t.id}`,o.setAttribute("aria-controls",m.id)),e}var Re=(e,t,r)=>{let n="transient"===t.mode,o=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=((e,t)=>!1!==e.visible&&("transient"!==e.mode||"connecting"===t||"paused"===t||"resuming"===t||"error"===t))(t,r)||n&&o&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!n),e.classList.toggle("persona-mb-2",n)},He=(e,t,r)=>{!t.parentElement||e.parentElement!==t.parentElement||("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function $e(e){return"runtype"===e?.type||"custom"===e?.type}var{setLoader:We,load:De,provide:Oe,getSync:Fe}=se({fallbackImport:()=>import("./markdown-parsers-entry")}),ze=new Set,qe=We,je=()=>{let e=Fe();return e?Promise.resolve(e):De().then(e=>((()=>{let e=[...ze];ze.clear();for(let t of e)try{t()}catch{}})(),e))},_e=e=>Fe()?()=>{}:(ze.add(e),()=>{ze.delete(e)}),Ve=Fe,Ue=e=>{let t=null;return r=>{let n=Ve();if(!n)return Ye(r);if(!t){let{Marked:r}=n,o=e?.markedOptions;t=new r({gfm:o?.gfm??!0,breaks:o?.breaks??!0,pedantic:o?.pedantic,silent:o?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,n)=>e({type:"heading",raw:n,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,n)=>e({type:"code",raw:"",text:t,lang:r,escaped:n})}if(r.blockquote){let e=r.blockquote;t.blockquote=t=>e({type:"blockquote",raw:"",text:t,tokens:[]})}if(r.table){let e=r.table;t.table=(t,r)=>e({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:t,bodyHtml:r})}if(r.link){let e=r.link;t.link=(t,r,n)=>e({type:"link",raw:"",href:t,title:r??null,text:n,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,n)=>e({type:"image",raw:"",href:t,title:r??null,text:n})}if(r.list){let e=r.list;t.list=(t,r,n)=>e({type:"list",raw:"",ordered:r,start:n,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,n)=>e({type:"list_item",raw:"",task:r,checked:n,loose:!1,text:t,tokens:[]})}if(r.paragraph){let e=r.paragraph;t.paragraph=t=>e({type:"paragraph",raw:"",text:t,tokens:[]})}if(r.codespan){let e=r.codespan;t.codespan=t=>e({type:"codespan",raw:"",text:t})}if(r.strong){let e=r.strong;t.strong=t=>e({type:"strong",raw:"",text:t,tokens:[]})}if(r.em){let e=r.em;t.em=t=>e({type:"em",raw:"",text:t,tokens:[]})}if(r.del){let e=r.del;t.del=t=>e({type:"del",raw:"",text:t,tokens:[]})}if(r.html){let e=r.html;t.html=t=>e({type:"html",raw:t,text:t})}if(r.text){let e=r.text;t.text=t=>e({type:"text",raw:t,text:t})}if(r.checkbox){let e=r.checkbox;t.checkbox=t=>e({checked:t})}return r.hr&&(t.hr=r.hr),r.br&&(t.br=r.br),t})(e?.renderer);a&&t.use({renderer:a})}return t.parse(r)}},Ke=e=>e?Ue({markedOptions:e.options,renderer:e.renderer}):Ue(),Je=Ue(),Ge=e=>Je(e),Ye=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Xe=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Qe=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ze=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let e=JSON.parse(r.trim());if(e&&"object"==typeof e&&"form"===e.component&&e.type){let r=Qe(t.length);return t.push({token:r,type:String(e.type)}),r}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let n=Qe(t.length);return t.push({token:n,type:r}),n}),r},et=e=>{let t=Ke(e);return e=>{let r=[],n=Ze(e,r),o=t(n);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Xe(t)}"></div>`;o=o.replace(r,n)}),o}},tt=e=>{let t=[],r=Ze(e,t),n=Ge(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Xe(t)}"></div>`;n=n.replace(r,o)}),n},rt={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"]},nt=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ot=()=>{let e=null;return t=>{let r=Ve();if(!r)return Ye(t);if(!e){let{DOMPurify:t}=r;e=t(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(e,t)=>{if("src"===t.attrName||"href"===t.attrName){let e=t.attrValue;e.toLowerCase().startsWith("data:")&&!nt.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,rt)}},at=e=>!1===e?null:"function"==typeof e?e:ot(),st=/^\s*\|?[\s:|-]*-[\s:|-]*$/,it=e=>e.includes("|"),lt=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(e=>e.trim())},dt=e=>`| ${e.join(" | ")} |`,ct=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,pt=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),ut="var(--persona-md-table-scroll-fade, 24px)",ht=new WeakSet;function mt(e){let t=e.scrollWidth-e.clientWidth;if(t<=1)return void e.removeAttribute("data-persona-scroll-x");e.setAttribute("data-persona-scroll-x","");let r="rtl"===getComputedStyle(e).direction?t+e.scrollLeft:e.scrollLeft,n=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":ut),e.style.setProperty("--persona-fade-r",n<=1?"0px":ut)}function gt(e){ht.has(e)||(ht.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&mt(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(mt)}var{setLoader:ft,load:yt,provide:bt,getSync:vt}=se({fallbackImport:()=>import("./client-stream")}),wt=ft,xt=yt,Ct=vt,St="webmcp:",kt=new Map,At=e=>{kt.clear();for(let t of e){let e=t.title?.trim();e&&kt.set(t.name,e)}},Mt=e=>kt.get(Et(e)),It=null;function Tt(e,t){let r=3735928559^t,n=1103547991^t;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);r=Math.imul(r^o,2654435761),n=Math.imul(n^o,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}var Et=e=>e.startsWith(St)?e.slice(St.length):e,Lt=e=>e.startsWith(St),Pt=()=>It?It():import("@mcp-b/webmcp-polyfill"),{setLoader:Bt,load:Nt}=se({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Rt=Bt,Ht=Nt;function $t(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function Wt(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Dt(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Ot(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var Ft=d(p(),1),zt="ask_user_question",qt="data-persona-ask-sheet-for",jt="Type your own answer here",_t="Send",Vt="data-ask-current-index",Ut="data-ask-question-count",Kt="data-ask-answers",Jt="data-ask-grouped",Gt="data-ask-layout",Yt=!1,Xt=e=>e.replace(/["\\]/g,"\\$&"),Qt=e=>"tool"===e.variant&&!!e.toolCall&&e.toolCall.name===zt,Zt=e=>e?.features?.askUserQuestion??{},er=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:r};let n=t.chunks;if(!n||0===n.length)return{payload:null,complete:r};try{let e=n.join(""),t=(0,Ft.parse)(e,Ft.STR|Ft.OBJ|Ft.ARR);if(t&&"object"==typeof t)return{payload:t,complete:r}}catch{}return{payload:null,complete:r}},tr=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!Yt&&(Yt=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},rr=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},nr=(e,t,r)=>{if("rows"!==e)return null;let n=ne("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let e=ne("span","persona-ask-row-check");n.appendChild(e)}else{let e=ne("span","persona-ask-row-badge");e.textContent=String(r+1),n.appendChild(e)}return n},or=e=>{let t=ne("span","rows"===e?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},ar=(e,t)=>{let r=ne("div","rows"===t?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=e.freeTextPlaceholder??jt,n.setAttribute("data-ask-free-text-input","true"),r.appendChild(n),"rows"!==t){let t=ne("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??_t,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},sr=e=>{let t=e.getAttribute(Kt);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},ir=e=>{let t=Number(e.getAttribute(Vt)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},lr=e=>{let t=Number(e.getAttribute(Ut)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},dr=e=>"true"===e.getAttribute(Jt),cr=(e,t,r)=>{let n=Zt(r),o=(e=>"pills"===e.getAttribute(Gt)?"pills":"rows")(e),{payload:a,complete:s}=er(t),i=dr(e),l=ir(e),d=lr(e),c=i?((e,t)=>tr(e)[t]??null)(a,l):(e=>tr(e)[0]??null)(a),p=!!c?.multiSelect,u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${l+1}/${d}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let m=e.querySelector('[data-ask-question="true"]');if(m){let e="string"==typeof c?.question?c.question:"";m.textContent=e,m.classList.toggle("persona-ask-question-skeleton",!e&&!s)}let g=e.querySelector('[data-ask-pill-list="true"]');if(g){let e=((e,t,r,n)=>{let o=ne("div","rows"===n?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&"string"==typeof e.label&&e.label.length>0);if(0===s.length&&!r){for(let e=0;e<3;e++)o.appendChild(or(n));return o}if(s.forEach((e,t)=>{o.appendChild(((e,t,r,n)=>{let o=ne("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",n?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),"rows"===r){let a=ne("span","persona-ask-row-content"),s=ne("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=ne("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}o.appendChild(a);let i=nr(r,n,t);i&&o.appendChild(i)}else o.textContent=e.label,e.description&&(o.title=e.description);return o})(e,t,n,a))}),!1!==e?.allowFreeText){let e="rows"===n?"Other":"Other…";if("rows"===n){let r=ne("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");r.setAttribute("data-ask-user-action","focus-free-text"),r.setAttribute("data-option-index",String(s.length)),r.setAttribute("data-ask-other-row","true");let i=ne("span","persona-ask-row-content"),l=document.createElement("input");l.type="text",l.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",l.placeholder=t.freeTextPlaceholder??jt,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=nr(n,a,s.length);d&&r.appendChild(d),o.appendChild(r)}else{let r=ne("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");r.type="button",r.setAttribute("data-ask-user-action","open-free-text"),r.textContent=t.freeTextLabel??e,o.appendChild(r)}}return o})(c,n,s,o);g.replaceWith(e)}if("rows"!==o){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(ar(n,o))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=ne("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=ne("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??_t,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(n)),e.setAttribute("data-multi-select",p?"true":"false");let y=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let n=ne("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=ne("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=r.backLabel??"Back",o.setAttribute("data-ask-user-action","back"),o.disabled=0===e,n.appendChild(o);let a=ne("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=ne("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=r.skipLabel??"Skip",s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=ne("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let l=e===t-1;return i.textContent=l?r.submitAllLabel??"Submit all":r.nextLabel??"Next",i.setAttribute("data-ask-user-action",l?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n})(l,d,n);y?y.replaceWith(t):e.appendChild(t)}else y&&y.remove();(e=>{let t=sr(e)[ir(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let n=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');n.forEach(e=>{let t=e.getAttribute("data-option-label")??"",n=r.has(t);e.setAttribute("aria-pressed",n?"true":"false"),e.classList.toggle("persona-ask-pill-selected",n)});let o=new Set(Array.from(n).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!o.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!dr(e))return;let t=sr(e)[ir(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,n=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');n&&(n.disabled=!r);let o=e.querySelector('[data-ask-user-action="submit-multi"]');if(o){let t=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));o.disabled=0===t.length}})(e)},pr=(e,t)=>{let r=ne("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Zt(t);rr(r,n);let o=ne("span","persona-ask-stub-label"),{complete:a}=er(e);return o.textContent=a?"Awaiting your response…":"Preparing options…",r.appendChild(o),r},ur=(e,t,r)=>{if(!r||!Qt(e)||!1===Zt(t).enabled)return;let n=e.toolCall.id;r.querySelectorAll(`[${qt}]`).forEach(e=>{e.getAttribute(qt)!==n&&e.remove()});let o=r.querySelector(`[${qt}="${Xt(n)}"]`);if(o)return void((e,t,r)=>{let{payload:n}=er(t),o=Math.max(1,tr(n).length);o>lr(e)&&(e.setAttribute(Ut,String(o)),o>1&&!dr(e)&&e.setAttribute(Jt,"true")),cr(e,t,r)})(o,e,t);let{payload:a}=er(e),s=((e,t,r)=>{let n=Zt(t),o=(e=>"pills"===e.layout?"pills":"rows")(n),a=e.toolCall.id,s=tr(r),i=Math.max(1,s.length),l=i>1,d=((e,t)=>{let r=e.agentMetadata?.askUserQuestionAnswers;if(!r||"object"!=typeof r)return{};let n={};return t.forEach((e,t)=>{let o="string"==typeof e?.question?e.question:"";if(o&&Object.prototype.hasOwnProperty.call(r,o)){let e=r[o];("string"==typeof e||Array.isArray(e))&&(n[t]=e)}}),n})(e,s),c=l?((e,t)=>{let r=e.agentMetadata?.askUserQuestionIndex;return"number"==typeof r&&Number.isFinite(r)?Math.max(0,Math.min(t-1,Math.floor(r))):0})(e,i):0,p=ne("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(qt,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(Ut,String(i)),p.setAttribute(Vt,String(c)),p.setAttribute(Jt,l?"true":"false"),p.setAttribute(Gt,o),((e,t)=>{e.setAttribute(Kt,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==n.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),rr(p,n);let u=ne("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=ne("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=ne("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=ne("div","rows"===o?"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 g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==o&&p.appendChild(ar(n,o)),cr(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},hr=(e,t)=>{if(!e)return;let r=t?`[${qt}="${Xt(t)}"]`:`[${qt}]`;e.querySelectorAll(r).forEach(e=>{e.classList.add("persona-ask-sheet-leave");let t=Number.parseInt(getComputedStyle(e).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},mr="suggest_replies",gr={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},fr={name:mr,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:gr,origin:"sdk",annotations:{readOnlyHint:!0}},yr=e=>"tool"===e.variant&&e.toolCall?.name===mr,br=e=>{let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{return[]}let r=t?.suggestions;if(!Array.isArray(r))return[];let n=r.flatMap(e=>{if("string"==typeof e){let t=e.trim();return t?[t]:[]}if(!e||"object"!=typeof e)return[];let t=e;if("string"!=typeof t.label||!t.label.trim())return[];let r={label:t.label.trim()};return"string"==typeof t.prompt&&t.prompt.trim()&&(r.prompt=t.prompt.trim()),"string"==typeof t.description&&t.description.trim()&&(r.description=t.description.trim()),[r]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},vr=e=>{for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return null;if(!yr(r))continue;let n=br(r.toolCall?.args);return n.length>0?n:null}return null},wr=new Set,xr=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,n=e=>{let n=t?.[e],o=r?.[e];void 0===n||void 0===o||n!==o&&((e,t,r)=>{let n=`${e}:${t}:${r}`;wr.has(n)||(wr.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,o,n)};e&&(n("enabled"),n("expose"));let o=t?.enabled??r?.enabled??!0;return{enabled:o,expose:!!o&&(t?.expose??r?.expose??!1)}},Cr={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:8,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},Sr={name:zt,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:Cr,origin:"sdk",annotations:{readOnlyHint:!0}},kr=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(Sr),xr(e).expose&&t.push(fr),t},Ar=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Mr=e=>{if("tool"!==e.variant)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||void 0===t.result)return null;let r=(e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""))(t.toolName);return r?{call:{toolCallId:t.toolCallId,toolName:r,args:Ar(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:r,result:t.result}}:null},Ir=(e,t)=>{let r,n=[],o=[],a=[],s="",i=()=>{0!==o.length&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:a}),o=[],a=[])};for(let l of e){let e=Mr(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(void 0===t||t!==r)&&i(),0===o.length&&(s=l.createdAt,r=t),o.some(t=>t.toolCallId===e.call.toolCallId)||(o.push(e.call),a.push(e.result));continue}let d=t(l);d&&(i(),n.push(d))}return i(),n},Tr=d(p(),1),Er=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Lr=e=>{if(null===e)return"null";if(void 0===e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Pr=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Br=e=>{let t="number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Pr(t)},Nr=e=>{let t=void 0!==e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Pr(t)},Rr=(e,t,r)=>{if(!t)return r;let n=e.name?.trim()||"tool",o=Br(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Hr=(e,t)=>{let r,n=e.replace(/\{toolName\}/g,t),o=[],a=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0;for(;null!==(r=a.exec(n));)r.index>s&&$r(o,n.slice(s,r.index),[]),void 0!==r[1]?$r(o,r[1],["bold"]):void 0!==r[2]?$r(o,r[2],["italic"]):void 0!==r[3]&&$r(o,r[3],["dim"]),s=r.index+r[0].length;return s<n.length&&$r(o,n.slice(s),[]),o},$r=(e,t,r)=>{let n=t.split("{duration}");for(let t=0;t<n.length;t++)n[t]&&e.push({text:n[t],styles:r}),t<n.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Wr=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),Dr=()=>{let e=(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return null!==e?{text:e,raw:r}:null;let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let o=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return t[1]}let r=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/);if(r&&r[1])try{return r[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return r[1]}return null})(r);return null!==o&&(e=o),t=r.length,null!==e?{text:e,raw:r}:null},close:async()=>{}}})();return{processChunk:async t=>{let r=t.trim();return r.startsWith("{")||r.startsWith("[")?e.processChunk(t):null},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Or=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return null!==e||""===e?{text:e||"",raw:r}:null;try{let t=(0,Tr.parse)(r,Tr.STR|Tr.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?Er(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=Er(t.text)))}catch{}return t=r.length,null!==e?{text:e,raw:r}:null},close:()=>{}}},Fr=e=>{let t=null,r=0,n=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?Er(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?Er(e.text):"";if("init"===e.type&&e.form)return"";if(e.action)switch(e.action){case"nav_then_click":return t(e.on_load_text)||t(e.text)||null;case"message":case"message_and_click":case"checkout":return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(e.length<=r)return null!==t?{text:t,raw:e}:null;try{let r=(0,Tr.parse)(e,Tr.STR|Tr.OBJ),o=n(r);null!==o&&(t=o)}catch{}return r=e.length,{text:t||"",raw:e}},close:()=>{}}},zr=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}},qr="4.26.0",{setLoader:jr,load:_r,provide:Vr}=se({fallbackImport:()=>import("./client-history")}),Ur=jr,Kr=_r,Jr="[Image]";function Gr(e){return"string"==typeof e?[{type:"text",text:e}]:e}function Yr(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")}function Xr(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function Qr(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function Zr(e){return{type:"text",text:e}}function en(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function tn(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}function rn(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var nn=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],on=[...nn,"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"];function an(e){return function(e){return nn.includes(e)||e.startsWith("image/")}(e.type)}function sn(e,t=on,r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function ln(e){let t=e.content;if("string"!=typeof t||""===t)return;let r=e.contentParts??e.llmContent??e.rawContent??t;return"string"!=typeof r||r!==t?t:void 0}function dn(e,t){let r=new Map;for(let t of e)r.set(t.id,t);for(let e of t)r.set(e.id,e);return[...r.values()].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o!==a?o-a:e.id.localeCompare(t.id)})}var cn={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"},pn=1e5,un=pn+1,hn=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}},mn=e=>"reason"in e?e.reason:void 0,gn=(e,t)=>e instanceof hn&&e.code===t,fn=e=>!e.voiceCaption&&!!(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),yn=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),bn=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt}),vn=class{constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#e=null,this.clientSession=null,this.#t=null,this.#r=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#n=null,this.#o=!1,this.#a=!1,this.#s=!1,this.#i=null,this.#l=new Set,this.#d=new Set,this.webMcpBridge=null,this.#c=null,this.#p=null,this.#u=null,e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#h=e.apiUrl??"https://api.runtype.com/v1/dispatch",this.#m={"Content-Type":"application/json","X-Persona-Version":qr,...e.headers},this.debug=!!e.debug,this.#g=e.streamParser??function(e){switch(e){case"json":return Or;case"regex-json":return Dr;case"xml":return zr;default:return Wr}}(e.parserType),this.#f=e.contextProviders??[],this.#y=e.requestMiddleware,this.#b=e.customFetch,this.#v=e.parseSSEEvent,this.#w=e.getHeaders,!0===e.webmcp?.enabled&&(this.#c=this.#x(e.webmcp))}#h;#m;#g;#f;#y;#b;#v;#w;#C;#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#S;#x(e){return Ht().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:At,getToolDisplayTitle:Mt,loadPolyfill:Pt});return void 0!==this.#S&&r.setConfirmHandler(this.#S),this.webMcpBridge=r,r}).catch(e=>(this.#c=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",e),null))}#k(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):!0!==this.config.webmcp?.enabled?Promise.resolve(null):(this.#c||(this.#c=this.#x(this.config.webmcp)),this.#c)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#C=e}setWebMcpConfirmHandler(e){this.#S=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return!0===this.webMcpBridge?.isOperational()}executeWebMcpToolCall(e,t,r){return!0!==this.config.webmcp?.enabled?null:this.#k().then(n=>n?n.executeToolCall(e,t,r):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#C}isClientTokenMode(){return!!this.config.clientToken}#A(){let{agentId:e,flowId:t,target:r,targetProviders:n}=this.config;if(!r)return{agentId:e,flowId:t};let o=function(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let n=r.indexOf(":");if(n>0){let e=r.slice(0,n),o=r.slice(n+1);if("runtype"===e){let e=$t(o);if(e)return e;throw new Error(`[Persona] target "runtype:${o}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw new Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:a(o).payload}}let o=$t(r);if(o)return o;let a=t?.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}(r,n);return"agentId"===o.kind?{agentId:o.agentId}:"flowId"===o.kind?{flowId:o.flowId}:{targetPayload:o.payload}}isAgentMode(){return!(!this.config.agent&&!this.#A().agentId)}#M(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||"https://api.runtype.com"}#I(e){return`${this.#M()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),r=!1;for(;;){let n=t.conversationId,o=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!n||!o)throw new hn("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.#M()}/v1/client/conversations/${encodeURIComponent(n)}/executions/${encodeURIComponent(e.executionId)}/events`,s=new URLSearchParams({sessionId:t.sessionId,after:e.after}),i=await fetch(`${a}?${s}`,{method:"GET",headers:{"X-Persona-Version":qr,"X-Visitor-Token":o},signal:e.signal});if(401===i.status&&!r){r=!0;let e=await Kr();t=await e.recoverFromUnauthorized(this.#T(),await e.readErrorCode(this.#T(),i),null,!0);continue}if(!i.ok)throw await(await Kr()).historyErrorFor(this.#T(),i,!0);return i}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#t||e&&new Date<e.expiresAt||this.#r===e?null:(this.#r=e,this.initSession().catch(()=>null))}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.#t)return this.#t;let e=this.#t=this.#E().then(t=>this.#t!==e?this.initSession():(this.clientSession=t,this.#r=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t)).finally(()=>{this.#t===e&&(this.#t=null)});return e}#L(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()&&!this.#o}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#P(){if(!this.#o){this.#B({state:"unavailable",reason:"history_disabled"}),this.#o=!0,!this.#a&&typeof console<"u"&&(this.#a=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#d])e(!1)}}getHistoryIdentityStatus(){return this.#i??this.#N()}subscribeHistoryIdentityStatus(e){return this.#l.add(e),()=>{this.#l.delete(e)}}subscribeHistoryAvailability(e){return this.#d.add(e),this.#o&&e(!1),()=>{this.#d.delete(e)}}#N(){return this.isClientTokenMode()?!0!==this.config.features?.history?.enabled||this.#o?{state:"unavailable",reason:"history_disabled"}:this.#R():{state:"unavailable",reason:"ineligible_mode"}}#R(){let e=this.#i;return"browser_only"===e?.state?e:this.#H()}#H(){return"browser"===this.config.features?.history?.scope?{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"}}#B(e){let t=this.getHistoryIdentityStatus(),r=t.state===e.state&&mn(t)===mn(e);if(this.#i=e,!r){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#l])t(e)}}async#$(e){let t=this.#L()&&!e.omitVisitorFields,r=!e.omitVisitorFields,n=null;(t||r)&&(await this.historyInternals.historyBootstrapReady,n=await this.readVisitorToken());let o=this.#A(),a=o.agentId??o.flowId,s=t||e.durableResume?e.conversationId:void 0,i={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(t||r)&&n?{visitorToken:n}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.#I("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qr},body:JSON.stringify(i),signal:e.signal});if(!l.ok){let r=await l.json().catch(()=>({error:"Session initialization failed"}));if(t&&403===l.status&&"visitor_history_disabled"===r.error){if(this.#P(),s)throw new hn("history_disabled","Visitor history is disabled for this surface");return this.#$({...e,omitVisitorFields:!0})}throw 403===l.status&&"durable_recovery_disabled"===r.error?new hn("history_disabled","Durable recovery is disabled for this surface"):(t||e.durableResume)&&401===l.status&&"visitor_required"===r.error?new hn("visitor_required","Visitor credential no longer resolves"):s&&404===l.status?new hn("not_found","Conversation not found"):401===l.status?new Error(`Invalid client token: ${r.hint||r.error}`):403===l.status?new Error(`Origin not allowed: ${r.hint||r.error}`):new Error(r.error||"Failed to initialize session")}let d=await l.json();return d.visitor?.token&&await(this.historyInternals.visitorStore?.set(d.visitor.token)),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#E(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=!0===this.historyInternals.shouldResumeDurableConversation?.();if(!this.#L()&&!t)return this.#W(e,!1);let r=await this.readVisitorToken();if(e&&r)try{let r=await this.#$({conversationId:e,durableResume:t});return t&&!0!==r.durableRecovery?.enabled&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,e,!1)}catch(r){if(!gn(r,"not_found")&&!gn(r,"visitor_required")&&!gn(r,"history_disabled"))throw r;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,t){let r=this.historyInternals.visitorStore;return r&&!await this.readVisitorToken()?r.withFirstInitLock(()=>this.#O(e,t)):this.#O(e,t)}async#O(e,t){let r=this.config.getStoredSessionId?.()||null,n=await this.#$({storedSessionId:r}),o=await this.#F(n);return this.#D(o,e,t)}async#z(e){let t=this.config.getStoredSessionId?.()||null,r=this.config.getStoredConversationId?.()||null,n=await this.#$({storedSessionId:t,identityProof:e}),o=this.#D(n,r,!1);return this.clientSession=o,this.#t=null,this.#r=!1,this.resetClientToolsFingerprint(),o}async#F(e){if(!e.visitor?.token||this.#s||!this.#L()&&!0!==e.durableRecovery?.enabled)return e;this.#s=!0;try{return await this.#$({storedSessionId:e.sessionId})}catch{return e}finally{this.#s=!1}}#D(e,t,r){let n=e.conversationId;return n&&t&&(r||n!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:n}),this.config.setStoredSessionId?.(e.sessionId),n&&(this.config.setStoredConversationId?.(n),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#q(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#r=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#L())throw new hn("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new hn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let n=await this.#$({conversationId:e,identityProof:r});return this.#q(n)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#$({});return this.#q(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#B(this.#H())}clearClientSession(){this.clientSession=null,this.#t=null,this.#r=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#n=null}#j(){return`${this.#M()}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if("csat"===e.type&&(void 0===e.rating||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if("nps"===e.type&&(void 0===e.rating||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},r=await fetch(this.#j(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qr},body:JSON.stringify(t)});if(!r.ok){let e=await r.json().catch(()=>({error:"Feedback submission failed"}));throw 401===r.status?(this.clientSession=null,this.#r=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(e.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async#_(e){e?.throwIfAborted();let t=this.config.identityProvider;if(void 0===t)return;let r,n,o=this.config.getIdentityProof;if(!t.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>o());r=e?await Promise.race([t,new Promise((t,r)=>{n=()=>r(e.reason),e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})]):await t}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{n&&e?.removeEventListener("abort",n)}if("string"!=typeof r||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:t,token:r}}#p;#V(){let e=this;return this.#p??={get config(){return e.config},headers:this.#m,getHeaders:this.#w,debug:this.debug,clientApiBase:()=>e.#M(),getClientApiUrl:t=>e.#I(t),getWebMcpBridge:()=>e.#k(),sendWithClientToolsDiff:(t,r,n,o)=>e.#U(t,r,n,o),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#u;#T(){let e=this;return this.#u??={HistoryClientError:hn,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#M(),setHistoryIdentityStatus:t=>e.#B(t),browserOnlyStatus:()=>e.#R(),derivedBrowserOnly:()=>e.#H(),reinitWithProof:t=>e.#z(t),isHistoryCapable:()=>e.#L(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await Kr()).listConversations(this.#T(),e)}async getConversation(e,t){return(await Kr()).getConversation(this.#T(),e,t)}async finalizeDisplayProjections(e,t){return(await Kr()).finalizeDisplayProjections(this.#T(),e,t)}async deleteConversation(e,t){return(await Kr()).deleteConversation(this.#T(),e,t)}async deleteAllConversations(e){return(await Kr()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await Kr()).resetVisitor(this.#T())}async dispatch(e,t){return e.signal?.throwIfAborted(),xt().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#G(e,t)}async#K(e,t){let r=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;this.#e=r;let n=()=>this.#e===r,o=e=>{n()&&t(e)};t({type:"status",status:"connecting"});try{let t=()=>{if(e.signal?.throwIfAborted(),!n())throw new DOMException("Turn superseded","AbortError")},a=this.clientSession??await this.initSession();t();let s=async()=>{t();let r=a,n=!0===r.durableRecovery?.enabled;if(n&&(!r.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");t();let o=await this.#$({...n||this.#L()?{conversationId:r.conversationId,durableResume:n}:{storedSessionId:r.sessionId},signal:e.signal});if(t(),r.conversationId&&o.conversationId!==r.conversationId||n&&!0!==o.durableRecovery?.enabled)throw new Error("Session renewal did not preserve this conversation.");a=this.#D(o,r.conversationId??null,!1),this.clientSession=a,this.#r=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await s();let i=await this.#Y(e.messages),l=i.metadata?Object.fromEntries(Object.entries(i.metadata).filter(([e])=>"sessionId"!==e&&"session_id"!==e)):void 0,d=this.#L(),c={sessionId:a.sessionId,messages:e.messages.filter(fn).map(e=>{let t=d?ln(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...void 0!==t&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...l&&Object.keys(l).length>0&&{metadata:l},...i.inputs&&Object.keys(i.inputs).length>0&&{inputs:i.inputs},...i.context&&{context:i.context},turnId:r,...e.interrupt&&{submitMode:"interrupt"}},p=async()=>{t();let r=!0===a.durableRecovery?.enabled?await this.readVisitorToken():null;return t(),this.#U(a.sessionId,i.clientTools,async n=>{t();let o=await this.#_(e.signal);t();let s={...c,sessionId:a.sessionId,...n,...o&&{identityProof:o}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...s,...o&&{identityProof:{provider:o.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qr,...r?{"X-Visitor-Token":r}:{}},body:JSON.stringify(s),signal:e.signal})})},u=await p();if(t(),401===u.response.status){let e=await u.response.clone().json().catch(()=>null);t(),"Session not found or expired"===e?.error&&(await s(),u=await p(),t())}let{response:h,commit:m}=u;if(!h.ok){let e=await h.json().catch(()=>({error:"Chat request failed"}));if(401===h.status&&"invalid_identity_proof"===e.error){let e=new hn("invalid_identity_proof","The identity proof was rejected");throw o({type:"error",error:e}),e}if(401===h.status){this.clearClientSession(),this.config.onSessionExpired?.();let e=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:e}),e}if(429===h.status){let t=new Error(e.hint||"Message limit reached for this session.");throw o({type:"error",error:t}),t}if(410===h.status&&"conversation_deleted"===e.error){let e=new hn("conversation_deleted","This conversation was deleted");throw o({type:"error",error:e}),e}let t=new Error(e.error||"Failed to send message");throw o({type:"error",error:t}),t}if(!h.body){let e=new Error("No response body received");throw o({type:"error",error:e}),e}m(),o({type:"status",status:"connected"});try{await this.#X(h.body,o,e.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(e){let t=e instanceof Error?e:new Error(String(e));throw!(t instanceof hn)&&!t.message.includes("Session expired")&&!t.message.includes("Message limit")&&o({type:"error",error:t}),t}}async#G(e,t){t({type:"status",status:"connecting"});let r=await this.#Y(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let n,o={...this.#m};if(this.#w)try{let e=await this.#w();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#b)try{n=await this.#b(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:new Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=new Error(`Chat backend request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t)}finally{t({type:"status",status:"idle"})}}async#J(e,t){t({type:"status",status:"connecting"});let r=await this.#Q(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let n,o={...this.#m};if(this.#w)try{let e=await this.#w();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#b)try{n=await this.#b(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:new Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=new Error(`Agent execution request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,n){t({type:"status",status:"connected"});try{await this.#X(e,t,r,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){return(await xt()).resolveApproval(this.#V(),e,t)}async#U(e,t,r,n){let o,a=!!(t&&t.length>0),s=a?function(e){if(0===e.length)return"0:empty";let t=e.map(e=>[e.name,e.description??"",e.parametersSchema?JSON.stringify(e.parametersSchema):"",e.origin??"",e.annotations?JSON.stringify(e.annotations):""].join("")).sort();return`${e.length}:${function(e){return`${Tt(e,0).toString(36)}.${Tt(e,2654435761).toString(36)}`}(t.join(""))}`}(t):void 0,i=this.clientToolsFingerprintSessionId===e,l=a&&i&&this.lastSentClientToolsFingerprint===s,d=!a&&!0===n?.emptyMeansReplace&&this.#n===e,c=!1;for(let e=0;o=await r({...a&&(c||!l)&&t?{clientTools:t}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),409===o.status&&0===e&&a&&"client_tools_resend_required"===(await o.clone().json().catch(()=>null))?.error;e++)c=!0,this.lastSentClientToolsFingerprint=null;return{response:o,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=e,a?this.#n=e:d&&(this.#n=null)}}}async resumeFlow(e,t,r){return(await xt()).resumeFlow(this.#V(),e,t,r)}#Z(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return r.mentionContext&&Object.keys(r.mentionContext).length>0?{mentions:r.mentionContext}:null}return null}async#ee(e){let t={};this.#f.length&&await Promise.all(this.#f.map(async r=>{try{let n=await r({messages:e,config:this.config});n&&"object"==typeof n&&Object.assign(t,n)}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",e)}}));let r=this.#Z(e);return r&&Object.assign(t,r),Object.keys(t).length?t:null}#te(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#re(e,t){let r=t?.selectedModelId;return r&&"model"in e&&this.config.composer?.models?.some(e=>e.id===r)?{...e,model:r}:e}async#Q(e,t){let r=this.#A().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let n=Ir(yn(e),e=>!fn(e)||"user"!==e.role&&"assistant"!==e.role&&"system"!==e.role||e.variant&&"assistant"!==e.variant?null:bn(e)),o=this.#te(t),a={agent:this.#re(this.config.agent??{agentId:r},o),messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};o&&(a.composerOptions=o);let s=[...kr(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];s.length>0&&(a.clientTools=s);let i=await this.#ee(e);return i&&(a.context=i),a}async#Y(e,t){let r=Ir(yn(e),e=>fn(e)?bn(e):null),n=this.#A(),o={messages:r,...n.agentId?{agent:{agentId:n.agentId}}:n.flowId?{flowId:n.flowId}:{}};if(n.targetPayload)for(let[e,t]of Object.entries(n.targetPayload))"messages"!==e&&(o[e]=t);let a=[...kr(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];a.length>0&&(o.clientTools=a);let s=await this.#ee(e);s&&(o.context=s);let i=this.#te(t);if(i&&(o.composerOptions=i),this.#y)try{let e=await this.#y({payload:{...o},config:this.config});if(e&&"object"==typeof e){let t=e;return void 0!==o.clientTools&&!("clientTools"in t)&&(t.clientTools=o.clientTools),t}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",e)}return o}async#X(e,t,r,n){let{streamResponse:o}=Ct()??await xt();return o({config:()=>this.config,createStreamParser:this.#g,parseSSEEvent:this.#v,onSSEEvent:(e,t)=>this.#C?.(e,t)},e,t,r,n)}},wn=class extends Error{constructor(e,t,r){super(t),this.name="HistoryProviderError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};function xn(e){return e instanceof wn}var{setLoader:Cn,load:Sn,provide:kn,getSync:An}=se({fallbackImport:()=>import("./ui-extras-entry")}),Mn=Cn,In=Sn,Tn=An,{setLoader:En,load:Ln,provide:Pn,getSync:Bn}=se({fallbackImport:()=>import("./session-actions")}),Nn=En,Rn=Ln,Hn=Bn;function $n(e){return"card"===e?"collapsed":e}function Wn(e){return e.split(";",1)[0].trim().toLowerCase()}function Dn(e,t){let r=e?.display,n="string"==typeof r?{default:r}:r??{};if(t.file&&n.files){if("string"==typeof n.files)return{mode:$n(n.files),matchedBy:{type:"files"}};let e=t.file.mimeType?Wn(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,n]of r)if(Wn(e)===t)return{mode:$n(n),selector:Wn(e)};let n=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(Wn(e)===n)return{mode:$n(t),selector:n}}(n.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(n.files.default)return{mode:$n(n.files.default),matchedBy:{type:"files"}}}let o=n.byKind?.[t.artifactType];if(o)return{mode:$n(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:$n(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:$n(s),matchedBy:{type:"preferredMode"}}:n.default?{mode:$n(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function On(e,t){return Dn(e,t).mode}function Fn(e,t){return JSON.stringify({component:"inline"===e?"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}:{},..."inline"===e&&t.component?{component:t.component}:{},..."inline"===e&&t.componentProps?{componentProps:t.componentProps}:{},...void 0!==t.markdown?{markdown:t.markdown}:{}}})}function zn(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function qn(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;t-=1)if("user"===e[t].role)return e[t].id;return null}function jn(e){return!("user"!==e.role||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||void 0!==e.rawContent||void 0!==e.llmContent&&e.llmContent!==e.content||e.quote)&&"string"==typeof e.content&&e.content.length>0}function _n(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 r of t){let t=e.find(e=>e.name===r);if(t)return t}return e.find(e=>e.lang.startsWith("en"))??e[0]}var Vn=class e{constructor(e={}){this.options=e,this.id="browser",this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,r){if(!e.isSupported())return void r.onError?.(new Error("Web Speech API is unavailable"));let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(o.voice=e)}else a.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(a):_n(a));void 0!==t.rate&&(o.rate=t.rate),void 0!==t.pitch&&(o.pitch=t.pitch),o.onend=()=>r.onEnd?.(),o.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(new Error(t||"Speech synthesis failed"))},setTimeout(()=>{n.speak(o),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Un=class{#h=null;#m=null;#g="idle";#f=new Set;#y=0;#b;constructor(e){this.#b=e}get supportsPause(){return this.#h?.supportsPause??!0}stateFor(e){return this.#m===e?this.#g:"idle"}activeMessageId(){return this.#m}onChange(e){return this.#f.add(e),()=>this.#f.delete(e)}toggle(e,t){if(this.#m===e){if("playing"===this.#g)return void(this.#h?.supportsPause?(this.#h.pause(),this.#v(e,"paused")):this.stop());if("paused"===this.#g)return this.#h?.resume(),void this.#v(e,"playing");if("loading"===this.#g)return void this.stop()}this.play(e,t)}async play(e,t){let r=++this.#y;this.#h?.stop(),this.#v(e,"loading");try{if(!this.#h){let e=await this.#b();if(r!==this.#y)return;if(!e)return void this.#v(null,"idle");this.#h=e}this.#h.speak(t,{onStart:()=>{r===this.#y&&this.#v(e,"playing")},onEnd:()=>{r===this.#y&&this.#v(null,"idle")},onError:()=>{r===this.#y&&this.#v(null,"idle")}})}catch{r===this.#y&&this.#v(null,"idle")}}stop(){this.#y++,this.#h?.stop(),this.#v(null,"idle")}destroy(){this.stop(),this.#h?.destroy?.(),this.#h=null,this.#f.clear()}#v(e,t){this.#m="idle"===t?null:e,this.#g=t;for(let e of this.#f)e(this.#m,this.#g)}},Kn=class{#h;#m=!1;start(e){this.#h=e,this.#m=!1}cancel(){this.#m=!0}accepts(e){return!(this.#m||e&&this.#h&&e!==this.#h)}},{setLoader:Jn,load:Gn,getSync:Yn}=se({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Xn=Jn,Qn=Gn,Zn=Yn;function eo(e){if(!e)return"";let t=function(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let e=JSON.parse(t);if(e&&"object"==typeof e&&"string"==typeof e.text)return e.text}catch{}return null}(e);return function(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,"\n"),t=t.replace(/\n{2,}/g,"\n"),t.trim()}(null!==t?t:e)}var to=null,ro=()=>to?to():import("./runtype-tts-entry"),{setLoader:no,load:oo}=se({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),ao=no,so=oo,io=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"],lo=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};function co(e,t){let r=e instanceof Error?e:new Error(String(e));if("string"==typeof t)return t;if("function"==typeof t)return t(r);let n="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 r.message?`${n}\n\n_Details: ${r.message}_`:n}var po=e=>Lt(e)||e===mr,uo=class e{constructor(e={},t,r={}){this.config=e,this.callbacks=t,this.historyInternals=r,this.status="idle",this.streaming=!1,this.abortController=null,this.#h=Date.now(),this.clientSession=null,this.agentExecution=null,this.#m=null,this.#g=null,this.#f=!1,this.#y=null,this.#b=null,this.#v=null,this.artifacts=new Map,this.#w=null,this.webMcpInflightKeys=new Set,this.webMcpResolvedKeys=new Set,this.webMcpResolveControllers=new Set,this.#C=0,this.webMcpApprovalResolvers=new Map,this.#e=0,this.approvalTokens=new Map,this.webMcpAwaitBatches=new Map,this.#t=null,this.#r=null,this.#n=0,this.#o=0,this.#a=!1,this.#s="disconnected",this.#i=null,this.#l=null,this.#d=null,this.#c=0,this.#S=!1,this.#x=null,this.#k=!1,this.#A=null,this.#M=new Map,this.#I=null,this.#L=new Map,this.#P=null,this.#N=null,this.#R=!1,this.#H=null,this.#B=null,this.#$=!1,this.#E=null,this.#z=null,this.#F=null,this.#D=new Kn,this.#q=Promise.resolve(),this.#j=null,this.#_=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new Un(()=>this.#p()),this.#ne=null,this.#oe=0,this.handleEvent=e=>{let t=this.#_;if(t&&("error"===e.type||"status"===e.type&&"error"===e.status?t.failed=!0:"message"===e.type&&"assistant"===e.message.role&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id))),"message"===e.type){this.upsertMessage(e.message),"approval"===e.message.variant&&e.message.approval&&"pending"!==e.message.approval.status&&this.#ae(e.message.id),"assistant"===e.message.role&&!e.message.variant&&e.message.streaming&&(this.#g=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&Rn().catch(()=>{});let t=e.message.toolCall,r=!!t?.name&&(Lt(t.name)||t.name===mr&&xr(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&r&&this.#se(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?void 0!==e.message.agentMetadata.iteration&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if("cursor"===e.type)this.#ie(e.id);else if("status"===e.type){if("idle"===e.status&&!e.terminal&&this.#le())return void this.#de();if(this.#ce(e.status),"connecting"===e.status)this.#pe(!0);else if("idle"===e.status||"error"===e.status){this.#ue()||this.#he(),0===this.webMcpResolveControllers.size&&(this.#pe(!1),this.abortController=null,this.#me(),this.#ge());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;"running"===this.agentExecution?.status&&("error"===e.status?this.agentExecution.status="error":t||(this.agentExecution.status="complete")),this.#fe()}}else"error"===e.type?(this.#ce("error"),this.#he(),0===this.webMcpResolveControllers.size&&(this.#pe(!1),this.abortController=null),"running"===this.agentExecution?.status&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):("artifact_start"===e.type||"artifact_delta"===e.type||"artifact_update"===e.type||"artifact_complete"===e.type)&&this.#ye(e)},this.historyInternals=this.#J(r),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#be()})),this.messages=this.#ve(this.messages),this.client=new vn(e,this.historyInternals),this.#we(),this.#xe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:"complete"});null!=e.initialSelectedArtifactId&&(this.#w=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ce(),this.callbacks.onStatusChanged(this.status),this.#O(),this.#W()}#h;#m;#g;#f;#y;#b;#v;#w;#C;#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#S;#x;#k;#A;#M;#I;#L;#P;#N;#R;#H;#B;#$;#E;#W(){this.config.voiceRecognition?.provider&&Qn().catch(()=>{})}#O(){let e=this.config.textToSpeech;if("runtype"!==e?.provider||e.createEngine)return;let t=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!t||!r||!this.config.clientToken||ro().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return"running"===this.agentExecution?.status}isVoiceSupported(){return function(e){try{if("custom"===e?.type&&e.custom){let t=e.custom,r="function"==typeof t?t():t;return!!r&&"function"==typeof r.startListening}return!("runtype"!==e?.type||!e.runtype)||typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)}catch{return!1}}(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#a}getVoiceStatus(){return this.#s}getVoiceDisclosure(){return this.#t?.getDisclosure?.()??null}getVoiceLevel(){return this.#t?.onLevel?this.#o:null}getVoiceInterruptionMode(){return this.#t?.getInterruptionMode?this.#t.getInterruptionMode():"none"}stopVoicePlayback(){this.#t?.stopPlayback&&(this.#D.cancel(),this.#j?.cancel(),this.#t.stopPlayback())}isBargeInActive(){return this.#t?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#t?.deactivateBargeIn&&await this.#t.deactivateBargeIn()}#z;#F;#D;#q;#j;#_;#p(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Vn.isSupported()?new Vn({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,o=this.config.clientToken,a=!1!==e.browserFallback;if(r&&n&&o)return ro().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:n,clientToken:o,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new i(l,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):l});if(a&&t)return o&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw new Error("Voice configuration not provided");this.cleanupVoice();let r=this.#q,n=++this.#n;this.#r=Qn().then(async e=>{await r,n===this.#n&&this.#V(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{n===this.#n&&(this.#r=null)})}catch(e){console.error("Failed to setup voice:",e)}}#V(e,t){this.#t=t;let r=this;e.wireSessionVoice({session:this,provider:()=>r.#t,generation:()=>r.#n,get keyed(){return r.#j},set keyed(e){r.#j=e},get pendingUser(){return r.#z},set pendingUser(e){r.#z=e},get pendingAssistant(){return r.#F},set pendingAssistant(e){r.#F=e},turns:()=>r.#D,busy:()=>r.#u(),setStreaming:e=>r.#pe(e),setDelegation:e=>{r.#_=e},setLevel:e=>{r.#o=e},setStatus:e=>{r.#s=e,r.#a="listening"===e},settlePending:e=>r.#K(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#t&&this.#r&&await this.#r,this.#t)if(this.#a)await this.#t.stopListening();else{this.stopSpeaking();try{await this.#t.startListening()}catch(e){console.error("Failed to start voice:",e)}}else console.error("Voice not configured")}prewarmVoice(){if(!$e(this.config.voiceRecognition?.provider))return void this.warmClientSession();let e=this.#n,t=()=>{let t=this.#t;!t?.prewarm||e!==this.#n||this.#a||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{})};this.#t||!this.#r?t():this.#r.then(t,()=>{})}#u(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#f||"resuming"===this.status}cleanupVoice(){let e=null!==this.#t;if(this.#n++,this.#r=null,this.#t){let e=this.#t;this.#t=null,this.#q=this.#T(e)}this.#a=!1,this.#s="disconnected",this.#K(!0),this.#j?.settle(),this.#j=null,this.#D=new Kn,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#T(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#K(e){let t=e?this.#z:null,r=this.#F;!t&&!r||(r&&this.#D.cancel(),e&&(this.#z=null),this.#F=null,r&&this.ttsSpokenMessageIds.add(r),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==r?[e]:e.id!==r||e.content.trim()?[{...e,streaming:!1,voiceProcessing:!1}]:[]),this.callbacks.onMessagesChanged([...this.messages]),r&&this.#pe(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#N=this.historyInternals.getStoredConversationRevision?.()??null,this.#R=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#G(e,t)}#G(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let r=this.messages[0],n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:r?.createdAt??(new Date).toISOString(),sequence:r?(r.sequence??0)-1:this.#be()};this.#Se(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return!!e&&new Date<e.expiresAt}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#J(e),this.client.setHistoryInternals(this.historyInternals),this.#we()}destroy(){this.cleanupVoice(),this.#H?.(),this.#H=null,this.#B=null}#J(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#ke(e),t?.(e)}}}get#U(){return this.historyInternals.historyProvider??null}#Z(){let e=this.#U;if(!e)throw new lo("history_unavailable","No conversation history provider is installed");return e}#ee(e){let t=this.#Z(),r=e??this.config.features?.history?.scope,n=this.config.getIdentityProof?"verified-user":"browser",o=r??(t.capabilities.scopes.includes(n)?n:t.capabilities.scopes[0]??n);if(!t.capabilities.scopes.includes(o))throw new wn("unsupported_scope","This history scope is not supported.");return{scope:o}}getHistoryState(){return{activeConversationId:this.#i,conversationRevision:this.#l,nextMessageCursor:this.#d,recovery:this.#x,sendBlocked:this.#k}}getActiveConversationId(){return this.#i}#te(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#re(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#A;e&&await e.catch(()=>{});let t=this.#I;t&&await t.catch(()=>{})}#Q(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new lo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#Z().list({...e?.cursor?{cursor:e.cursor}:{},...void 0!==e?.limit?{limit:e.limit}:{},...void 0!==e?.targetId?{targetId:e.targetId}:{},context:this.#ee(e?.scope)})}async openConversation(e,t){let r=this.#Z();this.#Q();let n=this.#ee(t?.scope);await this.awaitHistorySettled();let o=++this.#c,a=await r.getPage(e,{context:n});if(o!==this.#c)throw new lo("superseded","A later selection won");let s=await r.prepareOpen(e,{context:n});if(o!==this.#c)throw s.discard(),new lo("superseded","A later selection won");this.#S=!0;try{await this.#Ae(s)}finally{this.#S=!1}this.#i=s.conversationId||e,this.#l=s.conversationRevision||a.conversationRevision||null,this.#d=a.nextCursor,this.#x=null,this.#k=!1,this.#Me();for(let e of a.messages)this.#L.set(e.id,e.content);return this.#Ie(),this.hydrateMessages(a.messages),this.#te(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,r){let n=this.#Z(),o=this.#ee(r?.scope),a=t??this.#d;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let s=`${e} ${a}`,i=this.#M.get(s);if(i)return i;let l=this.#Y(n,e,a,o).finally(()=>{this.#M.delete(s)});return this.#M.set(s,l),l}async#Y(e,t,r,n){let o=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...o?{beforeCreatedAt:o}:{},context:n});if(this.#i&&this.#i!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=dn(this.messages,a.messages);this.messages=this.#ve(s.map(e=>this.#Te(e))),this.#d=a.nextCursor;for(let e of a.messages)this.#L.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#te(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#Z(),r=this.#ee(e?.scope);await this.awaitHistorySettled();let n=++this.#c,o=await t.prepareStartNew({context:r});if(n!==this.#c)throw o.discard(),new lo("superseded","A later action won");await this.#X(o)}async#X(e){this.#Ee(),await this.#Ae(e),this.#i=e.conversationId||null,this.#l=e.conversationRevision||null,this.#d=null,this.#x=null,this.#k=!1,this.#Ie(),this.#te()}async deleteConversation(e,t){let r=this.#Z(),n=this.#ee(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:n}),e===this.#i&&await this.#Le(n)}async updateConversation(e,t,r){let n=this.#Z();if(!n.update)throw new lo("history_unavailable","This history provider cannot update conversations");let o=this.#ee(r?.scope);return await this.awaitHistorySettled(),n.update(e,t,{context:o})}canUpdateConversations(){return"function"==typeof this.#U?.update}async clearConversationHistory(e){let t=this.#Z(),r=this.#ee(e?.scope);await this.awaitHistorySettled();let n=await t.deleteAll({...void 0!==e?.targetId?{targetId:e.targetId}:{},context:r});return await this.#Le(r),n}async resetHistoryDevice(){let e=this.#Z();if(!e.resetDevice)throw new lo("history_unavailable","This history provider cannot reset the device");this.#c+=1,this.#I=null;try{return await e.resetDevice()}finally{this.#Ee(),this.#i=null,this.#l=null,this.#d=null,this.#x=null,this.#k=!1,this.#te()}}async#Le(e){this.#c+=1,this.#I=null,this.#Ee(),this.#i=null,this.#l=null,this.#d=null,this.#k=!0,this.#x=null,this.#te(),await this.#Pe(e)}async#Pe(e){let t=this.#U;if(!t)return this.#k=!1,void this.#te();try{let r=await t.prepareStartNew({context:e});await this.#X(r)}catch{this.#k=!0,this.#x="new_conversation_required",this.#te(),this.#re("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Be(){if("new_conversation_required"===this.#x&&this.#U&&(this.#x=null,await this.#Pe(this.#ee()),"new_conversation_required"===this.#x))throw new lo("new_conversation_required","A new conversation is required before sending")}async#Ae(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#i=e.conversationId,this.#l=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#G(e)}#Ie(){this.#i?this.config.setStoredConversationId?.(this.#i):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#l),this.historyInternals.setStoredMessageCursor?.(this.#d)}#Me(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ne(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#L.clear(),this.#Re(null)}#Ee(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#He(),this.#$e(),this.#oe++,this.messages=[],this.#Me(),this.#M.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#pe(!1),this.#ce("idle"),this.callbacks.onMessagesChanged([...this.messages])}#ke(e){this.#c+=1,this.#I=null,this.#k=!0,this.#Ee(),this.#i=e.conversationId,this.#l=null,this.#d=null,this.#x=null,this.#te(),this.#re("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#A=Promise.resolve().then(()=>{this.#k=!1,this.#A=null,this.#te()})}#we(){let e=this.historyInternals.visitorStore??null;e!==this.#B&&(this.#H?.(),this.#H=null,this.#B=e,e&&(this.#H=e.subscribe(e=>this.#We(e))))}#We(e){if("external"!==e.source||null===e.previousToken)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#c+=1,this.#I=null,this.#$=!0,this.#E=null;let t=this.messages.length>0;t||null!==this.#i||null!==(this.config.getStoredConversationId?.()??null)?this.#Ee():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#M.clear(),this.#Re(null)),this.#i=null,this.#l=null,this.#d=null,this.#x=null,this.#te(),t&&this.#re("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#De(){return this.#$?(this.#E||(this.#E=this.#Oe().finally(()=>{this.#E=null})),this.#E):Promise.resolve()}async#Oe(){if(this.isClientTokenMode())try{this.bindActivatedSession(await this.client.initSession()),this.#$=!1}catch{}else this.#$=!1}reconcileBootConversation(e){let t=this.#U,r=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#i;if(!t||!r)return Promise.resolve();let n=this.#ee(e?.scope);this.#k=!0,this.#te();let o=this.#Fe(t,r,n).finally(()=>{this.#k=null!==this.#x,this.#A===o&&(this.#A=null),this.#te()});return this.#A=o,o}async#Fe(e,t,r){this.#i=t;let n=this.clientSession?.conversationRevision??this.#l??null,o=this.#R?this.#N:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#R=!1,this.#d=this.historyInternals.getStoredMessageCursor?.()??this.#d,await this.replayPendingProjections(),n&&o&&n===o)return void(this.#l=n);let a,s=await e.getPage(t,{context:r}),i=new Set(s.messages.map(e=>e.id)),l=this.messages.some(e=>i.has(e.id)),d=s.messages[0]?.createdAt;if(l){let e=this.#m?this.#g:null;a=dn(this.messages.filter(t=>!(!i.has(t.id)&&t.id!==e)||void 0!==d&&t.createdAt<d),s.messages).map(e=>this.#Te(e))}else a=s.messages.map(e=>this.#Te(e));this.#d=s.nextCursor,this.#l=s.conversationRevision||n||null,this.#L.clear();for(let e of s.messages)this.#L.set(e.id,e.content);this.#Ie(),this.messages=this.#ve(a),this.callbacks.onMessagesChanged([...this.messages])}#ze(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#Re(e){this.#P=e,this.historyInternals.setPendingDisplayProjections?.(e)}#qe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#P}#je(e){if(this.#ze())for(let t of e){let e=ln(t);void 0!==e&&this.#L.set(t.id,e)}}#ge(){if(!this.#ze())return;let e=this.#i;if(!e)return;let t=[];for(let e of this.messages){if("assistant"!==e.role||e.streaming)continue;let r=ln(e);void 0!==r&&this.#L.get(e.id)!==r&&t.push({id:e.id,displayContent:r})}0!==t.length&&(this.#Re({conversationId:e,messageIds:t.map(e=>e.id)}),this.#_e(e,t))}#_e(e,t){let r=(this.#I??Promise.resolve()).catch(()=>{}).then(()=>this.#Ve(e,t,!1)).finally(()=>{this.#I===r&&(this.#I=null)});this.#I=r}async#Ve(e,t,r){if(this.#i!==e)return;let n=t.filter(e=>this.#L.get(e.id)!==e.displayContent);if(0!==n.length)try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,n);for(let e of n)this.#L.set(e.id,e.displayContent);this.#i===e&&r&&(this.#l=r),this.#Ue(e,t)}catch(o){if(!r&&this.#Ke(o))return void await this.#Ve(e,n,!0);if(o instanceof hn&&("not_found"===o.code||"conversation_deleted"===o.code))return void this.#Ue(e,t);this.#re("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}else this.#Ue(e,t)}#Ke(e){return e instanceof hn?"request_failed"===e.code:e instanceof Error}#Ue(e,t){let r=this.#qe();if(!r||r.conversationId!==e)return;let n=new Set(t.map(e=>e.id)),o=r.messageIds.filter(e=>!n.has(e));this.#Re(o.length?{conversationId:e,messageIds:o}:null)}async replayPendingProjections(){if(!this.#ze())return;let e=this.#qe();if(!e)return;if(this.#i&&e.conversationId!==this.#i)return void this.#Re(null);let t=[];for(let r of e.messageIds){let e=this.messages.find(e=>e.id===r);!e||"string"!=typeof e.content||t.push({id:r,displayContent:e.content})}0!==t.length?(this.#_e(e.conversationId,t),await(this.#I?.catch(()=>{}))):this.#Re(null)}#me(){this.#i&&(this.#l=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Je(){await this.awaitHistorySettled(),await this.#De(),"new_conversation_required"===this.#x&&await this.#Be()}static#Ge(e){return e instanceof hn&&"conversation_deleted"===e.code}async#Ye(t,r,n,o,a){this.#je(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent)}catch(t){if(!e.#Ge(t))throw t;let s=await this.#Xe(o);if(!s)throw t;this.#je([s]),await this.client.dispatch({messages:[s],signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async#Xe(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#c+=1,this.#I=null,this.#Ee(),this.#i=null,this.#l=null,this.#d=null,this.#S=!0;try{let e=this.#U;if(e){let t=await e.prepareStartNew({context:this.#ee()});await this.#X(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#k=!0,this.#x="new_conversation_required",this.#te(),this.#re("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#S=!1}return this.#Se(r),this.#pe(!0),this.#re("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(e=>e.id===r.id)??r}updateConfig(e){let t=this.config.features?.artifacts?.display,r={...this.config,...e},n=function(e,t){let r=e.voiceRecognition,n=t.voiceRecognition;return!0===r?.enabled!=(!0===n?.enabled)||r?.provider?.type!==n?.provider?.type||r?.provider?.custom!==n?.provider?.custom||r?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),o=function(e,t){return io.some(r=>e[r]!==t[r])}(this.config,r);this.config=r,n&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&$e(r.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!o)return this.client.updateConfig(r),void(a&&this.#Qe());this.#$e(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.client=new vn(this.config,this.historyInternals),a&&this.#Qe(),this.#xe(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:n,contentParts:o,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e,u={id:a??("user"===t?Dt():"assistant"===t?Ot():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:r,createdAt:s??(new Date).toISOString(),sequence:i??this.#be(),streaming:l,...void 0!==n&&{llmContent:n},...void 0!==o&&{contentParts:o},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p}};return this.upsertMessage(u),u}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:e,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:l,streaming:d=!1,voiceProcessing:c,rawContent:p}=r,u={id:s??("user"===e?Dt():"assistant"===e?Ot():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:n,createdAt:i??(new Date).toISOString(),sequence:l??this.#be(),streaming:d,...void 0!==o&&{llmContent:o},...void 0!==a&&{contentParts:a},...void 0!==c&&{voiceProcessing:c},...void 0!==p&&{rawContent:p}};t.push(u)}return this.messages=this.#ve([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:n="",llmContent:o,id:a,createdAt:s,sequence:i}=e,l={text:n,component:t,props:r};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...void 0!==o&&{llmContent:o},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}async#Ze(e,t,r){let n;try{n=await r()}catch{return}let o=n.blocks.join("\n\n"),a=[o,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=n.contentParts.length>0;if(s){let t=[];o&&t.push(Zr(o)),t.push(...n.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(Zr(a)),t.push(...n.contentParts),e.contentParts=t}else o&&(e.llmContent=a);Object.keys(n.context).length>0&&(e.mentionContext=n.context)}async sendMessage(e,t){let r=e.trim(),n=!!t?.replayFields&&(void 0!==t.replayFields.llmContent||void 0!==t.replayFields.rawContent||(t.replayFields.contextMentions?.length??0)>0);if(!(r||t?.contentParts&&0!==t.contentParts.length||t?.mentions&&0!==t.mentions.refs.length||n))return;this.#_&&!t?.voiceTurn&&(this.#_.failed=!0,this.#_=null),(this.#A||this.#I||this.#k||this.#$)&&await this.#Je(),this.stopSpeaking(),this.abortController?.abort(),this.#$e(),this.#oe++,this.#He();let o=t?.voiceTurn?.userMessageId,a=o?this.messages.find(e=>e.id===o&&"user"===e.role):void 0,s=a?.id??Dt(),i=Ot();this.#g=null;let l=t?.contentParts&&Xr(t.contentParts)?Jr:"",d={id:s,role:"user",content:r||l,createdAt:(new Date).toISOString(),sequence:this.#be(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==r&&(a.llmContent=r),this.callbacks.onMessagesChanged([...this.messages])):this.#Se(d),this.#pe(!0);let c=new AbortController;if(this.abortController=c,t?.mentions){let e=this.messages.find(e=>e.id===s)??d;if(await this.#Ze(e,r,t.mentions.finalize),c.signal.aborted||this.abortController!==c)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===s)??d,r=function(e){let t=function(e){let t=e?.text?.trim()??"";return t?function(e,t){let r="`".repeat(Math.max(3,function(e){let t=0;for(let r of e.split("\n")){let e=/^ {0,3}(`+)/.exec(r);e&&e[1].length>t&&(t=e[1].length)}return t}(t)+1));return`${r}${e}\n${t}\n${r}`}((e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text")(e),t):""}(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Zr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join("\n\n")}:{}}({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});r.contentParts&&(e.contentParts=r.contentParts),void 0!==r.llmContent&&(e.llmContent=r.llmContent),(r.contentParts||void 0!==r.llmContent)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(new Date).toISOString()}]:[...this.messages];try{await this.#Ye(p,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt})}catch(e){if("resuming"===this.status||this.#f)return;this.#_&&(this.#_.failed=!0);let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));if(!t){let t=co(e,this.config.errorMessage);if(t){let e={id:i,role:"assistant",createdAt:(new Date).toISOString(),content:t,sequence:this.#be()};this.#Se(e)}}this.#ce("idle"),this.#pe(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(new Error(String(e))))}}resubmitFrom(e,t){let r=function(e,t){let r=e.findIndex(e=>e.id===t);if(-1===r||"user"!==e[r].role)return null;let n=r+1;for(;n<e.length&&"user"!==e[n].role;)n+=1;return{start:r,end:n}}(this.messages,e);if(!r)return!1;let n=this.messages[r.start],o=t.replacement,a=o?o.text:n.content,s=o?o.contentParts:n.contentParts;if(!(a?.trim()||(s?.length??0)>0||!o&&(n.llmContent?.trim()?.length??0)>0))return!1;let i=o?void 0:{...void 0!==n.llmContent&&{llmContent:n.llmContent},...void 0!==n.rawContent&&{rawContent:n.rawContent},...n.mentionContext&&{mentionContext:n.mentionContext},...n.contextMentions&&{contextMentions:n.contextMentions},...n.quote&&{quote:n.quote}},l=o?this.#et(o.options):n.composerOptions,d=o?o.contentSegments:n.contentSegments,c=o?o.options?.quote:void 0,p=o?o.viaVoice:n.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,r.start),this.sendMessage(a??"",{...s?.length?{contentParts:[...s]}:{},...d?.length?{contentSegments:[...d]}:{},...l?{composerOptions:l}:{},...c?{quote:c}:{},...i&&Object.keys(i).length>0?{replayFields:i}:{},viaVoice:!0===p}),!0}#et(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#A||this.#I||this.#k||this.#$)&&await this.#Je(),this.abortController?.abort(),this.#He();let e=Ot();this.#g=null,this.#pe(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if("resuming"===this.status||this.#f)return;let r=t instanceof Error&&("AbortError"===t.name||t.message.includes("aborted")||t.message.includes("abort"));if(!r){let r=co(t,this.config.errorMessage);if(r){let t={id:e,role:"assistant",createdAt:(new Date).toISOString(),content:r,sequence:this.#be()};this.#Se(t)}}this.#ce("idle"),this.#pe(!1),this.abortController=null,r||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(new Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#g=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,n=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.#pe(!0);try{await this.client.processStream(e,this.handleEvent,t?.assistantMessageId,t?.seedContent)}catch(e){if("resuming"===this.status||this.#f)return;this.#ce("error"),0===this.webMcpResolveControllers.size&&(this.#pe(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:new Error(String(e)))}}#xe(){let e=this.config.webmcp;!0===e?.enabled&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(!0===this.config.webmcp?.autoApprove?.(e))return Promise.resolve(!0)}catch{}let t={id:"webmcp-"+ ++this.#e,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(e=>{this.webMcpApprovalResolvers.set(r,e)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let n=this.messages.find(t=>t.id===e);n?.approval&&this.upsertMessage({...n,approval:{...n.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#ne;#oe;#tt(e){let t=this.#ne??={s:this,setStreaming:e=>this.#pe(e),appendMessage:e=>this.#Se(e),nextSequence:()=>this.#be(),settleApprovalPausedToolCall:e=>this.#ae(e),resumeAfter:e=>this.#m?.executionId===e?this.#m.lastEventId:void 0},r=Hn();if(r)return e(r,t);let n=this.#oe;return Rn().then(r=>n===this.#oe?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:new Error(String(e)))})}resolveApproval(e,t,r){return this.#tt((n,o)=>n.resolveApproval(o,e,t,r))}resolveAskUserQuestion(e,t){return this.#tt((r,n)=>r.resolveAskUserQuestion(n,e,t))}resolveWebMcpToolCall(e){return this.#tt((t,r)=>t.resolveWebMcpToolCall(r,e))}persistAskUserQuestionProgress(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#se(e){let t=e.agentMetadata?.executionId,r=e.toolCall?.id;if(!t||!r){let t=this.#C;return void queueMicrotask(()=>{t===this.#C&&this.resolveWebMcpToolCall(e)})}let n=this.webMcpAwaitBatches.get(t);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,n)),!n.seen.has(r)&&(n.seen.add(r),n.snapshots.push(e))}#fe(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#C;queueMicrotask(()=>{if(e===this.#C)for(let e of[...this.webMcpAwaitBatches.keys()])this.#rt(e)})}#rt(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;1===r.length?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.#tt((t,n)=>t.resolveWebMcpToolCallBatch(n,e,r))}#$e(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.#C++}cancel(){this.abortController?.abort(),this.abortController=null,this.#He(),this.#$e(),this.#oe++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#pe(!1),this.#ce("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#He(),this.#$e(),this.#oe++,this.messages=[],this.agentExecution=null,this.#Ne(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#pe(!1),this.#ce("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#w}selectArtifact(e){this.#w=e,this.#Ce()}clearArtifacts(){this.#Ne()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,r="markdown"===e.artifactType?{id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,r),this.#w=t,this.#Ce(),!1!==e.transcript&&this.#nt(r),r}#nt(e){let t=`artifact-ref-${e.id}`,r=Fn(On(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...void 0!==e.markdown?{markdown:e.markdown}:{}}),n=this.messages.find(e=>e.id===t);if(n)return n.rawContent=r,n.streaming=!1,void this.callbacks.onMessagesChanged([...this.messages]);this.injectAssistantMessage({id:t,content:"",rawContent:r})}#Qe(){let e=!1;for(let t of this.artifacts.values()){let r=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!r)continue;let n=Fn(On(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...void 0!==t.markdown?{markdown:t.markdown}:{}});r.rawContent!==n&&(r.rawContent=n,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ne(){0===this.artifacts.size&&null===this.#w||(this.artifacts.clear(),this.#w=null,this.#Ce())}#Ce(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#w})}#ye(e){switch(e.type){case"artifact_start":"markdown"===e.artifactType?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.#w=e.id;break;case"artifact_delta":{let t=this.artifacts.get(e.id);"markdown"===t?.artifactType&&(t.markdown=(t.markdown??"")+e.artDelta);break}case"artifact_update":{let t=this.artifacts.get(e.id);"component"===t?.artifactType&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case"artifact_complete":{let t=this.artifacts.get(e.id);t&&(t.status="complete");break}default:return}this.#Ce()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#He(),this.#$e(),this.#oe++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ve(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#be()}))),this.#pe(!1),this.#ce("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:"complete"});this.#w=t,this.#Ce()}#ie(e){let t=this.agentExecution?.executionId;if(!t||!this.#g||"running"!==this.agentExecution?.status)return;let r=null===this.#m;this.#m={executionId:t,lastEventId:e,assistantMessageId:this.#g,status:"running"},this.#ot(r)}#le(){return null!==this.#m&&"function"==typeof this.config.reconnectStream&&!0!==this.abortController?.signal.aborted&&0===this.webMcpResolveControllers.size&&0===this.webMcpAwaitBatches.size&&!this.#ue()}#ue(){return this.messages.some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata?.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)}#de(){this.#f||!this.#m||"function"!=typeof this.config.reconnectStream||(this.#f=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#m}),this.#pe(!0),this.#ce("resuming"),this.#at().then(e=>{this.#f&&this.#m&&e.begin()}))}#at(){return this.#y?Promise.resolve(this.#y):(this.#b||(this.#b=so().then(({createReconnectController:e})=>{let t=e(this.#st());return this.#y=t,t}),this.#b.catch(()=>{this.#b=null})),this.#b)}#st(){let e=this;return{get config(){return e.config},getResumable:()=>e.#m,clearResumable:()=>e.#he(),getStatus:()=>e.status,setStatus:t=>e.#ce(t),setStreaming:t=>e.#pe(t),setReconnecting:t=>{e.#f=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,n)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:t=>e.#Se(t),nextSequence:()=>e.#be(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>co(new Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#f?this.#y?.wake():this.#de()}resumeFromHandle(e){if("function"!=typeof this.config.reconnectStream||this.#f)return;let t=this.#it();t||(t=Ot(),this.#Se({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#be()})),this.#g=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#m={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#de()}#it(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if("assistant"===t.role&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if("user"===t.role)break}return null}#He(){this.#f=!1,this.#y?.teardown(),this.#he()}#he(){this.#v&&(clearTimeout(this.#v),this.#v=null);let e=null!==this.#m;this.#m=null,e&&this.config.onExecutionState?.(null)}#ot(e){let t=this.config.onExecutionState;if(t){if(e)return this.#v&&(clearTimeout(this.#v),this.#v=null),void t(this.#m);this.#v||(this.#v=setTimeout(()=>{this.#v=null,this.config.onExecutionState?.(this.#m)},500))}}getResumableHandle(){return this.#m}#ce(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#pe(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||t.provider&&"browser"!==t.provider&&("runtype"!==t.provider||!t.browserFallback))return;let r=[...this.messages].reverse().find(e=>"assistant"===e.role&&e.content&&!e.voiceProcessing);if(!r||e&&!e.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id))return void this.ttsSpokenMessageIds.delete(r.id);let n=eo(r.content);n.trim()&&this.readAloud.play(r.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return _n(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=eo(t.content||"");if(!r.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:n?.voice,rate:n?.rate,pitch:n?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#ae(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,n=r&&this.messages.find(e=>e.toolCall?.id===r),o=n&&n.toolCall;if(!o||"complete"===o.status||"pending"===t.status)return;let a={...o,status:"complete",approvalStatus:t.status,completedAt:Date.now(),..."approved"===t.status?{superseded:!0}:{success:!1,error:"denied"===t.status?"Denied":"Approval timed out"}};this.upsertMessage({...n,streaming:!1,toolCall:a})}#Se(e){let t=this.#Te(e);this.messages=this.#ve([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Te(e),r=this.messages.findIndex(e=>e.id===t.id);-1!==r?(this.messages=this.messages.map((e,n)=>{if(n!==r)return e;let o={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(o.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(o.agentMetadata={...o.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&o.agentMetadata&&!o.agentMetadata.clientToolAnswer&&(o.agentMetadata={...o.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,n=t.approval;o.approval={...r,...n,executionId:n.executionId||r.executionId,toolName:n.toolName||r.toolName,description:n.description||r.description,toolType:n.toolType??r.toolType,reason:n.reason??r.reason,parameters:n.parameters??r.parameters,toolCallId:n.toolCallId??r.toolCallId}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&po(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),n=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&po(a)&&"complete"===e.toolCall?.status;(r||n||s)&&(o.agentMetadata={...o.agentMetadata??{},awaitingLocalTool:!1},o.toolCall=e.toolCall,o.streaming=e.streaming)}return o}),this.messages=this.#ve(this.messages),this.callbacks.onMessagesChanged([...this.messages])):this.#Se(t)}#Te(e){return void 0!==e.sequence?{...e}:{...e,sequence:this.#be()}}#be(){return this.#h++}#ve(e){return[...e].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o!==a?o-a:e.id.localeCompare(t.id)})}},ho={add:e=>async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;an(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}(e)},mo={allowedTypes:on,maxFileSize:10485760,maxFiles:4};function go(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var fo=class e{constructor(e={}){this.attachments=[],this.#h=null,this.#m=new Map,this.#g=!1,this.config={allowedTypes:e.allowedTypes??mo.allowedTypes,maxFileSize:e.maxFileSize??mo.maxFileSize,maxFiles:e.maxFiles??mo.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#h;#m;#g;#f(){return"function"==typeof this.config.adapter?.add}#y(){return this.#f()?this.config.adapter:ho}setPreviewsContainer(e){this.#h=e}remountPreviews(e){if(this.#h=e,e){e.innerHTML="";for(let e of this.attachments)this.#e(e)}this.#n()}updateConfig(e){void 0!==e.allowedTypes&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:mo.allowedTypes),void 0!==e.maxFileSize&&(this.config.maxFileSize=e.maxFileSize),void 0!==e.maxFiles&&(this.config.maxFiles=e.maxFiles),void 0!==e.onFileRejected&&(this.config.onFileRejected=e.onFileRejected),void 0!==e.onAttachmentsChange&&(this.config.onAttachmentsChange=e.onAttachmentsChange),void 0!==e.adapter&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>"ready"===e.status)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>null!==e)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||0===e.length||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#g)return;let t=[];for(let r of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(r,"count");continue}let e=sn(r,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes("type")?"type":"size";this.config.onFileRejected?.(r,t);continue}let n={id:go(),file:r,previewUrl:an(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#f()?"uploading":"processing",progress:this.#f()?0:void 0};this.attachments.push(n),this.#e(n),t.push(n)}this.#n(),this.#C(),await Promise.all(t.map(e=>this.#b(e)))}async#b(e){let t=new AbortController;this.#m.set(e.id,t);let r=()=>this.#g||t.signal.aborted||this.#m.get(e.id)!==t||!this.attachments.includes(e);try{let n=await this.#y().add(e.file,{signal:t.signal,onProgress:t=>{r()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#t(e),this.#C())}});if(r())return;e.contentPart=n,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(r())return;e.status="error",e.progress=void 0,e.error=t instanceof Error?t.message:String(t??"Upload failed")}finally{this.#m.get(e.id)===t&&this.#m.delete(e.id)}this.#t(e),this.#C()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||"error"!==t.status||this.#g||(t.status=this.#f()?"uploading":"processing",t.progress=this.#f()?0:void 0,t.error=void 0,this.#t(t),this.#C(),this.#b(t))}#v(e){let t=this.#m.get(e);t&&(this.#m.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(-1===t)return;let r=this.attachments[t];this.#v(e),r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let n=this.#h?.querySelector(`[data-attachment-id="${e}"]`);n&&n.remove(),"ready"===r.status&&r.contentPart&&this.#w(r.contentPart),this.#n(),this.#C()}#w(e){let t=this.config.adapter?.remove;if(t)try{let r=t(e,{signal:(new AbortController).signal});r&&"function"==typeof r.catch&&r.catch(e=>{console.error("[AttachmentManager] adapter.remove failed:",e)})}catch(e){console.error("[AttachmentManager] adapter.remove failed:",e)}}clearAttachments(){for(let e of this.attachments)this.#v(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#m.clear(),this.#h&&(this.#h.innerHTML=""),this.#n(),this.#C()}destroy(){if(!this.#g){this.#g=!0;for(let e of this.#m.values())e.abort();this.#m.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#h=null}}#C(){this.#g||this.config.onAttachmentsChange?.(this.getAttachments())}#e(e){if(!this.#h)return;let t=an(e.file),r=ne("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let t=ne("img");t.src=e.previewUrl,t.alt=e.file.name,t.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",t.style.width="48px",t.style.height="48px",t.style.objectFit="cover",t.style.borderRadius="8px",r.appendChild(t)}else{let t=ne("div");t.style.width="48px",t.style.height="48px",t.style.borderRadius="8px",t.style.backgroundColor="var(--persona-container, #f3f4f6)",t.style.border="1px solid var(--persona-border, #e5e7eb)",t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="center",t.style.justifyContent="center",t.style.gap="2px",t.style.overflow="hidden";let n=function(e){return"application/pdf"===e||e.startsWith("text/")||e.includes("word")?S:e.includes("excel")||e.includes("spreadsheet")?C:"application/json"===e?x:k}(e.file.type),o=I(n,20,"var(--persona-muted, #6b7280)",1.5);o&&t.appendChild(o);let a=ne("span");a.textContent=function(e,t){let r=function(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}(e.file.type,e.file.name),a.style.fontSize="8px",a.style.fontWeight="600",a.style.color="var(--persona-muted, #6b7280)",a.style.textTransform="uppercase",a.style.lineHeight="1",t.appendChild(a),r.appendChild(t)}let n=oe("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),o=ne("div","persona-attachment-progress");o.appendChild(ne("div","persona-attachment-progress__bar"));let a=oe("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),s=xe("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);s?a.appendChild(s):a.textContent="↻",a.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),n.append(o,a),r.appendChild(n);let i=ne("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");i.type="button",i.setAttribute("aria-label","Remove attachment"),i.style.position="absolute",i.style.top="-4px",i.style.insetInlineEnd="-4px",i.style.width="18px",i.style.height="18px",i.style.borderRadius="50%",i.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",i.style.border="none",i.style.cursor="pointer",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.padding="0";let l=I(M,10,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):(i.textContent="×",i.style.color="var(--persona-text-inverse, #ffffff)",i.style.fontSize="14px",i.style.lineHeight="1"),i.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(i),this.#h.appendChild(r),this.#r(r,e)}#t(e){let t=this.#h?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#r(t,e)}#r(e,t){e.dataset.status=t.status;let r="ready"!==t.status&&"error"!==t.status;e.setAttribute("aria-busy",r?"true":"false"),e.title="error"===t.status?`${t.file.name}: ${t.error??"Upload failed"}`:t.file.name;let n=e.querySelector(".persona-attachment-progress__bar");if(n){let e=t.progress;n.style.width="number"==typeof e?`${Math.round(100*e)}%`:""}}#n(){this.#h&&(this.#h.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:r,adapter:t?.adapter})}},yo=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function bo(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,r=null,n=!1,o=!1,a=()=>(r||(r=(()=>{let t=e.preparing?"preparing":e.streaming?"streaming":"idle";return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:"idle"!==t||e.sendDisabled||e.inputDisabled})})()),r),s=()=>{if(n=!1,o||0===t.size)return;let e=a();for(let r of[...t])try{r(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",e)}},i=()=>{r=null,!o&&!n&&(n=!0,queueMicrotask(s))};return{getState:a,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,i())},setAttachments:t=>{((e,t)=>e.length===t.length&&e.every((e,r)=>{let n=t[r];return e.id===n.id&&e.name===n.name&&e.mimeType===n.mimeType&&e.size===n.size&&e.status===n.status&&e.progress===n.progress&&e.error===n.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{yo(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{yo(e.activeModeIds,t)||(e.activeModeIds=[...t],i())},setQuote:t=>{let r=e.quote;r?.text===t?.text&&r?.messageId===t?.messageId&&r?.sourceLabel===t?.sourceLabel||(e.quote=t?{...t}:void 0,i())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,i())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,i())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,i())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,i())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,i())},flush:()=>{n&&s()},destroy:()=>{o=!0,n=!1,t.clear()}}}var vo=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},wo=(e,t)=>{let r=ne("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r},xo=8,Co=8,So=200,ko=300,Ao=0,Mo=e=>Math.max(0,e),Io=new WeakMap,To="data-persona-tooltip-suppressed",Eo=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Lo=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Po=[...["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 Bo(e){Io.get(e.anchor)?.destroy();let t,{anchor:r,trigger:n=r,text:o,hint:a,enabled:s=!0,gap:i=xo,viewportPadding:l=Co}=e,d=()=>r.ownerDocument,c=()=>d().defaultView??window,p=null,u=null,h=null,m=null,g=!1,f=!1,y=!1,b=()=>("function"==typeof o?o():o).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>Mo(e.delayMs??So),x=()=>{void 0!==t&&(c().clearTimeout(t),t=void 0)},C=()=>{x();let t=null!==p;m?.(),m=null,p?.remove(),p=null,u=null,h=null,t&&(e=>{Ao=e>0?Date.now()+e:0})(Mo(e.skipDelayMs??ko))},S=()=>{if(!p)return;let e=d(),t=c(),n=r.getBoundingClientRect(),o=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-o.width,h=n.left+n.width/2-o.width/2,m=Lo(h,l,u),g=n.top-l,f=s-l-n.bottom,y=g>=o.height+i||g>=f?"top":"bottom",b="top"===y?n.top-i-o.height:n.bottom+i,v=s-l-o.height,w=Lo(b,l,v),x=n.left+n.width/2,C=Math.max(10,o.width-10),S=Lo(x-m,10,C);p.dataset.placement=y,p.style.left=`${m}px`,p.style.top=`${w}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${S}px`)},k=()=>{if(y||!s||p||!r.isConnected||(e=>"function"==typeof e.closest&&null!==e.closest(`[${To}]`))(r))return;let e=b(),t=(e=>{let t=e.getRootNode?.();return Eo(t)?t:e.ownerDocument.body})(r);if(!e||!t)return;let n=d(),o=c();p=n.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(un);let a=o.getComputedStyle?.(r);if(a){for(let e of Po){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=n.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=n.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=n.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),S(),p.dataset.state="open";let g=()=>{r.isConnected?(u&&(u.textContent=b()),h&&(h.textContent=v()),S()):C()};o.addEventListener("scroll",g,!0),o.addEventListener("resize",g);let f=r.getRootNode(),w=Eo(f)?f:n.documentElement,x=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||C()});x?.observe(w,{childList:!0,subtree:!0}),m=()=>{o.removeEventListener("scroll",g,!0),o.removeEventListener("resize",g),x?.disconnect()}},A=()=>{g||f?(e=>{if(!y&&!p){if(x(),e||w()<=0||Date.now()<Ao)return void k();t=c().setTimeout(()=>{t=void 0,k()},w())}})(f):C()},M=()=>{let e=c();(!e.matchMedia||!e.matchMedia("(hover: none)").matches)&&(g=!0,A())},I=()=>{g=!1,A()},T=()=>{try{f=r.matches(":focus-visible")}catch{f=!0}A()},E=()=>{f=!1,A()},L=()=>{g=!1,f=!1,C()},P=e=>{"Escape"===e.key&&L()};n.addEventListener("mouseenter",M),n.addEventListener("mouseleave",I),r.addEventListener("focus",T),r.addEventListener("blur",E),r.addEventListener("keydown",P),r.addEventListener("click",L);let B={get isOpen(){return null!==p},show:k,hide:C,reposition:S,destroy:()=>{y||(y=!0,C(),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",I),r.removeEventListener("focus",T),r.removeEventListener("blur",E),r.removeEventListener("keydown",P),r.removeEventListener("click",L),Io.delete(r))}};return Io.set(r,B),B}function No(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let r=t.getComputedStyle(e).lineHeight;if(!r||!r.trim().endsWith("px"))return 20;let n=parseFloat(r);return Number.isFinite(n)&&n>0?n:20}function Ro(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Ho(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||"function"!=typeof t.matchMedia)return!1;try{return!0===t.matchMedia("(pointer: coarse)").matches}catch{return!1}}function $o(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function Wo(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"!==(e.submitKey??"enter")||$o(e)?"enter":"send"}(t))}function Do(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let n=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};n("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),n("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),n("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),n("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function Oo(e){return!0===e?{disabled:!0}:e&&"object"==typeof e?{disabled:!0,reason:"string"==typeof e.reason&&e.reason?e.reason:void 0}:{disabled:!1}}var Fo="persona-composer-control",zo="persona-composer-control--glyph",qo=24,jo=(e,t,r)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let o=n.getComputedStyle(e);for(let e of r){let r=o.getPropertyValue(e).trim();r?t.style.setProperty(e,r):t.style.removeProperty(e)}},_o=(e,t)=>{let r=ne("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??U,r.dir="auto",Wo(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ho(r)}),Do(r,e?.composer?.inputAttributes),r.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",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=Ro(e?.composer?.maxLines,t?.defaultMaxLines??3),o=20*n+"px";return r.style.maxHeight=o,r.style.overflowY="auto",r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:()=>{r.addEventListener("input",()=>{r.style.height="auto";let e=Math.min(r.scrollHeight,(()=>{let e=r.style.maxHeight;if(e!==o){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=n*No(r);return o=`${t}px`,r.style.maxHeight=o,t})());r.style.height=`${e}px`})}}},Vo=(e,t,r="send")=>{let n=oe("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":r,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Uo=e=>{let t=e?.sendButton??{},r=t.useIcon??!1,n=t.iconText??"↑",o=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",l=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,p=t.size,u=parseFloat(p??"")||40,h=t.backgroundColor,m=t.textColor,g=ne("div","persona-send-button-wrapper"),f=oe("button",{className:ae("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?`persona-flex persona-items-center persona-justify-center ${Fo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!h&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:r?p:void 0,height:r?p:void 0,minWidth:r?p:void 0,minHeight:r?p:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":m||void 0,backgroundColor:r&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:r?"0":t.paddingX||void 0,paddingRight:r?"0":t.paddingX||void 0,paddingTop:r?"0":t.paddingY||void 0,paddingBottom:r?"0":t.paddingY||void 0}}),y=null,b=null,v=null;if(r){let e=parseFloat(t.iconSize??"")||Math.round(.5*u),r=t.iconStrokeWidth??2,s=m?.trim()||"currentColor";if(o&&(y=xe(o,e,s,r)),b=xe(a,e,s,r),!t.iconSize)for(let t of[y,b])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);y&&b?(v=Vo(y,b),f.appendChild(v)):y?f.appendChild(y):(f.textContent=n,b=null)}else f.textContent=l;f.setAttribute("aria-label",s),g.appendChild(f),Bo({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??"",enabled:c});let w="send";return{button:f,wrapper:g,setMode:e=>{if(e===w)return;w=e;let t="stop"===e?i:s;f.setAttribute("aria-label",t),f.setAttribute("data-persona-send-mode",e),r?(f.querySelector("[data-persona-glyph-stack]")??v)?.setAttribute("data-mode",e):f.textContent="stop"===e?d:l},glyphStack:v}},Ko=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled)return null;let r=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),n="runtype"===t.provider?.type,o="custom"===t.provider?.type;if(!(r||n||o))return null;let a=t.iconName??"mic",s=t.iconSize,i=parseFloat(s??"")||qo,l=t.backgroundColor??e?.sendButton?.backgroundColor,d=t.iconColor??e?.sendButton?.textColor,c=ne("div","persona-send-button-wrapper"),p=oe("button",{className:ae("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fo,!s&&zo),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",color:d||"var(--persona-text, #111827)",backgroundColor:l||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}}),u=xe(a,i,d||"currentColor",1.5);u?p.appendChild(u):p.textContent="🎤",c.appendChild(p);let h=t.tooltipText??"Start voice recognition",m=t.showTooltip??!1;return Bo({anchor:p,trigger:c,text:()=>p.getAttribute("aria-label")??h,enabled:m}),{button:p,wrapper:c}},Jo=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=ne("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let n=ne("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??on).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let o=t.buttonIconName??"paperclip",a=ne("div","persona-send-button-wrapper"),s=oe("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Fo} ${zo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=xe(o,qo,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),n.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Bo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:n,previewsContainer:r}},Go=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",n=ne("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status",""),Re(n,t,"idle");let o=t.idleText??"Online";if(t.idleLink){let e=ne("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=o,e.style.color="inherit",e.style.textDecoration="none",n.appendChild(e)}else n.textContent=o;return n},Yo=()=>oe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Xo(e){let{anchor:t,content:r,placement:n="bottom-start",offset:o=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:i,zIndex:l=2147483e3,onOpen:d,onDismiss:c}=e,p=e.container??function(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}(t),u=!1,h=null,m=()=>{if(!u)return;let e=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${e.width}px`),s&&(r.style.maxWidth=`${e.width}px`);let l=r.getBoundingClientRect(),d=i?.()??null,c=null!=d?e.top+d:e.top,p="top-start"===n||"top-end"===n?c-o-l.height:e.bottom+o,h="bottom-end"===n||"top-end"===n?e.right-l.width:e.left,m=s?.()??null;if(null!=m){let t=Math.max(e.left,e.right-l.width);h=Math.min(Math.max(e.left+m,e.left),t)}r.style.top=`${p}px`,r.style.left=`${h}px`},g=()=>{u&&(u=!1,h&&(h(),h=null),r.remove())},f=()=>{if(u)return;u=!0,null!=l&&(r.style.zIndex=String(l)),p.appendChild(r),m();let e=(t.ownerDocument??document).defaultView??window,n=t.ownerDocument??document,o=()=>{if(!t.isConnected)return g(),void c?.("anchor-removed");m()},a=e=>{let n="function"==typeof e.composedPath?e.composedPath():[];n.includes(r)||n.includes(t)||(g(),c?.("outside"))},s=e.setTimeout(()=>{n.addEventListener("pointerdown",a,!0)},0);e.addEventListener("scroll",o,!0),e.addEventListener("resize",o),h=()=>{e.clearTimeout(s),n.removeEventListener("pointerdown",a,!0),e.removeEventListener("scroll",o,!0),e.removeEventListener("resize",o)},d?.()};return{get isOpen(){return u},open:f,close:g,toggle:()=>u?g():f(),reposition:m,destroy:g}}var Qo=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Zo="data-persona-menu-focus",ea=new Set(["ArrowDown","ArrowUp","Home","End"]);function ta(e){return"menuitem"===e.getAttribute("role")?e:e.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??e}var ra=1e3,na="data-persona-composer-action",oa="data-persona-composer-disable-when-streaming";function aa(e){let t=e.clientWidth;if(!t)return 0;let r=e.ownerDocument?.defaultView;if(!r?.getComputedStyle)return t;let n=r.getComputedStyle(e),o=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-o)}var sa=(e,t)=>{!e||typeof console>"u"||console.warn(t)},ia=e=>"plugin"===e.source?`plugin "${e.pluginId}"`:"config"===e.source?"composer.actions":"a core built-in",la=(e,t,r)=>void 0===e?r:"function"==typeof e?!0===e(t):!0===e;function da(e,t){if(!e||"always"===e)return!0;let r=(e=>"streaming"===e.phase||e.text.trim().length>0||e.attachments.length>0)(t);return"when-text"===e?r:!r}var ca=e=>"custom"===e.kind,pa=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e;function ua(e){let t=new Map,r=[],n=!1,o=()=>e.getButtonSize?.(),a=(e,t)=>{let r=e.button;if(!r)return;if(r.setAttribute("aria-label",t.label),void 0===t.pressed?r.removeAttribute("aria-pressed"):r.setAttribute("aria-pressed",t.pressed?"true":"false"),r.toggleAttribute(oa,!0===t.disableWhenStreaming),"menu"===e.mode)return e.tooltip?.destroy(),e.tooltip=void 0,void((e,t)=>{let r=e.button;if(!r)return;r.setAttribute("role","menuitem"),r.setAttribute("tabindex","-1"),r.className="persona-composer-overflow-menu__item";for(let e of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])r.style[e]="";r.style.lineHeight="1",t.tooltipText?r.setAttribute("title",t.tooltipText):r.removeAttribute("title"),r.replaceChildren();let n=ne("span","persona-composer-overflow-menu__icon");if(t.iconName){let e=xe(t.iconName,16,"currentColor",1.5);e&&n.appendChild(e)}let o=ne("span","persona-composer-overflow-menu__label");o.textContent=t.shortLabel??t.label,r.append(n,o)})(e,t);r.removeAttribute("role"),r.removeAttribute("tabindex"),r.removeAttribute("title");let n=o(),a=!!t.shortLabel;if(r.className=ae("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Fo,zo,a&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),r.style.width=n&&!a?n:"",r.style.height=n??"",r.style.minWidth=n&&!a?n:"",r.style.minHeight=n??"",r.style.fontSize=a?"":"18px",r.style.lineHeight="1",r.style.color=t.iconColor??"",r.style.backgroundColor=t.backgroundColor??"",r.replaceChildren(),t.iconName){let e=xe(t.iconName,qo,"currentColor",1.5);e&&r.appendChild(e)}if(a){let e=ne("span","persona-composer-action-button__label");e.textContent=t.shortLabel,r.appendChild(e)}else r.firstChild||(r.textContent=t.label);e.tooltip?.destroy(),e.tooltip=Bo({anchor:r,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,r)=>{let n=t.action,o=oe("button",{attrs:{type:"button"}}),s=o;if("bar"===r){let e=ne("div","persona-send-button-wrapper");e.appendChild(o),s=e}s.setAttribute(na,t.id);let i={resolved:t,element:s,button:o,owned:!0,managed:!0,busy:!1,visible:!0,mode:r},l=t=>{if(t.preventDefault(),t.stopPropagation(),i.busy||o.disabled)return;let r,n=i.resolved.action;"menu"===i.mode&&p?.close(!0);try{r=n.onSelect(e.actionContext,t)}catch(t){return void e.reportError(t,{actionId:i.resolved.id})}!r||"function"!=typeof r.then||(i.busy=!0,o.setAttribute("aria-busy","true"),r.catch(t=>{e.reportError(t,{actionId:i.resolved.id})}).finally(()=>{i.busy=!1,o.removeAttribute("aria-busy")}))};return o.addEventListener("click",l),i.detach=()=>o.removeEventListener("click",l),a(i,n),i},i=(t,r)=>{if(t.builtIn){let e=t.builtIn.element;return e?{resolved:t,element:e,owned:!1,managed:!0===t.builtIn.managed,busy:!1,visible:!0,mode:"bar"}:null}let n=t.action;return n?ca(n)?(t=>{let r,n=t.action;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(r){return e.reportError(r,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(na,t.id),r.element.toggleAttribute(oa,!0===n.disableWhenStreaming),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:"bar"}):null})(t):s(t,r):null},l=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(r){e.reportError(r,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let r=0;r<t.length;r++){let n=t[r];if(!n.managed)continue;let o=null;for(let n=r+1;n<t.length;n++){let r=t[n];if(!r.managed&&r.element.parentElement===e){o=r.element;break}}o?(n.element.parentElement!==e||n.element.nextSibling!==o)&&e.insertBefore(n.element,o):e.lastChild!==n.element&&e.appendChild(n.element)}},c=(e,t)=>{if(e.button)return void(e.button.disabled=t);if(!e.owned)return;let r=e.element;r.toggleAttribute("data-disabled",t),r.setAttribute("aria-disabled",t?"true":"false");let n=r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement?r:r.querySelector("button, select, input, textarea");n&&(n.disabled=t)},p=null,u=null,h=null,m=0,g=(e,t,r)=>{if(!t)return"bar";if(e.resolved.builtIn){let r=(e=>"core:attachment"===e?"attachments":e.startsWith("core:mention")?"mentions":null)(e.resolved.id);return r&&t.includeBuiltIns?.includes(r)?"menu":"bar"}let n=e.resolved.presentation;return"overflow"===n||"auto"===n&&r?"menu":"bar"},f=e=>{let t=e.menuSlot;if(!t)return;if(!(e=>0===function(e){let t="",r=e=>{if(e.nodeType===Node.TEXT_NODE)return void(t+=e.nodeValue??"");if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e;"function"==typeof n.matches&&n.matches('.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]')||e.childNodes.forEach(r)};return r(e),t.trim()}(e).length)(e.element))return e.menuLabel?.remove(),void(e.menuLabel=void 0);let r=(e=>{let t=pa(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""})(e.element);if(!r)return e.menuLabel?.remove(),void(e.menuLabel=void 0);e.menuLabel||(e.menuLabel=ne("span","persona-composer-overflow-menu__label")),e.menuLabel.textContent!==r&&(e.menuLabel.textContent=r),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)},y=(e,r)=>{if(e.mode===r)return e;let n=e.resolved.action;if(n&&!ca(n)){l(e),t.delete(e.resolved.id);let n=s(e.resolved,r);return t.set(e.resolved.id,n),n}if("menu"===r){let t=oe("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[To]:""}});t.appendChild(e.element),function(e){Io.get(e)?.hide()}(pa(e.element)),e.menuSlot=t;let r=t=>{let r=pa(e.element);if(r.disabled)return;let n=t.target===r||r.contains(t.target);p?.close(!0),n||r.click()};t.addEventListener("click",r,!0),e.detachMenuSlot=()=>t.removeEventListener("click",r,!0),e.managed=!0,f(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=r,e},b=()=>{if(n)return;let a=e.getBindings();if(!a)return;let s=e.getState(),i="streaming"===s.phase,l=(()=>{let t=e.getOverflow?.();return!0===t?.enabled?t:void 0})();l&&(e=>{u!==e&&(h?.disconnect(),u=e,m=aa(e),!(typeof ResizeObserver>"u")&&(h=new ResizeObserver(t=>{let r=t[t.length-1]?.contentRect?.width??aa(e);r!==m&&(m=r,b())}),h.observe(e)))})(a.footer);let v=!!l&&((e,t)=>{let r=function(e,t){if(void 0===e)return null;if("number"==typeof e)return Number.isFinite(e)?e:null;let r=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(r))return r;let n=ne("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let o=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(o)&&o>0?o:Number.isFinite(r)?r:null}(e.collapseAutoActionsBelow,t);if(null===r)return!1;let n=m||aa(t);return n>0&&n<r})(l,a.footer),w={start:[],end:[]},x=[];for(let e of r){let r=t.get(e.id);if(!r)continue;let n=e.action,o=!n||la(n.visible,s,!0)&&da(n.visibility,s);if(r.visible!==o&&(r.visible=o,!o&&r.managed&&(r.menuSlot??r.element).remove()),o){if(r=y(r,g(r,l,v)),n){let e=la(n.disabled,s,!1)||!0===n.disableWhenStreaming&&i;c(r,e),!ca(n)&&void 0!==n.pressed&&r.button?.setAttribute("aria-pressed",n.pressed?"true":"false")}"menu"===r.mode?(f(r),x.push(r)):w[e.placement].push(r)}}if(x.length>0){let t=(p?p.setLabel(e.getOverflowLabel?.()??"More actions"):p=function(e){let t=e.label,r=!1,n=ne("div","persona-send-button-wrapper"),o=oe("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Fo} ${zo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(o);let a=oe("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),s=()=>{let t=e.getButtonSize?.()??"";o.style.width=t,o.style.height=t,o.style.minWidth=t,o.style.minHeight=t,o.style.lineHeight="1",o.replaceChildren();let r=xe("plus",qo,"currentColor",1.5);r?o.appendChild(r):o.textContent="+"},i=()=>{o.setAttribute("aria-label",t),o.setAttribute("title",t),a.setAttribute("aria-label",t)};i(),s();let l=[],d=-1,c=!1,p=()=>{let e=(()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null})();for(let t of l){let r=!!e&&ta(t)===e;t.toggleAttribute(Zo,r&&c)}},u=()=>l.filter(e=>e.isConnected||a.contains(e)).map(ta).filter(e=>!(e=>!0===e.disabled||"true"===e.getAttribute("aria-disabled"))(e)),h=(e,t)=>{e.forEach((e,r)=>{e.setAttribute("tabindex",r===t?"0":"-1")})},m=e=>{let t=u();if(0===t.length)return;let r=(e%t.length+t.length)%t.length;d=r,h(t,r),t[r].focus(),p()},g=()=>n.ownerDocument??document,f=null,y=null,b=null,v=()=>{f&&(g().removeEventListener("focusin",f,!0),f=null)},w=()=>{y&&(a.removeEventListener("focusin",y),y=null),b&&(a.removeEventListener("pointerdown",b,!0),b=null)},x=null,C=()=>!0===x?.isOpen,S=(e=!1)=>{if(C()){x?.close(),o.setAttribute("aria-expanded","false"),v(),w(),d=-1,c=!1;for(let e of l)e.removeAttribute(Zo);e&&o.focus()}},k=(e=0,t=!1)=>{if(r||C())return;c=t,jo(o,a,Qo),(x||(x=Xo({anchor:o,content:a,placement:"top-start",offset:6,onDismiss:()=>{o.setAttribute("aria-expanded","false"),v()}})),x).open(),o.setAttribute("aria-expanded","true");let s=u();h(s,-1),m(e<0?s.length-1:e),f=e=>{let t="function"==typeof e.composedPath?e.composedPath():[];t.includes(a)||t.includes(n)||S()},g().addEventListener("focusin",f,!0),y=()=>p(),a.addEventListener("focusin",y),b=()=>{c=!1},a.addEventListener("pointerdown",b,!0)},A=e=>{e.preventDefault(),e.stopPropagation(),C()?S(!0):k(0)},M=e=>{if("ArrowDown"===e.key||"Enter"===e.key||" "===e.key)return e.preventDefault(),c=!0,void(C()?m(0):k(0,!0));"ArrowUp"===e.key&&(e.preventDefault(),c=!0,C()?m(-1):k(-1,!0))},I=e=>{switch(ea.has(e.key)&&(c=!0),e.key){case"ArrowDown":return e.preventDefault(),void m(d+1);case"ArrowUp":return e.preventDefault(),void m(d-1);case"Home":return e.preventDefault(),void m(0);case"End":return e.preventDefault(),void m(u().length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void S(!0);case"Tab":return void S(!0)}};return o.addEventListener("click",A),o.addEventListener("keydown",M),a.addEventListener("keydown",I),{trigger:n,triggerButton:o,panel:a,setItems:e=>{for(let t of l)e.includes(t)||t.removeAttribute(Zo);if(l=[...e],!C())return;let t=u();h(t,Math.min(d,t.length-1)),p()},isOpen:C,open:()=>k(0),close:S,setLabel:e=>{e!==t&&(t=e,i())},applyButtonSize:s,destroy:()=>{r=!0,v(),w(),o.removeEventListener("click",A),o.removeEventListener("keydown",M),a.removeEventListener("keydown",I),x?.destroy(),x=null,n.remove(),a.remove(),l=[]}}}({label:e.getOverflowLabel?.()??"More actions",getButtonSize:o}),p);((e,t)=>{let r=t.map(e=>e.menuSlot??e.element);for(r.forEach((t,r)=>{let n=e.children[r];n!==t&&(n?e.insertBefore(t,n):e.appendChild(t))});e.children.length>r.length;)e.lastElementChild?.remove()})(t.panel,x),t.setItems(x.map(e=>e.menuSlot??e.element)),t.applyButtonSize();let r=Number.isFinite(l?.order)?l?.order:900,n=w.start.findIndex(e=>e.resolved.order>r),a={resolved:{id:"core:overflow",placement:"start",presentation:"bar",order:r,sequence:-1,source:"core"},element:t.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};w.start.splice(n<0?w.start.length:n,0,a)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(a.actionsStart,w.start),d(a.actionsEnd,w.end)};return{resolve:()=>{if(n)return;let o=function(e){let{debug:t}=e,r=[],n=new Map,o=0,a=e=>{let o=n.get(e.id);o?sa(t,`[Persona] composer action "${e.id}" is already contributed by ${ia(o)}; the ${ia(e)} copy is ignored.`):(n.set(e.id,e),r.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:"bar",order:t.order,sequence:o++,source:"core",builtIn:t});let s=(e,r,n)=>{let s=n?((e,t)=>t.includes(":")?t:`${e}:${t}`)(n,e.id):e.id,i=e.order??500;"end"===e.placement&&i>=ra&&(sa(t,`[Persona] composer action "${s}" ordered at ${i} would render after send; clamped to 999.`),i=999),a({id:s,placement:e.placement,presentation:e.presentation??"bar",order:i,sequence:o++,source:r,pluginId:n,action:e})};for(let t of e.configActions??[])s(t,"config");for(let t of e.plugins){if(!t.contributeComposerActions)continue;let r;try{r=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<"u"&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of r??[])s(e,"plugin",t.id)}return r.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}(e.collect()),s=new Set(o.map(e=>e.id));for(let[e,r]of t)s.has(e)||(l(r),t.delete(e));for(let e of o){let r=t.get(e.id);if(!r){let r=i(e,"bar");r&&t.set(e.id,r);continue}let n=r.resolved.action,o=e.action;if(!!n!=!!o||n&&o&&ca(n)!==ca(o)||n&&o&&ca(n)&&ca(o)&&n.render!==o.render){l(r),t.delete(e.id);let n=i(e,r.mode);n&&t.set(e.id,n);continue}r.resolved=e,e.builtIn?(r.managed=!0===e.builtIn.managed||"menu"===r.mode,e.builtIn.element&&"bar"===r.mode&&(r.element=e.builtIn.element)):o&&!ca(o)?a(r,o):o&&r.element.toggleAttribute(oa,!0===o.disableWhenStreaming)}r=o,b()},sync:b,getResolved:()=>r,getOverflowMenu:()=>p,destroy:()=>{if(!n){n=!0,h?.disconnect(),h=null,u=null;for(let e of t.values())l(e);t.clear(),p?.destroy(),p=null,r=[]}}}}var ha=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],ma=()=>({wrapper:oe("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),chevron:oe("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}})});function ga(e){let t=e.label??"Model",r=e.presentation??"native",n=null,o=t=>{let r=e.getSelectedModelId();return t.find(e=>e.id===r)??t[0]};return{action:{id:"core:model",kind:"custom",placement:"end",order:700,presentation:"popover"===r?"bar":"auto",label:t,render:()=>"popover"===r?(()=>{let r=oe("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),a=ne("span","persona-composer-model-picker-label"),s=ne("span","persona-composer-model-picker-suffix");r.append(a,s);let i=oe("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),l=new Map,d="",c=null,p=()=>!0===c?.isOpen,u=(e=!1)=>{p()&&(c?.close(),r.setAttribute("aria-expanded","false"),e&&r.focus())},h=e=>{let t=[...l.values()];0!==t.length&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(p())return;c||(c=Xo({anchor:r,content:i,placement:"top-start",offset:6,onDismiss:()=>r.setAttribute("aria-expanded","false")})),jo(r,i,ha),c.open(),r.setAttribute("aria-expanded","true");let n=[...l.keys()].indexOf(o(e.getModels())?.id??"");h(t??(n>=0?n:0))},g=t=>{t.preventDefault(),t.stopPropagation();let r=t.currentTarget.getAttribute("data-persona-model-option");r&&(t=>{u(!0),e.onSelect(t)})(r)},f=()=>{let n=e.getModels(),c=n.map(e=>`${e.id}:${e.label}:${e.icon??""}:${e.description??""}`).join("|");if(c!==d){d=c;for(let e of l.values())e.removeEventListener("click",g);l.clear(),i.replaceChildren(...n.map(e=>{let t=(e=>{let t=oe("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":e.id}});if(e.icon){let r=xe(e.icon,16,"currentColor",1.5);if(r){let e=ne("span","persona-composer-model-option-icon");e.appendChild(r),t.appendChild(e)}}let r=ne("span","persona-composer-model-option-body"),n=ne("span","persona-composer-model-option-label");if(n.textContent=e.label,r.appendChild(n),e.description){let t=ne("span","persona-composer-model-option-description");t.textContent=e.description,r.appendChild(t)}t.appendChild(r);let o=ne("span","persona-composer-model-option-check");o.setAttribute("aria-hidden","true");let a=xe("check",16,"currentColor",2);return a&&o.appendChild(a),t.appendChild(o),t.addEventListener("click",g),t})(e);return l.set(e.id,t),t}))}let p=o(n);for(let[e,t]of l)t.setAttribute("aria-selected",String(e===p?.id));a.textContent=p?.label??"";let u=e.getSuffix?.()??"";s.textContent=u,r.setAttribute("aria-label",[t,[p?.label,u].filter(Boolean).join(" ")].filter(Boolean).join(": "))};f(),n=f;let y=e=>{e.preventDefault(),e.stopPropagation(),p()?u(!0):m()},b=e=>{if("ArrowDown"===e.key)return e.preventDefault(),void(p()?h(0):m(0));"ArrowUp"===e.key&&(e.preventDefault(),p()?h(-1):m(-1))},v=e=>{let t=[...l.values()],r=t.indexOf(e.target?.closest?.(".persona-composer-model-option"));switch(e.key){case"ArrowDown":return e.preventDefault(),void h(r+1);case"ArrowUp":return e.preventDefault(),void h(r-1);case"Home":return e.preventDefault(),void h(0);case"End":return e.preventDefault(),void h(t.length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void u(!0);case"Tab":return void u(!0)}};r.addEventListener("click",y),r.addEventListener("keydown",b),i.addEventListener("keydown",v);let{wrapper:w,chevron:x}=ma();return w.append(r,x),{element:w,destroy:()=>{n===f&&(n=null),r.removeEventListener("click",y),r.removeEventListener("keydown",b),i.removeEventListener("keydown",v);for(let e of l.values())e.removeEventListener("click",g);l.clear(),c?.destroy(),c=null,i.remove()}}})():(()=>{let r=oe("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),a="",s=()=>{let t=e.getModels(),n=t.map(e=>`${e.id}:${e.label}`).join("|");n!==a&&(a=n,r.replaceChildren(...t.map(e=>{let t=oe("option",{attrs:{value:e.id}});return t.textContent=e.label,t}))),r.value=o(t)?.id??""};s(),n=s;let i=()=>{r.value&&e.onSelect(r.value)};r.addEventListener("change",i);let l=e=>e.stopPropagation();r.addEventListener("click",l);let{wrapper:d,chevron:c}=ma();return d.append(r,c),{element:d,destroy:()=>{n===s&&(n=null),r.removeEventListener("change",i),r.removeEventListener("click",l)}}})()},repaint:()=>n?.()}}var fa="[data-persona-composer-chip-row]";function ya(e){e.style.display=e.childElementCount>0?"flex":"none"}function ba(e){let t=e.querySelector(fa);if(t)return t;let r=oe("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(r,n):e.appendChild(r),r}var va=e=>`core:mode:${e}`,wa=e=>Math.min(300+e,499),xa=e=>`core:mode-group:${e}`;function Ca(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}function Sa(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function ka(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function Aa(e,t){return!1===t?{status:"canceled"}:t&&"object"==typeof t?("string"==typeof t.text&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"}):{status:"proceed"}}var{setLoader:Ma,load:Ia}=se({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ta=Ma,Ea=Ia,{setLoader:La,load:Pa}=se({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Ba=La,Na=Pa;function Ra(e){let{config:t,onOpen:r}=e,n=t.buttonIconName??"plus",o=t.buttonTooltipText??"Add context",a=ne("div","persona-send-button-wrapper"),s=oe("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Fo} ${zo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":o,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=xe(n,qo,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Bo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??o}),{button:s,wrapper:a}}var Ha=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),$a={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"},Wa="16px",Da="transparent",Oa=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=0===t?"0px":t/4+"rem";return e})(),Fa={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"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:Oa,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"}},za={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"}},qa={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:j,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Wa,canvasBackground:Da,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",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"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},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"}}},ja=Fa.colors.gray,_a={...Fa,colors:{...Fa.colors,gray:ja}},Va={...Fa,colors:{...Fa.colors,gray:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"}},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},Ua=_a,Ka=za,Ja={...za,colors:{...za.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...za.typography,fontSize:"14px",lineHeight:"1.5"}},Ga=Ka,Ya=qa,Xa={...qa,launcher:$a,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...qa.input,borderRadius:"palette.radius.full"},introCard:{...qa.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...qa.suggestion.chip,fontWeight:"400"},card:{...qa.suggestion.card,fontWeight:"400"},list:{...qa.suggestion.list,fontWeight:"400"}},panel:{...qa.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...qa.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...qa.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...qa.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...qa.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...qa.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}},Qa=Ya,Za=e=>"v5"===(e=>Q({future:e}))(e)?{palette:Va,semantic:Ja,components:Xa}:{palette:_a,semantic:Ka,components:Ya};function es(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),n=e;for(let e of r){if(null==n)return;n=n[e]}return"string"==typeof n&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?es(e,n):n}function ts(e){let t={};function r(n,o){for(let[a,s]of Object.entries(n)){let n=`${o}.${a}`;if("string"==typeof s){let r=es(e,s);void 0!==r&&(t[n]={path:n,value:r,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else"object"==typeof s&&null!==s&&r(s,n)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function rs(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:0===t.length,errors:t,warnings:r}}function ns(e,t){let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];t&&"object"==typeof t&&!Array.isArray(t)&&n&&"object"==typeof n&&!Array.isArray(n)?r[e]=ns(t,n):r[e]=n}return r}function os(e,t){return t?ns(e,t):e}function as(e,t={}){let r=Za(t.future),n={palette:r.palette,semantic:r.semantic,components:r.components},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:os(n.components,e?.components)},a=e?.components?.activity;for(let e of["toolBubble","reasoningBubble"])for(let t of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[t]&&(o.components[e][t]=a[t]);let s=e?.components?.collapsibleWidget?.surface;void 0!==s&&void 0===a?.bodySurface&&(o.components.activity={...o.components.activity,bodySurface:s});let i=e?.components?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(o.components.header.minimalPadding=o.components.header.padding);let l=e?.components?.message;if(void 0!==l?.gap&&void 0===l.fullscreenGap&&(o.components.message.fullscreenGap=o.components.message.gap),!1!==t.validate){let e=rs(o);if(!e.valid)throw new Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)o=e.transform(o);return o}var ss=e=>"0"===e.trim()?"0px":e,is="--persona-",ls=e=>{if(!e)return;let t,r=e.trim().toLowerCase();if(35===r.charCodeAt(0)){let e=r.slice(1);if(!/^[0-9a-f]+$/.test(e))return;3===e.length||4===e.length?t=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(6===e.length||8===e.length)&&(t=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=r.match(/^rgba?\(([^)]+)\)$/);if(e){let r=e[1].split(/[,/\s]+/).filter(Boolean);r.length>=3&&(t=r.slice(0,3).map(e=>{let t=e.endsWith("%"),r=parseFloat(t?e.slice(0,-1):e);return t?r/100*255:r}))}}if(!t||t.some(e=>!Number.isFinite(e)))return;let[n,o,a]=t.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)});return.2126*n+.7152*o+.0722*a},ds=.179,cs=(e,t)=>{for(let[r,...n]of t){let t;for(let r of n)if(t=61===r.charCodeAt(0)?r.slice(1):e[is+r],void 0!==t)break;void 0!==t&&(e[is+r]=t)}};function ps(e){let t=ts(e),r={};for(let[e,n]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=n.value;cs(r,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=r["--persona-components-launcher-foreground"];r["--persona-launcher-fg-muted"]=n&&n!==r["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:r["--persona-muted"],cs(r,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),cs(r,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),r["--persona-panel-border"]=r["--persona-components-panel-border"]??`1px solid ${r["--persona-border"]}`,cs(r,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),r["--persona-panel-inset"]=r["--persona-components-panel-inset"]??Wa,r["--persona-panel-canvas-bg"]=r["--persona-components-panel-canvasBackground"]??Da,cs(r,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),cs(r,[["header-bg","components-header-background","surface"]]);let o=r["--persona-header-bg"],a=r["--persona-components-header-foreground"],s=a?`color-mix(in srgb, ${a} 72%, ${o})`:void 0;r["--persona-header-border"]=r["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${o})`:void 0)??r["--persona-divider"],cs(r,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),r["--persona-header-title-fg"]=r["--persona-components-header-title-color"]??r["--persona-components-header-titleForeground"]??a??r["--persona-primary"],r["--persona-header-subtitle-fg"]=r["--persona-components-header-subtitle-color"]??r["--persona-components-header-subtitleForeground"]??s??r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=r["--persona-components-header-actionIconForeground"]??s??r["--persona-muted"],cs(r,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let i=e.components?.header;i?.shadow&&(r["--persona-header-shadow"]=i.shadow),i?.borderBottom&&(r["--persona-header-border-bottom"]=i.borderBottom),i?.minHeight&&(r["--persona-header-min-height"]=i.minHeight);let l=r["--persona-components-history-railHeader-background"];l&&(r["--persona-history-rail-header-bg"]=l);let d=r["--persona-components-history-railHeader-border"];d&&(r["--persona-history-rail-header-border"]=d);let c=r["--persona-components-history-railHeader-minHeight"];c&&(r["--persona-history-rail-header-min-height"]=c);for(let[e,t]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let n=r[`--persona-components-history-overlay-${e}`];n&&(r[`--persona-history-overlay-${t}`]=n)}for(let[e,t]of[["background","bg"],["borderRadius","radius"]]){let n=r[`--persona-components-history-menu-${e}`];n&&(r[`--persona-history-menu-${t}`]=n)}let p=e.components?.history?.motion;if(p){let e=e=>{if(void 0===e)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(p.enterDurationMs);void 0!==t&&(r["--persona-history-enter-ms"]=t);let n=e(p.exitDurationMs);void 0!==n&&(r["--persona-history-exit-ms"]=n),p.enterEasing&&(r["--persona-history-enter-easing"]=p.enterEasing),p.exitEasing&&(r["--persona-history-exit-easing"]=p.exitEasing)}let u=r["--persona-components-history-dangerForeground"];u&&(r["--persona-history-danger-fg"]=u),r["--persona-danger"]=r["--persona-components-history-confirm-dangerBackground"]??r["--persona-palette-colors-error-700"]??"#b42318",r["--persona-danger-fg"]=r["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let e of["scrim","shadow"]){let t=r[`--persona-components-history-confirm-${e}`];t&&(r[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let n=r[`--persona-components-tooltip-${e}`];n&&(r[`--persona-tooltip-${t}`]=n)}!1===e.components?.tooltip?.arrow&&(r["--persona-tooltip-arrow-display"]="none");for(let[e,t]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let n=r[`--persona-components-messageActions-${e}`];n&&(r[`--persona-message-action-${t}`]=n)}cs(r,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=r["--persona-components-introCard-background"],m=r["--persona-components-introCard-shadow"],g=!(h&&"transparent"!==h&&"none"!==h||m&&"none"!==m),f=r["--persona-components-introCard-padding"]??"1.5rem";r["--persona-intro-card-padding"]=g&&"1.5rem"===f?"1.5rem 0":f,cs(r,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),cs(r,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let y=r["--persona-components-markdown-heading-h1-fontSize"];y&&(r["--persona-md-h1-size"]=y);let b=r["--persona-components-markdown-heading-h1-fontWeight"];b&&(r["--persona-md-h1-weight"]=b);let v=r["--persona-components-markdown-heading-h2-fontSize"];v&&(r["--persona-md-h2-size"]=v);let w=r["--persona-components-markdown-heading-h2-fontWeight"];w&&(r["--persona-md-h2-weight"]=w);let x=r["--persona-components-markdown-prose-fontFamily"];x&&"inherit"!==x&&(r["--persona-md-prose-font-family"]=x),cs(r,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),cs(r,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),cs(r,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),cs(r,[["md-hr-color","components-markdown-hr-color","divider"]]),cs(r,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let C=[["container","surface"],["surface","surface"],["border","border"]];for(let[e,t]of C){let n=r[`--persona-components-collapsibleWidget-${e}`]??r[`--persona-${t}`];void 0!==n&&(r[`--persona-cw-${e}`]=n,r[`--cw-${e}`]=n)}cs(r,[["message-border","components-message-border","border"]]),cs(r,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let S=e.components,k=S?.iconButton;k&&(k.background&&(r["--persona-icon-btn-bg"]=k.background),k.border&&(r["--persona-icon-btn-border"]=k.border),k.color&&(r["--persona-icon-btn-color"]=k.color),k.padding&&(r["--persona-icon-btn-padding"]=k.padding),k.borderRadius&&(r["--persona-icon-btn-radius"]=k.borderRadius),k.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=k.hoverBackground),k.hoverColor&&(r["--persona-icon-btn-hover-color"]=k.hoverColor),k.activeBackground&&(r["--persona-icon-btn-active-bg"]=k.activeBackground),k.activeBorder&&(r["--persona-icon-btn-active-border"]=k.activeBorder));let A=S?.labelButton;A&&(A.background&&(r["--persona-label-btn-bg"]=A.background),A.border&&(r["--persona-label-btn-border"]=A.border),A.color&&(r["--persona-label-btn-color"]=A.color),A.padding&&(r["--persona-label-btn-padding"]=A.padding),A.borderRadius&&(r["--persona-label-btn-radius"]=A.borderRadius),A.hoverBackground&&(r["--persona-label-btn-hover-bg"]=A.hoverBackground),A.fontSize&&(r["--persona-label-btn-font-size"]=A.fontSize),A.gap&&(r["--persona-label-btn-gap"]=A.gap));let M=S?.toggleGroup;M&&(M.gap&&(r["--persona-toggle-group-gap"]=M.gap),M.borderRadius&&(r["--persona-toggle-group-radius"]=M.borderRadius));let I=S?.artifact;if(I?.toolbar){let t=I.toolbar;t.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=t.iconHoverColor),t.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=t.iconHoverBackground),t.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=t.iconPadding),t.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=t.iconBorderRadius),t.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=t.iconBorder),t.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=ss(t.toggleGroupGap)),t.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=t.toggleBorderRadius),t.toggleGroupPadding&&(r["--persona-artifact-toolbar-toggle-group-padding"]=ss(t.toggleGroupPadding)),t.toggleGroupBorder&&(r["--persona-artifact-toolbar-toggle-group-border"]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(r["--persona-artifact-toolbar-toggle-group-radius"]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(r["--persona-artifact-toolbar-toggle-group-bg"]=es(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=t.copyBackground),t.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=t.copyBorder),t.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=t.copyColor),t.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=ss(t.copyBorderRadius)),t.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=t.copyPadding),t.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=t.copyMenuBackground,r["--persona-dropdown-bg"]=r["--persona-dropdown-bg"]??t.copyMenuBackground),t.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=t.copyMenuBorder,r["--persona-dropdown-border"]=r["--persona-dropdown-border"]??t.copyMenuBorder),t.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=t.copyMenuShadow,r["--persona-dropdown-shadow"]=r["--persona-dropdown-shadow"]??t.copyMenuShadow),t.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=t.copyMenuBorderRadius,r["--persona-dropdown-radius"]=r["--persona-dropdown-radius"]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=t.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=r["--persona-dropdown-item-hover-bg"]??t.copyMenuItemHoverBackground),t.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=t.iconBackground),t.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=t.toolbarBorder)}if(I?.tab){let e=I.tab;e.background&&(r["--persona-artifact-tab-bg"]=e.background),e.activeBackground&&(r["--persona-artifact-tab-active-bg"]=e.activeBackground),e.activeBorder&&(r["--persona-artifact-tab-active-border"]=e.activeBorder),e.borderRadius&&(r["--persona-artifact-tab-radius"]=e.borderRadius),e.textColor&&(r["--persona-artifact-tab-color"]=e.textColor),e.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=e.hoverBackground),e.listBackground&&(r["--persona-artifact-tab-list-bg"]=e.listBackground),e.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=e.listBorderColor),e.listPadding&&(r["--persona-artifact-tab-list-padding"]=e.listPadding)}if(I?.pane){let t=I.pane;if(t.toolbarBackground){let n=es(e,t.toolbarBackground)??t.toolbarBackground;r["--persona-artifact-toolbar-bg"]=n}}if(I?.card){let e=I.card;e.background&&(r["--persona-artifact-card-bg"]=e.background),e.border&&(r["--persona-artifact-card-border"]=e.border),e.borderRadius&&(r["--persona-artifact-card-radius"]=e.borderRadius),e.hoverBackground&&(r["--persona-artifact-card-hover-bg"]=e.hoverBackground),e.hoverBorderColor&&(r["--persona-artifact-card-hover-border"]=e.hoverBorderColor)}if(I?.inline){let t=I.inline;t.background&&(r["--persona-artifact-inline-bg"]=es(e,t.background)??t.background),t.border&&(r["--persona-artifact-inline-border"]=t.border),t.borderRadius&&(r["--persona-artifact-inline-radius"]=t.borderRadius),t.chromeBackground&&(r["--persona-artifact-inline-chrome-bg"]=es(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(r["--persona-artifact-inline-chrome-border"]=es(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(r["--persona-artifact-inline-title-color"]=es(e,t.titleColor)??t.titleColor),t.mutedColor&&(r["--persona-artifact-inline-muted-color"]=es(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(r["--persona-artifact-inline-frame-height"]=t.frameHeight)}let T=S?.code;T&&(T.keywordColor&&(r["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(r["--persona-code-string-color"]=T.stringColor),T.commentColor&&(r["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(r["--persona-code-number-color"]=T.numberColor),T.tagColor&&(r["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(r["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(r["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(r["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(r["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(r["--persona-code-bg"]=es(e,T.background)??T.background));let E=r["--persona-surface"],L=r["--persona-container"],P=r["--persona-palette-colors-gray-100"]??"#f3f4f6",B=r["--persona-palette-colors-gray-200"]??"#e5e7eb",N=r["--persona-palette-colors-gray-300"]??"#d1d5db",R=!L||L===E,H=ls(E??r["--persona-background"]),$=R&&void 0!==H&&H<ds,W=$?"rgba(255, 255, 255, 0.16)":N,D=R?$?"rgba(255, 255, 255, 0.08)":P:L,O=R?$?"rgba(255, 255, 255, 0.12)":B:L;return r["--persona-icon-btn-hover-bg"]=r["--persona-icon-btn-hover-bg"]??D,r["--persona-icon-btn-active-bg"]=r["--persona-icon-btn-active-bg"]??O,R&&(r["--persona-icon-btn-active-border"]=r["--persona-icon-btn-active-border"]??W),r["--persona-label-btn-hover-bg"]=r["--persona-label-btn-hover-bg"]??D,r["--persona-artifact-tab-hover-bg"]=r["--persona-artifact-tab-hover-bg"]??D,r["--persona-artifact-card-hover-bg"]=r["--persona-artifact-card-hover-bg"]??D,r}var us={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"},hs={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},ms={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"}}},gs={...ms,colors:{...ms.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},fs=hs,ys={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",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"}}},components:{...hs.components,button:{...hs.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...hs.components?.eventStream,badge:{...hs.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},bs=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},vs=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",ws=e=>(e=>{let t=e?.colorScheme??"light";return"light"===t?"light":"dark"===t?"dark":vs()})(e),xs=e=>{let t=ws(e),r=bs(e?.theme),n=E({components:{launcher:"circle"===Ha(e)?$a:{...Ya.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}}}},r),o=bs(e?.darkTheme);return((e,t)=>{if(!t||!(e=>!!e&&"launcher"in e&&(!0===e.launcher?.sidebarMode||"docked"===e.launcher?.mountMode))(t))return e;let r=t.theme?.components?.panel?.width,n=t.darkTheme?.components?.panel?.width;return null!=("dark"===ws(t)?n??r:r)?e:{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===Q(t)?"400px":"420px"}}}})("dark"===t?((e,t={})=>{let r=(e=>"v5"===Q({future:e})?{palette:gs,components:ys}:{palette:ms,components:fs})(t.future),n=E(r.components,e??{})??{};return as({...n,palette:{...n.palette,colors:"v5"===Q(t)?E(r.palette.colors,n.palette?.colors):{...r.palette.colors,...n.palette?.colors}}},{validate:!1,future:t.future})})(E(n??{},o??{}),{future:e?.future}):((e,t={})=>as(e,t))(n,{future:e?.future}),e)},Cs=(e,t)=>{let r=(e=>ps(e))(xs(t));for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute("data-persona-color-scheme",ws(t)),e.setAttribute("data-persona-defaults",Q(t))},Ss=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(vs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window<"u"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(vs());r.addEventListener?(r.addEventListener("change",n),t.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),t.push(()=>r.removeListener(n)))}return()=>{t.forEach(e=>e())}},ks=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),As="24px",Ms=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",Is=e=>{if("string"!=typeof e)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let r=Number(t[1])/100;return r>0&&r<1?r:null},Ts=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},Es=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Ls=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),n={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)n.mod=!0;else if("shift"===r)n.shift=!0;else{if("alt"!==r&&"option"!==r)return Es("unknown modifier in",e),null;n.alt=!0}return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(Es("unsupported",e),null):("space"===r&&(n.key=" "),n)},Ps=(e,t)=>{let r=Ls(e);if(!r)return"";let n=Ts(),o=(e=>"ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space".split(" ").find(t=>t.toLowerCase()===e)??(" "===e?"Space":1===e.length?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))(r.key);if(!t&&n)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${o}`;let a=[t?n?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(o),a.join("+")},Bs=e=>Ps(e,!1),Ns=e=>Ps(e,!0),Rs=(e,t)=>t.key?.toLowerCase()===e.key&&(Ts()?t.metaKey:t.ctrlKey)===e.mod&&!(Ts()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Hs=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},$s=function(){let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:e=>"true"===e.getAttribute("im-preserve"),shouldReAppend:e=>"true"===e.getAttribute("im-re-append"),shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0},r=function(){function e(e,t,r,o){if(!1===o.callbacks.beforeNodeAdded(t))return null;if(o.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),n(a,t,o),o.callbacks.afterNodeAdded(a),a}{let n=document.importNode(t,!0);return e.insertBefore(n,r),o.callbacks.afterNodeAdded(n),n}}let t=function(){function e(e,t,r){let n=e.idMap.get(t),o=e.idMap.get(r);if(!o||!n)return!1;for(let e of n)if(o.has(e))return!0;return!1}function t(e,t){let r=e,n=t;return r.nodeType===n.nodeType&&r.tagName===n.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===n.getAttribute?.("id"))}return function(r,n,o,a){let s=null,i=n.nextSibling,l=0,d=o;for(;d&&d!=a;){if(t(d,n)){if(e(r,d,n))return d;null===s&&(r.idMap.has(d)||(s=d))}if(null===s&&i&&t(d,i)&&(l++,i=i.nextSibling,l>=2&&(s=void 0)),r.activeElementAndParents.includes(d))break;d=d.nextSibling}return s||null}}();function r(e,t){if(e.idMap.has(t))s(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;t.parentNode?.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function o(e,t,n){let o=t;for(;o&&o!==n;){let t=o;o=o.nextSibling,r(e,t)}return o}function a(e,t,r,n){let o=n.target.getAttribute?.("id")===t&&n.target||n.target.querySelector(`[id="${t}"]`)||n.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let n=t.idMap.get(e);n&&(n.delete(r),n.size||t.idMap.delete(e))}}(o,n),s(e,o,r),o}function s(e,t,r){if(e.moveBefore)try{e.moveBefore(t,r)}catch{e.insertBefore(t,r)}else e.insertBefore(t,r)}return function(s,i,l,d=null,c=null){i instanceof HTMLTemplateElement&&l instanceof HTMLTemplateElement&&(i=i.content,l=l.content),d||=i.firstChild;for(let r of l.childNodes){if(d&&d!=c){let e=t(s,r,d,c);if(e){e!==d&&o(s,d,e),n(e,r,s),d=e.nextSibling;continue}}if(r instanceof Element){let e=r.getAttribute("id");if(s.persistentIds.has(e)){let t=a(i,e,d,s);n(t,r,s),d=t.nextSibling;continue}}let l=e(i,r,d,s);l&&(d=l.nextSibling)}for(;d&&d!=c;){let e=d;d=d.nextSibling,r(s,e)}}}(),n=function(){function e(e,r,n,o){let a=r[n];if(a!==e[n]){let s=t(n,e,"update",o);s||(e[n]=r[n]),a?s||e.setAttribute(n,""):t(n,e,"remove",o)||e.removeAttribute(n)}}function t(e,t,r,n){return!("value"!==e||!n.ignoreActiveValue||t!==document.activeElement)||!1===n.callbacks.beforeAttributeUpdated(e,t,r)}function n(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(a,s,i){return i.ignoreActive&&a===document.activeElement?null:(!1===i.callbacks.beforeNodeMorphed(a,s)||(a instanceof HTMLHeadElement&&i.head.ignore||(a instanceof HTMLHeadElement&&"morph"!==i.head.style?o(a,s,i):(function(r,o,a){let s=o.nodeType;if(1===s){let s=r,i=o,l=s.attributes,d=i.attributes;for(let e of d)t(e.name,s,"update",a)||s.getAttribute(e.name)!==e.value&&s.setAttribute(e.name,e.value);for(let e=l.length-1;0<=e;e--){let r=l[e];if(r&&!i.hasAttribute(r.name)){if(t(r.name,s,"remove",a))continue;s.removeAttribute(r.name)}}n(s,a)||function(r,n,o){if(r instanceof HTMLInputElement&&n instanceof HTMLInputElement&&"file"!==n.type){let a=n.value,s=r.value;e(r,n,"checked",o),e(r,n,"disabled",o),n.hasAttribute("value")?s!==a&&(t("value",r,"update",o)||(r.setAttribute("value",a),r.value=a)):t("value",r,"remove",o)||(r.value="",r.removeAttribute("value"))}else if(r instanceof HTMLOptionElement&&n instanceof HTMLOptionElement)e(r,n,"selected",o);else if(r instanceof HTMLTextAreaElement&&n instanceof HTMLTextAreaElement){let e=n.value,a=r.value;if(t("value",r,"update",o))return;e!==a&&(r.value=e),r.firstChild&&r.firstChild.nodeValue!==e&&(r.firstChild.nodeValue=e)}}(s,i,a)}(8===s||3===s)&&r.nodeValue!==o.nodeValue&&(r.nodeValue=o.nodeValue)}(a,s,i),n(a,i)||r(i,a,s))),i.callbacks.afterNodeMorphed(a,s)),a)}}();function o(e,t,r){let n=[],o=[],a=[],s=[],i=new Map;for(let e of t.children)i.set(e.outerHTML,e);for(let t of e.children){let e=i.has(t.outerHTML),n=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?n?o.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?n&&(o.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&o.push(t)}s.push(...i.values());let l=[];for(let t of s){let o=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(o)){if("href"in o&&o.href||"src"in o&&o.src){let e,t=new Promise(function(t){e=t});o.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(o),r.callbacks.afterNodeAdded(o),n.push(o)}}for(let t of o)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:n,kept:a,removed:o}),l}let a=function(){function e(){let e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function r(e){let t=[],r=document.activeElement;if("BODY"!==r?.tagName&&e.contains(r))for(;r&&(t.push(r),r!==e);)r=r.parentElement;return t}function n(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function o(e,t,r,n){for(let o of n){let n=o.getAttribute("id");if(t.has(n)){let t=o;for(;t;){let o=e.get(t);if(null==o&&(o=new Set,e.set(t,o)),o.add(n),t===r)break;t=t.parentElement}}}}return function(a,s,i){let{persistentIds:l,idMap:d}=function(e,t){let r=n(e),a=n(t),s=function(e,t){let r=new Set,n=new Map;for(let{id:t,tagName:o}of e)n.has(t)?r.add(t):n.set(t,o);let o=new Set;for(let{id:e,tagName:a}of t)o.has(e)?r.add(e):n.get(e)===a&&o.add(e);for(let e of r)o.delete(e);return o}(r,a),i=new Map;return o(i,s,e,r),o(i,s,t.__idiomorphRoot||t,a),{persistentIds:s,idMap:i}}(a,s),c=function(e){let r=Object.assign({},t);return Object.assign(r,e),r.callbacks=Object.assign({},t.callbacks,e.callbacks),r.head=Object.assign({},t.head,e.head),r}(i),p=c.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(p))throw`Do not understand how to morph style ${p}`;return{target:a,newContent:s,config:c,morphStyle:p,ignoreActive:c.ignoreActive,ignoreActiveValue:c.ignoreActiveValue,restoreFocus:c.restoreFocus,idMap:d,persistentIds:l,pantry:e(),activeElementAndParents:r(a),callbacks:c.callbacks,head:c.head}}}(),{normalizeElement:s,normalizeParent:i}=function(){let e=new WeakSet;class t{constructor(e){this.originalNode=e,this.realParentNode=e.parentNode,this.previousSibling=e.previousSibling,this.nextSibling=e.nextSibling}get childNodes(){let e=[],t=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;t&&t!=this.nextSibling;)e.push(t),t=t.nextSibling;return e}querySelectorAll(e){return this.childNodes.reduce((t,r)=>{if(r instanceof Element){r.matches(e)&&t.push(r);let n=r.querySelectorAll(e);for(let e=0;e<n.length;e++)t.push(n[e])}return t},[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function r(n){if(null==n)return document.createElement("div");if("string"==typeof n)return r(function(t){let r=new DOMParser,n=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let o=r.parseFromString(t,"text/html");if(n.match(/<\/html>/))return e.add(o),o;{let t=o.firstChild;return t&&e.add(t),t}}{let n=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(n),n}}(n));if(e.has(n))return n;if(n instanceof Node){if(n.parentNode)return new t(n);{let e=document.createElement("div");return e.append(n),e}}{let e=document.createElement("div");for(let t of[...n])e.append(t);return e}}}}();return{morph:function(e,t,n={}){e=s(e);let l=i(t),d=a(e,l,n),c=function(e,t){if(!e.config.restoreFocus)return t();let r=document.activeElement;if(!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return t();let{id:n,selectionStart:o,selectionEnd:a}=r,s=t();return n&&n!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${n}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(o,a),s}(d,()=>function(e,t,r,n){if(e.head.block){let a=t.querySelector("head"),s=r.querySelector("head");if(a&&s){let t=o(a,s,e);return Promise.all(t).then(()=>{let t=Object.assign(e,{head:{block:!1,ignore:!0}});return n(t)})}}return n(e)}(d,e,l,t=>"innerHTML"===t.morphStyle?(r(t,e,l),Array.from(e.childNodes)):function(e,t,n){let o=i(t);return r(e,o,n,t,t.nextSibling),Array.from(o.childNodes)}(t,e,l)));return d.pantry.remove(),c},defaults:t}}(),Ws=(e,t,r={})=>{let{preserveTypingAnimation:n=!0}=r;$s.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&n){if(e.classList.contains("persona-animate-typing")||e.hasAttribute("data-preserve-runtime"))return!1;if(e.hasAttribute("data-tool-elapsed"))return!(t instanceof HTMLElement&&t.getAttribute("data-tool-elapsed")===e.getAttribute("data-tool-elapsed"))&&void 0;if(e.hasAttribute("data-preserve-animation")){if(t instanceof HTMLElement&&!t.hasAttribute("data-preserve-animation"))return;if(t instanceof HTMLElement&&t.hasAttribute("data-preserve-animation")&&(e.textContent??"")!==(t.textContent??""))return;return!1}}}}})},Ds={index:-1,draft:""};function Os(e){return"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function zs(e,t){return Fs(e)-e.scrollTop<=t}function qs(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}var js=["pre","code","a","script","style"],_s=e=>({type:e?.type??"none",placeholder:e?.placeholder??"none",speed:e?.speed??120,duration:e?.duration??1800,buffer:e?.buffer??"none"}),Vs=[{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"}],Us=new Map;for(let e of Vs)Us.set(e.name,e);var Ks=["wipe","glyph-cycle"],Js=e=>{Us.set(e.name,e)},Gs=e=>{Vs.some(t=>t.name===e)||Us.delete(e)},Ys=()=>Array.from(Us.keys()),Xs=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Us.get(e)??null,Qs=(e,t,r,n,o)=>{if(!o)return e;if(r?.bufferContent)return r.bufferContent(e,n);if(!e)return e;if("word"===t){let t=e.search(/\s(?=\S*$)/);return t<0?"":e.slice(0,t)}if("line"===t){let t=e.lastIndexOf("\n");return t<0?"":e.slice(0,t)}return e},Zs=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=t,o},ei=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=t,o},ti=/\s/,ri=(e,t)=>{let r=e.parentNode;for(;r;){if(1===r.nodeType){let e=r;if(t.has(e.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},ni=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(ti.test(a[i])){let e=i;for(;e<a.length&&ti.test(a[e]);)e+=1;s.appendChild(n.createTextNode(a.slice(i,e))),i=e}else{let e=n.createElement("span");e.className="persona-stream-word-group";let o=i;for(;o<a.length&&!ti.test(a[o]);)e.appendChild(Zs(n,a[o],t,r.value)),r.value+=1,o+=1;s.appendChild(e),i=o}o.replaceChild(s,e)},oi=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(n.createTextNode(e)):(s.appendChild(ei(n,e,t,r.value)),r.value+=1));o.replaceChild(s,e)},ai=(e,t,r,n)=>{if(!e||typeof document>"u")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set((n?.skipTags??js).map(e=>e.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)ri(l,a)||i.push(l),l=s.nextNode();let d={value:n?.startIndex??0},c="char"===t?ni:oi;for(let e of i)c(e,r,d);return o.innerHTML},si=(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},ii=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},li=new WeakMap,di=new WeakMap,ci=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=li.get(t);if(r||(r=new Set,li.set(t,r)),r.has(e.name)){let n=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${n}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=di.get(t);if(r||(r=new Map,di.set(t,r)),r.has(e.name))return;let n=e.onAttach(t);r.set(e.name,n)})(e,t)},{setLoader:pi,load:ui}=se({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),hi=pi,mi=ui;function gi(e,t=pn){let r=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s="static"===a.position||""===a.position;return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=n,e.style.isolation=o}}var fi=0,yi=null;function bi(e=document){if(1===++fi){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;yi={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:r},t.style.overflow="hidden",t.style.position="fixed",t.style.top=`-${r}px`,t.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,0===(fi=Math.max(0,fi-1))&&yi)){let t=e.body,r=e.defaultView??window;t.style.overflow=yi.originalOverflow,t.style.position=yi.originalPosition,t.style.top=yi.originalTop,t.style.width=yi.originalWidth,r.scrollTo(0,yi.scrollY),yi=null}}}var vi=e=>"docked"===(e?.launcher?.mountMode??"floating"),wi=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),xi=e=>{let t=e?.launcher?.dock,r=F(e).dockWidth?t?.width:es(xs(e),"components.panel.width");return{side:t?.side??"right",width:r??"420px",animate:t?.animate??true,reveal:t?.reveal??"resize",maxHeight:t?.maxHeight??"100dvh"}},Ci=e=>"followUp"===e?"follow-up":e,Si=(e,t=0)=>{if("string"==typeof e){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:"default"}:null}let r=e.label.trim();if(!r)return null;let n=e.prompt?.trim()||r;return{id:e.id?.trim()||n||`suggestion-${t}`,label:r,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},ki=new WeakSet,Ai=e=>{let{item:t,index:r,surface:n,source:o,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,g="followUp"===n,f=t.behavior,y=()=>{if(c.isStreaming())return;let e={suggestion:{...t},surface:n,source:o,behavior:f},r=u.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(g&&u.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of l)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:n,source:o,variant:a,config:i}))return;let s=p();if("fill"===f)return s.value=t.prompt,s.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),void s.focus();h?h(t.prompt):(s.value="",c.sendMessage(t.prompt))},b=()=>{let e=ne("button",`persona-suggestion persona-suggestion--${a}`);if(e.type="button",e.disabled=s,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=f,"chip"===a&&(d?.fontWeight&&(e.style.fontWeight=d.fontWeight),d?.paddingX&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(e.style.paddingTop=d.paddingY,e.style.paddingBottom=d.paddingY)),t.icon){let r=xe(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);r&&(r.classList.add("persona-suggestion__icon"),t.iconColor&&(r.style.color=t.iconColor),e.appendChild(r))}let r=ne("span","persona-suggestion__copy");if(r.appendChild(oe("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==a&&r.appendChild(oe("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(r),"chip"!==a){let t=I(m,16,"currentColor",1.8);t&&(t.classList.add("persona-suggestion__arrow"),e.appendChild(t))}return e.addEventListener("click",y),e},v=null;for(let e of l)if(e.renderSuggestion&&(v=e.renderSuggestion({suggestion:{...t},index:r,surface:n,source:o,variant:a,streaming:s,config:i,defaultRenderer:b,select:y}),v))break;return v??=b(),v.dataset.suggestionId||=t.id,v.dataset.behavior||=f,v.dataset.emphasis||=t.emphasis,v instanceof HTMLButtonElement||v.setAttribute("aria-disabled",s?"true":"false"),v},Mi=e=>{let t=[],r=[],n=null,o=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(o=null,e.hidden||"chip"!==e.dataset.variant||"scroll"!==e.dataset.overflow)return void a();let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1)return void a();let r="rtl"===getComputedStyle(e).direction,n=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=n<=4,i=n>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null===o&&"function"==typeof requestAnimationFrame?o=requestAnimationFrame(s):"function"!=typeof requestAnimationFrame&&s()};e.addEventListener("scroll",i,{passive:!0});let l="function"==typeof ResizeObserver?new ResizeObserver(i):null;return l?.observe(e),{buttons:t,elements:r,destroy:()=>{e.removeEventListener("scroll",i),l?.disconnect(),null!==o&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o),o=null},render:(o,l,d,c,p,u)=>{e.replaceChildren(),t.length=0,r.length=0;let h=u?.source??"config",m=u?.surface??("config"===h?"starter":"followUp"),g="followUp"===m,f=u?.variant??"chip",y=u?.behavior??"send",b=u?.overflow??"wrap",v=u?.config??{},w=u?.plugins??[],x="number"==typeof u?.maxItems?Math.max(0,Math.floor(u.maxItems)):void 0,C=g?"followUps":"starters";!ki.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(ki.add(v),console.info(`[persona] suggestions.${C}.overflow applies to the "chip" variant only; the "${f}" variant manages its own stacking.`));let S=e=>e.map(Si).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??y})),k=S(o??[]);w.forEach(e=>{e.transformSuggestions&&(k=S(e.transformSuggestions({suggestions:k.map(e=>({...e})),surface:m,source:h,config:v})))});let A=void 0===x?k:k.slice(0,x);if(!A.length)return e.hidden=!0,n=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(n=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ci(m),e.dataset.variant=f,e.dataset.overflow=b;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((n,o)=>{let a=Ai({item:n,index:o,surface:m,source:h,variant:f,streaming:I,config:v,plugins:w,chipsConfig:p,session:l,getTextarea:()=>d,eventTarget:e,submitPrompt:u?.submitPrompt});M.appendChild(a),r.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll("button"))].forEach(e=>{t.includes(e)||(e.disabled=I,t.push(e))})}),e.appendChild(M),s(),i();let T=JSON.stringify({normalized:A,surface:m,variant:f,source:h});T!==n&&(n=T,(e=>{typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||e.forEach((e,t)=>{"function"==typeof e.animate&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:60*t,easing:"ease-out",fill:"backwards"})})})(r),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:A.map(e=>({...e})),surface:m,source:h,variant:f},bubbles:!0,composed:!0})),g&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:A.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Ii={"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"},Ti={x:[1.4,1.05]},Ei="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Li="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pi=(e,t,r={})=>{let{iconSize:n,iconText:o}=r,[a,s]=Ti[t]??[1,1.5],i=!n;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=parseFloat(n??"")||20,d=xe(t,`${Math.round(l*a)}px`,"currentColor",s);d?(d.style.display="block",i||(d.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((s/1.5).toFixed(4))})`),e.replaceChildren(d)):o&&(e.textContent=o)},Bi=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:n,iconName:o,iconText:a,wrapperClassName:s=Ei,size:i,iconSize:l,color:d,backgroundColor:c,borderWidth:p,borderColor:u,borderRadius:h,paddingX:m,paddingY:g,hidden:f,extraClassName:y,attrs:b}=e,v=ne("div",s),w=!(!p&&!u),x=oe("button",{className:ae("persona-header-control","persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"persona-bg-transparent hover:persona-bg-gray-100",!w&&"persona-border-none",!h&&"persona-rounded-full",y),attrs:{type:"button","aria-label":t,...b},style:{width:i,height:i,minWidth:i,minHeight:i,display:f?"none":void 0,color:d||Hi.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return o?Pi(x,o,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Bo({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:n,enabled:r}),{button:x,wrapper:v}},Ni=(e,t={})=>{let{showClose:r=!0,wrapperClassName:n=Ei,buttonSize:o,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=Bi({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:n,size:o??s.closeButtonSize,iconSize:a,color:s.closeButtonColor,backgroundColor:s.closeButtonBackgroundColor,borderWidth:s.closeButtonBorderWidth,borderColor:s.closeButtonBorderColor,borderRadius:s.closeButtonBorderRadius,paddingX:s.closeButtonPaddingX,paddingY:s.closeButtonPaddingY,hidden:!r});return{button:d,wrapper:c}},Ri=(e,t={})=>{let{wrapperClassName:r=Li,buttonSize:n,iconSize:o}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=Bi({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:n??a.size,iconSize:o,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:l,wrapper:d}},Hi={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-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},$i={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)"},Wi={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)"},Di=e=>{let{config:t,showClose:r=!0}=e,n=oe("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:Hi.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)))"}}),o=t?.launcher??{},a=o.headerIconSize??V,s=o.closeButtonPlacement??"inline",i=o.headerIconHidden??!1,l=o.headerIconName,d=oe("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(l){let e=parseFloat(a)||24,r=xe(l,.6*e,"currentColor",1);r?(r.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,r.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,d.replaceChildren(r)):d.textContent=t?.launcher?.agentIconText??"💬"}else if(t?.launcher?.iconUrl){let e=ne("img");e.src=t.launcher.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=a,e.style.width=a,d.replaceChildren(e)}else d.textContent=t?.launcher?.agentIconText??"💬";let c=ne("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=oe("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Hi.titleColor,...$i}}),u=oe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Hi.subtitleColor,...Wi}});c.append(p,u),i?n.append(c):n.append(d,c);let h=o.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,y=null;if(m){let e=Ri(t,{wrapperClassName:"top-right"===g?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});f=e.button,y=e.wrapper,"top-right"===g&&(y.style.right="48px"),"inline"===g&&n.appendChild(y)}let b="top-right"===s?"persona-absolute persona-top-4 persona-right-4 persona-z-50":m&&"inline"===g?"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:v,wrapper:w}=Ni(t,{showClose:r,wrapperClassName:b});return"top-right"!==s&&n.appendChild(w),{header:n,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:v,closeButtonWrapper:w,clearChatButton:f,clearChatButtonWrapper:y}},Oi=(e,t,r)=>{let n=r?.launcher??{},o=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===o&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Fi(e){let{items:t,onSelect:r,anchor:n,position:o="bottom-left",portal:a,onOpenChange:s}=e,i=ne("div","persona-dropdown-menu persona-hidden");i.setAttribute("role","menu"),i.setAttribute("data-persona-theme-zone","dropdown"),a?(i.style.position="fixed",i.style.zIndex=String(un)):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px","bottom-right"===o?i.style.right="0":i.style.left="0");for(let e of t){if(e.dividerBefore){let e=document.createElement("hr");i.appendChild(e)}let t=document.createElement("button");if(t.type="button",t.setAttribute("role","menuitem"),t.setAttribute("data-dropdown-item-id",e.id),e.destructive&&t.setAttribute("data-destructive",""),e.icon){let r=xe(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let n=document.createElement("span");n.textContent=e.label,t.appendChild(n),t.addEventListener("click",t=>{t.stopPropagation(),c(),r(e.id)}),i.appendChild(t)}let l=null;function d(){let e=i.classList.contains("persona-hidden");(function(){if(!a)return;let e=n.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===o?(i.style.right=window.innerWidth-e.right+"px",i.style.left="auto"):(i.style.left=`${e.left}px`,i.style.right="auto")})(),i.classList.remove("persona-hidden"),e&&s?.(!0),requestAnimationFrame(()=>{let e=e=>{!i.contains(e.target)&&!n.contains(e.target)&&c()};document.addEventListener("click",e,!0),l=()=>document.removeEventListener("click",e,!0)})}function c(){let e=!i.classList.contains("persona-hidden");i.classList.add("persona-hidden"),l?.(),l=null,e&&s?.(!1)}return a&&a.appendChild(i),{element:i,show:d,hide:c,toggle:function(){i.classList.contains("persona-hidden")?d():c()},destroy:function(){c(),i.remove()}}}function zi(e){let{icon:t,label:r,size:n,strokeWidth:o,className:a,chromeless:s,onClick:i,aria:l}=e,d=ne("button",ae(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=xe(t,n??16,"currentColor",o??2);if(c&&d.appendChild(c),i&&d.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))d.setAttribute(e,t);return d}function qi(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==n&&(d+=" persona-label-btn--"+n),d+=" persona-label-btn--"+o,s&&(d+=" "+s);let c=ne("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=xe(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=ne("span");if(p.textContent=r,c.appendChild(p),i&&c.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))c.setAttribute(e,t);return c}function ji(e){let{items:t,selectedId:r,onSelect:n,className:o}=e,a=ne("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=r,i=[];function l(){for(let e of i)e.btn.setAttribute("aria-pressed",e.id===s?"true":"false")}for(let e of t){let t;e.icon?t=zi({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),n(e.id)}}):(t=ne("button","persona-icon-btn"+(e.className?" "+e.className:"")),t.type="button",t.setAttribute("aria-label",e.label),t.title=e.label,t.textContent=e.label,t.addEventListener("click",()=>{s=e.id,l(),n(e.id)})),t.setAttribute("aria-pressed",e.id===s?"true":"false"),i.push({id:e.id,btn:t}),a.appendChild(t)}return{element:a,setSelected:function(e){s=e,l()}}}function _i(e){let{label:t,icon:r,iconSize:n,iconOnly:o,menuItems:a,onSelect:s,onPrimary:i,position:l="bottom-left",portal:d,chevronLabel:c="More options",chevronIconSize:p,className:u,primaryClassName:h,chevronClassName:m}=e,g=ne("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},y=o&&r?zi({...f,icon:r,size:n??14}):qi({...f,icon:r,iconSize:n??14}),b=zi({icon:"chevron-down",label:c,size:p??14,className:"persona-split-btn-chevron"+(m?" "+m:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});g.append(y,b);let v=null,w=()=>{if(v)return v;let e=("function"==typeof d?d():d)??void 0;return v=Fi({items:a,onSelect:s,anchor:g,position:l,portal:e,onOpenChange:e=>{b.setAttribute("aria-expanded",e?"true":"false")}}),e||g.appendChild(v.element),v};return g.isConnected?w():requestAnimationFrame(()=>{v||w()}),b.addEventListener("click",e=>{e.stopPropagation(),w().toggle()}),{element:g,primaryButton:y,chevronButton:b,openMenu:()=>w().show(),closeMenu:()=>v?.hide(),toggleMenu:()=>w().toggle(),destroy:()=>{v?.destroy(),g.remove()}}}function Vi(e){let{label:t,icon:r="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=ne("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=ne("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=xe(r,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",d.appendChild(p)),l&&(d.style.borderRadius=l.borderRadius??"10px",d.style.padding=l.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=l.background??"",d.style.borderColor=l.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let u=Fi({items:n,onSelect:e=>{d.setAttribute("aria-expanded","false"),o(e)},anchor:d,position:a,portal:s});return s||d.appendChild(u.element),d.addEventListener("click",e=>{if(e.stopPropagation(),"true"===d.getAttribute("data-persona-menu-locked"))return;let t=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",t?"false":"true"),u.toggle()}),d.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),d.click())}),{element:d,setLabel:e=>{c.textContent=e,d.setAttribute("aria-label",e)},open:()=>{d.setAttribute("aria-expanded","true"),u.show()},close:()=>{d.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let e=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",e?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),d.remove()}}}var Ui=e=>{let t=Di({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=e.layoutHeaderConfig?.onTitleClick;if(r){let e=t.headerTitle.parentElement;e&&(e.style.cursor="pointer",e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.addEventListener("click",()=>r()),e.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),r())}))}return t},Ki=e=>{let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=t?.launcher??{},i=ne("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=Hi.minHeight,i.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let l,d,c=o?.titleMenu;if(c){let e=Vi({label:s.title??"Chat Assistant",menuItems:c.menuItems,onSelect:t=>{let r=r=>{!1===r&&e.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:t}}))},n=c.onSelect(t);n instanceof Promise?n.then(r,()=>{}):r(n)},hover:c.hover,className:""});l=e.element,l.style.color=Hi.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=ne("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=ne("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Hi.titleColor,Object.assign(d.style,$i),d.textContent=s.title??"Chat Assistant",l.appendChild(d),o?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=o.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=o?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??"10px",l.style.padding=e.padding??"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{l.style.backgroundColor=e.background??"",l.style.borderColor=e.border??""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:u,wrapper:h}=Ni(t,{showClose:r,wrapperClassName:p});n&&u.addEventListener("click",n);let m=ne("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let n of t){let{button:t,wrapper:o}=Bi({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?Bs(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",n.id),n.shortcut){let e=Ns(n.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(n.menuItems?.length){let e=Fi({items:n.menuItems,onSelect:e=>r?.(e),anchor:o,position:"bottom-right"});o.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(n.id));e.appendChild(o)}}(m,o?.trailingActions,o?.onAction??a);let g=s.clearChat??{},f=null,y=null;if(g.enabled??1){let e=g.placement??"inline",r=Ri(t,{wrapperClassName:"top-right"===e?"persona-absolute persona-top-4 persona-z-50":p});f=r.button,y=r.wrapper,"top-right"===e?y.style.right="48px":m.appendChild(y)}m.appendChild(h),i.appendChild(m);let b=ne("div");b.style.display="none";let v=ne("span");return v.style.display="none",{header:i,iconHolder:b,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:y}},Ji={default:Ui,minimal:Ki},Gi=e=>Ji[e]??Ji.default,Yi=(e,t,r)=>{if(t?.render){let n=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),o=ne("div");o.style.display="none";let a=ne("span"),s=ne("span"),i=ne("button");i.style.display="none";let l=ne("div");return l.style.display="none",{header:n,iconHolder:o,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let n=Gi(t?.layout??"default")({config:e,showClose:t?.showCloseButton??r?.showClose??!0,onClose:r?.onClose,onClearChat:r?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(!1===t.showIcon&&(n.iconHolder.style.display="none"),!1===t.showTitle&&(n.headerTitle.style.display="none"),!1===t.showSubtitle&&(n.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(n.closeButton.style.display="none"),!1===t.showClearChat&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n},Xi=e=>{let{config:t}=e,r=oe("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"}}),n=Yo(),o=oe("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":""}}),{textarea:a,attachAutoResize:s}=_o(t);s();let i=Uo(t),l=Ko(t),d=Jo(t),c=Go(t),p=oe("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(p),d&&(d.previewsContainer.style.gap="8px",p.append(d.previewsContainer),o.append(d.input)),o.append(a);let u=oe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=oe("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=oe("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&h.append(d.wrapper),l&&m.append(l.wrapper),m.append(i.wrapper),u.append(h,m),o.append(u),o.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),"transient"===t?.statusIndicator?.mode?r.append(n,c,o):r.append(n,o,c),{footer:r,suggestions:n,composerForm:o,header:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}},Qi=e=>{let{config:t}=e,r=oe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Yo(),o=Go(t);o.style.display="none";let{textarea:a,attachAutoResize:s}=_o(t,{defaultMaxLines:5});s();let i=Uo(t),l=Ko(t),d=Jo(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=oe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=oe("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=oe("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});l&&u.append(l.wrapper),u.append(i.wrapper),c.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(p,a,u);let h=oe("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(n,c,o);let m=c;return{footer:r,suggestions:n,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:o,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:p,rightActions:u,setSendButtonMode:i.setMode}};function Zi(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=oe("span",{className:ae("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&&r.style.setProperty("--persona-mention-token-accent",e.color);let n=xe(e.iconName??"at-sign",13,"currentColor",2);if(n){let e=ne("span","persona-mention-token-icon");e.appendChild(n),r.appendChild(e)}return r.appendChild(oe("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}var el=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")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:")&&e.includes(":"))},tl=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(n),e.appendChild(o),e},rl=(e,t,r)=>{if(t){let n=t({config:r??{},streaming:!0,location:e,defaultRenderer:tl});if(null!==n)return n}return tl()},nl=(e,t,r="div")=>{let n=ne(r,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ol=(e,t="bubble")=>{let r=["persona-message-bubble"];switch(t){case"flat":"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3")}return r},al={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},sl="custom:",il=e=>`${sl}${e}`,ll=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),dl=(e,t,r,n)=>{let o=t.showCopy??!0,a=t.showUpvote??!1,s=t.showDownvote??!1,i=t.showReadAloud??!1,l=(t.showRegenerate??!1)&&!0===n?.canRegenerate,d=(t.showEdit??!1)&&!0===n?.canEdit,c=(t.showQuote??!1)&&!1!==n?.canQuote,p=ll(t,e.role);if(!(o||a||s||i||l||d||c||0!==p.length)){let t=ne("div");return t.style.display="none",t.id=`actions-${e.id}`,t.setAttribute("data-actions-for",e.id),t}let u=t.visibility??"hover",h=t.align??"right",m=t.layout??"pill-inside",g=ne("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${{left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h]} ${{"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[m]} ${"hover"===u?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(e,t,r)=>{let n=zi({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return n.setAttribute("data-action",r),n};o&&g.appendChild(f("copy","Copy message","copy")),i&&g.appendChild(f("volume-2","Read aloud","read-aloud")),a&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),l&&g.appendChild(f("refresh-cw","Regenerate response","regenerate")),d&&g.appendChild(f("pencil","Edit message","edit")),c&&g.appendChild(f("quote","Quote message","quote"));for(let e of p)g.appendChild(f(e.iconName??"ellipsis",e.label,il(e.id)));return g},cl=(e,t,r,n,o,a)=>{let s=r??{},i=s.layout??"bubble",l=s.avatar,d=s.timestamp,c=l?.show??!1,p=d?.show??!1,u=l?.position??"left",h=d?.position??"below",m=ol(e.role,i),g=ne("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":"assistant-message");let f=Za(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message;((e,t,r="bubble",n)=>{if(!n)return;let o="user"===t?"user":"assistant",a=al[r??"bubble"]??al.bubble;n.padding&&(e.style.padding=`var(--persona-message-${o}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${o}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${o}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${o}-font-family, inherit)`)})(g,e.role,i,"user"===e.role?{...f.user,...y?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...f.assistant,...y?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),"flat"===i?(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):"user"===e.role?(g.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",g.style.color="var(--persona-message-user-text, white)"):"assistant"===e.role&&(g.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",g.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),v=e.content?.trim()??"",w=b.length>0&&v===Jr,x=_s(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?Xs(x.type,C):null,k="assistant"===e.role&&!0===S?.isAnimating?.(e),A="assistant"===e.role&&null!==S&&(!!e.streaming||k);A&&S?.bubbleClass&&g.classList.add(S.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),A&&S&&(S.containerClass&&M.classList.add(S.containerClass),M.style.setProperty("--persona-stream-step",`${x.speed}ms`),M.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let I=A?Qs(e.content??"",x.buffer,S,e,!!e.streaming):e.content??"",T=()=>{let r=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent});return A&&"char"===S?.wrap?ai(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?ai(r,"word",e.id,{skipTags:S.skipTags}):r},E=null;if(w?(E=document.createElement("div"),E.innerHTML=T(),E.style.display="none",M.appendChild(E)):e.contentSegments?.length?((e,t,r,n)=>{let o=Math.random().toString(36).slice(2,8),a=e=>`${o}:${e}`,s=r(t.map((e,t)=>"text"===e.kind?e.text:a(t)).join(""));if(!t.every((e,t)=>"text"===e.kind||s.includes(a(t))))return void e.replaceChildren(((e,t)=>{let r=document.createDocumentFragment();for(let n of e)"text"!==n.kind?r.appendChild(Zi(n.ref,{readonly:!0,render:t})):r.appendChild(document.createTextNode(n.text));return r})(t,n));e.innerHTML=s;let i=new RegExp(`${o}:(\\d+)`),l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),d=[];for(let e=l.nextNode();e;e=l.nextNode())d.push(e);for(let e of d){let r=e;for(let e=i.exec(r.data);e;e=i.exec(r.data)){let o=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===o?.kind&&a.parentNode?.insertBefore(Zi(o.ref,{readonly:!0,render:n}),a),r=a}}})(M,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=T(),A&&S?.useCaret&&!w&&v){let e=si(),t=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=M.lastElementChild;t?t.appendChild(e):M.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=nl(e,d,"span");t.classList.add("persona-timestamp-inline");let r=M.lastElementChild;r?r.appendChild(t):M.appendChild(t)}if(b.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let n=ne("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),r?.())};return e.forEach((e,t)=>{let r=ne("img");r.alt=e.alt?.trim()||`Attached image ${t+1}`,r.loading="lazy",r.decoding="async",r.referrerPolicy="no-referrer",r.style.display="block",r.style.width="100%",r.style.maxWidth="320px",r.style.maxHeight="320px",r.style.height="auto",r.style.objectFit="contain",r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let a=!1;o+=1,r.addEventListener("error",()=>{a||(a=!0,o=Math.max(0,o-1),r.remove(),0===o&&s())}),r.addEventListener("load",()=>{a=!0}),(e=>{let t=e.toLowerCase();return!(t.startsWith("data:image/svg+xml")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:image/")&&e.includes(":"))})(e.image)?(r.src=e.image,n.appendChild(r)):(a=!0,o=Math.max(0,o-1),r.remove())}),0===o?(s(),null):n}catch{return r?.(),null}})(b,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let L=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"audio"===e.type&&"string"==typeof e.audio&&e.audio.trim().length>0):[])(e);if(L.length>0){let e=(e=>{if(0===e.length)return null;try{let t=ne("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!el(e.audio))return;let n=ne("audio");n.controls=!0,n.preload="metadata",n.src=e.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(L);e&&g.appendChild(e)}let P=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"video"===e.type&&"string"==typeof e.video&&e.video.trim().length>0):[])(e);if(P.length>0){let e=(e=>{if(0===e.length)return null;try{let t=ne("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!el(e.video))return;let n=ne("video");n.controls=!0,n.preload="metadata",n.src=e.video,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",n.style.maxHeight="320px",n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(P);e&&g.appendChild(e)}let B=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"file"===e.type&&"string"==typeof e.data&&e.data.trim().length>0):[])(e);if(B.length>0){let e=(e=>{if(0===e.length)return null;try{let t=ne("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!el(e.data))return;let n=ne("a");n.href=e.data,n.download=e.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let N=e.contentSegments?.length?null:(e=>{if(!e||0===e.length)return null;let t=oe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=oe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),n=ne("span","persona-mention-chip-icon"),o=xe(r.iconName??"at-sign",13,"currentColor",2);o&&n.appendChild(o),e.appendChild(n),e.appendChild(oe("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(N&&g.appendChild(N),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=nl(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let R="assistant"===e.role?((e,t)=>{if(!e)return null;let r=(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}})(e);if(null===r)return null;let n=t?.[e];return(void 0!==n?n:r)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!I||!I.trim()),t="skeleton"===x.placeholder,r=t&&"line"===x.buffer&&e;if(e)r&&g.appendChild(ii());else if(t)g.appendChild(ii());else{let e=rl("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}R&&e.stopReason&&!e.streaming&&(v||(M.style.display="none"),g.appendChild(((e,t)=>{let r=ne("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r})(e.stopReason,R)));let H="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==n?.enabled,$=a?.actionEligibility,W="user"===e.role&&!e.streaming&&!1!==n?.enabled&&(!0===n?.showEdit&&!0===$?.canEdit||!0===n?.showQuote&&!0===$?.canQuote||ll(n,"user").length>0);if((H||W)&&n){let t=dl(e,W?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,o,$);g.appendChild(t)}if(!c||"system"===e.role)return g;let D=ne("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),O=((e,t)=>{let r=ne("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n="user"===t?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=ne("img");e.src=n,e.alt="user"===t?"User":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent="user"===t?"U":"A",r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?D.append(g,O):D.append(O,g),D},pl=(e,t,r,n,o,a)=>{let s=r??{};return"user"===e.role&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):"assistant"===e.role&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):cl(e,t,r,n,o,a)},ul=(e,t,r)=>{t.hidden=!r,t.style.display=r?"":"none",e.classList.toggle("persona-gap-6",r),e.classList.toggle("persona-gap-3",!r)},hl=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=""===t.subtitle,((e,t)=>{if(e.replaceChildren(),t){if("function"==typeof t){let r=null;try{r=t()}catch(e){console.warn("[persona] welcome.icon renderer threw",e)}return r?(e.appendChild(r),void(e.hidden=!1)):void(e.hidden=!0)}if("lucide"===t.type){let r=xe(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(oe("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(oe("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1}else e.hidden=!0})(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-layout",t.layout??"top"),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),"inline"===t.iconPlacement?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},ml="data-persona-welcome-overlay",gl="persona-welcome-overlay-active",fl=new WeakMap,yl=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(ml,""),e.classList.contains(gl)||(fl.set(e,e.scrollTop),e.classList.add(gl),e.scrollTop=0)},bl=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(ml),e.classList.contains(gl)&&(e.classList.remove(gl),e.scrollTop=fl.get(e)??e.scrollTop,fl.delete(e))},vl=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let n=r?.layout?.messages?.layout??"bubble",o=oe("div",{className:ol("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===n?{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(oe("div",{className:"persona-flex"},o)),e.hidden=!1},wl=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xl=new WeakSet,Cl=(e,t)=>!!e&&void 0!==e[t],Sl=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,n=e?.copy,o=!0===e?.future?.v5Defaults,a=r?.layout??(o?"centered":"top"),s=Cl(r,"variant")?r.variant:!1===n?.showWelcomeCard?"none":"card",i="hero"!==s||o||void 0!==r?.layout?Cl(r,"dismiss")?r.dismiss:o||"hero"===s?"on-first-message":"never":"on-first-message",l=[];Cl(r,"title")&&Cl(n,"welcomeTitle")&&l.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Cl(r,"subtitle")&&Cl(n,"welcomeSubtitle")&&l.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Cl(r,"variant")&&Cl(n,"showWelcomeCard")&&l.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),"hero"===s&&Cl(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!o&&void 0===r?.layout&&"hero"===s&&Cl(r,"dismiss")&&"on-first-message"!==r.dismiss&&l.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let d=r?.anchor??("centered"===a&&t?"center":"bottom"),c=null!==Is(r?.anchorComposerTop);return Cl(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(Cl(r,"anchorComposerTop")||Cl(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{!e||!0!==e.debug||!t.length||xl.has(e)||(xl.add(e),t.forEach(e=>console.warn(`[persona] ${e}`)))})(e,l),{title:Cl(r,"title")?r.title:n?.welcomeTitle??(o?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:Cl(r,"subtitle")?r.subtitle:n?.welcomeSubtitle??(o?"":"I can answer questions and help you get things done here."),icon:r?.icon,align:"start"===r?.align||"center"===r?.align?r.align:"centered"===a?"center":void 0,iconPlacement:r?.icon&&"function"!=typeof r.icon&&"inline"===r.icon.placement?"inline":"above",variant:s,dismiss:i,message:"hero"===s?void 0:r?.message,layout:a,anchor:d,anchorComposerTop:c?r.anchorComposerTop:"44%",composerGap:r?.composerGap?.trim()||As}},kl=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!(t??[]).some(e=>"user"===e.role)),Al="var(--persona-components-panel-height)",Ml=e=>{let t=F(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,n=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===n?`max(200px, ${Al})`:`max(200px, calc(${Al} - ${n}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},Il="16px",Tl="10px",El="14px",Ll=e=>{let t=oe("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ci(e)}});return t.hidden=!0,t},Pl=(e,t)=>{let r=((e,t,r={})=>{let n=oe("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let o=ne("p","persona-welcome-kicker");o.hidden=!0;let a=ne("h2","persona-welcome-title"),s=ne("p","persona-welcome-subtitle"),i=oe("div",{className:"persona-welcome-head-text"},o,a),l=oe("div",{className:"persona-welcome-title-row"},n,i);return{host:oe("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:r.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},l,s,t),iconHolder:n,kicker:o,title:a,subtitle:s,starterSuggestions:t}})(0,Ll("starter"),{flatShadow:vi(e)}),n=Sl(e);hl(r,n),ul(t,r.host,kl(n,e?.initialMessages));let o=(()=>{let e=oe("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return vl(o,n.message,e),{welcome:r,greetingHost:o}},Bl=(e,t)=>{let r=ne("button");r.type="button",r.innerHTML='\n <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">💬</span>\n <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />\n <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">\n <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>\n <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>\n </span>\n <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">↗</span>\n ',r.addEventListener("click",t);let n=e=>{let t=e.launcher??{},n=vi(e),o="circle"===Ha(e);o?(r.dataset.personaLauncherVariant="circle",r.setAttribute("aria-label",t.title??"Open chat")):(r.removeAttribute("data-persona-launcher-variant"),r.removeAttribute("aria-label"));let a=r.querySelector("[data-role='launcher-title']");if(a){let e=t.title??"Chat Assistant";a.textContent=e,a.setAttribute("title",e)}let s=r.querySelector("[data-role='launcher-subtitle']");if(s){let e=t.subtitle??"Here to help you get answers fast";s.textContent=e,s.setAttribute("title",e)}let i=r.querySelector(".persona-flex-col");i&&(t.textHidden||n||o?i.style.display="none":i.style.display="");let l=r.querySelector("[data-role='launcher-icon']");if(l)if(t.agentIconHidden)l.style.display="none";else{let e=t.agentIconSize??"40px";if(l.style.height=e,l.style.width=e,t.agentIconBackgroundColor?(l.style.backgroundColor=t.agentIconBackgroundColor,l.classList.remove("persona-bg-persona-primary")):(l.style.backgroundColor="",l.classList.add("persona-bg-persona-primary")),l.innerHTML="",t.agentIconName){let r=parseFloat(e)||24,n=xe(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);n?(l.appendChild(n),l.style.display=""):(l.textContent=t.agentIconText??"💬",l.style.display="")}else t.iconUrl?l.style.display="none":(l.textContent=t.agentIconText??"💬",l.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let e=t.agentIconSize??"40px";d.style.height=e,d.style.width=e,!t.iconUrl||t.agentIconName||t.agentIconHidden?d.style.display="none":(d.src=t.iconUrl,d.style.display="block")}let c=r.querySelector("[data-role='launcher-call-to-action-icon']");if(c){let e=t.callToActionIconSize??"32px";c.style.height=e,c.style.width=e,t.callToActionIconBackgroundColor?(c.style.backgroundColor=t.callToActionIconBackgroundColor,c.classList.remove("persona-bg-persona-primary")):(c.style.backgroundColor="",c.classList.add("persona-bg-persona-primary")),t.callToActionIconColor?(c.style.color=t.callToActionIconColor,c.classList.remove("persona-text-persona-call-to-action")):(c.style.color="",c.classList.add("persona-text-persona-call-to-action"));let r=0;if(t.callToActionIconPadding?(c.style.boxSizing="border-box",c.style.padding=t.callToActionIconPadding,r=2*(parseFloat(t.callToActionIconPadding)||0)):(c.style.boxSizing="",c.style.padding=""),t.callToActionIconHidden||o)c.style.display="none";else if(c.style.display=n?"none":"",c.innerHTML="",t.callToActionIconName){let n=parseFloat(e)||24,o=Math.max(n-r,8),a=xe(t.callToActionIconName,o,"currentColor",1.5);a?c.appendChild(a):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&Ii[t.position]?Ii[t.position]:Ii["bottom-right"];r.className=n?"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":`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 ${p}`,n||(r.style.zIndex=String(t.zIndex??pn)),r.style.border=t.border??"1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",r.style.boxShadow=void 0!==t.shadow?""===t.shadow.trim()?"none":t.shadow:"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?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=t.collapsedMaxWidth??"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")};return e&&n(e),{element:r,update:n,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},Nl=new Set,Rl=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},Hl=(e,t)=>{let r=ne("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let n=e??{},o=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(o?.frequency??"once")&&!1!==n.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,!a||!d||(d=!1,a.hidden=!0),((e,t)=>{if(Nl.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(Rl(n),e&&h())},f=e=>{!o||p||g("user"===e&&d)},y=()=>{l=null,a&&!p&&!u&&(c=!0,d=!0,a.hidden=!1,!(typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||"function"!=typeof a.animate)&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},b=()=>{g(h()),t()},v=e=>{e.stopPropagation(),g(h())},w=Bl(e,()=>{f("user"),t()}),x=()=>{m(),i?.removeEventListener("click",b),s?.removeEventListener("click",v),a?.remove(),a=null,i=null,s=null,d=!1},C=()=>{let e=n.launcher?.position??"bottom-right",t=Ii[e]??Ii["bottom-right"];if(!a)return r.className="persona-launcher-surface",r.removeAttribute("data-teaser"),r.style.zIndex="",void(w.element.style.position="");r.className=ae("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(n.launcher?.zIndex??pn),w.element.style.position="static"},S=e=>{let t=(e=>{let t=e?.launcher?.teaser;return t&&t.text&&!1!==e?.launcher?.enabled&&!vi(e??{})?t:null})(e);o=t,t?(a||(i=oe("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",b),s=oe("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=oe("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},i,s),r.insertBefore(a,w.element)),i.textContent=t.text,s.hidden=!1===t.dismissible,s.setAttribute("aria-label",t.dismissLabel??"Dismiss message"),!o||!a||p||c||u||((e,t)=>{if(Nl.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(Rl(n),h())||(m(),l=setTimeout(y,Math.max(0,o.delayMs??0)))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:y,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{n=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}},$l=({config:e,showClose:t})=>{let{wrapper:r,panel:n,pillRoot:o}=(e=>{let t=e?.launcher?.enabled??!0,r=vi(e);if(wi(e)){let t=e?.launcher?.composerBar??{},r=ne("div","persona-widget-wrapper persona-fixed persona-transition");r.setAttribute("data-persona-composer-bar",""),r.dataset.state="collapsed",r.dataset.expandedSize=t.expandedSize??"anchored",r.style.zIndex=String(e?.launcher?.zIndex??pn);let n=ne("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");n.style.width="100%",r.appendChild(n);let o=ne("div","persona-widget-pill-root");return o.setAttribute("data-persona-composer-bar",""),o.dataset.state="collapsed",o.dataset.expandedSize=t.expandedSize??"anchored",o.style.zIndex=String(e?.launcher?.zIndex??pn),{wrapper:r,panel:n,pillRoot:o}}if(r){let e=ne("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=ne("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=ne("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=ne("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),n=F(e),o=n.launcherWidth||n.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?Ml(e).width:"100%";return t.style.width=o,r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let n=e?.launcher??{},o=n.position&&Ii[n.position]?Ii[n.position]:Ii["bottom-right"],a=ne("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??pn);let s=ne("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=Ml(e);return s.style.width=i.width,s.style.maxWidth=i.maxWidth,a.appendChild(s),{wrapper:a,panel:s}})(e),a=((e,t=!0)=>{if(wi(e))return((e,t)=>{let r=ne("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Ni(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Il,iconSize:Tl});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=Ri(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Il,iconSize:El});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=oe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=oe("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"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=Pl(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=ne("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=Ll("followUp"),b=ks(e,!0);b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),l.append(p,c,g,f);let v=oe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),w=Qi({config:e}),{root:x,textNode:C}=(()=>{let e=oe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=ne("span","persona-pill-peek__icon"),r=I(A,16,"currentColor",1.5);r&&t.appendChild(r);let n=ne("span","persona-pill-peek__text"),o=ne("span","persona-pill-peek__caret"),a=I(y,16,"currentColor",1.5);return a&&o.appendChild(a),e.append(t,n,o),{root:e,textNode:n}})();return r.append(i,o,l,v),s&&r.appendChild(s),{container:r,body:l,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:f,composerOverlay:v,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,welcomeHost:p,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:u,introSubtitle:h,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:ne("span"),headerTitle:ne("span"),headerSubtitle:ne("span"),header:i,footer:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode,peekBanner:x,peekTextNode:C}})(e,t);let r=oe("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"}}),n=e?.layout?.header,o=!1!==e?.layout?.showHeader,a=n?Yi(e,n,{showClose:t}):Di({config:e,showClose:t}),s=oe("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:i,greetingHost:l}=Pl(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=ne("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=Ll("followUp"),g=ks(e,!1);g&&(h.style.maxWidth=g,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),s.append(d,l,h,m);let f=Xi({config:e}),b=!1!==e?.layout?.showFooter;o||(a.header.style.display="none"),Oi(r,a,e),r.append(s);let v=oe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return b||(f.footer.style.display="none"),r.append(f.footer),r.append(v),{container:r,body:s,messagesWrapper:h,starterSuggestions:u,transcriptSuggestions:m,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,welcomeHost:d,welcomeIconHolder:i.iconHolder,greetingHost:l,introKicker:i.kicker,introTitle:c,introSubtitle:p,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}})(e,t),s={wrapper:r,panel:n,pillRoot:o},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},l={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:l,composer:d,replaceHeader:e=>(l.element.replaceWith(e.header),l.element=e.header,l.iconHolder=e.iconHolder,l.headerTitle=e.headerTitle,l.headerSubtitle=e.headerSubtitle,l.closeButton=e.closeButton,l.closeButtonWrapper=e.closeButtonWrapper,l.clearChatButton=e.clearChatButton,l.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{d.footer.replaceWith(e),d.footer=e}}},Wl=({config:e,plugins:t,onToggle:r})=>{let n=t.find(e=>e.renderLauncher);if(n?.renderLauncher){let t=n.renderLauncher({config:e,defaultRenderer:()=>Bl(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let o=Hl(e,r);return{instance:o,element:o.element}},Dl=(e,t,r)=>{let n=r;for(let r of t){let t=ne("span","persona-tool-char");t.style.setProperty("--char-index",String(n)),t.textContent=" "===r?" ":r,e.appendChild(t),n++}return n},Ol=(e,t,r)=>{Ee(e,t,{stateSet:r,previewKind:"reasoning",iconColor:"currentColor"})},Fl=(e,t,r=new Set)=>{t=Le(t,"reasoning");let n=e.reasoning,o=Se("persona-reasoning-bubble",e.id);if(!n)return Ne(o,e,t,"reasoning");let a=t?.features?.reasoningDisplay??{},s=a.expandable??J.expandable,i=s&&r.has(e.id),l="complete"!==n.status,d=((e,t)=>{let r=e.reasoning?.chunks.join("").trim()??"";return r?r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,a.previewMaxLines??J.previewMaxLines),c=ke({expandable:s,expanded:i,bubbleType:"reasoning"}),p=ne("div","persona-flex persona-flex-col persona-text-left"),u=ne("span","persona-text-xs persona-text-persona-primary"),h="row"===Pe(t,"reasoning"),m=h&&!l?`Thought for ${Be(n.durationMs??(void 0!==n.completedAt&&void 0!==n.startedAt?n.completedAt-n.startedAt:void 0))}`:"Thinking...",g=t?.reasoning??{},f=String(n.startedAt??Date.now()),y=()=>{let e=ne("span","");return e.setAttribute("data-tool-elapsed",f),e.textContent=Nr(n),e},b=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:m,previewText:d,isActive:l,config:t??{},elapsed:Nr(n),createElapsedElement:y});"string"==typeof b&&b.trim()?(u.textContent=b,p.appendChild(u)):b instanceof HTMLElement?p.appendChild(b):(u.textContent=m,p.appendChild(u));let v=ne("span","persona-text-xs persona-text-persona-primary");v.textContent=(e=>"complete"===e.status?(e=>{let t=e.completedAt??Date.now(),r=e.startedAt??t,n=(void 0!==e.durationMs?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"pending"===e.status?"Waiting":"")(n),h||p.appendChild(v);let w=a.loadingAnimation??J.loadingAnimation,x=g.activeTextTemplate,C=g.completeTextTemplate,S=l?x:C,k=b instanceof HTMLElement,A=(e,t)=>{u.textContent="";let r=Hr(e,""),o=0;for(let e of r){let r=e.styles.length>0?(()=>{let t=ne("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return u.appendChild(t),t})():u;if(e.isDuration&&l)r.appendChild(y());else{let a=e.isDuration?Nr(n):e.text;t?o=Dl(r,a,o):r.appendChild(document.createTextNode(a))}}};if(!k&&S)if(v.style.display="none",u.style.display="",l&&"none"!==w){let e=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),"pulse"===w?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),A(S,!1)):(u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),A(S,!0))}else A(S,!1);else if(!k&&l&&"none"!==w){u.style.display="";let e=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),"pulse"===w)u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`);else{u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let t=u.textContent||m;u.textContent="",Dl(u,t,0)}"complete"===n.status&&!h&&(u.style.display="none")}else k||("complete"!==n.status||h?u.style.display="":u.style.display="none");if(a.iconName&&!k){let e=ne("span","persona-reasoning-header-icon"),t=xe(a.iconName,16,"currentColor",2);t&&(e.appendChild(t),c.appendChild(e))}let M="currentColor",I=Me(c,p,{expandable:s,expanded:i,iconColor:M,metaGap:!1}),T=Ie({bubble:o,previewKind:"reasoning",expanded:i,isActive:l,previewText:d,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return o.append(c,T),Ne(o,e,t,"reasoning");let E=ne("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let L=n.chunks.join(""),P=ne("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return P.textContent=L||("complete"===n.status?"No additional context was shared.":"Waiting for details…"),E.appendChild(P),Te({expanded:i,header:c,toggleIcon:I,content:E,collapsedPreview:T,iconColor:M}),o.append(c,T,E),Ne(o,e,t,"reasoning")},zl=e=>{if(null==e)return!0;if("string"==typeof e){if(!e.trim())return!0;try{return zl(JSON.parse(e))}catch{return!1}}return"object"==typeof e&&0===Object.keys(e).length},ql=e=>{if(null!==e&&"object"==typeof e)return!0;if("string"!=typeof e)return!1;try{let t=JSON.parse(e);return null!==t&&"object"==typeof t}catch{return!1}},jl=new WeakMap,_l=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),Vl=(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)"},Ul=(e,t)=>{let r=e.toolCall,n=t?.features?.toolCallDisplay,o=n?.collapsedMode??K.collapsedMode,a=!1===r?.success?r.error||"Tool failed":((e,t)=>{let r=e.toolCall;if(!r)return"";let n=(r.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join("\n");let o=Lr(r.args).trim();return o?o.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,n?.previewMaxLines??K.previewMaxLines),s=r?"row"===Pe(t,"tool")?`${"complete"===r.status?"Used":"Using"} ${r.name?.trim()||"tool"}`:(e=>"complete"===e.status?(e=>{let t=("number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"Using tool...")(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i="complete"!==r.status,l=t?.toolCall??{},d=s;return"tool-name"===o?d=r.name?.trim()||s:"tool-preview"===o&&a&&(d=a),i&&l.activeTextTemplate?d=Rr(r,l.activeTextTemplate,d):!i&&l.completeTextTemplate&&(d=Rr(r,l.completeTextTemplate,d)),!1===r.success?d+=" · Failed":r.superseded&&(d+=" · Approved, ran again below"),{summary:d,previewText:a,isActive:i}},Kl=(e,t,r,n)=>{Ee(e,t,{stateSet:r,previewKind:"tool",iconColor:_l(n?.toolCall??{},t.classList.contains("persona-activity-row"))})},Jl=(e,t,r=new Set)=>{t=Le(t,"tool");let n=e.toolCall,o=t?.toolCall??{},a=Se("persona-tool-bubble",e.id);if(o.backgroundColor&&(a.style.backgroundColor=o.backgroundColor),o.borderColor&&(a.style.borderColor=o.borderColor),o.borderWidth&&(a.style.borderWidth=o.borderWidth),o.borderRadius&&(a.style.borderRadius=o.borderRadius),a.style.boxShadow=void 0!==o.shadow?""===o.shadow.trim()?"none":o.shadow:"var(--persona-tool-bubble-shadow)",!n)return Ne(a,e,t,"tool");let s=t?.features?.toolCallDisplay??{},i=s.expandable??K.expandable,l=i&&r.has(e.id),{summary:d,previewText:c,isActive:p}=Ul(e,t),u=ke({expandable:i,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let h=ne("div","persona-flex persona-flex-col persona-text-left"),m=ne("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let g=String(n.startedAt??Date.now()),f=()=>{let e=ne("span","");return e.setAttribute("data-tool-elapsed",g),e.textContent=Br(n),e},y=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:s.collapsedMode??K.collapsedMode,isActive:p,config:t??{},elapsed:Br(n),createElapsedElement:f});"string"==typeof y&&y.trim()?(m.textContent=y,h.appendChild(m)):y instanceof HTMLElement?h.appendChild(y):(m.textContent=d,h.appendChild(m));let b=s.loadingAnimation??K.loadingAnimation,v=o.activeTextTemplate,w=o.completeTextTemplate,x=p?v:w,C=(e,t)=>{m.textContent="";let r=n.name?.trim()||"tool",o=Hr(e,r),a=0;for(let e of o){let r=e.styles.length>0?(()=>{let t=ne("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return m.appendChild(t),t})():m;if(e.isDuration&&p)r.appendChild(f());else{let o=e.isDuration?Br(n):e.text;t?a=Dl(r,o,a):r.appendChild(document.createTextNode(o))}}};if(!(y instanceof HTMLElement))if(p&&"none"!==b){let e=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),"pulse"===b)m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${b}`),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===b&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||d;m.textContent="",Dl(m,e,0)}}else x&&C(x,!1);let S=_l(o,"row"===Pe(t,"tool")),k=Me(u,h,{expandable:i,expanded:l,iconColor:S,metaGap:!0}),A=Ie({bubble:a,previewKind:"tool",expanded:l,isActive:p,previewText:c,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:p,config:t??{}})});if(!i)return a.append(u,A),Ne(a,e,t,"tool");let M=ne("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=l?"":"none",o.contentBackgroundColor&&(M.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(M.style.color=o.contentTextColor),o.contentPaddingX&&(M.style.paddingLeft=o.contentPaddingX,M.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(M.style.paddingTop=o.contentPaddingY,M.style.paddingBottom=o.contentPaddingY),!0===t.future?.v5Defaults)!function(e,t,r){let n=t.toolCall;if(!n)return;let o=r.toolCall??{},a=(t,r)=>{let n=oe("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:o.codeBlockBackgroundColor,borderColor:o.codeBlockBorderColor,borderWidth:o.codeBlockBorderColor?"1px":void 0}}),a=oe("div",{className:"persona-tool-detail-label",text:t,style:{color:o.labelTextColor}}),s=Lr(r),i=oe("pre",{className:"persona-tool-detail-value"+(ql(r)?" persona-tool-detail-code":""),text:s,attrs:s.length>420||s.split("\n").length>7?{tabindex:"0","aria-label":`${t} content`}:{},style:{color:o.codeBlockTextColor??o.contentTextColor}}),l=oe("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),d=xe("copy",14,"currentColor",1.7);d&&l.appendChild(d),n.append(a,i,l),e.appendChild(n)};zl(n.args)||a("Request",n.args);let s="complete"===n.status&&void 0!==n.result?n.result:n.chunks?.join("");void 0!==s&&("string"!=typeof s||s.trim())&&a("Response",s),!1===n.success&&e.appendChild(oe("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}(M,e,t);else{if(n.name){let e=ne("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,M.appendChild(e)}if(void 0!==n.args){let e=ne("div","persona-space-y-1"),t=ne("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Arguments";let r=ne("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Vl(r,o),r.textContent=Lr(n.args),e.append(t,r),M.appendChild(e)}if(n.chunks&&n.chunks.length){let e=ne("div","persona-space-y-1"),t=ne("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Activity";let r=ne("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Vl(r,o),r.textContent=n.chunks.join(""),e.append(t,r),M.appendChild(e)}if(!1===n.success&&M.appendChild(oe("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),"complete"===n.status&&void 0!==n.result){let e=ne("div","persona-space-y-1"),t=ne("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Result";let r=ne("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Vl(r,o),r.textContent=Lr(n.result),e.append(t,r),M.appendChild(e)}if("complete"===n.status&&"number"==typeof n.duration){let e=ne("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(e.style.color=o.contentTextColor),e.textContent=`Duration: ${n.duration}ms`,M.appendChild(e)}}return Te({expanded:l,header:u,toggleIcon:k,content:M,collapsedPreview:A,iconColor:S}),a.append(u,A,M),Ne(a,e,t,"tool")},{setLoader:Gl,load:Yl,provide:Xl,getSync:Ql}=se({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),Zl=Gl,ed=Yl,td=Ql,{setLoader:rd,load:nd}=se({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),od=rd,ad=nd,sd=new class{constructor(){this.components=new Map,this.#h=new Map}#h;register(e,t,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),r?this.#h.set(e,r):this.#h.delete(e)}unregister(e){this.components.delete(e),this.#h.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#h.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#h.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}},id=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:ld,load:dd,provide:cd,getSync:pd}=se({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ud=null,hd=new Set,md=e=>{if(ud)return ud;ud=e,e.initArtifactsUi({componentRegistry:sd});for(let t of id)sd.has(t)||sd.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Ve();t?e.__provideMarkdownParsers(t):_e(()=>{let t=Ve();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>ce());let r=[...hd];hd.clear();for(let e of r)try{e()}catch{}return e},gd=ld,fd=()=>dd().then(md),yd=()=>{if(ud)return ud;let e=pd();return e?md(e):null},bd=e=>ud?()=>{}:(hd.add(e),()=>{hd.delete(e)});function vd(e){return!0===e?.features?.artifacts?.enabled}function wd(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"),!vd(t))return;let r=t.features?.artifacts?.layout,n=r?.paneBorder?.trim(),o=r?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}var xd=["panel","seamless","detached"];function Cd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&xd.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Sd(e){return!(!e||!vd(e))&&"detached"===Cd(e)}function kd(e,t){if(!vd(t))return 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"),function(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")}(e),void wd(e,t);let r=t.features?.artifacts?.layout,n="detached"===Cd(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",r?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",r?.paneMaxWidth??"28rem"),r?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",r.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),r?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=r?.paneBackground?.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let a=r?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[r?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[r?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[r?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[r?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let n=t?.trim();n?e.style.setProperty(r,n):e.style.removeProperty(r)}wd(e,t)}function Ad(e,t){for(let t of xd)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!vd(t))return;let r=t.features?.artifacts?.layout,n=Cd(t);e.classList.add(`persona-artifact-appearance-${n}`);let o=r?.paneBorderRadius?.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=r?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=r?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}var Md=new Set(["__proto__","prototype","constructor"]),Id=new Set(["collapsed","card","panel","inline"]),Td=new Set(["markdown","component"]),Ed=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ld=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Pd=e=>!Md.has(e),Bd=e=>"string"==typeof e&&Id.has(e),Nd=e=>Object.keys(e).length>0;function Rd(e,t,r,n){e.push({path:t,code:r,message:n})}var Hd="Ignored because this key is not part of the persisted preference schema.",$d="Ignored an unsupported value.",Wd="Expected collapsed, panel, or inline.",Dd='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Od={kind:"mode",message:$d},Fd={kind:"string",message:"Expected a CSS length string."},zd={kind:"boolean"},qd={paneWidth:Fd,paneMaxWidth:Fd,paneMinWidth:Fd,expandedPanelWidth:Fd,resizableMinWidth:Fd,resizableMaxWidth:Fd,expandLauncherPanelWhenOpen:zd,resizable:zd},jd={kind:"object",message:"Expected a preference object.",children:{showToolCalls:zd,showReasoning:zd,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:$d},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:$d},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:$d},expandable:zd,grouped:zd}},reasoningDisplay:{kind:"object",children:{expandable:zd,activePreview:zd}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Od,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Od,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Td,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Td}}},filePreview:{kind:"object",children:{enabled:zd}},layout:{kind:"object",children:qd}}}}};function _d(e,t,r,n){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:Rd(n,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:Rd(n,r,"invalid_type",t.message);case"enum":return"string"==typeof e&&t.values.has(e)?e:Rd(n,r,"invalid_value",t.message);case"mode":return Bd(e)?$n(e):Rd(n,r,"invalid_value",t.message);case"modeMap":{if(!Ld(e))return Rd(n,r,"invalid_type","Expected an object.");let o="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=o?t:Wn(t);Pd(t)&&(o?o.has(t):Ed.test(e))?Bd(s)?a[e]=$n(s):Rd(n,`${r}.${t}`,"invalid_value",Wd):Rd(n,`${r}.${t}`,o?"unknown_key":"invalid_value",o?"Ignored an unsupported selector.":Dd)}return Nd(a)?a:void 0}case"object":{if(t.bareMode&&Bd(e))return $n(e);if(!Ld(e))return Rd(n,r,"invalid_type",t.message??"Expected an object.");let o=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!Pd(t)||!o.includes(t))&&Rd(n,a(t),"unknown_key",Hd);let s={};for(let r of o){let o=t.children[r],i=_d(e[r],o,a(r),n);if(o.deprecated&&void 0!==e[r]&&Rd(n,a(r),"deprecated_key",o.deprecated),void 0===i)continue;let l=o.alias??r,d=s[l];s[l]=Ld(d)&&Ld(i)?{...d,...i}:i}return Nd(s)?s:void 0}}}function Vd(e){let t=[];return{preferences:(null===e?void 0:_d(e,jd,"",t))??{},issues:t}}function Ud(e){if(Array.isArray(e))return e.map(Ud);if(!Ld(e))return e;let t={};for(let[r,n]of Object.entries(e))Pd(r)&&void 0!==n&&(t[r]=Ud(n));return t}function Kd(e,t){let r=Ud(e);for(let[e,n]of Object.entries(t)){if(!Pd(e)||void 0===n)continue;let t=r[e];r[e]=Ld(t)&&Ld(n)?Kd(t,n):Ud(n)}return r}function Jd(e,t){if(void 0===t)return void 0===e?void 0:Ud(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return void 0===e?void 0:Ud(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Nd(o)?{byMediaType:o}:{}};return Nd(a)?a:void 0}(r.files,t.files),s={...n?{default:n}:{},...Nd(o)?{byKind:o}:{},...void 0!==a?{files:a}:{}};return Nd(s)?s:void 0}function Gd(e={},t){let r=function(e){let t,r={};for(let n of e){let e=Vd(n).preferences;t=Jd(t,e.artifacts?.display),r=Kd(r,e)}let n=r;return n.artifacts&&(void 0!==t?n.artifacts.display=t:delete n.artifacts.display),n}(t),n={...e};if(void 0!==r.showToolCalls&&(n.showToolCalls=r.showToolCalls),void 0!==r.showReasoning&&(n.showReasoning=r.showReasoning),r.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...r.toolCallDisplay}),r.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...r.reasoningDisplay}),r.artifacts){let t=e.artifacts??{},o={...t};if(void 0!==r.artifacts.display){let e=Jd(t.display,r.artifacts.display);void 0!==e&&(o.display=e)}r.artifacts.filePreview&&(o.filePreview={...t.filePreview,enabled:r.artifacts.filePreview.enabled}),r.artifacts.layout&&(o.layout={...t.layout,...r.artifacts.layout}),n.artifacts=o}return n}function Yd(e){let t=e.preferences;return t&&Nd(t)?{...e,features:Gd(e.features??{},[t])}:e}function Xd(e,t){let r=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",n=/^([\d.]+)px$/i.exec(r);if(n)return Number(n[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}var{setLoader:Qd,load:Zd,provide:ec,getSync:tc}=se({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),rc=Qd,nc=Zd,oc=tc,ac=new class{#h=new Map;register(e){this.#h.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#h.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#h.get(e);t&&(t.onUnregister?.(),this.#h.delete(e))}getAll(){return Array.from(this.#h.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||0===e.length)return t;let r=new Set(e.map(e=>e.id));return[...t.filter(e=>!r.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#h.forEach(e=>e.onUnregister?.()),this.#h.clear()}},sc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ic=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),lc=(e,t,r)=>{if(!sc(e)||!sc(t)||ic.has(r))return t;let n={...e};for(let o of Object.keys(t)){if(void 0===t[o]){delete n[o];continue}let a=r?`${r}.${o}`:o;n[o]=lc(e[o],t[o],a)}return n};function dc(e,t){let r=B(X),n=function(e,t,r){let n=t[L];if(n)return n;let o=new Set(R(e,r));for(let e of r){let r=N(t,e);"clear"===r&&o.delete(e),"explicit"===r&&o.add(e)}return[...o]}(e,t,r),o=H(function(e,t,r){let n={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),o=n;for(let e of t.slice(0,-1)){let t=o[e];if(!P(t)){o=void 0;break}o[e]={...t},o=o[e]}o&&delete o[t[t.length-1]]}return n}(lc(e,t,""),r,n),n);return z(re(o),((e,t)=>{let r=t[W];if(r)return{...r};let n=F(e);return D(t,"launcherWidth")&&(n.legacyLauncherWidth=void 0!==t.launcherWidth),D(t,"launcher")&&void 0===t.launcher?(n.launcherWidth=!1,n.sidebarWidth=!1,n.dockWidth=!1,n):(D(t.launcher,"width")&&(n.launcherWidth=void 0!==t.launcher?.width),D(t.launcher,"sidebarWidth")&&(n.sidebarWidth=void 0!==t.launcher?.sidebarWidth),D(t.launcher,"dock")&&void 0===t.launcher?.dock?n.dockWidth=!1:D(t.launcher?.dock,"width")&&(n.dockWidth=void 0!==t.launcher?.dock?.width),n)})(e,t))}var cc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=(e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e})(e),r=(e=>{let t=e.trim(),r=t.indexOf("{");if(-1===r)return null;let n=0;for(let e=r;e<t.length;e+=1){let o=t[e];if("{"===o&&(n+=1),"}"===o&&(n-=1,0===n))return t.slice(r,e+1)}return null})(t);if(!r)return null;let n=JSON.parse(r);if(!n||"object"!=typeof n||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},pc=e=>"string"==typeof e?e:null==e?"":String(e),uc={message:e=>"message"!==e.type?void 0:{handled:!0,displayText:pc(e.payload.text)},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,n=pc(r.element);if(n&&t.document?.querySelector){let e=t.document.querySelector(n);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:pc(r.text)}}},hc=e=>Array.isArray(e)?e.map(e=>String(e)):[],mc=e=>{let t=new Set(hc(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let n="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!n&&"string"==typeof r.text&&r.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 o=n?e.parsers.reduce((e,t)=>e||t?.({text:n,message:r.message})||null,null):null;if(!o)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:o,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let n=()=>{e.emit("action:resubmit",a)},s=t(o,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:n});if(!s)continue;if(s.handled){let e=!1!==s.persistMessage;return{text:void 0!==s.displayText?s.displayText:"",persist:e,resubmit:s.resubmit}}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",e)}return{text:"",persist:!0}},syncFromMetadata:()=>{t=new Set(hc(e.getSessionMetadata().processedActionMessageIds))}}},gc=e=>e.map(e=>({...e,streaming:!1})),fc=e=>e.map(e=>({...e,status:"complete"})),yc=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?(e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}})(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let t={...r,messages:r.messages?gc(r.messages):void 0,artifacts:r.artifacts?fc(r.artifacts):void 0};n.setItem(e,JSON.stringify(t))}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",e)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}},bc=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let r=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return(e=>{let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")})(e)},{setLoader:vc,load:wc}=se({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),xc=vc,Cc=wc,{setLoader:Sc,load:kc,provide:Ac,getSync:Mc}=se({fallbackImport:()=>import("./history-shell")}),Ic=Sc,Tc=kc,Ec=Mc;function Lc(){return null}var Pc=d(p(),1);function Bc(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return e;try{let t=function(e,t){if(!function(e){if(!e||"object"!=typeof e||!("component"in e))return!1;let t=e.component;return"string"==typeof t&&t.length>0}(e))return null;let r=e.props&&"object"==typeof e.props&&null!==e.props?e.props:{};return{component:e.component,props:r,raw:t}}((0,Pc.parse)(r,Pc.STR|Pc.OBJ),r);t&&(e=t)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function Nc(e){return"object"==typeof e&&null!==e&&"component"in e&&"string"==typeof e.component&&"props"in e&&"object"==typeof e.props}function Rc(e,t){let{config:r,message:n,onPropsUpdate:o}=t,a=sd.get(e.component);if(!a){if(id.includes(e.component)){fd().catch(()=>{});let e=ne("div","persona-w-full");return e.setAttribute("data-persona-artifact-pending","true"),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let s={message:n,config:r,updateProps:e=>{o&&o(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Hc(){let e=Bc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function $c(e){if("string"==typeof e.rawContent&&e.rawContent.length>0)return e.rawContent;if("string"==typeof e.content){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Wc(e){let t=$c(e);if(!t)return!1;try{let e=JSON.parse(t);return"object"==typeof e&&null!==e&&"component"in e&&"string"==typeof e.component}catch{return!1}}function Dc(e){let t=$c(e);if(!t)return null;try{let e=JSON.parse(t);if("object"==typeof e&&null!==e&&"component"in e&&"string"==typeof e.component){let r=e;return{component:r.component,props:r.props&&"object"==typeof r.props&&null!==r.props?r.props:{},raw:t}}}catch{}return null}var Oc=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fc(e){let{onSubmit:t,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,ratingLabels:d=Oc}=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 p=null,u=document.createElement("div");u.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=n,h.appendChild(m);let g=document.createElement("p");g.className="persona-feedback-subtitle",g.textContent=o,h.appendChild(g),u.appendChild(h);let f=document.createElement("div");f.className="persona-feedback-rating persona-feedback-rating-csat",f.setAttribute("role","radiogroup"),f.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let e=1;e<=5;e++){let t=document.createElement("button");t.type="button",t.className="persona-feedback-rating-btn persona-feedback-star-btn",t.setAttribute("role","radio"),t.setAttribute("aria-checked","false"),t.setAttribute("aria-label",`${e} star${e>1?"s":""}: ${d[e-1]}`),t.title=d[e-1],t.dataset.rating=String(e),t.innerHTML='\n <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <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>\n </svg>\n ',t.addEventListener("click",()=>{p=e,y.forEach((t,r)=>{let n=r<e;t.classList.toggle("selected",n),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),y.push(t),f.appendChild(t)}u.appendChild(f);let b=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",b=document.createElement("textarea"),b.className="persona-feedback-comment",b.placeholder=a,b.rows=3,b.setAttribute("aria-label","Additional comments"),e.appendChild(b),u.appendChild(e)}let v=document.createElement("div");v.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{r?.(),c.remove()});let x=document.createElement("button");return x.type="button",x.className="persona-feedback-btn persona-feedback-btn-submit",x.textContent=s,x.addEventListener("click",async()=>{if(null===p)return f.classList.add("persona-feedback-shake"),void setTimeout(()=>f.classList.remove("persona-feedback-shake"),500);x.disabled=!0,x.textContent="Submitting...";try{let e=b?.value.trim()||void 0;await t(p,e),c.remove()}catch(e){x.disabled=!1,x.textContent=s,console.error("[CSAT Feedback] Failed to submit:",e)}}),v.appendChild(w),v.appendChild(x),u.appendChild(v),c.appendChild(u),c}function zc(e){let{onSubmit:t,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let u=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let g=document.createElement("h3");g.className="persona-feedback-title",g.textContent=n,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=o,m.appendChild(f),h.appendChild(m);let y=document.createElement("div");y.className="persona-feedback-rating persona-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="persona-feedback-labels";let v=document.createElement("span");v.className="persona-feedback-label-low",v.textContent=d;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=c,b.appendChild(v),b.appendChild(w);let x=document.createElement("div");x.className="persona-feedback-numbers";let C=[];for(let e=0;e<=10;e++){let t=document.createElement("button");t.type="button",t.className="persona-feedback-rating-btn persona-feedback-number-btn",t.setAttribute("role","radio"),t.setAttribute("aria-checked","false"),t.setAttribute("aria-label",`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add("persona-feedback-detractor"):e<=8?t.classList.add("persona-feedback-passive"):t.classList.add("persona-feedback-promoter"),t.addEventListener("click",()=>{u=e,C.forEach((t,r)=>{t.classList.toggle("selected",r===e),t.setAttribute("aria-checked",r===e?"true":"false")})}),C.push(t),x.appendChild(t)}y.appendChild(b),y.appendChild(x),h.appendChild(y);let S=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=a,S.rows=3,S.setAttribute("aria-label","Additional comments"),e.appendChild(S),h.appendChild(e)}let k=document.createElement("div");k.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{r?.(),p.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(null===u)return x.classList.add("persona-feedback-shake"),void setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);M.disabled=!0,M.textContent="Submitting...";try{let e=S?.value.trim()||void 0;await t(u,e),p.remove()}catch(e){M.disabled=!1,M.textContent=s,console.error("[NPS Feedback] Failed to submit:",e)}}),k.appendChild(A),k.appendChild(M),h.appendChild(k),p.appendChild(h),p}var qc="persona-chat-history",jc="data-persona-composer-reason",_c={"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 Vc(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}var Uc=e=>e&&"object"==typeof e?{...e}:{},Kc=e=>e.map(e=>({...e,streaming:!1})),Jc=(e,t,r)=>{let n=e?.markdown?Ke(e.markdown):null,o=at(e?.sanitize);e?.postprocessMessage&&o&&void 0===e?.sanitize&&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.");let a=!1;return s=>{try{return(a=>{let s=a.text??"",i=a.message.rawContent??null;if(t){let e=t.process({text:s,raw:i??s,message:a.message,streaming:a.streaming});null!==e&&(s=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&r&&r())}let l,d=null!==Ve();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=o?o(t):t}else if(n){let e=a.streaming?(e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1];if(!it(n)||st.test(n)||!st.test(o))continue;let a=lt(n).length;if(a<1)continue;let s=ct(a);t[e+1]!==s&&(t[e+1]=s,r=!0);let i=e+2;for(;i<t.length;i++){let e=t[i];if(""===e.trim()||!it(e))break;let n=dt(pt(lt(e),a));t[i]!==n&&(t[i]=n,r=!0)}e=i-1}return r?t.join("\n"):e})(s):s,t=n(e);l=o&&d?o(t):t}else l=Ye(s);return l})(s)}catch(e){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",e)),Ye(s.text??"")}}};function Gc(e){let t=ne("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),void 0!==e?.backdropBlur&&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 r=xe(e?.iconName??"upload",e?.iconSize??"48px",e?.iconColor??"rgba(59, 130, 246, 0.6)",e?.iconStrokeWidth??.5);if(r&&t.appendChild(r),e?.label){let r=ne("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}var Yc=(e,t)=>{let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...n}:n}return r},Xc=(e,t,r)=>{if(null==e)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=re(t),o=new Set,a=new Set,s=function(e){let t=new Set,r=new Set,n=new Set,o=new Map,a=e=>{clearTimeout(o.get(e)),o.delete(e)};return{observe(a,s,i,l={}){let d="tool"===s?a.toolCall:a.reasoning;if(d&&!r.has(a.id)&&(!t.has(a.id)&&"complete"!==d.status&&d.chunks?.some(Boolean)&&(t.add(a.id),!1!==l.autoExpand&&i.add(a.id)),t.has(a.id)&&"complete"===d.status&&!n.has(a.id))){if(n.add(a.id),!1===l.autoCollapseDelay)return;o.set(a.id,setTimeout(()=>{o.delete(a.id),i.delete(a.id),e(a.id,s)},l.autoCollapseDelay??1e3))}},manual(e){r.add(e),a(e)},prune(e){for(let o of new Set([...t,...r,...n]))e.has(o)||(a(o),t.delete(o),r.delete(o),n.delete(o))},clear(){for(let e of o.keys())a(e);t.clear(),r.clear(),n.clear()}}}((e,t)=>{qa.delete(e);let r=Array.from(ct.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e);r&&("tool"===t?Kl(e,r,o,n):Ol(e,r,a))}),i=new Map,l=()=>{!function(e){void 0!==e.delayMs&&(So=Mo(e.delayMs)),void 0!==e.skipDelayMs&&(ko=Mo(e.skipDelayMs))}({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};l();let d=n.features;n=Yd(n);let c=ac.getForInstance(n.plugins),p=(e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),n=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let n=r.composedPath?.();return n?.length?n.includes(e):e.contains(r.target)},o=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let o of t.values())if(Rs(o.parsed,e)&&!1!==o.when?.()&&n(o,e)&&(o.allowInInput||!Hs(r))){e.preventDefault();try{o.run(e)}catch(e){Es(`${o.id} threw on`,o.combo),console.warn(e)}return}};return r?.addEventListener("keydown",o),{register(e){let r=Ls(e.combo);if(!r)return()=>{};let n=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,o=t.get(n);return o?(Es(`${o.id} already owns`,e.combo),()=>{}):(t.set(n,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",Ns(e.combo)),()=>{t.get(n)?.id===e.id&&t.delete(n),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",o)}}})(e),u=[],m=!1,f=(e=>{let t=new Map,r=!1,n=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return o=>{let a=t=>((e,t,r)=>`${(e=>{let t=e?.persistState;return("object"==typeof t?t?.keyPrefix:void 0)??"persona-"})(e)}plugin:${t}:${r}`)(e(),o,t);return{get:e=>{let o=a(e),s=n();if(s)try{return s.getItem(o)}catch{r=!0}return t.get(o)??null},set:(e,o)=>{let s=a(e),i=n();if(i)try{return void i.setItem(s,o)}catch{r=!0}t.set(s,o)},remove:e=>{let o=a(e);t.delete(o);let s=n();if(s)try{s.removeItem(o)}catch{r=!0}}}}})(()=>n),y=null,b=null,v=null,x=!1,C=null,S=e=>{y=e,e.initApprovalUi({webMcpToolTitle:Mt});let t=e.createBuiltInApprovalPlugin(i);b=t.plugin,v=t.teardown},k=()=>{if(y)return y;let e=td();return e?(S(e),e):(ed().then(e=>{x||y||(S(e),C?.())}).catch(()=>{}),null)},A=!1,M=!1,T=null,L=(e,t,r,n)=>{if(!e.querySelector("[data-tv-form]"))return;let o=oc();o?o.enhanceWithForms(e,t,r,n):nc().then(()=>{A||M||!T||(M=!0,T())}).catch(()=>{})};n.components&&sd.registerAll(n.components);let P,B,N=(()=>{let e=new Map,t=(t,r)=>{e.get(t)?.delete(r)};return{on:(r,n)=>(e.has(r)||e.set(r,new Set),e.get(r).add(n),()=>t(r,n)),off:t,emit:(t,r)=>{e.get(t)?.forEach(e=>{try{e(r)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})}}})(),R=!1===n.persistState?null:n.storageAdapter??yc(),H=!!n.clientToken&&"function"!=typeof n.reconnectStream,$={},W=null,D=new Promise(e=>{P=e}),O=()=>{},z=new Promise(e=>{O=e}),q=!1,j=e=>{if(n.onStateLoaded)try{let t=n.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(q=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(R?.load)try{let e=R.load();if(e&&"function"==typeof e.then)W=e.then(e=>j(e??{messages:[],metadata:{}}));else{let t=j(e??{messages:[],metadata:{}});t.metadata&&($=Uc(t.metadata)),t.messages?.length&&(n={...n,initialMessages:t.messages}),t.artifacts?.length&&(n={...n,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),B=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(n.onStateLoaded)try{let e=j({messages:[],metadata:{}});e.messages?.length&&(n={...n,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}W||P();let _=()=>$,U=e=>{$=e({...$})??{},ei()},K=n.actionParsers&&n.actionParsers.length?n.actionParsers:[cc],J=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[uc.message,uc.messageAndClick],G=mc({parsers:K,handlers:J,getSessionMetadata:_,updateSessionMetadata:U,emit:N.emit,documentRef:typeof document<"u"?document:null});G.syncFromMetadata();let Y=n.launcher?.enabled??!0,X=n.launcher?.autoExpand??!1,Q=n.autoFocusInput??!1,Z=X,ee=Y,te=n.layout?.header?.layout,ae=!1,se=()=>wi(n),ie=()=>Y||se(),le=!se()&&(!Y||X),de=!1,ce=null,pe=()=>{de=!0,ce&&clearTimeout(ce),ce=setTimeout(()=>{de&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),de=!1)},1e4)},ue=Jc(n,G,pe),he=n.features?.showReasoning??!0,me=n.features?.showToolCalls??!0,ye=n.features?.showEventStreamToggle??!1,be=n.features?.scrollToBottom??{},ve=n.features?.scrollBehavior??{},we=()=>("object"==typeof n.persistState?n.persistState?.keyPrefix:void 0)??"persona-",Ce=`${we()}event-stream`,Se=null,ke=n.features?.eventStream?.maxEvents??2e3,Ae=null,Ie=null,Te=null,Ee=!1,Le=null,We=!1,De=null,Oe=0,Fe=(e,t)=>{Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},ze=(e,t)=>{Ie?.processEvent(e,t),Ae?Fe(e,t):Te&&(Te.length>=ke&&Te.shift(),Te.push({type:e,payload:t}))},qe=()=>{Ae||!ye||(Te??=[],ad().then(e=>{if(Ee||Ae||!ye)return;Se=new e.EventStreamStore(Ce),Ae=new e.EventStreamBuffer(ke,Se),Ie=Ie??new e.ThroughputTracker,Se.open().then(()=>Ae?.restore()).catch(e=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Te??[];Te=null;for(let e of t)Ie?.processEvent(e.type,e.payload),Fe(e.type,e.payload)}).catch(()=>{}))};ye&&qe();let Ue=!1,Ke=null,Je=()=>{},Ge=()=>{},Xe=()=>{},Qe=()=>{},Ze=()=>{},et={onCopy:e=>{N.emit("message:copy",e),ha?.isClientTokenMode()&&ha.submitMessageFeedback(e.id,"copy").catch(e=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),n.messageActions?.onCopy?.(e)},onFeedback:e=>{N.emit("message:feedback",e),ha?.isClientTokenMode()&&ha.submitMessageFeedback(e.messageId,e.type).catch(e=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),n.messageActions?.onFeedback?.(e)}},tt=(n.statusIndicator,(e,t=n.statusIndicator??{})=>"idle"===e?t.idleText??cn.idle:"connecting"===e?t.connectingText??cn.connecting:"connected"===e?t.connectedText??cn.connected:"error"===e?t.errorText??cn.error:"paused"===e?t.pausedText??cn.paused:"resuming"===e?t.resumingText??cn.resuming:cn[e]);function rt(e,t,r,n){if(!se()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(He(e,yt,r),Re(e,r,n)),!e.hasAttribute(jc))if("idle"===n&&r.idleLink){e.textContent="";let n=document.createElement("a");n.href=r.idleLink,n.target="_blank",n.rel="noopener noreferrer",n.textContent=t,n.style.color="inherit",n.style.textDecoration="none",e.appendChild(n)}else e.textContent=t}let nt=$l({config:n,showClose:ie()}),{wrapper:ot,panel:at,pillRoot:st}=nt.shell,it=nt.panelElements,{container:lt,body:dt,messagesWrapper:ct,starterSuggestions:pt,transcriptSuggestions:ut,suggestions:ht,textarea:mt,sendButton:ft,composerForm:yt,statusText:bt,welcomeHost:vt,welcomeIconHolder:wt,greetingHost:Ct,introKicker:St,introTitle:kt,introSubtitle:At,closeButton:It,iconHolder:Tt,headerTitle:Et,headerSubtitle:Lt,header:Pt,footer:Bt,actionsRow:Nt}=it,Rt=it.leftActions,Ht=it.rightActions,$t=it.sendButtonWrapper,Wt=it.setSendButtonMode,Dt=it.micButton,Ot=it.micButtonWrapper,Ft=it.attachmentButton,zt=it.attachmentButtonWrapper,qt=it.attachmentInput,jt=it.attachmentPreviewsContainer;lt.classList.add("persona-relative"),dt.classList.add("persona-relative");let _t=()=>be.label??"",Vt=()=>ve.mode??"anchor-top",Ut=()=>"follow"===Vt()||"anchor-top"===Vt()&&ds,Kt=()=>ve.anchorTopOffset??16,Jt=()=>!0===ve.pauseOnInteraction,Gt=()=>!1!==ve.showActivityWhilePinned,Yt=()=>!0===ve.announce,Xt=()=>ve.scrollbar??"on-scroll",Zt=ne("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Zt.type="button",Zt.style.display="none",Zt.setAttribute("data-persona-scroll-to-bottom","true");let tr=ne("span","persona-flex persona-items-center"),rr=ne("span",""),nr=ne("span","");nr.setAttribute("data-persona-scroll-to-bottom-count",""),nr.style.display="none",Zt.append(tr,rr,nr),lt.appendChild(Zt);let or=ne("div","persona-stream-anchor-spacer");or.setAttribute("aria-hidden","true"),or.setAttribute("data-persona-anchor-spacer",""),or.style.flexShrink="0",or.style.pointerEvents="none",or.style.height="0px",or.style.display="none",dt.appendChild(or);let ar=ne("div","persona-sr-only");ar.setAttribute("aria-live","polite"),ar.setAttribute("aria-atomic","true"),ar.setAttribute("role","status"),ar.setAttribute("data-persona-live-region",""),Object.assign(ar.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"}),lt.appendChild(ar);let sr=null,ir=null,lr=e=>{!Yt()||!e||(ir=e,null===sr&&(sr=setTimeout(()=>{sr=null,ir&&Yt()&&(ar.textContent=ir),ir=null},400)))},dr=()=>{let t=e.ownerDocument.defaultView??window;return(n.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(n.launcher?.mobileBreakpoint??640)&&(Y||vi(n))||!0===n.launcher?.fullHeight&&!n.launcher.sidebarMode&&!vi(n)},cr=()=>Sl(n,dr()),pr="empty",mr=0,gr=()=>mr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,fr=()=>{let e="none"===Bt.style.display?0:Bt.offsetHeight;Zt.style.bottom=`${e+gr()+12}px`};fr();let br=()=>{tn||(Bt.style.marginBottom=mr>0?`${mr}px`:"")},wr=()=>{let t=Ms(n,se()),r=cr();e.setAttribute("data-persona-welcome-fullscreen",String(dr())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",n.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let o="none"===Bt.style.display?0:Bt.offsetHeight,a="center"===r.anchor&&"empty"===pr?Is(r.anchorComposerTop)??Is("44%"):null,s=null!==a&&"centered"===r.layout&&void 0===n.welcome?.anchor&&void 0===n.welcome?.anchorComposerTop,i=s?getComputedStyle(dt):null,l=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,d=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,c=Math.max(0,(parseFloat(i?.paddingBottom??"")||0)-("overlay"===t?l+d:0)),p=s?dt.getBoundingClientRect().top-lt.getBoundingClientRect().top:0,u=!s||vt.hidden?0:(vt.querySelector("[data-persona-welcome-plugin]")??vt).offsetHeight,h=null===a||se()?0:s?Math.max(0,Math.round((lt.clientHeight-p-u-c-o)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:lt.clientHeight,footerHeight:o,fraction:a});e.style.setProperty("--persona-composer-overlay-height",`${o}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),mr="block"===t?h:0,br(),fr()},Cr=()=>{let e=!!_t();Zt.setAttribute("aria-label",_t()||"Jump to latest"),Zt.title=_t(),Zt.setAttribute("data-persona-scroll-to-bottom-has-label",e?"true":"false"),tr.innerHTML="";let t=xe(be.iconName??"arrow-down","14px","currentColor",2);t?(tr.appendChild(t),tr.style.display=""):tr.style.display="none",rr.textContent=_t(),rr.style.display=e?"":"none"};Cr();let Sr=null,kr=null,Ar=bo();Ar.subscribe(e=>{try{lt.dispatchEvent(new CustomEvent("persona:composer:state",{detail:e,bubbles:!0,composed:!0}))}catch{}});let Mr=()=>{Ar.setText(mt?.value??"")},Ir=()=>{Ar.setMentionRefs(kr?.getMentionRefs()??[])},Tr=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),Er=e=>{let t=Object.freeze(e.map(Tr));Ar.setAttachments(t);try{n.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}Dl()};Ar.setSelectedModelId(n.composer?.selectedModelId);let Lr=()=>n.composer?.modes??[],Br=()=>function(e,t){return e?.length?e.filter(e=>!Ca(e.groupId,t)&&!function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)):[]}(Lr(),n.composer?.modeGroups);{let e=Sa(n.composer?.defaultActiveModeIds??[],Lr());e.length&&Ar.setActiveModeIds(e)}function Nr(e){if(Ar.getState().selectedModelId!==e){Ar.setSelectedModelId(e),$r?.repaint();try{n.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function Rr(e){Ar.setActiveModeIds(e),Dr?.render(e,Br()),Or.forEach(e=>e.repaint()),fn?.resolve(),Cd(),An()}function Hr(e){Rr(function(e,t,r,n){let o=r.find(e=>e.id===t);if(!o)return[...e];let a=e.includes(t),s=new Set(e);if(a)s.delete(t);else{if("single"===((e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null)(o,n)){let e=r.filter(e=>e.groupId===o.groupId).map(e=>e.id);s=new Set([...s].filter(t=>!e.includes(t)))}s.add(t)}return r.filter(e=>s.has(e.id)).map(e=>e.id)}(Ar.getState().activeModeIds,e,Lr(),n.composer?.modeGroups))}let $r=null,Wr=null,Dr=null,Or=new Map,Fr=null;function zr(e){Ar.setQuote(e),Fr?.render(Ar.getState().quote),An(),oi()}let qr=!1;function jr(){let e=n.composer?.streamingSubmitBehavior??"block";return"interrupt"!==e?e:n.clientToken?"interrupt":(!qr&&!0===n.debug&&(qr=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let _r=null;function Vr(e){Ar.setPendingSubmission(e),_r?.render(Ar.getState().pendingSubmission),An()}let Ur=()=>{let e=[],t=Ar.getState().activeModeIds,r=new Set;if(Lr().forEach((o,a)=>{if(Ca(o.groupId,n.composer?.modeGroups)){let t=o.groupId;if(r.has(t))return;r.add(t);let s=(e=>{let t=Or.get(e);if(t)return t;let r=function(e){let t=null;return{action:{id:xa(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let r=oe("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),n=new Map,o="",a=t=>{t.preventDefault(),t.stopPropagation();let r=t.currentTarget.getAttribute("data-persona-composer-mode");!r||e.getActiveIds().includes(r)&&"single"===e.getGroup()?.selection||e.onSelect(r)},s=()=>{let t=e.getGroup();t?.label?(r.setAttribute("role","group"),r.setAttribute("aria-label",t.label)):(r.removeAttribute("role"),r.removeAttribute("aria-label"));let s=e.getModes(),i=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??""}`).join("|");if(i!==o){o=i;for(let e of n.values())e.removeEventListener("click",a);n.clear();let e=s.map(e=>{let t=(e=>{let t=oe("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let r=xe(e.iconName,16,"currentColor",1.5);r&&t.appendChild(r)}let r=ne("span","persona-composer-segmented-label");return r.textContent=e.shortLabel??e.label,t.appendChild(r),t.addEventListener("click",a),t})(e);return n.set(e.id,t),t});r.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of n)t.setAttribute("aria-pressed",String(l.includes(e)))};return s(),t=s,{element:r,destroy:()=>{t===s&&(t=null);for(let e of n.values())e.removeEventListener("click",a);n.clear()}}}},repaint:()=>t?.()}}({groupId:e,getGroup:()=>n.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Lr().filter(t=>t.groupId===e),getActiveIds:()=>Ar.getState().activeModeIds,onSelect:e=>Hr(e)});return Or.set(e,r),r})(t);return s.action.order=wa(a),s.action.label=n.composer?.modeGroups?.find(e=>e.id===t)?.label??t,void e.push(s.action)}e.push({id:va(o.id),kind:"button",placement:"start",order:wa(a),presentation:o.presentation??"auto",label:o.label,shortLabel:o.shortLabel,iconName:o.iconName,pressed:t.includes(o.id),onSelect:()=>Hr(o.id)})}),n.composer?.models?.length&&!c.some(e=>e.renderComposer)){let t=n.composer?.modelPicker?.presentation??"native";(!$r||Wr!==t)&&(Wr=t,$r=ga({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>Ar.getState().selectedModelId,onSelect:e=>Nr(e),presentation:t,getSuffix:()=>n.composer?.modelPicker?.suffix})),e.push($r.action)}return e},Kr=null,Jr=c.find(e=>e.renderHeader);if(Jr?.renderHeader){let e=Jr.renderHeader({config:n,defaultRenderer:()=>{let e=Di({config:n,showClose:ie()});return Oi(lt,e,n),e.header},onClose:()=>Pl(!1,"user")});e&&Pt&&(Pt.replaceWith(e),Pt=e,nt.header.element=e)}let Gr=()=>{Le&&(dt.style.display="none",Bt.parentNode?.insertBefore(Le.element,Bt),Le.update())},Yr=()=>{if(!Ae)return void qe();if(We=!0,Le?Gr():ad().then(e=>{Le||!We||!Ae||(Le=e.createEventStreamView({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>Xr(),config:n,plugins:c,getThroughput:()=>Ie?.getMetric()??{status:"idle"},renderIconByName:xe}),Gr())}).catch(()=>{Xr()}),Qr){Qr.style.boxShadow=`inset 0 0 0 1.5px ${Hi.actionIconColor}`;let e=n.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Qr.classList.add(e))}let e=()=>{if(!We)return;let t=Date.now();t-Oe>=200&&(Le?.update(),Oe=t),De=requestAnimationFrame(e)};Oe=0,De=requestAnimationFrame(e),Ni(),N.emit("eventStream:opened",{timestamp:Date.now()})},Xr=()=>{if(We){if(We=!1,Le&&Le.element.remove(),dt.style.display="",Qr){Qr.style.boxShadow="";let e=n.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Qr.classList.remove(e))}null!==De&&(cancelAnimationFrame(De),De=null),Ni(),N.emit("eventStream:closed",{timestamp:Date.now()})}},Qr=null;if(ye){let e=n.features?.eventStream?.classNames,t="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"+(e?.toggleButton?" "+e.toggleButton:"");Qr=ne("button",t),Qr.style.width="28px",Qr.style.height="28px",Qr.style.color=Hi.actionIconColor,Qr.type="button",Qr.setAttribute("aria-label","Event Stream"),Qr.title="Event Stream";let r=I(h,"18px","currentColor",1.5);r&&Qr.appendChild(r);let o=it.clearChatButtonWrapper,a=it.closeButtonWrapper,s=o||a;s&&s.parentNode===Pt?Pt.insertBefore(Qr,s):Pt.appendChild(Qr),Qr.addEventListener("click",()=>{We?Xr():Yr()})}let en=e=>{let t=n.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=ne("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let t=e.querySelector("[data-persona-composer-form]");t?.parentNode?t.parentNode.insertBefore(r,t):e.insertBefore(r,e.firstChild)}if(!(e.querySelector("[data-persona-composer-attachment-input]")??e.querySelector('input[type="file"]'))){let r=ne("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??on).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},tn=!1,rn=e=>{let t=c.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=n.composer,o=!!m&&ha.isStreaming();return t.renderComposer({config:n,defaultRenderer:e,requestRender:()=>mu(),storage:f(t.id),onSubmit:e=>{!ha||ha.isStreaming()||np(e.trim(),{consumeDraft:!1})},streaming:o,disabled:o,openAttachmentPicker:()=>{Nl()||qt?.click()},models:r?.models,selectedModelId:Ar.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>Nr(e),onVoiceToggle:!0===n.voiceRecognition?.enabled?()=>{Kr?.()}:void 0})},nn=rn(()=>Xi({config:n}).footer);nn&&(nt.replaceComposer(nn),Bt=nt.composer.footer,tn=!0);let an=null;function sn(){let e=mt;if(!e)return;let t=n.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");Do(e,t),r&&e.setAttribute("aria-label",r),Wo(e,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Ho(e)}),function(e,t){e.style.maxHeight=t*No(e)+"px",e.style.overflowY="auto"}(e,Ro(n.composer?.maxLines,se()?5:3))}let ln=e=>{an=function(e,t={}){let r=vo(e,"[data-persona-composer-form]"),n=vo(e,"[data-persona-composer-input]");if(!r||!n){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||n))throw new Error(e);return typeof console<"u"&&console.warn(e),null}let o={header:vo(e,"[data-persona-composer-header]"),body:vo(e,"[data-persona-composer-body]"),actionsStart:vo(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:vo(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:vo(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:vo(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:vo(e,"[data-persona-composer-status]")},a=new Set,s=o.header;s||(a.add("header"),s=wo("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=o.body??n.parentElement??r,l=(e,t,r,n,o)=>{if(t)return t;a.add(e);let s=wo(r,n);return o.appendChild(s),s},d=l("actionsStart",o.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",o.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",o.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",o.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:n,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:vo(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:vo(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:vo(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:vo(e,"[data-persona-composer-submit]")??void 0,micButton:vo(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:o,addListener:(e,t,r,n)=>{e.addEventListener(t,r,n),h.push({target:e,type:t,handler:r,options:n})},removeListener:(e,t,r,n)=>{e.removeEventListener(t,r,n),h=h.filter(n=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(n,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}(e,{debug:!0===n.debug}),an&&(e=>{yt=e.form,mt=e.input,$t=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(ft=e.sendButton),e.micButton&&(Dt=e.micButton,Ot=e.micButton.parentElement),e.found.status&&(bt=e.found.status),e.found.suggestions&&(ht=e.found.suggestions),e.attachmentButton&&(Ft=e.attachmentButton,zt=e.attachmentButton.parentElement),qt=e.attachmentInput??null,jt=e.attachmentPreviews??null,e.found.actionsRow&&(Nt=e.found.actionsRow),Rt=e.found.actionsStart,Ht=e.found.actionsEnd})(an),sn()};en(Bt),ln(Bt),Mr();let dn=ks(n,se());dn&&(ct.style.maxWidth=dn,ct.style.marginLeft="auto",ct.style.marginRight="auto",ct.style.width="100%",Ct.style.maxWidth=dn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto",Ct.style.width="100%",pt.style.maxWidth=dn,ut.style.maxWidth=dn,ut.style.marginLeft="auto",ut.style.marginRight="auto",ut.style.width="100%");let un=()=>{let e=ks(n,se());if(e&&!se())for(let t of[yt,ht,jt,bt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};un();let mn=()=>{!n.attachments?.enabled||!qt||!jt||(Sr?Sr.remountPreviews(jt):(Sr=fo.fromConfig(n.attachments,Er),Sr.setPreviewsContainer(jt)),an?.addListener(qt,"change",e=>{let t=e.target;Sr?.handleFileSelect(t.files),t.value=""}),lt.querySelector(".persona-attachment-drop-overlay")||lt.appendChild(Gc(n.attachments.dropOverlay)))};mn();let gn=()=>{if(!n.contextMentions?.enabled||!mt)return;let e=Tn();if(!e){let e=mt;return void In().then(()=>{kr||mt!==e||!e.isConnected||(gn(),fn?.resolve())},()=>{})}let t=an?.header??null,r=t?ba(t):void 0;if(kr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Ea,loadContextMentionsInline:Na,renderLucideIcon:xe,createMentionButton:Ra},config:n,textarea:mt,anchor:yt??mt,getMessages:()=>ha.getMessages(),liveRegionHost:lt,chipRow:r}),kr&&!r){let e=mt;e.parentElement?.insertBefore(kr.contextRow,e)}};gn();let fn=null,yn={getState:()=>Ar.getState(),getValue:()=>mt?.value??"",setValue:e=>{mt&&(mt.value=e,mt.dispatchEvent(new Event("input",{bubbles:!0})),Mr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(an?.form??null)},openAttachmentPicker:()=>{Nl()||qt?.click()},toggleVoice:()=>{Kr?.()},requestRender:()=>fn?.resolve()},bn=()=>{let e=[];return(kr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),zt&&e.push({id:"core:attachment",placement:"start",order:200,element:zt}),Ot&&e.push({id:"core:mic",placement:"end",order:800,element:Ot}),$t&&e.push({id:"core:send",placement:"end",order:ra,element:$t}),e},vn=()=>{fn?.destroy(),fn=ua({getBindings:()=>an,collect:()=>({builtIns:bn(),configActions:[...Ur(),...n.composer?.actions??[]],plugins:c,contributionContext:{config:n,getState:()=>Ar.getState(),requestRender:()=>fn?.resolve()},debug:!0===n.debug}),actionContext:yn,getState:()=>Ar.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),fn.resolve()};vn();let xn=()=>{if(Dr?.destroy(),Dr=null,!Br().length)return;let e=an?.header;e&&(Dr=function(e){let t=e.row,r="",n=!1,o=new Set(e.initialIds??[]),a=t=>{let r=oe("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=ne("span","persona-mention-chip-icon"),n=xe(t.iconName,12,"currentColor",1.5);n&&e.appendChild(n),r.appendChild(e)}let n=ne("span","persona-mention-chip-label");n.textContent=t.shortLabel??t.label,r.appendChild(n);let o=oe("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label}`}}),a=xe("x",12,"currentColor",2);return a?o.appendChild(a):o.textContent="×",o.addEventListener("click",r=>{r.preventDefault(),r.stopPropagation(),e.onRemove(t.id)}),r.appendChild(o),r},s=()=>Array.from(t.querySelectorAll(":scope > [data-persona-composer-mode]")),i=e=>{e.setAttribute("data-persona-chip-exit",""),e.setAttribute("aria-hidden","true"),e.style.pointerEvents="none";let r=()=>{e.remove(),ya(t)},n=t.ownerDocument.defaultView,o="function"==typeof n?.getComputedStyle?n.getComputedStyle(e).animationName:"";o&&"none"!==o?(e.addEventListener("animationend",r,{once:!0}),e.addEventListener("animationcancel",r,{once:!0})):r()};return{element:t,render:(e,l)=>{if(n)return;let d=l.filter(t=>e.includes(t.id)),c=d.map(e=>`${e.id}:${e.shortLabel??e.label}`).join("|");if(c===r)return;r=c;let p=new Map;for(let e of s()){let t=e.getAttribute("data-persona-composer-mode");t&&d.some(e=>e.id===t)&&!e.hasAttribute("data-persona-chip-exit")?p.set(t,e):e.hasAttribute("data-persona-chip-exit")||i(e)}let u=t.firstChild;for(let e of d){let r=p.get(e.id);r||(r=a(e),o.has(e.id)||(r.setAttribute("data-persona-chip-enter",""),r.addEventListener("animationend",()=>r?.removeAttribute("data-persona-chip-enter"),{once:!0}))),o.delete(e.id),r!==u&&t.insertBefore(r,u),u=r.nextSibling}ya(t)},destroy:()=>{n=!0,(()=>{for(let e of s())e.remove()})(),ya(t)}}}({row:ba(e),onRemove:e=>Hr(e),initialIds:Ar.getState().activeModeIds}),Dr.render(Ar.getState().activeModeIds,Br()))};xn();let Cn=()=>{Fr?.destroy(),Fr=null,_r?.destroy(),_r=null;let e=an?.header;e&&(Fr=function(e){let t=oe("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",n=!1;return{element:t,render:o=>{if(n)return;let a=o?`${o.sourceLabel??""}\0${o.text}`:"";if(a!==r){if(r=a,!o)return t.replaceChildren(),void(t.style.display="none");(r=>{let n=ne("span","persona-composer-quote-bar"),o=ne("div","persona-composer-quote-content");if(r.sourceLabel){let e=ne("div","persona-composer-quote-source");e.textContent=r.sourceLabel,o.appendChild(e)}let a=oe("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=zn(r.text),o.appendChild(a);let s=oe("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=xe("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(n,o,s)})(o),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}({onDismiss:()=>zr(void 0)}),e.appendChild(Fr.element),Fr.render(Ar.getState().quote),"defer-one"===jr()&&(_r=function(e){let t=oe("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,n=!1,o=(e,t,r,n)=>{let o=oe("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=xe(e,12,"currentColor",2);return a?o.appendChild(a):o.textContent=t,o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o};return{element:t,render:a=>{if(n||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=ne("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=oe("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=zn(e.text??"",90);if(t)return t;let r=e.contentParts?.length??0;return r>0?1===r?"1 attachment":`${r} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(", "):"Queued message"})(a),t.replaceChildren(s,i,o("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),o("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}({onEdit:()=>function(){let e=Ar.getState().pendingSubmission;e&&(Vr(void 0),mt&&(mt.value=e.text,mt.dispatchEvent(new Event("input",{bubbles:!0})),Mr()),e.options.selectedModelId&&(Ar.setSelectedModelId(e.options.selectedModelId),$r?.repaint()),e.options.activeModeIds?.length&&Rr(e.options.activeModeIds),e.options.quote&&zr(e.options.quote),mt?.focus())}(),onRemove:()=>Vr(void 0)}),e.appendChild(_r.element),_r.render(Ar.getState().pendingSubmission)))};Cn();let Sn=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),kn=()=>{let e=an?.header?.querySelector(fa);if(e)return e.childElementCount>0;let t=Ar.getState();return t.mentionRefs.length>0||Sa(t.activeModeIds,Br()).length>0};function An(){let e=Ar.getState(),t=Sn.observe(function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),n=Number.parseFloat(r.lineHeight),o=Number.parseFloat(r.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(o)&&o>0?1.4*o:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0);return e.scrollHeight-s>1.5*a}(mt),e.text);Bt.toggleAttribute("data-persona-composer-compact",function(e){return!e.wrapped&&!e.text.includes("\n")&&!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:kn(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}))}function Mn(){"single-row"!==n.composer?.layout||se()?Bt.removeAttribute("data-persona-composer-layout"):Bt.setAttribute("data-persona-composer-layout","single-row")}Mn(),Ar.subscribe(()=>{fn?.sync(),Dl(),zl(),An(),oi()}),zl();let En=!1;(()=>{let e=n.layout?.slots??{};(e=>{if(En||!0!==n.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(En=!0,console.warn(`[persona] layout.slots.${t.join(" and layout.slots.")} ${t.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))})(e);let t=e=>{switch(e){case"body-top":return dt.querySelector("[data-persona-intro-card]");case"messages":return ct;case"footer-top":return ht;case"composer":return yt;case"footer-bottom":return bt;default:return null}},r=(e,t)=>{switch(e){case"header-left":case"header-center":case"header-right":if("header-left"===e)Pt.insertBefore(t,Pt.firstChild);else if("header-right"===e)Pt.appendChild(t);else{let e=Pt.querySelector(".persona-flex-col");e?e.parentNode?.insertBefore(t,e.nextSibling):Pt.appendChild(t)}break;case"body-top":{let e=dt.querySelector("[data-persona-intro-card]");e?e.replaceWith(t):dt.insertBefore(t,dt.firstChild);break}case"body-bottom":dt.appendChild(t);break;case"footer-top":ht.replaceWith(t);break;case"footer-bottom":bt.replaceWith(t)}};for(let[o,a]of Object.entries(e))if(a)try{let e=a({config:n,defaultContent:()=>t(o)});e&&r(o,e)}catch(e){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${o}":`,e)}})(),ct.addEventListener("click",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest("button[data-persona-copy-tool-detail]");r&&(e.preventDefault(),e.stopPropagation(),async function(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let n=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(jl.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=xe("check",14,"currentColor",2);t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}jl.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",n),e.title=n;let t=xe("copy",14,"currentColor",1.7);t&&e.replaceChildren(t),jl.delete(e)},1800))}(r))});let Ln=e=>{let t=e.target.closest('button[data-expand-header="true"]');if(!t)return;let r=t.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!r)return;let l=r.getAttribute("data-message-id");if(!l)return;hs(),Ri();let d=t.getAttribute("data-bubble-type");if(r.classList.contains("persona-activity-row")){s.manual(l);let e=r.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&s.manual(e.dataset.messageId)}if("reasoning"===d)a.has(l)?a.delete(l):a.add(l),Ol(l,r,a);else if("tool"===d)o.has(l)?o.delete(l):o.add(l),Kl(l,r,o,n);else if("approval"===d&&y){let e="expanded"===((!1!==n.approval?n.approval:void 0)?.detailsDisplay??"collapsed"),t=i.get(l)??e;i.set(l,!t),y.updateApprovalDetailsUI(l,r,n,i)}qa.delete(l)};ct.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Ln(e))}),ct.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&Ln(e)}),ct.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Ln(e))}),ct.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=ct.getRootNode(),n="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!n||n.isCollapsed)return;let o=n.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(o);!a||a===o||(t.setData("text/plain",a),e.preventDefault())});let Pn=new Map,Bn=null,Nn="idle",Rn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Hn=()=>{ct.querySelectorAll('[data-action="read-aloud"]').forEach(e=>{let t=e.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;((e,t)=>{let{icon:r,label:n}=Rn[t];e.setAttribute("aria-label",n),e.title=n,e.setAttribute("aria-pressed","idle"===t?"false":"true"),e.classList.toggle("persona-message-action-active","idle"!==t),e.classList.toggle("persona-message-action-loading","loading"===t);let o=xe(r,14,"currentColor",2);o&&(e.innerHTML="",e.appendChild(o))})(e,t&&t===Bn?Nn:"idle")})};ct.addEventListener("click",e=>{let t=e.target.closest(".persona-message-action-btn[data-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest("[data-actions-for]");if(!r)return;let o=r.getAttribute("data-actions-for");if(!o)return;let a=t.getAttribute("data-action");if("copy"===a){let e=ha.getMessages().find(e=>e.id===o);if(e&&et.onCopy){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=I(g,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=I(w,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),et.onCopy(e)}}else if("read-aloud"===a)ha.toggleReadAloud(o);else if("upvote"===a||"downvote"===a){let e="upvote"===a?"thumbs-up":"thumbs-down";if((Pn.get(o)??null)===a){Pn.delete(o),t.classList.remove("persona-message-action-active");let r=xe(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let n="upvote"===a?"downvote":"upvote",s=r.querySelector(`[data-action="${n}"]`);if(s){s.classList.remove("persona-message-action-active");let e=xe("upvote"===n?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(s.innerHTML="",s.appendChild(e))}Pn.set(o,a),t.classList.add("persona-message-action-active");let i=xe(e,14,"currentColor",2);i&&(i.setAttribute("fill","currentColor"),t.innerHTML="",t.appendChild(i)),t.classList.remove("persona-message-action-pop"),t.offsetWidth,t.classList.add("persona-message-action-pop");let l=ha.getMessages().find(e=>e.id===o);l&&et.onFeedback&&et.onFeedback({type:a,messageId:l.id,message:l})}}else if("regenerate"===a)$n?.regenerate(o);else if("edit"===a)$n?.edit(o);else if("quote"===a)$n?.quote(o);else if(a?.startsWith(sl)){let e=a.slice(7),t=n.messageActions?.custom?.find(t=>t.id===e),r=ha.getMessages().find(e=>e.id===o);if(!t||!r)return;try{t.onSelect(r)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let $n=null;ct.addEventListener("click",e=>{let t=e.target.closest("button[data-approval-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest(".persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;let o=t.getAttribute("data-approval-action");if(!o)return;let a="approve"===o?"approved":"denied",s=ha.getMessages().find(e=>e.id===n);if(!s?.approval)return;let i=r.querySelector("[data-approval-buttons]");i&&i.querySelectorAll("button").forEach(e=>{e.disabled=!0,e.style.opacity="0.5",e.style.cursor="not-allowed"}),"webmcp"===s.approval.toolType?ha.resolveWebMcpApproval(n,a):ha.resolveApproval(s.approval,a)});let Wn=null,Dn=!1,Fn=null,_n=()=>{},Vn="none",Un=null,Kn={artifacts:[],selectedId:null},Jn=!1,Gn=!1,Yn=!1,Xn=!1,eo=()=>Xn||Kn.artifacts.some(e=>"panel"===On(n.features?.artifacts,e)),to=()=>Kn.artifacts.length>0&&!Jn&&eo(),ro={current:null},no=(e,t)=>{let r=ha.getArtifactById(t),n=r?.markdown,o=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!n){let t=e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(t){let e=ha.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);n=t?.props?.markdown,o=t?.props?.title||o,t?.props?.file&&"object"==typeof t.props.file&&(a=t.props.file),!r&&"string"==typeof t?.props?.artifactType&&(s=t.props.artifactType)}catch{}}}return{markdown:n,title:o,file:a,artifactType:s}};ct.addEventListener("click",e=>{let t=e.target.closest("[data-download-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-download-artifact");if(!r||!0===n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:o,title:a,file:s}=no(t,r);if(!o)return;let i=yd();i&&i.triggerArtifactDownload(i.downloadInfoFor({title:a,markdown:o,file:s}))}),ct.addEventListener("click",e=>{let t=e.target.closest("[data-artifact-custom-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-artifact-custom-action");if(!r)return;let o=t.closest("[data-artifact-inline]"),a=o?null:t.closest("[data-open-artifact]"),s=o?o.getAttribute("data-artifact-inline"):a?.getAttribute("data-open-artifact")??null,i=(o?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!i)return;let{markdown:l,title:d,file:c,artifactType:p}=no(t,s??""),u={artifactId:s,title:d,artifactType:p,markdown:l,file:c};try{Promise.resolve(i.onClick(u)).catch(()=>{})}catch{}}),ct.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-copy-artifact");if(!r)return;let n=ha.getArtifactById(r),o=yd();if(!o)return;let a="";if(n)a=o.artifactCopyText(n);else{let{markdown:e,file:n,artifactType:s}=no(t,r);"markdown"===s&&(a=o.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...n?{file:n}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=I(g,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=I(w,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),ct.addEventListener("click",e=>{let t=e.target.closest("[data-expand-artifact-inline]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-expand-artifact-inline");!r||!0===n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})||(Jn=!1,Xn=!0,Gn=!0,Yn=!0,ha.selectArtifact(r),_o())}),ct.addEventListener("click",e=>{let t=e.target;if(t.closest("[data-download-artifact]")||t.closest("[data-artifact-custom-action]"))return;let r=t.closest("[data-open-artifact]");if(!r)return;let o=r.getAttribute("data-open-artifact");!o||!0===n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:o})||(e.preventDefault(),e.stopPropagation(),Jn=!1,Xn=!0,ha.selectArtifact(o),_o())}),ct.addEventListener("keydown",e=>{if("Enter"!==e.key&&" "!==e.key)return;let t=e.target;!t.hasAttribute("data-open-artifact")&&!t.hasAttribute("data-expand-artifact-inline")||(e.preventDefault(),t.click())});let oo=it.composerOverlay,ao=e=>{In().catch(()=>{}),ur(e,n,oo)},so=null,io={mount:e,overlay:oo,sessionRef:ro,config:()=>n},lo=!1,co=e=>t=>{let r=t.target,n=r?.closest?.("[data-persona-ask-sheet-for]");if(!n||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let o=r=>{so??=r.createAskUserSheetHandlers(io),so[e](t)},a=Tn();a?o(a):lo||(lo=!0,In().then(e=>{lo=!1,n.isConnected&&o(e)},()=>{lo=!1}))};oo.addEventListener("click",co("click")),oo.addEventListener("keydown",co("keydown"));let po=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if("INPUT"===t?.tagName||"TEXTAREA"===t?.tagName||t?.isContentEditable)return;let r=oo.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let n=Number(e.key),o=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[n-1];o&&(e.preventDefault(),o.click())};document.addEventListener("keydown",po);let ho=null,mo=null,go=null,yo=null,xo=()=>{},Co=!1,Ao="",Io="";function To(){yo?.(),yo=null}let Eo=()=>{if(!ho||!mo)return;let t=e.classList.contains("persona-artifact-welded-split"),r=e.ownerDocument.defaultView??window,n=r.innerWidth<=640;if(!t||e.classList.contains("persona-artifact-narrow-host")||n)return mo.style.removeProperty("position"),mo.style.removeProperty("left"),mo.style.removeProperty("top"),mo.style.removeProperty("bottom"),mo.style.removeProperty("width"),void mo.style.removeProperty("z-index");let o=ho.firstElementChild;if(!o||o===mo)return;mo.style.position="absolute",mo.style.top="0",mo.style.bottom="0",mo.style.width="10px",mo.style.zIndex="5";let a=Xd(ho,r),s=o.offsetWidth+a/2-5;mo.style.left=`${Math.max(0,s)}px`},Lo=()=>{},Po=()=>{let t=e.ownerDocument.defaultView??window,r=n.launcher?.mobileFullscreen??!0,o=n.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>o)&&(Y||vi(n))},jo=()=>!vd(n)||!to()||e.classList.contains("persona-artifact-narrow-host")||Po()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":Sd(n)?"detached":"welded",_o=()=>{if(!Wn||!vd(n))return;kd(e,n),Ad(e,n),Lo();let t=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=at.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let o=to();Wn.setVisible(o),Wn.update(Kn),Jn?(Wn.setMobileOpen(!1),Wn.element.classList.add("persona-hidden"),Wn.backdrop?.classList.add("persona-hidden"),Gn=!1,Yn=!1):Kn.artifacts.length>0&&eo()?(Wn.element.classList.remove("persona-hidden"),Wn.setMobileOpen(!0)):(Wn.setMobileOpen(!1),Wn.element.classList.add("persona-hidden"),Wn.backdrop?.classList.add("persona-hidden"),Gn=!1,Yn=!1);let a=!0===n.features?.artifacts?.layout?.showExpandToggle;if(Wn.setExpandToggleVisible(a),Wn.setCopyButtonVisible(!0===n.features?.artifacts?.layout?.showCopyButton),Wn.setRefreshButtonVisible("function"==typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh),Wn.setCustomActions(n.features?.artifacts?.toolbarActions??[]),Wn.setTabFade(n.features?.artifacts?.layout?.tabFade),Wn.setRenderTabBar(n.features?.artifacts?.renderTabBar),!a&&!Yn&&(Gn=!1),Gn!==Co){let e=Wn.element;Gn?(Ao=e.style.width,Io=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(Ao&&(e.style.width=Ao),Io&&(e.style.maxWidth=Io),Ao="",Io=""),Co=Gn}e.classList.toggle("persona-artifact-expanded",Gn),Wn.setExpanded(Gn);let s=jo();s!==Vn&&(Vn=s,_n()),xo()};if(vd(n)){at.style.position="relative";let t=ne("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=ne("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(lt),ho=r,r.appendChild(t),at.appendChild(r);let o=e=>{Dn||Wn||(Wn=e.createArtifactPane(n,{onSelect:e=>ro.current?.selectArtifact(e),onDismiss:()=>{Jn=!0,_o()},onToggleExpand:()=>{let e=!Gn,t=Kn.selectedId??Kn.artifacts[Kn.artifacts.length-1]?.id??null;!0!==n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(Gn=e,e||(Yn=!1),_o())}}),Wn.element.classList.add("persona-hidden"),r.appendChild(Wn.element),Wn.backdrop&&at.appendChild(Wn.backdrop),xo(),_o())},a=yd();a?o(a):(bd(()=>{let e=yd();e&&o(e)}),fd().catch(()=>{})),xo=()=>{if(ho&&Wn){if(!0!==n.features?.artifacts?.layout?.resizable)return go?.(),go=null,To(),mo&&(mo.remove(),mo=null),Wn.element.style.removeProperty("width"),void Wn.element.style.removeProperty("maxWidth");if(!mo){let t=ne("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");t.setAttribute("role","separator"),t.setAttribute("aria-orientation","vertical"),t.setAttribute("aria-label","Resize artifacts panel"),t.tabIndex=0;let r=e.ownerDocument,o=r.defaultView??window,a=a=>{if(!Wn||0!==a.button||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||o.innerWidth<=640)return;a.preventDefault(),To();let s=a.clientX,i=Wn.element.getBoundingClientRect().width,l=n.features?.artifacts?.layout,d=r=>{let n=ho.getBoundingClientRect().width,a=e.classList.contains("persona-artifact-welded-split"),d=Xd(ho,o),c=a?0:t.getBoundingClientRect().width||6,p=function(e,t,r,n,o,a,s=200){let i=function(e){if(!e?.trim())return 200;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):200}(o),l=function(e,t,r,n){let o=e-n-2*t-r;return Math.max(0,o)}(t,r,n,s);l=Math.max(i,l);let d=function(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}(a);return null!==d&&(l=Math.min(l,d)),function(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}(e,i,l)}(i-(r.clientX-s),n,d,c,l?.resizableMinWidth,l?.resizableMaxWidth,(()=>{let e=Jd?.railShell?Jd.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360})());Wn.element.style.width=`${p}px`,Wn.element.style.maxWidth="none",Eo()},c=()=>{r.removeEventListener("pointermove",d),r.removeEventListener("pointerup",c),r.removeEventListener("pointercancel",c),yo=null;try{t.releasePointerCapture(a.pointerId)}catch{}};yo=c,r.addEventListener("pointermove",d),r.addEventListener("pointerup",c),r.addEventListener("pointercancel",c);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener("pointerdown",a),mo=t,ho.insertBefore(t,Wn.element),go=()=>{t.removeEventListener("pointerdown",a)}}if(mo){let e=to();mo.classList.toggle("persona-hidden",!e),Eo()}}},Lo=()=>{if(!Y||!Wn||n.launcher?.sidebarMode||vi(n)&&"emerge"===xi(n).reveal)return;let t=e.ownerDocument.defaultView??window,r=n.launcher?.mobileFullscreen??!0,o=n.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=o||!function(e,t){return!(!t||!vd(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(n,Y))return;let a=Ml(n).width,s=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";to()?(at.style.width=s,at.style.maxWidth=s):(at.style.width=a,at.style.maxWidth=a)},typeof ResizeObserver<"u"&&(Fn=new ResizeObserver(()=>{_o()}),Fn.observe(at))}else at.appendChild(lt);se()&&st&&(it.peekBanner&&st.appendChild(it.peekBanner),st.appendChild(Bt)),e.appendChild(ot),st&&e.appendChild(st);let Uo=()=>{let t=Po()||se()&&"fullscreen"===n.launcher?.composerBar?.expandedSize||!0===n.launcher?.fullHeight&&!n.launcher?.sidebarMode&&!vi(n);if(ct.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",ct.style.setProperty("--persona-transcript-gap",ct.style.gap),se()){at.style.width="100%",at.style.maxWidth="100%";let e=n.launcher?.composerBar??{},t="expanded"===ot.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return lt.style.background="",lt.style.border="",lt.style.borderRadius="",lt.style.overflow="",void(lt.style.boxShadow="");let o=n.theme?.components?.panel,a=xs(n),s=(e,t)=>null==e||""===e?t:es(a,e)??e,i="1px solid var(--persona-border)",l="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",d="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";return lt.style.background="var(--persona-surface, #ffffff)",lt.style.border=s(o?.border,i),lt.style.borderRadius=s(o?.borderRadius,d),lt.style.boxShadow=s(o?.shadow,l),void(lt.style.overflow="hidden")}let r=vi(n),o=n.launcher?.sidebarMode??!1,a=r||o||(n.launcher?.fullHeight??!1),s=!1===n.launcher?.enabled,i=!0===n.launcher?.detachedPanel,l=n.theme?.components?.panel,d=n.darkTheme?.components?.panel,c="dark"===ws(n)?E(l??{},d??{}):l,p=xs(n),u=(e,t)=>null==e||""===e?t:es(p,e)??e,h=e.ownerDocument.defaultView??window,m=n.launcher?.mobileFullscreen??!0,g=n.launcher?.mobileBreakpoint??640,f=h.innerWidth<=g,y=m&&f&&Y,b=r&&m&&f,v=n.launcher?.position??"bottom-left",w="bottom-left"===v||"top-left"===v,x=n.launcher?.zIndex??pn,C=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,S=c?.modes?.floating,k=u(S?.border??c?.border,C("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),A=u(S?.shadow??c?.shadow,C("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),M=u(S?.borderRadius??c?.borderRadius,C("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),I=i&&!y&&!b,T=y||b?"mobile":I?"floating":r?"docked":o?"sidebar":s?"inline":"floating",L=c?.modes?.[T];I?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let P=I?k:o||y?"none":k,B=I?A:y?"none":o?w?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":s?"none":A;r&&!y&&!I&&(B="none",P="none");let N=I?M:o||y?"0":M,R=u(L?.border??c?.border,C(T,"border",P)),H=u(L?.shadow??c?.shadow,C(T,"shadow",B)),$=u(L?.borderRadius??c?.borderRadius,C(T,"borderRadius",N)),W=jo(),D="detached"===W,O="welded"===W;e.classList.toggle("persona-artifact-detached-split",D),e.classList.toggle("persona-artifact-welded-split",O);let z="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)))))",q="flush"==("flush"===n.features?.artifacts?.layout?.chatSurface?"flush":"card")&&vd(n)&&Sd(n)&&s&&!r;e.classList.toggle("persona-artifact-chat-flush",q);let j=D||q?"none":H,_=D?k:O?"none":R,V=D?M:$;q&&(_="none",V="0");let U=null!=L?.borderRadius&&""!==L.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,K=q&&!U?"0":$,J=dt.scrollTop;e.style.cssText="",ot.style.cssText="",at.style.cssText="",lt.style.cssText="",dt.style.cssText="",tn||(Bt.style.cssText=""),We&&(dt.style.display="none"),(a||s)&&(e.style.minWidth="0");let G=()=>{J<=0||(dt.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(dt.scrollTop===J)return;let e=dt.scrollHeight-dt.clientHeight;e<=0||(dt.scrollTop=Math.min(J,e))})};if(y)return ot.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"),ot.style.cssText=`\n position: fixed !important;\n inset: 0 !important;\n width: 100% !important;\n height: 100% !important;\n max-height: 100% !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${x} !important;\n background-color: var(--persona-surface, #ffffff) !important;\n `,at.style.cssText="\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: none !important;\n border-radius: 0 !important;\n ",lt.style.cssText="\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: 0 !important;\n border: none !important;\n ",dt.style.flex="1 1 0%",dt.style.minHeight="0",dt.style.overflowY="auto",Bt.style.flexShrink="0",br(),ae=!0,void G();let X=Ml(n);if(o||r){if(r)if("emerge"!==xi(n).reveal||i)at.style.width="100%",at.style.maxWidth="100%";else{let e=xi(n).width;at.style.width=e,at.style.maxWidth=e}}else s&&a?(at.style.width="100%",at.style.maxWidth="100%"):(at.style.width=X.width,at.style.maxWidth=X.maxWidth);if(Lo(),at.style.boxShadow=j,at.style.borderRadius=K,D?at.style.border="none":O&&(at.style.border=R),lt.style.border=_,lt.style.borderRadius=V,lt.style.boxShadow=D&&!q?z:"",q&&(lt.style.background="transparent",dt.style.background="transparent",Bt.style.background="transparent",Bt.style.borderTop="none"),O){let e=n.features?.artifacts?.layout;Un=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||$}else Un=null;let Q=null!=L?.border||null!=c?.border;if(r&&!y&&!I&&!D&&!O&&!Q&&(lt.style.border="none","right"===xi(n).side?lt.style.borderLeft="1px solid var(--persona-border)":lt.style.borderRight="1px solid var(--persona-border)"),r&&!y&&O&&!Q&&("right"===xi(n).side?at.style.borderLeft="1px solid var(--persona-border)":at.style.borderRight="1px solid var(--persona-border)"),a&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",s&&(e.style.width="100%"),ot.style.display="flex",ot.style.flexDirection="column",ot.style.flex="1 1 0%",ot.style.minHeight="0",ot.style.maxHeight="100%",ot.style.height="100%",s&&(ot.style.overflow="hidden"),at.style.display="flex",at.style.flexDirection="column",at.style.flex="1 1 0%",at.style.minHeight="0",at.style.maxHeight="100%",at.style.height="100%",D||(at.style.overflow="hidden"),lt.style.display="flex",lt.style.flexDirection="column",lt.style.flex="1 1 0%",lt.style.minHeight="0",lt.style.maxHeight="100%",lt.style.overflow="hidden",dt.style.flex="1 1 0%",dt.style.minHeight="0",dt.style.overflowY="auto",Bt.style.flexShrink="0"),s&&(I||D||q)&&!r&&(q||(ot.style.padding="var(--persona-panel-inset)"),ot.style.background="var(--persona-panel-canvas-bg)"),ot.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"),!o&&!s&&!r&&(Ii[v]??Ii["bottom-right"]).split(" ").forEach(e=>ot.classList.add(e)),o){let e=F(n).sidebarWidth?n.launcher?.sidebarWidth??"420px":es(xs(n),"components.panel.width")??"420px";ot.style.cssText=i?`\n position: fixed !important;\n top: var(--persona-panel-inset) !important;\n bottom: var(--persona-panel-inset) !important;\n width: ${e} !important;\n height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${x} !important;\n ${w?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}\n `:`\n position: fixed !important;\n top: 0 !important;\n bottom: 0 !important;\n width: ${e} !important;\n height: 100vh !important;\n max-height: 100vh !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${x} !important;\n ${w?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}\n `,at.style.cssText=`\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: ${j} !important;\n border-radius: ${K} !important;\n ${D?"border: none !important;":O?`border: ${R} !important;`:""}\n `,at.style.setProperty("width","100%","important"),at.style.setProperty("max-width","100%","important"),lt.style.cssText=`\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: ${V} !important;\n border: ${_} !important;\n ${D&&!q?`box-shadow: ${z} !important;`:""}\n ${q?"background: transparent !important;":""}\n `,tn||(Bt.style.cssText=`\n flex-shrink: 0 !important;\n border-top: none !important;\n padding: 8px 16px 12px 16px !important;\n ${q?"background: transparent !important;":""}\n `)}if(!s&&!r){let e="max-height: -moz-available !important; max-height: stretch !important;",t=o?"":"padding-top: 1.25em !important;",r=o?"":`z-index: ${n.launcher?.zIndex??pn} !important;`;ot.style.cssText+=e+t+r}br(),G()},Jo=()=>{e.style.setProperty("--persona-content-max-width",ks(n,se()))},Go=!1;function Yo(){n.layout?.topFade&&dt.scrollTop>1?dt.setAttribute("data-persona-top-fade","true"):dt.removeAttribute("data-persona-top-fade")}let Xo=()=>{Yo();let t=Ms(n,se());se()&&n.composer?.placement&&!0===n.debug&&!Go&&(Go=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=cr();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",pr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??As),wr()},Qo=()=>{if(se())return;let t=vi(n),r=n.launcher?.sidebarMode??!1;if(t||r||n.launcher?.fullHeight||!Y)return;let o=e.ownerDocument.defaultView??window,a=n.launcher?.mobileFullscreen??!0,s=n.launcher?.mobileBreakpoint??640;if(a&&o.innerWidth<=s)return;let i=Ml(n);at.style.height=i.height,at.style.maxHeight=i.maxHeight};Uo(),Cs(e,n),kd(e,n),Ad(e,n),Jo(),Xo(),_n=()=>{Uo(),Qo(),Cs(e,n),kd(e,n),Ad(e,n),Jo(),Xo(),Un?e.style.setProperty("--persona-artifact-welded-outer-radius",Un):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Ge(),Je()};let Zo=[];Zo.push(()=>{Dn=!0}),Zo.push(()=>{u.forEach(e=>e()),p.destroy()}),Zo.push(()=>{document.removeEventListener("keydown",po)}),Zo.push(()=>{null!==sr&&clearTimeout(sr)});let ea=null,ta=null;Zo.push(()=>{ea?.(),ea=null,ta?.(),ta=null}),Fn&&Zo.push(()=>{Fn?.disconnect(),Fn=null}),Zo.push(()=>{go?.(),go=null,To(),mo&&(mo.remove(),mo=null),Wn?.element.style.removeProperty("width"),Wn?.element.style.removeProperty("maxWidth"),Wn?.destroy()}),ye&&Zo.push(()=>{Ee=!0,Te=null,null!==De&&(cancelAnimationFrame(De),De=null),Le?.destroy(),Le=null,Ae?.destroy(),Ae=null,Se=null});let na=null,oa=()=>{na&&(na(),na=null),"auto"===n.colorScheme&&(na=Ss(()=>{Cs(e,n)}))};oa(),Zo.push(()=>{na&&(na(),na=null)}),Zo.push(()=>{x=!0,v?.()}),Zo.push(()=>{A=!0});let aa=!1;Zo.push(()=>{aa=!0});let sa=(t,r)=>{let n=Xs(t,r);return n||!Ks.includes(t)?n:(mi().then(n=>{if(aa)return;Js(n.wipe),Js(n.glyphCycle);let o=Xs(t,r);o&&ci(o,e)}).catch(()=>{}),null)},ia=n.features?.streamAnimation;if(ia?.type&&"none"!==ia.type){let t=sa(ia.type,ia.plugins);t&&ci(t,e),Zo.push(()=>(e=>{let t=di.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}})(e))}let la=Mi(ht),da=Mi(pt),ca=Mi(ut),pa=[la,da,ca];Zo.push(()=>{pa.forEach(e=>e.destroy())});let ha,ma=null,Ma=null,Ia=!1,Ta=0,La=null,Pa=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),Ba=e=>{for(let t=e.length-1;t>=0;t--)if(yr(e[t]))return e[t].id??null;return null},Ha=!1,$a=!1,Wa=!1,Da=(e,t)=>{$a||!0!==n.debug||!t.enabled||t.expose||Ia||Wa&&(ha.isStreaming()||e.some(yr)||($a=!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.")))},Oa=e=>{if(!ha)return;let t=e??ha.getMessages(),r=e=>{e.render([],ha,mt,t)},o=e=>{pa.forEach(t=>{t!==e&&r(t)})};Ma&&(Pa(t)>Ta||Ba(t)!==La)&&(Ma=null);let a=xr(n);Da(t,a);let s=a.enabled?vr(t):null,i=Ma??s,l=Ma?"host":"agent";if(i){let e=n.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),a="after-message"===("auto"===r?se()?"composer":"after-message":r)?ca:la;return o(a),void a.render(i,ha,mt,t,n.suggestionChipsConfig,{source:l,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??"wrap",maxItems:e?.maxItems??4,config:n,plugins:c,submitPrompt:rp})}if(t.some(e=>"user"===e.role))return void pa.forEach(r);let d=!0===n.future?.v5Defaults,p=dr(),u=n.suggestions?.starters??(d?{}:void 0);if(u){let e=kl(cr(),t),a=u.placement??"auto",s="auto"===a?e?"welcome":"composer":a;if("welcome"===s&&!e)return Ha||!0!==n.debug||(Ha=!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".')),void pa.forEach(r);let i="welcome"===s?da:la;return o(i),void i.render(u.items??n.suggestionChips,ha,mt,t,n.suggestionChipsConfig,{surface:"starter",variant:u.variant??(d&&!p?"chip":"card"),behavior:u.behavior??"send",overflow:u.overflow??"wrap",maxItems:u.maxItems??(d&&!p?3:4),config:n,plugins:c,submitPrompt:rp})}o(la),la.render(n.suggestionChips,ha,mt,t,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:n,plugins:c,submitPrompt:rp})},Fa=()=>{Ma&&(Ma=null,Oa())},za=!1,qa=new Map,ja=new Map,_a=new Map,Va=new Map,Ua=null,Ka=null;function Ja(){if(!Ua)return;let e=Ua;Ua=null,Ka?.destroy(),Ka=null,qa.delete(e),lt.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),ha&&pl(ct,ha.getMessages(),ue)}let Ga=0,Ya=null!==Ve(),Xa=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),Qa=0,Za=null,ts=!1,rs=!1,ns=0,os=null,as=null,ss=!1,is=!1,ls=null,ds=!0,cs=!1,ps=null,us=!1,hs=()=>{us=!0,bs()},ms=null,gs=24,fs=null,ys=()=>{e.setAttribute("data-persona-scrollbar",Xt()),"on-scroll"!==Xt()&&(null!==fs&&clearTimeout(fs),fs=null,dt.removeAttribute("data-persona-scrollbar-visible"))},bs=()=>{"on-scroll"===Xt()&&(dt.setAttribute("data-persona-scrollbar-visible",""),null!==fs&&clearTimeout(fs),fs=setTimeout(()=>{fs=null,zs(dt,gs)&&dt.removeAttribute("data-persona-scrollbar-visible")},1e3))};ys(),Zo.push(()=>{null!==fs&&clearTimeout(fs)});let vs=new Map,Ts=!1,Ps=null,Bs={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};An();let $s=n.voiceRecognition?.autoResume??!1,js=e=>{N.emit("voice:state",{active:Bs.active,source:e,timestamp:Date.now()})},Vs=()=>{U(e=>({...e,voiceState:{active:Bs.active,timestamp:Date.now(),manuallyDeactivated:Bs.manuallyDeactivated}}))},Us=()=>ha?Kc(ha.getMessages()).filter(e=>!e.__skipPersist):[],Gs=null,Ys=(e,t)=>{typeof console<"u"&&console.error(e,t)},Zs=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{Ys(t,e)}):null}catch(e){return Ys(t,e),null}},n=Gs?Gs.then(()=>r()??void 0):r();if(!n)return;let o=n.finally(()=>{Gs===o&&(Gs=null)});Gs=o};function ei(e){if(!R?.save)return;let t=e?Kc(e):ha?Us():[],r=H&&ha?.getResumableHandle();r&&($={...$,durableResume:{executionId:r.executionId,after:r.lastEventId}});let n={messages:t,metadata:$,artifacts:Kn.artifacts,selectedArtifactId:Kn.selectedId,...ti?{draft:ti}:{}};Zs(()=>R.save(n),"[AgentWidget] Failed to persist state:")}let ti,ri=()=>!(!R?.save||!1===n.persistState||"object"==typeof n.persistState&&!1===n.persistState.persist?.draft),ni=function(e){let t=e.delay??500,r=null,n=!1,o=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{n||(o(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{n||null===r||(o(),e.write())},cancel:o,destroy:()=>{n=!0,o()}}}({write:()=>{if(!ri())return;let e=Ar.getState(),t=function(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}({text:e.text,mentionRefs:e.mentionRefs,contentSegments:Bc(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(ti)&&(ti=t,ei())}});function oi(){ri()&&ni.schedule()}function li(){ni.flush()}function pi(e){if(!ri())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),o=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(e=>e.id)),s=(e.activeModeIds??[]).filter(e=>a.has(e)),i=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...o?{mentionRefs:n}:{},...o&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(n.contextMentions?.sources??[]).map(e=>e.id),modelIds:(n.composer?.models??[]).map(e=>e.id),modes:n.composer?.modes??[]});t&&(ti=e,mt&&!mt.value&&(mt.value=t.text,mt.dispatchEvent(new Event("input",{bubbles:!0})),Mr()),t.selectedModelId&&(Ar.setSelectedModelId(t.selectedModelId),$r?.repaint()),Rr(t.activeModeIds??[]),t.quote&&zr(t.quote),ni.cancel())}function ui(){ni.cancel(),ti&&(ti=void 0,ri()&&ei())}let hi=null,fi=()=>ot.querySelector("#persona-scroll-container")||dt,yi=()=>{null!==hi&&(cancelAnimationFrame(hi),hi=null),ts=!1},Ci=()=>{null!==Za&&(cancelAnimationFrame(Za),Za=null),rs=!1,yi()},ki=()=>{let e=_t()||"Jump to latest",t=za&&Ei()&&("anchor-top"!==Vt()||Gt());Zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",t),ns>0?(nr.textContent=String(ns),nr.style.display="",Zt.setAttribute("aria-label",`${e} (${ns} new)`)):(nr.textContent="",nr.style.display="none",Zt.setAttribute("aria-label",t?`${e} (response streaming below)`:e))},Ti=()=>{0!==ns&&(ns=0,ki())},Ei=()=>Ut()?!Xa.isFollowing():!(()=>{let e=os?.spacerHeight??0;return e<=0?zs(dt,gs):Ki(e)-dt.scrollTop-dt.clientHeight<=gs})(),Li=()=>!!ha&&ha.getMessages().length>0,Ni=()=>{if(!1===be.enabled||We||Ue&&"panel"===Ke)return Zt.parentNode&&Zt.remove(),void(Zt.style.display="none");Zt.parentNode!==lt&<.appendChild(Zt),fr();let e=Fs(dt)>0&&Ei()&&Li();e?ki():Ti(),Zt.style.display=e?"":"none"},Ri=()=>{Xa.pause()&&(Ci(),Ni())},$i=()=>{Xa.resume(),Ti(),Ni()},Wi=(e=!1)=>{Ut()&&Li()&&Xa.isFollowing()&&(!e&&!za||(null!==Za&&(cancelAnimationFrame(Za),Za=null),rs=!0,Za=requestAnimationFrame(()=>{Za=null,rs=!1,Xa.isFollowing()&&zi(fi(),e?220:140)})))},Fi=(e,t,r,n=()=>!0)=>{let o=e.scrollTop,a=t(),s=a-o;if(yi(),Math.abs(s)<1)return ts=!0,e.scrollTop=a,Qa=e.scrollTop,void(ts=!1);let i=performance.now();ts=!0;let l=d=>{if(!n())return void yi();let c=t();c!==a&&(a=c,s=a-o);let p=d-i,u=Math.min(p/r,1),h=(e=>1-Math.pow(1-e,3))(u),m=o+s*h;e.scrollTop=m,Qa=e.scrollTop,u<1?hi=requestAnimationFrame(l):(e.scrollTop=a,Qa=e.scrollTop,hi=null,ts=!1)};hi=requestAnimationFrame(l)},zi=(e,t=500)=>{let r=Fs(e)-e.scrollTop;if(!(Math.abs(r)<1))return Math.abs(r)>=80?(yi(),ts=!0,e.scrollTop=Fs(e),Qa=e.scrollTop,void(ts=!1)):void Fi(e,()=>Fs(e),t,()=>Xa.isFollowing());Qa=e.scrollTop},qi=()=>{if(!Li())return void Ni();let e=fi();ts=!0,e.scrollTop=Fs(e),Qa=e.scrollTop,ts=!1,Ni()},ji=e=>{let t=0,r=e;for(;r&&r!==dt;)t+=r.offsetTop,r=r.offsetParent;return t},_i=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=dt.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??dt.ownerDocument.getSelection()})(),dt),Vi=()=>{if("last-user-turn"!==(ve.restorePosition??"bottom"))return!1;let e=ha?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>"user"===e.role);if(!t)return!1;let r=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(t.id):t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=dt.querySelector(`[data-message-id="${r}"]`);if(!n)return!1;let o=Math.min(Math.max(0,ji(n)-Kt()),Fs(dt));return ts=!0,dt.scrollTop=o,Qa=dt.scrollTop,ts=!1,"follow"===Vt()&&!zs(dt,gs)&&Xa.pause(),Ni(),!0},Ui=e=>{let t=Math.max(0,Math.round(e));or.style.height=`${t}px`,or.style.display=t>0?"":"none",os&&(os.spacerHeight=Math.max(0,e))},Ki=e=>{let t=parseFloat(getComputedStyle(dt).paddingBottom)||0,r=0;for(let e of Array.from(dt.children)){if(e===or||0===e.offsetHeight)continue;let t=ji(e)+e.offsetHeight;t>r&&(r=t)}let n=dt.scrollHeight-e;return r>0?Math.min(r+t,n):n},Ji=()=>{null!==as&&(cancelAnimationFrame(as),as=null),yi(),os=null,or.style.height="0px",or.style.display="none"},Gi=e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Zi=e=>dt.querySelector(`[data-message-id="${Gi(e)}"]`),el=e=>{null!==as&&cancelAnimationFrame(as),as=requestAnimationFrame(()=>{as=null;let t=Gi(e),r=dt.querySelector(`[data-message-id="${t}"]`);if(!r)return;let n=ji(r),o=Ki(os?.spacerHeight??0),{targetScrollTop:a,spacerHeight:s}=qs({anchorOffsetTop:n,topOffset:Kt(),viewportHeight:dt.clientHeight,contentHeight:o,slack:gs});os={initialSpacerHeight:s,contentHeightAtAnchor:o,spacerHeight:s},Ui(s),Fi(dt,()=>r.isConnected?Math.max(0,ji(r)-Kt()):a,220)})},rl=()=>{if("anchor-top"!==Vt()||!os||!ps)return;let e=Zi(ps);if(!e)return;yi();let t=os.spacerHeight,r=Ki(t),{targetScrollTop:n,spacerHeight:o}=qs({anchorOffsetTop:ji(e),topOffset:Kt(),viewportHeight:dt.clientHeight,contentHeight:r,slack:gs});os={initialSpacerHeight:o,contentHeightAtAnchor:r,spacerHeight:o},Ui(o),ts=!0,dt.scrollTop=n,Qa=dt.scrollTop,ts=!1,Ni()},nl=e=>{if(null===ls)return!0;let t=Zi(ls),r=Zi(e);if(!t||!r)return!0;let n=ji(r)-ji(t);return Kt()+n>dt.clientHeight-96},al=(e,t)=>{let r="user"===t?"user":"assistant",o=n.layout?.messages?.[r],a=o?.width??"content",s=o?.maxWidth??("full"===a?`var(--persona-message-${r}-max-width, 100%)`:void 0);e.classList.add("persona-message-row"),e.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",a),s?e.style.setProperty("--persona-message-row-max-width",s):e.style.removeProperty("--persona-message-row-max-width")},il=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),al(r,t),r},ll=!1,dl=()=>{ll||(ll=!0,xt().catch(()=>{}),je().catch(()=>{ll=!1}))},pl=(e,t,r)=>{t.length>0&&dl(),((e,t,r)=>{let l=new Set;for(let e of t){let t="tool"===e.variant?"tool":"reasoning"===e.variant?"reasoning":null;if(!t||"row"!==Pe(n,t))continue;let r="tool"===t?n.features?.toolCallDisplay:n.features?.reasoningDisplay;!1!==r?.expandable&&(l.add(e.id),s.observe(e,t,"tool"===t?o:a,r))}let d=document.createElement("div"),p=(()=>{let e=c.find(e=>e.renderLoadingIndicator);return e?.renderLoadingIndicator?e.renderLoadingIndicator:n.loadingIndicator?.render?n.loadingIndicator.render:void 0})(),u=new Set,h=new Map,m=new Set,g=c.some(e=>e.renderAskUserQuestion),f=[],y=[],v=!1!==n.enableComponentStreaming,w=!1!==n.approval,x=[],C=n.messageActions,S=!0===C?.showRegenerate&&!1!==C.enabled&&!0!==ro.current?.isStreaming()?function(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if("user"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return qn(e,r.id)?r.id:null}return null}(t):null,A=!0===C?.showEdit&&!1!==C.enabled,M=!0===C?.showQuote&&!1!==C.enabled,I=null,T=n.features?.reasoningDisplay?.completedVisibility,E=e=>"removed"===T||"removed-when-short"===T&&((e,t)=>{let r=t?.durationMs??15e3,n=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<n})(e,n.features?.reasoningDisplay?.shortThinkThreshold),P="removed"===n.features?.toolCallDisplay?.completedVisibility,B=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?E(e.reasoning):P&&"tool"===e.variant&&"complete"===e.toolCall?.status;if(t.forEach(t=>{if(B(t))return;if(u.add(t.id),h.set(t.id,t.role),Ua===t.id&&Ka){let e=il(t.id,t.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void(I={messageId:t.id,element:Ka.element})}let s=g&&Qt(t),l=w&&"approval"===t.variant&&!!t.approval,C=!s&&"assistant"===t.role&&!t.variant&&v&&Wc(t);!l&&Va.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Va.delete(t.id)),!C&&_a.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),_a.delete(t.id));let T=Qt(t)?`:${t.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:"",E={canRegenerate:S===t.id,canEdit:A&&jn(t),canQuote:M&&!t.variant&&(t.content?.trim().length??0)>0},P=`${E.canRegenerate?"r":""}${E.canEdit?"e":""}${E.canQuote?"q":""}`,N=function(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)??"","string"==typeof e.toolCall?.args?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")}(t,Ga)+T+`:${P}`,R=s||l||C?null:function(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}(qa,t.id,N);if(R)return d.appendChild(R.cloneNode(!0)),void(Qt(t)&&t.toolCall?.id&&!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ao(t)));let H=null,$=c.find(e=>!!("reasoning"===t.variant&&e.renderReasoning||"tool"===t.variant&&e.renderToolCall||!t.variant&&e.renderMessage)),W=n.layout?.messages;if(Qt(t)&&!0===t.agentMetadata?.askUserQuestionAnswered)return ja.delete(t.id),void e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime");if(yr(t)&&xr(n).enabled)return;if(Qt(t)&&!1!==n.features?.askUserQuestion?.enabled){let e=c.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&ro.current){let r=ja.get(t.id),o=r!==N,a=null;if(o){let{payload:r,complete:o}=er(t),s=t.id,i=()=>ro.current?.getMessages().find(e=>e.id===s);a=e.renderAskUserQuestion({message:t,payload:r,complete:o,resolve:e=>{let t=i();t&&ro.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=i();e?.agentMetadata?.awaitingLocalTool&&(ro.current?.markAskUserQuestionResolved(e),ro.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:n})}if(o&&null===a&&null==r)return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ao(t)));let s=il(t.id,t.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),d.appendChild(s),void f.push({messageId:t.id,fingerprint:N,bubble:a})}return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ao(t)))}if(l){let r=k();if(!r)return void d.appendChild(il(t.id,t.role));let o=c.find(e=>"function"==typeof e.renderApproval)??b,a=Va.get(t.id)!==N,s=null;if(a&&o?.renderApproval){let e=t.id,a=(t,r)=>{let n=ro.current?.getMessages().find(t=>t.id===e);n?.approval&&("webmcp"===n.approval.toolType?ro.current?.resolveWebMcpApproval(n.id,t):ro.current?.resolveApproval(n.approval,t,r))};s=o.renderApproval({message:t,defaultRenderer:()=>r.createApprovalBubble(t,n,i),config:n,approve:e=>a("approved",e),deny:e=>a("denied",e)})}if(!a||null!==s){let e=il(t.id,t.role);return e.setAttribute("data-approval-plugin-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void x.push({messageId:t.id,fingerprint:N,bubble:s})}e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Va.delete(t.id),H=r.createApprovalBubble(t,n,i)}else if($)if("reasoning"===t.variant&&t.reasoning&&$.renderReasoning){if(!he)return;H=$.renderReasoning({message:t,defaultRenderer:()=>Fl(t,n,a),config:n})}else if("tool"===t.variant&&t.toolCall&&$.renderToolCall){if(!me)return;H=$.renderToolCall({message:t,defaultRenderer:()=>Jl(t,n,o),config:n})}else $.renderMessage&&(H=$.renderMessage({message:t,defaultRenderer:()=>{let e=cl(t,r,W,n.messageActions,et,{loadingIndicatorRenderer:p,widgetConfig:n,actionEligibility:E});return"user"!==t.role&&L(e,t,n,ha),e},config:n}));if(!H&&C){let o=Dc(t);if(o){let a=_a.get(t.id),s=a!==N,i=!1!==n.wrapComponentDirectiveInBubble&&!1!==sd.getOptions(o.component)?.bubbleChrome,l=null;if(s){let a=Rc(o,{config:n,message:t,transform:r});if(a&&"PersonaArtifactInline"===o.component){let r=a.hasAttribute("data-artifact-inline")?a:a.querySelector("[data-artifact-inline]"),n=r?.getAttribute("data-artifact-inline")??"",o=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(n):n,s=n?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${o}"]`)??null:null;r&&s&&s!==r&&yd()?.hasLiveInlineArtifactBlock(s)&&(r===a?a=s:r.replaceWith(s))}if(a)if(i){let e=document.createElement("div");if(e.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),e.id=`bubble-${t.id}`,e.setAttribute("data-message-id",t.id),t.content&&t.content.trim()){let n=document.createElement("div");n.className="persona-mb-3 persona-text-sm persona-leading-relaxed",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(a),l=e}else{let e=document.createElement("div");if(e.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",e.id=`bubble-${t.id}`,e.setAttribute("data-message-id",t.id),e.setAttribute("data-persona-component-directive","true"),t.content&&t.content.trim()){let n=document.createElement("div");n.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(a),l=e}}if(l||null!=a){let e=il(t.id,t.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void y.push({messageId:t.id,fingerprint:N,bubble:l})}}}if(!H)if("reasoning"===t.variant&&t.reasoning){if(!he)return;H=Fl(t,n,a)}else if("tool"===t.variant&&t.toolCall){if(!me)return;H=Jl(t,n,o)}else if("approval"===t.variant&&t.approval){if(!1===n.approval)return;let e=k();if(!e)return;H=e.createApprovalBubble(t,n,i)}else{let e=n.layout?.messages;H=e?.renderUserMessage&&"user"===t.role?e.renderUserMessage({message:t,config:n,streaming:!!t.streaming}):e?.renderAssistantMessage&&"assistant"===t.role?e.renderAssistantMessage({message:t,config:n,streaming:!!t.streaming}):cl(t,r,e,n.messageActions,et,{loadingIndicatorRenderer:p,widgetConfig:n,actionEligibility:E}),"user"!==t.role&&H&&L(H,t,n,ha)}let D=il(t.id,t.role);D.appendChild(H),function(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}(qa,t.id,N,D),d.appendChild(D)}),it.composerOverlay&&it.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!m.has(t)&&hr(it.composerOverlay,t)}),n.features?.toolCallDisplay?.grouped){let e=[],r=[],a="summary"===n.features.toolCallDisplay.groupedMode;t.forEach(t=>{if("tool"===t.variant&&t.toolCall&&me){if(P&&"complete"===t.toolCall.status)return;r.push(t)}else"reasoning"===t.variant&&(!he||"complete"===t.reasoning?.status&&E(t.reasoning))||((r.length>1||a&&r.length>0)&&e.push(r),r=[])}),(r.length>1||a&&r.length>0)&&e.push(r),e.forEach(e=>{let t=e.map(e=>Array.from(d.children).find(t=>t instanceof HTMLElement&&t.getAttribute("data-wrapper-id")===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let r=il(`tool-group-${e[0].id}`,"assistant");if(r.setAttribute("data-persona-tool-group-row","true"),"collapsible"===n.features?.toolCallDisplay?.groupedMode){let a=`tool-group-${e[0].id}`,i=e.some(e=>"complete"!==e.toolCall?.status),d={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:i?"running":"complete",chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>!1===e.toolCall?.success)}};l.add(a),s.observe(d,"tool",o,n.features.toolCallDisplay);let c=`${i?"Using":"Used"} ${e.length} tools`,p=n.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:c,config:n}),u=function(e,t,r,n){let o=ne("div","");o.id=`bubble-${e.id}`,o.dataset.messageId=e.id;let a=ne("button","");a.type="button",a.dataset.expandHeader="true",a.dataset.bubbleType="tool",a.setAttribute("aria-expanded",String(r));let s=ne("div","");"string"==typeof n?s.textContent=n:s.appendChild(n),Me(a,s,{expandable:!0,expanded:r,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let i=ne("div","persona-border-t");return i.id=`activity-details-${e.id}`,i.style.display=r?"":"none",a.setAttribute("aria-controls",i.id),o.append(a,i),Ne(o,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),o.dataset.personaToolGroup="true","shimmer"===t.features?.toolCallDisplay?.loadingAnimation&&(o.dataset.activityGroupShimmer="true"),{bubble:o,body:i}}(d,n,o.has(a),p??c);return u.bubble.classList.add("persona-tool-group"),u.body.dataset.personaToolGroupStack="true",t[0].before(r),r.appendChild(u.bubble),void t.forEach((e,t)=>{e.style.setProperty("--persona-message-row-max-width","100%"),e.style.setProperty("--persona-activity-stagger",40*t+"ms"),e.classList.add("persona-activity-group-child"),u.body.appendChild(e)})}let i=document.createElement("div");i.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",i.setAttribute("data-persona-tool-group","true");let c=document.createElement("div");c.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",c.id=`tool-group-summary-${e[0].id}`;let p=`Called ${e.length} ${1===e.length?"tool":"tools"}`,u=n.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:p,config:n});((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(c,u)||(c.textContent=p);let h=document.createElement("div");h.className="persona-tool-group-stack persona-flex persona-flex-col",h.id=`tool-group-stack-${e[0].id}`,h.setAttribute("data-persona-tool-group-stack","true"),i.appendChild(c),a||i.appendChild(h),r.appendChild(i),t[0].before(r),t.forEach((e,r)=>{if(a)return void e.remove();e.style.setProperty("--persona-message-row-max-width","100%");let n=document.createElement("div");n.className="persona-tool-group-item persona-relative",n.setAttribute("data-persona-tool-group-item","true"),r<t.length-1&&n.setAttribute("data-persona-tool-group-connector","true"),n.appendChild(e),h.appendChild(n)})})}s.prune(l),function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(qa,u);let N=e=>"tool"===e.variant&&!me||"reasoning"===e.variant&&!he||B(e),R=t.some(e=>"assistant"===e.role&&e.streaming&&!N(e)),H=t.length-1;for(;H>=0&&N(t[H]);)H--;let $=H>=0?t[H]:void 0,W=H<t.length-1,D="assistant"===$?.role&&!$.streaming&&"approval"!==$.variant&&!W;if(za&&t.some(e=>"user"===e.role)&&!R&&!D){let e={config:n,streaming:!0,location:"standalone",defaultRenderer:tl},t=c.find(e=>e.renderLoadingIndicator),r=null;if(t?.renderLoadingIndicator&&(r=t.renderLoadingIndicator(e)),null===r&&n.loadingIndicator?.render&&(r=n.loadingIndicator.render(e)),null===r&&(r=tl()),r){let e=document.createElement("div"),t=!1!==n.loadingIndicator?.showBubble,o=n.layout?.messages?.layout??"bubble";e.className=t?ol("assistant",o).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),e.setAttribute("data-typing-indicator","true"),t&&(e.style.color="var(--persona-message-assistant-text, var(--persona-text))","flat"!==o&&(e.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),e.appendChild(r);let a=il("typing-indicator","assistant");a.appendChild(e),d.appendChild(a)}}if(!za&&t.length>0){let e=t[t.length-1],r={config:n,lastMessage:e,messageCount:t.length},o=c.find(e=>e.renderIdleIndicator),a=null;if(o?.renderIdleIndicator&&(a=o.renderIdleIndicator(r)),null===a&&n.loadingIndicator?.renderIdle&&(a=n.loadingIndicator.renderIdle(r)),a){let e=document.createElement("div"),t=!1!==n.loadingIndicator?.showBubble;e.className=t?["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(" "),e.setAttribute("data-idle-indicator","true"),e.appendChild(a);let r=il("idle-indicator","assistant");r.appendChild(e),d.appendChild(r)}}if(function(e){e.querySelectorAll("table").forEach(e=>{if(e.parentElement?.classList.contains("persona-table-scroll"))return;let t=document.createElement("div");t.className="persona-table-scroll",e.replaceWith(t),t.appendChild(e)})}(d),Ws(e,d),gt(e),I){let{messageId:t,element:r}=I,n=e.querySelector(`#wrapper-${t}`);n&&r.parentElement!==n&&(al(n,h.get(t)??"user"),n.replaceChildren(r))}if(f.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of f){let o=e.querySelector(`#wrapper-${t}`);o&&(al(o,h.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),ja.set(t,r)))}if(ja.size>0)for(let e of ja.keys())u.has(e)||ja.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of y){let o=e.querySelector(`#wrapper-${t}`);o&&(al(o,h.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),_a.set(t,r)))}if(_a.size>0)for(let e of _a.keys())u.has(e)||_a.delete(e);if(x.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of x){let o=e.querySelector(`#wrapper-${t}`);o&&(al(o,h.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Va.set(t,r)))}if(Va.size>0)for(let e of Va.keys())u.has(e)||Va.delete(e)})(e,t,r),Hn()},ml=null,gl=()=>{ml&&((e.ownerDocument??document).removeEventListener("pointerdown",ml,!0),ml=null)};Zo.push(()=>gl());let fl=null,xl=()=>{fl&&((e.ownerDocument??document).removeEventListener("keydown",fl,!0),fl=null)};Zo.push(()=>xl());let Cl=!1,Al=new Set,Il=()=>{if(!se())return;let t=it.peekBanner,r=it.peekTextNode;if(!t||!r)return;if(le)return void t.classList.remove("persona-pill-peek--visible");let o,a=ha?.getMessages()??[];for(let e=a.length-1;e>=0;e--){let t=a[e];if("assistant"===t.role&&t.content){o=t;break}}if(!o)return void t.classList.remove("persona-pill-peek--visible");let s=o.content,i=!!o.streaming,l=(()=>{let e=n.launcher?.composerBar?.peek?.streamAnimation;return e||n.features?.streamAnimation})(),d=_s(l),c="none"!==d.type?sa(d.type,l?.plugins):null,p=!0===c?.isAnimating?.(o),u=null!==c&&(i||p);u&&c&&!Al.has(c.name)&&(ci(c,e),Al.add(c.name));let h=u&&c?.containerClass?c.containerClass:null,m=r.dataset.personaPeekStreamClass??null;m&&m!==h&&(r.classList.remove(m),delete r.dataset.personaPeekStreamClass),h&&m!==h&&(r.classList.add(h),r.dataset.personaPeekStreamClass=h),u?(r.style.setProperty("--persona-stream-step",`${d.speed}ms`),r.style.setProperty("--persona-stream-duration",`${d.duration}ms`)):(r.style.removeProperty("--persona-stream-step"),r.style.removeProperty("--persona-stream-duration"));let g=u?Qs(s,d.buffer,c,o,i):s;if(!u||"skeleton"!==d.placeholder||!i||g&&g.trim()){let e=Math.max(0,g.length-100),n=g.length>100?g.slice(-100):g,a=Ye(n);if(u&&c){let s=a;("char"===c.wrap||"word"===c.wrap)&&(s=ai(a,c.wrap,`peek-${o.id}`,{skipTags:c.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,c.useCaret&&n.length>0){let e=si(),t=i.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];r?.parentNode?r.parentNode.insertBefore(e,r.nextSibling):i.appendChild(e)}Ws(r,i),c.onAfterRender?.({container:r,bubble:t,messageId:o.id,message:o,speed:d.speed,duration:d.duration})}else{let e=g.length>100?`…${n}`:n;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=ii();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),Ws(r,e)}let f=za||Cl;t.classList.toggle("persona-pill-peek--visible",f)};if(se()){let e=it.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Pl(!0,"user")};e.addEventListener("pointerdown",t),Zo.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Cl||(Cl=!0,Il())},r=()=>{Cl&&(Cl=!1,Il())};at.addEventListener("pointerenter",t),at.addEventListener("pointerleave",r),Zo.push(()=>{at.removeEventListener("pointerenter",t),at.removeEventListener("pointerleave",r)}),st&&(st.addEventListener("pointerenter",t),st.addEventListener("pointerleave",r),Zo.push(()=>{st.removeEventListener("pointerenter",t),st.removeEventListener("pointerleave",r)}))}let Ll=()=>{if(le&&dl(),!ie())return;if(se()){let t=(n.launcher?.composerBar??{}).expandedSize??"anchored",r=le?"expanded":"collapsed";return ot.dataset.state=r,ot.dataset.expandedSize=t,st&&(st.dataset.state=r,st.dataset.expandedSize=t),ot.style.removeProperty("display"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=n.launcher?.composerBar??{},r=t.expandedSize??"anchored",o=t.bottomOffset??"16px",a=t.collapsedMaxWidth,s=t.expandedMaxWidth??"880px",i=t.expandedTopOffset??"5vh",l=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)",p=ot.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",st){let e=st.style;e.bottom=o,e.width=a??""}if(e&&"fullscreen"!==r){if("modal"===r)return p.top="50%",p.left="50%",p.transform="translate(-50%, -50%)",p.bottom="auto",p.right="auto",p.width=l,p.maxWidth=c,p.maxHeight=d,void(p.height=d);p.left="50%",p.transform="translateX(-50%)",p.bottom=`calc(${o} + var(--persona-pill-area-height, 80px))`,p.top=i,p.width=s,p.maxWidth=c}})(le),lt.style.display=le?"flex":"none",_n(),le?((()=>{if(ml)return;let t=e=>{let t=e.composedPath();t.includes(ot)||st&&t.includes(st)||Pl(!1,"user")};ml=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)})(),(()=>{if(fl)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Pl(!1,"user"))};fl=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)})()):(gl(),xl()),void Il()}let t=vi(n),r=e.ownerDocument.defaultView??window,o=n.launcher?.mobileBreakpoint??640,a=n.launcher?.mobileFullscreen??!0,s=r.innerWidth<=o,i=a&&s&&Y,l=xi(n).reveal;le?(ot.style.removeProperty("display"),ot.style.display=t?"flex":"",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-95","persona-opacity-0"),at.classList.add("persona-scale-100","persona-opacity-100"),Kp?(Kp.setPanelOpen(!0),Kp.element.style.display="none"):Jp&&(Jp.style.display="none")):(t?!t||"overlay"!==l&&"push"!==l||i?(ot.style.setProperty("display","none","important"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.removeProperty("display"),ot.style.display="flex",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.display="",ot.classList.add("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-100","persona-opacity-100"),at.classList.add("persona-scale-95","persona-opacity-0")),Kp?(Kp.setPanelOpen(!1),Kp.element.style.display=t?"none":""):Jp&&(Jp.style.display=t?"none":""))},Pl=(t,r="user")=>{if(!ie()||le===t)return;let o=le;le=t,Ll();let a=(()=>{let t=n.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,o=n.launcher?.mobileFullscreen??!0,a=n.launcher?.mobileBreakpoint??640,s=r.innerWidth<=a,i=vi(n)&&o&&s,l=se()&&"fullscreen"===(n.launcher?.composerBar?.expandedSize??"fullscreen");return t||o&&s&&Y||i||l})();if(le&&a){if(!ea){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(ea=gi(r,n.launcher?.zIndex??pn))}ta||(ta=bi(e.ownerDocument))}else le||(ea?.(),ea=null,ta?.(),ta=null);le&&(Qp(),Vi()||("follow"===Vt()?Wi(!0):qi()));let s={open:le,source:r,timestamp:Date.now()};le&&!o?N.emit("widget:opened",s):!le&&o&&N.emit("widget:closed",s),N.emit("widget:state",{open:le,launcherEnabled:Y,voiceActive:Bs.active,streaming:ha.isStreaming()})},Bl={inputDisabled:!1,sendDisabled:!1},Nl=()=>Bl.inputDisabled,Rl=()=>$e(n.voiceRecognition?.provider)&&!!ha&&(ha.isBargeInActive()||["listening","processing","speaking"].includes(ha.getVoiceStatus())),Hl=()=>Bl.inputDisabled||Bl.sendDisabled;function Dl(){if(!ft)return;if("streaming"===Ar.getState().phase)return void(ft.disabled=!1);let e=!!Sr&&!Sr.isReady();ft.disabled=Hl()||e}function zl(){if(!$t)return;let e=Ar.getState(),t="when-text"===n.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;$t.toggleAttribute("data-persona-send-hidden",t)}function ql(){let e=Oo(n.composer?.inputDisabled),t=Oo(n.composer?.sendDisabled);Bl={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Ar.setInputDisabled(e.disabled),Ar.setSendDisabled(t.disabled);let r="streaming"===Ar.getState().phase,o=e.disabled,a=r||o;mt&&(mt instanceof HTMLTextAreaElement?mt.disabled=o:mt.setAttribute("contenteditable",o?"false":"true"),mt.setAttribute("aria-disabled",o?"true":"false")),Ft&&(Ft.disabled=o),qt&&(qt.disabled=o);for(let e of kr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=o});Dt&&(Dt.disabled=o||r&&!Rl()),pa.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",a?"true":"false")}),e.buttons.forEach(e=>{e.disabled=a})}),ud.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute("aria-disabled",a?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=a})}),Bt.dataset.personaComposerStreaming=r?"true":"false",Bt.dataset.personaComposerInputDisabled=o?"true":"false",Bt.dataset.personaComposerSendDisabled=Hl()?"true":"false",Bt.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=r)}),Dl(),function(){let e=(Bl.inputDisabled?Bl.inputReason:void 0)??(Bl.sendDisabled?Bl.sendReason:void 0);if(se()){let t=yt??Bt;return e?t.setAttribute("title",e):t.removeAttribute("title"),void Bt.toggleAttribute(jc,!!e)}if(e)return bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.setAttribute(jc,""),bt.textContent=e,void Re(bt,n.statusIndicator??{},"idle");if(bt.hasAttribute(jc)&&(bt.removeAttribute("role"),bt.removeAttribute("aria-live"),bt.removeAttribute(jc),m)){let e=ha.getStatus();rt(bt,tt(e),n.statusIndicator??{},e)}}()}let _l=e=>{Ar.setStreaming(e),Wt(e?"stop":"send"),ql()},Vl=()=>{Bs.active||mt&&mt.focus()};N.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Vl(),200)});let Ul=null,Gl=!1,Yl=!vt.hidden,Xl=null,Ql=!W,Zl=null;Zo.push(()=>{Zl?.cancel(),Zl=null});let rd,nd,od=null,id=null,ld=null,dd=!1,cd=t=>{let r=cr(),o=`${r.variant}|${r.layout}|${r.dismiss}|${r.anchor??"bottom"}|${r.align??""}|${r.iconPlacement}|${r.kicker??""}|${r.title}|${r.subtitle}`;(o!==od||r.icon!==rd)&&(od=o,rd=r.icon,hl({host:vt,iconHolder:wt,kicker:St,title:kt,subtitle:At,starterSuggestions:pt},r));let a=void 0===r.message?null:`${n.layout?.messages?.layout??"bubble"}|${r.message}`;a!==id&&(id=a,vl(Ct,r.message,n));let s=t??(ha?ha.getMessages():n.initialMessages);(t=>{let r=(e=>(e??[]).some(e=>"user"===e.role)?"active":"empty")(t);if(r===pr)return;pr=r,e.setAttribute("data-persona-conversation-state",r);let n=gr();wr(),Ql&&(Zl?.cancel(),Zl=((e,t,r,n=260)=>{if(t<=1||wl()||"function"!=typeof e.animate||!e.isConnected)return null;let o="drop"===r?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:n,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})})(Bt,"active"===r?n:gr(),"active"===r?"drop":"rise","centered"===cr().layout?320:260)),rl()})(s);let i=Gl,l=!i&&kl(r,s),d=l!==Yl;if(Yl=l,ld)return Xl?.cancel(),Xl=null,i!==dd&&(dd=i,i?bl(dt,vt,null):yl(dt,vt,ld)),void ul(dt,vt,!i);if(d&&!l&&!i&&"on-first-message"===r.dismiss&&Ql)return void(Xl=((e,t)=>{if(wl()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),n=e.parentElement,o=0,a=0,s=0;if(n){let t=getComputedStyle(n);o=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=n.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-n.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-o:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-o:0)}let i=e.style.overflow;e.style.overflow="hidden";let l=getComputedStyle(e),d=parseFloat(l.paddingTop)||0,c=parseFloat(l.paddingBottom)||0,p=e.animate([{opacity:"1",transform:"none",height:`${r.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${c}px`,marginTop:`${a}px`,marginBottom:`${s}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:-o+"px"}],{duration:180,easing:"ease-out",fill:"forwards"}),u=!1,h=()=>{u||(u=!0,e.style.overflow=i,t(p))};return p.finished.then(h).catch(h),p})(vt,e=>{Xl===e&&(Xl=null),!Yl&&!ld&&(ul(dt,vt,!1),rl()),e?.cancel()}));if(Xl){if(!l&&!i)return;Xl.cancel(),Xl=null}let c=!vt.hidden;ul(dt,vt,l),!l&&c&&rl()},pd=[],ud=[],hd=!1,md=null,gd=()=>{ud.length=0;let e=pd.splice(0,pd.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};Zo.push(gd);let wd=(e,t)=>{let r=Si(e,t);if(!r)return!0===n.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),ne("span");let o=n.suggestions?.starters,a=Ai({item:{...r,behavior:r.behavior??o?.behavior??"send"},index:t,surface:"starter",source:"config",variant:o?.variant??"card",streaming:!!m&&ha.isStreaming(),config:n,plugins:c,chipsConfig:n.suggestionChipsConfig,session:ha,getTextarea:()=>mt,eventTarget:vt,submitPrompt:rp});return ud.push(a),a},xd=()=>{if(hd)return;hd=!0;let e=cr();md=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,nd=e.icon;try{gd(),bl(dt,vt,ld),ld=null,dd=!1;let t=ha?ha.getMessages():n.initialMessages,r=kl(e,t),o=0,a=null;for(let t of c)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>vt,sendMessage:e=>{if(!ha||ha.isStreaming())return;let t=e.trim();t&&ha.sendMessage(t)},requestRender:()=>xd(),renderStarter:e=>wd(e,o++),storage:f(t.id),onCleanup:e=>{pd.push(e)}}),a))break;a&&a!==vt&&(ld=a,yl(dt,vt,a))}finally{hd=!1}cd()},Cd=()=>{cd(),tn||(mt.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Ar.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!n.sendButton?.useIcon&&!ha?.isStreaming()&&(ft.textContent=n.copy?.sendButtonLabel??"Send")),mt.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',mt.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Md=!!n.setStoredConversationId,Id=e=>U(t=>{let r={...t};return delete r[e],r}),Td=e=>{let t=$[e];return"string"==typeof t?t:null},Ed=()=>{let e=$.durableResume;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.executionId&&t.executionId.length>0&&"string"==typeof t.after&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};n.clientToken&&(n={...n,getStoredSessionId:()=>Td("sessionId"),setStoredSessionId:e=>{U(t=>({...t,sessionId:e}))},clearStoredSessionId:n.clearStoredSessionId??(()=>Id("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Td("conversationId")),setStoredConversationId:n.setStoredConversationId??(e=>{U(t=>({...t,conversationId:e}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>Id("conversationId"))});let Ld=()=>n.clientToken??null,Pd=e=>((e,t,r)=>{let n="",o="",a="",s=!1,i=!1,l=0,d=null,c=null,p=new Set,u=()=>{if(r||s)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return s=!0,null}},h=()=>{let e=u();if(!e)return d;try{return e.getItem(n)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let n={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(n)},g=e=>{i||null!==e.key&&e.key!==n||m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await bc(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await bc(`${e}\0${t}`)}`}})(e,t);n=s.storageKey,o=s.leaseKey,a=s.lockName,d=h(),!r&&typeof window<"u"&&window.addEventListener("storage",g)})(),y=e=>new Promise(t=>setTimeout(t,e)),b=()=>{let e=u();if(!e)return null;try{let t=e.getItem(o);if(!t)return null;let r=JSON.parse(t);return"number"==typeof r?.expiresAt&&"string"==typeof r?.ownerNonce?r:null}catch{return null}},v=e=>{let t=u();if(t)try{b()?.ownerNonce===e&&t.removeItem(o)}catch{}},w=new Set,x=e=>i?Promise.reject(new Error("Visitor store destroyed before its first init could start")):e(),C=e=>new Promise(t=>{let r=setTimeout(n,e);function n(){clearTimeout(r),w.delete(n),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===o)&&n()}w.add(n),window.addEventListener("storage",a)});return{ready:f,get:async()=>(await f,m(h(),"external"),d),async set(e){await f;let t=u();if(t)try{t.setItem(n,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(n)}catch{s=!0}m(null,"local")},revision:()=>l,subscribe:e=>(p.add(e),()=>{p.delete(e)}),async withFirstInitLock(e){await f;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):u()?(async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=Date.now()+15e3;for(;!i&&Date.now()<r;){let r=u();if(!r)break;let n=Date.now(),a=b();if(a&&a.expiresAt>n&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-n,500));else{try{r.setItem(o,JSON.stringify({ownerNonce:t,expiresAt:n+1e4}))}catch{s=!0;break}if(await y(20+40*Math.random()),b()?.ownerNonce===t){c=t;try{return await x(e)}finally{c=null,v(t)}}else await C(500)}}return x(e)})(e):x(e)},matches:(n,o,a)=>n===e&&o===t&&a===r,destroy(){i=!0,p.clear(),typeof window<"u"&&window.removeEventListener("storage",g),c&&v(c);for(let e of[...w])e()}}})(e,we(),!1===n.persistState),Bd=Ld(),Nd=Bd?Pd(Bd):null,Rd={...Nd?{visitorStore:Nd}:{},historyBootstrapReady:!0!==n.features?.history?.enabled||Ec()?D:Promise.all([D,z]).then(()=>{}),getStoredMessageCursor:()=>Td("historyMessageCursor"),setStoredMessageCursor:e=>{null!==e?U(t=>({...t,historyMessageCursor:e})):Id("historyMessageCursor")},getPendingDisplayProjections:()=>{let e=$.pendingDisplayProjections;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.conversationId&&Array.isArray(t.messageIds)?{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>"string"==typeof e)}:null},setPendingDisplayProjections:e=>{e?U(t=>({...t,pendingDisplayProjections:e})):Id("pendingDisplayProjections")},getStoredResumableHandle:Ed,setStoredResumableHandle:e=>{e?U(t=>({...t,durableResume:e})):Id("durableResume")},shouldResumeDurableConversation:()=>H&&null!==Ed(),...Md?{}:{getStoredConversationRevision:()=>Td("conversationRevision"),setStoredConversationRevision:e=>{null!==e?U(t=>({...t,conversationRevision:e})):Id("conversationRevision")}}};if(H){let t=n.onExecutionState,r=e.ownerDocument.defaultView,o=!1,a=()=>o=!0,s=()=>o=!1;r?.addEventListener("pagehide",a),r?.addEventListener("pageshow",s),Zo.push(()=>{r?.removeEventListener("pagehide",a),r?.removeEventListener("pageshow",s)}),n={...n,reconnectStream:n.reconnectStream??(e=>ha.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!o)&&Rd.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Hd=null,$d=(e,t)=>{if(Object.is(e,t))return!0;if(null===e||null===t||"object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)&&e.every((e,r)=>$d(e,t[r]));let r=e,n=t,o=Object.keys(r),a=Object.keys(n);return o.length===a.length&&o.every(e=>Object.prototype.hasOwnProperty.call(n,e)&&$d(r[e],n[e]))},Wd=e=>{let{content:t,rawContent:r,llmContent:n,...o}=e;return o},Dd=e=>!("assistant"!==e.role||!0!==e.streaming||e.variant||e.toolCall||e.tools||e.approval||e.reasoning||e.contentParts||e.stopReason||Wc(e)),Od=null,Fd=null,zd=null,qd=null,jd=null,_d=e=>{let t,r;Od=e,Fd=null;for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(!t&&"user"===o.role&&(t=o),!r&&"assistant"===o.role&&(r=o),!Fd&&Dd(o)&&(Fd={index:n,id:o.id}),t&&r&&Fd)break}pl(ct,e,ue),yd()?.updateInlineArtifactBlocks(ct,Kn.artifacts,{suppressTransition:za}),null==Hd&&(Hd=setInterval(()=>{let e=ct.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Hd),void(Hd=null);let t=Date.now();e.forEach(e=>{let r=Number(e.getAttribute("data-tool-elapsed"));r&&(e.textContent=e.closest(".persona-activity-row")?Be(t-r):Pr(t-r))})},100)),cd(e),Oa(e),Wi(!za),(e=>{let t=new Map;e.forEach(e=>{let r=vs.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(N.emit("assistant:message",e),!is&&("anchor-top"!==Vt()||Gt())&&Ei()&&(ns+=1,ki(),Ni(),lr(1===ns?"1 new message below.":`${ns} new messages below.`))),"assistant"===e.role&&r?.streaming&&!1===e.streaming&&N.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&N.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):N.emit("approval:requested",{approval:e.approval,message:e}))}),vs.clear(),t.forEach((e,t)=>{vs.set(t,e)})})(e),0===e.length&&(Ji(),ds=!0,cs=!1,ps=null,us=!1),!ss||is?(ss=!0,ls=t?.id??null,ms=r?.id??null):t&&t.id!==ls?(ls=t.id,(e=>{let t=Vt();"follow"===t?($i(),Wi(!0)):"anchor-top"===t&&(ds=!1,cs=!0,us=!1,ps=e,el(e))})(t.id)):r&&r.id!==ms&&(()=>{if("anchor-top"===Vt()){if(cs)return void(ds=!1);ds=!0,Ji(),$i(),Wi(!0)}})(),r&&(ms=r.id),(e=>{if("anchor-top"!==Vt()||!cs||us||_i())return;let t=null===ls;for(let r of e)if(t){if(Os(r)){if(r.id===ps||!nl(r.id))return;return ps=r.id,void el(r.id)}}else r.id===ls&&(t=!0)})(e);let n=Bs.lastUserMessageId;t&&t.id!==n&&(Bs.lastUserMessageId=t.id,N.emit("user:message",t)),Bs.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!H)return ei(e);jd=e,queueMicrotask(()=>{jd===e&&(jd=null,ei(e))})})(e),Il()},Vd=()=>{null!==qd&&(cancelAnimationFrame(qd),qd=null);let e=zd;zd=null,e&&_d(e)},Ud=()=>{null!==qd&&cancelAnimationFrame(qd),qd=null,zd=null};ha=new uo(n,{onMessagesChanged(e){(e=>{let t=zd??Od;za&&t&&Fd&&((e,t,r)=>{if(e.length!==t.length)return!1;let n=e[r.index],o=t[r.index];return!(!n||!o||n.id!==r.id||o.id!==r.id)&&(!Object.is(n.content,o.content)||!Object.is(n.rawContent,o.rawContent)||!Object.is(n.llmContent,o.llmContent))&&Dd(n)&&Dd(o)&&$d(Wd(n),Wd(o))})(t,e,Fd)?(zd=e,null===qd&&(qd=requestAnimationFrame(()=>{qd=null;let e=zd;zd=null,e&&_d(e)}))):0===e.length?(Ud(),_d(e)):(Vd(),_d(e))})(e)},onStatusChanged(e){let t=n.statusIndicator??{};var r;rt(bt,"idle"===(r=e)?t.idleText??cn.idle:"connecting"===r?t.connectingText??cn.connecting:"connected"===r?t.connectedText??cn.connected:"error"===r?t.errorText??cn.error:"paused"===r?t.pausedText??cn.paused:"resuming"===r?t.resumingText??cn.resuming:cn[r],t,e),Ze()},onStreamingChanged(e){e||(0===ha?.getMessages().length?Ud():Vd()),za=e,_l(e),Ze(),ha&&pl(ct,ha.getMessages(),ue),e||(Wi(!0),(()=>{if(!os||os.spacerHeight<=0)return;let e=Ki(os.spacerHeight),t=Math.max(0,Math.round(dt.scrollTop)+dt.clientHeight-e+gs);t<os.spacerHeight&&(Ui(t),Ni())})(),Wa=!0,ha&&Da(ha.getMessages(),xr(n))),Ni(),lr(e?"Responding…":"Response complete."),Il()},onVoiceStatusChanged(e){if(N.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"===e||$e(n.voiceRecognition?.provider))switch(e){case"listening":if(!Ts){let e=ha.getVoiceDisclosure();e&&(Ts=!0,se()?(Ps=mt.placeholder,mt.placeholder=e,lr(e)):Qc(e,1e4))}Bp(),Ep();break;case"processing":Bp(),Lp();break;case"speaking":Bp(),Pp();break;default:"idle"===e&&ha.isBargeInActive()?(Bp(),Ep(),Dt?.setAttribute("aria-label","End voice session")):(Bs.active=!1,Ts=!1,null!==Ps&&(mt.placeholder=Ps,Ps=null),Bp(),js("system"),Vs())}},onArtifactsState(e){Kn=e,0===e.artifacts.length&&(Xn=!1),yd()?.updateInlineArtifactBlocks(ct,e.artifacts,{suppressTransition:za}),_o(),ei()},onHistoryStateChanged(e){Xe(e)},onHistoryNotice(e){Qe(e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?N.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?N.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):N.emit("stream:resumed",{executionId:t,after:r})}},Rd),ro.current=ha,Zo.push(()=>ha.cancel()),Zo.push(()=>{ha.destroy(),Nd?.destroy(),Nd=null});let Kd=null;if(ha.onReadAloudChange((e,t)=>{Bn=e,Nn=t,Hn();let r=e??Kd;e&&(Kd=e);let n=r?ha.getMessages().find(e=>e.id===r)??null:null;N.emit("message:read-aloud",{messageId:r,message:n,state:t,timestamp:Date.now()}),"idle"===t&&(Kd=null)}),m=!0,ss=!0,!0===n.voiceRecognition?.enabled&&$e(n.voiceRecognition.provider))try{ha.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let Jd=null,Gd=null,Qd=!1,Zd=ha.getHistoryState(),ec=()=>!0===n.features?.history?.enabled,tc=e=>{e&&(ar.textContent="",ar.textContent=e)},rc=()=>{u.forEach(e=>e()),u=[];let t=Jd,r=t?.railCollapseShortcut();t&&r&&u.push(p.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===n.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>Ue&&"rail"===Ke&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of n.layout?.header?.trailingActions??[])t.shortcut&&u.push(p.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():n.layout?.header?.onAction?.(t.id)}}));for(let e of c)for(let t of e.shortcuts??[])u.push(p.register({...t,id:`${e.id}:${t.id}`}))};rc();let sc=null,ic=!1,lc=()=>{if(!Et)return;let e="conversation"===n.layout?.header?.titleSource,t=e&&sc?.trim()||null;Et.textContent=t??n.launcher?.title??"Chat Assistant";let r=Et.closest(".persona-combo-btn");if(!r)return;let o=!e||null!==ha.getActiveConversationId();r.setAttribute("data-persona-menu-locked",o?"false":"true"),r.setAttribute("aria-haspopup",o?"true":"false"),o||r.setAttribute("aria-expanded","false"),r.style.cursor=o?"pointer":"default";let a=r.querySelector("svg");a&&(a.style.display=o?"":"none")};lc(),lt.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=ha.getActiveConversationId();r&&("delete"===t?fc(e=>e.requestDeleteConversation(r)):"star"===t&&ha.canUpdateConversations()&&fc(e=>e.updateHistoryConversation(r,{starred:!ic})).catch(()=>{}))}),Xe=e=>{Zd=e,Jd?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),_l(e.sendBlocked||za),Jd?.syncEarlierMessagesPill()},Qe=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(qa.clear(),Ji(),$i()),tc(e.message),Jd?.historySurface?.view.refresh()};let pc={get actionManager(){return G},get activeConversationTitle(){return sc},announceHistory:tc,get applyRailChrome(){return Ge},set applyRailChrome(e){Ge=e},get artifactSplitRoot(){return ho},get body(){return dt},get config(){return n},get container(){return lt},get conversationOpenPendingEl(){return Ul},set conversationOpenPendingEl(e){Ul=e},get conversationOpenTakeover(){return Gl},set conversationOpenTakeover(e){Gl=e},currentKeyPrefix:we,destroyCallbacks:Zo,eventBus:N,get footer(){return Bt},get header(){return Pt},get historyChromeSync(){return Ze},set historyChromeSync(e){Ze=e},historyFeatureEnabled:ec,get historyInternals(){return Rd},set historyInternals(e){Rd=e},get historyPresentation(){return Ke},set historyPresentation(e){Ke=e},get historySessionState(){return Zd},get historyVisible(){return Ue},set historyVisible(e){Ue=e},get isStreaming(){return za},jumpToBottomInstant:qi,get lastAppliedMessages(){return Od},set lastAppliedMessages(e){Od=e},get launcherEnabled(){return Y},get launcherSurfaceInstance(){return Kp},maybeFocusInput:Vl,messageCache:qa,get messagesWrapper(){return ct},mount:e,get open(){return le},panel:at,panelElements:it,get persistentMetadata(){return $},set persistentMetadata(e){$=e},plugins:c,get reapplyHistoryHostChrome(){return Je},set reapplyHistoryHostChrome(e){Je=e},repinAnchoredMessage:rl,resetAnchorState:Ji,restoreScrollPosition:Vi,resumeAutoScroll:$i,runStorageMutation:Zs,get session(){return ha},setActiveConversationSummary:e=>{ic=!0===e?.starred,(e=>{e!==sc&&(sc=e,lc())})(e&&e.title.trim()||null),lc()},storageAdapter:R,get suppressScrollSend(){return is},set suppressScrollSend(e){is=e},syncScrollToBottomButton:Ni,updateWelcome:cd,getHistoryProviderFactory:Lc,historyErrors:{HistoryClientError:hn,HistoryProviderError:wn},isDockedMountMode:vi,renderLucideIcon:xe,loadHistoryView:Cc,createHeaderIconButton:Bi,attachTooltip:Bo},hc=e=>(!Jd&&!Qd&&(Jd=e.createHistoryShell(pc),Jd.railCollapseShortcut()&&rc()),Jd),gc=()=>{if(Jd)return Promise.resolve(Jd);let e=Ec();return e?Promise.resolve(hc(e)):(Gd??=Tc().then(hc,e=>{throw Gd=null,e}),Gd)},fc=e=>{let t=Ec(),r=Jd??(t?hc(t):null);return r?e(r):gc().then(t=>{if(!t)throw new Error("[AgentWidget] The widget was destroyed");return e(t)})},vc=()=>{Jd?.syncHistoryPresentation()};Zo.push(()=>{Qd=!0}),ec()&&gc().catch(()=>{}).finally(O),n.clientToken&&(!0===n.features?.history?.enabled||"mount"===n.sessionInit)&&ha.initClientSession().then(()=>{let e=Jd;if(e?.historyAvailable())return ha.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Jd?.syncEarlierMessagesPill()}).catch(e=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let wc=()=>ha.warmClientSession(),xc=e=>{let t=n.sessionInit??"input",r=an?.input??mt,o=e.target;r&&("input"===e.type?("input"===t||"focus"===t)&&o===r&&e.inputType&&r.value.trim():"focus"===t&&("keyup"===e.type?o===r&&"Tab"===e.key:(an?.form??yt)?.contains(o)))&&wc()},Sc=["input","pointerdown","keyup"];Sc.forEach(t=>e.addEventListener(t,xc));let kc,Ac,Mc=()=>{let e=Ac;Ac=void 0;try{"function"==typeof e&&e()}catch{}},Ic=()=>{let t=n.clientToken&&"function"==typeof n.sessionInit?n.sessionInit:void 0;if(t!==kc){Mc(),kc=t;try{Ac=t?.({warm:wc,mount:e})}catch{}}};Ic(),Zo.push(()=>{Sc.forEach(t=>e.removeEventListener(t,xc)),Mc()}),(ye||n.onSSEEvent)&&ha.setSSEEventCallback((e,t)=>{n.onSSEEvent?.(e,t),ze(e,t)});let Pc=()=>{let e=n.resume??(H?Rd.getStoredResumableHandle?.():null);e&&"function"==typeof n.reconnectStream&&ha.resumeFromHandle(e)};W?W.then(e=>{if(e){if(e.metadata&&($=Uc(e.metadata),G.syncFromMetadata()),e.messages?.length){is=!0;try{ha.hydrateMessages(e.messages)}finally{is=!1}dl()}e.artifacts?.length&&ha.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),pi(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{Ql=!0,P(),Pc()}):(pi(B),Pc());let Bc=()=>{let e=mt.getInlineMessageFields?.();return e&&e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},Nc=!1,Hc=null,$c=()=>{mt.value="",mt.style.height="auto",Mr(),ip()},Oc="data-persona-composer-notice",Xc=null;function Qc(e,t=4e3){lr(e),!se()&&bt&&(bt.hasAttribute(jc)||(bt.setAttribute(Oc,""),bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.textContent=e,Re(bt,n.statusIndicator??{},"idle"),Xc&&clearTimeout(Xc),Xc=setTimeout(()=>{if(Xc=null,bt?.hasAttribute(Oc)&&(bt.removeAttribute(Oc),bt.removeAttribute("role"),bt.removeAttribute("aria-live"),m)){let e=ha.getStatus();rt(bt,tt(e),n.statusIndicator??{},e)}},t)))}let Zc=(e={})=>{let t=(e.overrideText??mt?.value??"").trim();return e.resolveInlineCommand&&t?(kr?.takeInlineCommand(t)??Promise.resolve(null)).then(r=>ep(e,t,r)):ep(e,t,null)},ep=(e,t,r)=>{if("action"===r?.kind)return $c(),kr?.clear(),void Ir();let o="server"===r?.kind?r.mentions:null,a="prompt"===r?.kind?r.sendText:t,s=e.pending?.contentParts;if(!function(e){return!(!0===e.inputDisabled||!0===e.sendDisabled||e.hasAttachments&&!e.attachmentsReady)&&(!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions)}({text:a,hasAttachments:(Sr?.hasAttachments()??!1)||(s?.length??0)>0,attachmentsReady:Sr?.isReady()??!0,hasMentions:kr?.hasMentions()??!1,hasServerMentions:!!o,inputDisabled:Nl(),sendDisabled:Hl()}))return;let i=ha.isStreaming()?jr():"block";if("defer-one"===i&&!e.pending)return Ar.getState().pendingSubmission?void Qc("One message is already queued. Edit or remove it first."):void function(e){let t=Ar.getState(),r=Sr?.hasAttachments()??!1,n=r?[...Sr.getContentParts()]:[];r&&e.sendText&&n.push(Zr(e.sendText)),Vr(ka({text:e.sendText,contentParts:n.length?n:void 0,mentionRefs:[...kr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:Bc(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),!1!==e.intent.consumeDraft&&$c(),r&&Sr.clearAttachments(),kr?.clear(),Ir(),t.quote&&zr(void 0),ui(),Sn.release(),An(),lr("Message queued. It sends when the response finishes.")}({intent:e,sendText:a,serverMentions:o});let l={text:a,mentionRefs:[...kr?.getMentionRefs()??[],...o?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:Bc(),options:{...Ar.getState().selectedModelId&&{selectedModelId:Ar.getState().selectedModelId},...Ar.getState().activeModeIds.length>0&&{activeModeIds:[...Ar.getState().activeModeIds]},...Ar.getState().quote&&{quote:{...Ar.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(l.options={...e.pending.options},l.contentSegments=e.pending.contentSegments,l.mentionRefs=[...e.pending.mentionRefs],l.viaVoice=e.pending.viaVoice);let d=()=>{if(s?.length)return[...s];if(!Sr?.hasAttachments())return;let e=[...Sr.getContentParts()];return l.text&&e.push(Zr(l.text)),e};l.contentParts=d();let c=()=>{Ja(),!se()||le||!(n.launcher?.composerBar?.expandOnSubmit??1)||Pl(!0,"auto");let t=kr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,n]=await Promise.allSettled([e.finalize(),t.finalize()]),o=[];return"fulfilled"===r.status?o.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===n.status?o.push(n.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",n.reason),(e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Yc(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}))(o)}}:e:t)(t,o),a=d();!1!==e.consumeDraft&&$c();let s={selectedModelId:l.options.selectedModelId,activeModeIds:l.options.activeModeIds},c="interrupt"===i;c&&ha.cancel(),ha.sendMessage(l.text,{contentParts:a,mentions:r??void 0,contentSegments:l.contentSegments,viaVoice:l.viaVoice,composerOptions:s,...l.options.quote&&{quote:l.options.quote},...c&&{interrupt:!0}}),Sr?.hasAttachments()&&Sr.clearAttachments(),t&&kr?.clear(),Ir();let p=Ar.getState().activeModeIds,u=function(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&"once"!==(t.persistence??"sticky")).map(e=>e.id):[]}(p,n.composer?.modes);u.length!==p.length&&Rr(u),Ar.getState().quote&&zr(void 0),ui(),Sn.release(),An()},p=n.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;Hc=u;let h=e=>{Hc=null,"error"!==e.status?"proceed"===e.status&&c():(e=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",e)})(e.error)},m=function(e,t,r){let n;try{n=e(ka(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(n)?Promise.resolve(n).then(e=>r.aborted?{status:"aborted"}:Aa(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Aa(t,n)}(p,l,u.signal);if(m instanceof Promise)return Ar.setPreparing(!0),m.then(h).finally(()=>Ar.setPreparing(!1));h(m)};$n={regenerate:function(e){if(ha.isStreaming())return;let t=qn(ha.getMessages(),e);t&&(Ja(),ha.resubmitFrom(t,{reason:"retry"})&&rl())},edit:function(e){if(!0!==n.messageActions?.showEdit)return;let t=ha.getMessages().find(t=>t.id===e);!t||!jn(t)||Ua!==e&&(Ja(),Ua=e,Ka=function(e){let t=oe("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=oe("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});r.value=e.initialText;let n=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",n);let o=ne("div","persona-message-edit-actions"),a=(e,t,r,n)=>{let o=oe("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return o.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",s)),r.addEventListener("keydown",t=>{if("Escape"===t.key)return t.preventDefault(),t.stopPropagation(),void e.onCancel();"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,o),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=Ka;Ua=null,Ka=null,r?.destroy(),qa.delete(e),ha.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?rl():pl(ct,ha.getMessages(),ue)}(e,t),onCancel:()=>Ja()}),qa.delete(e),pl(ct,ha.getMessages(),ue),Ka.focus())},quote:e=>{let t=ha.getMessages().find(t=>t.id===e)?.content?.trim();t&&(zr({text:t,messageId:e}),mt?.focus())}};let tp=async e=>{if(!Nc){Nc=!0;try{await Zc({resolveInlineCommand:!0,...e})}finally{Nc=!1}}};function rp(e){Hl()||($c(),np(e,{consumeDraft:!1}))}let np=(e,t)=>{if(Nc)return;Nc=!0;let r=()=>{Nc=!1};try{let n=Zc({...t,overrideText:e});n instanceof Promise?n.finally(r):r()}catch(e){throw r(),e}},op=e=>{if(e.preventDefault(),ha.isStreaming())return ha.cancel(),Ie?.reset(),void Le?.update();Nc||tp()},ap={...Ds},sp=!1,ip=()=>{ap={...Ds}},lp=e=>{if("Escape"===e.key&&!e.isComposing&&e.composedPath().includes(lt)){if(Hc)return Hc.abort(),Hc=null,e.preventDefault(),void e.stopImmediatePropagation();ha.isStreaming()&&(ha.cancel(),Ie?.reset(),Le?.update(),ip(),e.preventDefault(),e.stopImmediatePropagation())}},dp=null,cp=!1,pp=null,up=null,hp=()=>"review"===n.voiceRecognition?.completionBehavior;function mp(e){Dt?.setAttribute("data-state",e),"recording"===e?function(){if(null!==yp)return;if("function"!=typeof requestAnimationFrame)return void xp(m?ha.getVoiceLevel()??fp:fp);let e=()=>{yp=requestAnimationFrame(e);let t=m?ha.getVoiceLevel():null;null!==t?(vp+=.3*(t-vp),xp(vp)):xp(fp)};yp=requestAnimationFrame(e)}():Sp()}let gp="--persona-voice-level",fp=.5,yp=null,bp=-1,vp=0,wp=()=>{let e=[],t=Ot??Dt?.parentElement??null;return t&&e.push(t),Bt&&e.push(Bt),e},xp=e=>{let t=Math.round(100*Math.max(0,Math.min(1,e)))/100;if(t!==bp){bp=t;for(let e of wp())e.style.setProperty(gp,String(t))}},Cp=()=>{bp=-1,vp=0;for(let e of wp())e.style.removeProperty(gp)};function Sp(){null!==yp&&(cancelAnimationFrame(yp),yp=null),Cp()}let kp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ap=(e="user")=>{if(cp||ha.isStreaming())return;let t=kp();if(!t)return;dp=new t;let r=n.voiceRecognition??{},o=r.pauseDuration??2e3;dp.continuous=r.provider?.browser?.continuous??!0,dp.interimResults=!0,dp.lang=r.provider?.browser?.language??"en-US";let a=mt.value;dp.onresult=e=>{let t="",r="";for(let n=0;n<e.results.length;n++){let o=e.results[n],a=o[0].transcript;o.isFinal?t+=a+" ":r=a}let n=a+t+r;mt.value=n,Mr(),pp&&clearTimeout(pp),(t||r)&&(pp=window.setTimeout(()=>{if(mt.value.trim()&&dp&&cp){if(Mp(),hp())return;tp({viaVoice:!0})}},o))},dp.onerror=e=>{"no-speech"!==e.error&&Mp()},dp.onend=()=>{if(cp){let e=mt.value.trim();!hp()&&e&&e!==a.trim()&&tp({viaVoice:!0}),Mp()}};try{if(dp.start(),cp=!0,Bs.active=!0,"system"!==e&&(Bs.manuallyDeactivated=!1),js(e),Vs(),An(),Dt){let e=n.voiceRecognition??{};up={backgroundColor:Dt.style.backgroundColor,color:Dt.style.color,borderColor:Dt.style.borderColor,iconName:e.iconName??"mic",iconSize:parseFloat(e.iconSize??"")||qo};let t=e.recordingBackgroundColor,r=e.recordingIconColor,o=e.recordingBorderColor;if(Dt.classList.add("persona-voice-recording"),mp("recording"),Dt.style.backgroundColor=t??"var(--persona-voice-recording-bg, #ef4444)",Dt.style.color=r??"var(--persona-voice-recording-indicator, #ffffff)",r){let e=Dt.querySelector("svg");e&&e.setAttribute("stroke",r)}o&&(Dt.style.borderColor=o),Dt.setAttribute("aria-label","Stop voice recognition")}}catch{Mp("system")}},Mp=(e="user")=>{if(cp){if(cp=!1,pp&&(clearTimeout(pp),pp=null),dp){try{dp.stop()}catch{}dp=null}if(Bs.active=!1,js(e),Vs(),An(),Dt){if(Dt.classList.remove("persona-voice-recording"),mp("idle"),up){Dt.style.backgroundColor=up.backgroundColor,Dt.style.color=up.color,Dt.style.borderColor=up.borderColor;let e=Dt.querySelector("svg");e&&e.setAttribute("stroke",up.color||"currentColor"),up=null}Dt.setAttribute("aria-label","Start voice recognition")}}},Ip=null,Tp=e=>{let t=t=>{Ip??=t.createMicStateStyles({mic:()=>Dt,config:()=>n,session:()=>ha,get original(){return up},set original(e){up=e},setMicState:mp,renderIcon:xe,iconFallbackPx:qo}),e(Ip)},r=Zn();r?t(r):Qn().then(t,()=>{})},Ep=()=>Tp(e=>e.recording()),Lp=()=>Tp(e=>e.processing()),Pp=()=>Tp(e=>e.speaking()),Bp=()=>Tp(e=>e.reset()),Np=()=>{if(!Nl()){if($e(n.voiceRecognition?.provider)){let e=ha.getVoiceStatus(),t=ha.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;return"cancel"!==t||"processing"!==e&&"speaking"!==e?ha.isBargeInActive()?(ha.stopVoicePlayback(),void ha.deactivateBargeIn().then(()=>{Bs.active=!1,Bs.manuallyDeactivated=!0,Vs(),js("user"),Bp()})):void ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),Bs.manuallyDeactivated=!ha.isVoiceActive(),Vs(),js("user"),ha.isVoiceActive()?Ep():Bp()}):void ha.stopVoicePlayback()}if(cp){let e=mt.value.trim();Bs.manuallyDeactivated=!0,Vs(),Mp("user"),e&&!hp()&&tp()}else Bs.manuallyDeactivated=!1,Vs(),Ap("user")}};Kr=Np;let Rp=()=>ha.prewarmVoice(),Hp=()=>{let e=n.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!n.clientToken&&"hover"))},$p=e=>{"hover"===Hp()&&Dt?.contains(e.target)&&Rp()},Wp=["pointerover","pointerdown","focusin"];Wp.forEach(t=>e.addEventListener(t,$p));let Dp,Op,Fp=null,zp=()=>{let e=Op;Op=void 0;try{"function"==typeof e&&e()}catch{}},qp=()=>{let t=Hp(),r="function"==typeof t&&Dt?t:void 0,n=r?Dt:null;if((r!==Dp||n!==Fp)&&(zp(),Dp=r,Fp=n,r&&n))try{Op=r({warm:Rp,micButton:n,mount:e})}catch{}};qp(),Zo.push(()=>{Wp.forEach(t=>e.removeEventListener(t,$p)),zp()}),Dt&&Zo.push(()=>{$e(n.voiceRecognition?.provider)?(ha.isVoiceActive()&&ha.toggleVoice(),Bp()):Mp("system")});let jp=N.on("assistant:complete",()=>{Ar.getState().pendingSubmission&&setTimeout(()=>{ha.isStreaming()||function(){let e=Ar.getState().pendingSubmission;e&&(Vr(void 0),np(e.text,{consumeDraft:!1,pending:e}))}()},0)});Zo.push(jp);let _p=N.on("assistant:complete",()=>{$s&&(Bs.active||Bs.manuallyDeactivated||"assistant"===$s&&!Bs.lastUserMessageWasVoice||setTimeout(()=>{!Bs.active&&!Bs.manuallyDeactivated&&($e(n.voiceRecognition?.provider)?ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),js("auto"),ha.isVoiceActive()&&Ep()}):Ap("auto"))},600))});Zo.push(_p);let Vp=N.on("action:resubmit",()=>{setTimeout(()=>{ha&&!ha.isStreaming()&&ha.continueConversation()},100)});Zo.push(Vp);let Up=()=>{Pl(!le,"user")},Kp=null,Jp=null;if(Y&&!se()){let{instance:e,element:t}=Wl({config:n,plugins:c,onToggle:Up});Kp=e,e||(Jp=t)}Kp?e.appendChild(Kp.element):Jp&&e.appendChild(Jp),Ll(),Oa(),Cd(),xd(),_l(ha.isStreaming()),Vi()||("follow"===Vt()?Wi(!0):qi()),(()=>{if(!1===n.voiceRecognition?.enabled)return;let e=Uc($.voiceState),t=!!e.active,r=Number(e.timestamp??0);Bs.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4&&setTimeout(()=>{Bs.active||(Bs.manuallyDeactivated=!1,$e(n.voiceRecognition?.provider)?ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),js("restore"),ha.isVoiceActive()&&Ep()}):Ap("restore"))},1e3)})(),Q&&(!Y||se()?setTimeout(()=>Vl(),0):le&&setTimeout(()=>Vl(),200));let Gp=null,Yp=()=>{Gp&&(Gp.disconnect(),Gp.observe(Bt),Gp.observe(lt),Gp.observe(vt))},Xp=dr(),Qp=()=>{if(se())return fr(),void Ll();let t=vi(n),r=n.launcher?.sidebarMode??!1,o=e.ownerDocument.defaultView??window,a=n.launcher?.mobileFullscreen??!0,s=n.launcher?.mobileBreakpoint??640,i=o.innerWidth<=s,l=a&&i&&Y;try{if(l)return _n(),void(Vn=jo());let e=!1;ae&&(ae=!1,_n(),e=!0);let o=jo();if(!e&&o!==Vn&&(_n(),e=!0),Vn=o,e&&xo(),!Y&&!t)return at.style.height="",void(at.style.width="");if(!r&&!t){let e=Ml(n);at.style.width=e.width,at.style.maxWidth=e.maxWidth}Lo(),Qo()}finally{fr(),wr();let t=dr();if(t!==Xp&&(Xp=t,cd(),Oa()),Ll(),le&&Y){let t=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),r=n.launcher?.sidebarMode??!1,o=n.launcher?.mobileFullscreen??!0,a=vi(n)&&o&&t,s=r||o&&t&&Y||a;if(s&&!ta){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!ea&&(ea=gi(r,n.launcher?.zIndex??pn)),ta=bi(e.ownerDocument)}else s||(ea?.(),ea=null,ta?.(),ta=null)}}};Qp();let Zp=e.ownerDocument.defaultView??window;if(Zp.addEventListener("resize",Qp),Zo.push(()=>Zp.removeEventListener("resize",Qp)),typeof ResizeObserver<"u"){Gp=new ResizeObserver(()=>{wr()}),Yp(),Zo.push(()=>{Gp?.disconnect(),Gp=null});let e=new ResizeObserver(()=>{vc()});e.observe(lt),Zo.push(()=>e.disconnect())}Zp.addEventListener("resize",vc),Zo.push(()=>Zp.removeEventListener("resize",vc)),Qa=dt.scrollTop;let eu=Fs(dt),tu=()=>{Yo();let e=dt.scrollTop,t=Fs(dt),r=t<eu;if(eu=t,!Ut())return Qa=e,void Ni();let{action:n,nextLastScrollTop:o}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-n;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&o&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!o?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Xa.isFollowing(),currentScrollTop:e,lastScrollTop:Qa,nearBottom:zs(dt,gs),userScrollThreshold:4,isAutoScrolling:ts||rs||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Qa=o,"resume"!==n?"pause"===n&&Ri():_i()||$i()};if(dt.addEventListener("scroll",tu,{passive:!0}),Zo.push(()=>dt.removeEventListener("scroll",tu)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(Ut()){if(!Xa.isFollowing()||zs(dt,1))return;Wi(!za)}else{if(os&&os.initialSpacerHeight>0){let e=dt.scrollHeight-os.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:os.initialSpacerHeight,contentHeightAtAnchor:os.contentHeightAtAnchor,currentContentHeight:e});t!==os.spacerHeight&&Ui(t)}Ni()}})(),gt(ct)});e.observe(ct),e.observe(dt),Zo.push(()=>e.disconnect())}let ru=()=>{Ut()&&Xa.isFollowing()&&_i()&&Ri()},nu=dt.ownerDocument;nu.addEventListener("selectionchange",ru),Zo.push(()=>{nu.removeEventListener("selectionchange",ru)});let ou=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),au=e=>{ou.has(e.key)&&(hs(),Jt()&&Ut()&&Xa.isFollowing()&&Ri())},su=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(hs(),Jt()&&Ut()&&Xa.isFollowing()&&Ri())};dt.addEventListener("keydown",au),dt.addEventListener("focusin",su),Zo.push(()=>{dt.removeEventListener("keydown",au),dt.removeEventListener("focusin",su)});let iu=e=>{if(0!==e.deltaY&&hs(),!Ut())return;let t=function(e){let{following:t,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return t&&r<0?"pause":!t&&o&&r>0&&n?"resume":"none"}({following:Xa.isFollowing(),deltaY:e.deltaY,nearBottom:zs(dt,gs),resumeWhenNearBottom:!0});"pause"===t?Ri():"resume"===t&&!_i()&&$i()};dt.addEventListener("wheel",iu,{passive:!0}),dt.addEventListener("touchmove",hs,{passive:!0}),dt.addEventListener("pointerdown",hs,{passive:!0}),Zo.push(()=>{dt.removeEventListener("touchmove",hs),dt.removeEventListener("pointerdown",hs)}),Zo.push(()=>dt.removeEventListener("wheel",iu)),Zt.addEventListener("click",()=>{Ji(),dt.scrollTop=dt.scrollHeight,Qa=dt.scrollTop,$i(),Wi(!0),Ni()}),Zo.push(()=>Zt.remove()),Zo.push(()=>{Ci(),Ji()});let lu=()=>{It&&(ma&&(It.removeEventListener("click",ma),ma=null),ie()?(It.style.display="",ma=()=>{Pl(!1,"user")},It.addEventListener("click",ma)):It.style.display="none")};lu(),(()=>{let{clearChatButton:e}=it;e&&e.addEventListener("click",()=>{let e=Jd;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",e)});ha.clearMessages(),n.layout?.topFade&&(dt.scrollTop=0),dt.removeAttribute("data-persona-top-fade"),qa.clear(),$i(),hr(it.composerOverlay);try{localStorage.removeItem(qc),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==qc)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let t=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(t),R?.clear&&Zs(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),$={},G.syncFromMetadata(),Sr?.clearAttachments(),ui(),Vr(void 0),zr(void 0),Ja(),Ae?.clear(),Ie?.reset(),Le?.update()})})();let du=[["keydown",e=>{if(mt&&!Nl()&&(e.isComposing||!kr?.handleKeydown(e))){if(!(!1===n.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===mt.selectionStart&&0===mt.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:n,atStart:o,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!o)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:n}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let e=a.index+1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}({direction:"ArrowUp"===e.key?"up":"down",history:ha.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:mt.value,atStart:t,state:ap});if(ap=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!mt)return;sp=!0,mt.value=e,mt.dispatchEvent(new Event("input",{bubbles:!0})),sp=!1;let t=mt.value.length;mt.setSelectionRange(t,t)})(r.value))}if(function(e,t){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,n=t.submitKey??"enter";return"none"!==n&&("mod-enter"===n?r:r||!$o(t))}(e,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Ho(mt)})){if(ha.isStreaming()){if(e.preventDefault(),"block"===jr()||Nc||Hl())return;return ip(),void tp()}if(Nc)return void e.preventDefault();if(Hl())return void e.preventDefault();ip(),e.preventDefault(),ft.click()}}}],["input",e=>{sp||(e.isComposing||kr?.handleInput(e.inputType??void 0),ip())}],["input",Mr],["input",Ir],["keyup",Ir],["paste",async e=>{if(!0!==n.attachments?.enabled||!Sr||Nl())return;let t=function(e){if(!e)return[];let t=[],r=Array.from(e.items??[]);for(let e of r){if("file"!==e.kind||!e.type.startsWith("image/"))continue;let r=e.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let n=_c[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${n}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let r of Array.from(e.files??[]))r.type.startsWith("image/")&&t.push(r);return t}(e.clipboardData);0!==t.length&&(e.preventDefault(),await Sr.handleFiles(t))}],["focus",()=>kr?.prefetch()]],cu=e=>{if(e)for(let[t,r]of du)an?.addListener(e,t,r)},pu=()=>{an&&(an.addListener(an.form,"submit",op),an.addListener(an.footer,"click",Ir),cu(mt),Dt&&an.addListener(Dt,"click",Np),qp())};pu();let uu=()=>{kr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of du)an?.removeListener(e,t,r)})(t),mt=e,an&&(an.input=e),cu(e),sn(),ql(),Mr()})};uu();let hu=!1;function mu(){if(!hu){hu=!0;try{let e=mt?.value??"",t=Bt.ownerDocument??document,r=!!mt&&t.activeElement===mt;Sp(),an?.destroy(),an=null,kr?.destroy(),kr=null;let o=null,a=()=>(o=se()?Qi({config:n}):Xi({config:n}),o.footer),s=rn(a)??a();nt.replaceComposer(s),Bt=nt.composer.footer;let i=null!==o&&s===o.footer;tn=!i,Wt=i?o.setSendButtonMode:()=>{},en(Bt),ln(Bt),un(),mn(),gn(),uu(),vn(),xn(),Cn(),pu();let l=pa.indexOf(la);if(la.destroy(),la=Mi(ht),l>=0&&(pa[l]=la),mt&&(mt.value=e),Mr(),Ir(),Cd(),Oa(),_l(ha.isStreaming()),"transient"===n.statusIndicator?.mode&&!se()){let e=ha.getStatus();rt(bt,tt(e),n.statusIndicator,e)}Bs.active&&mp("recording"),_n(),Yp(),fr(),An(),zl(),r&&mt?.focus()}finally{hu=!1}}}let gu=e.ownerDocument??document;gu.addEventListener("keydown",lp,!0);let fu=()=>{li()},yu=()=>{"hidden"===gu.visibilityState&&li()};typeof window<"u"&&(window.addEventListener("pagehide",fu),gu.addEventListener("visibilitychange",yu),Zo.push(()=>{window.removeEventListener("pagehide",fu),gu.removeEventListener("visibilitychange",yu)}));let bu="persona-attachment-drop-active",vu=0,wu=()=>{vu=0,lt.classList.remove(bu)},xu=()=>!0===n.attachments?.enabled&&null!==Sr&&!Nl(),Cu=e=>{!Vc(e.dataTransfer)||!xu()||(vu++,1===vu&<.classList.add(bu))},Su=e=>{!Vc(e.dataTransfer)||!xu()||(vu--,vu<=0&&wu())},ku=e=>{!Vc(e.dataTransfer)||!xu()||(e.preventDefault(),e.dataTransfer.dropEffect="copy")},Au=e=>{if(!Vc(e.dataTransfer)||!xu())return;e.preventDefault(),e.stopPropagation(),wu();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&Sr.handleFiles(t)},Mu=!0;lt.addEventListener("dragenter",Cu,Mu),lt.addEventListener("dragleave",Su,Mu),e.addEventListener("dragover",ku,Mu),e.addEventListener("drop",Au,Mu);let Iu=e.ownerDocument,Tu=e=>{xu()&&e.preventDefault()},Eu=e=>{xu()&&e.preventDefault()};Iu.addEventListener("dragover",Tu),Iu.addEventListener("drop",Eu),Zo.push(()=>{an?.destroy(),an=null,Sp(),fn?.destroy(),fn=null,Dr?.destroy(),Dr=null,Fr?.destroy(),Fr=null,_r?.destroy(),_r=null,$r=null,Wr=null,li(),ni.destroy(),Xc&&clearTimeout(Xc),Ja(),Hc?.abort(),Hc=null,Sr?.destroy(),Sr=null,Ar.destroy(),gu.removeEventListener("keydown",lp,!0),kr?.destroy()}),Zo.push(()=>{lt.removeEventListener("dragenter",Cu,Mu),lt.removeEventListener("dragleave",Su,Mu),e.removeEventListener("dragover",ku,Mu),e.removeEventListener("drop",Au,Mu),Iu.removeEventListener("dragover",Tu),Iu.removeEventListener("drop",Eu),wu()}),Zo.push(()=>{ha.cancel()}),Kp?Zo.push(()=>{Kp?.destroy()}):Jp&&Zo.push(()=>{Jp?.remove()});let Lu={update(t){let r=!0===n.future?.v5Defaults,o=n.toolCall,a=n.messageActions,s=n.layout?.messages,i=n.colorScheme,p=n.loadingIndicator,u=n.iterationDisplay,m=n.features?.showReasoning,g=n.features?.showToolCalls,f=n.features?.toolCallDisplay,y=n.features?.reasoningDisplay,b=n.features?.streamAnimation?.type,v=!0===n.features?.history?.enabled,w=n.features?.history?.provider,x=n.getIdentityProof,C=n.clientToken,S=n.contextMentions;n=dc({...n,features:d},t),d=n.features,n=Yd(n),l(),Uo(),Cs(e,n),kd(e,n),Ad(e,n),Ge(),_o(),n.colorScheme!==i&&oa();let k=ac.getForInstance(n.plugins);c.length=0,c.push(...k),rc(),Y=n.launcher?.enabled??!0,X=n.launcher?.autoExpand??!1,he=n.features?.showReasoning??!0,me=n.features?.showToolCalls??!0,be=n.features?.scrollToBottom??{};let A=Vt();ve=n.features?.scrollBehavior??{},A!==Vt()&&(Ji(),$i()),ys(),Cr(),Ni();let M=ye;if(ye=n.features?.showEventStreamToggle??!1,ye&&!M){if(Ae||(qe(),ha.setSSEEventCallback((e,t)=>{n.onSSEEvent?.(e,t),ze(e,t)})),!Qr&&Pt){let e=n.features?.eventStream?.classNames,t="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"+(e?.toggleButton?" "+e.toggleButton:"");Qr=ne("button",t),Qr.style.width="28px",Qr.style.height="28px",Qr.style.color=Hi.actionIconColor,Qr.type="button",Qr.setAttribute("aria-label","Event Stream"),Qr.title="Event Stream";let r=I(h,"18px","currentColor",1.5);r&&Qr.appendChild(r);let o=it.clearChatButtonWrapper,a=it.closeButtonWrapper,s=o||a;s&&s.parentNode===Pt?Pt.insertBefore(Qr,s):Pt.appendChild(Qr),Qr.addEventListener("click",()=>{We?Xr():Yr()})}}else!ye&&M&&(Xr(),Qr&&(Qr.remove(),Qr=null),Ae?.clear(),Se?.destroy(),Ae=null,Se=null,Ie?.reset(),Ie=null,Te=null);if(!1===n.launcher?.enabled&&Kp&&(Kp.destroy(),Kp=null),!1===n.launcher?.enabled&&Jp&&(Jp.remove(),Jp=null),!1!==n.launcher?.enabled&&!Kp&&!Jp){let{instance:t,element:r}=Wl({config:n,plugins:c,onToggle:Up});Kp=t,t||(Jp=r),e.appendChild(r)}Kp&&Kp.update(n),lc(),Lt&&void 0!==n.launcher?.subtitle&&(Lt.textContent=n.launcher.subtitle);let T=n.layout?.header;if(T?.layout!==te&&Pt){let e=T?Yi(n,T,{showClose:ie(),onClose:()=>Pl(!1,"user")}):Di({config:n,showClose:ie(),onClose:()=>Pl(!1,"user")});nt.replaceHeader(e),Pt=nt.header.element,Tt=nt.header.iconHolder,Et=nt.header.headerTitle,Lt=nt.header.headerSubtitle,It=nt.header.closeButton,te=T?.layout,lc()}else if(T){if(Tt&&(Tt.style.display=!1===T.showIcon?"none":""),Et&&(Et.style.display=!1===T.showTitle?"none":""),Lt&&(Lt.style.display=!1===T.showSubtitle?"none":""),It){let e=ie()&&!1!==T.showCloseButton;It.style.display=e?"":"none"}if(it.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){it.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=it;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=!1!==n.layout?.showHeader;Pt&&(Pt.style.display=E?"":"none");let L=!1!==n.layout?.showFooter;Bt&&(Bt.style.display=L?"":"none"),fr(),Ni(),Y!==ee?Y?Pl(X,"auto"):(le=!0,Ll()):X!==Z&&Pl(X,"auto"),Z=X,ee=Y,Qp(),lu();let P=JSON.stringify(n.toolCall)!==JSON.stringify(o),B=JSON.stringify(n.messageActions)!==JSON.stringify(a),R=JSON.stringify(n.layout?.messages)!==JSON.stringify(s),H=n.loadingIndicator?.render!==p?.render||n.loadingIndicator?.renderIdle!==p?.renderIdle||n.loadingIndicator?.showBubble!==p?.showBubble,$=n.iterationDisplay!==u,W=(n.features?.showReasoning??!0)!==(m??!0)||(n.features?.showToolCalls??!0)!==(g??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(f)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(y);(!0===n.future?.v5Defaults!==r||P||B||R||H||$||W)&&ha&&(Ga++,pl(ct,ha.getMessages(),ue));let D=n.features?.streamAnimation?.type;if(D!==b&&D&&"none"!==D){let t=sa(D,n.features?.streamAnimation?.plugins);t&&ci(t,e)}let O=n.launcher??{},F=O.headerIconHidden??!1,z=n.layout?.header?.showIcon,q=F||!1===z,j=O.headerIconName,K=O.headerIconSize??V;if(Tt){let e=Pt,t=e?.querySelector(".persona-flex-col");if(q)Tt.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Tt.style.display="",Tt.style.height=K,Tt.style.width=K,e&&t&&(e.contains(Tt)?Tt.nextSibling!==t&&(Tt.remove(),e.insertBefore(Tt,t)):e.insertBefore(Tt,t)),j){let e=parseFloat(K)||24,t=xe(j,.6*e,"currentColor",1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,Tt.replaceChildren(t)):Tt.textContent=O.agentIconText??"💬"}else if(O.iconUrl){let e=Tt.querySelector("img");if(e)e.src=O.iconUrl,e.style.height=K,e.style.width=K;else{let e=document.createElement("img");e.src=O.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=K,e.style.width=K,Tt.replaceChildren(e)}}else{let e=Tt.querySelector("svg"),t=Tt.querySelector("img");(e||t)&&Tt.replaceChildren(),Tt.textContent=O.agentIconText??"💬"}let r=Tt.querySelector("img");r&&(r.style.height=K,r.style.width=K)}}let J=n.layout?.header?.showTitle,Q=n.layout?.header?.showSubtitle;if(Et&&(Et.style.display=!1===J?"none":""),Lt&&(Lt.style.display=!1===Q?"none":""),It){let e=ie()&&!1!==n.layout?.header?.showCloseButton;if(It.style.display=e?"":"none",!se()){let e=O.closeButtonSize??"";It.style.height=e,It.style.width=e,It.style.minWidth=e,It.style.minHeight=e}let t=O.closeButtonPlacement??"inline",{closeButtonWrapper:r}=it,o="top-right"===t,a=r?.classList.contains("persona-absolute");if(r&&o!==a)if(r.remove(),o){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=Jd?.railColumn??lt;e.style.position="relative",e.appendChild(r)}else{let e=O.clearChat?.placement??"inline",t=O.clearChat?.enabled??!0;r.className=t&&"inline"===e?"":"persona-ml-auto",Pt&&Pt.appendChild(r)}if(It.style.color=O.closeButtonColor||Hi.actionIconColor,O.closeButtonBackgroundColor?(It.style.backgroundColor=O.closeButtonBackgroundColor,It.classList.remove("hover:persona-bg-gray-100")):(It.style.backgroundColor="",It.classList.add("hover:persona-bg-gray-100")),O.closeButtonBorderWidth||O.closeButtonBorderColor){let e=O.closeButtonBorderWidth||"0px",t=O.closeButtonBorderColor||"transparent";It.style.border=`${e} solid ${t}`,It.classList.remove("persona-border-none")}else It.style.border="",It.classList.add("persona-border-none");O.closeButtonBorderRadius?(It.style.borderRadius=O.closeButtonBorderRadius,It.classList.remove("persona-rounded-full")):(It.style.borderRadius="",It.classList.add("persona-rounded-full")),O.closeButtonPaddingX?(It.style.paddingLeft=O.closeButtonPaddingX,It.style.paddingRight=O.closeButtonPaddingX):(It.style.paddingLeft="",It.style.paddingRight=""),O.closeButtonPaddingY?(It.style.paddingTop=O.closeButtonPaddingY,It.style.paddingBottom=O.closeButtonPaddingY):(It.style.paddingTop="",It.style.paddingBottom=""),Pi(It,O.closeButtonIconName??"x",{iconSize:se()?Tl:void 0,iconText:O.closeButtonIconText??"×"});let s=O.closeButtonTooltipText??"Close chat",i=O.closeButtonShowTooltip??!0;It.setAttribute("aria-label",s),r&&Bo({anchor:It,trigger:r,text:()=>It?.getAttribute("aria-label")??s,enabled:i})}let{clearChatButton:re,clearChatButtonWrapper:oe}=it;if(re){let e=O.clearChat??{},t=e.enabled??!0,r=n.layout?.header?.showClearChat,o=void 0!==r?r:t,a=e.placement??"inline";if(oe){oe.style.display=o?"":"none";let{closeButtonWrapper:e}=it;!se()&&e&&!e.classList.contains("persona-absolute")&&(o?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===a,r=oe.classList.contains("persona-absolute");if(!se()&&t!==r&&o){if(oe.remove(),t){oe.className="persona-absolute persona-top-4 persona-z-50",oe.style.right="48px";let e=Jd?.railColumn??lt;e.style.position="relative",e.appendChild(oe)}else{oe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oe.style.right="";let e=it.closeButtonWrapper;Pt&&e&&e.parentElement===Pt?Pt.insertBefore(oe,e):Pt&&Pt.appendChild(oe)}let e=it.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(o){if(!se()){let t=e.size??"";re.style.height=t,re.style.width=t,re.style.minWidth=t,re.style.minHeight=t}let t=e.iconColor??"";if(re.style.color=t||Hi.actionIconColor,Pi(re,e.iconName??"refresh-cw",{iconSize:se()?El:void 0}),e.backgroundColor?(re.style.backgroundColor=e.backgroundColor,re.classList.remove("hover:persona-bg-gray-100")):(re.style.backgroundColor="",re.classList.add("hover:persona-bg-gray-100")),e.borderWidth||e.borderColor){let t=e.borderWidth||"0px",r=e.borderColor||"transparent";re.style.border=`${t} solid ${r}`,re.classList.remove("persona-border-none")}else re.style.border="",re.classList.add("persona-border-none");e.borderRadius?(re.style.borderRadius=e.borderRadius,re.classList.remove("persona-rounded-full")):(re.style.borderRadius="",re.classList.add("persona-rounded-full")),e.paddingX?(re.style.paddingLeft=e.paddingX,re.style.paddingRight=e.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),e.paddingY?(re.style.paddingTop=e.paddingY,re.style.paddingBottom=e.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let r=e.tooltipText??"Clear chat",n=e.showTooltip??!0;re.setAttribute("aria-label",r),oe&&Bo({anchor:re,trigger:oe,text:()=>re?.getAttribute("aria-label")??r,enabled:n})}}let ae=n.actionParsers&&n.actionParsers.length?n.actionParsers:[cc],de=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[uc.message,uc.messageAndClick];G=mc({parsers:ae,handlers:de,getSessionMetadata:_,updateSessionMetadata:U,emit:N.emit,documentRef:typeof document<"u"?document:null}),ue=Jc(n,G,pe),(()=>{let e=Ld();if(e&&Nd?.matches(e,we(),!1===n.persistState)||!e&&!Nd)return;Nd?.destroy(),Nd=e?Pd(e):null;let t={...Rd};Nd?t.visitorStore=Nd:delete t.visitorStore,Rd=t,ha.setHistoryInternals(Rd)})(),ha.updateConfig(n),Ic(),(!0===n.features?.history?.enabled!==v||n.features?.history?.provider!==w||n.getIdentityProof!==x||n.clientToken!==C)&&(Jd?.closeHistory({restoreFocus:!1}),Jd?.installHistoryProvider()),Jd?.syncHistoryChromeImpl(),vc(),ec()&&!Jd&&gc().catch(()=>{}),pl(ct,ha.getMessages(),ue),Oa(),Cd(),(()=>{let e=cr();`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`===md&&e.icon===nd||xd()})(),_l(ha.isStreaming()),S!==n.contextMentions&&mu();let ce=!0===n.voiceRecognition?.enabled,ge=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),fe=$e(n.voiceRecognition?.provider);if(ce&&(ge||fe))if(Dt&&Ot){let e=n.voiceRecognition??{},t=n.sendButton??{},r=e.iconName??"mic",o=e.iconSize,a=parseFloat(o??"")||qo;Dt.classList.add(Fo),Dt.classList.toggle(zo,!o),Dt.style.width=o??"",Dt.style.height=o??"",Dt.style.minWidth=o??"",Dt.style.minHeight=o??"";let s=e.iconColor??t.textColor;Dt.innerHTML="";let i=xe(r,a,s||"currentColor",1.5);i?Dt.appendChild(i):Dt.textContent="🎤";let l=e.backgroundColor??t.backgroundColor;Dt.style.backgroundColor=l||"",Dt.style.color=s||"var(--persona-text, #111827)",e.borderWidth?(Dt.style.borderWidth=e.borderWidth,Dt.style.borderStyle="solid"):(Dt.style.borderWidth="",Dt.style.borderStyle=""),e.borderColor?Dt.style.borderColor=e.borderColor:Dt.style.borderColor="",e.paddingX?(Dt.style.paddingLeft=e.paddingX,Dt.style.paddingRight=e.paddingX):(Dt.style.paddingLeft="",Dt.style.paddingRight=""),e.paddingY?(Dt.style.paddingTop=e.paddingY,Dt.style.paddingBottom=e.paddingY):(Dt.style.paddingTop="",Dt.style.paddingBottom="");let d=e.tooltipText??"Start voice recognition",c=e.showTooltip??!1;Dt.setAttribute("aria-label",d),Ot&&Bo({anchor:Dt,trigger:Ot,text:()=>Dt?.getAttribute("aria-label")??d,enabled:c}),Ot.style.display="",Dt.disabled=Nl()||ha.isStreaming()&&!Rl()}else{let e=Ko(n);if(e){Dt=e.button,Ot=e.wrapper;let t=$t&&$t.parentElement===Ht?$t:null;Ht?Ht.insertBefore(Ot,t):yt?.appendChild(Ot),an&&(an.micButton=Dt),an?.addListener(Dt,"click",Np),Dt.disabled=Nl()||ha.isStreaming()&&!Rl()}}else Dt&&Ot&&(Ot.style.display="none",$e(n.voiceRecognition?.provider)?ha.isVoiceActive()&&ha.toggleVoice():cp&&Mp());if(qp(),!0===n.attachments?.enabled){if(zt&&Ft){zt.style.display="";let e=n.attachments??{};qt&&(qt.accept=(e.allowedTypes??on).join(","),qt.multiple=(e.maxFiles??4)>1),Sr&&Sr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}else{let e=n.attachments??{};jt||(jt=ne("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),jt.style.display="none",(mt.parentElement??yt).insertBefore(jt,mt)),qt||(qt=document.createElement("input"),qt.type="file",qt.accept=(e.allowedTypes??on).join(","),qt.multiple=(e.maxFiles??4)>1,qt.style.display="none",qt.setAttribute("aria-label","Attach files"),(mt.parentElement??yt).insertBefore(qt,mt)),zt=ne("div","persona-send-button-wrapper"),Ft=ne("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Fo} ${zo}`),Ft.type="button",Ft.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";Ft.style.fontSize="18px",Ft.style.lineHeight="1";let r=xe(t,qo,"currentColor",1.5);r?Ft.appendChild(r):Ft.textContent="📎",Ft.addEventListener("click",e=>{e.preventDefault(),qt?.click()}),zt.appendChild(Ft);let o=e.buttonTooltipText??"Attach file";Bo({anchor:Ft,trigger:zt,text:()=>Ft?.getAttribute("aria-label")??o}),Rt?Rt.append(zt):yt.appendChild(zt),an&&(an.attachmentButton=Ft,an.attachmentInput=qt??void 0,an.attachmentPreviews=jt??void 0),!Sr&&qt&&jt&&(Sr=fo.fromConfig(e,Er),Sr.setPreviewsContainer(jt),an?.addListener(qt,"change",async()=>{Sr&&qt?.files&&(await Sr.handleFileSelect(qt.files),qt.value="")}))}if(lt.querySelector(".persona-attachment-drop-overlay")?.remove(),lt.appendChild(Gc(n.attachments?.dropOverlay)),Ft){let e=n.attachments??{},t=e.buttonTooltipText??"Attach file";Ft.setAttribute("aria-label",t),Ft.textContent="";let r=xe(e.buttonIconName??"paperclip",qo,"currentColor",1.5);r?Ft.appendChild(r):Ft.textContent="📎",zt&&Bo({anchor:Ft,trigger:zt,text:()=>Ft?.getAttribute("aria-label")??t})}}else zt&&(zt.style.display="none"),Sr&&Sr.clearAttachments(),lt.querySelector(".persona-attachment-drop-overlay")?.remove();let Ce=n.sendButton??{},ke=Ce.useIcon??!1,Me=Ce.iconText??"↑",Ee=Ce.iconName,Le=Ce.tooltipText??"Send message",Pe=Ce.showTooltip??!1,Be=Ce.size,Ne=parseFloat(Be??"")||40,De=Ce.backgroundColor,Oe=Ce.textColor;if(ke){if(ft.style.width=Be??"",ft.style.height=Be??"",ft.style.minWidth=Be??"",ft.style.minHeight=Be??"",ft.style.fontSize="18px",ft.style.lineHeight="1",ft.style.color=Oe||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!ha.isStreaming())if(ft.innerHTML="",Ee){let e=parseFloat(Ce.iconSize??"")||Math.round(.5*Ne),t=Oe?.trim()||"currentColor",r=Ce.iconStrokeWidth??2,n=xe(Ee,e,t,r),o=xe(Ce.stopIconName??"square",e,t,r);n&&o?ft.appendChild(Vo(n,o)):n?ft.appendChild(n):ft.textContent=Me}else ft.textContent=Me;ft.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Fo}`,De?(ft.style.backgroundColor=De,ft.classList.remove("persona-bg-persona-primary")):(ft.style.backgroundColor="",ft.classList.add("persona-bg-persona-primary"))}else ft.textContent=n.copy?.sendButtonLabel??"Send",ft.style.width="",ft.style.height="",ft.style.minWidth="",ft.style.minHeight="",ft.style.fontSize="",ft.style.lineHeight="",ft.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",De?(ft.style.backgroundColor=De,ft.classList.remove("persona-bg-persona-accent")):ft.classList.add("persona-bg-persona-accent"),Oe?ft.style.color=Oe:ft.classList.add("persona-text-white");Ce.borderWidth?(ft.style.borderWidth=Ce.borderWidth,ft.style.borderStyle="solid"):(ft.style.borderWidth="",ft.style.borderStyle=""),Ce.borderColor?ft.style.borderColor=Ce.borderColor:ft.style.borderColor="",Ce.paddingX?(ft.style.paddingLeft=Ce.paddingX,ft.style.paddingRight=Ce.paddingX):(ft.style.paddingLeft="",ft.style.paddingRight=""),Ce.paddingY?(ft.style.paddingTop=Ce.paddingY,ft.style.paddingBottom=Ce.paddingY):(ft.style.paddingTop="",ft.style.paddingBottom=""),ha.isStreaming()||ft.setAttribute("aria-label",Le),zl(),$t&&Bo({anchor:ft,trigger:$t,text:()=>ft.getAttribute("aria-label")??Le,enabled:Pe}),Mn(),Xo();let Fe=Sa(Ar.getState().activeModeIds,n.composer?.modes);Ar.setActiveModeIds(Fe),Br().length>0!=!!Dr&&xn(),Dr?.render(Fe,Br());for(let e of[...Or.keys()])Ca(e,n.composer?.modeGroups)||Or.delete(e);Or.forEach(e=>e.repaint()),$r?.repaint(),fn?.resolve();let je=ks(n,se());if(Jo(),je){ct.style.maxWidth=je,ct.style.marginLeft="auto",ct.style.marginRight="auto",ct.style.width="100%",Ct.style.maxWidth=je,Ct.style.marginLeft="auto",Ct.style.marginRight="auto",Ct.style.width="100%";for(let e of[yt,ht,jt,bt])e&&(e.style.maxWidth=je,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{ct.style.maxWidth="",ct.style.marginLeft="",ct.style.marginRight="",ct.style.width="",Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight="",Ct.style.width="";for(let e of[yt,ht,jt,bt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let _e=n.statusIndicator??{};if(He(bt,yt,_e),Re(bt,_e,ha?.getStatus()??"idle"),ha){let e=ha.getStatus();rt(bt,"idle"===(Ve=e)?_e.idleText??cn.idle:"connecting"===Ve?_e.connectingText??cn.connecting:"connected"===Ve?_e.connectedText??cn.connected:"error"===Ve?_e.errorText??cn.error:"paused"===Ve?_e.pausedText??cn.paused:"resuming"===Ve?_e.resumingText??cn.resuming:cn[Ve],_e,e)}var Ve;bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Ue="left"===_e.align?"persona-text-left":"center"===_e.align?"persona-text-center":"persona-text-right";bt.classList.add(Ue),sn(),ql(),An(),Je()},open(){ie()&&Pl(!0,"api")},close(){ie()&&Pl(!1,"api")},toggle(){ie()&&Pl(!le,"api")},reconnect(){ha.reconnectNow()},clearChat(){Jn=!1,s.clear(),o.clear(),a.clear(),i.clear(),ha.clearMessages(),n.layout?.topFade&&(dt.scrollTop=0),dt.removeAttribute("data-persona-top-fade"),qa.clear(),$i();try{localStorage.removeItem(qc),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==qc)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let e=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(e),R?.clear&&Zs(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),$={},G.syncFromMetadata(),Sr?.clearAttachments(),ui(),Vr(void 0),zr(void 0),Ja(),Ae?.clear(),Ie?.reset(),Le?.update()},setMessage:e=>!(!mt||ha.isStreaming()||Nl()||(!le&&ie()&&Pl(!0,"system"),mt.value=e,mt.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(ha.isStreaming()||Hl())return!1;let t=e?.trim()||mt.value.trim();return!!t&&(!le&&ie()&&Pl(!0,"system"),mt.value="",mt.style.height="auto",Mr(),np(t,{consumeDraft:!1}),!0)},getComposerState:()=>Ar.getState(),setQuote(e){let t=e?.text?.trim();t&&zr({...e,text:t})},clearQuote(){zr(void 0)},startVoiceRecognition:()=>!ha.isStreaming()&&($e(n.voiceRecognition?.provider)?(ha.isVoiceActive()||ha.isBargeInActive()||(!le&&ie()&&Pl(!0,"system"),Bs.manuallyDeactivated=!1,Vs(),ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),js("user"),ha.isVoiceActive()&&Ep()})),!0):!!cp||!!kp()&&(!le&&ie()&&Pl(!0,"system"),Bs.manuallyDeactivated=!1,Vs(),Ap("user"),!0)),stopVoiceRecognition:()=>$e(n.voiceRecognition?.provider)?!(!ha.isVoiceActive()&&!ha.isBargeInActive()||((ha.isBargeInActive()?ha.deactivateBargeIn():ha.toggleVoice()).then(()=>{Bs.active=!1,Bs.manuallyDeactivated=!0,Vs(),js("user"),Bp()}),0)):!!cp&&(Bs.manuallyDeactivated=!0,Vs(),Mp("user"),!0),injectMessage:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectMessage(e)),injectAssistantMessage(e){!le&&ie()&&Pl(!0,"system");let t=ha.injectAssistantMessage(e);return de&&(de=!1,ce&&(clearTimeout(ce),ce=null),setTimeout(()=>{ha&&!ha.isStreaming()&&ha.continueConversation()},100)),t},injectUserMessage:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectUserMessage(e)),injectSystemMessage:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectSystemMessage(e)),injectMessageBatch:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectMessageBatch(e)),injectComponentDirective:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectComponentDirective(e)),injectTestMessage(e){!le&&ie()&&Pl(!0,"system"),ha.injectTestEvent(e)},connectStream:async(e,t)=>ha.connectStream(e,t),__pushEventStreamEvent(e){ye&&(qe(),ze(e.type,e.payload))},showEventStream(){ye&&Yr()},hideEventStream(){We&&Xr()},isEventStreamVisible:()=>We,listConversations:e=>ha.listConversations(e),getActiveConversationId:()=>ha.getActiveConversationId(),openConversation:(e,t)=>fc(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus})),startNewConversation:e=>fc(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){wc()},deleteConversation:e=>fc(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>fc(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>fc(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>fc(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>fc(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Nd;if(!e)return null;let t=await e.get();return e===Nd?t:null},getHistoryIdentityStatus(){let e=Jd?.historyProvider;return e?e.getIdentityStatus():ec()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>ec()?fc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0!==e?.focus?{focus:e.focus}:{}})):Promise.resolve(),hideHistory(e){Jd?.closeHistory(void 0!==e?.restoreFocus?{restoreFocus:e.restoreFocus}:void 0)},isHistoryVisible:()=>Ue,showArtifacts(){vd(n)&&(Jn=!1,Xn=!0,_o(),Wn?.setMobileOpen(!0))},hideArtifacts(){vd(n)&&(Jn=!0,_o())},upsertArtifact:e=>vd(n)?("panel"===On(n.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Jn=!1,Xn=!0),ha.upsertArtifact(e)):null,selectArtifact(e){vd(n)&&ha.selectArtifact(e)},clearArtifacts(){vd(n)&&ha.clearArtifacts()},getArtifacts:()=>ha?.getArtifacts()??[],getSelectedArtifactId:()=>ha?.getSelectedArtifactId()??null,focusInput:()=>!(Y&&!le&&!se()||!mt||(mt.focus(),0)),async resolveApproval(e,t,r){let n=ha.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!n?.approval)throw new Error(`Approval not found: ${e}`);if("webmcp"!==n.approval.toolType)return ha.resolveApproval(n.approval,t,r);ha.resolveWebMcpApproval(n.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Fa();let r=ha?ha.getMessages():[];Ma=t,Ia=!0,Ta=Pa(r),La=Ba(r),Oa(r)})(e)},clearFollowUpSuggestions(){Fa()},getMessages:()=>ha.getMessages(),getStatus:()=>ha.getStatus(),getPersistentMetadata:()=>({...$}),updatePersistentMetadata(e){U(e)},on:(e,t)=>N.on(e,t),off(e,t){N.off(e,t)},isOpen:()=>ie()&&le,isVoiceActive:()=>Bs.active,toggleReadAloud(e){ha.toggleReadAloud(e)},stopReadAloud(){ha.stopSpeaking()},getReadAloudState:e=>ha.getReadAloudState(e),onReadAloudChange:e=>ha.onReadAloudChange(e),getState:()=>({open:ie()&&le,launcherEnabled:Y,voiceActive:Bs.active,streaming:ha.isStreaming()}),showCSATFeedback(e){!le&&ie()&&Pl(!0,"system");let t=ct.querySelector(".persona-feedback-container");t&&t.remove();let r=Fc({onSubmit:async(t,r)=>{ha.isClientTokenMode()&&await ha.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});ct.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(e){!le&&ie()&&Pl(!0,"system");let t=ct.querySelector(".persona-feedback-container");t&&t.remove();let r=zc({onSubmit:async(t,r)=>{ha.isClientTokenMode()&&await ha.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});ct.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},submitCSATFeedback:async(e,t)=>ha.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>ha.submitNPSFeedback(e,t),destroy(){Vd(),null!=Hd&&(clearInterval(Hd),Hd=null),s.clear(),o.clear(),a.clear(),i.clear(),Zo.forEach(e=>e()),ot.remove(),st?.remove(),Kp?.destroy(),Jp?.remove(),ma&&It.removeEventListener("click",ma)}};if((r?.debugTools||n.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Lu,getMessages:Lu.getMessages,getStatus:Lu.getStatus,getMetadata:Lu.getPersistentMetadata,updateMetadata:Lu.updatePersistentMetadata,clearHistory:()=>Lu.clearChat(),setVoiceActive:e=>e?Lu.startVoiceRecognition():Lu.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Zo.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<"u"){let t=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.focusInput()};if(window.addEventListener("persona:focusInput",r),Zo.push(()=>{window.removeEventListener("persona:focusInput",r)}),ye){let e=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.showEventStream()},r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.hideEventStream()};window.addEventListener("persona:showEventStream",e),window.addEventListener("persona:hideEventStream",r),Zo.push(()=>{window.removeEventListener("persona:showEventStream",e),window.removeEventListener("persona:hideEventStream",r)})}let n=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.showHistory()},o=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.hideHistory()};window.addEventListener("persona:showHistory",n),window.addEventListener("persona:hideHistory",o),Zo.push(()=>{window.removeEventListener("persona:showHistory",n),window.removeEventListener("persona:hideHistory",o)});let a=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.showArtifacts()},s=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.hideArtifacts()},i=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||r?.artifact&&Lu.upsertArtifact(r.artifact)},l=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||"string"==typeof r?.id&&Lu.selectArtifact(r.id)},d=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.clearArtifacts()};window.addEventListener("persona:showArtifacts",a),window.addEventListener("persona:hideArtifacts",s),window.addEventListener("persona:upsertArtifact",i),window.addEventListener("persona:selectArtifact",l),window.addEventListener("persona:clearArtifacts",d),Zo.push(()=>{window.removeEventListener("persona:showArtifacts",a),window.removeEventListener("persona:hideArtifacts",s),window.removeEventListener("persona:upsertArtifact",i),window.removeEventListener("persona:selectArtifact",l),window.removeEventListener("persona:clearArtifacts",d)})}let Pu=function(e){return e?!0===e?{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}(n.persistState);if(Pu&&ie()){let t=function(e){try{let t="local"===e?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}(Pu.storage),r=`${Pu.keyPrefix}widget-open`,n=`${Pu.keyPrefix}widget-voice`,o=`${Pu.keyPrefix}widget-voice-mode`;if(t){let a=Pu.persist?.openState&&"true"===t.getItem(r),s=Pu.persist?.voiceState&&"true"===t.getItem(n),i=Pu.persist?.voiceState&&"true"===t.getItem(o);if(a&&(Kp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lu.open(),setTimeout(()=>{if(s||i)Lu.startVoiceRecognition();else if(Pu.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),Pu.persist?.openState&&(N.on("widget:opened",()=>{t.setItem(r,"true")}),N.on("widget:closed",()=>{t.setItem(r,"false")})),Pu.persist?.voiceState&&(N.on("voice:state",e=>{t.setItem(n,e.active?"true":"false")}),N.on("user:message",e=>{t.setItem(o,e.viaVoice?"true":"false")})),Pu.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(n),t.removeItem(o)},a=()=>e();window.addEventListener("persona:clear-chat",a),Zo.push(()=>{window.removeEventListener("persona:clear-chat",a)})}}}if(q&&ie()&&(Kp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lu.open()},0)),Il(),!Ya){let e=_e(()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))});Zo.push(e)}C=()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))},ha.getMessages().length>0&&dl(),T=()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))};let Bu=(e=>ge?()=>{}:(fe.add(e),()=>{fe.delete(e)}))(()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))});Zo.push(Bu);let Nu=bd(()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue),yd()?.updateInlineArtifactBlocks(ct,Kn.artifacts,{suppressTransition:!0}),_o())});return Zo.push(Nu),Lu},Qc=(e,t)=>{let r=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,t*parseFloat(o[1])/100):420},Zc=(e,t)=>{let r=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0",e.style.minWidth=r?"":"0"},ep=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=""},tp=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ep(e)},rp=e=>{e.style.transition=""},np=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},op=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ap=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},sp=(e,t,r,n)=>{if(!t)return e.style.padding="",e.style.background="",void(e.style.boxSizing="");e.style.boxSizing="border-box",e.style.padding=r,e.style.background=n},ip=(e,t)=>vi(t)?((e,t)=>{let{ownerDocument:r}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if("BODY"===o||"HTML"===o)throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),l=r.createElement("div"),d=r.createElement("aside"),c=r.createElement("div"),p=!(t?.launcher?.enabled??1)||(t?.launcher?.autoExpand??!1);i.dataset.personaDockRole="push-track",l.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),n.insertBefore(s,e),l.appendChild(e);let u=null,h=()=>{u?.disconnect(),u=null},m=null,g=()=>{m=!0===t?.launcher?.detachedPanel?(e=>{let t=xs(e),r=t.components?.panel,n=(e,r)=>null==e||""===e?r:es(t,e)??e;return{inset:n(r?.inset,Wa),canvasBackground:n(r?.canvasBackground,Da)}})(t):null};g();let f=()=>{((e,t,r,n,o,a,s,i)=>{let l=xi(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,n,o)=>{o?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,n),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(n))})(e,t,r,n,d),((e,t,r,n,o,a)=>{let s=a?t:e;"left"===o?s.firstElementChild!==n&&s.replaceChildren(n,r):s.lastElementChild!==n&&s.replaceChildren(r,n)})(e,t,r,n,l.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=l.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,g=a?.launcher?.mobileBreakpoint??640,f=null!=h&&h.innerWidth<=g;if(m&&f&&s)return e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),np(t),rp(n),tp(n),op(r),ap(o,n),sp(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??pn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",void(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",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0"));if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),tp(n),((e,t)=>{!1!==t?(e.style.maxHeight="100vh",e.style.maxHeight=t):e.style.maxHeight=""})(n,l.maxHeight),sp(n,c&&s,p,u),"overlay"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",np(t),rp(n),op(r),ap(o,n);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=l.width,n.style.maxWidth=l.width,n.style.minWidth=l.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=a,n.style.transform=d,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2","right"===l.side?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if("push"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",rp(n),ep(n),ap(o,n);let a=Qc(l.width,e.clientWidth),i=Math.max(0,e.clientWidth),d=l.animate?"margin-left 180ms ease":"none",c="right"===l.side?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=`${i+a}px`,t.style.transition=d,t.style.marginLeft=`${c}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${i}px`,r.style.maxWidth=`${i}px`,r.style.minWidth=`${i}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=l.width,n.style.minWidth=l.width,n.style.maxWidth=l.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",np(t),ep(n),op(r),ap(o,n);let a="emerge"===l.reveal;a?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let i=s?l.width:"0px",d=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease"+(c?", padding 180ms ease":""):"none",u=!s;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(n,l.maxHeight),n.style.overflow=a||u?"hidden":"visible",n.style.transition=d,a){n.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Qc(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;o.style.width=t,o.style.minWidth=t,o.style.maxWidth=t,o.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},y=null,b=()=>{y?.(),y=null,!0===t?.launcher?.detachedPanel&&"auto"===t?.colorScheme&&(y=Ss(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===xi(t).reveal&&(typeof ResizeObserver>"u"||(u=new ResizeObserver(()=>{f()}),u.observe(s))),p&&!v&&"true"!==s.dataset.personaDockMobileFullscreen&&(v=!0,((e,t)=>{let r=e.parentElement;if(!r)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(n);let o=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),o&&!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."+(!1===t.maxHeight?" 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.")})(s,xi(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===xi(t).reveal?(i.appendChild(l),i.appendChild(d),s.appendChild(i)):(s.appendChild(l),s.appendChild(d)),w(),b(),{mode:"docked",host:c,shell:s,syncWidgetState(e){let t=!e.launcherEnabled||e.open;p!==t&&(p=t,w())},updateConfig(e){t=e,!1===(t?.launcher?.enabled??!0)&&(p=!0),g(),w(),b()},destroy(){x?.removeEventListener("resize",C),y?.(),y=null,h(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Zc(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Zc(r,e)},destroy(){r.remove()}}})(e,t),lp=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let n=r.cloneNode(!0);e.insertBefore(n,e.firstChild)},dp=[],cp=()=>[...dp],pp=e=>{let t,r=(e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if("string"==typeof e){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e})(e.target),n=!0===e.useShadowDom,o=r.ownerDocument,a=e.config,s=ip(r,a),i=[],l=()=>{s.syncWidgetState(t.getState())},d=()=>{let d=((e,t)=>{let a=!(t?.launcher?.enabled??1)||vi(t),s=o.createElement("div");if(s.setAttribute("data-persona-root","true"),a&&(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0",s.style.minWidth="0"),n){let t=e.attachShadow({mode:"open"});t.appendChild(s),lp(t,o)}else e.appendChild(s),lp(e,o);return r.id&&s.setAttribute("data-persona-instance",r.id),s})(s.host,a);t=Xc(d,a,{debugTools:e.debugTools}),i.forEach(e=>e()),i=[t.on("widget:opened",l),t.on("widget:closed",l)],l()},c=()=>{i.forEach(e=>e()),i=[],t.destroy()};d(),e.onChatReady?.();let p=new Proxy({update(e){let n=dc(a??{},e),o=vi(a),i=vi(n),p=wi(a),u=wi(n);o===i&&p===u?(a=n,s.updateConfig(a),t.update(e),l()):(e=>{c(),s.destroy(),s=ip(r,e),a=e,d()})(n)},destroy(){c(),s.destroy();let t=dp.indexOf(p);-1!==t&&dp.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,n){if("host"===r)return s.host;if(r in e)return Reflect.get(e,r,n);let o=t[r];return"function"==typeof o?o.bind(t):o}});return dp.push(p),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=p),p},up=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),hp=new Set(["button","a","input","select","textarea","details","summary"]),mp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),gp=/\b(product|card|item|listing|result)\b/i,fp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,yp=3e3,bp=100;function vp(e){let t="string"==typeof e.className?e.className:"";if(gp.test(t)||e.id&&gp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&gp.test(r.value))return!0}return!1}function wp(e){return fp.test((e.textContent??"").trim())}function xp(e){let t=e.querySelectorAll("a[href]");for(let e=0;e<t.length;e++){let r=t[e].getAttribute("href")??"";if(r&&"#"!==r&&!r.toLowerCase().startsWith("javascript:"))return!0}return!1}function Cp(e){let t=e.match(fp);return t?t[0]:null}function Sp(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 e=t.getAttribute("href");return{title:t.textContent.trim(),href:e&&"#"!==e?e:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return r?.textContent?.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function kp(e){return vp(e)&&wp(e)&&(xp(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function Ap(e){return!vp(e)||wp(e)||!xp(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}var Mp=[{id:"commerce-card",scoreElement:e=>kp(e),shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if("static"===r.interactivity){let e=r.text.trim();return!!(0===e.length||fp.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===kp(e))return null;let{title:r,href:n}=Sp(e),o=Cp((e.textContent??"").trim())??Cp(t.text)??"",a=function(e){let t=[],r=e=>{let r=e.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(e=>r(e.textContent??"")),e.querySelectorAll('[role="button"]').forEach(e=>r(e.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(e=>{r(e.value??"")}),t.slice(0,6)}(e);return[n&&r?`[${r}](${n})${o?`: ${o}`:""}`:r?`${r}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>Ap(e),formatSummary(e,t){if(0===Ap(e))return null;let{title:r,href:n}=Sp(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Ip(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Tp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Ep(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return"a"===t&&e.hasAttribute("href")?"navigable":"input"===t||"select"===t||"textarea"===t||"textbox"===r||"combobox"===r||"listbox"===r||"spinbutton"===r?"input":"button"===t||"button"===r||hp.has(t)||r&&mp.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function Lp(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return!1}catch{}return!("none"===e.style.display||"hidden"===e.style.visibility)}function Pp(e){let t={},r=e.id;r&&(t.id=r);let n=e.getAttribute("href");n&&(t.href=n);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let l=e.getAttribute("role");l&&(t.role=l);for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];n.name.startsWith("data-")&&(t[n.name]=n.value)}return t}function Bp(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Ip(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of Tp){let n=e.getAttribute(r);if(n){let o=`${t}[${r}="${Ip(n)}"]`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(e=>Ip(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${n}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function Np(e,t){let r=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Bp(e),tagName:r,text:n,role:e.getAttribute("role"),interactivity:Ep(e),attributes:Pp(e)}}function Rp(e,t,r,n){let o=function(e){return"static"===e?bp:yp}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,n);r>0&&(o+=r,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function Hp(e,t){for(let r of e)if(t.el!==r.el&&r.formattingRule?.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function $p(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",o=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,i=t.mode??"structured",l=t.maxCandidates??Math.max(500,10*r),d=e.rules??Mp;return"simple"===i&&e.rules&&e.rules.length>0?(typeof console<"u"&&"function"==typeof console.warn&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.'),d=[]):"simple"===i&&(d=[]),{mode:i,maxElements:r,maxCandidates:l,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],n=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(up.has(s)){a=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Lp(t)){a=o.nextNode();continue}let i=Np(t,e.maxTextLength),l=i.text.length>0,d=Object.keys(i.attributes).length>0&&!Object.keys(i.attributes).every(e=>"role"===e);if(!l&&!d){a=o.nextNode();continue}n.has(i.selector)||(n.add(i.selector),r.push(i))}a=o.nextNode()}let s=[],i=[];for(let e of r)"static"!==e.interactivity?s.push(e):i.push(e);return[...s,...i].slice(0,e.maxElements)}(t,r):function(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(up.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Lp(t)){i=s.nextNode();continue}let d=Np(t,e.maxTextLength),c=d.text.length>0,p=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(e=>"role"===e);if(!c&&!p){i=s.nextNode();continue}if(n.has(d.selector)){i=s.nextNode();continue}n.add(d.selector);let{score:u,formattingRule:h}=Rp(t,d,e.rules,r);o.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}o.sort((e,t)=>{let r="static"===e.enriched.interactivity?1:0,n="static"===t.enriched.interactivity?1:0;return r!==n?r-n:t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex});let l=[];for(let t of o){if(l.length>=e.maxElements)break;Hp(l,t)||l.push(t)}return l.sort((e,t)=>{let r="static"===e.enriched.interactivity?1:0,n="static"===t.enriched.interactivity?1:0;return r!==n?r-n:1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let n=e.formattingRule.formatSummary(e.el,e.enriched,r);n&&(t=n)}let n={...e.enriched};return t&&(n.formattedSummary=t),n})}(t,r):[]}var Wp=100;function Dp(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",n=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&n.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||o[t.interactivity].push(t);if(o.clickable.length>0){let e=o.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,Wp)}" (clickable)`);n.push(`Interactive elements:\n${e.join("\n")}`)}if(o.navigable.length>0){let e=o.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,Wp)}" (navigable)`);n.push(`Navigation links:\n${e.join("\n")}`)}if(o.input.length>0){let e=o.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,Wp)}" (input)`);n.push(`Form inputs:\n${e.join("\n")}`)}if(o.static.length>0){let e=o.static.map(e=>`- ${e.selector}: "${e.text.substring(0,Wp)}"`);n.push(`Content:\n${e.join("\n")}`)}return n.join("\n\n")}var Op={components:{panel:{borderRadius:"0",shadow:"none"}}},Fp={id:"shop",label:"Shopping Assistant",config:{theme:{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"}}},launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"🛍️",position:"bottom-right",width:j},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"]}},zp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Op}},qp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Op}},jp={shop:Fp,minimal:zp,fullscreen:qp};function _p(e){return jp[e]}var Vp=typeof document<"u"?document.currentScript?.src??null:null,Up=(e,t=`host ${e} alongside it`)=>()=>{let r=Vp?.replace(/index\.global\.js($|\?)/,`${e}$1`);return r&&r!==Vp?import(r):Promise.reject(new Error(`Could not derive the ${e} URL from the widget script URL (${Vp??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))};return(e=>{It=e})(Up("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),qe(Up("markdown-parsers.js")),wt(Up("client-stream.js")),Ur(Up("client-history.js")),Mn(Up("ui-extras.js")),Nn(Up("session-actions.js")),Ic(Up("history-shell.js")),(e=>{to=e})(Up("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),Ta(Up("context-mentions.js")),Ba(Up("context-mentions-inline.js")),xc(Up("history-view.js")),hi(Up("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),Zl(Up("approval-ui.js")),Xn(Up("voice-runtime.js")),gd(Up("artifacts-ui.js")),rc(Up("forms-ui.js")),de(Up("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),Rt(Up("webmcp-runtime.js")),ao(Up("session-reconnect.js")),od(Up("event-stream-view.js")),(e=>l(r({},"__esModule",{value:!0}),e))(u)})();
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var e,t=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,i=(e=function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof require<"u"?require:typeof Proxy<"u"&&new Proxy(e,{get:(e,t)=>(typeof require<"u"?require:e)[t]}),(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports)),l=(e,t,a,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of o(t))!s.call(e,l)&&l!==a&&r(e,l,{get:()=>t[l],enumerable:!(i=n(t,l))||i.enumerable});return e},d=(e,n,o)=>(o=null!=e?t(a(e)):{},l(!n&&e&&e.__esModule?o:r(o,"default",{value:e,enumerable:!0}),e)),c=i(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}),p=i(e=>{var t=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=e&&e.__exportStar||function(e,r){for(var n in e)"default"!==n&&!Object.prototype.hasOwnProperty.call(r,n)&&t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var n=c();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return n.Allow}}),r(c(),e);var o=class extends Error{};e.PartialJSON=o;var a=class extends Error{};function s(e,t=n.Allow.ALL){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return i(e.trim(),t)}e.MalformedJSON=a,e.parseJSON=s;var i=(e,t)=>{let r=e.length,s=0,i=e=>{throw new o(`${e} at position ${s}`)},l=e=>{throw new a(`${e} at position ${s}`)},d=()=>(m(),s>=r&&i("Unexpected end of input"),'"'===e[s]?c():"{"===e[s]?p():"["===e[s]?u():"null"===e.substring(s,s+4)||n.Allow.NULL&t&&r-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||n.Allow.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||n.Allow.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||n.Allow.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||n.Allow._INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||n.Allow.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):h()),c=()=>{let o=s,a=!1;for(s++;s<r&&('"'!==e[s]||a&&"\\"===e[s-1]);)a="\\"===e[s]&&!a,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(o,++s-Number(a)))}catch(e){l(String(e))}else if(n.Allow.STR&t)try{return JSON.parse(e.substring(o,s-Number(a))+'"')}catch{return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{s++,m();let o={};try{for(;"}"!==e[s];){if(m(),s>=r&&n.Allow.OBJ&t)return o;let a=c();m(),s++;try{let e=d();o[a]=e}catch(e){if(n.Allow.OBJ&t)return o;throw e}m(),","===e[s]&&s++}}catch{if(n.Allow.OBJ&t)return o;i("Expected '}' at end of object")}return s++,o},u=()=>{s++;let r=[];try{for(;"]"!==e[s];)r.push(d()),m(),","===e[s]&&s++}catch{if(n.Allow.ARR&t)return r;i("Expected ']' at end of array")}return s++,r},h=()=>{if(0===s){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(n.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let o=s;for("-"===e[s]&&s++;e[s]&&-1===",]}".indexOf(e[s]);)s++;s==r&&!(n.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(o,s))}catch{"-"===e.substring(o,s)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(e){l(String(e))}}},m=()=>{for(;s<r&&" \n\r\t".includes(e[s]);)s++};return d()},l=s;e.parse=l}),u={};((e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})})(u,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Sr,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Cr,ASK_USER_QUESTION_TOOL_NAME:()=>zt,AgentWidgetClient:()=>vn,AgentWidgetSession:()=>uo,AttachmentManager:()=>fo,BrowserSpeechEngine:()=>Vn,DEFAULT_COMPONENTS:()=>Qa,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>_,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>j,DEFAULT_PALETTE:()=>Ua,DEFAULT_SEMANTIC:()=>Ga,DEFAULT_WIDGET_CONFIG:()=>ee,HistoryProviderError:()=>wn,PRESETS:()=>jp,PRESET_FULLSCREEN:()=>qp,PRESET_MINIMAL:()=>zp,PRESET_SHOP:()=>Fp,ReadAloudController:()=>Un,SUGGEST_REPLIES_CLIENT_TOOL:()=>fr,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>gr,SUGGEST_REPLIES_TOOL_NAME:()=>mr,THEME_ZONES:()=>us,VERSION:()=>qr,WEBMCP_TOOL_PREFIX:()=>St,applyFeaturePreferences:()=>Gd,applyThemeVariables:()=>Cs,attachHeaderToContainer:()=>Oi,buildComposer:()=>Xi,buildDefaultHeader:()=>Ui,buildHeader:()=>Di,buildHeaderWithLayout:()=>Yi,buildMinimalHeader:()=>Ki,builtInClientToolsForDispatch:()=>kr,canonicalArtifactDisplayMode:()=>$n,collectEnrichedPageContext:()=>$p,componentRegistry:()=>sd,createActionManager:()=>mc,createAgentExperience:()=>Xc,createAskUserQuestionBubble:()=>pr,createBubbleWithLayout:()=>pl,createCSATFeedback:()=>Fc,createComboButton:()=>Vi,createComponentMiddleware:()=>Hc,createComponentStreamParser:()=>Bc,createDefaultSanitizer:()=>ot,createDirectivePostprocessor:()=>et,createDropdownMenu:()=>Fi,createFlexibleJsonStreamParser:()=>Fr,createIconButton:()=>zi,createImagePart:()=>en,createJsonStreamParser:()=>Or,createLabelButton:()=>qi,createLocalStorageAdapter:()=>yc,createMarkdownProcessor:()=>Ue,createMarkdownProcessorFromConfig:()=>Ke,createMessageActions:()=>dl,createNPSFeedback:()=>zc,createPlainTextParser:()=>Wr,createRegexJsonParser:()=>Dr,createSplitButton:()=>_i,createStandardBubble:()=>cl,createTextPart:()=>Zr,createTheme:()=>as,createThemeObserver:()=>Ss,createToggleGroup:()=>ji,createTypingIndicator:()=>tl,createWidgetHostLayout:()=>ip,createXmlParser:()=>zr,defaultActionHandlers:()=>uc,defaultJsonActionParser:()=>cc,defaultParseRules:()=>Mp,detectColorScheme:()=>vs,directivePostprocessor:()=>tt,ensureAskUserQuestionSheet:()=>ur,escapeHtml:()=>Ye,extractComponentDirectiveFromMessage:()=>Dc,fileToImagePart:()=>tn,formatEnrichedContext:()=>Dp,generateAssistantMessageId:()=>Ot,generateMessageId:()=>Wt,generateStableSelector:()=>Bp,generateUserMessageId:()=>Dt,getActiveTheme:()=>xs,getAgentWidgetHandles:()=>cp,getColorScheme:()=>ws,getDisplayText:()=>Yr,getHeaderLayout:()=>Gi,getImageParts:()=>Qr,getPreset:()=>_p,hasComponentDirective:()=>Wc,hasImages:()=>Xr,headerLayouts:()=>Ji,initAgentWidget:()=>pp,isAskUserQuestionMessage:()=>Qt,isComponentDirectiveType:()=>Nc,isDockedMountMode:()=>vi,isHistoryProviderError:()=>xn,isSuggestRepliesMessage:()=>yr,isWebMcpToolName:()=>Lt,isWelcomeVisible:()=>kl,latestAgentSuggestions:()=>vr,listRegisteredStreamAnimations:()=>Ys,loadMarkdownParsers:()=>je,markdownPostprocessor:()=>Ge,mergeWithDefaults:()=>re,normalizeContent:()=>Gr,normalizeMediaType:()=>Wn,onMarkdownParsersReady:()=>_e,parseAskUserQuestionPayload:()=>er,parseSuggestRepliesPayload:()=>br,parseWidgetPreferenceSlice:()=>Vd,pickBestVoice:()=>_n,pluginRegistry:()=>ac,registerIcons:()=>ve,registerStreamAnimationPlugin:()=>Js,removeAskUserQuestionSheet:()=>hr,renderComponentDirective:()=>Rc,renderLoadingIndicatorWithFallback:()=>rl,renderLucideIcon:()=>xe,resolveArtifactDisplay:()=>Dn,resolveArtifactDisplayMode:()=>On,resolveConfigPreferences:()=>Yd,resolveDockConfig:()=>xi,resolveSanitizer:()=>at,resolveTokens:()=>ts,resolveWelcomeConfig:()=>Sl,stripWebMcpPrefix:()=>Et,themeToCssVariables:()=>ps,unregisterStreamAnimationPlugin:()=>Gs,validateImageFile:()=>rn,validateTheme:()=>rs});var h=[["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"}]],m=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]],g=[["path",{d:"M20 6 9 17l-5-5"}]],f=[["path",{d:"m6 9 6 6 6-6"}]],y=[["path",{d:"m18 15-6-6-6 6"}]],b=[["circle",{cx:"12",cy:"12",r:"10"}]],v=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]],w=[["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"}]],x=[["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"}]],C=[["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"}]],S=[["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"}]],k=[["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"}]],A=[["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"}]],M=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]],I=(e,t=24,r="currentColor",n=2)=>{if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],r=e[1];if(!r)return;let n=document.createElementNS("http://www.w3.org/2000/svg",t);Object.entries(r).forEach(([e,t])=>{"stroke"!==e&&n.setAttribute(e,String(t))}),o.appendChild(n)}),o},T=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function E(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];T(t)&&T(n)?r[e]=E(t,n):r[e]=n}return r}var L=Symbol("persona.defaultsProvenance"),P=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function B(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let n=t?`${t}.${e}`:e;return P(r)?B(r,n):[n]})}function N(e,t){for(let r of t.split(".")){if(!P(e)||!Object.prototype.hasOwnProperty.call(e,r))return"absent";if(void 0===(e=e[r]))return"clear"}return"explicit"}function R(e,t){return e?.[L]??t.filter(t=>"explicit"===N(e,t))}function H(e,t){return Object.defineProperty(e,L,{value:t,enumerable:!0,configurable:!0}),e}function $(e,t,r){return H(e,R(t,B(r)))}var W=Symbol("persona.panelAliasProvenance"),D=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),O=(e,t)=>D(e,t)&&void 0!==e[t],F=e=>{let t=e?.[W];return t?{...t}:(e=>({launcherWidth:O(e?.launcher,"width"),legacyLauncherWidth:O(e,"launcherWidth"),sidebarWidth:O(e?.launcher,"sidebarWidth"),dockWidth:O(e?.launcher?.dock,"width")}))(e)},z=(e,t)=>(Object.defineProperty(e,W,{value:t,enumerable:!0,configurable:!0}),e),q=(e,t)=>z(e,F(t)),j="min(440px, calc(100vw - 24px))",_="440px",V="40px",U="How can I help...",K={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},J={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},G={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:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"💬",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:j,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:V,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)"},copy:{inputPlaceholder:U,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"↑",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting…",connectedText:"Streaming…",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",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:K,reasoningDisplay:J,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other…",freeTextPlaceholder:"Type your answer…",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},Y={},X={launcher:{variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function Q(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function Z(e){let t="v5"===Q(e)?X:Y;return E(G,t)}var ee=Z();function te(e,t){if(e||t)return e?t?E(e,t):e:t}function re(e){let t=Z(e);return e?$(q({...t,...e,theme:te(t.theme,e.theme),darkTheme:te(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let r=t.features?.artifacts,n=e.features?.artifacts,o=t.features?.scrollToBottom,a=e.features?.scrollToBottom,s=t.features?.scrollBehavior,i=e.features?.scrollBehavior,l=t.features?.streamAnimation,d=e.features?.streamAnimation,c=t.features?.askUserQuestion,p=e.features?.askUserQuestion,u=t.features?.history,h=e.features?.history,m=void 0===r&&void 0===n?void 0:{...r,...n,layout:{...r?.layout,...n?.layout}},g=void 0===o&&void 0===a?void 0:{...o,...a},f=void 0===s&&void 0===i?void 0:{...s,...i},y=void 0===l&&void 0===d?void 0:{...l,...d},b=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},v=void 0===u&&void 0===h?void 0:{...u,...h,copy:{...u?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...void 0!==g?{scrollToBottom:g}:{},...void 0!==f?{scrollBehavior:f}:{},...void 0!==m?{artifacts:m}:{},...void 0!==y?{streamAnimation:y}:{},...void 0!==b?{askUserQuestion:b}:{},...void 0!==v?{history:v}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,X):$(q(t),void 0,X)}var ne=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},oe=(e,t={},...r)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),void 0!==t.text&&(n.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);if(t.style){let e=n.style,r=t.style;for(let t of Object.keys(r)){let n=r[t];null!=n&&(e[t]=n)}}let o=r.filter(e=>null!=e);return o.length>0&&n.append(...o),n},ae=(...e)=>e.filter(Boolean).join(" "),se=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,n=null,o=null,a=null;return{setLoader:e=>{n=e,r&&(o=null,a=null)},load:()=>o?Promise.resolve(o):a||(a=(n??t)().then(e=>(o=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{o=e},getSync:()=>o}},{setLoader:ie,load:le}=se({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),de=ie,ce=le,pe={activity:h,"arrow-down":[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]],"arrow-up":[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]],"arrow-up-right":[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]],bot:[["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"}]],"chevron-down":f,"chevron-up":y,"chevron-right":[["path",{d:"m9 18 6-6-6-6"}]],"chevron-left":[["path",{d:"m15 18-6-6 6-6"}]],check:g,clipboard:[["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"}]],"clipboard-copy":[["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"}]],"code-xml":[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]],copy:w,file:k,"file-code":x,"file-spreadsheet":C,"file-text":S,"image-plus":[["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"}]],loader:[["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"}]],"loader-circle":[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]],mic:[["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"}]],paperclip:[["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"}]],quote:[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]],"refresh-cw":[["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"}]],search:[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]],send:[["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"}]],"shield-alert":[["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"}]],"shield-check":[["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"}]],"shield-x":[["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"}]],square:[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]],"thumbs-down":[["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"}]],"thumbs-up":[["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"}]],upload:[["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"}]],"volume-2":[["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"}]],x:M,"at-sign":[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]],"arrow-left":[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]],"arrow-right":m,"external-link":[["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"}]],ellipsis:[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]],"ellipsis-vertical":[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]],menu:[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]],"panel-left":[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]],plus:[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]],minus:[["path",{d:"M5 12h14"}]],pencil:[["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"}]],trash:[["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"}]],"trash-2":[["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"}]],download:[["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"}]],maximize:[["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"}]],minimize:[["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"}]],"message-square":A,star:[["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"}]],eye:[["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"}]],history:[["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"}]]},ue=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],he=new Map(Object.entries(pe)),me=new Set,ge=!1,fe=new Set,ye=e=>{let t=[...fe];e&&fe.clear();for(let e of t)try{e()}catch{}},be=()=>{let e=0;for(let t of[...me]){let r=he.get(t.name);if(!r)continue;me.delete(t),e++;let n=I(r,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},ve=e=>{for(let[t,r]of Object.entries(e))he.set(t,r);be()>0&&!ge&&ye(!1)},we=!1,xe=(e,t=24,r="currentColor",n=2)=>{let o=he.get(e);if(o)return I(o,t,r,n);if(ue.includes(e)){we&&(we=!1);let o=((e,t,r)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(r)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n})(t,r,n);if(me.size>=500){let e=me.values().next().value;e&&me.delete(e)}return me.add({el:o,name:e,size:t,color:r,strokeWidth:n}),ce().then(e=>{if(!ge){for(let[t,r]of Object.entries(e.EXTRA_LUCIDE_ICONS))he.has(t)||he.set(t,r);ge=!0,be(),ye(!0)}}).catch(e=>{we=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)}),o}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null},Ce=["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"],Se=(e,t)=>{let r=ne("div",["persona-message-bubble",e,...Ce].join(" "));return r.id=`bubble-${t}`,r.setAttribute("data-message-id",t),r},ke=e=>{let t=ne("button",e.expandable?"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");return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},Ae=(e,t,r)=>{e.innerHTML="";let n=I(t?y:f,16,r,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Me=(e,t,r)=>{if(!r.expandable)return e.append(t),null;let n=ne("div","persona-flex persona-items-center");Ae(n,r.expanded,r.iconColor);let o=ne("div",r.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return o.append(n),e.append(t,o),n},Ie=e=>{let t=ne("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let r=e.renderPreview?.();((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(t,r)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Te=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Ae(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Ee=(e,t,r)=>{let n=r.stateSet.has(e),o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),s=t.querySelector(`[data-persona-collapsed-preview="${r.previewKind}"]`);if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");i&&Ae(i,n,r.iconColor),a.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")};function Le(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[r]:{..."tool"===t?K:J,...!0===e?.future?.v5Defaults?X.features?.[r]:{},...e?.features?.[r]}}}}function Pe(e,t){let r="tool"===t?"toolCallDisplay":"reasoningDisplay";return e?.features?.[r]?.variant??(e?.future?.v5Defaults?"row":"card")}function Be(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Ne(e,t,r,n){if("row"!==Pe(r,n))return e;e.className=`persona-message-bubble persona-${n}-bubble persona-activity-row`,e.dataset.activityKind=n,"tool"===n&&void 0===r.toolCall?.shadow&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let o=e.querySelector(":scope > button");if(!o)return e;o.className="persona-activity-header";let a="tool"===n?t.toolCall:t.reasoning,s="complete"!==a?.status,i=t.approval?.status??t.toolCall?.approvalStatus,l="denied"===i?"denied":"pending"===i?"awaiting-approval":!1===t.toolCall?.success?"error":s?"pending"===a?.status?"pending":"running":"done";e.dataset.activityState=l;let d=ne("span","persona-activity-icon");d.dataset.activityIcon=l;let c="reasoning"===n?r.features?.reasoningDisplay?.iconName:void 0,p=c?xe(c,16,"currentColor",2):"pending"===l?I(b,16,"currentColor",2):"awaiting-approval"===l?I(v,16,"currentColor",2):xe({pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"}[l],16,"currentColor",2);p&&d.appendChild(p),o.querySelector(".persona-reasoning-header-icon")?.remove();let u="tool"===n?"toolCallDisplay":"reasoningDisplay",h=r.features?.[u]?.iconVisibility??(r.future?.v5Defaults?"active":"always");if(("always"===h||"active"===h&&"done"!==l)&&o.prepend(d),"tool"===n&&a){let e=ne("span","persona-activity-duration");s&&a.startedAt&&e.setAttribute("data-tool-elapsed",String(a.startedAt));let r=("tool"===n?t.toolCall?.duration:void 0)??a.durationMs??(void 0!==a.completedAt&&void 0!==a.startedAt?a.completedAt-a.startedAt:void 0);e.textContent=void 0===r?"":Be(r),o.appendChild(e)}o.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),o.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let m=e.querySelector(":scope > .persona-border-t");return m?.classList.add("persona-activity-body"),m&&(m.id=`activity-details-${t.id}`,o.setAttribute("aria-controls",m.id)),e}var Re=(e,t,r)=>{let n="transient"===t.mode,o=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=((e,t)=>!1!==e.visible&&("transient"!==e.mode||"connecting"===t||"paused"===t||"resuming"===t||"error"===t))(t,r)||n&&o&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!n),e.classList.toggle("persona-mb-2",n)},He=(e,t,r)=>{!t.parentElement||e.parentElement!==t.parentElement||("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function $e(e){return"runtype"===e?.type||"custom"===e?.type}var{setLoader:We,load:De,provide:Oe,getSync:Fe}=se({fallbackImport:()=>import("./markdown-parsers-entry")}),ze=new Set,qe=We,je=()=>{let e=Fe();return e?Promise.resolve(e):De().then(e=>((()=>{let e=[...ze];ze.clear();for(let t of e)try{t()}catch{}})(),e))},_e=e=>Fe()?()=>{}:(ze.add(e),()=>{ze.delete(e)}),Ve=Fe,Ue=e=>{let t=null;return r=>{let n=Ve();if(!n)return Ye(r);if(!t){let{Marked:r}=n,o=e?.markedOptions;t=new r({gfm:o?.gfm??!0,breaks:o?.breaks??!0,pedantic:o?.pedantic,silent:o?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,n)=>e({type:"heading",raw:n,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,n)=>e({type:"code",raw:"",text:t,lang:r,escaped:n})}if(r.blockquote){let e=r.blockquote;t.blockquote=t=>e({type:"blockquote",raw:"",text:t,tokens:[]})}if(r.table){let e=r.table;t.table=(t,r)=>e({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:t,bodyHtml:r})}if(r.link){let e=r.link;t.link=(t,r,n)=>e({type:"link",raw:"",href:t,title:r??null,text:n,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,n)=>e({type:"image",raw:"",href:t,title:r??null,text:n})}if(r.list){let e=r.list;t.list=(t,r,n)=>e({type:"list",raw:"",ordered:r,start:n,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,n)=>e({type:"list_item",raw:"",task:r,checked:n,loose:!1,text:t,tokens:[]})}if(r.paragraph){let e=r.paragraph;t.paragraph=t=>e({type:"paragraph",raw:"",text:t,tokens:[]})}if(r.codespan){let e=r.codespan;t.codespan=t=>e({type:"codespan",raw:"",text:t})}if(r.strong){let e=r.strong;t.strong=t=>e({type:"strong",raw:"",text:t,tokens:[]})}if(r.em){let e=r.em;t.em=t=>e({type:"em",raw:"",text:t,tokens:[]})}if(r.del){let e=r.del;t.del=t=>e({type:"del",raw:"",text:t,tokens:[]})}if(r.html){let e=r.html;t.html=t=>e({type:"html",raw:t,text:t})}if(r.text){let e=r.text;t.text=t=>e({type:"text",raw:t,text:t})}if(r.checkbox){let e=r.checkbox;t.checkbox=t=>e({checked:t})}return r.hr&&(t.hr=r.hr),r.br&&(t.br=r.br),t})(e?.renderer);a&&t.use({renderer:a})}return t.parse(r)}},Ke=e=>e?Ue({markedOptions:e.options,renderer:e.renderer}):Ue(),Je=Ue(),Ge=e=>Je(e),Ye=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Xe=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Qe=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ze=(e,t)=>{let r=e;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,r)=>{try{let e=JSON.parse(r.trim());if(e&&"object"==typeof e&&"form"===e.component&&e.type){let r=Qe(t.length);return t.push({token:r,type:String(e.type)}),r}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let n=Qe(t.length);return t.push({token:n,type:r}),n}),r},et=e=>{let t=Ke(e);return e=>{let r=[],n=Ze(e,r),o=t(n);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Xe(t)}"></div>`;o=o.replace(r,n)}),o}},tt=e=>{let t=[],r=Ze(e,t),n=Ge(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Xe(t)}"></div>`;n=n.replace(r,o)}),n},rt={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"]},nt=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ot=()=>{let e=null;return t=>{let r=Ve();if(!r)return Ye(t);if(!e){let{DOMPurify:t}=r;e=t(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(e,t)=>{if("src"===t.attrName||"href"===t.attrName){let e=t.attrValue;e.toLowerCase().startsWith("data:")&&!nt.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,rt)}},at=e=>!1===e?null:"function"==typeof e?e:ot(),st=/^\s*\|?[\s:|-]*-[\s:|-]*$/,it=e=>e.includes("|"),lt=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(e=>e.trim())},dt=e=>`| ${e.join(" | ")} |`,ct=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,pt=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),ut="var(--persona-md-table-scroll-fade, 24px)",ht=new WeakSet;function mt(e){let t=e.scrollWidth-e.clientWidth;if(t<=1)return void e.removeAttribute("data-persona-scroll-x");e.setAttribute("data-persona-scroll-x","");let r="rtl"===getComputedStyle(e).direction?t+e.scrollLeft:e.scrollLeft,n=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":ut),e.style.setProperty("--persona-fade-r",n<=1?"0px":ut)}function gt(e){ht.has(e)||(ht.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&mt(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(mt)}var{setLoader:ft,load:yt,provide:bt,getSync:vt}=se({fallbackImport:()=>import("./client-stream")}),wt=ft,xt=yt,Ct=vt,St="webmcp:",kt=new Map,At=e=>{kt.clear();for(let t of e){let e=t.title?.trim();e&&kt.set(t.name,e)}},Mt=e=>kt.get(Et(e)),It=null;function Tt(e,t){let r=3735928559^t,n=1103547991^t;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);r=Math.imul(r^o,2654435761),n=Math.imul(n^o,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}var Et=e=>e.startsWith(St)?e.slice(St.length):e,Lt=e=>e.startsWith(St),Pt=()=>It?It():import("@mcp-b/webmcp-polyfill"),{setLoader:Bt,load:Nt}=se({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Rt=Bt,Ht=Nt;function $t(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function Wt(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Dt(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Ot(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var Ft=d(p(),1),zt="ask_user_question",qt="data-persona-ask-sheet-for",jt="Type your own answer here",_t="Send",Vt="data-ask-current-index",Ut="data-ask-question-count",Kt="data-ask-answers",Jt="data-ask-grouped",Gt="data-ask-layout",Yt=!1,Xt=e=>e.replace(/["\\]/g,"\\$&"),Qt=e=>"tool"===e.variant&&!!e.toolCall&&e.toolCall.name===zt,Zt=e=>e?.features?.askUserQuestion??{},er=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:r};let n=t.chunks;if(!n||0===n.length)return{payload:null,complete:r};try{let e=n.join(""),t=(0,Ft.parse)(e,Ft.STR|Ft.OBJ|Ft.ARR);if(t&&"object"==typeof t)return{payload:t,complete:r}}catch{}return{payload:null,complete:r}},tr=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!Yt&&(Yt=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},rr=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},nr=(e,t,r)=>{if("rows"!==e)return null;let n=ne("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let e=ne("span","persona-ask-row-check");n.appendChild(e)}else{let e=ne("span","persona-ask-row-badge");e.textContent=String(r+1),n.appendChild(e)}return n},or=e=>{let t=ne("span","rows"===e?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},ar=(e,t)=>{let r=ne("div","rows"===t?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=e.freeTextPlaceholder??jt,n.setAttribute("data-ask-free-text-input","true"),r.appendChild(n),"rows"!==t){let t=ne("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??_t,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},sr=e=>{let t=e.getAttribute(Kt);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},ir=e=>{let t=Number(e.getAttribute(Vt)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},lr=e=>{let t=Number(e.getAttribute(Ut)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},dr=e=>"true"===e.getAttribute(Jt),cr=(e,t,r)=>{let n=Zt(r),o=(e=>"pills"===e.getAttribute(Gt)?"pills":"rows")(e),{payload:a,complete:s}=er(t),i=dr(e),l=ir(e),d=lr(e),c=i?((e,t)=>tr(e)[t]??null)(a,l):(e=>tr(e)[0]??null)(a),p=!!c?.multiSelect,u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${l+1}/${d}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let m=e.querySelector('[data-ask-question="true"]');if(m){let e="string"==typeof c?.question?c.question:"";m.textContent=e,m.classList.toggle("persona-ask-question-skeleton",!e&&!s)}let g=e.querySelector('[data-ask-pill-list="true"]');if(g){let e=((e,t,r,n)=>{let o=ne("div","rows"===n?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&"string"==typeof e.label&&e.label.length>0);if(0===s.length&&!r){for(let e=0;e<3;e++)o.appendChild(or(n));return o}if(s.forEach((e,t)=>{o.appendChild(((e,t,r,n)=>{let o=ne("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",n?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),"rows"===r){let a=ne("span","persona-ask-row-content"),s=ne("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=ne("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}o.appendChild(a);let i=nr(r,n,t);i&&o.appendChild(i)}else o.textContent=e.label,e.description&&(o.title=e.description);return o})(e,t,n,a))}),!1!==e?.allowFreeText){let e="rows"===n?"Other":"Other…";if("rows"===n){let r=ne("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");r.setAttribute("data-ask-user-action","focus-free-text"),r.setAttribute("data-option-index",String(s.length)),r.setAttribute("data-ask-other-row","true");let i=ne("span","persona-ask-row-content"),l=document.createElement("input");l.type="text",l.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",l.placeholder=t.freeTextPlaceholder??jt,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=nr(n,a,s.length);d&&r.appendChild(d),o.appendChild(r)}else{let r=ne("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");r.type="button",r.setAttribute("data-ask-user-action","open-free-text"),r.textContent=t.freeTextLabel??e,o.appendChild(r)}}return o})(c,n,s,o);g.replaceWith(e)}if("rows"!==o){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(ar(n,o))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=ne("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=ne("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??_t,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(n)),e.setAttribute("data-multi-select",p?"true":"false");let y=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let n=ne("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=ne("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=r.backLabel??"Back",o.setAttribute("data-ask-user-action","back"),o.disabled=0===e,n.appendChild(o);let a=ne("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=ne("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=r.skipLabel??"Skip",s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=ne("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let l=e===t-1;return i.textContent=l?r.submitAllLabel??"Submit all":r.nextLabel??"Next",i.setAttribute("data-ask-user-action",l?"submit-all":"next"),i.disabled=!0,a.appendChild(i),n.appendChild(a),n})(l,d,n);y?y.replaceWith(t):e.appendChild(t)}else y&&y.remove();(e=>{let t=sr(e)[ir(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let n=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');n.forEach(e=>{let t=e.getAttribute("data-option-label")??"",n=r.has(t);e.setAttribute("aria-pressed",n?"true":"false"),e.classList.toggle("persona-ask-pill-selected",n)});let o=new Set(Array.from(n).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!o.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!dr(e))return;let t=sr(e)[ir(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,n=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');n&&(n.disabled=!r);let o=e.querySelector('[data-ask-user-action="submit-multi"]');if(o){let t=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));o.disabled=0===t.length}})(e)},pr=(e,t)=>{let r=ne("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let n=Zt(t);rr(r,n);let o=ne("span","persona-ask-stub-label"),{complete:a}=er(e);return o.textContent=a?"Awaiting your response…":"Preparing options…",r.appendChild(o),r},ur=(e,t,r)=>{if(!r||!Qt(e)||!1===Zt(t).enabled)return;let n=e.toolCall.id;r.querySelectorAll(`[${qt}]`).forEach(e=>{e.getAttribute(qt)!==n&&e.remove()});let o=r.querySelector(`[${qt}="${Xt(n)}"]`);if(o)return void((e,t,r)=>{let{payload:n}=er(t),o=Math.max(1,tr(n).length);o>lr(e)&&(e.setAttribute(Ut,String(o)),o>1&&!dr(e)&&e.setAttribute(Jt,"true")),cr(e,t,r)})(o,e,t);let{payload:a}=er(e),s=((e,t,r)=>{let n=Zt(t),o=(e=>"pills"===e.layout?"pills":"rows")(n),a=e.toolCall.id,s=tr(r),i=Math.max(1,s.length),l=i>1,d=((e,t)=>{let r=e.agentMetadata?.askUserQuestionAnswers;if(!r||"object"!=typeof r)return{};let n={};return t.forEach((e,t)=>{let o="string"==typeof e?.question?e.question:"";if(o&&Object.prototype.hasOwnProperty.call(r,o)){let e=r[o];("string"==typeof e||Array.isArray(e))&&(n[t]=e)}}),n})(e,s),c=l?((e,t)=>{let r=e.agentMetadata?.askUserQuestionIndex;return"number"==typeof r&&Number.isFinite(r)?Math.max(0,Math.min(t-1,Math.floor(r))):0})(e,i):0,p=ne("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(qt,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(Ut,String(i)),p.setAttribute(Vt,String(c)),p.setAttribute(Jt,l?"true":"false"),p.setAttribute(Gt,o),((e,t)=>{e.setAttribute(Kt,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==n.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),rr(p,n);let u=ne("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=ne("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=ne("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=ne("div","rows"===o?"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 g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==o&&p.appendChild(ar(n,o)),cr(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},hr=(e,t)=>{if(!e)return;let r=t?`[${qt}="${Xt(t)}"]`:`[${qt}]`;e.querySelectorAll(r).forEach(e=>{e.classList.add("persona-ask-sheet-leave");let t=Number.parseInt(getComputedStyle(e).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},mr="suggest_replies",gr={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},fr={name:mr,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:gr,origin:"sdk",annotations:{readOnlyHint:!0}},yr=e=>"tool"===e.variant&&e.toolCall?.name===mr,br=e=>{let t=e;if("string"==typeof t)try{t=JSON.parse(t)}catch{return[]}let r=t?.suggestions;if(!Array.isArray(r))return[];let n=r.flatMap(e=>{if("string"==typeof e){let t=e.trim();return t?[t]:[]}if(!e||"object"!=typeof e)return[];let t=e;if("string"!=typeof t.label||!t.label.trim())return[];let r={label:t.label.trim()};return"string"==typeof t.prompt&&t.prompt.trim()&&(r.prompt=t.prompt.trim()),"string"==typeof t.description&&t.description.trim()&&(r.description=t.description.trim()),[r]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},vr=e=>{for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return null;if(!yr(r))continue;let n=br(r.toolCall?.args);return n.length>0?n:null}return null},wr=new Set,xr=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,n=e=>{let n=t?.[e],o=r?.[e];void 0===n||void 0===o||n!==o&&((e,t,r)=>{let n=`${e}:${t}:${r}`;wr.has(n)||(wr.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,o,n)};e&&(n("enabled"),n("expose"));let o=t?.enabled??r?.enabled??!0;return{enabled:o,expose:!!o&&(t?.expose??r?.expose??!1)}},Cr={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:8,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},Sr={name:zt,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:Cr,origin:"sdk",annotations:{readOnlyHint:!0}},kr=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(Sr),xr(e).expose&&t.push(fr),t},Ar=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Mr=e=>{if("tool"!==e.variant)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||void 0===t.result)return null;let r=(e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""))(t.toolName);return r?{call:{toolCallId:t.toolCallId,toolName:r,args:Ar(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:r,result:t.result}}:null},Ir=(e,t)=>{let r,n=[],o=[],a=[],s="",i=()=>{0!==o.length&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:a}),o=[],a=[])};for(let l of e){let e=Mr(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(void 0===t||t!==r)&&i(),0===o.length&&(s=l.createdAt,r=t),o.some(t=>t.toolCallId===e.call.toolCallId)||(o.push(e.call),a.push(e.result));continue}let d=t(l);d&&(i(),n.push(d))}return i(),n},Tr=d(p(),1),Er=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Lr=e=>{if(null===e)return"null";if(void 0===e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Pr=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Br=e=>{let t="number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Pr(t)},Nr=e=>{let t=void 0!==e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Pr(t)},Rr=(e,t,r)=>{if(!t)return r;let n=e.name?.trim()||"tool",o=Br(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,o)},Hr=(e,t)=>{let r,n=e.replace(/\{toolName\}/g,t),o=[],a=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0;for(;null!==(r=a.exec(n));)r.index>s&&$r(o,n.slice(s,r.index),[]),void 0!==r[1]?$r(o,r[1],["bold"]):void 0!==r[2]?$r(o,r[2],["italic"]):void 0!==r[3]&&$r(o,r[3],["dim"]),s=r.index+r[0].length;return s<n.length&&$r(o,n.slice(s),[]),o},$r=(e,t,r)=>{let n=t.split("{duration}");for(let t=0;t<n.length;t++)n[t]&&e.push({text:n[t],styles:r}),t<n.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Wr=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),Dr=()=>{let e=(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return null!==e?{text:e,raw:r}:null;let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let o=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return t[1]}let r=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/);if(r&&r[1])try{return r[1].replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return r[1]}return null})(r);return null!==o&&(e=o),t=r.length,null!==e?{text:e,raw:r}:null},close:async()=>{}}})();return{processChunk:async t=>{let r=t.trim();return r.startsWith("{")||r.startsWith("[")?e.processChunk(t):null},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Or=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return null!==e||""===e?{text:e||"",raw:r}:null;try{let t=(0,Tr.parse)(r,Tr.STR|Tr.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?Er(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=Er(t.text)))}catch{}return t=r.length,null!==e?{text:e,raw:r}:null},close:()=>{}}},Fr=e=>{let t=null,r=0,n=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?Er(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?Er(e.text):"";if("init"===e.type&&e.form)return"";if(e.action)switch(e.action){case"nav_then_click":return t(e.on_load_text)||t(e.text)||null;case"message":case"message_and_click":case"checkout":return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(e.length<=r)return null!==t?{text:t,raw:e}:null;try{let r=(0,Tr.parse)(e,Tr.STR|Tr.OBJ),o=n(r);null!==o&&(t=o)}catch{}return r=e.length,{text:t||"",raw:e}},close:()=>{}}},zr=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}},qr="4.26.1",{setLoader:jr,load:_r,provide:Vr}=se({fallbackImport:()=>import("./client-history")}),Ur=jr,Kr=_r,Jr="[Image]";function Gr(e){return"string"==typeof e?[{type:"text",text:e}]:e}function Yr(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")}function Xr(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function Qr(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function Zr(e){return{type:"text",text:e}}function en(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function tn(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}function rn(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var nn=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],on=[...nn,"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"];function an(e){return function(e){return nn.includes(e)||e.startsWith("image/")}(e.type)}function sn(e,t=on,r=10485760){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function ln(e){let t=e.content;if("string"!=typeof t||""===t)return;let r=e.contentParts??e.llmContent??e.rawContent??t;return"string"!=typeof r||r!==t?t:void 0}function dn(e,t){let r=new Map;for(let t of e)r.set(t.id,t);for(let e of t)r.set(e.id,e);return[...r.values()].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o!==a?o-a:e.id.localeCompare(t.id)})}var cn={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"},pn=1e5,un=pn+1,hn=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}},mn=e=>"reason"in e?e.reason:void 0,gn=(e,t)=>e instanceof hn&&e.code===t,fn=e=>!e.voiceCaption&&!!(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),yn=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),bn=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt}),vn=class{constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#e=null,this.clientSession=null,this.#t=null,this.#r=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#n=null,this.#o=!1,this.#a=!1,this.#s=!1,this.#i=null,this.#l=new Set,this.#d=new Set,this.webMcpBridge=null,this.#c=null,this.#p=null,this.#u=null,e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#h=e.apiUrl??"https://api.runtype.com/v1/dispatch",this.#m={"Content-Type":"application/json","X-Persona-Version":qr,...e.headers},this.debug=!!e.debug,this.#g=e.streamParser??function(e){switch(e){case"json":return Or;case"regex-json":return Dr;case"xml":return zr;default:return Wr}}(e.parserType),this.#f=e.contextProviders??[],this.#y=e.requestMiddleware,this.#b=e.customFetch,this.#v=e.parseSSEEvent,this.#w=e.getHeaders,!0===e.webmcp?.enabled&&(this.#c=this.#x(e.webmcp))}#h;#m;#g;#f;#y;#b;#v;#w;#C;#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#S;#x(e){return Ht().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:At,getToolDisplayTitle:Mt,loadPolyfill:Pt});return void 0!==this.#S&&r.setConfirmHandler(this.#S),this.webMcpBridge=r,r}).catch(e=>(this.#c=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",e),null))}#k(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):!0!==this.config.webmcp?.enabled?Promise.resolve(null):(this.#c||(this.#c=this.#x(this.config.webmcp)),this.#c)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#C=e}setWebMcpConfirmHandler(e){this.#S=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return!0===this.webMcpBridge?.isOperational()}executeWebMcpToolCall(e,t,r){return!0!==this.config.webmcp?.enabled?null:this.#k().then(n=>n?n.executeToolCall(e,t,r):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#C}isClientTokenMode(){return!!this.config.clientToken}#A(){let{agentId:e,flowId:t,target:r,targetProviders:n}=this.config;if(!r)return{agentId:e,flowId:t};let o=function(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let n=r.indexOf(":");if(n>0){let e=r.slice(0,n),o=r.slice(n+1);if("runtype"===e){let e=$t(o);if(e)return e;throw new Error(`[Persona] target "runtype:${o}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw new Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:a(o).payload}}let o=$t(r);if(o)return o;let a=t?.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}(r,n);return"agentId"===o.kind?{agentId:o.agentId}:"flowId"===o.kind?{flowId:o.flowId}:{targetPayload:o.payload}}isAgentMode(){return!(!this.config.agent&&!this.#A().agentId)}#M(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||"https://api.runtype.com"}#I(e){return`${this.#M()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),r=!1;for(;;){let n=t.conversationId,o=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!n||!o)throw new hn("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.#M()}/v1/client/conversations/${encodeURIComponent(n)}/executions/${encodeURIComponent(e.executionId)}/events`,s=new URLSearchParams({sessionId:t.sessionId,after:e.after}),i=await fetch(`${a}?${s}`,{method:"GET",headers:{"X-Persona-Version":qr,"X-Visitor-Token":o},signal:e.signal});if(401===i.status&&!r){r=!0;let e=await Kr();t=await e.recoverFromUnauthorized(this.#T(),await e.readErrorCode(this.#T(),i),null,!0);continue}if(!i.ok)throw await(await Kr()).historyErrorFor(this.#T(),i,!0);return i}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#t||e&&new Date<e.expiresAt||this.#r===e?null:(this.#r=e,this.initSession().catch(()=>null))}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.#t)return this.#t;let e=this.#t=this.#E().then(t=>this.#t!==e?this.initSession():(this.clientSession=t,this.#r=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t)).finally(()=>{this.#t===e&&(this.#t=null)});return e}#L(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()&&!this.#o}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#P(){if(!this.#o){this.#B({state:"unavailable",reason:"history_disabled"}),this.#o=!0,!this.#a&&typeof console<"u"&&(this.#a=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#d])e(!1)}}getHistoryIdentityStatus(){return this.#i??this.#N()}subscribeHistoryIdentityStatus(e){return this.#l.add(e),()=>{this.#l.delete(e)}}subscribeHistoryAvailability(e){return this.#d.add(e),this.#o&&e(!1),()=>{this.#d.delete(e)}}#N(){return this.isClientTokenMode()?!0!==this.config.features?.history?.enabled||this.#o?{state:"unavailable",reason:"history_disabled"}:this.#R():{state:"unavailable",reason:"ineligible_mode"}}#R(){let e=this.#i;return"browser_only"===e?.state?e:this.#H()}#H(){return"browser"===this.config.features?.history?.scope?{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"}}#B(e){let t=this.getHistoryIdentityStatus(),r=t.state===e.state&&mn(t)===mn(e);if(this.#i=e,!r){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#l])t(e)}}async#$(e){let t=this.#L()&&!e.omitVisitorFields,r=!e.omitVisitorFields,n=null;(t||r)&&(await this.historyInternals.historyBootstrapReady,n=await this.readVisitorToken());let o=this.#A(),a=o.agentId??o.flowId,s=t||e.durableResume?e.conversationId:void 0,i={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(t||r)&&n?{visitorToken:n}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.#I("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qr},body:JSON.stringify(i),signal:e.signal});if(!l.ok){let r=await l.json().catch(()=>({error:"Session initialization failed"}));if(t&&403===l.status&&"visitor_history_disabled"===r.error){if(this.#P(),s)throw new hn("history_disabled","Visitor history is disabled for this surface");return this.#$({...e,omitVisitorFields:!0})}throw 403===l.status&&"durable_recovery_disabled"===r.error?new hn("history_disabled","Durable recovery is disabled for this surface"):(t||e.durableResume)&&401===l.status&&"visitor_required"===r.error?new hn("visitor_required","Visitor credential no longer resolves"):s&&404===l.status?new hn("not_found","Conversation not found"):401===l.status?new Error(`Invalid client token: ${r.hint||r.error}`):403===l.status?new Error(`Origin not allowed: ${r.hint||r.error}`):new Error(r.error||"Failed to initialize session")}let d=await l.json();return d.visitor?.token&&await(this.historyInternals.visitorStore?.set(d.visitor.token)),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#E(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=!0===this.historyInternals.shouldResumeDurableConversation?.();if(!this.#L()&&!t)return this.#W(e,!1);let r=await this.readVisitorToken();if(e&&r)try{let r=await this.#$({conversationId:e,durableResume:t});return t&&!0!==r.durableRecovery?.enabled&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,e,!1)}catch(r){if(!gn(r,"not_found")&&!gn(r,"visitor_required")&&!gn(r,"history_disabled"))throw r;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,t){let r=this.historyInternals.visitorStore;return r&&!await this.readVisitorToken()?r.withFirstInitLock(()=>this.#O(e,t)):this.#O(e,t)}async#O(e,t){let r=this.config.getStoredSessionId?.()||null,n=await this.#$({storedSessionId:r}),o=await this.#F(n);return this.#D(o,e,t)}async#z(e){let t=this.config.getStoredSessionId?.()||null,r=this.config.getStoredConversationId?.()||null,n=await this.#$({storedSessionId:t,identityProof:e}),o=this.#D(n,r,!1);return this.clientSession=o,this.#t=null,this.#r=!1,this.resetClientToolsFingerprint(),o}async#F(e){if(!e.visitor?.token||this.#s||!this.#L()&&!0!==e.durableRecovery?.enabled)return e;this.#s=!0;try{return await this.#$({storedSessionId:e.sessionId})}catch{return e}finally{this.#s=!1}}#D(e,t,r){let n=e.conversationId;return n&&t&&(r||n!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:n}),this.config.setStoredSessionId?.(e.sessionId),n&&(this.config.setStoredConversationId?.(n),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#q(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#r=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#L())throw new hn("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new hn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let n=await this.#$({conversationId:e,identityProof:r});return this.#q(n)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#$({});return this.#q(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#L()&&this.#B(this.#H())}clearClientSession(){this.clientSession=null,this.#t=null,this.#r=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#n=null}#j(){return`${this.#M()}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if("csat"===e.type&&(void 0===e.rating||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if("nps"===e.type&&(void 0===e.rating||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},r=await fetch(this.#j(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qr},body:JSON.stringify(t)});if(!r.ok){let e=await r.json().catch(()=>({error:"Feedback submission failed"}));throw 401===r.status?(this.clientSession=null,this.#r=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(e.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async#_(e){e?.throwIfAborted();let t=this.config.identityProvider;if(void 0===t)return;let r,n,o=this.config.getIdentityProof;if(!t.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>o());r=e?await Promise.race([t,new Promise((t,r)=>{n=()=>r(e.reason),e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})]):await t}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{n&&e?.removeEventListener("abort",n)}if("string"!=typeof r||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:t,token:r}}#p;#V(){let e=this;return this.#p??={get config(){return e.config},headers:this.#m,getHeaders:this.#w,debug:this.debug,clientApiBase:()=>e.#M(),getClientApiUrl:t=>e.#I(t),getWebMcpBridge:()=>e.#k(),sendWithClientToolsDiff:(t,r,n,o)=>e.#U(t,r,n,o),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#u;#T(){let e=this;return this.#u??={HistoryClientError:hn,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#M(),setHistoryIdentityStatus:t=>e.#B(t),browserOnlyStatus:()=>e.#R(),derivedBrowserOnly:()=>e.#H(),reinitWithProof:t=>e.#z(t),isHistoryCapable:()=>e.#L(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await Kr()).listConversations(this.#T(),e)}async getConversation(e,t){return(await Kr()).getConversation(this.#T(),e,t)}async finalizeDisplayProjections(e,t){return(await Kr()).finalizeDisplayProjections(this.#T(),e,t)}async deleteConversation(e,t){return(await Kr()).deleteConversation(this.#T(),e,t)}async deleteAllConversations(e){return(await Kr()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await Kr()).resetVisitor(this.#T())}async dispatch(e,t){return e.signal?.throwIfAborted(),xt().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#G(e,t)}async#K(e,t){let r=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;this.#e=r;let n=()=>this.#e===r,o=e=>{n()&&t(e)};t({type:"status",status:"connecting"});try{let t=()=>{if(e.signal?.throwIfAborted(),!n())throw new DOMException("Turn superseded","AbortError")},a=this.clientSession??await this.initSession();t();let s=async()=>{t();let r=a,n=!0===r.durableRecovery?.enabled;if(n&&(!r.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");t();let o=await this.#$({...n||this.#L()?{conversationId:r.conversationId,durableResume:n}:{storedSessionId:r.sessionId},signal:e.signal});if(t(),r.conversationId&&o.conversationId!==r.conversationId||n&&!0!==o.durableRecovery?.enabled)throw new Error("Session renewal did not preserve this conversation.");a=this.#D(o,r.conversationId??null,!1),this.clientSession=a,this.#r=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await s();let i=await this.#Y(e.messages),l=i.metadata?Object.fromEntries(Object.entries(i.metadata).filter(([e])=>"sessionId"!==e&&"session_id"!==e)):void 0,d=this.#L(),c={sessionId:a.sessionId,messages:e.messages.filter(fn).map(e=>{let t=d?ln(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...void 0!==t&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...l&&Object.keys(l).length>0&&{metadata:l},...i.inputs&&Object.keys(i.inputs).length>0&&{inputs:i.inputs},...i.context&&{context:i.context},turnId:r,...e.interrupt&&{submitMode:"interrupt"}},p=async()=>{t();let r=!0===a.durableRecovery?.enabled?await this.readVisitorToken():null;return t(),this.#U(a.sessionId,i.clientTools,async n=>{t();let o=await this.#_(e.signal);t();let s={...c,sessionId:a.sessionId,...n,...o&&{identityProof:o}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...s,...o&&{identityProof:{provider:o.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qr,...r?{"X-Visitor-Token":r}:{}},body:JSON.stringify(s),signal:e.signal})})},u=await p();if(t(),401===u.response.status){let e=await u.response.clone().json().catch(()=>null);t(),"Session not found or expired"===e?.error&&(await s(),u=await p(),t())}let{response:h,commit:m}=u;if(!h.ok){let e=await h.json().catch(()=>({error:"Chat request failed"}));if(401===h.status&&"invalid_identity_proof"===e.error){let e=new hn("invalid_identity_proof","The identity proof was rejected");throw o({type:"error",error:e}),e}if(401===h.status){this.clearClientSession(),this.config.onSessionExpired?.();let e=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:e}),e}if(429===h.status){let t=new Error(e.hint||"Message limit reached for this session.");throw o({type:"error",error:t}),t}if(410===h.status&&"conversation_deleted"===e.error){let e=new hn("conversation_deleted","This conversation was deleted");throw o({type:"error",error:e}),e}let t=new Error(e.error||"Failed to send message");throw o({type:"error",error:t}),t}if(!h.body){let e=new Error("No response body received");throw o({type:"error",error:e}),e}m(),o({type:"status",status:"connected"});try{await this.#X(h.body,o,e.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(e){let t=e instanceof Error?e:new Error(String(e));throw!(t instanceof hn)&&!t.message.includes("Session expired")&&!t.message.includes("Message limit")&&o({type:"error",error:t}),t}}async#G(e,t){t({type:"status",status:"connecting"});let r=await this.#Y(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let n,o={...this.#m};if(this.#w)try{let e=await this.#w();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#b)try{n=await this.#b(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:new Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=new Error(`Chat backend request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t)}finally{t({type:"status",status:"idle"})}}async#J(e,t){t({type:"status",status:"connecting"});let r=await this.#Q(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let n,o={...this.#m};if(this.#w)try{let e=await this.#w();o={...o,...e}}catch(e){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",e)}if(this.#b)try{n=await this.#b(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(e){let r=e instanceof Error?e:new Error(String(e));throw t({type:"error",error:r}),r}else n=await fetch(this.#h,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!n.ok||!n.body){let e=new Error(`Agent execution request failed: ${n.status} ${n.statusText}`);throw t({type:"error",error:e}),e}t({type:"status",status:"connected"});try{await this.#X(n.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,n){t({type:"status",status:"connected"});try{await this.#X(e,t,r,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){return(await xt()).resolveApproval(this.#V(),e,t)}async#U(e,t,r,n){let o,a=!!(t&&t.length>0),s=a?function(e){if(0===e.length)return"0:empty";let t=e.map(e=>[e.name,e.description??"",e.parametersSchema?JSON.stringify(e.parametersSchema):"",e.origin??"",e.annotations?JSON.stringify(e.annotations):""].join("")).sort();return`${e.length}:${function(e){return`${Tt(e,0).toString(36)}.${Tt(e,2654435761).toString(36)}`}(t.join(""))}`}(t):void 0,i=this.clientToolsFingerprintSessionId===e,l=a&&i&&this.lastSentClientToolsFingerprint===s,d=!a&&!0===n?.emptyMeansReplace&&this.#n===e,c=!1;for(let e=0;o=await r({...a&&(c||!l)&&t?{clientTools:t}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),409===o.status&&0===e&&a&&"client_tools_resend_required"===(await o.clone().json().catch(()=>null))?.error;e++)c=!0,this.lastSentClientToolsFingerprint=null;return{response:o,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=e,a?this.#n=e:d&&(this.#n=null)}}}async resumeFlow(e,t,r){return(await xt()).resumeFlow(this.#V(),e,t,r)}#Z(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)return r.mentionContext&&Object.keys(r.mentionContext).length>0?{mentions:r.mentionContext}:null}return null}async#ee(e){let t={};this.#f.length&&await Promise.all(this.#f.map(async r=>{try{let n=await r({messages:e,config:this.config});n&&"object"==typeof n&&Object.assign(t,n)}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",e)}}));let r=this.#Z(e);return r&&Object.assign(t,r),Object.keys(t).length?t:null}#te(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#re(e,t){let r=t?.selectedModelId;return r&&"model"in e&&this.config.composer?.models?.some(e=>e.id===r)?{...e,model:r}:e}async#Q(e,t){let r=this.#A().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let n=Ir(yn(e),e=>!fn(e)||"user"!==e.role&&"assistant"!==e.role&&"system"!==e.role||e.variant&&"assistant"!==e.variant?null:bn(e)),o=this.#te(t),a={agent:this.#re(this.config.agent??{agentId:r},o),messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};o&&(a.composerOptions=o);let s=[...kr(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];s.length>0&&(a.clientTools=s);let i=await this.#ee(e);return i&&(a.context=i),a}async#Y(e,t){let r=Ir(yn(e),e=>fn(e)?bn(e):null),n=this.#A(),o={messages:r,...n.agentId?{agent:{agentId:n.agentId}}:n.flowId?{flowId:n.flowId}:{}};if(n.targetPayload)for(let[e,t]of Object.entries(n.targetPayload))"messages"!==e&&(o[e]=t);let a=[...kr(this.config),...await((await this.#k())?.snapshotForDispatch())??[]];a.length>0&&(o.clientTools=a);let s=await this.#ee(e);s&&(o.context=s);let i=this.#te(t);if(i&&(o.composerOptions=i),this.#y)try{let e=await this.#y({payload:{...o},config:this.config});if(e&&"object"==typeof e){let t=e;return void 0!==o.clientTools&&!("clientTools"in t)&&(t.clientTools=o.clientTools),t}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",e)}return o}async#X(e,t,r,n){let{streamResponse:o}=Ct()??await xt();return o({config:()=>this.config,createStreamParser:this.#g,parseSSEEvent:this.#v,onSSEEvent:(e,t)=>this.#C?.(e,t)},e,t,r,n)}},wn=class extends Error{constructor(e,t,r){super(t),this.name="HistoryProviderError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};function xn(e){return e instanceof wn}var{setLoader:Cn,load:Sn,provide:kn,getSync:An}=se({fallbackImport:()=>import("./ui-extras-entry")}),Mn=Cn,In=Sn,Tn=An,{setLoader:En,load:Ln,provide:Pn,getSync:Bn}=se({fallbackImport:()=>import("./session-actions")}),Nn=En,Rn=Ln,Hn=Bn;function $n(e){return"card"===e?"collapsed":e}function Wn(e){return e.split(";",1)[0].trim().toLowerCase()}function Dn(e,t){let r=e?.display,n="string"==typeof r?{default:r}:r??{};if(t.file&&n.files){if("string"==typeof n.files)return{mode:$n(n.files),matchedBy:{type:"files"}};let e=t.file.mimeType?Wn(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,n]of r)if(Wn(e)===t)return{mode:$n(n),selector:Wn(e)};let n=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(Wn(e)===n)return{mode:$n(t),selector:n}}(n.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(n.files.default)return{mode:$n(n.files.default),matchedBy:{type:"files"}}}let o=n.byKind?.[t.artifactType];if(o)return{mode:$n(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:$n(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:$n(s),matchedBy:{type:"preferredMode"}}:n.default?{mode:$n(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function On(e,t){return Dn(e,t).mode}function Fn(e,t){return JSON.stringify({component:"inline"===e?"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}:{},..."inline"===e&&t.component?{component:t.component}:{},..."inline"===e&&t.componentProps?{componentProps:t.componentProps}:{},...void 0!==t.markdown?{markdown:t.markdown}:{}}})}function zn(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function qn(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;t-=1)if("user"===e[t].role)return e[t].id;return null}function jn(e){return!("user"!==e.role||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||void 0!==e.rawContent||void 0!==e.llmContent&&e.llmContent!==e.content||e.quote)&&"string"==typeof e.content&&e.content.length>0}function _n(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 r of t){let t=e.find(e=>e.name===r);if(t)return t}return e.find(e=>e.lang.startsWith("en"))??e[0]}var Vn=class e{constructor(e={}){this.options=e,this.id="browser",this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,r){if(!e.isSupported())return void r.onError?.(new Error("Web Speech API is unavailable"));let n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(o.voice=e)}else a.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(a):_n(a));void 0!==t.rate&&(o.rate=t.rate),void 0!==t.pitch&&(o.pitch=t.pitch),o.onend=()=>r.onEnd?.(),o.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(new Error(t||"Speech synthesis failed"))},setTimeout(()=>{n.speak(o),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Un=class{#h=null;#m=null;#g="idle";#f=new Set;#y=0;#b;constructor(e){this.#b=e}get supportsPause(){return this.#h?.supportsPause??!0}stateFor(e){return this.#m===e?this.#g:"idle"}activeMessageId(){return this.#m}onChange(e){return this.#f.add(e),()=>this.#f.delete(e)}toggle(e,t){if(this.#m===e){if("playing"===this.#g)return void(this.#h?.supportsPause?(this.#h.pause(),this.#v(e,"paused")):this.stop());if("paused"===this.#g)return this.#h?.resume(),void this.#v(e,"playing");if("loading"===this.#g)return void this.stop()}this.play(e,t)}async play(e,t){let r=++this.#y;this.#h?.stop(),this.#v(e,"loading");try{if(!this.#h){let e=await this.#b();if(r!==this.#y)return;if(!e)return void this.#v(null,"idle");this.#h=e}this.#h.speak(t,{onStart:()=>{r===this.#y&&this.#v(e,"playing")},onEnd:()=>{r===this.#y&&this.#v(null,"idle")},onError:()=>{r===this.#y&&this.#v(null,"idle")}})}catch{r===this.#y&&this.#v(null,"idle")}}stop(){this.#y++,this.#h?.stop(),this.#v(null,"idle")}destroy(){this.stop(),this.#h?.destroy?.(),this.#h=null,this.#f.clear()}#v(e,t){this.#m="idle"===t?null:e,this.#g=t;for(let e of this.#f)e(this.#m,this.#g)}},Kn=class{#h;#m=!1;start(e){this.#h=e,this.#m=!1}cancel(){this.#m=!0}accepts(e){return!(this.#m||e&&this.#h&&e!==this.#h)}},{setLoader:Jn,load:Gn,getSync:Yn}=se({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Xn=Jn,Qn=Gn,Zn=Yn;function eo(e){if(!e)return"";let t=function(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let e=JSON.parse(t);if(e&&"object"==typeof e&&"string"==typeof e.text)return e.text}catch{}return null}(e);return function(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,"\n"),t=t.replace(/\n{2,}/g,"\n"),t.trim()}(null!==t?t:e)}var to=null,ro=()=>to?to():import("./runtype-tts-entry"),{setLoader:no,load:oo}=se({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),ao=no,so=oo,io=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"],lo=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};function co(e,t){let r=e instanceof Error?e:new Error(String(e));if("string"==typeof t)return t;if("function"==typeof t)return t(r);let n="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 r.message?`${n}\n\n_Details: ${r.message}_`:n}var po=e=>Lt(e)||e===mr,uo=class e{constructor(e={},t,r={}){this.config=e,this.callbacks=t,this.historyInternals=r,this.status="idle",this.streaming=!1,this.#h=new Map,this.abortController=null,this.#g=Date.now(),this.clientSession=null,this.agentExecution=null,this.#f=null,this.#y=null,this.#b=!1,this.#v=null,this.#w=null,this.#C=null,this.artifacts=new Map,this.#e=null,this.webMcpInflightKeys=new Set,this.webMcpResolvedKeys=new Set,this.webMcpResolveControllers=new Set,this.#t=0,this.webMcpApprovalResolvers=new Map,this.#r=0,this.approvalTokens=new Map,this.webMcpAwaitBatches=new Map,this.#n=null,this.#o=null,this.#a=0,this.#s=0,this.#i=!1,this.#l="disconnected",this.#d=null,this.#c=null,this.#S=null,this.#x=0,this.#k=!1,this.#A=null,this.#M=!1,this.#I=null,this.#L=new Map,this.#P=null,this.#N=new Map,this.#R=null,this.#H=null,this.#B=!1,this.#$=null,this.#E=null,this.#W=!1,this.#O=null,this.#D=null,this.#q=null,this.#j=new Kn,this.#_=Promise.resolve(),this.#p=null,this.#V=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new Un(()=>this.#u()),this.#ne=null,this.#oe=0,this.handleEvent=e=>{let t=this.#V;if(t&&("error"===e.type||"status"===e.type&&"error"===e.status?t.failed=!0:"message"===e.type&&"assistant"===e.message.role&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id))),"message"===e.type){this.upsertMessage(e.message),"approval"===e.message.variant&&e.message.approval&&"pending"!==e.message.approval.status&&this.#h.set(e.message.id,this.#m),"assistant"===e.message.role&&!e.message.variant&&e.message.streaming&&(this.#y=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&Rn().catch(()=>{});let t=e.message.toolCall,r=!!t?.name&&(Lt(t.name)||t.name===mr&&xr(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&r&&this.#ae(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?void 0!==e.message.agentMetadata.iteration&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if("cursor"===e.type)this.#se(e.id);else if("status"===e.type){if("idle"===e.status&&!e.terminal&&this.#ie())return void this.#le();if(this.#de(e.status),"connecting"===e.status)this.#ce(!0);else if("idle"===e.status||"error"===e.status){this.#pe()||this.#ue(),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null,this.#he(),this.#me());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;"running"===this.agentExecution?.status&&("error"===e.status?this.agentExecution.status="error":t||(this.agentExecution.status="complete")),this.#ge()}}else"error"===e.type?(this.#de("error"),this.#ue(),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null),"running"===this.agentExecution?.status&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):("artifact_start"===e.type||"artifact_delta"===e.type||"artifact_update"===e.type||"artifact_complete"===e.type)&&this.#fe(e)},this.historyInternals=this.#Z(r),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#ye()})),this.messages=this.#be(this.messages),this.client=new vn(e,this.historyInternals),this.#ve(),this.#we();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:"complete"});null!=e.initialSelectedArtifactId&&(this.#e=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#xe(),this.callbacks.onStatusChanged(this.status),this.#F(),this.#z()}#h;#m;#g;#f;#y;#b;#v;#w;#C;#e;#t;#r;#n;#o;#a;#s;#i;#l;#d;#c;#S;#x;#k;#A;#M;#I;#L;#P;#N;#R;#H;#B;#$;#E;#W;#O;#z(){this.config.voiceRecognition?.provider&&Qn().catch(()=>{})}#F(){let e=this.config.textToSpeech;if("runtype"!==e?.provider||e.createEngine)return;let t=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!t||!r||!this.config.clientToken||ro().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return"running"===this.agentExecution?.status}isVoiceSupported(){return function(e){try{if("custom"===e?.type&&e.custom){let t=e.custom,r="function"==typeof t?t():t;return!!r&&"function"==typeof r.startListening}return!("runtype"!==e?.type||!e.runtype)||typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)}catch{return!1}}(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#i}getVoiceStatus(){return this.#l}getVoiceDisclosure(){return this.#n?.getDisclosure?.()??null}getVoiceLevel(){return this.#n?.onLevel?this.#s:null}getVoiceInterruptionMode(){return this.#n?.getInterruptionMode?this.#n.getInterruptionMode():"none"}stopVoicePlayback(){this.#n?.stopPlayback&&(this.#j.cancel(),this.#p?.cancel(),this.#n.stopPlayback())}isBargeInActive(){return this.#n?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#n?.deactivateBargeIn&&await this.#n.deactivateBargeIn()}#D;#q;#j;#_;#p;#V;#u(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Vn.isSupported()?new Vn({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,o=this.config.clientToken,a=!1!==e.browserFallback;if(r&&n&&o)return ro().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:n,clientToken:o,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new i(l,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):l});if(a&&t)return o&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw new Error("Voice configuration not provided");this.cleanupVoice();let r=this.#_,n=++this.#a;this.#o=Qn().then(async e=>{await r,n===this.#a&&this.#T(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{n===this.#a&&(this.#o=null)})}catch(e){console.error("Failed to setup voice:",e)}}#T(e,t){this.#n=t;let r=this;e.wireSessionVoice({session:this,provider:()=>r.#n,generation:()=>r.#a,get keyed(){return r.#p},set keyed(e){r.#p=e},get pendingUser(){return r.#D},set pendingUser(e){r.#D=e},get pendingAssistant(){return r.#q},set pendingAssistant(e){r.#q=e},turns:()=>r.#j,busy:()=>r.#K(),setStreaming:e=>r.#ce(e),setDelegation:e=>{r.#V=e},setLevel:e=>{r.#s=e},setStatus:e=>{r.#l=e,r.#i="listening"===e},settlePending:e=>r.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#n&&this.#o&&await this.#o,this.#n)if(this.#i)await this.#n.stopListening();else{this.stopSpeaking();try{await this.#n.startListening()}catch(e){console.error("Failed to start voice:",e)}}else console.error("Voice not configured")}prewarmVoice(){if(!$e(this.config.voiceRecognition?.provider))return void this.warmClientSession();let e=this.#a,t=()=>{let t=this.#n;!t?.prewarm||e!==this.#a||this.#i||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{})};this.#n||!this.#o?t():this.#o.then(t,()=>{})}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#b||"resuming"===this.status}cleanupVoice(){let e=null!==this.#n;if(this.#a++,this.#o=null,this.#n){let e=this.#n;this.#n=null,this.#_=this.#G(e)}this.#i=!1,this.#l="disconnected",this.#J(!0),this.#p?.settle(),this.#p=null,this.#j=new Kn,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#G(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#J(e){let t=e?this.#D:null,r=this.#q;!t&&!r||(r&&this.#j.cancel(),e&&(this.#D=null),this.#q=null,r&&this.ttsSpokenMessageIds.add(r),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==r?[e]:e.id!==r||e.content.trim()?[{...e,streaming:!1,voiceProcessing:!1}]:[]),this.callbacks.onMessagesChanged([...this.messages]),r&&this.#ce(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#H=this.historyInternals.getStoredConversationRevision?.()??null,this.#B=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#U(e,t)}#U(e,t=!this.messages.length){if(this.#k||!e.config.welcomeMessage||!t)return;let r=this.messages[0],n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:r?.createdAt??(new Date).toISOString(),sequence:r?(r.sequence??0)-1:this.#ye()};this.#Ce(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return!!e&&new Date<e.expiresAt}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#Z(e),this.client.setHistoryInternals(this.historyInternals),this.#ve()}destroy(){this.cleanupVoice(),this.#$?.(),this.#$=null,this.#E=null}#Z(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#Se(e),t?.(e)}}}get#ee(){return this.historyInternals.historyProvider??null}#te(){let e=this.#ee;if(!e)throw new lo("history_unavailable","No conversation history provider is installed");return e}#re(e){let t=this.#te(),r=e??this.config.features?.history?.scope,n=this.config.getIdentityProof?"verified-user":"browser",o=r??(t.capabilities.scopes.includes(n)?n:t.capabilities.scopes[0]??n);if(!t.capabilities.scopes.includes(o))throw new wn("unsupported_scope","This history scope is not supported.");return{scope:o}}getHistoryState(){return{activeConversationId:this.#d,conversationRevision:this.#c,nextMessageCursor:this.#S,recovery:this.#A,sendBlocked:this.#M}}getActiveConversationId(){return this.#d}#Q(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#Y(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#I;e&&await e.catch(()=>{});let t=this.#P;t&&await t.catch(()=>{})}#X(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new lo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#te().list({...e?.cursor?{cursor:e.cursor}:{},...void 0!==e?.limit?{limit:e.limit}:{},...void 0!==e?.targetId?{targetId:e.targetId}:{},context:this.#re(e?.scope)})}async openConversation(e,t){let r=this.#te();this.#X();let n=this.#re(t?.scope);await this.awaitHistorySettled();let o=++this.#x,a=await r.getPage(e,{context:n});if(o!==this.#x)throw new lo("superseded","A later selection won");let s=await r.prepareOpen(e,{context:n});if(o!==this.#x)throw s.discard(),new lo("superseded","A later selection won");this.#k=!0;try{await this.#ke(s)}finally{this.#k=!1}this.#d=s.conversationId||e,this.#c=s.conversationRevision||a.conversationRevision||null,this.#S=a.nextCursor,this.#A=null,this.#M=!1,this.#Ae();for(let e of a.messages)this.#N.set(e.id,e.content);return this.#Me(),this.hydrateMessages(a.messages),this.#Q(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,r){let n=this.#te(),o=this.#re(r?.scope),a=t??this.#S;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let s=`${e} ${a}`,i=this.#L.get(s);if(i)return i;let l=this.#Ie(n,e,a,o).finally(()=>{this.#L.delete(s)});return this.#L.set(s,l),l}async#Ie(e,t,r,n){let o=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...o?{beforeCreatedAt:o}:{},context:n});if(this.#d&&this.#d!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=dn(this.messages,a.messages);this.messages=this.#be(s.map(e=>this.#Te(e))),this.#S=a.nextCursor;for(let e of a.messages)this.#N.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#Q(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let n=++this.#x,o=await t.prepareStartNew({context:r});if(n!==this.#x)throw o.discard(),new lo("superseded","A later action won");await this.#Ee(o)}async#Ee(e){this.#Le(),await this.#ke(e),this.#d=e.conversationId||null,this.#c=e.conversationRevision||null,this.#S=null,this.#A=null,this.#M=!1,this.#Me(),this.#Q()}async deleteConversation(e,t){let r=this.#te(),n=this.#re(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:n}),e===this.#d&&await this.#Pe(n)}async updateConversation(e,t,r){let n=this.#te();if(!n.update)throw new lo("history_unavailable","This history provider cannot update conversations");let o=this.#re(r?.scope);return await this.awaitHistorySettled(),n.update(e,t,{context:o})}canUpdateConversations(){return"function"==typeof this.#ee?.update}async clearConversationHistory(e){let t=this.#te(),r=this.#re(e?.scope);await this.awaitHistorySettled();let n=await t.deleteAll({...void 0!==e?.targetId?{targetId:e.targetId}:{},context:r});return await this.#Pe(r),n}async resetHistoryDevice(){let e=this.#te();if(!e.resetDevice)throw new lo("history_unavailable","This history provider cannot reset the device");this.#x+=1,this.#P=null;try{return await e.resetDevice()}finally{this.#Le(),this.#d=null,this.#c=null,this.#S=null,this.#A=null,this.#M=!1,this.#Q()}}async#Pe(e){this.#x+=1,this.#P=null,this.#Le(),this.#d=null,this.#c=null,this.#S=null,this.#M=!0,this.#A=null,this.#Q(),await this.#Be(e)}async#Be(e){let t=this.#ee;if(!t)return this.#M=!1,void this.#Q();try{let r=await t.prepareStartNew({context:e});await this.#Ee(r)}catch{this.#M=!0,this.#A="new_conversation_required",this.#Q(),this.#Y("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Ne(){if("new_conversation_required"===this.#A&&this.#ee&&(this.#A=null,await this.#Be(this.#re()),"new_conversation_required"===this.#A))throw new lo("new_conversation_required","A new conversation is required before sending")}async#ke(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#d=e.conversationId,this.#c=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#k||this.#U(e)}#Me(){this.#d?this.config.setStoredConversationId?.(this.#d):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#c),this.historyInternals.setStoredMessageCursor?.(this.#S)}#Ae(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#N.clear(),this.#He(null)}#Le(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.messages=[],this.#Ae(),this.#L.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ce(!1),this.#de("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Se(e){this.#x+=1,this.#P=null,this.#M=!0,this.#Le(),this.#d=e.conversationId,this.#c=null,this.#S=null,this.#A=null,this.#Q(),this.#Y("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#I=Promise.resolve().then(()=>{this.#M=!1,this.#I=null,this.#Q()})}#ve(){let e=this.historyInternals.visitorStore??null;e!==this.#E&&(this.#$?.(),this.#$=null,this.#E=e,e&&(this.#$=e.subscribe(e=>this.#De(e))))}#De(e){if("external"!==e.source||null===e.previousToken)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#P=null,this.#W=!0,this.#O=null;let t=this.messages.length>0;t||null!==this.#d||null!==(this.config.getStoredConversationId?.()??null)?this.#Le():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#L.clear(),this.#He(null)),this.#d=null,this.#c=null,this.#S=null,this.#A=null,this.#Q(),t&&this.#Y("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Oe(){return this.#W?(this.#O||(this.#O=this.#Fe().finally(()=>{this.#O=null})),this.#O):Promise.resolve()}async#Fe(){if(this.isClientTokenMode())try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}else this.#W=!1}reconcileBootConversation(e){let t=this.#ee,r=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#d;if(!t||!r)return Promise.resolve();let n=this.#re(e?.scope);this.#M=!0,this.#Q();let o=this.#ze(t,r,n).finally(()=>{this.#M=null!==this.#A,this.#I===o&&(this.#I=null),this.#Q()});return this.#I=o,o}async#ze(e,t,r){this.#d=t;let n=this.clientSession?.conversationRevision??this.#c??null,o=this.#B?this.#H:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#S=this.historyInternals.getStoredMessageCursor?.()??this.#S,await this.replayPendingProjections(),n&&o&&n===o)return void(this.#c=n);let a,s=await e.getPage(t,{context:r}),i=new Set(s.messages.map(e=>e.id)),l=this.messages.some(e=>i.has(e.id)),d=s.messages[0]?.createdAt;if(l){let e=this.#f?this.#y:null;a=dn(this.messages.filter(t=>!(!i.has(t.id)&&t.id!==e)||void 0!==d&&t.createdAt<d),s.messages).map(e=>this.#Te(e))}else a=s.messages.map(e=>this.#Te(e));this.#S=s.nextCursor,this.#c=s.conversationRevision||n||null,this.#N.clear();for(let e of s.messages)this.#N.set(e.id,e.content);this.#Me(),this.messages=this.#be(a),this.callbacks.onMessagesChanged([...this.messages])}#qe(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#He(e){this.#R=e,this.historyInternals.setPendingDisplayProjections?.(e)}#je(){return this.historyInternals.getPendingDisplayProjections?.()??this.#R}#_e(e){if(this.#qe())for(let t of e){let e=ln(t);void 0!==e&&this.#N.set(t.id,e)}}#me(){if(!this.#qe())return;let e=this.#d;if(!e)return;let t=[];for(let e of this.messages){if("assistant"!==e.role||e.streaming)continue;let r=ln(e);void 0!==r&&this.#N.get(e.id)!==r&&t.push({id:e.id,displayContent:r})}0!==t.length&&(this.#He({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Ve(e,t))}#Ve(e,t){let r=(this.#P??Promise.resolve()).catch(()=>{}).then(()=>this.#Ue(e,t,!1)).finally(()=>{this.#P===r&&(this.#P=null)});this.#P=r}async#Ue(e,t,r){if(this.#d!==e)return;let n=t.filter(e=>this.#N.get(e.id)!==e.displayContent);if(0!==n.length)try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,n);for(let e of n)this.#N.set(e.id,e.displayContent);this.#d===e&&r&&(this.#c=r),this.#Ke(e,t)}catch(o){if(!r&&this.#Je(o))return void await this.#Ue(e,n,!0);if(o instanceof hn&&("not_found"===o.code||"conversation_deleted"===o.code))return void this.#Ke(e,t);this.#Y("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}else this.#Ke(e,t)}#Je(e){return e instanceof hn?"request_failed"===e.code:e instanceof Error}#Ke(e,t){let r=this.#je();if(!r||r.conversationId!==e)return;let n=new Set(t.map(e=>e.id)),o=r.messageIds.filter(e=>!n.has(e));this.#He(o.length?{conversationId:e,messageIds:o}:null)}async replayPendingProjections(){if(!this.#qe())return;let e=this.#je();if(!e)return;if(this.#d&&e.conversationId!==this.#d)return void this.#He(null);let t=[];for(let r of e.messageIds){let e=this.messages.find(e=>e.id===r);!e||"string"!=typeof e.content||t.push({id:r,displayContent:e.content})}0!==t.length?(this.#Ve(e.conversationId,t),await(this.#P?.catch(()=>{}))):this.#He(null)}#he(){this.#d&&(this.#c=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ge(){await this.awaitHistorySettled(),await this.#Oe(),"new_conversation_required"===this.#A&&await this.#Ne()}static#Ye(e){return e instanceof hn&&"conversation_deleted"===e.code}async#Xe(t,r,n,o,a){this.#_e(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent)}catch(t){if(!e.#Ye(t))throw t;let s=await this.#Qe(o);if(!s)throw t;this.#_e([s]),await this.client.dispatch({messages:[s],signal:r.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async#Qe(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#x+=1,this.#P=null,this.#Le(),this.#d=null,this.#c=null,this.#S=null,this.#k=!0;try{let e=this.#ee;if(e){let t=await e.prepareStartNew({context:this.#re()});await this.#Ee(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#M=!0,this.#A="new_conversation_required",this.#Q(),this.#Y("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#k=!1}return this.#Ce(r),this.#ce(!0),this.#Y("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(e=>e.id===r.id)??r}updateConfig(e){let t=this.config.features?.artifacts?.display,r={...this.config,...e},n=function(e,t){let r=e.voiceRecognition,n=t.voiceRecognition;return!0===r?.enabled!=(!0===n?.enabled)||r?.provider?.type!==n?.provider?.type||r?.provider?.custom!==n?.provider?.custom||r?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),o=function(e,t){return io.some(r=>e[r]!==t[r])}(this.config,r);this.config=r,n&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&$e(r.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!o)return this.client.updateConfig(r),void(a&&this.#Ze());this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.client=new vn(this.config,this.historyInternals),a&&this.#Ze(),this.#we(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:n,contentParts:o,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e,u={id:a??("user"===t?Dt():"assistant"===t?Ot():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:r,createdAt:s??(new Date).toISOString(),sequence:i??this.#ye(),streaming:l,...void 0!==n&&{llmContent:n},...void 0!==o&&{contentParts:o},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p}};return this.upsertMessage(u),u}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:e,content:n,llmContent:o,contentParts:a,id:s,createdAt:i,sequence:l,streaming:d=!1,voiceProcessing:c,rawContent:p}=r,u={id:s??("user"===e?Dt():"assistant"===e?Ot():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:n,createdAt:i??(new Date).toISOString(),sequence:l??this.#ye(),streaming:d,...void 0!==o&&{llmContent:o},...void 0!==a&&{contentParts:a},...void 0!==c&&{voiceProcessing:c},...void 0!==p&&{rawContent:p}};t.push(u)}return this.messages=this.#be([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:n="",llmContent:o,id:a,createdAt:s,sequence:i}=e,l={text:n,component:t,props:r};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...void 0!==o&&{llmContent:o},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}async#et(e,t,r){let n;try{n=await r()}catch{return}let o=n.blocks.join("\n\n"),a=[o,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=n.contentParts.length>0;if(s){let t=[];o&&t.push(Zr(o)),t.push(...n.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(Zr(a)),t.push(...n.contentParts),e.contentParts=t}else o&&(e.llmContent=a);Object.keys(n.context).length>0&&(e.mentionContext=n.context)}async sendMessage(e,t){let r=e.trim(),n=!!t?.replayFields&&(void 0!==t.replayFields.llmContent||void 0!==t.replayFields.rawContent||(t.replayFields.contextMentions?.length??0)>0);if(!(r||t?.contentParts&&0!==t.contentParts.length||t?.mentions&&0!==t.mentions.refs.length||n))return;this.#V&&!t?.voiceTurn&&(this.#V.failed=!0,this.#V=null),(this.#I||this.#P||this.#M||this.#W)&&await this.#Ge(),this.stopSpeaking(),this.abortController?.abort(),this.#We(),this.#oe++,this.#$e();let o=t?.voiceTurn?.userMessageId,a=o?this.messages.find(e=>e.id===o&&"user"===e.role):void 0,s=a?.id??Dt(),i=Ot();this.#y=null;let l=t?.contentParts&&Xr(t.contentParts)?Jr:"",d={id:s,role:"user",content:r||l,createdAt:(new Date).toISOString(),sequence:this.#ye(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==r&&(a.llmContent=r),this.callbacks.onMessagesChanged([...this.messages])):this.#Ce(d),this.#ce(!0);let c=new AbortController;if(this.abortController=c,t?.mentions){let e=this.messages.find(e=>e.id===s)??d;if(await this.#et(e,r,t.mentions.finalize),c.signal.aborted||this.abortController!==c)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===s)??d,r=function(e){let t=function(e){let t=e?.text?.trim()??"";return t?function(e,t){let r="`".repeat(Math.max(3,function(e){let t=0;for(let r of e.split("\n")){let e=/^ {0,3}(`+)/.exec(r);e&&e[1].length>t&&(t=e[1].length)}return t}(t)+1));return`${r}${e}\n${t}\n${r}`}((e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text")(e),t):""}(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Zr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join("\n\n")}:{}}({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});r.contentParts&&(e.contentParts=r.contentParts),void 0!==r.llmContent&&(e.llmContent=r.llmContent),(r.contentParts||void 0!==r.llmContent)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(new Date).toISOString()}]:[...this.messages];try{await this.#Xe(p,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt})}catch(e){if("resuming"===this.status||this.#b)return;this.#V&&(this.#V.failed=!0);let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));if(!t){let t=co(e,this.config.errorMessage);if(t){let e={id:i,role:"assistant",createdAt:(new Date).toISOString(),content:t,sequence:this.#ye()};this.#Ce(e)}}this.#de("idle"),this.#ce(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(new Error(String(e))))}}resubmitFrom(e,t){let r=function(e,t){let r=e.findIndex(e=>e.id===t);if(-1===r||"user"!==e[r].role)return null;let n=r+1;for(;n<e.length&&"user"!==e[n].role;)n+=1;return{start:r,end:n}}(this.messages,e);if(!r)return!1;let n=this.messages[r.start],o=t.replacement,a=o?o.text:n.content,s=o?o.contentParts:n.contentParts;if(!(a?.trim()||(s?.length??0)>0||!o&&(n.llmContent?.trim()?.length??0)>0))return!1;let i=o?void 0:{...void 0!==n.llmContent&&{llmContent:n.llmContent},...void 0!==n.rawContent&&{rawContent:n.rawContent},...n.mentionContext&&{mentionContext:n.mentionContext},...n.contextMentions&&{contextMentions:n.contextMentions},...n.quote&&{quote:n.quote}},l=o?this.#tt(o.options):n.composerOptions,d=o?o.contentSegments:n.contentSegments,c=o?o.options?.quote:void 0,p=o?o.viaVoice:n.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,r.start),this.sendMessage(a??"",{...s?.length?{contentParts:[...s]}:{},...d?.length?{contentSegments:[...d]}:{},...l?{composerOptions:l}:{},...c?{quote:c}:{},...i&&Object.keys(i).length>0?{replayFields:i}:{},viaVoice:!0===p}),!0}#tt(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#I||this.#P||this.#M||this.#W)&&await this.#Ge(),this.abortController?.abort(),this.#$e();let e=Ot();this.#y=null,this.#ce(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if("resuming"===this.status||this.#b)return;let r=t instanceof Error&&("AbortError"===t.name||t.message.includes("aborted")||t.message.includes("abort"));if(!r){let r=co(t,this.config.errorMessage);if(r){let t={id:e,role:"assistant",createdAt:(new Date).toISOString(),content:r,sequence:this.#ye()};this.#Ce(t)}}this.#de("idle"),this.#ce(!1),this.abortController=null,r||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(new Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#y=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,n=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.#ce(!0);let o={};try{await this.client.processStream(e,e=>{let t=this.#m;this.#m=o;try{this.handleEvent(e)}finally{this.#m=t}},t?.assistantMessageId,t?.seedContent),this.#rt(o)}catch(e){if("resuming"===this.status||this.#b)return void this.#nt(o);this.#rt(o),this.#de("error"),0===this.webMcpResolveControllers.size&&(this.#ce(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:new Error(String(e)))}}#we(){let e=this.config.webmcp;!0===e?.enabled&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(!0===this.config.webmcp?.autoApprove?.(e))return Promise.resolve(!0)}catch{}let t={id:"webmcp-"+ ++this.#r,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(e=>{this.webMcpApprovalResolvers.set(r,e)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let n=this.messages.find(t=>t.id===e);n?.approval&&this.upsertMessage({...n,approval:{...n.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#ne;#oe;#ot(e){let t=this.#ne??={s:this,setStreaming:e=>this.#ce(e),appendMessage:e=>this.#Ce(e),nextSequence:()=>this.#ye(),settleApprovalPausedToolCall:e=>this.#at(e),resumeAfter:e=>this.#f?.executionId===e?this.#f.lastEventId:void 0},r=Hn();if(r)return e(r,t);let n=this.#oe;return Rn().then(r=>n===this.#oe?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:new Error(String(e)))})}resolveApproval(e,t,r){return this.#ot((n,o)=>n.resolveApproval(o,e,t,r))}resolveAskUserQuestion(e,t){return this.#ot((r,n)=>r.resolveAskUserQuestion(n,e,t))}resolveWebMcpToolCall(e){return this.#ot((t,r)=>t.resolveWebMcpToolCall(r,e))}persistAskUserQuestionProgress(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(t=>t.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ae(e){let t=e.agentMetadata?.executionId,r=e.toolCall?.id;if(!t||!r){let t=this.#t;return void queueMicrotask(()=>{t===this.#t&&this.resolveWebMcpToolCall(e)})}let n=this.webMcpAwaitBatches.get(t);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,n)),!n.seen.has(r)&&(n.seen.add(r),n.snapshots.push(e))}#ge(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#t;queueMicrotask(()=>{if(e===this.#t)for(let e of[...this.webMcpAwaitBatches.keys()])this.#st(e)})}#st(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;1===r.length?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.#ot((t,n)=>t.resolveWebMcpToolCallBatch(n,e,r))}#We(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.#t++}cancel(){this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ce(!1),this.#de("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.messages=[],this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ce(!1),this.#de("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#e}selectArtifact(e){this.#e=e,this.#xe()}clearArtifacts(){this.#Re()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,r="markdown"===e.artifactType?{id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,r),this.#e=t,this.#xe(),!1!==e.transcript&&this.#it(r),r}#it(e){let t=`artifact-ref-${e.id}`,r=Fn(On(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...void 0!==e.markdown?{markdown:e.markdown}:{}}),n=this.messages.find(e=>e.id===t);if(n)return n.rawContent=r,n.streaming=!1,void this.callbacks.onMessagesChanged([...this.messages]);this.injectAssistantMessage({id:t,content:"",rawContent:r})}#Ze(){let e=!1;for(let t of this.artifacts.values()){let r=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!r)continue;let n=Fn(On(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...void 0!==t.markdown?{markdown:t.markdown}:{}});r.rawContent!==n&&(r.rawContent=n,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Re(){0===this.artifacts.size&&null===this.#e||(this.artifacts.clear(),this.#e=null,this.#xe())}#xe(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#e})}#fe(e){switch(e.type){case"artifact_start":"markdown"===e.artifactType?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.#e=e.id;break;case"artifact_delta":{let t=this.artifacts.get(e.id);"markdown"===t?.artifactType&&(t.markdown=(t.markdown??"")+e.artDelta);break}case"artifact_update":{let t=this.artifacts.get(e.id);"component"===t?.artifactType&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case"artifact_complete":{let t=this.artifacts.get(e.id);t&&(t.status="complete");break}default:return}this.#xe()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#$e(),this.#We(),this.#oe++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#be(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#ye()}))),this.#ce(!1),this.#de("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:"complete"});this.#e=t,this.#xe()}#se(e){let t=this.agentExecution?.executionId;if(!t||!this.#y||"running"!==this.agentExecution?.status)return;let r=null===this.#f;this.#f={executionId:t,lastEventId:e,assistantMessageId:this.#y,status:"running"},this.#lt(r)}#ie(){return null!==this.#f&&"function"==typeof this.config.reconnectStream&&!0!==this.abortController?.signal.aborted&&0===this.webMcpResolveControllers.size&&0===this.webMcpAwaitBatches.size&&!this.#pe()}#pe(){return this.messages.some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata?.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)}#le(){this.#b||!this.#f||"function"!=typeof this.config.reconnectStream||(this.#b=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#f}),this.#ce(!0),this.#de("resuming"),this.#dt().then(e=>{this.#b&&this.#f&&e.begin()}))}#dt(){return this.#v?Promise.resolve(this.#v):(this.#w||(this.#w=so().then(({createReconnectController:e})=>{let t=e(this.#ct());return this.#v=t,t}),this.#w.catch(()=>{this.#w=null})),this.#w)}#ct(){let e=this;return{get config(){return e.config},getResumable:()=>e.#f,clearResumable:()=>e.#ue(),getStatus:()=>e.status,setStatus:t=>e.#de(t),setStreaming:t=>e.#ce(t),setReconnecting:t=>{e.#b=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,n)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:t=>e.#Ce(t),nextSequence:()=>e.#ye(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>co(new Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#b?this.#v?.wake():this.#le()}resumeFromHandle(e){if("function"!=typeof this.config.reconnectStream||this.#b)return;let t=this.#pt();t||(t=Ot(),this.#Ce({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#ye()})),this.#y=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#f={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#le()}#pt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if("assistant"===t.role&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if("user"===t.role)break}return null}#$e(){this.#b=!1,this.#v?.teardown(),this.#ue()}#ue(){this.#C&&(clearTimeout(this.#C),this.#C=null);let e=null!==this.#f;this.#f=null,e&&this.config.onExecutionState?.(null)}#lt(e){let t=this.config.onExecutionState;if(t){if(e)return this.#C&&(clearTimeout(this.#C),this.#C=null),void t(this.#f);this.#C||(this.#C=setTimeout(()=>{this.#C=null,this.config.onExecutionState?.(this.#f)},500))}}getResumableHandle(){return this.#f}#de(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ce(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#rt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||t.provider&&"browser"!==t.provider&&("runtype"!==t.provider||!t.browserFallback))return;let r=[...this.messages].reverse().find(e=>"assistant"===e.role&&e.content&&!e.voiceProcessing);if(!r||e&&!e.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id))return void this.ttsSpokenMessageIds.delete(r.id);let n=eo(r.content);n.trim()&&this.readAloud.play(r.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return _n(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=eo(t.content||"");if(!r.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:n?.voice,rate:n?.rate,pitch:n?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#rt(e){for(let[t,r]of[...this.#h])r===e&&(this.#h.delete(t),this.#at(t))}#nt(e){for(let[t,r]of this.#h)r===e&&this.#h.set(t,void 0)}#at(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,n=r&&this.messages.find(e=>e.toolCall?.id===r),o=n&&n.toolCall;if(!o||"complete"===o.status||"pending"===t.status)return;let a={...o,status:"complete",approvalStatus:t.status,completedAt:Date.now(),..."approved"===t.status?{superseded:!0}:{success:!1,error:"denied"===t.status?"Denied":"Approval timed out"}};this.upsertMessage({...n,streaming:!1,toolCall:a})}#Ce(e){let t=this.#Te(e);this.messages=this.#be([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Te(e),r=this.messages.findIndex(e=>e.id===t.id);-1!==r?(this.messages=this.messages.map((e,n)=>{if(n!==r)return e;let o={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(o.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(o.agentMetadata={...o.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&o.agentMetadata&&!o.agentMetadata.clientToolAnswer&&(o.agentMetadata={...o.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,n=t.approval;o.approval={...r,...n,executionId:n.executionId||r.executionId,toolName:n.toolName||r.toolName,description:n.description||r.description,toolType:n.toolType??r.toolType,reason:n.reason??r.reason,parameters:n.parameters??r.parameters,toolCallId:n.toolCallId??r.toolCallId}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&po(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),n=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&po(a)&&"complete"===e.toolCall?.status;(r||n||s)&&(o.agentMetadata={...o.agentMetadata??{},awaitingLocalTool:!1},o.toolCall=e.toolCall,o.streaming=e.streaming)}return o}),this.messages=this.#be(this.messages),this.callbacks.onMessagesChanged([...this.messages])):this.#Ce(t)}#Te(e){return void 0!==e.sequence?{...e}:{...e,sequence:this.#ye()}}#ye(){return this.#g++}#be(e){return[...e].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o!==a?o-a:e.id.localeCompare(t.id)})}},ho={add:e=>async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;an(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}(e)},mo={allowedTypes:on,maxFileSize:10485760,maxFiles:4};function go(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var fo=class e{constructor(e={}){this.attachments=[],this.#h=null,this.#m=new Map,this.#g=!1,this.config={allowedTypes:e.allowedTypes??mo.allowedTypes,maxFileSize:e.maxFileSize??mo.maxFileSize,maxFiles:e.maxFiles??mo.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#h;#m;#g;#f(){return"function"==typeof this.config.adapter?.add}#y(){return this.#f()?this.config.adapter:ho}setPreviewsContainer(e){this.#h=e}remountPreviews(e){if(this.#h=e,e){e.innerHTML="";for(let e of this.attachments)this.#e(e)}this.#n()}updateConfig(e){void 0!==e.allowedTypes&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:mo.allowedTypes),void 0!==e.maxFileSize&&(this.config.maxFileSize=e.maxFileSize),void 0!==e.maxFiles&&(this.config.maxFiles=e.maxFiles),void 0!==e.onFileRejected&&(this.config.onFileRejected=e.onFileRejected),void 0!==e.onAttachmentsChange&&(this.config.onAttachmentsChange=e.onAttachmentsChange),void 0!==e.adapter&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>"ready"===e.status)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>null!==e)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||0===e.length||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#g)return;let t=[];for(let r of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(r,"count");continue}let e=sn(r,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes("type")?"type":"size";this.config.onFileRejected?.(r,t);continue}let n={id:go(),file:r,previewUrl:an(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#f()?"uploading":"processing",progress:this.#f()?0:void 0};this.attachments.push(n),this.#e(n),t.push(n)}this.#n(),this.#C(),await Promise.all(t.map(e=>this.#b(e)))}async#b(e){let t=new AbortController;this.#m.set(e.id,t);let r=()=>this.#g||t.signal.aborted||this.#m.get(e.id)!==t||!this.attachments.includes(e);try{let n=await this.#y().add(e.file,{signal:t.signal,onProgress:t=>{r()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#t(e),this.#C())}});if(r())return;e.contentPart=n,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(r())return;e.status="error",e.progress=void 0,e.error=t instanceof Error?t.message:String(t??"Upload failed")}finally{this.#m.get(e.id)===t&&this.#m.delete(e.id)}this.#t(e),this.#C()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||"error"!==t.status||this.#g||(t.status=this.#f()?"uploading":"processing",t.progress=this.#f()?0:void 0,t.error=void 0,this.#t(t),this.#C(),this.#b(t))}#v(e){let t=this.#m.get(e);t&&(this.#m.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(-1===t)return;let r=this.attachments[t];this.#v(e),r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let n=this.#h?.querySelector(`[data-attachment-id="${e}"]`);n&&n.remove(),"ready"===r.status&&r.contentPart&&this.#w(r.contentPart),this.#n(),this.#C()}#w(e){let t=this.config.adapter?.remove;if(t)try{let r=t(e,{signal:(new AbortController).signal});r&&"function"==typeof r.catch&&r.catch(e=>{console.error("[AttachmentManager] adapter.remove failed:",e)})}catch(e){console.error("[AttachmentManager] adapter.remove failed:",e)}}clearAttachments(){for(let e of this.attachments)this.#v(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#m.clear(),this.#h&&(this.#h.innerHTML=""),this.#n(),this.#C()}destroy(){if(!this.#g){this.#g=!0;for(let e of this.#m.values())e.abort();this.#m.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#h=null}}#C(){this.#g||this.config.onAttachmentsChange?.(this.getAttachments())}#e(e){if(!this.#h)return;let t=an(e.file),r=ne("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let t=ne("img");t.src=e.previewUrl,t.alt=e.file.name,t.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",t.style.width="48px",t.style.height="48px",t.style.objectFit="cover",t.style.borderRadius="8px",r.appendChild(t)}else{let t=ne("div");t.style.width="48px",t.style.height="48px",t.style.borderRadius="8px",t.style.backgroundColor="var(--persona-container, #f3f4f6)",t.style.border="1px solid var(--persona-border, #e5e7eb)",t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="center",t.style.justifyContent="center",t.style.gap="2px",t.style.overflow="hidden";let n=function(e){return"application/pdf"===e||e.startsWith("text/")||e.includes("word")?S:e.includes("excel")||e.includes("spreadsheet")?C:"application/json"===e?x:k}(e.file.type),o=I(n,20,"var(--persona-muted, #6b7280)",1.5);o&&t.appendChild(o);let a=ne("span");a.textContent=function(e,t){let r=function(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}(e.file.type,e.file.name),a.style.fontSize="8px",a.style.fontWeight="600",a.style.color="var(--persona-muted, #6b7280)",a.style.textTransform="uppercase",a.style.lineHeight="1",t.appendChild(a),r.appendChild(t)}let n=oe("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),o=ne("div","persona-attachment-progress");o.appendChild(ne("div","persona-attachment-progress__bar"));let a=oe("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),s=xe("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);s?a.appendChild(s):a.textContent="↻",a.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),n.append(o,a),r.appendChild(n);let i=ne("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");i.type="button",i.setAttribute("aria-label","Remove attachment"),i.style.position="absolute",i.style.top="-4px",i.style.insetInlineEnd="-4px",i.style.width="18px",i.style.height="18px",i.style.borderRadius="50%",i.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",i.style.border="none",i.style.cursor="pointer",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.padding="0";let l=I(M,10,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):(i.textContent="×",i.style.color="var(--persona-text-inverse, #ffffff)",i.style.fontSize="14px",i.style.lineHeight="1"),i.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(i),this.#h.appendChild(r),this.#r(r,e)}#t(e){let t=this.#h?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#r(t,e)}#r(e,t){e.dataset.status=t.status;let r="ready"!==t.status&&"error"!==t.status;e.setAttribute("aria-busy",r?"true":"false"),e.title="error"===t.status?`${t.file.name}: ${t.error??"Upload failed"}`:t.file.name;let n=e.querySelector(".persona-attachment-progress__bar");if(n){let e=t.progress;n.style.width="number"==typeof e?`${Math.round(100*e)}%`:""}}#n(){this.#h&&(this.#h.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:r,adapter:t?.adapter})}},yo=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function bo(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,r=null,n=!1,o=!1,a=()=>(r||(r=(()=>{let t=e.preparing?"preparing":e.streaming?"streaming":"idle";return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:"idle"!==t||e.sendDisabled||e.inputDisabled})})()),r),s=()=>{if(n=!1,o||0===t.size)return;let e=a();for(let r of[...t])try{r(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",e)}},i=()=>{r=null,!o&&!n&&(n=!0,queueMicrotask(s))};return{getState:a,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,i())},setAttachments:t=>{((e,t)=>e.length===t.length&&e.every((e,r)=>{let n=t[r];return e.id===n.id&&e.name===n.name&&e.mimeType===n.mimeType&&e.size===n.size&&e.status===n.status&&e.progress===n.progress&&e.error===n.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{yo(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{yo(e.activeModeIds,t)||(e.activeModeIds=[...t],i())},setQuote:t=>{let r=e.quote;r?.text===t?.text&&r?.messageId===t?.messageId&&r?.sourceLabel===t?.sourceLabel||(e.quote=t?{...t}:void 0,i())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,i())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,i())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,i())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,i())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,i())},flush:()=>{n&&s()},destroy:()=>{o=!0,n=!1,t.clear()}}}var vo=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},wo=(e,t)=>{let r=ne("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r},xo=8,Co=8,So=200,ko=300,Ao=0,Mo=e=>Math.max(0,e),Io=new WeakMap,To="data-persona-tooltip-suppressed",Eo=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Lo=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Po=[...["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 Bo(e){Io.get(e.anchor)?.destroy();let t,{anchor:r,trigger:n=r,text:o,hint:a,enabled:s=!0,gap:i=xo,viewportPadding:l=Co}=e,d=()=>r.ownerDocument,c=()=>d().defaultView??window,p=null,u=null,h=null,m=null,g=!1,f=!1,y=!1,b=()=>("function"==typeof o?o():o).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>Mo(e.delayMs??So),x=()=>{void 0!==t&&(c().clearTimeout(t),t=void 0)},C=()=>{x();let t=null!==p;m?.(),m=null,p?.remove(),p=null,u=null,h=null,t&&(e=>{Ao=e>0?Date.now()+e:0})(Mo(e.skipDelayMs??ko))},S=()=>{if(!p)return;let e=d(),t=c(),n=r.getBoundingClientRect(),o=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-o.width,h=n.left+n.width/2-o.width/2,m=Lo(h,l,u),g=n.top-l,f=s-l-n.bottom,y=g>=o.height+i||g>=f?"top":"bottom",b="top"===y?n.top-i-o.height:n.bottom+i,v=s-l-o.height,w=Lo(b,l,v),x=n.left+n.width/2,C=Math.max(10,o.width-10),S=Lo(x-m,10,C);p.dataset.placement=y,p.style.left=`${m}px`,p.style.top=`${w}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${S}px`)},k=()=>{if(y||!s||p||!r.isConnected||(e=>"function"==typeof e.closest&&null!==e.closest(`[${To}]`))(r))return;let e=b(),t=(e=>{let t=e.getRootNode?.();return Eo(t)?t:e.ownerDocument.body})(r);if(!e||!t)return;let n=d(),o=c();p=n.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(un);let a=o.getComputedStyle?.(r);if(a){for(let e of Po){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=n.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=n.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=n.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),S(),p.dataset.state="open";let g=()=>{r.isConnected?(u&&(u.textContent=b()),h&&(h.textContent=v()),S()):C()};o.addEventListener("scroll",g,!0),o.addEventListener("resize",g);let f=r.getRootNode(),w=Eo(f)?f:n.documentElement,x=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||C()});x?.observe(w,{childList:!0,subtree:!0}),m=()=>{o.removeEventListener("scroll",g,!0),o.removeEventListener("resize",g),x?.disconnect()}},A=()=>{g||f?(e=>{if(!y&&!p){if(x(),e||w()<=0||Date.now()<Ao)return void k();t=c().setTimeout(()=>{t=void 0,k()},w())}})(f):C()},M=()=>{let e=c();(!e.matchMedia||!e.matchMedia("(hover: none)").matches)&&(g=!0,A())},I=()=>{g=!1,A()},T=()=>{try{f=r.matches(":focus-visible")}catch{f=!0}A()},E=()=>{f=!1,A()},L=()=>{g=!1,f=!1,C()},P=e=>{"Escape"===e.key&&L()};n.addEventListener("mouseenter",M),n.addEventListener("mouseleave",I),r.addEventListener("focus",T),r.addEventListener("blur",E),r.addEventListener("keydown",P),r.addEventListener("click",L);let B={get isOpen(){return null!==p},show:k,hide:C,reposition:S,destroy:()=>{y||(y=!0,C(),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",I),r.removeEventListener("focus",T),r.removeEventListener("blur",E),r.removeEventListener("keydown",P),r.removeEventListener("click",L),Io.delete(r))}};return Io.set(r,B),B}function No(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let r=t.getComputedStyle(e).lineHeight;if(!r||!r.trim().endsWith("px"))return 20;let n=parseFloat(r);return Number.isFinite(n)&&n>0?n:20}function Ro(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function Ho(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||"function"!=typeof t.matchMedia)return!1;try{return!0===t.matchMedia("(pointer: coarse)").matches}catch{return!1}}function $o(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function Wo(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"!==(e.submitKey??"enter")||$o(e)?"enter":"send"}(t))}function Do(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let n=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};n("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),n("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),n("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),n("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function Oo(e){return!0===e?{disabled:!0}:e&&"object"==typeof e?{disabled:!0,reason:"string"==typeof e.reason&&e.reason?e.reason:void 0}:{disabled:!1}}var Fo="persona-composer-control",zo="persona-composer-control--glyph",qo=24,jo=(e,t,r)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let o=n.getComputedStyle(e);for(let e of r){let r=o.getPropertyValue(e).trim();r?t.style.setProperty(e,r):t.style.removeProperty(e)}},_o=(e,t)=>{let r=ne("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??U,r.dir="auto",Wo(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ho(r)}),Do(r,e?.composer?.inputAttributes),r.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",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=Ro(e?.composer?.maxLines,t?.defaultMaxLines??3),o=20*n+"px";return r.style.maxHeight=o,r.style.overflowY="auto",r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:()=>{r.addEventListener("input",()=>{r.style.height="auto";let e=Math.min(r.scrollHeight,(()=>{let e=r.style.maxHeight;if(e!==o){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=n*No(r);return o=`${t}px`,r.style.maxHeight=o,t})());r.style.height=`${e}px`})}}},Vo=(e,t,r="send")=>{let n=oe("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":r,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Uo=e=>{let t=e?.sendButton??{},r=t.useIcon??!1,n=t.iconText??"↑",o=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",l=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,p=t.size,u=parseFloat(p??"")||40,h=t.backgroundColor,m=t.textColor,g=ne("div","persona-send-button-wrapper"),f=oe("button",{className:ae("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?`persona-flex persona-items-center persona-justify-center ${Fo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!h&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:r?p:void 0,height:r?p:void 0,minWidth:r?p:void 0,minHeight:r?p:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":m||void 0,backgroundColor:r&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:r?"0":t.paddingX||void 0,paddingRight:r?"0":t.paddingX||void 0,paddingTop:r?"0":t.paddingY||void 0,paddingBottom:r?"0":t.paddingY||void 0}}),y=null,b=null,v=null;if(r){let e=parseFloat(t.iconSize??"")||Math.round(.5*u),r=t.iconStrokeWidth??2,s=m?.trim()||"currentColor";if(o&&(y=xe(o,e,s,r)),b=xe(a,e,s,r),!t.iconSize)for(let t of[y,b])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);y&&b?(v=Vo(y,b),f.appendChild(v)):y?f.appendChild(y):(f.textContent=n,b=null)}else f.textContent=l;f.setAttribute("aria-label",s),g.appendChild(f),Bo({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??"",enabled:c});let w="send";return{button:f,wrapper:g,setMode:e=>{if(e===w)return;w=e;let t="stop"===e?i:s;f.setAttribute("aria-label",t),f.setAttribute("data-persona-send-mode",e),r?(f.querySelector("[data-persona-glyph-stack]")??v)?.setAttribute("data-mode",e):f.textContent="stop"===e?d:l},glyphStack:v}},Ko=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled)return null;let r=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),n="runtype"===t.provider?.type,o="custom"===t.provider?.type;if(!(r||n||o))return null;let a=t.iconName??"mic",s=t.iconSize,i=parseFloat(s??"")||qo,l=t.backgroundColor??e?.sendButton?.backgroundColor,d=t.iconColor??e?.sendButton?.textColor,c=ne("div","persona-send-button-wrapper"),p=oe("button",{className:ae("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fo,!s&&zo),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",color:d||"var(--persona-text, #111827)",backgroundColor:l||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}}),u=xe(a,i,d||"currentColor",1.5);u?p.appendChild(u):p.textContent="🎤",c.appendChild(p);let h=t.tooltipText??"Start voice recognition",m=t.showTooltip??!1;return Bo({anchor:p,trigger:c,text:()=>p.getAttribute("aria-label")??h,enabled:m}),{button:p,wrapper:c}},Jo=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=ne("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let n=ne("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??on).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let o=t.buttonIconName??"paperclip",a=ne("div","persona-send-button-wrapper"),s=oe("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Fo} ${zo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=xe(o,qo,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),n.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Bo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:n,previewsContainer:r}},Go=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",n=ne("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status",""),Re(n,t,"idle");let o=t.idleText??"Online";if(t.idleLink){let e=ne("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=o,e.style.color="inherit",e.style.textDecoration="none",n.appendChild(e)}else n.textContent=o;return n},Yo=()=>oe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Xo(e){let{anchor:t,content:r,placement:n="bottom-start",offset:o=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:i,zIndex:l=2147483e3,onOpen:d,onDismiss:c}=e,p=e.container??function(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}(t),u=!1,h=null,m=()=>{if(!u)return;let e=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${e.width}px`),s&&(r.style.maxWidth=`${e.width}px`);let l=r.getBoundingClientRect(),d=i?.()??null,c=null!=d?e.top+d:e.top,p="top-start"===n||"top-end"===n?c-o-l.height:e.bottom+o,h="bottom-end"===n||"top-end"===n?e.right-l.width:e.left,m=s?.()??null;if(null!=m){let t=Math.max(e.left,e.right-l.width);h=Math.min(Math.max(e.left+m,e.left),t)}r.style.top=`${p}px`,r.style.left=`${h}px`},g=()=>{u&&(u=!1,h&&(h(),h=null),r.remove())},f=()=>{if(u)return;u=!0,null!=l&&(r.style.zIndex=String(l)),p.appendChild(r),m();let e=(t.ownerDocument??document).defaultView??window,n=t.ownerDocument??document,o=()=>{if(!t.isConnected)return g(),void c?.("anchor-removed");m()},a=e=>{let n="function"==typeof e.composedPath?e.composedPath():[];n.includes(r)||n.includes(t)||(g(),c?.("outside"))},s=e.setTimeout(()=>{n.addEventListener("pointerdown",a,!0)},0);e.addEventListener("scroll",o,!0),e.addEventListener("resize",o),h=()=>{e.clearTimeout(s),n.removeEventListener("pointerdown",a,!0),e.removeEventListener("scroll",o,!0),e.removeEventListener("resize",o)},d?.()};return{get isOpen(){return u},open:f,close:g,toggle:()=>u?g():f(),reposition:m,destroy:g}}var Qo=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Zo="data-persona-menu-focus",ea=new Set(["ArrowDown","ArrowUp","Home","End"]);function ta(e){return"menuitem"===e.getAttribute("role")?e:e.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??e}var ra=1e3,na="data-persona-composer-action",oa="data-persona-composer-disable-when-streaming";function aa(e){let t=e.clientWidth;if(!t)return 0;let r=e.ownerDocument?.defaultView;if(!r?.getComputedStyle)return t;let n=r.getComputedStyle(e),o=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-o)}var sa=(e,t)=>{!e||typeof console>"u"||console.warn(t)},ia=e=>"plugin"===e.source?`plugin "${e.pluginId}"`:"config"===e.source?"composer.actions":"a core built-in",la=(e,t,r)=>void 0===e?r:"function"==typeof e?!0===e(t):!0===e;function da(e,t){if(!e||"always"===e)return!0;let r=(e=>"streaming"===e.phase||e.text.trim().length>0||e.attachments.length>0)(t);return"when-text"===e?r:!r}var ca=e=>"custom"===e.kind,pa=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e;function ua(e){let t=new Map,r=[],n=!1,o=()=>e.getButtonSize?.(),a=(e,t)=>{let r=e.button;if(!r)return;if(r.setAttribute("aria-label",t.label),void 0===t.pressed?r.removeAttribute("aria-pressed"):r.setAttribute("aria-pressed",t.pressed?"true":"false"),r.toggleAttribute(oa,!0===t.disableWhenStreaming),"menu"===e.mode)return e.tooltip?.destroy(),e.tooltip=void 0,void((e,t)=>{let r=e.button;if(!r)return;r.setAttribute("role","menuitem"),r.setAttribute("tabindex","-1"),r.className="persona-composer-overflow-menu__item";for(let e of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])r.style[e]="";r.style.lineHeight="1",t.tooltipText?r.setAttribute("title",t.tooltipText):r.removeAttribute("title"),r.replaceChildren();let n=ne("span","persona-composer-overflow-menu__icon");if(t.iconName){let e=xe(t.iconName,16,"currentColor",1.5);e&&n.appendChild(e)}let o=ne("span","persona-composer-overflow-menu__label");o.textContent=t.shortLabel??t.label,r.append(n,o)})(e,t);r.removeAttribute("role"),r.removeAttribute("tabindex"),r.removeAttribute("title");let n=o(),a=!!t.shortLabel;if(r.className=ae("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Fo,zo,a&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),r.style.width=n&&!a?n:"",r.style.height=n??"",r.style.minWidth=n&&!a?n:"",r.style.minHeight=n??"",r.style.fontSize=a?"":"18px",r.style.lineHeight="1",r.style.color=t.iconColor??"",r.style.backgroundColor=t.backgroundColor??"",r.replaceChildren(),t.iconName){let e=xe(t.iconName,qo,"currentColor",1.5);e&&r.appendChild(e)}if(a){let e=ne("span","persona-composer-action-button__label");e.textContent=t.shortLabel,r.appendChild(e)}else r.firstChild||(r.textContent=t.label);e.tooltip?.destroy(),e.tooltip=Bo({anchor:r,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,r)=>{let n=t.action,o=oe("button",{attrs:{type:"button"}}),s=o;if("bar"===r){let e=ne("div","persona-send-button-wrapper");e.appendChild(o),s=e}s.setAttribute(na,t.id);let i={resolved:t,element:s,button:o,owned:!0,managed:!0,busy:!1,visible:!0,mode:r},l=t=>{if(t.preventDefault(),t.stopPropagation(),i.busy||o.disabled)return;let r,n=i.resolved.action;"menu"===i.mode&&p?.close(!0);try{r=n.onSelect(e.actionContext,t)}catch(t){return void e.reportError(t,{actionId:i.resolved.id})}!r||"function"!=typeof r.then||(i.busy=!0,o.setAttribute("aria-busy","true"),r.catch(t=>{e.reportError(t,{actionId:i.resolved.id})}).finally(()=>{i.busy=!1,o.removeAttribute("aria-busy")}))};return o.addEventListener("click",l),i.detach=()=>o.removeEventListener("click",l),a(i,n),i},i=(t,r)=>{if(t.builtIn){let e=t.builtIn.element;return e?{resolved:t,element:e,owned:!1,managed:!0===t.builtIn.managed,busy:!1,visible:!0,mode:"bar"}:null}let n=t.action;return n?ca(n)?(t=>{let r,n=t.action;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(r){return e.reportError(r,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(na,t.id),r.element.toggleAttribute(oa,!0===n.disableWhenStreaming),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:"bar"}):null})(t):s(t,r):null},l=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(r){e.reportError(r,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let r=0;r<t.length;r++){let n=t[r];if(!n.managed)continue;let o=null;for(let n=r+1;n<t.length;n++){let r=t[n];if(!r.managed&&r.element.parentElement===e){o=r.element;break}}o?(n.element.parentElement!==e||n.element.nextSibling!==o)&&e.insertBefore(n.element,o):e.lastChild!==n.element&&e.appendChild(n.element)}},c=(e,t)=>{if(e.button)return void(e.button.disabled=t);if(!e.owned)return;let r=e.element;r.toggleAttribute("data-disabled",t),r.setAttribute("aria-disabled",t?"true":"false");let n=r instanceof HTMLButtonElement||r instanceof HTMLSelectElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement?r:r.querySelector("button, select, input, textarea");n&&(n.disabled=t)},p=null,u=null,h=null,m=0,g=(e,t,r)=>{if(!t)return"bar";if(e.resolved.builtIn){let r=(e=>"core:attachment"===e?"attachments":e.startsWith("core:mention")?"mentions":null)(e.resolved.id);return r&&t.includeBuiltIns?.includes(r)?"menu":"bar"}let n=e.resolved.presentation;return"overflow"===n||"auto"===n&&r?"menu":"bar"},f=e=>{let t=e.menuSlot;if(!t)return;if(!(e=>0===function(e){let t="",r=e=>{if(e.nodeType===Node.TEXT_NODE)return void(t+=e.nodeValue??"");if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e;"function"==typeof n.matches&&n.matches('.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]')||e.childNodes.forEach(r)};return r(e),t.trim()}(e).length)(e.element))return e.menuLabel?.remove(),void(e.menuLabel=void 0);let r=(e=>{let t=pa(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""})(e.element);if(!r)return e.menuLabel?.remove(),void(e.menuLabel=void 0);e.menuLabel||(e.menuLabel=ne("span","persona-composer-overflow-menu__label")),e.menuLabel.textContent!==r&&(e.menuLabel.textContent=r),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)},y=(e,r)=>{if(e.mode===r)return e;let n=e.resolved.action;if(n&&!ca(n)){l(e),t.delete(e.resolved.id);let n=s(e.resolved,r);return t.set(e.resolved.id,n),n}if("menu"===r){let t=oe("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[To]:""}});t.appendChild(e.element),function(e){Io.get(e)?.hide()}(pa(e.element)),e.menuSlot=t;let r=t=>{let r=pa(e.element);if(r.disabled)return;let n=t.target===r||r.contains(t.target);p?.close(!0),n||r.click()};t.addEventListener("click",r,!0),e.detachMenuSlot=()=>t.removeEventListener("click",r,!0),e.managed=!0,f(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=r,e},b=()=>{if(n)return;let a=e.getBindings();if(!a)return;let s=e.getState(),i="streaming"===s.phase,l=(()=>{let t=e.getOverflow?.();return!0===t?.enabled?t:void 0})();l&&(e=>{u!==e&&(h?.disconnect(),u=e,m=aa(e),!(typeof ResizeObserver>"u")&&(h=new ResizeObserver(t=>{let r=t[t.length-1]?.contentRect?.width??aa(e);r!==m&&(m=r,b())}),h.observe(e)))})(a.footer);let v=!!l&&((e,t)=>{let r=function(e,t){if(void 0===e)return null;if("number"==typeof e)return Number.isFinite(e)?e:null;let r=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(r))return r;let n=ne("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let o=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(o)&&o>0?o:Number.isFinite(r)?r:null}(e.collapseAutoActionsBelow,t);if(null===r)return!1;let n=m||aa(t);return n>0&&n<r})(l,a.footer),w={start:[],end:[]},x=[];for(let e of r){let r=t.get(e.id);if(!r)continue;let n=e.action,o=!n||la(n.visible,s,!0)&&da(n.visibility,s);if(r.visible!==o&&(r.visible=o,!o&&r.managed&&(r.menuSlot??r.element).remove()),o){if(r=y(r,g(r,l,v)),n){let e=la(n.disabled,s,!1)||!0===n.disableWhenStreaming&&i;c(r,e),!ca(n)&&void 0!==n.pressed&&r.button?.setAttribute("aria-pressed",n.pressed?"true":"false")}"menu"===r.mode?(f(r),x.push(r)):w[e.placement].push(r)}}if(x.length>0){let t=(p?p.setLabel(e.getOverflowLabel?.()??"More actions"):p=function(e){let t=e.label,r=!1,n=ne("div","persona-send-button-wrapper"),o=oe("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Fo} ${zo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(o);let a=oe("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),s=()=>{let t=e.getButtonSize?.()??"";o.style.width=t,o.style.height=t,o.style.minWidth=t,o.style.minHeight=t,o.style.lineHeight="1",o.replaceChildren();let r=xe("plus",qo,"currentColor",1.5);r?o.appendChild(r):o.textContent="+"},i=()=>{o.setAttribute("aria-label",t),o.setAttribute("title",t),a.setAttribute("aria-label",t)};i(),s();let l=[],d=-1,c=!1,p=()=>{let e=(()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null})();for(let t of l){let r=!!e&&ta(t)===e;t.toggleAttribute(Zo,r&&c)}},u=()=>l.filter(e=>e.isConnected||a.contains(e)).map(ta).filter(e=>!(e=>!0===e.disabled||"true"===e.getAttribute("aria-disabled"))(e)),h=(e,t)=>{e.forEach((e,r)=>{e.setAttribute("tabindex",r===t?"0":"-1")})},m=e=>{let t=u();if(0===t.length)return;let r=(e%t.length+t.length)%t.length;d=r,h(t,r),t[r].focus(),p()},g=()=>n.ownerDocument??document,f=null,y=null,b=null,v=()=>{f&&(g().removeEventListener("focusin",f,!0),f=null)},w=()=>{y&&(a.removeEventListener("focusin",y),y=null),b&&(a.removeEventListener("pointerdown",b,!0),b=null)},x=null,C=()=>!0===x?.isOpen,S=(e=!1)=>{if(C()){x?.close(),o.setAttribute("aria-expanded","false"),v(),w(),d=-1,c=!1;for(let e of l)e.removeAttribute(Zo);e&&o.focus()}},k=(e=0,t=!1)=>{if(r||C())return;c=t,jo(o,a,Qo),(x||(x=Xo({anchor:o,content:a,placement:"top-start",offset:6,onDismiss:()=>{o.setAttribute("aria-expanded","false"),v()}})),x).open(),o.setAttribute("aria-expanded","true");let s=u();h(s,-1),m(e<0?s.length-1:e),f=e=>{let t="function"==typeof e.composedPath?e.composedPath():[];t.includes(a)||t.includes(n)||S()},g().addEventListener("focusin",f,!0),y=()=>p(),a.addEventListener("focusin",y),b=()=>{c=!1},a.addEventListener("pointerdown",b,!0)},A=e=>{e.preventDefault(),e.stopPropagation(),C()?S(!0):k(0)},M=e=>{if("ArrowDown"===e.key||"Enter"===e.key||" "===e.key)return e.preventDefault(),c=!0,void(C()?m(0):k(0,!0));"ArrowUp"===e.key&&(e.preventDefault(),c=!0,C()?m(-1):k(-1,!0))},I=e=>{switch(ea.has(e.key)&&(c=!0),e.key){case"ArrowDown":return e.preventDefault(),void m(d+1);case"ArrowUp":return e.preventDefault(),void m(d-1);case"Home":return e.preventDefault(),void m(0);case"End":return e.preventDefault(),void m(u().length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void S(!0);case"Tab":return void S(!0)}};return o.addEventListener("click",A),o.addEventListener("keydown",M),a.addEventListener("keydown",I),{trigger:n,triggerButton:o,panel:a,setItems:e=>{for(let t of l)e.includes(t)||t.removeAttribute(Zo);if(l=[...e],!C())return;let t=u();h(t,Math.min(d,t.length-1)),p()},isOpen:C,open:()=>k(0),close:S,setLabel:e=>{e!==t&&(t=e,i())},applyButtonSize:s,destroy:()=>{r=!0,v(),w(),o.removeEventListener("click",A),o.removeEventListener("keydown",M),a.removeEventListener("keydown",I),x?.destroy(),x=null,n.remove(),a.remove(),l=[]}}}({label:e.getOverflowLabel?.()??"More actions",getButtonSize:o}),p);((e,t)=>{let r=t.map(e=>e.menuSlot??e.element);for(r.forEach((t,r)=>{let n=e.children[r];n!==t&&(n?e.insertBefore(t,n):e.appendChild(t))});e.children.length>r.length;)e.lastElementChild?.remove()})(t.panel,x),t.setItems(x.map(e=>e.menuSlot??e.element)),t.applyButtonSize();let r=Number.isFinite(l?.order)?l?.order:900,n=w.start.findIndex(e=>e.resolved.order>r),a={resolved:{id:"core:overflow",placement:"start",presentation:"bar",order:r,sequence:-1,source:"core"},element:t.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};w.start.splice(n<0?w.start.length:n,0,a)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(a.actionsStart,w.start),d(a.actionsEnd,w.end)};return{resolve:()=>{if(n)return;let o=function(e){let{debug:t}=e,r=[],n=new Map,o=0,a=e=>{let o=n.get(e.id);o?sa(t,`[Persona] composer action "${e.id}" is already contributed by ${ia(o)}; the ${ia(e)} copy is ignored.`):(n.set(e.id,e),r.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:"bar",order:t.order,sequence:o++,source:"core",builtIn:t});let s=(e,r,n)=>{let s=n?((e,t)=>t.includes(":")?t:`${e}:${t}`)(n,e.id):e.id,i=e.order??500;"end"===e.placement&&i>=ra&&(sa(t,`[Persona] composer action "${s}" ordered at ${i} would render after send; clamped to 999.`),i=999),a({id:s,placement:e.placement,presentation:e.presentation??"bar",order:i,sequence:o++,source:r,pluginId:n,action:e})};for(let t of e.configActions??[])s(t,"config");for(let t of e.plugins){if(!t.contributeComposerActions)continue;let r;try{r=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<"u"&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of r??[])s(e,"plugin",t.id)}return r.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}(e.collect()),s=new Set(o.map(e=>e.id));for(let[e,r]of t)s.has(e)||(l(r),t.delete(e));for(let e of o){let r=t.get(e.id);if(!r){let r=i(e,"bar");r&&t.set(e.id,r);continue}let n=r.resolved.action,o=e.action;if(!!n!=!!o||n&&o&&ca(n)!==ca(o)||n&&o&&ca(n)&&ca(o)&&n.render!==o.render){l(r),t.delete(e.id);let n=i(e,r.mode);n&&t.set(e.id,n);continue}r.resolved=e,e.builtIn?(r.managed=!0===e.builtIn.managed||"menu"===r.mode,e.builtIn.element&&"bar"===r.mode&&(r.element=e.builtIn.element)):o&&!ca(o)?a(r,o):o&&r.element.toggleAttribute(oa,!0===o.disableWhenStreaming)}r=o,b()},sync:b,getResolved:()=>r,getOverflowMenu:()=>p,destroy:()=>{if(!n){n=!0,h?.disconnect(),h=null,u=null;for(let e of t.values())l(e);t.clear(),p?.destroy(),p=null,r=[]}}}}var ha=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],ma=()=>({wrapper:oe("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),chevron:oe("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}})});function ga(e){let t=e.label??"Model",r=e.presentation??"native",n=null,o=t=>{let r=e.getSelectedModelId();return t.find(e=>e.id===r)??t[0]};return{action:{id:"core:model",kind:"custom",placement:"end",order:700,presentation:"popover"===r?"bar":"auto",label:t,render:()=>"popover"===r?(()=>{let r=oe("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),a=ne("span","persona-composer-model-picker-label"),s=ne("span","persona-composer-model-picker-suffix");r.append(a,s);let i=oe("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),l=new Map,d="",c=null,p=()=>!0===c?.isOpen,u=(e=!1)=>{p()&&(c?.close(),r.setAttribute("aria-expanded","false"),e&&r.focus())},h=e=>{let t=[...l.values()];0!==t.length&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(p())return;c||(c=Xo({anchor:r,content:i,placement:"top-start",offset:6,onDismiss:()=>r.setAttribute("aria-expanded","false")})),jo(r,i,ha),c.open(),r.setAttribute("aria-expanded","true");let n=[...l.keys()].indexOf(o(e.getModels())?.id??"");h(t??(n>=0?n:0))},g=t=>{t.preventDefault(),t.stopPropagation();let r=t.currentTarget.getAttribute("data-persona-model-option");r&&(t=>{u(!0),e.onSelect(t)})(r)},f=()=>{let n=e.getModels(),c=n.map(e=>`${e.id}:${e.label}:${e.icon??""}:${e.description??""}`).join("|");if(c!==d){d=c;for(let e of l.values())e.removeEventListener("click",g);l.clear(),i.replaceChildren(...n.map(e=>{let t=(e=>{let t=oe("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":e.id}});if(e.icon){let r=xe(e.icon,16,"currentColor",1.5);if(r){let e=ne("span","persona-composer-model-option-icon");e.appendChild(r),t.appendChild(e)}}let r=ne("span","persona-composer-model-option-body"),n=ne("span","persona-composer-model-option-label");if(n.textContent=e.label,r.appendChild(n),e.description){let t=ne("span","persona-composer-model-option-description");t.textContent=e.description,r.appendChild(t)}t.appendChild(r);let o=ne("span","persona-composer-model-option-check");o.setAttribute("aria-hidden","true");let a=xe("check",16,"currentColor",2);return a&&o.appendChild(a),t.appendChild(o),t.addEventListener("click",g),t})(e);return l.set(e.id,t),t}))}let p=o(n);for(let[e,t]of l)t.setAttribute("aria-selected",String(e===p?.id));a.textContent=p?.label??"";let u=e.getSuffix?.()??"";s.textContent=u,r.setAttribute("aria-label",[t,[p?.label,u].filter(Boolean).join(" ")].filter(Boolean).join(": "))};f(),n=f;let y=e=>{e.preventDefault(),e.stopPropagation(),p()?u(!0):m()},b=e=>{if("ArrowDown"===e.key)return e.preventDefault(),void(p()?h(0):m(0));"ArrowUp"===e.key&&(e.preventDefault(),p()?h(-1):m(-1))},v=e=>{let t=[...l.values()],r=t.indexOf(e.target?.closest?.(".persona-composer-model-option"));switch(e.key){case"ArrowDown":return e.preventDefault(),void h(r+1);case"ArrowUp":return e.preventDefault(),void h(r-1);case"Home":return e.preventDefault(),void h(0);case"End":return e.preventDefault(),void h(t.length-1);case"Escape":return e.preventDefault(),e.stopPropagation(),void u(!0);case"Tab":return void u(!0)}};r.addEventListener("click",y),r.addEventListener("keydown",b),i.addEventListener("keydown",v);let{wrapper:w,chevron:x}=ma();return w.append(r,x),{element:w,destroy:()=>{n===f&&(n=null),r.removeEventListener("click",y),r.removeEventListener("keydown",b),i.removeEventListener("keydown",v);for(let e of l.values())e.removeEventListener("click",g);l.clear(),c?.destroy(),c=null,i.remove()}}})():(()=>{let r=oe("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),a="",s=()=>{let t=e.getModels(),n=t.map(e=>`${e.id}:${e.label}`).join("|");n!==a&&(a=n,r.replaceChildren(...t.map(e=>{let t=oe("option",{attrs:{value:e.id}});return t.textContent=e.label,t}))),r.value=o(t)?.id??""};s(),n=s;let i=()=>{r.value&&e.onSelect(r.value)};r.addEventListener("change",i);let l=e=>e.stopPropagation();r.addEventListener("click",l);let{wrapper:d,chevron:c}=ma();return d.append(r,c),{element:d,destroy:()=>{n===s&&(n=null),r.removeEventListener("change",i),r.removeEventListener("click",l)}}})()},repaint:()=>n?.()}}var fa="[data-persona-composer-chip-row]";function ya(e){e.style.display=e.childElementCount>0?"flex":"none"}function ba(e){let t=e.querySelector(fa);if(t)return t;let r=oe("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(r,n):e.appendChild(r),r}var va=e=>`core:mode:${e}`,wa=e=>Math.min(300+e,499),xa=e=>`core:mode-group:${e}`;function Ca(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}function Sa(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function ka(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function Aa(e,t){return!1===t?{status:"canceled"}:t&&"object"==typeof t?("string"==typeof t.text&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"}):{status:"proceed"}}var{setLoader:Ma,load:Ia}=se({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ta=Ma,Ea=Ia,{setLoader:La,load:Pa}=se({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Ba=La,Na=Pa;function Ra(e){let{config:t,onOpen:r}=e,n=t.buttonIconName??"plus",o=t.buttonTooltipText??"Add context",a=ne("div","persona-send-button-wrapper"),s=oe("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Fo} ${zo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":o,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=xe(n,qo,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Bo({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??o}),{button:s,wrapper:a}}var Ha=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),$a={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"},Wa="16px",Da="transparent",Oa=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=0===t?"0px":t/4+"rem";return e})(),Fa={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"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:Oa,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"}},za={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"}},qa={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:j,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Wa,canvasBackground:Da,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",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"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},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"}}},ja=Fa.colors.gray,_a={...Fa,colors:{...Fa.colors,gray:ja}},Va={...Fa,colors:{...Fa.colors,gray:{50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"}},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},Ua=_a,Ka=za,Ja={...za,colors:{...za.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...za.typography,fontSize:"14px",lineHeight:"1.5"}},Ga=Ka,Ya=qa,Xa={...qa,launcher:$a,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...qa.input,borderRadius:"palette.radius.full"},introCard:{...qa.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...qa.suggestion.chip,fontWeight:"400"},card:{...qa.suggestion.card,fontWeight:"400"},list:{...qa.suggestion.list,fontWeight:"400"}},panel:{...qa.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...qa.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...qa.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...qa.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...qa.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...qa.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}},Qa=Ya,Za=e=>"v5"===(e=>Q({future:e}))(e)?{palette:Va,semantic:Ja,components:Xa}:{palette:_a,semantic:Ka,components:Ya};function es(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),n=e;for(let e of r){if(null==n)return;n=n[e]}return"string"==typeof n&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?es(e,n):n}function ts(e){let t={};function r(n,o){for(let[a,s]of Object.entries(n)){let n=`${o}.${a}`;if("string"==typeof s){let r=es(e,s);void 0!==r&&(t[n]={path:n,value:r,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else"object"==typeof s&&null!==s&&r(s,n)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function rs(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:0===t.length,errors:t,warnings:r}}function ns(e,t){let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];t&&"object"==typeof t&&!Array.isArray(t)&&n&&"object"==typeof n&&!Array.isArray(n)?r[e]=ns(t,n):r[e]=n}return r}function os(e,t){return t?ns(e,t):e}function as(e,t={}){let r=Za(t.future),n={palette:r.palette,semantic:r.semantic,components:r.components},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:os(n.components,e?.components)},a=e?.components?.activity;for(let e of["toolBubble","reasoningBubble"])for(let t of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[t]&&(o.components[e][t]=a[t]);let s=e?.components?.collapsibleWidget?.surface;void 0!==s&&void 0===a?.bodySurface&&(o.components.activity={...o.components.activity,bodySurface:s});let i=e?.components?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(o.components.header.minimalPadding=o.components.header.padding);let l=e?.components?.message;if(void 0!==l?.gap&&void 0===l.fullscreenGap&&(o.components.message.fullscreenGap=o.components.message.gap),!1!==t.validate){let e=rs(o);if(!e.valid)throw new Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)o=e.transform(o);return o}var ss=e=>"0"===e.trim()?"0px":e,is="--persona-",ls=e=>{if(!e)return;let t,r=e.trim().toLowerCase();if(35===r.charCodeAt(0)){let e=r.slice(1);if(!/^[0-9a-f]+$/.test(e))return;3===e.length||4===e.length?t=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(6===e.length||8===e.length)&&(t=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=r.match(/^rgba?\(([^)]+)\)$/);if(e){let r=e[1].split(/[,/\s]+/).filter(Boolean);r.length>=3&&(t=r.slice(0,3).map(e=>{let t=e.endsWith("%"),r=parseFloat(t?e.slice(0,-1):e);return t?r/100*255:r}))}}if(!t||t.some(e=>!Number.isFinite(e)))return;let[n,o,a]=t.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)});return.2126*n+.7152*o+.0722*a},ds=.179,cs=(e,t)=>{for(let[r,...n]of t){let t;for(let r of n)if(t=61===r.charCodeAt(0)?r.slice(1):e[is+r],void 0!==t)break;void 0!==t&&(e[is+r]=t)}};function ps(e){let t=ts(e),r={};for(let[e,n]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=n.value;cs(r,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=r["--persona-components-launcher-foreground"];r["--persona-launcher-fg-muted"]=n&&n!==r["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:r["--persona-muted"],cs(r,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),cs(r,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),r["--persona-panel-border"]=r["--persona-components-panel-border"]??`1px solid ${r["--persona-border"]}`,cs(r,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),r["--persona-panel-inset"]=r["--persona-components-panel-inset"]??Wa,r["--persona-panel-canvas-bg"]=r["--persona-components-panel-canvasBackground"]??Da,cs(r,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),cs(r,[["header-bg","components-header-background","surface"]]);let o=r["--persona-header-bg"],a=r["--persona-components-header-foreground"],s=a?`color-mix(in srgb, ${a} 72%, ${o})`:void 0;r["--persona-header-border"]=r["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${o})`:void 0)??r["--persona-divider"],cs(r,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),r["--persona-header-title-fg"]=r["--persona-components-header-title-color"]??r["--persona-components-header-titleForeground"]??a??r["--persona-primary"],r["--persona-header-subtitle-fg"]=r["--persona-components-header-subtitle-color"]??r["--persona-components-header-subtitleForeground"]??s??r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=r["--persona-components-header-actionIconForeground"]??s??r["--persona-muted"],cs(r,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let i=e.components?.header;i?.shadow&&(r["--persona-header-shadow"]=i.shadow),i?.borderBottom&&(r["--persona-header-border-bottom"]=i.borderBottom),i?.minHeight&&(r["--persona-header-min-height"]=i.minHeight);let l=r["--persona-components-history-railHeader-background"];l&&(r["--persona-history-rail-header-bg"]=l);let d=r["--persona-components-history-railHeader-border"];d&&(r["--persona-history-rail-header-border"]=d);let c=r["--persona-components-history-railHeader-minHeight"];c&&(r["--persona-history-rail-header-min-height"]=c);for(let[e,t]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let n=r[`--persona-components-history-overlay-${e}`];n&&(r[`--persona-history-overlay-${t}`]=n)}for(let[e,t]of[["background","bg"],["borderRadius","radius"]]){let n=r[`--persona-components-history-menu-${e}`];n&&(r[`--persona-history-menu-${t}`]=n)}let p=e.components?.history?.motion;if(p){let e=e=>{if(void 0===e)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(p.enterDurationMs);void 0!==t&&(r["--persona-history-enter-ms"]=t);let n=e(p.exitDurationMs);void 0!==n&&(r["--persona-history-exit-ms"]=n),p.enterEasing&&(r["--persona-history-enter-easing"]=p.enterEasing),p.exitEasing&&(r["--persona-history-exit-easing"]=p.exitEasing)}let u=r["--persona-components-history-dangerForeground"];u&&(r["--persona-history-danger-fg"]=u),r["--persona-danger"]=r["--persona-components-history-confirm-dangerBackground"]??r["--persona-palette-colors-error-700"]??"#b42318",r["--persona-danger-fg"]=r["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let e of["scrim","shadow"]){let t=r[`--persona-components-history-confirm-${e}`];t&&(r[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let n=r[`--persona-components-tooltip-${e}`];n&&(r[`--persona-tooltip-${t}`]=n)}!1===e.components?.tooltip?.arrow&&(r["--persona-tooltip-arrow-display"]="none");for(let[e,t]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let n=r[`--persona-components-messageActions-${e}`];n&&(r[`--persona-message-action-${t}`]=n)}cs(r,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=r["--persona-components-introCard-background"],m=r["--persona-components-introCard-shadow"],g=!(h&&"transparent"!==h&&"none"!==h||m&&"none"!==m),f=r["--persona-components-introCard-padding"]??"1.5rem";r["--persona-intro-card-padding"]=g&&"1.5rem"===f?"1.5rem 0":f,cs(r,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),cs(r,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let y=r["--persona-components-markdown-heading-h1-fontSize"];y&&(r["--persona-md-h1-size"]=y);let b=r["--persona-components-markdown-heading-h1-fontWeight"];b&&(r["--persona-md-h1-weight"]=b);let v=r["--persona-components-markdown-heading-h2-fontSize"];v&&(r["--persona-md-h2-size"]=v);let w=r["--persona-components-markdown-heading-h2-fontWeight"];w&&(r["--persona-md-h2-weight"]=w);let x=r["--persona-components-markdown-prose-fontFamily"];x&&"inherit"!==x&&(r["--persona-md-prose-font-family"]=x),cs(r,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),cs(r,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),cs(r,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),cs(r,[["md-hr-color","components-markdown-hr-color","divider"]]),cs(r,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let C=[["container","surface"],["surface","surface"],["border","border"]];for(let[e,t]of C){let n=r[`--persona-components-collapsibleWidget-${e}`]??r[`--persona-${t}`];void 0!==n&&(r[`--persona-cw-${e}`]=n,r[`--cw-${e}`]=n)}cs(r,[["message-border","components-message-border","border"]]),cs(r,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let S=e.components,k=S?.iconButton;k&&(k.background&&(r["--persona-icon-btn-bg"]=k.background),k.border&&(r["--persona-icon-btn-border"]=k.border),k.color&&(r["--persona-icon-btn-color"]=k.color),k.padding&&(r["--persona-icon-btn-padding"]=k.padding),k.borderRadius&&(r["--persona-icon-btn-radius"]=k.borderRadius),k.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=k.hoverBackground),k.hoverColor&&(r["--persona-icon-btn-hover-color"]=k.hoverColor),k.activeBackground&&(r["--persona-icon-btn-active-bg"]=k.activeBackground),k.activeBorder&&(r["--persona-icon-btn-active-border"]=k.activeBorder));let A=S?.labelButton;A&&(A.background&&(r["--persona-label-btn-bg"]=A.background),A.border&&(r["--persona-label-btn-border"]=A.border),A.color&&(r["--persona-label-btn-color"]=A.color),A.padding&&(r["--persona-label-btn-padding"]=A.padding),A.borderRadius&&(r["--persona-label-btn-radius"]=A.borderRadius),A.hoverBackground&&(r["--persona-label-btn-hover-bg"]=A.hoverBackground),A.fontSize&&(r["--persona-label-btn-font-size"]=A.fontSize),A.gap&&(r["--persona-label-btn-gap"]=A.gap));let M=S?.toggleGroup;M&&(M.gap&&(r["--persona-toggle-group-gap"]=M.gap),M.borderRadius&&(r["--persona-toggle-group-radius"]=M.borderRadius));let I=S?.artifact;if(I?.toolbar){let t=I.toolbar;t.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=t.iconHoverColor),t.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=t.iconHoverBackground),t.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=t.iconPadding),t.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=t.iconBorderRadius),t.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=t.iconBorder),t.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=ss(t.toggleGroupGap)),t.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=t.toggleBorderRadius),t.toggleGroupPadding&&(r["--persona-artifact-toolbar-toggle-group-padding"]=ss(t.toggleGroupPadding)),t.toggleGroupBorder&&(r["--persona-artifact-toolbar-toggle-group-border"]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(r["--persona-artifact-toolbar-toggle-group-radius"]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(r["--persona-artifact-toolbar-toggle-group-bg"]=es(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=t.copyBackground),t.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=t.copyBorder),t.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=t.copyColor),t.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=ss(t.copyBorderRadius)),t.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=t.copyPadding),t.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=t.copyMenuBackground,r["--persona-dropdown-bg"]=r["--persona-dropdown-bg"]??t.copyMenuBackground),t.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=t.copyMenuBorder,r["--persona-dropdown-border"]=r["--persona-dropdown-border"]??t.copyMenuBorder),t.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=t.copyMenuShadow,r["--persona-dropdown-shadow"]=r["--persona-dropdown-shadow"]??t.copyMenuShadow),t.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=t.copyMenuBorderRadius,r["--persona-dropdown-radius"]=r["--persona-dropdown-radius"]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=t.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=r["--persona-dropdown-item-hover-bg"]??t.copyMenuItemHoverBackground),t.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=t.iconBackground),t.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=t.toolbarBorder)}if(I?.tab){let e=I.tab;e.background&&(r["--persona-artifact-tab-bg"]=e.background),e.activeBackground&&(r["--persona-artifact-tab-active-bg"]=e.activeBackground),e.activeBorder&&(r["--persona-artifact-tab-active-border"]=e.activeBorder),e.borderRadius&&(r["--persona-artifact-tab-radius"]=e.borderRadius),e.textColor&&(r["--persona-artifact-tab-color"]=e.textColor),e.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=e.hoverBackground),e.listBackground&&(r["--persona-artifact-tab-list-bg"]=e.listBackground),e.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=e.listBorderColor),e.listPadding&&(r["--persona-artifact-tab-list-padding"]=e.listPadding)}if(I?.pane){let t=I.pane;if(t.toolbarBackground){let n=es(e,t.toolbarBackground)??t.toolbarBackground;r["--persona-artifact-toolbar-bg"]=n}}if(I?.card){let e=I.card;e.background&&(r["--persona-artifact-card-bg"]=e.background),e.border&&(r["--persona-artifact-card-border"]=e.border),e.borderRadius&&(r["--persona-artifact-card-radius"]=e.borderRadius),e.hoverBackground&&(r["--persona-artifact-card-hover-bg"]=e.hoverBackground),e.hoverBorderColor&&(r["--persona-artifact-card-hover-border"]=e.hoverBorderColor)}if(I?.inline){let t=I.inline;t.background&&(r["--persona-artifact-inline-bg"]=es(e,t.background)??t.background),t.border&&(r["--persona-artifact-inline-border"]=t.border),t.borderRadius&&(r["--persona-artifact-inline-radius"]=t.borderRadius),t.chromeBackground&&(r["--persona-artifact-inline-chrome-bg"]=es(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(r["--persona-artifact-inline-chrome-border"]=es(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(r["--persona-artifact-inline-title-color"]=es(e,t.titleColor)??t.titleColor),t.mutedColor&&(r["--persona-artifact-inline-muted-color"]=es(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(r["--persona-artifact-inline-frame-height"]=t.frameHeight)}let T=S?.code;T&&(T.keywordColor&&(r["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(r["--persona-code-string-color"]=T.stringColor),T.commentColor&&(r["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(r["--persona-code-number-color"]=T.numberColor),T.tagColor&&(r["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(r["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(r["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(r["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(r["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(r["--persona-code-bg"]=es(e,T.background)??T.background));let E=r["--persona-surface"],L=r["--persona-container"],P=r["--persona-palette-colors-gray-100"]??"#f3f4f6",B=r["--persona-palette-colors-gray-200"]??"#e5e7eb",N=r["--persona-palette-colors-gray-300"]??"#d1d5db",R=!L||L===E,H=ls(E??r["--persona-background"]),$=R&&void 0!==H&&H<ds,W=$?"rgba(255, 255, 255, 0.16)":N,D=R?$?"rgba(255, 255, 255, 0.08)":P:L,O=R?$?"rgba(255, 255, 255, 0.12)":B:L;return r["--persona-icon-btn-hover-bg"]=r["--persona-icon-btn-hover-bg"]??D,r["--persona-icon-btn-active-bg"]=r["--persona-icon-btn-active-bg"]??O,R&&(r["--persona-icon-btn-active-border"]=r["--persona-icon-btn-active-border"]??W),r["--persona-label-btn-hover-bg"]=r["--persona-label-btn-hover-bg"]??D,r["--persona-artifact-tab-hover-bg"]=r["--persona-artifact-tab-hover-bg"]??D,r["--persona-artifact-card-hover-bg"]=r["--persona-artifact-card-hover-bg"]??D,r}var us={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"},hs={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},ms={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"}}},gs={...ms,colors:{...ms.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},fs=hs,ys={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",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"}}},components:{...hs.components,button:{...hs.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...hs.components?.eventStream,badge:{...hs.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},bs=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},vs=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",ws=e=>(e=>{let t=e?.colorScheme??"light";return"light"===t?"light":"dark"===t?"dark":vs()})(e),xs=e=>{let t=ws(e),r=bs(e?.theme),n=E({components:{launcher:"circle"===Ha(e)?$a:{...Ya.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}}}},r),o=bs(e?.darkTheme);return((e,t)=>{if(!t||!(e=>!!e&&"launcher"in e&&(!0===e.launcher?.sidebarMode||"docked"===e.launcher?.mountMode))(t))return e;let r=t.theme?.components?.panel?.width,n=t.darkTheme?.components?.panel?.width;return null!=("dark"===ws(t)?n??r:r)?e:{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===Q(t)?"400px":"420px"}}}})("dark"===t?((e,t={})=>{let r=(e=>"v5"===Q({future:e})?{palette:gs,components:ys}:{palette:ms,components:fs})(t.future),n=E(r.components,e??{})??{};return as({...n,palette:{...n.palette,colors:"v5"===Q(t)?E(r.palette.colors,n.palette?.colors):{...r.palette.colors,...n.palette?.colors}}},{validate:!1,future:t.future})})(E(n??{},o??{}),{future:e?.future}):((e,t={})=>as(e,t))(n,{future:e?.future}),e)},Cs=(e,t)=>{let r=(e=>ps(e))(xs(t));for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute("data-persona-color-scheme",ws(t)),e.setAttribute("data-persona-defaults",Q(t))},Ss=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(vs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window<"u"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(vs());r.addEventListener?(r.addEventListener("change",n),t.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),t.push(()=>r.removeListener(n)))}return()=>{t.forEach(e=>e())}},ks=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),As="24px",Ms=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",Is=e=>{if("string"!=typeof e)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let r=Number(t[1])/100;return r>0&&r<1?r:null},Ts=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},Es=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Ls=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),n={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)n.mod=!0;else if("shift"===r)n.shift=!0;else{if("alt"!==r&&"option"!==r)return Es("unknown modifier in",e),null;n.alt=!0}return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(Es("unsupported",e),null):("space"===r&&(n.key=" "),n)},Ps=(e,t)=>{let r=Ls(e);if(!r)return"";let n=Ts(),o=(e=>"ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space".split(" ").find(t=>t.toLowerCase()===e)??(" "===e?"Space":1===e.length?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))(r.key);if(!t&&n)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${o}`;let a=[t?n?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(o),a.join("+")},Bs=e=>Ps(e,!1),Ns=e=>Ps(e,!0),Rs=(e,t)=>t.key?.toLowerCase()===e.key&&(Ts()?t.metaKey:t.ctrlKey)===e.mod&&!(Ts()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Hs=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},$s=function(){let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:e=>"true"===e.getAttribute("im-preserve"),shouldReAppend:e=>"true"===e.getAttribute("im-re-append"),shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0},r=function(){function e(e,t,r,o){if(!1===o.callbacks.beforeNodeAdded(t))return null;if(o.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),n(a,t,o),o.callbacks.afterNodeAdded(a),a}{let n=document.importNode(t,!0);return e.insertBefore(n,r),o.callbacks.afterNodeAdded(n),n}}let t=function(){function e(e,t,r){let n=e.idMap.get(t),o=e.idMap.get(r);if(!o||!n)return!1;for(let e of n)if(o.has(e))return!0;return!1}function t(e,t){let r=e,n=t;return r.nodeType===n.nodeType&&r.tagName===n.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===n.getAttribute?.("id"))}return function(r,n,o,a){let s=null,i=n.nextSibling,l=0,d=o;for(;d&&d!=a;){if(t(d,n)){if(e(r,d,n))return d;null===s&&(r.idMap.has(d)||(s=d))}if(null===s&&i&&t(d,i)&&(l++,i=i.nextSibling,l>=2&&(s=void 0)),r.activeElementAndParents.includes(d))break;d=d.nextSibling}return s||null}}();function r(e,t){if(e.idMap.has(t))s(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;t.parentNode?.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function o(e,t,n){let o=t;for(;o&&o!==n;){let t=o;o=o.nextSibling,r(e,t)}return o}function a(e,t,r,n){let o=n.target.getAttribute?.("id")===t&&n.target||n.target.querySelector(`[id="${t}"]`)||n.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let n=t.idMap.get(e);n&&(n.delete(r),n.size||t.idMap.delete(e))}}(o,n),s(e,o,r),o}function s(e,t,r){if(e.moveBefore)try{e.moveBefore(t,r)}catch{e.insertBefore(t,r)}else e.insertBefore(t,r)}return function(s,i,l,d=null,c=null){i instanceof HTMLTemplateElement&&l instanceof HTMLTemplateElement&&(i=i.content,l=l.content),d||=i.firstChild;for(let r of l.childNodes){if(d&&d!=c){let e=t(s,r,d,c);if(e){e!==d&&o(s,d,e),n(e,r,s),d=e.nextSibling;continue}}if(r instanceof Element){let e=r.getAttribute("id");if(s.persistentIds.has(e)){let t=a(i,e,d,s);n(t,r,s),d=t.nextSibling;continue}}let l=e(i,r,d,s);l&&(d=l.nextSibling)}for(;d&&d!=c;){let e=d;d=d.nextSibling,r(s,e)}}}(),n=function(){function e(e,r,n,o){let a=r[n];if(a!==e[n]){let s=t(n,e,"update",o);s||(e[n]=r[n]),a?s||e.setAttribute(n,""):t(n,e,"remove",o)||e.removeAttribute(n)}}function t(e,t,r,n){return!("value"!==e||!n.ignoreActiveValue||t!==document.activeElement)||!1===n.callbacks.beforeAttributeUpdated(e,t,r)}function n(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(a,s,i){return i.ignoreActive&&a===document.activeElement?null:(!1===i.callbacks.beforeNodeMorphed(a,s)||(a instanceof HTMLHeadElement&&i.head.ignore||(a instanceof HTMLHeadElement&&"morph"!==i.head.style?o(a,s,i):(function(r,o,a){let s=o.nodeType;if(1===s){let s=r,i=o,l=s.attributes,d=i.attributes;for(let e of d)t(e.name,s,"update",a)||s.getAttribute(e.name)!==e.value&&s.setAttribute(e.name,e.value);for(let e=l.length-1;0<=e;e--){let r=l[e];if(r&&!i.hasAttribute(r.name)){if(t(r.name,s,"remove",a))continue;s.removeAttribute(r.name)}}n(s,a)||function(r,n,o){if(r instanceof HTMLInputElement&&n instanceof HTMLInputElement&&"file"!==n.type){let a=n.value,s=r.value;e(r,n,"checked",o),e(r,n,"disabled",o),n.hasAttribute("value")?s!==a&&(t("value",r,"update",o)||(r.setAttribute("value",a),r.value=a)):t("value",r,"remove",o)||(r.value="",r.removeAttribute("value"))}else if(r instanceof HTMLOptionElement&&n instanceof HTMLOptionElement)e(r,n,"selected",o);else if(r instanceof HTMLTextAreaElement&&n instanceof HTMLTextAreaElement){let e=n.value,a=r.value;if(t("value",r,"update",o))return;e!==a&&(r.value=e),r.firstChild&&r.firstChild.nodeValue!==e&&(r.firstChild.nodeValue=e)}}(s,i,a)}(8===s||3===s)&&r.nodeValue!==o.nodeValue&&(r.nodeValue=o.nodeValue)}(a,s,i),n(a,i)||r(i,a,s))),i.callbacks.afterNodeMorphed(a,s)),a)}}();function o(e,t,r){let n=[],o=[],a=[],s=[],i=new Map;for(let e of t.children)i.set(e.outerHTML,e);for(let t of e.children){let e=i.has(t.outerHTML),n=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?n?o.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?n&&(o.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&o.push(t)}s.push(...i.values());let l=[];for(let t of s){let o=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(o)){if("href"in o&&o.href||"src"in o&&o.src){let e,t=new Promise(function(t){e=t});o.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(o),r.callbacks.afterNodeAdded(o),n.push(o)}}for(let t of o)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:n,kept:a,removed:o}),l}let a=function(){function e(){let e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function r(e){let t=[],r=document.activeElement;if("BODY"!==r?.tagName&&e.contains(r))for(;r&&(t.push(r),r!==e);)r=r.parentElement;return t}function n(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function o(e,t,r,n){for(let o of n){let n=o.getAttribute("id");if(t.has(n)){let t=o;for(;t;){let o=e.get(t);if(null==o&&(o=new Set,e.set(t,o)),o.add(n),t===r)break;t=t.parentElement}}}}return function(a,s,i){let{persistentIds:l,idMap:d}=function(e,t){let r=n(e),a=n(t),s=function(e,t){let r=new Set,n=new Map;for(let{id:t,tagName:o}of e)n.has(t)?r.add(t):n.set(t,o);let o=new Set;for(let{id:e,tagName:a}of t)o.has(e)?r.add(e):n.get(e)===a&&o.add(e);for(let e of r)o.delete(e);return o}(r,a),i=new Map;return o(i,s,e,r),o(i,s,t.__idiomorphRoot||t,a),{persistentIds:s,idMap:i}}(a,s),c=function(e){let r=Object.assign({},t);return Object.assign(r,e),r.callbacks=Object.assign({},t.callbacks,e.callbacks),r.head=Object.assign({},t.head,e.head),r}(i),p=c.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(p))throw`Do not understand how to morph style ${p}`;return{target:a,newContent:s,config:c,morphStyle:p,ignoreActive:c.ignoreActive,ignoreActiveValue:c.ignoreActiveValue,restoreFocus:c.restoreFocus,idMap:d,persistentIds:l,pantry:e(),activeElementAndParents:r(a),callbacks:c.callbacks,head:c.head}}}(),{normalizeElement:s,normalizeParent:i}=function(){let e=new WeakSet;class t{constructor(e){this.originalNode=e,this.realParentNode=e.parentNode,this.previousSibling=e.previousSibling,this.nextSibling=e.nextSibling}get childNodes(){let e=[],t=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;t&&t!=this.nextSibling;)e.push(t),t=t.nextSibling;return e}querySelectorAll(e){return this.childNodes.reduce((t,r)=>{if(r instanceof Element){r.matches(e)&&t.push(r);let n=r.querySelectorAll(e);for(let e=0;e<n.length;e++)t.push(n[e])}return t},[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function r(n){if(null==n)return document.createElement("div");if("string"==typeof n)return r(function(t){let r=new DOMParser,n=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let o=r.parseFromString(t,"text/html");if(n.match(/<\/html>/))return e.add(o),o;{let t=o.firstChild;return t&&e.add(t),t}}{let n=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(n),n}}(n));if(e.has(n))return n;if(n instanceof Node){if(n.parentNode)return new t(n);{let e=document.createElement("div");return e.append(n),e}}{let e=document.createElement("div");for(let t of[...n])e.append(t);return e}}}}();return{morph:function(e,t,n={}){e=s(e);let l=i(t),d=a(e,l,n),c=function(e,t){if(!e.config.restoreFocus)return t();let r=document.activeElement;if(!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return t();let{id:n,selectionStart:o,selectionEnd:a}=r,s=t();return n&&n!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${n}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(o,a),s}(d,()=>function(e,t,r,n){if(e.head.block){let a=t.querySelector("head"),s=r.querySelector("head");if(a&&s){let t=o(a,s,e);return Promise.all(t).then(()=>{let t=Object.assign(e,{head:{block:!1,ignore:!0}});return n(t)})}}return n(e)}(d,e,l,t=>"innerHTML"===t.morphStyle?(r(t,e,l),Array.from(e.childNodes)):function(e,t,n){let o=i(t);return r(e,o,n,t,t.nextSibling),Array.from(o.childNodes)}(t,e,l)));return d.pantry.remove(),c},defaults:t}}(),Ws=(e,t,r={})=>{let{preserveTypingAnimation:n=!0}=r;$s.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&n){if(e.classList.contains("persona-animate-typing")||e.hasAttribute("data-preserve-runtime"))return!1;if(e.hasAttribute("data-tool-elapsed"))return!(t instanceof HTMLElement&&t.getAttribute("data-tool-elapsed")===e.getAttribute("data-tool-elapsed"))&&void 0;if(e.hasAttribute("data-preserve-animation")){if(t instanceof HTMLElement&&!t.hasAttribute("data-preserve-animation"))return;if(t instanceof HTMLElement&&t.hasAttribute("data-preserve-animation")&&(e.textContent??"")!==(t.textContent??""))return;return!1}}}}})},Ds={index:-1,draft:""};function Os(e){return"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function zs(e,t){return Fs(e)-e.scrollTop<=t}function qs(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}var js=["pre","code","a","script","style"],_s=e=>({type:e?.type??"none",placeholder:e?.placeholder??"none",speed:e?.speed??120,duration:e?.duration??1800,buffer:e?.buffer??"none"}),Vs=[{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"}],Us=new Map;for(let e of Vs)Us.set(e.name,e);var Ks=["wipe","glyph-cycle"],Js=e=>{Us.set(e.name,e)},Gs=e=>{Vs.some(t=>t.name===e)||Us.delete(e)},Ys=()=>Array.from(Us.keys()),Xs=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Us.get(e)??null,Qs=(e,t,r,n,o)=>{if(!o)return e;if(r?.bufferContent)return r.bufferContent(e,n);if(!e)return e;if("word"===t){let t=e.search(/\s(?=\S*$)/);return t<0?"":e.slice(0,t)}if("line"===t){let t=e.lastIndexOf("\n");return t<0?"":e.slice(0,t)}return e},Zs=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=t,o},ei=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=t,o},ti=/\s/,ri=(e,t)=>{let r=e.parentNode;for(;r;){if(1===r.nodeType){let e=r;if(t.has(e.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},ni=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(ti.test(a[i])){let e=i;for(;e<a.length&&ti.test(a[e]);)e+=1;s.appendChild(n.createTextNode(a.slice(i,e))),i=e}else{let e=n.createElement("span");e.className="persona-stream-word-group";let o=i;for(;o<a.length&&!ti.test(a[o]);)e.appendChild(Zs(n,a[o],t,r.value)),r.value+=1,o+=1;s.appendChild(e),i=o}o.replaceChild(s,e)},oi=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(n.createTextNode(e)):(s.appendChild(ei(n,e,t,r.value)),r.value+=1));o.replaceChild(s,e)},ai=(e,t,r,n)=>{if(!e||typeof document>"u")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set((n?.skipTags??js).map(e=>e.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)ri(l,a)||i.push(l),l=s.nextNode();let d={value:n?.startIndex??0},c="char"===t?ni:oi;for(let e of i)c(e,r,d);return o.innerHTML},si=(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},ii=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},li=new WeakMap,di=new WeakMap,ci=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=li.get(t);if(r||(r=new Set,li.set(t,r)),r.has(e.name)){let n=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${n}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=di.get(t);if(r||(r=new Map,di.set(t,r)),r.has(e.name))return;let n=e.onAttach(t);r.set(e.name,n)})(e,t)},{setLoader:pi,load:ui}=se({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),hi=pi,mi=ui;function gi(e,t=pn){let r=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s="static"===a.position||""===a.position;return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=n,e.style.isolation=o}}var fi=0,yi=null;function bi(e=document){if(1===++fi){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;yi={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:r},t.style.overflow="hidden",t.style.position="fixed",t.style.top=`-${r}px`,t.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,0===(fi=Math.max(0,fi-1))&&yi)){let t=e.body,r=e.defaultView??window;t.style.overflow=yi.originalOverflow,t.style.position=yi.originalPosition,t.style.top=yi.originalTop,t.style.width=yi.originalWidth,r.scrollTo(0,yi.scrollY),yi=null}}}var vi=e=>"docked"===(e?.launcher?.mountMode??"floating"),wi=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),xi=e=>{let t=e?.launcher?.dock,r=F(e).dockWidth?t?.width:es(xs(e),"components.panel.width");return{side:t?.side??"right",width:r??"420px",animate:t?.animate??true,reveal:t?.reveal??"resize",maxHeight:t?.maxHeight??"100dvh"}},Ci=e=>"followUp"===e?"follow-up":e,Si=(e,t=0)=>{if("string"==typeof e){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:"default"}:null}let r=e.label.trim();if(!r)return null;let n=e.prompt?.trim()||r;return{id:e.id?.trim()||n||`suggestion-${t}`,label:r,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},ki=new WeakSet,Ai=e=>{let{item:t,index:r,surface:n,source:o,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,g="followUp"===n,f=t.behavior,y=()=>{if(c.isStreaming())return;let e={suggestion:{...t},surface:n,source:o,behavior:f},r=u.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(g&&u.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of l)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:n,source:o,variant:a,config:i}))return;let s=p();if("fill"===f)return s.value=t.prompt,s.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),void s.focus();h?h(t.prompt):(s.value="",c.sendMessage(t.prompt))},b=()=>{let e=ne("button",`persona-suggestion persona-suggestion--${a}`);if(e.type="button",e.disabled=s,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=f,"chip"===a&&(d?.fontWeight&&(e.style.fontWeight=d.fontWeight),d?.paddingX&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(e.style.paddingTop=d.paddingY,e.style.paddingBottom=d.paddingY)),t.icon){let r=xe(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);r&&(r.classList.add("persona-suggestion__icon"),t.iconColor&&(r.style.color=t.iconColor),e.appendChild(r))}let r=ne("span","persona-suggestion__copy");if(r.appendChild(oe("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==a&&r.appendChild(oe("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(r),"chip"!==a){let t=I(m,16,"currentColor",1.8);t&&(t.classList.add("persona-suggestion__arrow"),e.appendChild(t))}return e.addEventListener("click",y),e},v=null;for(let e of l)if(e.renderSuggestion&&(v=e.renderSuggestion({suggestion:{...t},index:r,surface:n,source:o,variant:a,streaming:s,config:i,defaultRenderer:b,select:y}),v))break;return v??=b(),v.dataset.suggestionId||=t.id,v.dataset.behavior||=f,v.dataset.emphasis||=t.emphasis,v instanceof HTMLButtonElement||v.setAttribute("aria-disabled",s?"true":"false"),v},Mi=e=>{let t=[],r=[],n=null,o=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(o=null,e.hidden||"chip"!==e.dataset.variant||"scroll"!==e.dataset.overflow)return void a();let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1)return void a();let r="rtl"===getComputedStyle(e).direction,n=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=n<=4,i=n>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null===o&&"function"==typeof requestAnimationFrame?o=requestAnimationFrame(s):"function"!=typeof requestAnimationFrame&&s()};e.addEventListener("scroll",i,{passive:!0});let l="function"==typeof ResizeObserver?new ResizeObserver(i):null;return l?.observe(e),{buttons:t,elements:r,destroy:()=>{e.removeEventListener("scroll",i),l?.disconnect(),null!==o&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o),o=null},render:(o,l,d,c,p,u)=>{e.replaceChildren(),t.length=0,r.length=0;let h=u?.source??"config",m=u?.surface??("config"===h?"starter":"followUp"),g="followUp"===m,f=u?.variant??"chip",y=u?.behavior??"send",b=u?.overflow??"wrap",v=u?.config??{},w=u?.plugins??[],x="number"==typeof u?.maxItems?Math.max(0,Math.floor(u.maxItems)):void 0,C=g?"followUps":"starters";!ki.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(ki.add(v),console.info(`[persona] suggestions.${C}.overflow applies to the "chip" variant only; the "${f}" variant manages its own stacking.`));let S=e=>e.map(Si).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??y})),k=S(o??[]);w.forEach(e=>{e.transformSuggestions&&(k=S(e.transformSuggestions({suggestions:k.map(e=>({...e})),surface:m,source:h,config:v})))});let A=void 0===x?k:k.slice(0,x);if(!A.length)return e.hidden=!0,n=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(n=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ci(m),e.dataset.variant=f,e.dataset.overflow=b;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((n,o)=>{let a=Ai({item:n,index:o,surface:m,source:h,variant:f,streaming:I,config:v,plugins:w,chipsConfig:p,session:l,getTextarea:()=>d,eventTarget:e,submitPrompt:u?.submitPrompt});M.appendChild(a),r.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll("button"))].forEach(e=>{t.includes(e)||(e.disabled=I,t.push(e))})}),e.appendChild(M),s(),i();let T=JSON.stringify({normalized:A,surface:m,variant:f,source:h});T!==n&&(n=T,(e=>{typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||e.forEach((e,t)=>{"function"==typeof e.animate&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:60*t,easing:"ease-out",fill:"backwards"})})})(r),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:A.map(e=>({...e})),surface:m,source:h,variant:f},bubbles:!0,composed:!0})),g&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:A.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Ii={"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"},Ti={x:[1.4,1.05]},Ei="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Li="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pi=(e,t,r={})=>{let{iconSize:n,iconText:o}=r,[a,s]=Ti[t]??[1,1.5],i=!n;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=parseFloat(n??"")||20,d=xe(t,`${Math.round(l*a)}px`,"currentColor",s);d?(d.style.display="block",i||(d.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((s/1.5).toFixed(4))})`),e.replaceChildren(d)):o&&(e.textContent=o)},Bi=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:n,iconName:o,iconText:a,wrapperClassName:s=Ei,size:i,iconSize:l,color:d,backgroundColor:c,borderWidth:p,borderColor:u,borderRadius:h,paddingX:m,paddingY:g,hidden:f,extraClassName:y,attrs:b}=e,v=ne("div",s),w=!(!p&&!u),x=oe("button",{className:ae("persona-header-control","persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"persona-bg-transparent hover:persona-bg-gray-100",!w&&"persona-border-none",!h&&"persona-rounded-full",y),attrs:{type:"button","aria-label":t,...b},style:{width:i,height:i,minWidth:i,minHeight:i,display:f?"none":void 0,color:d||Hi.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return o?Pi(x,o,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Bo({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:n,enabled:r}),{button:x,wrapper:v}},Ni=(e,t={})=>{let{showClose:r=!0,wrapperClassName:n=Ei,buttonSize:o,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=Bi({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:n,size:o??s.closeButtonSize,iconSize:a,color:s.closeButtonColor,backgroundColor:s.closeButtonBackgroundColor,borderWidth:s.closeButtonBorderWidth,borderColor:s.closeButtonBorderColor,borderRadius:s.closeButtonBorderRadius,paddingX:s.closeButtonPaddingX,paddingY:s.closeButtonPaddingY,hidden:!r});return{button:d,wrapper:c}},Ri=(e,t={})=>{let{wrapperClassName:r=Li,buttonSize:n,iconSize:o}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=Bi({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:n??a.size,iconSize:o,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:l,wrapper:d}},Hi={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-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},$i={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)"},Wi={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)"},Di=e=>{let{config:t,showClose:r=!0}=e,n=oe("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:Hi.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)))"}}),o=t?.launcher??{},a=o.headerIconSize??V,s=o.closeButtonPlacement??"inline",i=o.headerIconHidden??!1,l=o.headerIconName,d=oe("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(l){let e=parseFloat(a)||24,r=xe(l,.6*e,"currentColor",1);r?(r.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,r.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,d.replaceChildren(r)):d.textContent=t?.launcher?.agentIconText??"💬"}else if(t?.launcher?.iconUrl){let e=ne("img");e.src=t.launcher.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=a,e.style.width=a,d.replaceChildren(e)}else d.textContent=t?.launcher?.agentIconText??"💬";let c=ne("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=oe("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Hi.titleColor,...$i}}),u=oe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Hi.subtitleColor,...Wi}});c.append(p,u),i?n.append(c):n.append(d,c);let h=o.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,y=null;if(m){let e=Ri(t,{wrapperClassName:"top-right"===g?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});f=e.button,y=e.wrapper,"top-right"===g&&(y.style.right="48px"),"inline"===g&&n.appendChild(y)}let b="top-right"===s?"persona-absolute persona-top-4 persona-right-4 persona-z-50":m&&"inline"===g?"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:v,wrapper:w}=Ni(t,{showClose:r,wrapperClassName:b});return"top-right"!==s&&n.appendChild(w),{header:n,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:v,closeButtonWrapper:w,clearChatButton:f,clearChatButtonWrapper:y}},Oi=(e,t,r)=>{let n=r?.launcher??{},o=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===o&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Fi(e){let{items:t,onSelect:r,anchor:n,position:o="bottom-left",portal:a,onOpenChange:s}=e,i=ne("div","persona-dropdown-menu persona-hidden");i.setAttribute("role","menu"),i.setAttribute("data-persona-theme-zone","dropdown"),a?(i.style.position="fixed",i.style.zIndex=String(un)):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px","bottom-right"===o?i.style.right="0":i.style.left="0");for(let e of t){if(e.dividerBefore){let e=document.createElement("hr");i.appendChild(e)}let t=document.createElement("button");if(t.type="button",t.setAttribute("role","menuitem"),t.setAttribute("data-dropdown-item-id",e.id),e.destructive&&t.setAttribute("data-destructive",""),e.icon){let r=xe(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let n=document.createElement("span");n.textContent=e.label,t.appendChild(n),t.addEventListener("click",t=>{t.stopPropagation(),c(),r(e.id)}),i.appendChild(t)}let l=null;function d(){let e=i.classList.contains("persona-hidden");(function(){if(!a)return;let e=n.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===o?(i.style.right=window.innerWidth-e.right+"px",i.style.left="auto"):(i.style.left=`${e.left}px`,i.style.right="auto")})(),i.classList.remove("persona-hidden"),e&&s?.(!0),requestAnimationFrame(()=>{let e=e=>{!i.contains(e.target)&&!n.contains(e.target)&&c()};document.addEventListener("click",e,!0),l=()=>document.removeEventListener("click",e,!0)})}function c(){let e=!i.classList.contains("persona-hidden");i.classList.add("persona-hidden"),l?.(),l=null,e&&s?.(!1)}return a&&a.appendChild(i),{element:i,show:d,hide:c,toggle:function(){i.classList.contains("persona-hidden")?d():c()},destroy:function(){c(),i.remove()}}}function zi(e){let{icon:t,label:r,size:n,strokeWidth:o,className:a,chromeless:s,onClick:i,aria:l}=e,d=ne("button",ae(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=xe(t,n??16,"currentColor",o??2);if(c&&d.appendChild(c),i&&d.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))d.setAttribute(e,t);return d}function qi(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==n&&(d+=" persona-label-btn--"+n),d+=" persona-label-btn--"+o,s&&(d+=" "+s);let c=ne("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=xe(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=ne("span");if(p.textContent=r,c.appendChild(p),i&&c.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))c.setAttribute(e,t);return c}function ji(e){let{items:t,selectedId:r,onSelect:n,className:o}=e,a=ne("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=r,i=[];function l(){for(let e of i)e.btn.setAttribute("aria-pressed",e.id===s?"true":"false")}for(let e of t){let t;e.icon?t=zi({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),n(e.id)}}):(t=ne("button","persona-icon-btn"+(e.className?" "+e.className:"")),t.type="button",t.setAttribute("aria-label",e.label),t.title=e.label,t.textContent=e.label,t.addEventListener("click",()=>{s=e.id,l(),n(e.id)})),t.setAttribute("aria-pressed",e.id===s?"true":"false"),i.push({id:e.id,btn:t}),a.appendChild(t)}return{element:a,setSelected:function(e){s=e,l()}}}function _i(e){let{label:t,icon:r,iconSize:n,iconOnly:o,menuItems:a,onSelect:s,onPrimary:i,position:l="bottom-left",portal:d,chevronLabel:c="More options",chevronIconSize:p,className:u,primaryClassName:h,chevronClassName:m}=e,g=ne("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},y=o&&r?zi({...f,icon:r,size:n??14}):qi({...f,icon:r,iconSize:n??14}),b=zi({icon:"chevron-down",label:c,size:p??14,className:"persona-split-btn-chevron"+(m?" "+m:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});g.append(y,b);let v=null,w=()=>{if(v)return v;let e=("function"==typeof d?d():d)??void 0;return v=Fi({items:a,onSelect:s,anchor:g,position:l,portal:e,onOpenChange:e=>{b.setAttribute("aria-expanded",e?"true":"false")}}),e||g.appendChild(v.element),v};return g.isConnected?w():requestAnimationFrame(()=>{v||w()}),b.addEventListener("click",e=>{e.stopPropagation(),w().toggle()}),{element:g,primaryButton:y,chevronButton:b,openMenu:()=>w().show(),closeMenu:()=>v?.hide(),toggleMenu:()=>w().toggle(),destroy:()=>{v?.destroy(),g.remove()}}}function Vi(e){let{label:t,icon:r="chevron-down",menuItems:n,onSelect:o,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=ne("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=ne("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=xe(r,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",d.appendChild(p)),l&&(d.style.borderRadius=l.borderRadius??"10px",d.style.padding=l.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=l.background??"",d.style.borderColor=l.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let u=Fi({items:n,onSelect:e=>{d.setAttribute("aria-expanded","false"),o(e)},anchor:d,position:a,portal:s});return s||d.appendChild(u.element),d.addEventListener("click",e=>{if(e.stopPropagation(),"true"===d.getAttribute("data-persona-menu-locked"))return;let t=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",t?"false":"true"),u.toggle()}),d.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),d.click())}),{element:d,setLabel:e=>{c.textContent=e,d.setAttribute("aria-label",e)},open:()=>{d.setAttribute("aria-expanded","true"),u.show()},close:()=>{d.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let e=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",e?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),d.remove()}}}var Ui=e=>{let t=Di({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=e.layoutHeaderConfig?.onTitleClick;if(r){let e=t.headerTitle.parentElement;e&&(e.style.cursor="pointer",e.setAttribute("role","button"),e.setAttribute("tabindex","0"),e.addEventListener("click",()=>r()),e.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),r())}))}return t},Ki=e=>{let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,onHeaderAction:a}=e,s=t?.launcher??{},i=ne("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=Hi.minHeight,i.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let l,d,c=o?.titleMenu;if(c){let e=Vi({label:s.title??"Chat Assistant",menuItems:c.menuItems,onSelect:t=>{let r=r=>{!1===r&&e.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:t}}))},n=c.onSelect(t);n instanceof Promise?n.then(r,()=>{}):r(n)},hover:c.hover,className:""});l=e.element,l.style.color=Hi.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=ne("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=ne("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Hi.titleColor,Object.assign(d.style,$i),d.textContent=s.title??"Chat Assistant",l.appendChild(d),o?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=o.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=o?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??"10px",l.style.padding=e.padding??"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{l.style.backgroundColor=e.background??"",l.style.borderColor=e.border??""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:u,wrapper:h}=Ni(t,{showClose:r,wrapperClassName:p});n&&u.addEventListener("click",n);let m=ne("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let n of t){let{button:t,wrapper:o}=Bi({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?Bs(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",n.id),n.shortcut){let e=Ns(n.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(n.menuItems?.length){let e=Fi({items:n.menuItems,onSelect:e=>r?.(e),anchor:o,position:"bottom-right"});o.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(n.id));e.appendChild(o)}}(m,o?.trailingActions,o?.onAction??a);let g=s.clearChat??{},f=null,y=null;if(g.enabled??1){let e=g.placement??"inline",r=Ri(t,{wrapperClassName:"top-right"===e?"persona-absolute persona-top-4 persona-z-50":p});f=r.button,y=r.wrapper,"top-right"===e?y.style.right="48px":m.appendChild(y)}m.appendChild(h),i.appendChild(m);let b=ne("div");b.style.display="none";let v=ne("span");return v.style.display="none",{header:i,iconHolder:b,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:y}},Ji={default:Ui,minimal:Ki},Gi=e=>Ji[e]??Ji.default,Yi=(e,t,r)=>{if(t?.render){let n=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),o=ne("div");o.style.display="none";let a=ne("span"),s=ne("span"),i=ne("button");i.style.display="none";let l=ne("div");return l.style.display="none",{header:n,iconHolder:o,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let n=Gi(t?.layout??"default")({config:e,showClose:t?.showCloseButton??r?.showClose??!0,onClose:r?.onClose,onClearChat:r?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(!1===t.showIcon&&(n.iconHolder.style.display="none"),!1===t.showTitle&&(n.headerTitle.style.display="none"),!1===t.showSubtitle&&(n.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(n.closeButton.style.display="none"),!1===t.showClearChat&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n},Xi=e=>{let{config:t}=e,r=oe("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"}}),n=Yo(),o=oe("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":""}}),{textarea:a,attachAutoResize:s}=_o(t);s();let i=Uo(t),l=Ko(t),d=Jo(t),c=Go(t),p=oe("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(p),d&&(d.previewsContainer.style.gap="8px",p.append(d.previewsContainer),o.append(d.input)),o.append(a);let u=oe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=oe("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=oe("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&h.append(d.wrapper),l&&m.append(l.wrapper),m.append(i.wrapper),u.append(h,m),o.append(u),o.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),"transient"===t?.statusIndicator?.mode?r.append(n,c,o):r.append(n,o,c),{footer:r,suggestions:n,composerForm:o,header:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}},Qi=e=>{let{config:t}=e,r=oe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Yo(),o=Go(t);o.style.display="none";let{textarea:a,attachAutoResize:s}=_o(t,{defaultMaxLines:5});s();let i=Uo(t),l=Ko(t),d=Jo(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=oe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=oe("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=oe("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});l&&u.append(l.wrapper),u.append(i.wrapper),c.addEventListener("click",e=>{e.target!==i.button&&e.target!==i.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&e.target!==d?.button&&e.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(p,a,u);let h=oe("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(n,c,o);let m=c;return{footer:r,suggestions:n,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:o,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:p,rightActions:u,setSendButtonMode:i.setMode}};function Zi(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=oe("span",{className:ae("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&&r.style.setProperty("--persona-mention-token-accent",e.color);let n=xe(e.iconName??"at-sign",13,"currentColor",2);if(n){let e=ne("span","persona-mention-token-icon");e.appendChild(n),r.appendChild(e)}return r.appendChild(oe("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}var el=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")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:")&&e.includes(":"))},tl=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(n),e.appendChild(o),e},rl=(e,t,r)=>{if(t){let n=t({config:r??{},streaming:!0,location:e,defaultRenderer:tl});if(null!==n)return n}return tl()},nl=(e,t,r="div")=>{let n=ne(r,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ol=(e,t="bubble")=>{let r=["persona-message-bubble"];switch(t){case"flat":"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3")}return r},al={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},sl="custom:",il=e=>`${sl}${e}`,ll=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),dl=(e,t,r,n)=>{let o=t.showCopy??!0,a=t.showUpvote??!1,s=t.showDownvote??!1,i=t.showReadAloud??!1,l=(t.showRegenerate??!1)&&!0===n?.canRegenerate,d=(t.showEdit??!1)&&!0===n?.canEdit,c=(t.showQuote??!1)&&!1!==n?.canQuote,p=ll(t,e.role);if(!(o||a||s||i||l||d||c||0!==p.length)){let t=ne("div");return t.style.display="none",t.id=`actions-${e.id}`,t.setAttribute("data-actions-for",e.id),t}let u=t.visibility??"hover",h=t.align??"right",m=t.layout??"pill-inside",g=ne("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${{left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h]} ${{"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[m]} ${"hover"===u?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(e,t,r)=>{let n=zi({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return n.setAttribute("data-action",r),n};o&&g.appendChild(f("copy","Copy message","copy")),i&&g.appendChild(f("volume-2","Read aloud","read-aloud")),a&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),l&&g.appendChild(f("refresh-cw","Regenerate response","regenerate")),d&&g.appendChild(f("pencil","Edit message","edit")),c&&g.appendChild(f("quote","Quote message","quote"));for(let e of p)g.appendChild(f(e.iconName??"ellipsis",e.label,il(e.id)));return g},cl=(e,t,r,n,o,a)=>{let s=r??{},i=s.layout??"bubble",l=s.avatar,d=s.timestamp,c=l?.show??!1,p=d?.show??!1,u=l?.position??"left",h=d?.position??"below",m=ol(e.role,i),g=ne("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":"assistant-message");let f=Za(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message;((e,t,r="bubble",n)=>{if(!n)return;let o="user"===t?"user":"assistant",a=al[r??"bubble"]??al.bubble;n.padding&&(e.style.padding=`var(--persona-message-${o}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${o}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${o}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${o}-font-family, inherit)`)})(g,e.role,i,"user"===e.role?{...f.user,...y?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...f.assistant,...y?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),"flat"===i?(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):"user"===e.role?(g.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",g.style.color="var(--persona-message-user-text, white)"):"assistant"===e.role&&(g.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",g.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),v=e.content?.trim()??"",w=b.length>0&&v===Jr,x=_s(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?Xs(x.type,C):null,k="assistant"===e.role&&!0===S?.isAnimating?.(e),A="assistant"===e.role&&null!==S&&(!!e.streaming||k);A&&S?.bubbleClass&&g.classList.add(S.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),A&&S&&(S.containerClass&&M.classList.add(S.containerClass),M.style.setProperty("--persona-stream-step",`${x.speed}ms`),M.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let I=A?Qs(e.content??"",x.buffer,S,e,!!e.streaming):e.content??"",T=()=>{let r=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent});return A&&"char"===S?.wrap?ai(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?ai(r,"word",e.id,{skipTags:S.skipTags}):r},E=null;if(w?(E=document.createElement("div"),E.innerHTML=T(),E.style.display="none",M.appendChild(E)):e.contentSegments?.length?((e,t,r,n)=>{let o=Math.random().toString(36).slice(2,8),a=e=>`${o}:${e}`,s=r(t.map((e,t)=>"text"===e.kind?e.text:a(t)).join(""));if(!t.every((e,t)=>"text"===e.kind||s.includes(a(t))))return void e.replaceChildren(((e,t)=>{let r=document.createDocumentFragment();for(let n of e)"text"!==n.kind?r.appendChild(Zi(n.ref,{readonly:!0,render:t})):r.appendChild(document.createTextNode(n.text));return r})(t,n));e.innerHTML=s;let i=new RegExp(`${o}:(\\d+)`),l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),d=[];for(let e=l.nextNode();e;e=l.nextNode())d.push(e);for(let e of d){let r=e;for(let e=i.exec(r.data);e;e=i.exec(r.data)){let o=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===o?.kind&&a.parentNode?.insertBefore(Zi(o.ref,{readonly:!0,render:n}),a),r=a}}})(M,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=T(),A&&S?.useCaret&&!w&&v){let e=si(),t=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=M.lastElementChild;t?t.appendChild(e):M.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=nl(e,d,"span");t.classList.add("persona-timestamp-inline");let r=M.lastElementChild;r?r.appendChild(t):M.appendChild(t)}if(b.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let n=ne("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),r?.())};return e.forEach((e,t)=>{let r=ne("img");r.alt=e.alt?.trim()||`Attached image ${t+1}`,r.loading="lazy",r.decoding="async",r.referrerPolicy="no-referrer",r.style.display="block",r.style.width="100%",r.style.maxWidth="320px",r.style.maxHeight="320px",r.style.height="auto",r.style.objectFit="contain",r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let a=!1;o+=1,r.addEventListener("error",()=>{a||(a=!0,o=Math.max(0,o-1),r.remove(),0===o&&s())}),r.addEventListener("load",()=>{a=!0}),(e=>{let t=e.toLowerCase();return!(t.startsWith("data:image/svg+xml")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:image/")&&e.includes(":"))})(e.image)?(r.src=e.image,n.appendChild(r)):(a=!0,o=Math.max(0,o-1),r.remove())}),0===o?(s(),null):n}catch{return r?.(),null}})(b,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let L=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"audio"===e.type&&"string"==typeof e.audio&&e.audio.trim().length>0):[])(e);if(L.length>0){let e=(e=>{if(0===e.length)return null;try{let t=ne("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!el(e.audio))return;let n=ne("audio");n.controls=!0,n.preload="metadata",n.src=e.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(L);e&&g.appendChild(e)}let P=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"video"===e.type&&"string"==typeof e.video&&e.video.trim().length>0):[])(e);if(P.length>0){let e=(e=>{if(0===e.length)return null;try{let t=ne("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!el(e.video))return;let n=ne("video");n.controls=!0,n.preload="metadata",n.src=e.video,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",n.style.maxHeight="320px",n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(P);e&&g.appendChild(e)}let B=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"file"===e.type&&"string"==typeof e.data&&e.data.trim().length>0):[])(e);if(B.length>0){let e=(e=>{if(0===e.length)return null;try{let t=ne("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!el(e.data))return;let n=ne("a");n.href=e.data,n.download=e.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let N=e.contentSegments?.length?null:(e=>{if(!e||0===e.length)return null;let t=oe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=oe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),n=ne("span","persona-mention-chip-icon"),o=xe(r.iconName??"at-sign",13,"currentColor",2);o&&n.appendChild(o),e.appendChild(n),e.appendChild(oe("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(N&&g.appendChild(N),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=nl(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let R="assistant"===e.role?((e,t)=>{if(!e)return null;let r=(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}})(e);if(null===r)return null;let n=t?.[e];return(void 0!==n?n:r)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!I||!I.trim()),t="skeleton"===x.placeholder,r=t&&"line"===x.buffer&&e;if(e)r&&g.appendChild(ii());else if(t)g.appendChild(ii());else{let e=rl("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}R&&e.stopReason&&!e.streaming&&(v||(M.style.display="none"),g.appendChild(((e,t)=>{let r=ne("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r})(e.stopReason,R)));let H="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==n?.enabled,$=a?.actionEligibility,W="user"===e.role&&!e.streaming&&!1!==n?.enabled&&(!0===n?.showEdit&&!0===$?.canEdit||!0===n?.showQuote&&!0===$?.canQuote||ll(n,"user").length>0);if((H||W)&&n){let t=dl(e,W?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,o,$);g.appendChild(t)}if(!c||"system"===e.role)return g;let D=ne("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),O=((e,t)=>{let r=ne("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n="user"===t?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=ne("img");e.src=n,e.alt="user"===t?"User":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent="user"===t?"U":"A",r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?D.append(g,O):D.append(O,g),D},pl=(e,t,r,n,o,a)=>{let s=r??{};return"user"===e.role&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):"assistant"===e.role&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):cl(e,t,r,n,o,a)},ul=(e,t,r)=>{t.hidden=!r,t.style.display=r?"":"none",e.classList.toggle("persona-gap-6",r),e.classList.toggle("persona-gap-3",!r)},hl=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=""===t.subtitle,((e,t)=>{if(e.replaceChildren(),t){if("function"==typeof t){let r=null;try{r=t()}catch(e){console.warn("[persona] welcome.icon renderer threw",e)}return r?(e.appendChild(r),void(e.hidden=!1)):void(e.hidden=!0)}if("lucide"===t.type){let r=xe(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(oe("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(oe("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1}else e.hidden=!0})(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-layout",t.layout??"top"),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),"inline"===t.iconPlacement?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},ml="data-persona-welcome-overlay",gl="persona-welcome-overlay-active",fl=new WeakMap,yl=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(ml,""),e.classList.contains(gl)||(fl.set(e,e.scrollTop),e.classList.add(gl),e.scrollTop=0)},bl=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(ml),e.classList.contains(gl)&&(e.classList.remove(gl),e.scrollTop=fl.get(e)??e.scrollTop,fl.delete(e))},vl=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let n=r?.layout?.messages?.layout??"bubble",o=oe("div",{className:ol("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===n?{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(oe("div",{className:"persona-flex"},o)),e.hidden=!1},wl=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xl=new WeakSet,Cl=(e,t)=>!!e&&void 0!==e[t],Sl=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,n=e?.copy,o=!0===e?.future?.v5Defaults,a=r?.layout??(o?"centered":"top"),s=Cl(r,"variant")?r.variant:!1===n?.showWelcomeCard?"none":"card",i="hero"!==s||o||void 0!==r?.layout?Cl(r,"dismiss")?r.dismiss:o||"hero"===s?"on-first-message":"never":"on-first-message",l=[];Cl(r,"title")&&Cl(n,"welcomeTitle")&&l.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Cl(r,"subtitle")&&Cl(n,"welcomeSubtitle")&&l.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Cl(r,"variant")&&Cl(n,"showWelcomeCard")&&l.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),"hero"===s&&Cl(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!o&&void 0===r?.layout&&"hero"===s&&Cl(r,"dismiss")&&"on-first-message"!==r.dismiss&&l.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let d=r?.anchor??("centered"===a&&t?"center":"bottom"),c=null!==Is(r?.anchorComposerTop);return Cl(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(Cl(r,"anchorComposerTop")||Cl(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{!e||!0!==e.debug||!t.length||xl.has(e)||(xl.add(e),t.forEach(e=>console.warn(`[persona] ${e}`)))})(e,l),{title:Cl(r,"title")?r.title:n?.welcomeTitle??(o?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:Cl(r,"subtitle")?r.subtitle:n?.welcomeSubtitle??(o?"":"I can answer questions and help you get things done here."),icon:r?.icon,align:"start"===r?.align||"center"===r?.align?r.align:"centered"===a?"center":void 0,iconPlacement:r?.icon&&"function"!=typeof r.icon&&"inline"===r.icon.placement?"inline":"above",variant:s,dismiss:i,message:"hero"===s?void 0:r?.message,layout:a,anchor:d,anchorComposerTop:c?r.anchorComposerTop:"44%",composerGap:r?.composerGap?.trim()||As}},kl=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!(t??[]).some(e=>"user"===e.role)),Al="var(--persona-components-panel-height)",Ml=e=>{let t=F(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,n=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===n?`max(200px, ${Al})`:`max(200px, calc(${Al} - ${n}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},Il="16px",Tl="10px",El="14px",Ll=e=>{let t=oe("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ci(e)}});return t.hidden=!0,t},Pl=(e,t)=>{let r=((e,t,r={})=>{let n=oe("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let o=ne("p","persona-welcome-kicker");o.hidden=!0;let a=ne("h2","persona-welcome-title"),s=ne("p","persona-welcome-subtitle"),i=oe("div",{className:"persona-welcome-head-text"},o,a),l=oe("div",{className:"persona-welcome-title-row"},n,i);return{host:oe("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:r.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},l,s,t),iconHolder:n,kicker:o,title:a,subtitle:s,starterSuggestions:t}})(0,Ll("starter"),{flatShadow:vi(e)}),n=Sl(e);hl(r,n),ul(t,r.host,kl(n,e?.initialMessages));let o=(()=>{let e=oe("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return vl(o,n.message,e),{welcome:r,greetingHost:o}},Bl=(e,t)=>{let r=ne("button");r.type="button",r.innerHTML='\n <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">💬</span>\n <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />\n <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">\n <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>\n <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>\n </span>\n <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">↗</span>\n ',r.addEventListener("click",t);let n=e=>{let t=e.launcher??{},n=vi(e),o="circle"===Ha(e);o?(r.dataset.personaLauncherVariant="circle",r.setAttribute("aria-label",t.title??"Open chat")):(r.removeAttribute("data-persona-launcher-variant"),r.removeAttribute("aria-label"));let a=r.querySelector("[data-role='launcher-title']");if(a){let e=t.title??"Chat Assistant";a.textContent=e,a.setAttribute("title",e)}let s=r.querySelector("[data-role='launcher-subtitle']");if(s){let e=t.subtitle??"Here to help you get answers fast";s.textContent=e,s.setAttribute("title",e)}let i=r.querySelector(".persona-flex-col");i&&(t.textHidden||n||o?i.style.display="none":i.style.display="");let l=r.querySelector("[data-role='launcher-icon']");if(l)if(t.agentIconHidden)l.style.display="none";else{let e=t.agentIconSize??"40px";if(l.style.height=e,l.style.width=e,t.agentIconBackgroundColor?(l.style.backgroundColor=t.agentIconBackgroundColor,l.classList.remove("persona-bg-persona-primary")):(l.style.backgroundColor="",l.classList.add("persona-bg-persona-primary")),l.innerHTML="",t.agentIconName){let r=parseFloat(e)||24,n=xe(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);n?(l.appendChild(n),l.style.display=""):(l.textContent=t.agentIconText??"💬",l.style.display="")}else t.iconUrl?l.style.display="none":(l.textContent=t.agentIconText??"💬",l.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let e=t.agentIconSize??"40px";d.style.height=e,d.style.width=e,!t.iconUrl||t.agentIconName||t.agentIconHidden?d.style.display="none":(d.src=t.iconUrl,d.style.display="block")}let c=r.querySelector("[data-role='launcher-call-to-action-icon']");if(c){let e=t.callToActionIconSize??"32px";c.style.height=e,c.style.width=e,t.callToActionIconBackgroundColor?(c.style.backgroundColor=t.callToActionIconBackgroundColor,c.classList.remove("persona-bg-persona-primary")):(c.style.backgroundColor="",c.classList.add("persona-bg-persona-primary")),t.callToActionIconColor?(c.style.color=t.callToActionIconColor,c.classList.remove("persona-text-persona-call-to-action")):(c.style.color="",c.classList.add("persona-text-persona-call-to-action"));let r=0;if(t.callToActionIconPadding?(c.style.boxSizing="border-box",c.style.padding=t.callToActionIconPadding,r=2*(parseFloat(t.callToActionIconPadding)||0)):(c.style.boxSizing="",c.style.padding=""),t.callToActionIconHidden||o)c.style.display="none";else if(c.style.display=n?"none":"",c.innerHTML="",t.callToActionIconName){let n=parseFloat(e)||24,o=Math.max(n-r,8),a=xe(t.callToActionIconName,o,"currentColor",1.5);a?c.appendChild(a):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&Ii[t.position]?Ii[t.position]:Ii["bottom-right"];r.className=n?"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":`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 ${p}`,n||(r.style.zIndex=String(t.zIndex??pn)),r.style.border=t.border??"1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",r.style.boxShadow=void 0!==t.shadow?""===t.shadow.trim()?"none":t.shadow:"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?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=t.collapsedMaxWidth??"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")};return e&&n(e),{element:r,update:n,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},Nl=new Set,Rl=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},Hl=(e,t)=>{let r=ne("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let n=e??{},o=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(o?.frequency??"once")&&!1!==n.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,!a||!d||(d=!1,a.hidden=!0),((e,t)=>{if(Nl.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(Rl(n),e&&h())},f=e=>{!o||p||g("user"===e&&d)},y=()=>{l=null,a&&!p&&!u&&(c=!0,d=!0,a.hidden=!1,!(typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||"function"!=typeof a.animate)&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},b=()=>{g(h()),t()},v=e=>{e.stopPropagation(),g(h())},w=Bl(e,()=>{f("user"),t()}),x=()=>{m(),i?.removeEventListener("click",b),s?.removeEventListener("click",v),a?.remove(),a=null,i=null,s=null,d=!1},C=()=>{let e=n.launcher?.position??"bottom-right",t=Ii[e]??Ii["bottom-right"];if(!a)return r.className="persona-launcher-surface",r.removeAttribute("data-teaser"),r.style.zIndex="",void(w.element.style.position="");r.className=ae("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(n.launcher?.zIndex??pn),w.element.style.position="static"},S=e=>{let t=(e=>{let t=e?.launcher?.teaser;return t&&t.text&&!1!==e?.launcher?.enabled&&!vi(e??{})?t:null})(e);o=t,t?(a||(i=oe("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",b),s=oe("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=oe("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},i,s),r.insertBefore(a,w.element)),i.textContent=t.text,s.hidden=!1===t.dismissible,s.setAttribute("aria-label",t.dismissLabel??"Dismiss message"),!o||!a||p||c||u||((e,t)=>{if(Nl.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(Rl(n),h())||(m(),l=setTimeout(y,Math.max(0,o.delayMs??0)))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:y,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{n=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}},$l=({config:e,showClose:t})=>{let{wrapper:r,panel:n,pillRoot:o}=(e=>{let t=e?.launcher?.enabled??!0,r=vi(e);if(wi(e)){let t=e?.launcher?.composerBar??{},r=ne("div","persona-widget-wrapper persona-fixed persona-transition");r.setAttribute("data-persona-composer-bar",""),r.dataset.state="collapsed",r.dataset.expandedSize=t.expandedSize??"anchored",r.style.zIndex=String(e?.launcher?.zIndex??pn);let n=ne("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");n.style.width="100%",r.appendChild(n);let o=ne("div","persona-widget-pill-root");return o.setAttribute("data-persona-composer-bar",""),o.dataset.state="collapsed",o.dataset.expandedSize=t.expandedSize??"anchored",o.style.zIndex=String(e?.launcher?.zIndex??pn),{wrapper:r,panel:n,pillRoot:o}}if(r){let e=ne("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=ne("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=ne("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=ne("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),n=F(e),o=n.launcherWidth||n.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?Ml(e).width:"100%";return t.style.width=o,r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let n=e?.launcher??{},o=n.position&&Ii[n.position]?Ii[n.position]:Ii["bottom-right"],a=ne("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??pn);let s=ne("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=Ml(e);return s.style.width=i.width,s.style.maxWidth=i.maxWidth,a.appendChild(s),{wrapper:a,panel:s}})(e),a=((e,t=!0)=>{if(wi(e))return((e,t)=>{let r=ne("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:o}=Ni(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Il,iconSize:Tl});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=Ri(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Il,iconSize:El});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=oe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=oe("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"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=Pl(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=ne("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=Ll("followUp"),b=ks(e,!0);b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),l.append(p,c,g,f);let v=oe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),w=Qi({config:e}),{root:x,textNode:C}=(()=>{let e=oe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=ne("span","persona-pill-peek__icon"),r=I(A,16,"currentColor",1.5);r&&t.appendChild(r);let n=ne("span","persona-pill-peek__text"),o=ne("span","persona-pill-peek__caret"),a=I(y,16,"currentColor",1.5);return a&&o.appendChild(a),e.append(t,n,o),{root:e,textNode:n}})();return r.append(i,o,l,v),s&&r.appendChild(s),{container:r,body:l,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:f,composerOverlay:v,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,welcomeHost:p,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:u,introSubtitle:h,closeButton:n,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:ne("span"),headerTitle:ne("span"),headerSubtitle:ne("span"),header:i,footer:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode,peekBanner:x,peekTextNode:C}})(e,t);let r=oe("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"}}),n=e?.layout?.header,o=!1!==e?.layout?.showHeader,a=n?Yi(e,n,{showClose:t}):Di({config:e,showClose:t}),s=oe("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:i,greetingHost:l}=Pl(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=ne("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=Ll("followUp"),g=ks(e,!1);g&&(h.style.maxWidth=g,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),s.append(d,l,h,m);let f=Xi({config:e}),b=!1!==e?.layout?.showFooter;o||(a.header.style.display="none"),Oi(r,a,e),r.append(s);let v=oe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return b||(f.footer.style.display="none"),r.append(f.footer),r.append(v),{container:r,body:s,messagesWrapper:h,starterSuggestions:u,transcriptSuggestions:m,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,welcomeHost:d,welcomeIconHolder:i.iconHolder,greetingHost:l,introKicker:i.kicker,introTitle:c,introSubtitle:p,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}})(e,t),s={wrapper:r,panel:n,pillRoot:o},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},l={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:l,composer:d,replaceHeader:e=>(l.element.replaceWith(e.header),l.element=e.header,l.iconHolder=e.iconHolder,l.headerTitle=e.headerTitle,l.headerSubtitle=e.headerSubtitle,l.closeButton=e.closeButton,l.closeButtonWrapper=e.closeButtonWrapper,l.clearChatButton=e.clearChatButton,l.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{d.footer.replaceWith(e),d.footer=e}}},Wl=({config:e,plugins:t,onToggle:r})=>{let n=t.find(e=>e.renderLauncher);if(n?.renderLauncher){let t=n.renderLauncher({config:e,defaultRenderer:()=>Bl(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let o=Hl(e,r);return{instance:o,element:o.element}},Dl=(e,t,r)=>{let n=r;for(let r of t){let t=ne("span","persona-tool-char");t.style.setProperty("--char-index",String(n)),t.textContent=" "===r?" ":r,e.appendChild(t),n++}return n},Ol=(e,t,r)=>{Ee(e,t,{stateSet:r,previewKind:"reasoning",iconColor:"currentColor"})},Fl=(e,t,r=new Set)=>{t=Le(t,"reasoning");let n=e.reasoning,o=Se("persona-reasoning-bubble",e.id);if(!n)return Ne(o,e,t,"reasoning");let a=t?.features?.reasoningDisplay??{},s=a.expandable??J.expandable,i=s&&r.has(e.id),l="complete"!==n.status,d=((e,t)=>{let r=e.reasoning?.chunks.join("").trim()??"";return r?r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,a.previewMaxLines??J.previewMaxLines),c=ke({expandable:s,expanded:i,bubbleType:"reasoning"}),p=ne("div","persona-flex persona-flex-col persona-text-left"),u=ne("span","persona-text-xs persona-text-persona-primary"),h="row"===Pe(t,"reasoning"),m=h&&!l?`Thought for ${Be(n.durationMs??(void 0!==n.completedAt&&void 0!==n.startedAt?n.completedAt-n.startedAt:void 0))}`:"Thinking...",g=t?.reasoning??{},f=String(n.startedAt??Date.now()),y=()=>{let e=ne("span","");return e.setAttribute("data-tool-elapsed",f),e.textContent=Nr(n),e},b=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:m,previewText:d,isActive:l,config:t??{},elapsed:Nr(n),createElapsedElement:y});"string"==typeof b&&b.trim()?(u.textContent=b,p.appendChild(u)):b instanceof HTMLElement?p.appendChild(b):(u.textContent=m,p.appendChild(u));let v=ne("span","persona-text-xs persona-text-persona-primary");v.textContent=(e=>"complete"===e.status?(e=>{let t=e.completedAt??Date.now(),r=e.startedAt??t,n=(void 0!==e.durationMs?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"pending"===e.status?"Waiting":"")(n),h||p.appendChild(v);let w=a.loadingAnimation??J.loadingAnimation,x=g.activeTextTemplate,C=g.completeTextTemplate,S=l?x:C,k=b instanceof HTMLElement,A=(e,t)=>{u.textContent="";let r=Hr(e,""),o=0;for(let e of r){let r=e.styles.length>0?(()=>{let t=ne("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return u.appendChild(t),t})():u;if(e.isDuration&&l)r.appendChild(y());else{let a=e.isDuration?Nr(n):e.text;t?o=Dl(r,a,o):r.appendChild(document.createTextNode(a))}}};if(!k&&S)if(v.style.display="none",u.style.display="",l&&"none"!==w){let e=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),"pulse"===w?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),A(S,!1)):(u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),A(S,!0))}else A(S,!1);else if(!k&&l&&"none"!==w){u.style.display="";let e=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),"pulse"===w)u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`);else{u.classList.add(`persona-tool-loading-${w}`),u.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===w&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let t=u.textContent||m;u.textContent="",Dl(u,t,0)}"complete"===n.status&&!h&&(u.style.display="none")}else k||("complete"!==n.status||h?u.style.display="":u.style.display="none");if(a.iconName&&!k){let e=ne("span","persona-reasoning-header-icon"),t=xe(a.iconName,16,"currentColor",2);t&&(e.appendChild(t),c.appendChild(e))}let M="currentColor",I=Me(c,p,{expandable:s,expanded:i,iconColor:M,metaGap:!1}),T=Ie({bubble:o,previewKind:"reasoning",expanded:i,isActive:l,previewText:d,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return o.append(c,T),Ne(o,e,t,"reasoning");let E=ne("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let L=n.chunks.join(""),P=ne("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return P.textContent=L||("complete"===n.status?"No additional context was shared.":"Waiting for details…"),E.appendChild(P),Te({expanded:i,header:c,toggleIcon:I,content:E,collapsedPreview:T,iconColor:M}),o.append(c,T,E),Ne(o,e,t,"reasoning")},zl=e=>{if(null==e)return!0;if("string"==typeof e){if(!e.trim())return!0;try{return zl(JSON.parse(e))}catch{return!1}}return"object"==typeof e&&0===Object.keys(e).length},ql=e=>{if(null!==e&&"object"==typeof e)return!0;if("string"!=typeof e)return!1;try{let t=JSON.parse(e);return null!==t&&"object"==typeof t}catch{return!1}},jl=new WeakMap,_l=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),Vl=(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)"},Ul=(e,t)=>{let r=e.toolCall,n=t?.features?.toolCallDisplay,o=n?.collapsedMode??K.collapsedMode,a=!1===r?.success?r.error||"Tool failed":((e,t)=>{let r=e.toolCall;if(!r)return"";let n=(r.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join("\n");let o=Lr(r.args).trim();return o?o.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join("\n"):""})(e,n?.previewMaxLines??K.previewMaxLines),s=r?"row"===Pe(t,"tool")?`${"complete"===r.status?"Used":"Using"} ${r.name?.trim()||"tool"}`:(e=>"complete"===e.status?(e=>{let t=("number"==typeof e.duration?e.duration:"number"==typeof e.durationMs?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`})(e):"Using tool...")(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i="complete"!==r.status,l=t?.toolCall??{},d=s;return"tool-name"===o?d=r.name?.trim()||s:"tool-preview"===o&&a&&(d=a),i&&l.activeTextTemplate?d=Rr(r,l.activeTextTemplate,d):!i&&l.completeTextTemplate&&(d=Rr(r,l.completeTextTemplate,d)),!1===r.success?d+=" · Failed":r.superseded&&(d+=" · Approved, ran again below"),{summary:d,previewText:a,isActive:i}},Kl=(e,t,r,n)=>{Ee(e,t,{stateSet:r,previewKind:"tool",iconColor:_l(n?.toolCall??{},t.classList.contains("persona-activity-row"))})},Jl=(e,t,r=new Set)=>{t=Le(t,"tool");let n=e.toolCall,o=t?.toolCall??{},a=Se("persona-tool-bubble",e.id);if(o.backgroundColor&&(a.style.backgroundColor=o.backgroundColor),o.borderColor&&(a.style.borderColor=o.borderColor),o.borderWidth&&(a.style.borderWidth=o.borderWidth),o.borderRadius&&(a.style.borderRadius=o.borderRadius),a.style.boxShadow=void 0!==o.shadow?""===o.shadow.trim()?"none":o.shadow:"var(--persona-tool-bubble-shadow)",!n)return Ne(a,e,t,"tool");let s=t?.features?.toolCallDisplay??{},i=s.expandable??K.expandable,l=i&&r.has(e.id),{summary:d,previewText:c,isActive:p}=Ul(e,t),u=ke({expandable:i,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let h=ne("div","persona-flex persona-flex-col persona-text-left"),m=ne("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let g=String(n.startedAt??Date.now()),f=()=>{let e=ne("span","");return e.setAttribute("data-tool-elapsed",g),e.textContent=Br(n),e},y=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:s.collapsedMode??K.collapsedMode,isActive:p,config:t??{},elapsed:Br(n),createElapsedElement:f});"string"==typeof y&&y.trim()?(m.textContent=y,h.appendChild(m)):y instanceof HTMLElement?h.appendChild(y):(m.textContent=d,h.appendChild(m));let b=s.loadingAnimation??K.loadingAnimation,v=o.activeTextTemplate,w=o.completeTextTemplate,x=p?v:w,C=(e,t)=>{m.textContent="";let r=n.name?.trim()||"tool",o=Hr(e,r),a=0;for(let e of o){let r=e.styles.length>0?(()=>{let t=ne("span",e.styles.map(e=>`persona-tool-text-${e}`).join(" "));return m.appendChild(t),t})():m;if(e.isDuration&&p)r.appendChild(f());else{let o=e.isDuration?Br(n):e.text;t?a=Dl(r,o,a):r.appendChild(document.createTextNode(o))}}};if(!(y instanceof HTMLElement))if(p&&"none"!==b){let e=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),"pulse"===b)m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${b}`),m.style.setProperty("--persona-tool-anim-duration",`${e}ms`),"shimmer-color"===b&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||d;m.textContent="",Dl(m,e,0)}}else x&&C(x,!1);let S=_l(o,"row"===Pe(t,"tool")),k=Me(u,h,{expandable:i,expanded:l,iconColor:S,metaGap:!0}),A=Ie({bubble:a,previewKind:"tool",expanded:l,isActive:p,previewText:c,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:p,config:t??{}})});if(!i)return a.append(u,A),Ne(a,e,t,"tool");let M=ne("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=l?"":"none",o.contentBackgroundColor&&(M.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(M.style.color=o.contentTextColor),o.contentPaddingX&&(M.style.paddingLeft=o.contentPaddingX,M.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(M.style.paddingTop=o.contentPaddingY,M.style.paddingBottom=o.contentPaddingY),!0===t.future?.v5Defaults)!function(e,t,r){let n=t.toolCall;if(!n)return;let o=r.toolCall??{},a=(t,r)=>{let n=oe("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:o.codeBlockBackgroundColor,borderColor:o.codeBlockBorderColor,borderWidth:o.codeBlockBorderColor?"1px":void 0}}),a=oe("div",{className:"persona-tool-detail-label",text:t,style:{color:o.labelTextColor}}),s=Lr(r),i=oe("pre",{className:"persona-tool-detail-value"+(ql(r)?" persona-tool-detail-code":""),text:s,attrs:s.length>420||s.split("\n").length>7?{tabindex:"0","aria-label":`${t} content`}:{},style:{color:o.codeBlockTextColor??o.contentTextColor}}),l=oe("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),d=xe("copy",14,"currentColor",1.7);d&&l.appendChild(d),n.append(a,i,l),e.appendChild(n)};zl(n.args)||a("Request",n.args);let s="complete"===n.status&&void 0!==n.result?n.result:n.chunks?.join("");void 0!==s&&("string"!=typeof s||s.trim())&&a("Response",s),!1===n.success&&e.appendChild(oe("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}(M,e,t);else{if(n.name){let e=ne("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,M.appendChild(e)}if(void 0!==n.args){let e=ne("div","persona-space-y-1"),t=ne("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Arguments";let r=ne("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Vl(r,o),r.textContent=Lr(n.args),e.append(t,r),M.appendChild(e)}if(n.chunks&&n.chunks.length){let e=ne("div","persona-space-y-1"),t=ne("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Activity";let r=ne("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Vl(r,o),r.textContent=n.chunks.join(""),e.append(t,r),M.appendChild(e)}if(!1===n.success&&M.appendChild(oe("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),"complete"===n.status&&void 0!==n.result){let e=ne("div","persona-space-y-1"),t=ne("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(t.style.color=o.labelTextColor),t.textContent="Result";let r=ne("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");r.style.fontSize="0.75rem",r.style.lineHeight="1rem",Vl(r,o),r.textContent=Lr(n.result),e.append(t,r),M.appendChild(e)}if("complete"===n.status&&"number"==typeof n.duration){let e=ne("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(e.style.color=o.contentTextColor),e.textContent=`Duration: ${n.duration}ms`,M.appendChild(e)}}return Te({expanded:l,header:u,toggleIcon:k,content:M,collapsedPreview:A,iconColor:S}),a.append(u,A,M),Ne(a,e,t,"tool")},{setLoader:Gl,load:Yl,provide:Xl,getSync:Ql}=se({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),Zl=Gl,ed=Yl,td=Ql,{setLoader:rd,load:nd}=se({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),od=rd,ad=nd,sd=new class{constructor(){this.components=new Map,this.#h=new Map}#h;register(e,t,r){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),r?this.#h.set(e,r):this.#h.delete(e)}unregister(e){this.components.delete(e),this.#h.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#h.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#h.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}},id=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:ld,load:dd,provide:cd,getSync:pd}=se({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ud=null,hd=new Set,md=e=>{if(ud)return ud;ud=e,e.initArtifactsUi({componentRegistry:sd});for(let t of id)sd.has(t)||sd.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Ve();t?e.__provideMarkdownParsers(t):_e(()=>{let t=Ve();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>ce());let r=[...hd];hd.clear();for(let e of r)try{e()}catch{}return e},gd=ld,fd=()=>dd().then(md),yd=()=>{if(ud)return ud;let e=pd();return e?md(e):null},bd=e=>ud?()=>{}:(hd.add(e),()=>{hd.delete(e)});function vd(e){return!0===e?.features?.artifacts?.enabled}function wd(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"),!vd(t))return;let r=t.features?.artifacts?.layout,n=r?.paneBorder?.trim(),o=r?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}var xd=["panel","seamless","detached"];function Cd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&xd.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Sd(e){return!(!e||!vd(e))&&"detached"===Cd(e)}function kd(e,t){if(!vd(t))return 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"),function(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")}(e),void wd(e,t);let r=t.features?.artifacts?.layout,n="detached"===Cd(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",r?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",r?.paneMaxWidth??"28rem"),r?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",r.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),r?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=r?.paneBackground?.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let a=r?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[r?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[r?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[r?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[r?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let n=t?.trim();n?e.style.setProperty(r,n):e.style.removeProperty(r)}wd(e,t)}function Ad(e,t){for(let t of xd)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!vd(t))return;let r=t.features?.artifacts?.layout,n=Cd(t);e.classList.add(`persona-artifact-appearance-${n}`);let o=r?.paneBorderRadius?.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=r?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=r?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}var Md=new Set(["__proto__","prototype","constructor"]),Id=new Set(["collapsed","card","panel","inline"]),Td=new Set(["markdown","component"]),Ed=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ld=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Pd=e=>!Md.has(e),Bd=e=>"string"==typeof e&&Id.has(e),Nd=e=>Object.keys(e).length>0;function Rd(e,t,r,n){e.push({path:t,code:r,message:n})}var Hd="Ignored because this key is not part of the persisted preference schema.",$d="Ignored an unsupported value.",Wd="Expected collapsed, panel, or inline.",Dd='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Od={kind:"mode",message:$d},Fd={kind:"string",message:"Expected a CSS length string."},zd={kind:"boolean"},qd={paneWidth:Fd,paneMaxWidth:Fd,paneMinWidth:Fd,expandedPanelWidth:Fd,resizableMinWidth:Fd,resizableMaxWidth:Fd,expandLauncherPanelWhenOpen:zd,resizable:zd},jd={kind:"object",message:"Expected a preference object.",children:{showToolCalls:zd,showReasoning:zd,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:$d},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:$d},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:$d},expandable:zd,grouped:zd}},reasoningDisplay:{kind:"object",children:{expandable:zd,activePreview:zd}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Od,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Od,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Td,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Td}}},filePreview:{kind:"object",children:{enabled:zd}},layout:{kind:"object",children:qd}}}}};function _d(e,t,r,n){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:Rd(n,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:Rd(n,r,"invalid_type",t.message);case"enum":return"string"==typeof e&&t.values.has(e)?e:Rd(n,r,"invalid_value",t.message);case"mode":return Bd(e)?$n(e):Rd(n,r,"invalid_value",t.message);case"modeMap":{if(!Ld(e))return Rd(n,r,"invalid_type","Expected an object.");let o="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=o?t:Wn(t);Pd(t)&&(o?o.has(t):Ed.test(e))?Bd(s)?a[e]=$n(s):Rd(n,`${r}.${t}`,"invalid_value",Wd):Rd(n,`${r}.${t}`,o?"unknown_key":"invalid_value",o?"Ignored an unsupported selector.":Dd)}return Nd(a)?a:void 0}case"object":{if(t.bareMode&&Bd(e))return $n(e);if(!Ld(e))return Rd(n,r,"invalid_type",t.message??"Expected an object.");let o=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!Pd(t)||!o.includes(t))&&Rd(n,a(t),"unknown_key",Hd);let s={};for(let r of o){let o=t.children[r],i=_d(e[r],o,a(r),n);if(o.deprecated&&void 0!==e[r]&&Rd(n,a(r),"deprecated_key",o.deprecated),void 0===i)continue;let l=o.alias??r,d=s[l];s[l]=Ld(d)&&Ld(i)?{...d,...i}:i}return Nd(s)?s:void 0}}}function Vd(e){let t=[];return{preferences:(null===e?void 0:_d(e,jd,"",t))??{},issues:t}}function Ud(e){if(Array.isArray(e))return e.map(Ud);if(!Ld(e))return e;let t={};for(let[r,n]of Object.entries(e))Pd(r)&&void 0!==n&&(t[r]=Ud(n));return t}function Kd(e,t){let r=Ud(e);for(let[e,n]of Object.entries(t)){if(!Pd(e)||void 0===n)continue;let t=r[e];r[e]=Ld(t)&&Ld(n)?Kd(t,n):Ud(n)}return r}function Jd(e,t){if(void 0===t)return void 0===e?void 0:Ud(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return void 0===e?void 0:Ud(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Nd(o)?{byMediaType:o}:{}};return Nd(a)?a:void 0}(r.files,t.files),s={...n?{default:n}:{},...Nd(o)?{byKind:o}:{},...void 0!==a?{files:a}:{}};return Nd(s)?s:void 0}function Gd(e={},t){let r=function(e){let t,r={};for(let n of e){let e=Vd(n).preferences;t=Jd(t,e.artifacts?.display),r=Kd(r,e)}let n=r;return n.artifacts&&(void 0!==t?n.artifacts.display=t:delete n.artifacts.display),n}(t),n={...e};if(void 0!==r.showToolCalls&&(n.showToolCalls=r.showToolCalls),void 0!==r.showReasoning&&(n.showReasoning=r.showReasoning),r.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...r.toolCallDisplay}),r.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...r.reasoningDisplay}),r.artifacts){let t=e.artifacts??{},o={...t};if(void 0!==r.artifacts.display){let e=Jd(t.display,r.artifacts.display);void 0!==e&&(o.display=e)}r.artifacts.filePreview&&(o.filePreview={...t.filePreview,enabled:r.artifacts.filePreview.enabled}),r.artifacts.layout&&(o.layout={...t.layout,...r.artifacts.layout}),n.artifacts=o}return n}function Yd(e){let t=e.preferences;return t&&Nd(t)?{...e,features:Gd(e.features??{},[t])}:e}function Xd(e,t){let r=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",n=/^([\d.]+)px$/i.exec(r);if(n)return Number(n[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}var{setLoader:Qd,load:Zd,provide:ec,getSync:tc}=se({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),rc=Qd,nc=Zd,oc=tc,ac=new class{#h=new Map;register(e){this.#h.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#h.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#h.get(e);t&&(t.onUnregister?.(),this.#h.delete(e))}getAll(){return Array.from(this.#h.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||0===e.length)return t;let r=new Set(e.map(e=>e.id));return[...t.filter(e=>!r.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#h.forEach(e=>e.onUnregister?.()),this.#h.clear()}},sc=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),ic=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),lc=(e,t,r)=>{if(!sc(e)||!sc(t)||ic.has(r))return t;let n={...e};for(let o of Object.keys(t)){if(void 0===t[o]){delete n[o];continue}let a=r?`${r}.${o}`:o;n[o]=lc(e[o],t[o],a)}return n};function dc(e,t){let r=B(X),n=function(e,t,r){let n=t[L];if(n)return n;let o=new Set(R(e,r));for(let e of r){let r=N(t,e);"clear"===r&&o.delete(e),"explicit"===r&&o.add(e)}return[...o]}(e,t,r),o=H(function(e,t,r){let n={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),o=n;for(let e of t.slice(0,-1)){let t=o[e];if(!P(t)){o=void 0;break}o[e]={...t},o=o[e]}o&&delete o[t[t.length-1]]}return n}(lc(e,t,""),r,n),n);return z(re(o),((e,t)=>{let r=t[W];if(r)return{...r};let n=F(e);return D(t,"launcherWidth")&&(n.legacyLauncherWidth=void 0!==t.launcherWidth),D(t,"launcher")&&void 0===t.launcher?(n.launcherWidth=!1,n.sidebarWidth=!1,n.dockWidth=!1,n):(D(t.launcher,"width")&&(n.launcherWidth=void 0!==t.launcher?.width),D(t.launcher,"sidebarWidth")&&(n.sidebarWidth=void 0!==t.launcher?.sidebarWidth),D(t.launcher,"dock")&&void 0===t.launcher?.dock?n.dockWidth=!1:D(t.launcher?.dock,"width")&&(n.dockWidth=void 0!==t.launcher?.dock?.width),n)})(e,t))}var cc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=(e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e})(e),r=(e=>{let t=e.trim(),r=t.indexOf("{");if(-1===r)return null;let n=0;for(let e=r;e<t.length;e+=1){let o=t[e];if("{"===o&&(n+=1),"}"===o&&(n-=1,0===n))return t.slice(r,e+1)}return null})(t);if(!r)return null;let n=JSON.parse(r);if(!n||"object"!=typeof n||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},pc=e=>"string"==typeof e?e:null==e?"":String(e),uc={message:e=>"message"!==e.type?void 0:{handled:!0,displayText:pc(e.payload.text)},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,n=pc(r.element);if(n&&t.document?.querySelector){let e=t.document.querySelector(n);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:pc(r.text)}}},hc=e=>Array.isArray(e)?e.map(e=>String(e)):[],mc=e=>{let t=new Set(hc(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let n="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!n&&"string"==typeof r.text&&r.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 o=n?e.parsers.reduce((e,t)=>e||t?.({text:n,message:r.message})||null,null):null;if(!o)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:o,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let n=()=>{e.emit("action:resubmit",a)},s=t(o,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:n});if(!s)continue;if(s.handled){let e=!1!==s.persistMessage;return{text:void 0!==s.displayText?s.displayText:"",persist:e,resubmit:s.resubmit}}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",e)}return{text:"",persist:!0}},syncFromMetadata:()=>{t=new Set(hc(e.getSessionMetadata().processedActionMessageIds))}}},gc=e=>e.map(e=>({...e,streaming:!1})),fc=e=>e.map(e=>({...e,status:"complete"})),yc=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?(e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}})(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let t={...r,messages:r.messages?gc(r.messages):void 0,artifacts:r.artifacts?fc(r.artifacts):void 0};n.setItem(e,JSON.stringify(t))}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",e)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}},bc=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let r=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return(e=>{let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")})(e)},{setLoader:vc,load:wc}=se({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),xc=vc,Cc=wc,{setLoader:Sc,load:kc,provide:Ac,getSync:Mc}=se({fallbackImport:()=>import("./history-shell")}),Ic=Sc,Tc=kc,Ec=Mc;function Lc(){return null}var Pc=d(p(),1);function Bc(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return e;try{let t=function(e,t){if(!function(e){if(!e||"object"!=typeof e||!("component"in e))return!1;let t=e.component;return"string"==typeof t&&t.length>0}(e))return null;let r=e.props&&"object"==typeof e.props&&null!==e.props?e.props:{};return{component:e.component,props:r,raw:t}}((0,Pc.parse)(r,Pc.STR|Pc.OBJ),r);t&&(e=t)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function Nc(e){return"object"==typeof e&&null!==e&&"component"in e&&"string"==typeof e.component&&"props"in e&&"object"==typeof e.props}function Rc(e,t){let{config:r,message:n,onPropsUpdate:o}=t,a=sd.get(e.component);if(!a){if(id.includes(e.component)){fd().catch(()=>{});let e=ne("div","persona-w-full");return e.setAttribute("data-persona-artifact-pending","true"),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let s={message:n,config:r,updateProps:e=>{o&&o(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Hc(){let e=Bc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function $c(e){if("string"==typeof e.rawContent&&e.rawContent.length>0)return e.rawContent;if("string"==typeof e.content){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Wc(e){let t=$c(e);if(!t)return!1;try{let e=JSON.parse(t);return"object"==typeof e&&null!==e&&"component"in e&&"string"==typeof e.component}catch{return!1}}function Dc(e){let t=$c(e);if(!t)return null;try{let e=JSON.parse(t);if("object"==typeof e&&null!==e&&"component"in e&&"string"==typeof e.component){let r=e;return{component:r.component,props:r.props&&"object"==typeof r.props&&null!==r.props?r.props:{},raw:t}}}catch{}return null}var Oc=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fc(e){let{onSubmit:t,onDismiss:r,title:n="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,ratingLabels:d=Oc}=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 p=null,u=document.createElement("div");u.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=n,h.appendChild(m);let g=document.createElement("p");g.className="persona-feedback-subtitle",g.textContent=o,h.appendChild(g),u.appendChild(h);let f=document.createElement("div");f.className="persona-feedback-rating persona-feedback-rating-csat",f.setAttribute("role","radiogroup"),f.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let e=1;e<=5;e++){let t=document.createElement("button");t.type="button",t.className="persona-feedback-rating-btn persona-feedback-star-btn",t.setAttribute("role","radio"),t.setAttribute("aria-checked","false"),t.setAttribute("aria-label",`${e} star${e>1?"s":""}: ${d[e-1]}`),t.title=d[e-1],t.dataset.rating=String(e),t.innerHTML='\n <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">\n <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>\n </svg>\n ',t.addEventListener("click",()=>{p=e,y.forEach((t,r)=>{let n=r<e;t.classList.toggle("selected",n),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),y.push(t),f.appendChild(t)}u.appendChild(f);let b=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",b=document.createElement("textarea"),b.className="persona-feedback-comment",b.placeholder=a,b.rows=3,b.setAttribute("aria-label","Additional comments"),e.appendChild(b),u.appendChild(e)}let v=document.createElement("div");v.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{r?.(),c.remove()});let x=document.createElement("button");return x.type="button",x.className="persona-feedback-btn persona-feedback-btn-submit",x.textContent=s,x.addEventListener("click",async()=>{if(null===p)return f.classList.add("persona-feedback-shake"),void setTimeout(()=>f.classList.remove("persona-feedback-shake"),500);x.disabled=!0,x.textContent="Submitting...";try{let e=b?.value.trim()||void 0;await t(p,e),c.remove()}catch(e){x.disabled=!1,x.textContent=s,console.error("[CSAT Feedback] Failed to submit:",e)}}),v.appendChild(w),v.appendChild(x),u.appendChild(v),c.appendChild(u),c}function zc(e){let{onSubmit:t,onDismiss:r,title:n="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:l=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let u=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let g=document.createElement("h3");g.className="persona-feedback-title",g.textContent=n,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=o,m.appendChild(f),h.appendChild(m);let y=document.createElement("div");y.className="persona-feedback-rating persona-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let b=document.createElement("div");b.className="persona-feedback-labels";let v=document.createElement("span");v.className="persona-feedback-label-low",v.textContent=d;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=c,b.appendChild(v),b.appendChild(w);let x=document.createElement("div");x.className="persona-feedback-numbers";let C=[];for(let e=0;e<=10;e++){let t=document.createElement("button");t.type="button",t.className="persona-feedback-rating-btn persona-feedback-number-btn",t.setAttribute("role","radio"),t.setAttribute("aria-checked","false"),t.setAttribute("aria-label",`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add("persona-feedback-detractor"):e<=8?t.classList.add("persona-feedback-passive"):t.classList.add("persona-feedback-promoter"),t.addEventListener("click",()=>{u=e,C.forEach((t,r)=>{t.classList.toggle("selected",r===e),t.setAttribute("aria-checked",r===e?"true":"false")})}),C.push(t),x.appendChild(t)}y.appendChild(b),y.appendChild(x),h.appendChild(y);let S=null;if(l){let e=document.createElement("div");e.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=a,S.rows=3,S.setAttribute("aria-label","Additional comments"),e.appendChild(S),h.appendChild(e)}let k=document.createElement("div");k.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{r?.(),p.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(null===u)return x.classList.add("persona-feedback-shake"),void setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);M.disabled=!0,M.textContent="Submitting...";try{let e=S?.value.trim()||void 0;await t(u,e),p.remove()}catch(e){M.disabled=!1,M.textContent=s,console.error("[NPS Feedback] Failed to submit:",e)}}),k.appendChild(A),k.appendChild(M),h.appendChild(k),p.appendChild(h),p}var qc="persona-chat-history",jc="data-persona-composer-reason",_c={"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 Vc(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}var Uc=e=>e&&"object"==typeof e?{...e}:{},Kc=e=>e.map(e=>({...e,streaming:!1})),Jc=(e,t,r)=>{let n=e?.markdown?Ke(e.markdown):null,o=at(e?.sanitize);e?.postprocessMessage&&o&&void 0===e?.sanitize&&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.");let a=!1;return s=>{try{return(a=>{let s=a.text??"",i=a.message.rawContent??null;if(t){let e=t.process({text:s,raw:i??s,message:a.message,streaming:a.streaming});null!==e&&(s=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&r&&r())}let l,d=null!==Ve();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=o?o(t):t}else if(n){let e=a.streaming?(e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1];if(!it(n)||st.test(n)||!st.test(o))continue;let a=lt(n).length;if(a<1)continue;let s=ct(a);t[e+1]!==s&&(t[e+1]=s,r=!0);let i=e+2;for(;i<t.length;i++){let e=t[i];if(""===e.trim()||!it(e))break;let n=dt(pt(lt(e),a));t[i]!==n&&(t[i]=n,r=!0)}e=i-1}return r?t.join("\n"):e})(s):s,t=n(e);l=o&&d?o(t):t}else l=Ye(s);return l})(s)}catch(e){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",e)),Ye(s.text??"")}}};function Gc(e){let t=ne("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),void 0!==e?.backdropBlur&&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 r=xe(e?.iconName??"upload",e?.iconSize??"48px",e?.iconColor??"rgba(59, 130, 246, 0.6)",e?.iconStrokeWidth??.5);if(r&&t.appendChild(r),e?.label){let r=ne("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}var Yc=(e,t)=>{let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...n}:n}return r},Xc=(e,t,r)=>{if(null==e)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=re(t),o=new Set,a=new Set,s=function(e){let t=new Set,r=new Set,n=new Set,o=new Map,a=e=>{clearTimeout(o.get(e)),o.delete(e)};return{observe(a,s,i,l={}){let d="tool"===s?a.toolCall:a.reasoning;if(d&&!r.has(a.id)&&(!t.has(a.id)&&"complete"!==d.status&&d.chunks?.some(Boolean)&&(t.add(a.id),!1!==l.autoExpand&&i.add(a.id)),t.has(a.id)&&"complete"===d.status&&!n.has(a.id))){if(n.add(a.id),!1===l.autoCollapseDelay)return;o.set(a.id,setTimeout(()=>{o.delete(a.id),i.delete(a.id),e(a.id,s)},l.autoCollapseDelay??1e3))}},manual(e){r.add(e),a(e)},prune(e){for(let o of new Set([...t,...r,...n]))e.has(o)||(a(o),t.delete(o),r.delete(o),n.delete(o))},clear(){for(let e of o.keys())a(e);t.clear(),r.clear(),n.clear()}}}((e,t)=>{qa.delete(e);let r=Array.from(ct.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e);r&&("tool"===t?Kl(e,r,o,n):Ol(e,r,a))}),i=new Map,l=()=>{!function(e){void 0!==e.delayMs&&(So=Mo(e.delayMs)),void 0!==e.skipDelayMs&&(ko=Mo(e.skipDelayMs))}({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};l();let d=n.features;n=Yd(n);let c=ac.getForInstance(n.plugins),p=(e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),n=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let n=r.composedPath?.();return n?.length?n.includes(e):e.contains(r.target)},o=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let o of t.values())if(Rs(o.parsed,e)&&!1!==o.when?.()&&n(o,e)&&(o.allowInInput||!Hs(r))){e.preventDefault();try{o.run(e)}catch(e){Es(`${o.id} threw on`,o.combo),console.warn(e)}return}};return r?.addEventListener("keydown",o),{register(e){let r=Ls(e.combo);if(!r)return()=>{};let n=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,o=t.get(n);return o?(Es(`${o.id} already owns`,e.combo),()=>{}):(t.set(n,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",Ns(e.combo)),()=>{t.get(n)?.id===e.id&&t.delete(n),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",o)}}})(e),u=[],m=!1,f=(e=>{let t=new Map,r=!1,n=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return o=>{let a=t=>((e,t,r)=>`${(e=>{let t=e?.persistState;return("object"==typeof t?t?.keyPrefix:void 0)??"persona-"})(e)}plugin:${t}:${r}`)(e(),o,t);return{get:e=>{let o=a(e),s=n();if(s)try{return s.getItem(o)}catch{r=!0}return t.get(o)??null},set:(e,o)=>{let s=a(e),i=n();if(i)try{return void i.setItem(s,o)}catch{r=!0}t.set(s,o)},remove:e=>{let o=a(e);t.delete(o);let s=n();if(s)try{s.removeItem(o)}catch{r=!0}}}}})(()=>n),y=null,b=null,v=null,x=!1,C=null,S=e=>{y=e,e.initApprovalUi({webMcpToolTitle:Mt});let t=e.createBuiltInApprovalPlugin(i);b=t.plugin,v=t.teardown},k=()=>{if(y)return y;let e=td();return e?(S(e),e):(ed().then(e=>{x||y||(S(e),C?.())}).catch(()=>{}),null)},A=!1,M=!1,T=null,L=(e,t,r,n)=>{if(!e.querySelector("[data-tv-form]"))return;let o=oc();o?o.enhanceWithForms(e,t,r,n):nc().then(()=>{A||M||!T||(M=!0,T())}).catch(()=>{})};n.components&&sd.registerAll(n.components);let P,B,N=(()=>{let e=new Map,t=(t,r)=>{e.get(t)?.delete(r)};return{on:(r,n)=>(e.has(r)||e.set(r,new Set),e.get(r).add(n),()=>t(r,n)),off:t,emit:(t,r)=>{e.get(t)?.forEach(e=>{try{e(r)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})}}})(),R=!1===n.persistState?null:n.storageAdapter??yc(),H=!!n.clientToken&&"function"!=typeof n.reconnectStream,$={},W=null,D=new Promise(e=>{P=e}),O=()=>{},z=new Promise(e=>{O=e}),q=!1,j=e=>{if(n.onStateLoaded)try{let t=n.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(q=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(R?.load)try{let e=R.load();if(e&&"function"==typeof e.then)W=e.then(e=>j(e??{messages:[],metadata:{}}));else{let t=j(e??{messages:[],metadata:{}});t.metadata&&($=Uc(t.metadata)),t.messages?.length&&(n={...n,initialMessages:t.messages}),t.artifacts?.length&&(n={...n,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),B=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(n.onStateLoaded)try{let e=j({messages:[],metadata:{}});e.messages?.length&&(n={...n,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}W||P();let _=()=>$,U=e=>{$=e({...$})??{},ei()},K=n.actionParsers&&n.actionParsers.length?n.actionParsers:[cc],J=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[uc.message,uc.messageAndClick],G=mc({parsers:K,handlers:J,getSessionMetadata:_,updateSessionMetadata:U,emit:N.emit,documentRef:typeof document<"u"?document:null});G.syncFromMetadata();let Y=n.launcher?.enabled??!0,X=n.launcher?.autoExpand??!1,Q=n.autoFocusInput??!1,Z=X,ee=Y,te=n.layout?.header?.layout,ae=!1,se=()=>wi(n),ie=()=>Y||se(),le=!se()&&(!Y||X),de=!1,ce=null,pe=()=>{de=!0,ce&&clearTimeout(ce),ce=setTimeout(()=>{de&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),de=!1)},1e4)},ue=Jc(n,G,pe),he=n.features?.showReasoning??!0,me=n.features?.showToolCalls??!0,ye=n.features?.showEventStreamToggle??!1,be=n.features?.scrollToBottom??{},ve=n.features?.scrollBehavior??{},we=()=>("object"==typeof n.persistState?n.persistState?.keyPrefix:void 0)??"persona-",Ce=`${we()}event-stream`,Se=null,ke=n.features?.eventStream?.maxEvents??2e3,Ae=null,Ie=null,Te=null,Ee=!1,Le=null,We=!1,De=null,Oe=0,Fe=(e,t)=>{Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},ze=(e,t)=>{Ie?.processEvent(e,t),Ae?Fe(e,t):Te&&(Te.length>=ke&&Te.shift(),Te.push({type:e,payload:t}))},qe=()=>{Ae||!ye||(Te??=[],ad().then(e=>{if(Ee||Ae||!ye)return;Se=new e.EventStreamStore(Ce),Ae=new e.EventStreamBuffer(ke,Se),Ie=Ie??new e.ThroughputTracker,Se.open().then(()=>Ae?.restore()).catch(e=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Te??[];Te=null;for(let e of t)Ie?.processEvent(e.type,e.payload),Fe(e.type,e.payload)}).catch(()=>{}))};ye&&qe();let Ue=!1,Ke=null,Je=()=>{},Ge=()=>{},Xe=()=>{},Qe=()=>{},Ze=()=>{},et={onCopy:e=>{N.emit("message:copy",e),ha?.isClientTokenMode()&&ha.submitMessageFeedback(e.id,"copy").catch(e=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),n.messageActions?.onCopy?.(e)},onFeedback:e=>{N.emit("message:feedback",e),ha?.isClientTokenMode()&&ha.submitMessageFeedback(e.messageId,e.type).catch(e=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),n.messageActions?.onFeedback?.(e)}},tt=(n.statusIndicator,(e,t=n.statusIndicator??{})=>"idle"===e?t.idleText??cn.idle:"connecting"===e?t.connectingText??cn.connecting:"connected"===e?t.connectedText??cn.connected:"error"===e?t.errorText??cn.error:"paused"===e?t.pausedText??cn.paused:"resuming"===e?t.resumingText??cn.resuming:cn[e]);function rt(e,t,r,n){if(!se()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(He(e,yt,r),Re(e,r,n)),!e.hasAttribute(jc))if("idle"===n&&r.idleLink){e.textContent="";let n=document.createElement("a");n.href=r.idleLink,n.target="_blank",n.rel="noopener noreferrer",n.textContent=t,n.style.color="inherit",n.style.textDecoration="none",e.appendChild(n)}else e.textContent=t}let nt=$l({config:n,showClose:ie()}),{wrapper:ot,panel:at,pillRoot:st}=nt.shell,it=nt.panelElements,{container:lt,body:dt,messagesWrapper:ct,starterSuggestions:pt,transcriptSuggestions:ut,suggestions:ht,textarea:mt,sendButton:ft,composerForm:yt,statusText:bt,welcomeHost:vt,welcomeIconHolder:wt,greetingHost:Ct,introKicker:St,introTitle:kt,introSubtitle:At,closeButton:It,iconHolder:Tt,headerTitle:Et,headerSubtitle:Lt,header:Pt,footer:Bt,actionsRow:Nt}=it,Rt=it.leftActions,Ht=it.rightActions,$t=it.sendButtonWrapper,Wt=it.setSendButtonMode,Dt=it.micButton,Ot=it.micButtonWrapper,Ft=it.attachmentButton,zt=it.attachmentButtonWrapper,qt=it.attachmentInput,jt=it.attachmentPreviewsContainer;lt.classList.add("persona-relative"),dt.classList.add("persona-relative");let _t=()=>be.label??"",Vt=()=>ve.mode??"anchor-top",Ut=()=>"follow"===Vt()||"anchor-top"===Vt()&&ds,Kt=()=>ve.anchorTopOffset??16,Jt=()=>!0===ve.pauseOnInteraction,Gt=()=>!1!==ve.showActivityWhilePinned,Yt=()=>!0===ve.announce,Xt=()=>ve.scrollbar??"on-scroll",Zt=ne("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Zt.type="button",Zt.style.display="none",Zt.setAttribute("data-persona-scroll-to-bottom","true");let tr=ne("span","persona-flex persona-items-center"),rr=ne("span",""),nr=ne("span","");nr.setAttribute("data-persona-scroll-to-bottom-count",""),nr.style.display="none",Zt.append(tr,rr,nr),lt.appendChild(Zt);let or=ne("div","persona-stream-anchor-spacer");or.setAttribute("aria-hidden","true"),or.setAttribute("data-persona-anchor-spacer",""),or.style.flexShrink="0",or.style.pointerEvents="none",or.style.height="0px",or.style.display="none",dt.appendChild(or);let ar=ne("div","persona-sr-only");ar.setAttribute("aria-live","polite"),ar.setAttribute("aria-atomic","true"),ar.setAttribute("role","status"),ar.setAttribute("data-persona-live-region",""),Object.assign(ar.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"}),lt.appendChild(ar);let sr=null,ir=null,lr=e=>{!Yt()||!e||(ir=e,null===sr&&(sr=setTimeout(()=>{sr=null,ir&&Yt()&&(ar.textContent=ir),ir=null},400)))},dr=()=>{let t=e.ownerDocument.defaultView??window;return(n.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(n.launcher?.mobileBreakpoint??640)&&(Y||vi(n))||!0===n.launcher?.fullHeight&&!n.launcher.sidebarMode&&!vi(n)},cr=()=>Sl(n,dr()),pr="empty",mr=0,gr=()=>mr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,fr=()=>{let e="none"===Bt.style.display?0:Bt.offsetHeight;Zt.style.bottom=`${e+gr()+12}px`};fr();let br=()=>{tn||(Bt.style.marginBottom=mr>0?`${mr}px`:"")},wr=()=>{let t=Ms(n,se()),r=cr();e.setAttribute("data-persona-welcome-fullscreen",String(dr())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",n.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let o="none"===Bt.style.display?0:Bt.offsetHeight,a="center"===r.anchor&&"empty"===pr?Is(r.anchorComposerTop)??Is("44%"):null,s=null!==a&&"centered"===r.layout&&void 0===n.welcome?.anchor&&void 0===n.welcome?.anchorComposerTop,i=s?getComputedStyle(dt):null,l=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,d=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,c=Math.max(0,(parseFloat(i?.paddingBottom??"")||0)-("overlay"===t?l+d:0)),p=s?dt.getBoundingClientRect().top-lt.getBoundingClientRect().top:0,u=!s||vt.hidden?0:(vt.querySelector("[data-persona-welcome-plugin]")??vt).offsetHeight,h=null===a||se()?0:s?Math.max(0,Math.round((lt.clientHeight-p-u-c-o)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:lt.clientHeight,footerHeight:o,fraction:a});e.style.setProperty("--persona-composer-overlay-height",`${o}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),mr="block"===t?h:0,br(),fr()},Cr=()=>{let e=!!_t();Zt.setAttribute("aria-label",_t()||"Jump to latest"),Zt.title=_t(),Zt.setAttribute("data-persona-scroll-to-bottom-has-label",e?"true":"false"),tr.innerHTML="";let t=xe(be.iconName??"arrow-down","14px","currentColor",2);t?(tr.appendChild(t),tr.style.display=""):tr.style.display="none",rr.textContent=_t(),rr.style.display=e?"":"none"};Cr();let Sr=null,kr=null,Ar=bo();Ar.subscribe(e=>{try{lt.dispatchEvent(new CustomEvent("persona:composer:state",{detail:e,bubbles:!0,composed:!0}))}catch{}});let Mr=()=>{Ar.setText(mt?.value??"")},Ir=()=>{Ar.setMentionRefs(kr?.getMentionRefs()??[])},Tr=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),Er=e=>{let t=Object.freeze(e.map(Tr));Ar.setAttachments(t);try{n.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}Dl()};Ar.setSelectedModelId(n.composer?.selectedModelId);let Lr=()=>n.composer?.modes??[],Br=()=>function(e,t){return e?.length?e.filter(e=>!Ca(e.groupId,t)&&!function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)):[]}(Lr(),n.composer?.modeGroups);{let e=Sa(n.composer?.defaultActiveModeIds??[],Lr());e.length&&Ar.setActiveModeIds(e)}function Nr(e){if(Ar.getState().selectedModelId!==e){Ar.setSelectedModelId(e),$r?.repaint();try{n.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function Rr(e){Ar.setActiveModeIds(e),Dr?.render(e,Br()),Or.forEach(e=>e.repaint()),fn?.resolve(),Cd(),An()}function Hr(e){Rr(function(e,t,r,n){let o=r.find(e=>e.id===t);if(!o)return[...e];let a=e.includes(t),s=new Set(e);if(a)s.delete(t);else{if("single"===((e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null)(o,n)){let e=r.filter(e=>e.groupId===o.groupId).map(e=>e.id);s=new Set([...s].filter(t=>!e.includes(t)))}s.add(t)}return r.filter(e=>s.has(e.id)).map(e=>e.id)}(Ar.getState().activeModeIds,e,Lr(),n.composer?.modeGroups))}let $r=null,Wr=null,Dr=null,Or=new Map,Fr=null;function zr(e){Ar.setQuote(e),Fr?.render(Ar.getState().quote),An(),oi()}let qr=!1;function jr(){let e=n.composer?.streamingSubmitBehavior??"block";return"interrupt"!==e?e:n.clientToken?"interrupt":(!qr&&!0===n.debug&&(qr=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let _r=null;function Vr(e){Ar.setPendingSubmission(e),_r?.render(Ar.getState().pendingSubmission),An()}let Ur=()=>{let e=[],t=Ar.getState().activeModeIds,r=new Set;if(Lr().forEach((o,a)=>{if(Ca(o.groupId,n.composer?.modeGroups)){let t=o.groupId;if(r.has(t))return;r.add(t);let s=(e=>{let t=Or.get(e);if(t)return t;let r=function(e){let t=null;return{action:{id:xa(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let r=oe("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),n=new Map,o="",a=t=>{t.preventDefault(),t.stopPropagation();let r=t.currentTarget.getAttribute("data-persona-composer-mode");!r||e.getActiveIds().includes(r)&&"single"===e.getGroup()?.selection||e.onSelect(r)},s=()=>{let t=e.getGroup();t?.label?(r.setAttribute("role","group"),r.setAttribute("aria-label",t.label)):(r.removeAttribute("role"),r.removeAttribute("aria-label"));let s=e.getModes(),i=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??""}`).join("|");if(i!==o){o=i;for(let e of n.values())e.removeEventListener("click",a);n.clear();let e=s.map(e=>{let t=(e=>{let t=oe("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let r=xe(e.iconName,16,"currentColor",1.5);r&&t.appendChild(r)}let r=ne("span","persona-composer-segmented-label");return r.textContent=e.shortLabel??e.label,t.appendChild(r),t.addEventListener("click",a),t})(e);return n.set(e.id,t),t});r.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of n)t.setAttribute("aria-pressed",String(l.includes(e)))};return s(),t=s,{element:r,destroy:()=>{t===s&&(t=null);for(let e of n.values())e.removeEventListener("click",a);n.clear()}}}},repaint:()=>t?.()}}({groupId:e,getGroup:()=>n.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Lr().filter(t=>t.groupId===e),getActiveIds:()=>Ar.getState().activeModeIds,onSelect:e=>Hr(e)});return Or.set(e,r),r})(t);return s.action.order=wa(a),s.action.label=n.composer?.modeGroups?.find(e=>e.id===t)?.label??t,void e.push(s.action)}e.push({id:va(o.id),kind:"button",placement:"start",order:wa(a),presentation:o.presentation??"auto",label:o.label,shortLabel:o.shortLabel,iconName:o.iconName,pressed:t.includes(o.id),onSelect:()=>Hr(o.id)})}),n.composer?.models?.length&&!c.some(e=>e.renderComposer)){let t=n.composer?.modelPicker?.presentation??"native";(!$r||Wr!==t)&&(Wr=t,$r=ga({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>Ar.getState().selectedModelId,onSelect:e=>Nr(e),presentation:t,getSuffix:()=>n.composer?.modelPicker?.suffix})),e.push($r.action)}return e},Kr=null,Jr=c.find(e=>e.renderHeader);if(Jr?.renderHeader){let e=Jr.renderHeader({config:n,defaultRenderer:()=>{let e=Di({config:n,showClose:ie()});return Oi(lt,e,n),e.header},onClose:()=>Pl(!1,"user")});e&&Pt&&(Pt.replaceWith(e),Pt=e,nt.header.element=e)}let Gr=()=>{Le&&(dt.style.display="none",Bt.parentNode?.insertBefore(Le.element,Bt),Le.update())},Yr=()=>{if(!Ae)return void qe();if(We=!0,Le?Gr():ad().then(e=>{Le||!We||!Ae||(Le=e.createEventStreamView({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>Xr(),config:n,plugins:c,getThroughput:()=>Ie?.getMetric()??{status:"idle"},renderIconByName:xe}),Gr())}).catch(()=>{Xr()}),Qr){Qr.style.boxShadow=`inset 0 0 0 1.5px ${Hi.actionIconColor}`;let e=n.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Qr.classList.add(e))}let e=()=>{if(!We)return;let t=Date.now();t-Oe>=200&&(Le?.update(),Oe=t),De=requestAnimationFrame(e)};Oe=0,De=requestAnimationFrame(e),Ni(),N.emit("eventStream:opened",{timestamp:Date.now()})},Xr=()=>{if(We){if(We=!1,Le&&Le.element.remove(),dt.style.display="",Qr){Qr.style.boxShadow="";let e=n.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Qr.classList.remove(e))}null!==De&&(cancelAnimationFrame(De),De=null),Ni(),N.emit("eventStream:closed",{timestamp:Date.now()})}},Qr=null;if(ye){let e=n.features?.eventStream?.classNames,t="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"+(e?.toggleButton?" "+e.toggleButton:"");Qr=ne("button",t),Qr.style.width="28px",Qr.style.height="28px",Qr.style.color=Hi.actionIconColor,Qr.type="button",Qr.setAttribute("aria-label","Event Stream"),Qr.title="Event Stream";let r=I(h,"18px","currentColor",1.5);r&&Qr.appendChild(r);let o=it.clearChatButtonWrapper,a=it.closeButtonWrapper,s=o||a;s&&s.parentNode===Pt?Pt.insertBefore(Qr,s):Pt.appendChild(Qr),Qr.addEventListener("click",()=>{We?Xr():Yr()})}let en=e=>{let t=n.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=ne("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let t=e.querySelector("[data-persona-composer-form]");t?.parentNode?t.parentNode.insertBefore(r,t):e.insertBefore(r,e.firstChild)}if(!(e.querySelector("[data-persona-composer-attachment-input]")??e.querySelector('input[type="file"]'))){let r=ne("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??on).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},tn=!1,rn=e=>{let t=c.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=n.composer,o=!!m&&ha.isStreaming();return t.renderComposer({config:n,defaultRenderer:e,requestRender:()=>mu(),storage:f(t.id),onSubmit:e=>{!ha||ha.isStreaming()||np(e.trim(),{consumeDraft:!1})},streaming:o,disabled:o,openAttachmentPicker:()=>{Nl()||qt?.click()},models:r?.models,selectedModelId:Ar.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>Nr(e),onVoiceToggle:!0===n.voiceRecognition?.enabled?()=>{Kr?.()}:void 0})},nn=rn(()=>Xi({config:n}).footer);nn&&(nt.replaceComposer(nn),Bt=nt.composer.footer,tn=!0);let an=null;function sn(){let e=mt;if(!e)return;let t=n.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");Do(e,t),r&&e.setAttribute("aria-label",r),Wo(e,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Ho(e)}),function(e,t){e.style.maxHeight=t*No(e)+"px",e.style.overflowY="auto"}(e,Ro(n.composer?.maxLines,se()?5:3))}let ln=e=>{an=function(e,t={}){let r=vo(e,"[data-persona-composer-form]"),n=vo(e,"[data-persona-composer-input]");if(!r||!n){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||n))throw new Error(e);return typeof console<"u"&&console.warn(e),null}let o={header:vo(e,"[data-persona-composer-header]"),body:vo(e,"[data-persona-composer-body]"),actionsStart:vo(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:vo(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:vo(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:vo(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:vo(e,"[data-persona-composer-status]")},a=new Set,s=o.header;s||(a.add("header"),s=wo("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=o.body??n.parentElement??r,l=(e,t,r,n,o)=>{if(t)return t;a.add(e);let s=wo(r,n);return o.appendChild(s),s},d=l("actionsStart",o.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",o.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",o.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",o.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:n,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:vo(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:vo(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:vo(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:vo(e,"[data-persona-composer-submit]")??void 0,micButton:vo(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:o,addListener:(e,t,r,n)=>{e.addEventListener(t,r,n),h.push({target:e,type:t,handler:r,options:n})},removeListener:(e,t,r,n)=>{e.removeEventListener(t,r,n),h=h.filter(n=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(n,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}(e,{debug:!0===n.debug}),an&&(e=>{yt=e.form,mt=e.input,$t=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(ft=e.sendButton),e.micButton&&(Dt=e.micButton,Ot=e.micButton.parentElement),e.found.status&&(bt=e.found.status),e.found.suggestions&&(ht=e.found.suggestions),e.attachmentButton&&(Ft=e.attachmentButton,zt=e.attachmentButton.parentElement),qt=e.attachmentInput??null,jt=e.attachmentPreviews??null,e.found.actionsRow&&(Nt=e.found.actionsRow),Rt=e.found.actionsStart,Ht=e.found.actionsEnd})(an),sn()};en(Bt),ln(Bt),Mr();let dn=ks(n,se());dn&&(ct.style.maxWidth=dn,ct.style.marginLeft="auto",ct.style.marginRight="auto",ct.style.width="100%",Ct.style.maxWidth=dn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto",Ct.style.width="100%",pt.style.maxWidth=dn,ut.style.maxWidth=dn,ut.style.marginLeft="auto",ut.style.marginRight="auto",ut.style.width="100%");let un=()=>{let e=ks(n,se());if(e&&!se())for(let t of[yt,ht,jt,bt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};un();let mn=()=>{!n.attachments?.enabled||!qt||!jt||(Sr?Sr.remountPreviews(jt):(Sr=fo.fromConfig(n.attachments,Er),Sr.setPreviewsContainer(jt)),an?.addListener(qt,"change",e=>{let t=e.target;Sr?.handleFileSelect(t.files),t.value=""}),lt.querySelector(".persona-attachment-drop-overlay")||lt.appendChild(Gc(n.attachments.dropOverlay)))};mn();let gn=()=>{if(!n.contextMentions?.enabled||!mt)return;let e=Tn();if(!e){let e=mt;return void In().then(()=>{kr||mt!==e||!e.isConnected||(gn(),fn?.resolve())},()=>{})}let t=an?.header??null,r=t?ba(t):void 0;if(kr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Ea,loadContextMentionsInline:Na,renderLucideIcon:xe,createMentionButton:Ra},config:n,textarea:mt,anchor:yt??mt,getMessages:()=>ha.getMessages(),liveRegionHost:lt,chipRow:r}),kr&&!r){let e=mt;e.parentElement?.insertBefore(kr.contextRow,e)}};gn();let fn=null,yn={getState:()=>Ar.getState(),getValue:()=>mt?.value??"",setValue:e=>{mt&&(mt.value=e,mt.dispatchEvent(new Event("input",{bubbles:!0})),Mr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(an?.form??null)},openAttachmentPicker:()=>{Nl()||qt?.click()},toggleVoice:()=>{Kr?.()},requestRender:()=>fn?.resolve()},bn=()=>{let e=[];return(kr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),zt&&e.push({id:"core:attachment",placement:"start",order:200,element:zt}),Ot&&e.push({id:"core:mic",placement:"end",order:800,element:Ot}),$t&&e.push({id:"core:send",placement:"end",order:ra,element:$t}),e},vn=()=>{fn?.destroy(),fn=ua({getBindings:()=>an,collect:()=>({builtIns:bn(),configActions:[...Ur(),...n.composer?.actions??[]],plugins:c,contributionContext:{config:n,getState:()=>Ar.getState(),requestRender:()=>fn?.resolve()},debug:!0===n.debug}),actionContext:yn,getState:()=>Ar.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),fn.resolve()};vn();let xn=()=>{if(Dr?.destroy(),Dr=null,!Br().length)return;let e=an?.header;e&&(Dr=function(e){let t=e.row,r="",n=!1,o=new Set(e.initialIds??[]),a=t=>{let r=oe("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=ne("span","persona-mention-chip-icon"),n=xe(t.iconName,12,"currentColor",1.5);n&&e.appendChild(n),r.appendChild(e)}let n=ne("span","persona-mention-chip-label");n.textContent=t.shortLabel??t.label,r.appendChild(n);let o=oe("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label}`}}),a=xe("x",12,"currentColor",2);return a?o.appendChild(a):o.textContent="×",o.addEventListener("click",r=>{r.preventDefault(),r.stopPropagation(),e.onRemove(t.id)}),r.appendChild(o),r},s=()=>Array.from(t.querySelectorAll(":scope > [data-persona-composer-mode]")),i=e=>{e.setAttribute("data-persona-chip-exit",""),e.setAttribute("aria-hidden","true"),e.style.pointerEvents="none";let r=()=>{e.remove(),ya(t)},n=t.ownerDocument.defaultView,o="function"==typeof n?.getComputedStyle?n.getComputedStyle(e).animationName:"";o&&"none"!==o?(e.addEventListener("animationend",r,{once:!0}),e.addEventListener("animationcancel",r,{once:!0})):r()};return{element:t,render:(e,l)=>{if(n)return;let d=l.filter(t=>e.includes(t.id)),c=d.map(e=>`${e.id}:${e.shortLabel??e.label}`).join("|");if(c===r)return;r=c;let p=new Map;for(let e of s()){let t=e.getAttribute("data-persona-composer-mode");t&&d.some(e=>e.id===t)&&!e.hasAttribute("data-persona-chip-exit")?p.set(t,e):e.hasAttribute("data-persona-chip-exit")||i(e)}let u=t.firstChild;for(let e of d){let r=p.get(e.id);r||(r=a(e),o.has(e.id)||(r.setAttribute("data-persona-chip-enter",""),r.addEventListener("animationend",()=>r?.removeAttribute("data-persona-chip-enter"),{once:!0}))),o.delete(e.id),r!==u&&t.insertBefore(r,u),u=r.nextSibling}ya(t)},destroy:()=>{n=!0,(()=>{for(let e of s())e.remove()})(),ya(t)}}}({row:ba(e),onRemove:e=>Hr(e),initialIds:Ar.getState().activeModeIds}),Dr.render(Ar.getState().activeModeIds,Br()))};xn();let Cn=()=>{Fr?.destroy(),Fr=null,_r?.destroy(),_r=null;let e=an?.header;e&&(Fr=function(e){let t=oe("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",n=!1;return{element:t,render:o=>{if(n)return;let a=o?`${o.sourceLabel??""}\0${o.text}`:"";if(a!==r){if(r=a,!o)return t.replaceChildren(),void(t.style.display="none");(r=>{let n=ne("span","persona-composer-quote-bar"),o=ne("div","persona-composer-quote-content");if(r.sourceLabel){let e=ne("div","persona-composer-quote-source");e.textContent=r.sourceLabel,o.appendChild(e)}let a=oe("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=zn(r.text),o.appendChild(a);let s=oe("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=xe("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(n,o,s)})(o),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}({onDismiss:()=>zr(void 0)}),e.appendChild(Fr.element),Fr.render(Ar.getState().quote),"defer-one"===jr()&&(_r=function(e){let t=oe("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,n=!1,o=(e,t,r,n)=>{let o=oe("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=xe(e,12,"currentColor",2);return a?o.appendChild(a):o.textContent=t,o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o};return{element:t,render:a=>{if(n||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=ne("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=oe("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=zn(e.text??"",90);if(t)return t;let r=e.contentParts?.length??0;return r>0?1===r?"1 attachment":`${r} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(", "):"Queued message"})(a),t.replaceChildren(s,i,o("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),o("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}({onEdit:()=>function(){let e=Ar.getState().pendingSubmission;e&&(Vr(void 0),mt&&(mt.value=e.text,mt.dispatchEvent(new Event("input",{bubbles:!0})),Mr()),e.options.selectedModelId&&(Ar.setSelectedModelId(e.options.selectedModelId),$r?.repaint()),e.options.activeModeIds?.length&&Rr(e.options.activeModeIds),e.options.quote&&zr(e.options.quote),mt?.focus())}(),onRemove:()=>Vr(void 0)}),e.appendChild(_r.element),_r.render(Ar.getState().pendingSubmission)))};Cn();let Sn=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),kn=()=>{let e=an?.header?.querySelector(fa);if(e)return e.childElementCount>0;let t=Ar.getState();return t.mentionRefs.length>0||Sa(t.activeModeIds,Br()).length>0};function An(){let e=Ar.getState(),t=Sn.observe(function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),n=Number.parseFloat(r.lineHeight),o=Number.parseFloat(r.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(o)&&o>0?1.4*o:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0);return e.scrollHeight-s>1.5*a}(mt),e.text);Bt.toggleAttribute("data-persona-composer-compact",function(e){return!e.wrapped&&!e.text.includes("\n")&&!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:kn(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}))}function Mn(){"single-row"!==n.composer?.layout||se()?Bt.removeAttribute("data-persona-composer-layout"):Bt.setAttribute("data-persona-composer-layout","single-row")}Mn(),Ar.subscribe(()=>{fn?.sync(),Dl(),zl(),An(),oi()}),zl();let En=!1;(()=>{let e=n.layout?.slots??{};(e=>{if(En||!0!==n.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(En=!0,console.warn(`[persona] layout.slots.${t.join(" and layout.slots.")} ${t.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))})(e);let t=e=>{switch(e){case"body-top":return dt.querySelector("[data-persona-intro-card]");case"messages":return ct;case"footer-top":return ht;case"composer":return yt;case"footer-bottom":return bt;default:return null}},r=(e,t)=>{switch(e){case"header-left":case"header-center":case"header-right":if("header-left"===e)Pt.insertBefore(t,Pt.firstChild);else if("header-right"===e)Pt.appendChild(t);else{let e=Pt.querySelector(".persona-flex-col");e?e.parentNode?.insertBefore(t,e.nextSibling):Pt.appendChild(t)}break;case"body-top":{let e=dt.querySelector("[data-persona-intro-card]");e?e.replaceWith(t):dt.insertBefore(t,dt.firstChild);break}case"body-bottom":dt.appendChild(t);break;case"footer-top":ht.replaceWith(t);break;case"footer-bottom":bt.replaceWith(t)}};for(let[o,a]of Object.entries(e))if(a)try{let e=a({config:n,defaultContent:()=>t(o)});e&&r(o,e)}catch(e){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${o}":`,e)}})(),ct.addEventListener("click",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest("button[data-persona-copy-tool-detail]");r&&(e.preventDefault(),e.stopPropagation(),async function(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let n=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(jl.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=xe("check",14,"currentColor",2);t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}jl.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",n),e.title=n;let t=xe("copy",14,"currentColor",1.7);t&&e.replaceChildren(t),jl.delete(e)},1800))}(r))});let Ln=e=>{let t=e.target.closest('button[data-expand-header="true"]');if(!t)return;let r=t.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!r)return;let l=r.getAttribute("data-message-id");if(!l)return;hs(),Ri();let d=t.getAttribute("data-bubble-type");if(r.classList.contains("persona-activity-row")){s.manual(l);let e=r.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&s.manual(e.dataset.messageId)}if("reasoning"===d)a.has(l)?a.delete(l):a.add(l),Ol(l,r,a);else if("tool"===d)o.has(l)?o.delete(l):o.add(l),Kl(l,r,o,n);else if("approval"===d&&y){let e="expanded"===((!1!==n.approval?n.approval:void 0)?.detailsDisplay??"collapsed"),t=i.get(l)??e;i.set(l,!t),y.updateApprovalDetailsUI(l,r,n,i)}qa.delete(l)};ct.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Ln(e))}),ct.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&Ln(e)}),ct.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),Ln(e))}),ct.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=ct.getRootNode(),n="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!n||n.isCollapsed)return;let o=n.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(o);!a||a===o||(t.setData("text/plain",a),e.preventDefault())});let Pn=new Map,Bn=null,Nn="idle",Rn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Hn=()=>{ct.querySelectorAll('[data-action="read-aloud"]').forEach(e=>{let t=e.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;((e,t)=>{let{icon:r,label:n}=Rn[t];e.setAttribute("aria-label",n),e.title=n,e.setAttribute("aria-pressed","idle"===t?"false":"true"),e.classList.toggle("persona-message-action-active","idle"!==t),e.classList.toggle("persona-message-action-loading","loading"===t);let o=xe(r,14,"currentColor",2);o&&(e.innerHTML="",e.appendChild(o))})(e,t&&t===Bn?Nn:"idle")})};ct.addEventListener("click",e=>{let t=e.target.closest(".persona-message-action-btn[data-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest("[data-actions-for]");if(!r)return;let o=r.getAttribute("data-actions-for");if(!o)return;let a=t.getAttribute("data-action");if("copy"===a){let e=ha.getMessages().find(e=>e.id===o);if(e&&et.onCopy){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=I(g,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=I(w,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),et.onCopy(e)}}else if("read-aloud"===a)ha.toggleReadAloud(o);else if("upvote"===a||"downvote"===a){let e="upvote"===a?"thumbs-up":"thumbs-down";if((Pn.get(o)??null)===a){Pn.delete(o),t.classList.remove("persona-message-action-active");let r=xe(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let n="upvote"===a?"downvote":"upvote",s=r.querySelector(`[data-action="${n}"]`);if(s){s.classList.remove("persona-message-action-active");let e=xe("upvote"===n?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(s.innerHTML="",s.appendChild(e))}Pn.set(o,a),t.classList.add("persona-message-action-active");let i=xe(e,14,"currentColor",2);i&&(i.setAttribute("fill","currentColor"),t.innerHTML="",t.appendChild(i)),t.classList.remove("persona-message-action-pop"),t.offsetWidth,t.classList.add("persona-message-action-pop");let l=ha.getMessages().find(e=>e.id===o);l&&et.onFeedback&&et.onFeedback({type:a,messageId:l.id,message:l})}}else if("regenerate"===a)$n?.regenerate(o);else if("edit"===a)$n?.edit(o);else if("quote"===a)$n?.quote(o);else if(a?.startsWith(sl)){let e=a.slice(7),t=n.messageActions?.custom?.find(t=>t.id===e),r=ha.getMessages().find(e=>e.id===o);if(!t||!r)return;try{t.onSelect(r)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let $n=null;ct.addEventListener("click",e=>{let t=e.target.closest("button[data-approval-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest(".persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;let o=t.getAttribute("data-approval-action");if(!o)return;let a="approve"===o?"approved":"denied",s=ha.getMessages().find(e=>e.id===n);if(!s?.approval)return;let i=r.querySelector("[data-approval-buttons]");i&&i.querySelectorAll("button").forEach(e=>{e.disabled=!0,e.style.opacity="0.5",e.style.cursor="not-allowed"}),"webmcp"===s.approval.toolType?ha.resolveWebMcpApproval(n,a):ha.resolveApproval(s.approval,a)});let Wn=null,Dn=!1,Fn=null,_n=()=>{},Vn="none",Un=null,Kn={artifacts:[],selectedId:null},Jn=!1,Gn=!1,Yn=!1,Xn=!1,eo=()=>Xn||Kn.artifacts.some(e=>"panel"===On(n.features?.artifacts,e)),to=()=>Kn.artifacts.length>0&&!Jn&&eo(),ro={current:null},no=(e,t)=>{let r=ha.getArtifactById(t),n=r?.markdown,o=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!n){let t=e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(t){let e=ha.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);n=t?.props?.markdown,o=t?.props?.title||o,t?.props?.file&&"object"==typeof t.props.file&&(a=t.props.file),!r&&"string"==typeof t?.props?.artifactType&&(s=t.props.artifactType)}catch{}}}return{markdown:n,title:o,file:a,artifactType:s}};ct.addEventListener("click",e=>{let t=e.target.closest("[data-download-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-download-artifact");if(!r||!0===n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:o,title:a,file:s}=no(t,r);if(!o)return;let i=yd();i&&i.triggerArtifactDownload(i.downloadInfoFor({title:a,markdown:o,file:s}))}),ct.addEventListener("click",e=>{let t=e.target.closest("[data-artifact-custom-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-artifact-custom-action");if(!r)return;let o=t.closest("[data-artifact-inline]"),a=o?null:t.closest("[data-open-artifact]"),s=o?o.getAttribute("data-artifact-inline"):a?.getAttribute("data-open-artifact")??null,i=(o?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!i)return;let{markdown:l,title:d,file:c,artifactType:p}=no(t,s??""),u={artifactId:s,title:d,artifactType:p,markdown:l,file:c};try{Promise.resolve(i.onClick(u)).catch(()=>{})}catch{}}),ct.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-copy-artifact");if(!r)return;let n=ha.getArtifactById(r),o=yd();if(!o)return;let a="";if(n)a=o.artifactCopyText(n);else{let{markdown:e,file:n,artifactType:s}=no(t,r);"markdown"===s&&(a=o.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...n?{file:n}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=I(g,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=I(w,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),ct.addEventListener("click",e=>{let t=e.target.closest("[data-expand-artifact-inline]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-expand-artifact-inline");!r||!0===n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})||(Jn=!1,Xn=!0,Gn=!0,Yn=!0,ha.selectArtifact(r),_o())}),ct.addEventListener("click",e=>{let t=e.target;if(t.closest("[data-download-artifact]")||t.closest("[data-artifact-custom-action]"))return;let r=t.closest("[data-open-artifact]");if(!r)return;let o=r.getAttribute("data-open-artifact");!o||!0===n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:o})||(e.preventDefault(),e.stopPropagation(),Jn=!1,Xn=!0,ha.selectArtifact(o),_o())}),ct.addEventListener("keydown",e=>{if("Enter"!==e.key&&" "!==e.key)return;let t=e.target;!t.hasAttribute("data-open-artifact")&&!t.hasAttribute("data-expand-artifact-inline")||(e.preventDefault(),t.click())});let oo=it.composerOverlay,ao=e=>{In().catch(()=>{}),ur(e,n,oo)},so=null,io={mount:e,overlay:oo,sessionRef:ro,config:()=>n},lo=!1,co=e=>t=>{let r=t.target,n=r?.closest?.("[data-persona-ask-sheet-for]");if(!n||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let o=r=>{so??=r.createAskUserSheetHandlers(io),so[e](t)},a=Tn();a?o(a):lo||(lo=!0,In().then(e=>{lo=!1,n.isConnected&&o(e)},()=>{lo=!1}))};oo.addEventListener("click",co("click")),oo.addEventListener("keydown",co("keydown"));let po=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if("INPUT"===t?.tagName||"TEXTAREA"===t?.tagName||t?.isContentEditable)return;let r=oo.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let n=Number(e.key),o=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[n-1];o&&(e.preventDefault(),o.click())};document.addEventListener("keydown",po);let ho=null,mo=null,go=null,yo=null,xo=()=>{},Co=!1,Ao="",Io="";function To(){yo?.(),yo=null}let Eo=()=>{if(!ho||!mo)return;let t=e.classList.contains("persona-artifact-welded-split"),r=e.ownerDocument.defaultView??window,n=r.innerWidth<=640;if(!t||e.classList.contains("persona-artifact-narrow-host")||n)return mo.style.removeProperty("position"),mo.style.removeProperty("left"),mo.style.removeProperty("top"),mo.style.removeProperty("bottom"),mo.style.removeProperty("width"),void mo.style.removeProperty("z-index");let o=ho.firstElementChild;if(!o||o===mo)return;mo.style.position="absolute",mo.style.top="0",mo.style.bottom="0",mo.style.width="10px",mo.style.zIndex="5";let a=Xd(ho,r),s=o.offsetWidth+a/2-5;mo.style.left=`${Math.max(0,s)}px`},Lo=()=>{},Po=()=>{let t=e.ownerDocument.defaultView??window,r=n.launcher?.mobileFullscreen??!0,o=n.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>o)&&(Y||vi(n))},jo=()=>!vd(n)||!to()||e.classList.contains("persona-artifact-narrow-host")||Po()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":Sd(n)?"detached":"welded",_o=()=>{if(!Wn||!vd(n))return;kd(e,n),Ad(e,n),Lo();let t=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=at.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let o=to();Wn.setVisible(o),Wn.update(Kn),Jn?(Wn.setMobileOpen(!1),Wn.element.classList.add("persona-hidden"),Wn.backdrop?.classList.add("persona-hidden"),Gn=!1,Yn=!1):Kn.artifacts.length>0&&eo()?(Wn.element.classList.remove("persona-hidden"),Wn.setMobileOpen(!0)):(Wn.setMobileOpen(!1),Wn.element.classList.add("persona-hidden"),Wn.backdrop?.classList.add("persona-hidden"),Gn=!1,Yn=!1);let a=!0===n.features?.artifacts?.layout?.showExpandToggle;if(Wn.setExpandToggleVisible(a),Wn.setCopyButtonVisible(!0===n.features?.artifacts?.layout?.showCopyButton),Wn.setRefreshButtonVisible("function"==typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh),Wn.setCustomActions(n.features?.artifacts?.toolbarActions??[]),Wn.setTabFade(n.features?.artifacts?.layout?.tabFade),Wn.setRenderTabBar(n.features?.artifacts?.renderTabBar),!a&&!Yn&&(Gn=!1),Gn!==Co){let e=Wn.element;Gn?(Ao=e.style.width,Io=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(Ao&&(e.style.width=Ao),Io&&(e.style.maxWidth=Io),Ao="",Io=""),Co=Gn}e.classList.toggle("persona-artifact-expanded",Gn),Wn.setExpanded(Gn);let s=jo();s!==Vn&&(Vn=s,_n()),xo()};if(vd(n)){at.style.position="relative";let t=ne("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=ne("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(lt),ho=r,r.appendChild(t),at.appendChild(r);let o=e=>{Dn||Wn||(Wn=e.createArtifactPane(n,{onSelect:e=>ro.current?.selectArtifact(e),onDismiss:()=>{Jn=!0,_o()},onToggleExpand:()=>{let e=!Gn,t=Kn.selectedId??Kn.artifacts[Kn.artifacts.length-1]?.id??null;!0!==n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(Gn=e,e||(Yn=!1),_o())}}),Wn.element.classList.add("persona-hidden"),r.appendChild(Wn.element),Wn.backdrop&&at.appendChild(Wn.backdrop),xo(),_o())},a=yd();a?o(a):(bd(()=>{let e=yd();e&&o(e)}),fd().catch(()=>{})),xo=()=>{if(ho&&Wn){if(!0!==n.features?.artifacts?.layout?.resizable)return go?.(),go=null,To(),mo&&(mo.remove(),mo=null),Wn.element.style.removeProperty("width"),void Wn.element.style.removeProperty("maxWidth");if(!mo){let t=ne("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");t.setAttribute("role","separator"),t.setAttribute("aria-orientation","vertical"),t.setAttribute("aria-label","Resize artifacts panel"),t.tabIndex=0;let r=e.ownerDocument,o=r.defaultView??window,a=a=>{if(!Wn||0!==a.button||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||o.innerWidth<=640)return;a.preventDefault(),To();let s=a.clientX,i=Wn.element.getBoundingClientRect().width,l=n.features?.artifacts?.layout,d=r=>{let n=ho.getBoundingClientRect().width,a=e.classList.contains("persona-artifact-welded-split"),d=Xd(ho,o),c=a?0:t.getBoundingClientRect().width||6,p=function(e,t,r,n,o,a,s=200){let i=function(e){if(!e?.trim())return 200;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):200}(o),l=function(e,t,r,n){let o=e-n-2*t-r;return Math.max(0,o)}(t,r,n,s);l=Math.max(i,l);let d=function(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}(a);return null!==d&&(l=Math.min(l,d)),function(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}(e,i,l)}(i-(r.clientX-s),n,d,c,l?.resizableMinWidth,l?.resizableMaxWidth,(()=>{let e=Jd?.railShell?Jd.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360})());Wn.element.style.width=`${p}px`,Wn.element.style.maxWidth="none",Eo()},c=()=>{r.removeEventListener("pointermove",d),r.removeEventListener("pointerup",c),r.removeEventListener("pointercancel",c),yo=null;try{t.releasePointerCapture(a.pointerId)}catch{}};yo=c,r.addEventListener("pointermove",d),r.addEventListener("pointerup",c),r.addEventListener("pointercancel",c);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener("pointerdown",a),mo=t,ho.insertBefore(t,Wn.element),go=()=>{t.removeEventListener("pointerdown",a)}}if(mo){let e=to();mo.classList.toggle("persona-hidden",!e),Eo()}}},Lo=()=>{if(!Y||!Wn||n.launcher?.sidebarMode||vi(n)&&"emerge"===xi(n).reveal)return;let t=e.ownerDocument.defaultView??window,r=n.launcher?.mobileFullscreen??!0,o=n.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=o||!function(e,t){return!(!t||!vd(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(n,Y))return;let a=Ml(n).width,s=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";to()?(at.style.width=s,at.style.maxWidth=s):(at.style.width=a,at.style.maxWidth=a)},typeof ResizeObserver<"u"&&(Fn=new ResizeObserver(()=>{_o()}),Fn.observe(at))}else at.appendChild(lt);se()&&st&&(it.peekBanner&&st.appendChild(it.peekBanner),st.appendChild(Bt)),e.appendChild(ot),st&&e.appendChild(st);let Uo=()=>{let t=Po()||se()&&"fullscreen"===n.launcher?.composerBar?.expandedSize||!0===n.launcher?.fullHeight&&!n.launcher?.sidebarMode&&!vi(n);if(ct.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",ct.style.setProperty("--persona-transcript-gap",ct.style.gap),se()){at.style.width="100%",at.style.maxWidth="100%";let e=n.launcher?.composerBar??{},t="expanded"===ot.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return lt.style.background="",lt.style.border="",lt.style.borderRadius="",lt.style.overflow="",void(lt.style.boxShadow="");let o=n.theme?.components?.panel,a=xs(n),s=(e,t)=>null==e||""===e?t:es(a,e)??e,i="1px solid var(--persona-border)",l="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",d="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";return lt.style.background="var(--persona-surface, #ffffff)",lt.style.border=s(o?.border,i),lt.style.borderRadius=s(o?.borderRadius,d),lt.style.boxShadow=s(o?.shadow,l),void(lt.style.overflow="hidden")}let r=vi(n),o=n.launcher?.sidebarMode??!1,a=r||o||(n.launcher?.fullHeight??!1),s=!1===n.launcher?.enabled,i=!0===n.launcher?.detachedPanel,l=n.theme?.components?.panel,d=n.darkTheme?.components?.panel,c="dark"===ws(n)?E(l??{},d??{}):l,p=xs(n),u=(e,t)=>null==e||""===e?t:es(p,e)??e,h=e.ownerDocument.defaultView??window,m=n.launcher?.mobileFullscreen??!0,g=n.launcher?.mobileBreakpoint??640,f=h.innerWidth<=g,y=m&&f&&Y,b=r&&m&&f,v=n.launcher?.position??"bottom-left",w="bottom-left"===v||"top-left"===v,x=n.launcher?.zIndex??pn,C=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,S=c?.modes?.floating,k=u(S?.border??c?.border,C("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),A=u(S?.shadow??c?.shadow,C("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),M=u(S?.borderRadius??c?.borderRadius,C("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),I=i&&!y&&!b,T=y||b?"mobile":I?"floating":r?"docked":o?"sidebar":s?"inline":"floating",L=c?.modes?.[T];I?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let P=I?k:o||y?"none":k,B=I?A:y?"none":o?w?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":s?"none":A;r&&!y&&!I&&(B="none",P="none");let N=I?M:o||y?"0":M,R=u(L?.border??c?.border,C(T,"border",P)),H=u(L?.shadow??c?.shadow,C(T,"shadow",B)),$=u(L?.borderRadius??c?.borderRadius,C(T,"borderRadius",N)),W=jo(),D="detached"===W,O="welded"===W;e.classList.toggle("persona-artifact-detached-split",D),e.classList.toggle("persona-artifact-welded-split",O);let z="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)))))",q="flush"==("flush"===n.features?.artifacts?.layout?.chatSurface?"flush":"card")&&vd(n)&&Sd(n)&&s&&!r;e.classList.toggle("persona-artifact-chat-flush",q);let j=D||q?"none":H,_=D?k:O?"none":R,V=D?M:$;q&&(_="none",V="0");let U=null!=L?.borderRadius&&""!==L.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,K=q&&!U?"0":$,J=dt.scrollTop;e.style.cssText="",ot.style.cssText="",at.style.cssText="",lt.style.cssText="",dt.style.cssText="",tn||(Bt.style.cssText=""),We&&(dt.style.display="none"),(a||s)&&(e.style.minWidth="0");let G=()=>{J<=0||(dt.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(dt.scrollTop===J)return;let e=dt.scrollHeight-dt.clientHeight;e<=0||(dt.scrollTop=Math.min(J,e))})};if(y)return ot.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"),ot.style.cssText=`\n position: fixed !important;\n inset: 0 !important;\n width: 100% !important;\n height: 100% !important;\n max-height: 100% !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${x} !important;\n background-color: var(--persona-surface, #ffffff) !important;\n `,at.style.cssText="\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: none !important;\n border-radius: 0 !important;\n ",lt.style.cssText="\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: 0 !important;\n border: none !important;\n ",dt.style.flex="1 1 0%",dt.style.minHeight="0",dt.style.overflowY="auto",Bt.style.flexShrink="0",br(),ae=!0,void G();let X=Ml(n);if(o||r){if(r)if("emerge"!==xi(n).reveal||i)at.style.width="100%",at.style.maxWidth="100%";else{let e=xi(n).width;at.style.width=e,at.style.maxWidth=e}}else s&&a?(at.style.width="100%",at.style.maxWidth="100%"):(at.style.width=X.width,at.style.maxWidth=X.maxWidth);if(Lo(),at.style.boxShadow=j,at.style.borderRadius=K,D?at.style.border="none":O&&(at.style.border=R),lt.style.border=_,lt.style.borderRadius=V,lt.style.boxShadow=D&&!q?z:"",q&&(lt.style.background="transparent",dt.style.background="transparent",Bt.style.background="transparent",Bt.style.borderTop="none"),O){let e=n.features?.artifacts?.layout;Un=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||$}else Un=null;let Q=null!=L?.border||null!=c?.border;if(r&&!y&&!I&&!D&&!O&&!Q&&(lt.style.border="none","right"===xi(n).side?lt.style.borderLeft="1px solid var(--persona-border)":lt.style.borderRight="1px solid var(--persona-border)"),r&&!y&&O&&!Q&&("right"===xi(n).side?at.style.borderLeft="1px solid var(--persona-border)":at.style.borderRight="1px solid var(--persona-border)"),a&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",s&&(e.style.width="100%"),ot.style.display="flex",ot.style.flexDirection="column",ot.style.flex="1 1 0%",ot.style.minHeight="0",ot.style.maxHeight="100%",ot.style.height="100%",s&&(ot.style.overflow="hidden"),at.style.display="flex",at.style.flexDirection="column",at.style.flex="1 1 0%",at.style.minHeight="0",at.style.maxHeight="100%",at.style.height="100%",D||(at.style.overflow="hidden"),lt.style.display="flex",lt.style.flexDirection="column",lt.style.flex="1 1 0%",lt.style.minHeight="0",lt.style.maxHeight="100%",lt.style.overflow="hidden",dt.style.flex="1 1 0%",dt.style.minHeight="0",dt.style.overflowY="auto",Bt.style.flexShrink="0"),s&&(I||D||q)&&!r&&(q||(ot.style.padding="var(--persona-panel-inset)"),ot.style.background="var(--persona-panel-canvas-bg)"),ot.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"),!o&&!s&&!r&&(Ii[v]??Ii["bottom-right"]).split(" ").forEach(e=>ot.classList.add(e)),o){let e=F(n).sidebarWidth?n.launcher?.sidebarWidth??"420px":es(xs(n),"components.panel.width")??"420px";ot.style.cssText=i?`\n position: fixed !important;\n top: var(--persona-panel-inset) !important;\n bottom: var(--persona-panel-inset) !important;\n width: ${e} !important;\n height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${x} !important;\n ${w?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}\n `:`\n position: fixed !important;\n top: 0 !important;\n bottom: 0 !important;\n width: ${e} !important;\n height: 100vh !important;\n max-height: 100vh !important;\n margin: 0 !important;\n padding: 0 !important;\n display: flex !important;\n flex-direction: column !important;\n z-index: ${x} !important;\n ${w?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}\n `,at.style.cssText=`\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: ${j} !important;\n border-radius: ${K} !important;\n ${D?"border: none !important;":O?`border: ${R} !important;`:""}\n `,at.style.setProperty("width","100%","important"),at.style.setProperty("max-width","100%","important"),lt.style.cssText=`\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n max-height: 100% !important;\n overflow: hidden !important;\n border-radius: ${V} !important;\n border: ${_} !important;\n ${D&&!q?`box-shadow: ${z} !important;`:""}\n ${q?"background: transparent !important;":""}\n `,tn||(Bt.style.cssText=`\n flex-shrink: 0 !important;\n border-top: none !important;\n padding: 8px 16px 12px 16px !important;\n ${q?"background: transparent !important;":""}\n `)}if(!s&&!r){let e="max-height: -moz-available !important; max-height: stretch !important;",t=o?"":"padding-top: 1.25em !important;",r=o?"":`z-index: ${n.launcher?.zIndex??pn} !important;`;ot.style.cssText+=e+t+r}br(),G()},Jo=()=>{e.style.setProperty("--persona-content-max-width",ks(n,se()))},Go=!1;function Yo(){n.layout?.topFade&&dt.scrollTop>1?dt.setAttribute("data-persona-top-fade","true"):dt.removeAttribute("data-persona-top-fade")}let Xo=()=>{Yo();let t=Ms(n,se());se()&&n.composer?.placement&&!0===n.debug&&!Go&&(Go=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=cr();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",pr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??As),wr()},Qo=()=>{if(se())return;let t=vi(n),r=n.launcher?.sidebarMode??!1;if(t||r||n.launcher?.fullHeight||!Y)return;let o=e.ownerDocument.defaultView??window,a=n.launcher?.mobileFullscreen??!0,s=n.launcher?.mobileBreakpoint??640;if(a&&o.innerWidth<=s)return;let i=Ml(n);at.style.height=i.height,at.style.maxHeight=i.maxHeight};Uo(),Cs(e,n),kd(e,n),Ad(e,n),Jo(),Xo(),_n=()=>{Uo(),Qo(),Cs(e,n),kd(e,n),Ad(e,n),Jo(),Xo(),Un?e.style.setProperty("--persona-artifact-welded-outer-radius",Un):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Ge(),Je()};let Zo=[];Zo.push(()=>{Dn=!0}),Zo.push(()=>{u.forEach(e=>e()),p.destroy()}),Zo.push(()=>{document.removeEventListener("keydown",po)}),Zo.push(()=>{null!==sr&&clearTimeout(sr)});let ea=null,ta=null;Zo.push(()=>{ea?.(),ea=null,ta?.(),ta=null}),Fn&&Zo.push(()=>{Fn?.disconnect(),Fn=null}),Zo.push(()=>{go?.(),go=null,To(),mo&&(mo.remove(),mo=null),Wn?.element.style.removeProperty("width"),Wn?.element.style.removeProperty("maxWidth"),Wn?.destroy()}),ye&&Zo.push(()=>{Ee=!0,Te=null,null!==De&&(cancelAnimationFrame(De),De=null),Le?.destroy(),Le=null,Ae?.destroy(),Ae=null,Se=null});let na=null,oa=()=>{na&&(na(),na=null),"auto"===n.colorScheme&&(na=Ss(()=>{Cs(e,n)}))};oa(),Zo.push(()=>{na&&(na(),na=null)}),Zo.push(()=>{x=!0,v?.()}),Zo.push(()=>{A=!0});let aa=!1;Zo.push(()=>{aa=!0});let sa=(t,r)=>{let n=Xs(t,r);return n||!Ks.includes(t)?n:(mi().then(n=>{if(aa)return;Js(n.wipe),Js(n.glyphCycle);let o=Xs(t,r);o&&ci(o,e)}).catch(()=>{}),null)},ia=n.features?.streamAnimation;if(ia?.type&&"none"!==ia.type){let t=sa(ia.type,ia.plugins);t&&ci(t,e),Zo.push(()=>(e=>{let t=di.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}})(e))}let la=Mi(ht),da=Mi(pt),ca=Mi(ut),pa=[la,da,ca];Zo.push(()=>{pa.forEach(e=>e.destroy())});let ha,ma=null,Ma=null,Ia=!1,Ta=0,La=null,Pa=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),Ba=e=>{for(let t=e.length-1;t>=0;t--)if(yr(e[t]))return e[t].id??null;return null},Ha=!1,$a=!1,Wa=!1,Da=(e,t)=>{$a||!0!==n.debug||!t.enabled||t.expose||Ia||Wa&&(ha.isStreaming()||e.some(yr)||($a=!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.")))},Oa=e=>{if(!ha)return;let t=e??ha.getMessages(),r=e=>{e.render([],ha,mt,t)},o=e=>{pa.forEach(t=>{t!==e&&r(t)})};Ma&&(Pa(t)>Ta||Ba(t)!==La)&&(Ma=null);let a=xr(n);Da(t,a);let s=a.enabled?vr(t):null,i=Ma??s,l=Ma?"host":"agent";if(i){let e=n.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),a="after-message"===("auto"===r?se()?"composer":"after-message":r)?ca:la;return o(a),void a.render(i,ha,mt,t,n.suggestionChipsConfig,{source:l,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??"wrap",maxItems:e?.maxItems??4,config:n,plugins:c,submitPrompt:rp})}if(t.some(e=>"user"===e.role))return void pa.forEach(r);let d=!0===n.future?.v5Defaults,p=dr(),u=n.suggestions?.starters??(d?{}:void 0);if(u){let e=kl(cr(),t),a=u.placement??"auto",s="auto"===a?e?"welcome":"composer":a;if("welcome"===s&&!e)return Ha||!0!==n.debug||(Ha=!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".')),void pa.forEach(r);let i="welcome"===s?da:la;return o(i),void i.render(u.items??n.suggestionChips,ha,mt,t,n.suggestionChipsConfig,{surface:"starter",variant:u.variant??(d&&!p?"chip":"card"),behavior:u.behavior??"send",overflow:u.overflow??"wrap",maxItems:u.maxItems??(d&&!p?3:4),config:n,plugins:c,submitPrompt:rp})}o(la),la.render(n.suggestionChips,ha,mt,t,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:n,plugins:c,submitPrompt:rp})},Fa=()=>{Ma&&(Ma=null,Oa())},za=!1,qa=new Map,ja=new Map,_a=new Map,Va=new Map,Ua=null,Ka=null;function Ja(){if(!Ua)return;let e=Ua;Ua=null,Ka?.destroy(),Ka=null,qa.delete(e),lt.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),ha&&pl(ct,ha.getMessages(),ue)}let Ga=0,Ya=null!==Ve(),Xa=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),Qa=0,Za=null,ts=!1,rs=!1,ns=0,os=null,as=null,ss=!1,is=!1,ls=null,ds=!0,cs=!1,ps=null,us=!1,hs=()=>{us=!0,bs()},ms=null,gs=24,fs=null,ys=()=>{e.setAttribute("data-persona-scrollbar",Xt()),"on-scroll"!==Xt()&&(null!==fs&&clearTimeout(fs),fs=null,dt.removeAttribute("data-persona-scrollbar-visible"))},bs=()=>{"on-scroll"===Xt()&&(dt.setAttribute("data-persona-scrollbar-visible",""),null!==fs&&clearTimeout(fs),fs=setTimeout(()=>{fs=null,zs(dt,gs)&&dt.removeAttribute("data-persona-scrollbar-visible")},1e3))};ys(),Zo.push(()=>{null!==fs&&clearTimeout(fs)});let vs=new Map,Ts=!1,Ps=null,Bs={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};An();let $s=n.voiceRecognition?.autoResume??!1,js=e=>{N.emit("voice:state",{active:Bs.active,source:e,timestamp:Date.now()})},Vs=()=>{U(e=>({...e,voiceState:{active:Bs.active,timestamp:Date.now(),manuallyDeactivated:Bs.manuallyDeactivated}}))},Us=()=>ha?Kc(ha.getMessages()).filter(e=>!e.__skipPersist):[],Gs=null,Ys=(e,t)=>{typeof console<"u"&&console.error(e,t)},Zs=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{Ys(t,e)}):null}catch(e){return Ys(t,e),null}},n=Gs?Gs.then(()=>r()??void 0):r();if(!n)return;let o=n.finally(()=>{Gs===o&&(Gs=null)});Gs=o};function ei(e){if(!R?.save)return;let t=e?Kc(e):ha?Us():[],r=H&&ha?.getResumableHandle();r&&($={...$,durableResume:{executionId:r.executionId,after:r.lastEventId}});let n={messages:t,metadata:$,artifacts:Kn.artifacts,selectedArtifactId:Kn.selectedId,...ti?{draft:ti}:{}};Zs(()=>R.save(n),"[AgentWidget] Failed to persist state:")}let ti,ri=()=>!(!R?.save||!1===n.persistState||"object"==typeof n.persistState&&!1===n.persistState.persist?.draft),ni=function(e){let t=e.delay??500,r=null,n=!1,o=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{n||(o(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{n||null===r||(o(),e.write())},cancel:o,destroy:()=>{n=!0,o()}}}({write:()=>{if(!ri())return;let e=Ar.getState(),t=function(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}({text:e.text,mentionRefs:e.mentionRefs,contentSegments:Bc(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(ti)&&(ti=t,ei())}});function oi(){ri()&&ni.schedule()}function li(){ni.flush()}function pi(e){if(!ri())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),o=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(e=>e.id)),s=(e.activeModeIds??[]).filter(e=>a.has(e)),i=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...o?{mentionRefs:n}:{},...o&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(n.contextMentions?.sources??[]).map(e=>e.id),modelIds:(n.composer?.models??[]).map(e=>e.id),modes:n.composer?.modes??[]});t&&(ti=e,mt&&!mt.value&&(mt.value=t.text,mt.dispatchEvent(new Event("input",{bubbles:!0})),Mr()),t.selectedModelId&&(Ar.setSelectedModelId(t.selectedModelId),$r?.repaint()),Rr(t.activeModeIds??[]),t.quote&&zr(t.quote),ni.cancel())}function ui(){ni.cancel(),ti&&(ti=void 0,ri()&&ei())}let hi=null,fi=()=>ot.querySelector("#persona-scroll-container")||dt,yi=()=>{null!==hi&&(cancelAnimationFrame(hi),hi=null),ts=!1},Ci=()=>{null!==Za&&(cancelAnimationFrame(Za),Za=null),rs=!1,yi()},ki=()=>{let e=_t()||"Jump to latest",t=za&&Ei()&&("anchor-top"!==Vt()||Gt());Zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",t),ns>0?(nr.textContent=String(ns),nr.style.display="",Zt.setAttribute("aria-label",`${e} (${ns} new)`)):(nr.textContent="",nr.style.display="none",Zt.setAttribute("aria-label",t?`${e} (response streaming below)`:e))},Ti=()=>{0!==ns&&(ns=0,ki())},Ei=()=>Ut()?!Xa.isFollowing():!(()=>{let e=os?.spacerHeight??0;return e<=0?zs(dt,gs):Ki(e)-dt.scrollTop-dt.clientHeight<=gs})(),Li=()=>!!ha&&ha.getMessages().length>0,Ni=()=>{if(!1===be.enabled||We||Ue&&"panel"===Ke)return Zt.parentNode&&Zt.remove(),void(Zt.style.display="none");Zt.parentNode!==lt&<.appendChild(Zt),fr();let e=Fs(dt)>0&&Ei()&&Li();e?ki():Ti(),Zt.style.display=e?"":"none"},Ri=()=>{Xa.pause()&&(Ci(),Ni())},$i=()=>{Xa.resume(),Ti(),Ni()},Wi=(e=!1)=>{Ut()&&Li()&&Xa.isFollowing()&&(!e&&!za||(null!==Za&&(cancelAnimationFrame(Za),Za=null),rs=!0,Za=requestAnimationFrame(()=>{Za=null,rs=!1,Xa.isFollowing()&&zi(fi(),e?220:140)})))},Fi=(e,t,r,n=()=>!0)=>{let o=e.scrollTop,a=t(),s=a-o;if(yi(),Math.abs(s)<1)return ts=!0,e.scrollTop=a,Qa=e.scrollTop,void(ts=!1);let i=performance.now();ts=!0;let l=d=>{if(!n())return void yi();let c=t();c!==a&&(a=c,s=a-o);let p=d-i,u=Math.min(p/r,1),h=(e=>1-Math.pow(1-e,3))(u),m=o+s*h;e.scrollTop=m,Qa=e.scrollTop,u<1?hi=requestAnimationFrame(l):(e.scrollTop=a,Qa=e.scrollTop,hi=null,ts=!1)};hi=requestAnimationFrame(l)},zi=(e,t=500)=>{let r=Fs(e)-e.scrollTop;if(!(Math.abs(r)<1))return Math.abs(r)>=80?(yi(),ts=!0,e.scrollTop=Fs(e),Qa=e.scrollTop,void(ts=!1)):void Fi(e,()=>Fs(e),t,()=>Xa.isFollowing());Qa=e.scrollTop},qi=()=>{if(!Li())return void Ni();let e=fi();ts=!0,e.scrollTop=Fs(e),Qa=e.scrollTop,ts=!1,Ni()},ji=e=>{let t=0,r=e;for(;r&&r!==dt;)t+=r.offsetTop,r=r.offsetParent;return t},_i=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=dt.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??dt.ownerDocument.getSelection()})(),dt),Vi=()=>{if("last-user-turn"!==(ve.restorePosition??"bottom"))return!1;let e=ha?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>"user"===e.role);if(!t)return!1;let r=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(t.id):t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=dt.querySelector(`[data-message-id="${r}"]`);if(!n)return!1;let o=Math.min(Math.max(0,ji(n)-Kt()),Fs(dt));return ts=!0,dt.scrollTop=o,Qa=dt.scrollTop,ts=!1,"follow"===Vt()&&!zs(dt,gs)&&Xa.pause(),Ni(),!0},Ui=e=>{let t=Math.max(0,Math.round(e));or.style.height=`${t}px`,or.style.display=t>0?"":"none",os&&(os.spacerHeight=Math.max(0,e))},Ki=e=>{let t=parseFloat(getComputedStyle(dt).paddingBottom)||0,r=0;for(let e of Array.from(dt.children)){if(e===or||0===e.offsetHeight)continue;let t=ji(e)+e.offsetHeight;t>r&&(r=t)}let n=dt.scrollHeight-e;return r>0?Math.min(r+t,n):n},Ji=()=>{null!==as&&(cancelAnimationFrame(as),as=null),yi(),os=null,or.style.height="0px",or.style.display="none"},Gi=e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Zi=e=>dt.querySelector(`[data-message-id="${Gi(e)}"]`),el=e=>{null!==as&&cancelAnimationFrame(as),as=requestAnimationFrame(()=>{as=null;let t=Gi(e),r=dt.querySelector(`[data-message-id="${t}"]`);if(!r)return;let n=ji(r),o=Ki(os?.spacerHeight??0),{targetScrollTop:a,spacerHeight:s}=qs({anchorOffsetTop:n,topOffset:Kt(),viewportHeight:dt.clientHeight,contentHeight:o,slack:gs});os={initialSpacerHeight:s,contentHeightAtAnchor:o,spacerHeight:s},Ui(s),Fi(dt,()=>r.isConnected?Math.max(0,ji(r)-Kt()):a,220)})},rl=()=>{if("anchor-top"!==Vt()||!os||!ps)return;let e=Zi(ps);if(!e)return;yi();let t=os.spacerHeight,r=Ki(t),{targetScrollTop:n,spacerHeight:o}=qs({anchorOffsetTop:ji(e),topOffset:Kt(),viewportHeight:dt.clientHeight,contentHeight:r,slack:gs});os={initialSpacerHeight:o,contentHeightAtAnchor:r,spacerHeight:o},Ui(o),ts=!0,dt.scrollTop=n,Qa=dt.scrollTop,ts=!1,Ni()},nl=e=>{if(null===ls)return!0;let t=Zi(ls),r=Zi(e);if(!t||!r)return!0;let n=ji(r)-ji(t);return Kt()+n>dt.clientHeight-96},al=(e,t)=>{let r="user"===t?"user":"assistant",o=n.layout?.messages?.[r],a=o?.width??"content",s=o?.maxWidth??("full"===a?`var(--persona-message-${r}-max-width, 100%)`:void 0);e.classList.add("persona-message-row"),e.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",a),s?e.style.setProperty("--persona-message-row-max-width",s):e.style.removeProperty("--persona-message-row-max-width")},il=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),al(r,t),r},ll=!1,dl=()=>{ll||(ll=!0,xt().catch(()=>{}),je().catch(()=>{ll=!1}))},pl=(e,t,r)=>{t.length>0&&dl(),((e,t,r)=>{let l=new Set;for(let e of t){let t="tool"===e.variant?"tool":"reasoning"===e.variant?"reasoning":null;if(!t||"row"!==Pe(n,t))continue;let r="tool"===t?n.features?.toolCallDisplay:n.features?.reasoningDisplay;!1!==r?.expandable&&(l.add(e.id),s.observe(e,t,"tool"===t?o:a,r))}let d=document.createElement("div"),p=(()=>{let e=c.find(e=>e.renderLoadingIndicator);return e?.renderLoadingIndicator?e.renderLoadingIndicator:n.loadingIndicator?.render?n.loadingIndicator.render:void 0})(),u=new Set,h=new Map,m=new Set,g=c.some(e=>e.renderAskUserQuestion),f=[],y=[],v=!1!==n.enableComponentStreaming,w=!1!==n.approval,x=[],C=n.messageActions,S=!0===C?.showRegenerate&&!1!==C.enabled&&!0!==ro.current?.isStreaming()?function(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if("user"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return qn(e,r.id)?r.id:null}return null}(t):null,A=!0===C?.showEdit&&!1!==C.enabled,M=!0===C?.showQuote&&!1!==C.enabled,I=null,T=n.features?.reasoningDisplay?.completedVisibility,E=e=>"removed"===T||"removed-when-short"===T&&((e,t)=>{let r=t?.durationMs??15e3,n=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<n})(e,n.features?.reasoningDisplay?.shortThinkThreshold),P="removed"===n.features?.toolCallDisplay?.completedVisibility,B=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?E(e.reasoning):P&&"tool"===e.variant&&"complete"===e.toolCall?.status;if(t.forEach(t=>{if(B(t))return;if(u.add(t.id),h.set(t.id,t.role),Ua===t.id&&Ka){let e=il(t.id,t.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void(I={messageId:t.id,element:Ka.element})}let s=g&&Qt(t),l=w&&"approval"===t.variant&&!!t.approval,C=!s&&"assistant"===t.role&&!t.variant&&v&&Wc(t);!l&&Va.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Va.delete(t.id)),!C&&_a.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),_a.delete(t.id));let T=Qt(t)?`:${t.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:"",E={canRegenerate:S===t.id,canEdit:A&&jn(t),canQuote:M&&!t.variant&&(t.content?.trim().length??0)>0},P=`${E.canRegenerate?"r":""}${E.canEdit?"e":""}${E.canQuote?"q":""}`,N=function(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)??"","string"==typeof e.toolCall?.args?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")}(t,Ga)+T+`:${P}`,R=s||l||C?null:function(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}(qa,t.id,N);if(R)return d.appendChild(R.cloneNode(!0)),void(Qt(t)&&t.toolCall?.id&&!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ao(t)));let H=null,$=c.find(e=>!!("reasoning"===t.variant&&e.renderReasoning||"tool"===t.variant&&e.renderToolCall||!t.variant&&e.renderMessage)),W=n.layout?.messages;if(Qt(t)&&!0===t.agentMetadata?.askUserQuestionAnswered)return ja.delete(t.id),void e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime");if(yr(t)&&xr(n).enabled)return;if(Qt(t)&&!1!==n.features?.askUserQuestion?.enabled){let e=c.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&ro.current){let r=ja.get(t.id),o=r!==N,a=null;if(o){let{payload:r,complete:o}=er(t),s=t.id,i=()=>ro.current?.getMessages().find(e=>e.id===s);a=e.renderAskUserQuestion({message:t,payload:r,complete:o,resolve:e=>{let t=i();t&&ro.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=i();e?.agentMetadata?.awaitingLocalTool&&(ro.current?.markAskUserQuestionResolved(e),ro.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:n})}if(o&&null===a&&null==r)return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ao(t)));let s=il(t.id,t.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),d.appendChild(s),void f.push({messageId:t.id,fingerprint:N,bubble:a})}return void(!0===t.agentMetadata?.awaitingLocalTool&&!t.agentMetadata?.askUserQuestionAnswered&&(m.add(t.toolCall.id),ao(t)))}if(l){let r=k();if(!r)return void d.appendChild(il(t.id,t.role));let o=c.find(e=>"function"==typeof e.renderApproval)??b,a=Va.get(t.id)!==N,s=null;if(a&&o?.renderApproval){let e=t.id,a=(t,r)=>{let n=ro.current?.getMessages().find(t=>t.id===e);n?.approval&&("webmcp"===n.approval.toolType?ro.current?.resolveWebMcpApproval(n.id,t):ro.current?.resolveApproval(n.approval,t,r))};s=o.renderApproval({message:t,defaultRenderer:()=>r.createApprovalBubble(t,n,i),config:n,approve:e=>a("approved",e),deny:e=>a("denied",e)})}if(!a||null!==s){let e=il(t.id,t.role);return e.setAttribute("data-approval-plugin-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void x.push({messageId:t.id,fingerprint:N,bubble:s})}e.querySelector(`#wrapper-${t.id}`)?.removeAttribute("data-preserve-runtime"),Va.delete(t.id),H=r.createApprovalBubble(t,n,i)}else if($)if("reasoning"===t.variant&&t.reasoning&&$.renderReasoning){if(!he)return;H=$.renderReasoning({message:t,defaultRenderer:()=>Fl(t,n,a),config:n})}else if("tool"===t.variant&&t.toolCall&&$.renderToolCall){if(!me)return;H=$.renderToolCall({message:t,defaultRenderer:()=>Jl(t,n,o),config:n})}else $.renderMessage&&(H=$.renderMessage({message:t,defaultRenderer:()=>{let e=cl(t,r,W,n.messageActions,et,{loadingIndicatorRenderer:p,widgetConfig:n,actionEligibility:E});return"user"!==t.role&&L(e,t,n,ha),e},config:n}));if(!H&&C){let o=Dc(t);if(o){let a=_a.get(t.id),s=a!==N,i=!1!==n.wrapComponentDirectiveInBubble&&!1!==sd.getOptions(o.component)?.bubbleChrome,l=null;if(s){let a=Rc(o,{config:n,message:t,transform:r});if(a&&"PersonaArtifactInline"===o.component){let r=a.hasAttribute("data-artifact-inline")?a:a.querySelector("[data-artifact-inline]"),n=r?.getAttribute("data-artifact-inline")??"",o=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(n):n,s=n?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${o}"]`)??null:null;r&&s&&s!==r&&yd()?.hasLiveInlineArtifactBlock(s)&&(r===a?a=s:r.replaceWith(s))}if(a)if(i){let e=document.createElement("div");if(e.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),e.id=`bubble-${t.id}`,e.setAttribute("data-message-id",t.id),t.content&&t.content.trim()){let n=document.createElement("div");n.className="persona-mb-3 persona-text-sm persona-leading-relaxed",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(a),l=e}else{let e=document.createElement("div");if(e.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",e.id=`bubble-${t.id}`,e.setAttribute("data-message-id",t.id),e.setAttribute("data-persona-component-directive","true"),t.content&&t.content.trim()){let n=document.createElement("div");n.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",n.innerHTML=r({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(n)}e.appendChild(a),l=e}}if(l||null!=a){let e=il(t.id,t.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),d.appendChild(e),void y.push({messageId:t.id,fingerprint:N,bubble:l})}}}if(!H)if("reasoning"===t.variant&&t.reasoning){if(!he)return;H=Fl(t,n,a)}else if("tool"===t.variant&&t.toolCall){if(!me)return;H=Jl(t,n,o)}else if("approval"===t.variant&&t.approval){if(!1===n.approval)return;let e=k();if(!e)return;H=e.createApprovalBubble(t,n,i)}else{let e=n.layout?.messages;H=e?.renderUserMessage&&"user"===t.role?e.renderUserMessage({message:t,config:n,streaming:!!t.streaming}):e?.renderAssistantMessage&&"assistant"===t.role?e.renderAssistantMessage({message:t,config:n,streaming:!!t.streaming}):cl(t,r,e,n.messageActions,et,{loadingIndicatorRenderer:p,widgetConfig:n,actionEligibility:E}),"user"!==t.role&&H&&L(H,t,n,ha)}let D=il(t.id,t.role);D.appendChild(H),function(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}(qa,t.id,N,D),d.appendChild(D)}),it.composerOverlay&&it.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!m.has(t)&&hr(it.composerOverlay,t)}),n.features?.toolCallDisplay?.grouped){let e=[],r=[],a="summary"===n.features.toolCallDisplay.groupedMode;t.forEach(t=>{if("tool"===t.variant&&t.toolCall&&me){if(P&&"complete"===t.toolCall.status)return;r.push(t)}else"reasoning"===t.variant&&(!he||"complete"===t.reasoning?.status&&E(t.reasoning))||((r.length>1||a&&r.length>0)&&e.push(r),r=[])}),(r.length>1||a&&r.length>0)&&e.push(r),e.forEach(e=>{let t=e.map(e=>Array.from(d.children).find(t=>t instanceof HTMLElement&&t.getAttribute("data-wrapper-id")===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let r=il(`tool-group-${e[0].id}`,"assistant");if(r.setAttribute("data-persona-tool-group-row","true"),"collapsible"===n.features?.toolCallDisplay?.groupedMode){let a=`tool-group-${e[0].id}`,i=e.some(e=>"complete"!==e.toolCall?.status),d={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:i?"running":"complete",chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>!1===e.toolCall?.success)}};l.add(a),s.observe(d,"tool",o,n.features.toolCallDisplay);let c=`${i?"Using":"Used"} ${e.length} tools`,p=n.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:c,config:n}),u=function(e,t,r,n){let o=ne("div","");o.id=`bubble-${e.id}`,o.dataset.messageId=e.id;let a=ne("button","");a.type="button",a.dataset.expandHeader="true",a.dataset.bubbleType="tool",a.setAttribute("aria-expanded",String(r));let s=ne("div","");"string"==typeof n?s.textContent=n:s.appendChild(n),Me(a,s,{expandable:!0,expanded:r,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let i=ne("div","persona-border-t");return i.id=`activity-details-${e.id}`,i.style.display=r?"":"none",a.setAttribute("aria-controls",i.id),o.append(a,i),Ne(o,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),o.dataset.personaToolGroup="true","shimmer"===t.features?.toolCallDisplay?.loadingAnimation&&(o.dataset.activityGroupShimmer="true"),{bubble:o,body:i}}(d,n,o.has(a),p??c);return u.bubble.classList.add("persona-tool-group"),u.body.dataset.personaToolGroupStack="true",t[0].before(r),r.appendChild(u.bubble),void t.forEach((e,t)=>{e.style.setProperty("--persona-message-row-max-width","100%"),e.style.setProperty("--persona-activity-stagger",40*t+"ms"),e.classList.add("persona-activity-group-child"),u.body.appendChild(e)})}let i=document.createElement("div");i.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",i.setAttribute("data-persona-tool-group","true");let c=document.createElement("div");c.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",c.id=`tool-group-summary-${e[0].id}`;let p=`Called ${e.length} ${1===e.length?"tool":"tools"}`,u=n.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:p,config:n});((e,t)=>null!=t&&("string"==typeof t?(e.textContent=t,!0):(e.appendChild(t),!0)))(c,u)||(c.textContent=p);let h=document.createElement("div");h.className="persona-tool-group-stack persona-flex persona-flex-col",h.id=`tool-group-stack-${e[0].id}`,h.setAttribute("data-persona-tool-group-stack","true"),i.appendChild(c),a||i.appendChild(h),r.appendChild(i),t[0].before(r),t.forEach((e,r)=>{if(a)return void e.remove();e.style.setProperty("--persona-message-row-max-width","100%");let n=document.createElement("div");n.className="persona-tool-group-item persona-relative",n.setAttribute("data-persona-tool-group-item","true"),r<t.length-1&&n.setAttribute("data-persona-tool-group-connector","true"),n.appendChild(e),h.appendChild(n)})})}s.prune(l),function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(qa,u);let N=e=>"tool"===e.variant&&!me||"reasoning"===e.variant&&!he||B(e),R=t.some(e=>"assistant"===e.role&&e.streaming&&!N(e)),H=t.length-1;for(;H>=0&&N(t[H]);)H--;let $=H>=0?t[H]:void 0,W=H<t.length-1,D="assistant"===$?.role&&!$.streaming&&"approval"!==$.variant&&!W;if(za&&t.some(e=>"user"===e.role)&&!R&&!D){let e={config:n,streaming:!0,location:"standalone",defaultRenderer:tl},t=c.find(e=>e.renderLoadingIndicator),r=null;if(t?.renderLoadingIndicator&&(r=t.renderLoadingIndicator(e)),null===r&&n.loadingIndicator?.render&&(r=n.loadingIndicator.render(e)),null===r&&(r=tl()),r){let e=document.createElement("div"),t=!1!==n.loadingIndicator?.showBubble,o=n.layout?.messages?.layout??"bubble";e.className=t?ol("assistant",o).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),e.setAttribute("data-typing-indicator","true"),t&&(e.style.color="var(--persona-message-assistant-text, var(--persona-text))","flat"!==o&&(e.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),e.appendChild(r);let a=il("typing-indicator","assistant");a.appendChild(e),d.appendChild(a)}}if(!za&&t.length>0){let e=t[t.length-1],r={config:n,lastMessage:e,messageCount:t.length},o=c.find(e=>e.renderIdleIndicator),a=null;if(o?.renderIdleIndicator&&(a=o.renderIdleIndicator(r)),null===a&&n.loadingIndicator?.renderIdle&&(a=n.loadingIndicator.renderIdle(r)),a){let e=document.createElement("div"),t=!1!==n.loadingIndicator?.showBubble;e.className=t?["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(" "),e.setAttribute("data-idle-indicator","true"),e.appendChild(a);let r=il("idle-indicator","assistant");r.appendChild(e),d.appendChild(r)}}if(function(e){e.querySelectorAll("table").forEach(e=>{if(e.parentElement?.classList.contains("persona-table-scroll"))return;let t=document.createElement("div");t.className="persona-table-scroll",e.replaceWith(t),t.appendChild(e)})}(d),Ws(e,d),gt(e),I){let{messageId:t,element:r}=I,n=e.querySelector(`#wrapper-${t}`);n&&r.parentElement!==n&&(al(n,h.get(t)??"user"),n.replaceChildren(r))}if(f.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of f){let o=e.querySelector(`#wrapper-${t}`);o&&(al(o,h.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),ja.set(t,r)))}if(ja.size>0)for(let e of ja.keys())u.has(e)||ja.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of y){let o=e.querySelector(`#wrapper-${t}`);o&&(al(o,h.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),_a.set(t,r)))}if(_a.size>0)for(let e of _a.keys())u.has(e)||_a.delete(e);if(x.length>0)for(let{messageId:t,fingerprint:r,bubble:n}of x){let o=e.querySelector(`#wrapper-${t}`);o&&(al(o,h.get(t)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Va.set(t,r)))}if(Va.size>0)for(let e of Va.keys())u.has(e)||Va.delete(e)})(e,t,r),Hn()},ml=null,gl=()=>{ml&&((e.ownerDocument??document).removeEventListener("pointerdown",ml,!0),ml=null)};Zo.push(()=>gl());let fl=null,xl=()=>{fl&&((e.ownerDocument??document).removeEventListener("keydown",fl,!0),fl=null)};Zo.push(()=>xl());let Cl=!1,Al=new Set,Il=()=>{if(!se())return;let t=it.peekBanner,r=it.peekTextNode;if(!t||!r)return;if(le)return void t.classList.remove("persona-pill-peek--visible");let o,a=ha?.getMessages()??[];for(let e=a.length-1;e>=0;e--){let t=a[e];if("assistant"===t.role&&t.content){o=t;break}}if(!o)return void t.classList.remove("persona-pill-peek--visible");let s=o.content,i=!!o.streaming,l=(()=>{let e=n.launcher?.composerBar?.peek?.streamAnimation;return e||n.features?.streamAnimation})(),d=_s(l),c="none"!==d.type?sa(d.type,l?.plugins):null,p=!0===c?.isAnimating?.(o),u=null!==c&&(i||p);u&&c&&!Al.has(c.name)&&(ci(c,e),Al.add(c.name));let h=u&&c?.containerClass?c.containerClass:null,m=r.dataset.personaPeekStreamClass??null;m&&m!==h&&(r.classList.remove(m),delete r.dataset.personaPeekStreamClass),h&&m!==h&&(r.classList.add(h),r.dataset.personaPeekStreamClass=h),u?(r.style.setProperty("--persona-stream-step",`${d.speed}ms`),r.style.setProperty("--persona-stream-duration",`${d.duration}ms`)):(r.style.removeProperty("--persona-stream-step"),r.style.removeProperty("--persona-stream-duration"));let g=u?Qs(s,d.buffer,c,o,i):s;if(!u||"skeleton"!==d.placeholder||!i||g&&g.trim()){let e=Math.max(0,g.length-100),n=g.length>100?g.slice(-100):g,a=Ye(n);if(u&&c){let s=a;("char"===c.wrap||"word"===c.wrap)&&(s=ai(a,c.wrap,`peek-${o.id}`,{skipTags:c.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,c.useCaret&&n.length>0){let e=si(),t=i.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];r?.parentNode?r.parentNode.insertBefore(e,r.nextSibling):i.appendChild(e)}Ws(r,i),c.onAfterRender?.({container:r,bubble:t,messageId:o.id,message:o,speed:d.speed,duration:d.duration})}else{let e=g.length>100?`…${n}`:n;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=ii();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),Ws(r,e)}let f=za||Cl;t.classList.toggle("persona-pill-peek--visible",f)};if(se()){let e=it.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Pl(!0,"user")};e.addEventListener("pointerdown",t),Zo.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Cl||(Cl=!0,Il())},r=()=>{Cl&&(Cl=!1,Il())};at.addEventListener("pointerenter",t),at.addEventListener("pointerleave",r),Zo.push(()=>{at.removeEventListener("pointerenter",t),at.removeEventListener("pointerleave",r)}),st&&(st.addEventListener("pointerenter",t),st.addEventListener("pointerleave",r),Zo.push(()=>{st.removeEventListener("pointerenter",t),st.removeEventListener("pointerleave",r)}))}let Ll=()=>{if(le&&dl(),!ie())return;if(se()){let t=(n.launcher?.composerBar??{}).expandedSize??"anchored",r=le?"expanded":"collapsed";return ot.dataset.state=r,ot.dataset.expandedSize=t,st&&(st.dataset.state=r,st.dataset.expandedSize=t),ot.style.removeProperty("display"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=n.launcher?.composerBar??{},r=t.expandedSize??"anchored",o=t.bottomOffset??"16px",a=t.collapsedMaxWidth,s=t.expandedMaxWidth??"880px",i=t.expandedTopOffset??"5vh",l=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)",p=ot.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",st){let e=st.style;e.bottom=o,e.width=a??""}if(e&&"fullscreen"!==r){if("modal"===r)return p.top="50%",p.left="50%",p.transform="translate(-50%, -50%)",p.bottom="auto",p.right="auto",p.width=l,p.maxWidth=c,p.maxHeight=d,void(p.height=d);p.left="50%",p.transform="translateX(-50%)",p.bottom=`calc(${o} + var(--persona-pill-area-height, 80px))`,p.top=i,p.width=s,p.maxWidth=c}})(le),lt.style.display=le?"flex":"none",_n(),le?((()=>{if(ml)return;let t=e=>{let t=e.composedPath();t.includes(ot)||st&&t.includes(st)||Pl(!1,"user")};ml=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)})(),(()=>{if(fl)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Pl(!1,"user"))};fl=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)})()):(gl(),xl()),void Il()}let t=vi(n),r=e.ownerDocument.defaultView??window,o=n.launcher?.mobileBreakpoint??640,a=n.launcher?.mobileFullscreen??!0,s=r.innerWidth<=o,i=a&&s&&Y,l=xi(n).reveal;le?(ot.style.removeProperty("display"),ot.style.display=t?"flex":"",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-95","persona-opacity-0"),at.classList.add("persona-scale-100","persona-opacity-100"),Kp?(Kp.setPanelOpen(!0),Kp.element.style.display="none"):Jp&&(Jp.style.display="none")):(t?!t||"overlay"!==l&&"push"!==l||i?(ot.style.setProperty("display","none","important"),ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.removeProperty("display"),ot.style.display="flex",ot.classList.remove("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ot.style.display="",ot.classList.add("persona-pointer-events-none","persona-opacity-0"),at.classList.remove("persona-scale-100","persona-opacity-100"),at.classList.add("persona-scale-95","persona-opacity-0")),Kp?(Kp.setPanelOpen(!1),Kp.element.style.display=t?"none":""):Jp&&(Jp.style.display=t?"none":""))},Pl=(t,r="user")=>{if(!ie()||le===t)return;let o=le;le=t,Ll();let a=(()=>{let t=n.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,o=n.launcher?.mobileFullscreen??!0,a=n.launcher?.mobileBreakpoint??640,s=r.innerWidth<=a,i=vi(n)&&o&&s,l=se()&&"fullscreen"===(n.launcher?.composerBar?.expandedSize??"fullscreen");return t||o&&s&&Y||i||l})();if(le&&a){if(!ea){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(ea=gi(r,n.launcher?.zIndex??pn))}ta||(ta=bi(e.ownerDocument))}else le||(ea?.(),ea=null,ta?.(),ta=null);le&&(Qp(),Vi()||("follow"===Vt()?Wi(!0):qi()));let s={open:le,source:r,timestamp:Date.now()};le&&!o?N.emit("widget:opened",s):!le&&o&&N.emit("widget:closed",s),N.emit("widget:state",{open:le,launcherEnabled:Y,voiceActive:Bs.active,streaming:ha.isStreaming()})},Bl={inputDisabled:!1,sendDisabled:!1},Nl=()=>Bl.inputDisabled,Rl=()=>$e(n.voiceRecognition?.provider)&&!!ha&&(ha.isBargeInActive()||["listening","processing","speaking"].includes(ha.getVoiceStatus())),Hl=()=>Bl.inputDisabled||Bl.sendDisabled;function Dl(){if(!ft)return;if("streaming"===Ar.getState().phase)return void(ft.disabled=!1);let e=!!Sr&&!Sr.isReady();ft.disabled=Hl()||e}function zl(){if(!$t)return;let e=Ar.getState(),t="when-text"===n.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;$t.toggleAttribute("data-persona-send-hidden",t)}function ql(){let e=Oo(n.composer?.inputDisabled),t=Oo(n.composer?.sendDisabled);Bl={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Ar.setInputDisabled(e.disabled),Ar.setSendDisabled(t.disabled);let r="streaming"===Ar.getState().phase,o=e.disabled,a=r||o;mt&&(mt instanceof HTMLTextAreaElement?mt.disabled=o:mt.setAttribute("contenteditable",o?"false":"true"),mt.setAttribute("aria-disabled",o?"true":"false")),Ft&&(Ft.disabled=o),qt&&(qt.disabled=o);for(let e of kr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=o});Dt&&(Dt.disabled=o||r&&!Rl()),pa.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",a?"true":"false")}),e.buttons.forEach(e=>{e.disabled=a})}),ud.forEach(e=>{e.toggleAttribute("data-disabled",a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute("aria-disabled",a?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=a})}),Bt.dataset.personaComposerStreaming=r?"true":"false",Bt.dataset.personaComposerInputDisabled=o?"true":"false",Bt.dataset.personaComposerSendDisabled=Hl()?"true":"false",Bt.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=r)}),Dl(),function(){let e=(Bl.inputDisabled?Bl.inputReason:void 0)??(Bl.sendDisabled?Bl.sendReason:void 0);if(se()){let t=yt??Bt;return e?t.setAttribute("title",e):t.removeAttribute("title"),void Bt.toggleAttribute(jc,!!e)}if(e)return bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.setAttribute(jc,""),bt.textContent=e,void Re(bt,n.statusIndicator??{},"idle");if(bt.hasAttribute(jc)&&(bt.removeAttribute("role"),bt.removeAttribute("aria-live"),bt.removeAttribute(jc),m)){let e=ha.getStatus();rt(bt,tt(e),n.statusIndicator??{},e)}}()}let _l=e=>{Ar.setStreaming(e),Wt(e?"stop":"send"),ql()},Vl=()=>{Bs.active||mt&&mt.focus()};N.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Vl(),200)});let Ul=null,Gl=!1,Yl=!vt.hidden,Xl=null,Ql=!W,Zl=null;Zo.push(()=>{Zl?.cancel(),Zl=null});let rd,nd,od=null,id=null,ld=null,dd=!1,cd=t=>{let r=cr(),o=`${r.variant}|${r.layout}|${r.dismiss}|${r.anchor??"bottom"}|${r.align??""}|${r.iconPlacement}|${r.kicker??""}|${r.title}|${r.subtitle}`;(o!==od||r.icon!==rd)&&(od=o,rd=r.icon,hl({host:vt,iconHolder:wt,kicker:St,title:kt,subtitle:At,starterSuggestions:pt},r));let a=void 0===r.message?null:`${n.layout?.messages?.layout??"bubble"}|${r.message}`;a!==id&&(id=a,vl(Ct,r.message,n));let s=t??(ha?ha.getMessages():n.initialMessages);(t=>{let r=(e=>(e??[]).some(e=>"user"===e.role)?"active":"empty")(t);if(r===pr)return;pr=r,e.setAttribute("data-persona-conversation-state",r);let n=gr();wr(),Ql&&(Zl?.cancel(),Zl=((e,t,r,n=260)=>{if(t<=1||wl()||"function"!=typeof e.animate||!e.isConnected)return null;let o="drop"===r?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:n,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})})(Bt,"active"===r?n:gr(),"active"===r?"drop":"rise","centered"===cr().layout?320:260)),rl()})(s);let i=Gl,l=!i&&kl(r,s),d=l!==Yl;if(Yl=l,ld)return Xl?.cancel(),Xl=null,i!==dd&&(dd=i,i?bl(dt,vt,null):yl(dt,vt,ld)),void ul(dt,vt,!i);if(d&&!l&&!i&&"on-first-message"===r.dismiss&&Ql)return void(Xl=((e,t)=>{if(wl()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),n=e.parentElement,o=0,a=0,s=0;if(n){let t=getComputedStyle(n);o=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=n.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-n.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-o:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-o:0)}let i=e.style.overflow;e.style.overflow="hidden";let l=getComputedStyle(e),d=parseFloat(l.paddingTop)||0,c=parseFloat(l.paddingBottom)||0,p=e.animate([{opacity:"1",transform:"none",height:`${r.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${c}px`,marginTop:`${a}px`,marginBottom:`${s}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:-o+"px"}],{duration:180,easing:"ease-out",fill:"forwards"}),u=!1,h=()=>{u||(u=!0,e.style.overflow=i,t(p))};return p.finished.then(h).catch(h),p})(vt,e=>{Xl===e&&(Xl=null),!Yl&&!ld&&(ul(dt,vt,!1),rl()),e?.cancel()}));if(Xl){if(!l&&!i)return;Xl.cancel(),Xl=null}let c=!vt.hidden;ul(dt,vt,l),!l&&c&&rl()},pd=[],ud=[],hd=!1,md=null,gd=()=>{ud.length=0;let e=pd.splice(0,pd.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};Zo.push(gd);let wd=(e,t)=>{let r=Si(e,t);if(!r)return!0===n.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),ne("span");let o=n.suggestions?.starters,a=Ai({item:{...r,behavior:r.behavior??o?.behavior??"send"},index:t,surface:"starter",source:"config",variant:o?.variant??"card",streaming:!!m&&ha.isStreaming(),config:n,plugins:c,chipsConfig:n.suggestionChipsConfig,session:ha,getTextarea:()=>mt,eventTarget:vt,submitPrompt:rp});return ud.push(a),a},xd=()=>{if(hd)return;hd=!0;let e=cr();md=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,nd=e.icon;try{gd(),bl(dt,vt,ld),ld=null,dd=!1;let t=ha?ha.getMessages():n.initialMessages,r=kl(e,t),o=0,a=null;for(let t of c)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>vt,sendMessage:e=>{if(!ha||ha.isStreaming())return;let t=e.trim();t&&ha.sendMessage(t)},requestRender:()=>xd(),renderStarter:e=>wd(e,o++),storage:f(t.id),onCleanup:e=>{pd.push(e)}}),a))break;a&&a!==vt&&(ld=a,yl(dt,vt,a))}finally{hd=!1}cd()},Cd=()=>{cd(),tn||(mt.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Ar.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!n.sendButton?.useIcon&&!ha?.isStreaming()&&(ft.textContent=n.copy?.sendButtonLabel??"Send")),mt.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',mt.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Md=!!n.setStoredConversationId,Id=e=>U(t=>{let r={...t};return delete r[e],r}),Td=e=>{let t=$[e];return"string"==typeof t?t:null},Ed=()=>{let e=$.durableResume;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.executionId&&t.executionId.length>0&&"string"==typeof t.after&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};n.clientToken&&(n={...n,getStoredSessionId:()=>Td("sessionId"),setStoredSessionId:e=>{U(t=>({...t,sessionId:e}))},clearStoredSessionId:n.clearStoredSessionId??(()=>Id("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Td("conversationId")),setStoredConversationId:n.setStoredConversationId??(e=>{U(t=>({...t,conversationId:e}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>Id("conversationId"))});let Ld=()=>n.clientToken??null,Pd=e=>((e,t,r)=>{let n="",o="",a="",s=!1,i=!1,l=0,d=null,c=null,p=new Set,u=()=>{if(r||s)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return s=!0,null}},h=()=>{let e=u();if(!e)return d;try{return e.getItem(n)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let n={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(n)},g=e=>{i||null!==e.key&&e.key!==n||m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await bc(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await bc(`${e}\0${t}`)}`}})(e,t);n=s.storageKey,o=s.leaseKey,a=s.lockName,d=h(),!r&&typeof window<"u"&&window.addEventListener("storage",g)})(),y=e=>new Promise(t=>setTimeout(t,e)),b=()=>{let e=u();if(!e)return null;try{let t=e.getItem(o);if(!t)return null;let r=JSON.parse(t);return"number"==typeof r?.expiresAt&&"string"==typeof r?.ownerNonce?r:null}catch{return null}},v=e=>{let t=u();if(t)try{b()?.ownerNonce===e&&t.removeItem(o)}catch{}},w=new Set,x=e=>i?Promise.reject(new Error("Visitor store destroyed before its first init could start")):e(),C=e=>new Promise(t=>{let r=setTimeout(n,e);function n(){clearTimeout(r),w.delete(n),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===o)&&n()}w.add(n),window.addEventListener("storage",a)});return{ready:f,get:async()=>(await f,m(h(),"external"),d),async set(e){await f;let t=u();if(t)try{t.setItem(n,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(n)}catch{s=!0}m(null,"local")},revision:()=>l,subscribe:e=>(p.add(e),()=>{p.delete(e)}),async withFirstInitLock(e){await f;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):u()?(async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=Date.now()+15e3;for(;!i&&Date.now()<r;){let r=u();if(!r)break;let n=Date.now(),a=b();if(a&&a.expiresAt>n&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-n,500));else{try{r.setItem(o,JSON.stringify({ownerNonce:t,expiresAt:n+1e4}))}catch{s=!0;break}if(await y(20+40*Math.random()),b()?.ownerNonce===t){c=t;try{return await x(e)}finally{c=null,v(t)}}else await C(500)}}return x(e)})(e):x(e)},matches:(n,o,a)=>n===e&&o===t&&a===r,destroy(){i=!0,p.clear(),typeof window<"u"&&window.removeEventListener("storage",g),c&&v(c);for(let e of[...w])e()}}})(e,we(),!1===n.persistState),Bd=Ld(),Nd=Bd?Pd(Bd):null,Rd={...Nd?{visitorStore:Nd}:{},historyBootstrapReady:!0!==n.features?.history?.enabled||Ec()?D:Promise.all([D,z]).then(()=>{}),getStoredMessageCursor:()=>Td("historyMessageCursor"),setStoredMessageCursor:e=>{null!==e?U(t=>({...t,historyMessageCursor:e})):Id("historyMessageCursor")},getPendingDisplayProjections:()=>{let e=$.pendingDisplayProjections;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.conversationId&&Array.isArray(t.messageIds)?{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>"string"==typeof e)}:null},setPendingDisplayProjections:e=>{e?U(t=>({...t,pendingDisplayProjections:e})):Id("pendingDisplayProjections")},getStoredResumableHandle:Ed,setStoredResumableHandle:e=>{e?U(t=>({...t,durableResume:e})):Id("durableResume")},shouldResumeDurableConversation:()=>H&&null!==Ed(),...Md?{}:{getStoredConversationRevision:()=>Td("conversationRevision"),setStoredConversationRevision:e=>{null!==e?U(t=>({...t,conversationRevision:e})):Id("conversationRevision")}}};if(H){let t=n.onExecutionState,r=e.ownerDocument.defaultView,o=!1,a=()=>o=!0,s=()=>o=!1;r?.addEventListener("pagehide",a),r?.addEventListener("pageshow",s),Zo.push(()=>{r?.removeEventListener("pagehide",a),r?.removeEventListener("pageshow",s)}),n={...n,reconnectStream:n.reconnectStream??(e=>ha.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!o)&&Rd.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Hd=null,$d=(e,t)=>{if(Object.is(e,t))return!0;if(null===e||null===t||"object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)&&e.every((e,r)=>$d(e,t[r]));let r=e,n=t,o=Object.keys(r),a=Object.keys(n);return o.length===a.length&&o.every(e=>Object.prototype.hasOwnProperty.call(n,e)&&$d(r[e],n[e]))},Wd=e=>{let{content:t,rawContent:r,llmContent:n,...o}=e;return o},Dd=e=>!("assistant"!==e.role||!0!==e.streaming||e.variant||e.toolCall||e.tools||e.approval||e.reasoning||e.contentParts||e.stopReason||Wc(e)),Od=null,Fd=null,zd=null,qd=null,jd=null,_d=e=>{let t,r;Od=e,Fd=null;for(let n=e.length-1;n>=0;n-=1){let o=e[n];if(!t&&"user"===o.role&&(t=o),!r&&"assistant"===o.role&&(r=o),!Fd&&Dd(o)&&(Fd={index:n,id:o.id}),t&&r&&Fd)break}pl(ct,e,ue),yd()?.updateInlineArtifactBlocks(ct,Kn.artifacts,{suppressTransition:za}),null==Hd&&(Hd=setInterval(()=>{let e=ct.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Hd),void(Hd=null);let t=Date.now();e.forEach(e=>{let r=Number(e.getAttribute("data-tool-elapsed"));r&&(e.textContent=e.closest(".persona-activity-row")?Be(t-r):Pr(t-r))})},100)),cd(e),Oa(e),Wi(!za),(e=>{let t=new Map;e.forEach(e=>{let r=vs.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(N.emit("assistant:message",e),!is&&("anchor-top"!==Vt()||Gt())&&Ei()&&(ns+=1,ki(),Ni(),lr(1===ns?"1 new message below.":`${ns} new messages below.`))),"assistant"===e.role&&r?.streaming&&!1===e.streaming&&N.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&N.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):N.emit("approval:requested",{approval:e.approval,message:e}))}),vs.clear(),t.forEach((e,t)=>{vs.set(t,e)})})(e),0===e.length&&(Ji(),ds=!0,cs=!1,ps=null,us=!1),!ss||is?(ss=!0,ls=t?.id??null,ms=r?.id??null):t&&t.id!==ls?(ls=t.id,(e=>{let t=Vt();"follow"===t?($i(),Wi(!0)):"anchor-top"===t&&(ds=!1,cs=!0,us=!1,ps=e,el(e))})(t.id)):r&&r.id!==ms&&(()=>{if("anchor-top"===Vt()){if(cs)return void(ds=!1);ds=!0,Ji(),$i(),Wi(!0)}})(),r&&(ms=r.id),(e=>{if("anchor-top"!==Vt()||!cs||us||_i())return;let t=null===ls;for(let r of e)if(t){if(Os(r)){if(r.id===ps||!nl(r.id))return;return ps=r.id,void el(r.id)}}else r.id===ls&&(t=!0)})(e);let n=Bs.lastUserMessageId;t&&t.id!==n&&(Bs.lastUserMessageId=t.id,N.emit("user:message",t)),Bs.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!H)return ei(e);jd=e,queueMicrotask(()=>{jd===e&&(jd=null,ei(e))})})(e),Il()},Vd=()=>{null!==qd&&(cancelAnimationFrame(qd),qd=null);let e=zd;zd=null,e&&_d(e)},Ud=()=>{null!==qd&&cancelAnimationFrame(qd),qd=null,zd=null};ha=new uo(n,{onMessagesChanged(e){(e=>{let t=zd??Od;za&&t&&Fd&&((e,t,r)=>{if(e.length!==t.length)return!1;let n=e[r.index],o=t[r.index];return!(!n||!o||n.id!==r.id||o.id!==r.id)&&(!Object.is(n.content,o.content)||!Object.is(n.rawContent,o.rawContent)||!Object.is(n.llmContent,o.llmContent))&&Dd(n)&&Dd(o)&&$d(Wd(n),Wd(o))})(t,e,Fd)?(zd=e,null===qd&&(qd=requestAnimationFrame(()=>{qd=null;let e=zd;zd=null,e&&_d(e)}))):0===e.length?(Ud(),_d(e)):(Vd(),_d(e))})(e)},onStatusChanged(e){let t=n.statusIndicator??{};var r;rt(bt,"idle"===(r=e)?t.idleText??cn.idle:"connecting"===r?t.connectingText??cn.connecting:"connected"===r?t.connectedText??cn.connected:"error"===r?t.errorText??cn.error:"paused"===r?t.pausedText??cn.paused:"resuming"===r?t.resumingText??cn.resuming:cn[r],t,e),Ze()},onStreamingChanged(e){e||(0===ha?.getMessages().length?Ud():Vd()),za=e,_l(e),Ze(),ha&&pl(ct,ha.getMessages(),ue),e||(Wi(!0),(()=>{if(!os||os.spacerHeight<=0)return;let e=Ki(os.spacerHeight),t=Math.max(0,Math.round(dt.scrollTop)+dt.clientHeight-e+gs);t<os.spacerHeight&&(Ui(t),Ni())})(),Wa=!0,ha&&Da(ha.getMessages(),xr(n))),Ni(),lr(e?"Responding…":"Response complete."),Il()},onVoiceStatusChanged(e){if(N.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"===e||$e(n.voiceRecognition?.provider))switch(e){case"listening":if(!Ts){let e=ha.getVoiceDisclosure();e&&(Ts=!0,se()?(Ps=mt.placeholder,mt.placeholder=e,lr(e)):Qc(e,1e4))}Bp(),Ep();break;case"processing":Bp(),Lp();break;case"speaking":Bp(),Pp();break;default:"idle"===e&&ha.isBargeInActive()?(Bp(),Ep(),Dt?.setAttribute("aria-label","End voice session")):(Bs.active=!1,Ts=!1,null!==Ps&&(mt.placeholder=Ps,Ps=null),Bp(),js("system"),Vs())}},onArtifactsState(e){Kn=e,0===e.artifacts.length&&(Xn=!1),yd()?.updateInlineArtifactBlocks(ct,e.artifacts,{suppressTransition:za}),_o(),ei()},onHistoryStateChanged(e){Xe(e)},onHistoryNotice(e){Qe(e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?N.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?N.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):N.emit("stream:resumed",{executionId:t,after:r})}},Rd),ro.current=ha,Zo.push(()=>ha.cancel()),Zo.push(()=>{ha.destroy(),Nd?.destroy(),Nd=null});let Kd=null;if(ha.onReadAloudChange((e,t)=>{Bn=e,Nn=t,Hn();let r=e??Kd;e&&(Kd=e);let n=r?ha.getMessages().find(e=>e.id===r)??null:null;N.emit("message:read-aloud",{messageId:r,message:n,state:t,timestamp:Date.now()}),"idle"===t&&(Kd=null)}),m=!0,ss=!0,!0===n.voiceRecognition?.enabled&&$e(n.voiceRecognition.provider))try{ha.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let Jd=null,Gd=null,Qd=!1,Zd=ha.getHistoryState(),ec=()=>!0===n.features?.history?.enabled,tc=e=>{e&&(ar.textContent="",ar.textContent=e)},rc=()=>{u.forEach(e=>e()),u=[];let t=Jd,r=t?.railCollapseShortcut();t&&r&&u.push(p.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===n.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>Ue&&"rail"===Ke&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of n.layout?.header?.trailingActions??[])t.shortcut&&u.push(p.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():n.layout?.header?.onAction?.(t.id)}}));for(let e of c)for(let t of e.shortcuts??[])u.push(p.register({...t,id:`${e.id}:${t.id}`}))};rc();let sc=null,ic=!1,lc=()=>{if(!Et)return;let e="conversation"===n.layout?.header?.titleSource,t=e&&sc?.trim()||null;Et.textContent=t??n.launcher?.title??"Chat Assistant";let r=Et.closest(".persona-combo-btn");if(!r)return;let o=!e||null!==ha.getActiveConversationId();r.setAttribute("data-persona-menu-locked",o?"false":"true"),r.setAttribute("aria-haspopup",o?"true":"false"),o||r.setAttribute("aria-expanded","false"),r.style.cursor=o?"pointer":"default";let a=r.querySelector("svg");a&&(a.style.display=o?"":"none")};lc(),lt.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=ha.getActiveConversationId();r&&("delete"===t?fc(e=>e.requestDeleteConversation(r)):"star"===t&&ha.canUpdateConversations()&&fc(e=>e.updateHistoryConversation(r,{starred:!ic})).catch(()=>{}))}),Xe=e=>{Zd=e,Jd?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),_l(e.sendBlocked||za),Jd?.syncEarlierMessagesPill()},Qe=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(qa.clear(),Ji(),$i()),tc(e.message),Jd?.historySurface?.view.refresh()};let pc={get actionManager(){return G},get activeConversationTitle(){return sc},announceHistory:tc,get applyRailChrome(){return Ge},set applyRailChrome(e){Ge=e},get artifactSplitRoot(){return ho},get body(){return dt},get config(){return n},get container(){return lt},get conversationOpenPendingEl(){return Ul},set conversationOpenPendingEl(e){Ul=e},get conversationOpenTakeover(){return Gl},set conversationOpenTakeover(e){Gl=e},currentKeyPrefix:we,destroyCallbacks:Zo,eventBus:N,get footer(){return Bt},get header(){return Pt},get historyChromeSync(){return Ze},set historyChromeSync(e){Ze=e},historyFeatureEnabled:ec,get historyInternals(){return Rd},set historyInternals(e){Rd=e},get historyPresentation(){return Ke},set historyPresentation(e){Ke=e},get historySessionState(){return Zd},get historyVisible(){return Ue},set historyVisible(e){Ue=e},get isStreaming(){return za},jumpToBottomInstant:qi,get lastAppliedMessages(){return Od},set lastAppliedMessages(e){Od=e},get launcherEnabled(){return Y},get launcherSurfaceInstance(){return Kp},maybeFocusInput:Vl,messageCache:qa,get messagesWrapper(){return ct},mount:e,get open(){return le},panel:at,panelElements:it,get persistentMetadata(){return $},set persistentMetadata(e){$=e},plugins:c,get reapplyHistoryHostChrome(){return Je},set reapplyHistoryHostChrome(e){Je=e},repinAnchoredMessage:rl,resetAnchorState:Ji,restoreScrollPosition:Vi,resumeAutoScroll:$i,runStorageMutation:Zs,get session(){return ha},setActiveConversationSummary:e=>{ic=!0===e?.starred,(e=>{e!==sc&&(sc=e,lc())})(e&&e.title.trim()||null),lc()},storageAdapter:R,get suppressScrollSend(){return is},set suppressScrollSend(e){is=e},syncScrollToBottomButton:Ni,updateWelcome:cd,getHistoryProviderFactory:Lc,historyErrors:{HistoryClientError:hn,HistoryProviderError:wn},isDockedMountMode:vi,renderLucideIcon:xe,loadHistoryView:Cc,createHeaderIconButton:Bi,attachTooltip:Bo},hc=e=>(!Jd&&!Qd&&(Jd=e.createHistoryShell(pc),Jd.railCollapseShortcut()&&rc()),Jd),gc=()=>{if(Jd)return Promise.resolve(Jd);let e=Ec();return e?Promise.resolve(hc(e)):(Gd??=Tc().then(hc,e=>{throw Gd=null,e}),Gd)},fc=e=>{let t=Ec(),r=Jd??(t?hc(t):null);return r?e(r):gc().then(t=>{if(!t)throw new Error("[AgentWidget] The widget was destroyed");return e(t)})},vc=()=>{Jd?.syncHistoryPresentation()};Zo.push(()=>{Qd=!0}),ec()&&gc().catch(()=>{}).finally(O),n.clientToken&&(!0===n.features?.history?.enabled||"mount"===n.sessionInit)&&ha.initClientSession().then(()=>{let e=Jd;if(e?.historyAvailable())return ha.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Jd?.syncEarlierMessagesPill()}).catch(e=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let wc=()=>ha.warmClientSession(),xc=e=>{let t=n.sessionInit??"input",r=an?.input??mt,o=e.target;r&&("input"===e.type?("input"===t||"focus"===t)&&o===r&&e.inputType&&r.value.trim():"focus"===t&&("keyup"===e.type?o===r&&"Tab"===e.key:(an?.form??yt)?.contains(o)))&&wc()},Sc=["input","pointerdown","keyup"];Sc.forEach(t=>e.addEventListener(t,xc));let kc,Ac,Mc=()=>{let e=Ac;Ac=void 0;try{"function"==typeof e&&e()}catch{}},Ic=()=>{let t=n.clientToken&&"function"==typeof n.sessionInit?n.sessionInit:void 0;if(t!==kc){Mc(),kc=t;try{Ac=t?.({warm:wc,mount:e})}catch{}}};Ic(),Zo.push(()=>{Sc.forEach(t=>e.removeEventListener(t,xc)),Mc()}),(ye||n.onSSEEvent)&&ha.setSSEEventCallback((e,t)=>{n.onSSEEvent?.(e,t),ze(e,t)});let Pc=()=>{let e=n.resume??(H?Rd.getStoredResumableHandle?.():null);e&&"function"==typeof n.reconnectStream&&ha.resumeFromHandle(e)};W?W.then(e=>{if(e){if(e.metadata&&($=Uc(e.metadata),G.syncFromMetadata()),e.messages?.length){is=!0;try{ha.hydrateMessages(e.messages)}finally{is=!1}dl()}e.artifacts?.length&&ha.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),pi(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{Ql=!0,P(),Pc()}):(pi(B),Pc());let Bc=()=>{let e=mt.getInlineMessageFields?.();return e&&e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},Nc=!1,Hc=null,$c=()=>{mt.value="",mt.style.height="auto",Mr(),ip()},Oc="data-persona-composer-notice",Xc=null;function Qc(e,t=4e3){lr(e),!se()&&bt&&(bt.hasAttribute(jc)||(bt.setAttribute(Oc,""),bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.textContent=e,Re(bt,n.statusIndicator??{},"idle"),Xc&&clearTimeout(Xc),Xc=setTimeout(()=>{if(Xc=null,bt?.hasAttribute(Oc)&&(bt.removeAttribute(Oc),bt.removeAttribute("role"),bt.removeAttribute("aria-live"),m)){let e=ha.getStatus();rt(bt,tt(e),n.statusIndicator??{},e)}},t)))}let Zc=(e={})=>{let t=(e.overrideText??mt?.value??"").trim();return e.resolveInlineCommand&&t?(kr?.takeInlineCommand(t)??Promise.resolve(null)).then(r=>ep(e,t,r)):ep(e,t,null)},ep=(e,t,r)=>{if("action"===r?.kind)return $c(),kr?.clear(),void Ir();let o="server"===r?.kind?r.mentions:null,a="prompt"===r?.kind?r.sendText:t,s=e.pending?.contentParts;if(!function(e){return!(!0===e.inputDisabled||!0===e.sendDisabled||e.hasAttachments&&!e.attachmentsReady)&&(!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions)}({text:a,hasAttachments:(Sr?.hasAttachments()??!1)||(s?.length??0)>0,attachmentsReady:Sr?.isReady()??!0,hasMentions:kr?.hasMentions()??!1,hasServerMentions:!!o,inputDisabled:Nl(),sendDisabled:Hl()}))return;let i=ha.isStreaming()?jr():"block";if("defer-one"===i&&!e.pending)return Ar.getState().pendingSubmission?void Qc("One message is already queued. Edit or remove it first."):void function(e){let t=Ar.getState(),r=Sr?.hasAttachments()??!1,n=r?[...Sr.getContentParts()]:[];r&&e.sendText&&n.push(Zr(e.sendText)),Vr(ka({text:e.sendText,contentParts:n.length?n:void 0,mentionRefs:[...kr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:Bc(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),!1!==e.intent.consumeDraft&&$c(),r&&Sr.clearAttachments(),kr?.clear(),Ir(),t.quote&&zr(void 0),ui(),Sn.release(),An(),lr("Message queued. It sends when the response finishes.")}({intent:e,sendText:a,serverMentions:o});let l={text:a,mentionRefs:[...kr?.getMentionRefs()??[],...o?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:Bc(),options:{...Ar.getState().selectedModelId&&{selectedModelId:Ar.getState().selectedModelId},...Ar.getState().activeModeIds.length>0&&{activeModeIds:[...Ar.getState().activeModeIds]},...Ar.getState().quote&&{quote:{...Ar.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(l.options={...e.pending.options},l.contentSegments=e.pending.contentSegments,l.mentionRefs=[...e.pending.mentionRefs],l.viaVoice=e.pending.viaVoice);let d=()=>{if(s?.length)return[...s];if(!Sr?.hasAttachments())return;let e=[...Sr.getContentParts()];return l.text&&e.push(Zr(l.text)),e};l.contentParts=d();let c=()=>{Ja(),!se()||le||!(n.launcher?.composerBar?.expandOnSubmit??1)||Pl(!0,"auto");let t=kr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,n]=await Promise.allSettled([e.finalize(),t.finalize()]),o=[];return"fulfilled"===r.status?o.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===n.status?o.push(n.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",n.reason),(e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Yc(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}))(o)}}:e:t)(t,o),a=d();!1!==e.consumeDraft&&$c();let s={selectedModelId:l.options.selectedModelId,activeModeIds:l.options.activeModeIds},c="interrupt"===i;c&&ha.cancel(),ha.sendMessage(l.text,{contentParts:a,mentions:r??void 0,contentSegments:l.contentSegments,viaVoice:l.viaVoice,composerOptions:s,...l.options.quote&&{quote:l.options.quote},...c&&{interrupt:!0}}),Sr?.hasAttachments()&&Sr.clearAttachments(),t&&kr?.clear(),Ir();let p=Ar.getState().activeModeIds,u=function(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&"once"!==(t.persistence??"sticky")).map(e=>e.id):[]}(p,n.composer?.modes);u.length!==p.length&&Rr(u),Ar.getState().quote&&zr(void 0),ui(),Sn.release(),An()},p=n.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;Hc=u;let h=e=>{Hc=null,"error"!==e.status?"proceed"===e.status&&c():(e=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",e)})(e.error)},m=function(e,t,r){let n;try{n=e(ka(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(n)?Promise.resolve(n).then(e=>r.aborted?{status:"aborted"}:Aa(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Aa(t,n)}(p,l,u.signal);if(m instanceof Promise)return Ar.setPreparing(!0),m.then(h).finally(()=>Ar.setPreparing(!1));h(m)};$n={regenerate:function(e){if(ha.isStreaming())return;let t=qn(ha.getMessages(),e);t&&(Ja(),ha.resubmitFrom(t,{reason:"retry"})&&rl())},edit:function(e){if(!0!==n.messageActions?.showEdit)return;let t=ha.getMessages().find(t=>t.id===e);!t||!jn(t)||Ua!==e&&(Ja(),Ua=e,Ka=function(e){let t=oe("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=oe("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});r.value=e.initialText;let n=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",n);let o=ne("div","persona-message-edit-actions"),a=(e,t,r,n)=>{let o=oe("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return o.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",s)),r.addEventListener("keydown",t=>{if("Escape"===t.key)return t.preventDefault(),t.stopPropagation(),void e.onCancel();"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,o),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=Ka;Ua=null,Ka=null,r?.destroy(),qa.delete(e),ha.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?rl():pl(ct,ha.getMessages(),ue)}(e,t),onCancel:()=>Ja()}),qa.delete(e),pl(ct,ha.getMessages(),ue),Ka.focus())},quote:e=>{let t=ha.getMessages().find(t=>t.id===e)?.content?.trim();t&&(zr({text:t,messageId:e}),mt?.focus())}};let tp=async e=>{if(!Nc){Nc=!0;try{await Zc({resolveInlineCommand:!0,...e})}finally{Nc=!1}}};function rp(e){Hl()||($c(),np(e,{consumeDraft:!1}))}let np=(e,t)=>{if(Nc)return;Nc=!0;let r=()=>{Nc=!1};try{let n=Zc({...t,overrideText:e});n instanceof Promise?n.finally(r):r()}catch(e){throw r(),e}},op=e=>{if(e.preventDefault(),ha.isStreaming())return ha.cancel(),Ie?.reset(),void Le?.update();Nc||tp()},ap={...Ds},sp=!1,ip=()=>{ap={...Ds}},lp=e=>{if("Escape"===e.key&&!e.isComposing&&e.composedPath().includes(lt)){if(Hc)return Hc.abort(),Hc=null,e.preventDefault(),void e.stopImmediatePropagation();ha.isStreaming()&&(ha.cancel(),Ie?.reset(),Le?.update(),ip(),e.preventDefault(),e.stopImmediatePropagation())}},dp=null,cp=!1,pp=null,up=null,hp=()=>"review"===n.voiceRecognition?.completionBehavior;function mp(e){Dt?.setAttribute("data-state",e),"recording"===e?function(){if(null!==yp)return;if("function"!=typeof requestAnimationFrame)return void xp(m?ha.getVoiceLevel()??fp:fp);let e=()=>{yp=requestAnimationFrame(e);let t=m?ha.getVoiceLevel():null;null!==t?(vp+=.3*(t-vp),xp(vp)):xp(fp)};yp=requestAnimationFrame(e)}():Sp()}let gp="--persona-voice-level",fp=.5,yp=null,bp=-1,vp=0,wp=()=>{let e=[],t=Ot??Dt?.parentElement??null;return t&&e.push(t),Bt&&e.push(Bt),e},xp=e=>{let t=Math.round(100*Math.max(0,Math.min(1,e)))/100;if(t!==bp){bp=t;for(let e of wp())e.style.setProperty(gp,String(t))}},Cp=()=>{bp=-1,vp=0;for(let e of wp())e.style.removeProperty(gp)};function Sp(){null!==yp&&(cancelAnimationFrame(yp),yp=null),Cp()}let kp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ap=(e="user")=>{if(cp||ha.isStreaming())return;let t=kp();if(!t)return;dp=new t;let r=n.voiceRecognition??{},o=r.pauseDuration??2e3;dp.continuous=r.provider?.browser?.continuous??!0,dp.interimResults=!0,dp.lang=r.provider?.browser?.language??"en-US";let a=mt.value;dp.onresult=e=>{let t="",r="";for(let n=0;n<e.results.length;n++){let o=e.results[n],a=o[0].transcript;o.isFinal?t+=a+" ":r=a}let n=a+t+r;mt.value=n,Mr(),pp&&clearTimeout(pp),(t||r)&&(pp=window.setTimeout(()=>{if(mt.value.trim()&&dp&&cp){if(Mp(),hp())return;tp({viaVoice:!0})}},o))},dp.onerror=e=>{"no-speech"!==e.error&&Mp()},dp.onend=()=>{if(cp){let e=mt.value.trim();!hp()&&e&&e!==a.trim()&&tp({viaVoice:!0}),Mp()}};try{if(dp.start(),cp=!0,Bs.active=!0,"system"!==e&&(Bs.manuallyDeactivated=!1),js(e),Vs(),An(),Dt){let e=n.voiceRecognition??{};up={backgroundColor:Dt.style.backgroundColor,color:Dt.style.color,borderColor:Dt.style.borderColor,iconName:e.iconName??"mic",iconSize:parseFloat(e.iconSize??"")||qo};let t=e.recordingBackgroundColor,r=e.recordingIconColor,o=e.recordingBorderColor;if(Dt.classList.add("persona-voice-recording"),mp("recording"),Dt.style.backgroundColor=t??"var(--persona-voice-recording-bg, #ef4444)",Dt.style.color=r??"var(--persona-voice-recording-indicator, #ffffff)",r){let e=Dt.querySelector("svg");e&&e.setAttribute("stroke",r)}o&&(Dt.style.borderColor=o),Dt.setAttribute("aria-label","Stop voice recognition")}}catch{Mp("system")}},Mp=(e="user")=>{if(cp){if(cp=!1,pp&&(clearTimeout(pp),pp=null),dp){try{dp.stop()}catch{}dp=null}if(Bs.active=!1,js(e),Vs(),An(),Dt){if(Dt.classList.remove("persona-voice-recording"),mp("idle"),up){Dt.style.backgroundColor=up.backgroundColor,Dt.style.color=up.color,Dt.style.borderColor=up.borderColor;let e=Dt.querySelector("svg");e&&e.setAttribute("stroke",up.color||"currentColor"),up=null}Dt.setAttribute("aria-label","Start voice recognition")}}},Ip=null,Tp=e=>{let t=t=>{Ip??=t.createMicStateStyles({mic:()=>Dt,config:()=>n,session:()=>ha,get original(){return up},set original(e){up=e},setMicState:mp,renderIcon:xe,iconFallbackPx:qo}),e(Ip)},r=Zn();r?t(r):Qn().then(t,()=>{})},Ep=()=>Tp(e=>e.recording()),Lp=()=>Tp(e=>e.processing()),Pp=()=>Tp(e=>e.speaking()),Bp=()=>Tp(e=>e.reset()),Np=()=>{if(!Nl()){if($e(n.voiceRecognition?.provider)){let e=ha.getVoiceStatus(),t=ha.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;return"cancel"!==t||"processing"!==e&&"speaking"!==e?ha.isBargeInActive()?(ha.stopVoicePlayback(),void ha.deactivateBargeIn().then(()=>{Bs.active=!1,Bs.manuallyDeactivated=!0,Vs(),js("user"),Bp()})):void ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),Bs.manuallyDeactivated=!ha.isVoiceActive(),Vs(),js("user"),ha.isVoiceActive()?Ep():Bp()}):void ha.stopVoicePlayback()}if(cp){let e=mt.value.trim();Bs.manuallyDeactivated=!0,Vs(),Mp("user"),e&&!hp()&&tp()}else Bs.manuallyDeactivated=!1,Vs(),Ap("user")}};Kr=Np;let Rp=()=>ha.prewarmVoice(),Hp=()=>{let e=n.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!n.clientToken&&"hover"))},$p=e=>{"hover"===Hp()&&Dt?.contains(e.target)&&Rp()},Wp=["pointerover","pointerdown","focusin"];Wp.forEach(t=>e.addEventListener(t,$p));let Dp,Op,Fp=null,zp=()=>{let e=Op;Op=void 0;try{"function"==typeof e&&e()}catch{}},qp=()=>{let t=Hp(),r="function"==typeof t&&Dt?t:void 0,n=r?Dt:null;if((r!==Dp||n!==Fp)&&(zp(),Dp=r,Fp=n,r&&n))try{Op=r({warm:Rp,micButton:n,mount:e})}catch{}};qp(),Zo.push(()=>{Wp.forEach(t=>e.removeEventListener(t,$p)),zp()}),Dt&&Zo.push(()=>{$e(n.voiceRecognition?.provider)?(ha.isVoiceActive()&&ha.toggleVoice(),Bp()):Mp("system")});let jp=N.on("assistant:complete",()=>{Ar.getState().pendingSubmission&&setTimeout(()=>{ha.isStreaming()||function(){let e=Ar.getState().pendingSubmission;e&&(Vr(void 0),np(e.text,{consumeDraft:!1,pending:e}))}()},0)});Zo.push(jp);let _p=N.on("assistant:complete",()=>{$s&&(Bs.active||Bs.manuallyDeactivated||"assistant"===$s&&!Bs.lastUserMessageWasVoice||setTimeout(()=>{!Bs.active&&!Bs.manuallyDeactivated&&($e(n.voiceRecognition?.provider)?ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),js("auto"),ha.isVoiceActive()&&Ep()}):Ap("auto"))},600))});Zo.push(_p);let Vp=N.on("action:resubmit",()=>{setTimeout(()=>{ha&&!ha.isStreaming()&&ha.continueConversation()},100)});Zo.push(Vp);let Up=()=>{Pl(!le,"user")},Kp=null,Jp=null;if(Y&&!se()){let{instance:e,element:t}=Wl({config:n,plugins:c,onToggle:Up});Kp=e,e||(Jp=t)}Kp?e.appendChild(Kp.element):Jp&&e.appendChild(Jp),Ll(),Oa(),Cd(),xd(),_l(ha.isStreaming()),Vi()||("follow"===Vt()?Wi(!0):qi()),(()=>{if(!1===n.voiceRecognition?.enabled)return;let e=Uc($.voiceState),t=!!e.active,r=Number(e.timestamp??0);Bs.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4&&setTimeout(()=>{Bs.active||(Bs.manuallyDeactivated=!1,$e(n.voiceRecognition?.provider)?ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),js("restore"),ha.isVoiceActive()&&Ep()}):Ap("restore"))},1e3)})(),Q&&(!Y||se()?setTimeout(()=>Vl(),0):le&&setTimeout(()=>Vl(),200));let Gp=null,Yp=()=>{Gp&&(Gp.disconnect(),Gp.observe(Bt),Gp.observe(lt),Gp.observe(vt))},Xp=dr(),Qp=()=>{if(se())return fr(),void Ll();let t=vi(n),r=n.launcher?.sidebarMode??!1,o=e.ownerDocument.defaultView??window,a=n.launcher?.mobileFullscreen??!0,s=n.launcher?.mobileBreakpoint??640,i=o.innerWidth<=s,l=a&&i&&Y;try{if(l)return _n(),void(Vn=jo());let e=!1;ae&&(ae=!1,_n(),e=!0);let o=jo();if(!e&&o!==Vn&&(_n(),e=!0),Vn=o,e&&xo(),!Y&&!t)return at.style.height="",void(at.style.width="");if(!r&&!t){let e=Ml(n);at.style.width=e.width,at.style.maxWidth=e.maxWidth}Lo(),Qo()}finally{fr(),wr();let t=dr();if(t!==Xp&&(Xp=t,cd(),Oa()),Ll(),le&&Y){let t=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),r=n.launcher?.sidebarMode??!1,o=n.launcher?.mobileFullscreen??!0,a=vi(n)&&o&&t,s=r||o&&t&&Y||a;if(s&&!ta){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!ea&&(ea=gi(r,n.launcher?.zIndex??pn)),ta=bi(e.ownerDocument)}else s||(ea?.(),ea=null,ta?.(),ta=null)}}};Qp();let Zp=e.ownerDocument.defaultView??window;if(Zp.addEventListener("resize",Qp),Zo.push(()=>Zp.removeEventListener("resize",Qp)),typeof ResizeObserver<"u"){Gp=new ResizeObserver(()=>{wr()}),Yp(),Zo.push(()=>{Gp?.disconnect(),Gp=null});let e=new ResizeObserver(()=>{vc()});e.observe(lt),Zo.push(()=>e.disconnect())}Zp.addEventListener("resize",vc),Zo.push(()=>Zp.removeEventListener("resize",vc)),Qa=dt.scrollTop;let eu=Fs(dt),tu=()=>{Yo();let e=dt.scrollTop,t=Fs(dt),r=t<eu;if(eu=t,!Ut())return Qa=e,void Ni();let{action:n,nextLastScrollTop:o}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-n;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&o&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!o?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Xa.isFollowing(),currentScrollTop:e,lastScrollTop:Qa,nearBottom:zs(dt,gs),userScrollThreshold:4,isAutoScrolling:ts||rs||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Qa=o,"resume"!==n?"pause"===n&&Ri():_i()||$i()};if(dt.addEventListener("scroll",tu,{passive:!0}),Zo.push(()=>dt.removeEventListener("scroll",tu)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(Ut()){if(!Xa.isFollowing()||zs(dt,1))return;Wi(!za)}else{if(os&&os.initialSpacerHeight>0){let e=dt.scrollHeight-os.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:os.initialSpacerHeight,contentHeightAtAnchor:os.contentHeightAtAnchor,currentContentHeight:e});t!==os.spacerHeight&&Ui(t)}Ni()}})(),gt(ct)});e.observe(ct),e.observe(dt),Zo.push(()=>e.disconnect())}let ru=()=>{Ut()&&Xa.isFollowing()&&_i()&&Ri()},nu=dt.ownerDocument;nu.addEventListener("selectionchange",ru),Zo.push(()=>{nu.removeEventListener("selectionchange",ru)});let ou=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),au=e=>{ou.has(e.key)&&(hs(),Jt()&&Ut()&&Xa.isFollowing()&&Ri())},su=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(hs(),Jt()&&Ut()&&Xa.isFollowing()&&Ri())};dt.addEventListener("keydown",au),dt.addEventListener("focusin",su),Zo.push(()=>{dt.removeEventListener("keydown",au),dt.removeEventListener("focusin",su)});let iu=e=>{if(0!==e.deltaY&&hs(),!Ut())return;let t=function(e){let{following:t,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return t&&r<0?"pause":!t&&o&&r>0&&n?"resume":"none"}({following:Xa.isFollowing(),deltaY:e.deltaY,nearBottom:zs(dt,gs),resumeWhenNearBottom:!0});"pause"===t?Ri():"resume"===t&&!_i()&&$i()};dt.addEventListener("wheel",iu,{passive:!0}),dt.addEventListener("touchmove",hs,{passive:!0}),dt.addEventListener("pointerdown",hs,{passive:!0}),Zo.push(()=>{dt.removeEventListener("touchmove",hs),dt.removeEventListener("pointerdown",hs)}),Zo.push(()=>dt.removeEventListener("wheel",iu)),Zt.addEventListener("click",()=>{Ji(),dt.scrollTop=dt.scrollHeight,Qa=dt.scrollTop,$i(),Wi(!0),Ni()}),Zo.push(()=>Zt.remove()),Zo.push(()=>{Ci(),Ji()});let lu=()=>{It&&(ma&&(It.removeEventListener("click",ma),ma=null),ie()?(It.style.display="",ma=()=>{Pl(!1,"user")},It.addEventListener("click",ma)):It.style.display="none")};lu(),(()=>{let{clearChatButton:e}=it;e&&e.addEventListener("click",()=>{let e=Jd;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",e)});ha.clearMessages(),n.layout?.topFade&&(dt.scrollTop=0),dt.removeAttribute("data-persona-top-fade"),qa.clear(),$i(),hr(it.composerOverlay);try{localStorage.removeItem(qc),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==qc)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let t=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(t),R?.clear&&Zs(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),$={},G.syncFromMetadata(),Sr?.clearAttachments(),ui(),Vr(void 0),zr(void 0),Ja(),Ae?.clear(),Ie?.reset(),Le?.update()})})();let du=[["keydown",e=>{if(mt&&!Nl()&&(e.isComposing||!kr?.handleKeydown(e))){if(!(!1===n.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===mt.selectionStart&&0===mt.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:n,atStart:o,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!o)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:n}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let e=a.index+1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}({direction:"ArrowUp"===e.key?"up":"down",history:ha.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:mt.value,atStart:t,state:ap});if(ap=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!mt)return;sp=!0,mt.value=e,mt.dispatchEvent(new Event("input",{bubbles:!0})),sp=!1;let t=mt.value.length;mt.setSelectionRange(t,t)})(r.value))}if(function(e,t){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,n=t.submitKey??"enter";return"none"!==n&&("mod-enter"===n?r:r||!$o(t))}(e,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Ho(mt)})){if(ha.isStreaming()){if(e.preventDefault(),"block"===jr()||Nc||Hl())return;return ip(),void tp()}if(Nc)return void e.preventDefault();if(Hl())return void e.preventDefault();ip(),e.preventDefault(),ft.click()}}}],["input",e=>{sp||(e.isComposing||kr?.handleInput(e.inputType??void 0),ip())}],["input",Mr],["input",Ir],["keyup",Ir],["paste",async e=>{if(!0!==n.attachments?.enabled||!Sr||Nl())return;let t=function(e){if(!e)return[];let t=[],r=Array.from(e.items??[]);for(let e of r){if("file"!==e.kind||!e.type.startsWith("image/"))continue;let r=e.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let n=_c[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${n}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let r of Array.from(e.files??[]))r.type.startsWith("image/")&&t.push(r);return t}(e.clipboardData);0!==t.length&&(e.preventDefault(),await Sr.handleFiles(t))}],["focus",()=>kr?.prefetch()]],cu=e=>{if(e)for(let[t,r]of du)an?.addListener(e,t,r)},pu=()=>{an&&(an.addListener(an.form,"submit",op),an.addListener(an.footer,"click",Ir),cu(mt),Dt&&an.addListener(Dt,"click",Np),qp())};pu();let uu=()=>{kr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of du)an?.removeListener(e,t,r)})(t),mt=e,an&&(an.input=e),cu(e),sn(),ql(),Mr()})};uu();let hu=!1;function mu(){if(!hu){hu=!0;try{let e=mt?.value??"",t=Bt.ownerDocument??document,r=!!mt&&t.activeElement===mt;Sp(),an?.destroy(),an=null,kr?.destroy(),kr=null;let o=null,a=()=>(o=se()?Qi({config:n}):Xi({config:n}),o.footer),s=rn(a)??a();nt.replaceComposer(s),Bt=nt.composer.footer;let i=null!==o&&s===o.footer;tn=!i,Wt=i?o.setSendButtonMode:()=>{},en(Bt),ln(Bt),un(),mn(),gn(),uu(),vn(),xn(),Cn(),pu();let l=pa.indexOf(la);if(la.destroy(),la=Mi(ht),l>=0&&(pa[l]=la),mt&&(mt.value=e),Mr(),Ir(),Cd(),Oa(),_l(ha.isStreaming()),"transient"===n.statusIndicator?.mode&&!se()){let e=ha.getStatus();rt(bt,tt(e),n.statusIndicator,e)}Bs.active&&mp("recording"),_n(),Yp(),fr(),An(),zl(),r&&mt?.focus()}finally{hu=!1}}}let gu=e.ownerDocument??document;gu.addEventListener("keydown",lp,!0);let fu=()=>{li()},yu=()=>{"hidden"===gu.visibilityState&&li()};typeof window<"u"&&(window.addEventListener("pagehide",fu),gu.addEventListener("visibilitychange",yu),Zo.push(()=>{window.removeEventListener("pagehide",fu),gu.removeEventListener("visibilitychange",yu)}));let bu="persona-attachment-drop-active",vu=0,wu=()=>{vu=0,lt.classList.remove(bu)},xu=()=>!0===n.attachments?.enabled&&null!==Sr&&!Nl(),Cu=e=>{!Vc(e.dataTransfer)||!xu()||(vu++,1===vu&<.classList.add(bu))},Su=e=>{!Vc(e.dataTransfer)||!xu()||(vu--,vu<=0&&wu())},ku=e=>{!Vc(e.dataTransfer)||!xu()||(e.preventDefault(),e.dataTransfer.dropEffect="copy")},Au=e=>{if(!Vc(e.dataTransfer)||!xu())return;e.preventDefault(),e.stopPropagation(),wu();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&Sr.handleFiles(t)},Mu=!0;lt.addEventListener("dragenter",Cu,Mu),lt.addEventListener("dragleave",Su,Mu),e.addEventListener("dragover",ku,Mu),e.addEventListener("drop",Au,Mu);let Iu=e.ownerDocument,Tu=e=>{xu()&&e.preventDefault()},Eu=e=>{xu()&&e.preventDefault()};Iu.addEventListener("dragover",Tu),Iu.addEventListener("drop",Eu),Zo.push(()=>{an?.destroy(),an=null,Sp(),fn?.destroy(),fn=null,Dr?.destroy(),Dr=null,Fr?.destroy(),Fr=null,_r?.destroy(),_r=null,$r=null,Wr=null,li(),ni.destroy(),Xc&&clearTimeout(Xc),Ja(),Hc?.abort(),Hc=null,Sr?.destroy(),Sr=null,Ar.destroy(),gu.removeEventListener("keydown",lp,!0),kr?.destroy()}),Zo.push(()=>{lt.removeEventListener("dragenter",Cu,Mu),lt.removeEventListener("dragleave",Su,Mu),e.removeEventListener("dragover",ku,Mu),e.removeEventListener("drop",Au,Mu),Iu.removeEventListener("dragover",Tu),Iu.removeEventListener("drop",Eu),wu()}),Zo.push(()=>{ha.cancel()}),Kp?Zo.push(()=>{Kp?.destroy()}):Jp&&Zo.push(()=>{Jp?.remove()});let Lu={update(t){let r=!0===n.future?.v5Defaults,o=n.toolCall,a=n.messageActions,s=n.layout?.messages,i=n.colorScheme,p=n.loadingIndicator,u=n.iterationDisplay,m=n.features?.showReasoning,g=n.features?.showToolCalls,f=n.features?.toolCallDisplay,y=n.features?.reasoningDisplay,b=n.features?.streamAnimation?.type,v=!0===n.features?.history?.enabled,w=n.features?.history?.provider,x=n.getIdentityProof,C=n.clientToken,S=n.contextMentions;n=dc({...n,features:d},t),d=n.features,n=Yd(n),l(),Uo(),Cs(e,n),kd(e,n),Ad(e,n),Ge(),_o(),n.colorScheme!==i&&oa();let k=ac.getForInstance(n.plugins);c.length=0,c.push(...k),rc(),Y=n.launcher?.enabled??!0,X=n.launcher?.autoExpand??!1,he=n.features?.showReasoning??!0,me=n.features?.showToolCalls??!0,be=n.features?.scrollToBottom??{};let A=Vt();ve=n.features?.scrollBehavior??{},A!==Vt()&&(Ji(),$i()),ys(),Cr(),Ni();let M=ye;if(ye=n.features?.showEventStreamToggle??!1,ye&&!M){if(Ae||(qe(),ha.setSSEEventCallback((e,t)=>{n.onSSEEvent?.(e,t),ze(e,t)})),!Qr&&Pt){let e=n.features?.eventStream?.classNames,t="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"+(e?.toggleButton?" "+e.toggleButton:"");Qr=ne("button",t),Qr.style.width="28px",Qr.style.height="28px",Qr.style.color=Hi.actionIconColor,Qr.type="button",Qr.setAttribute("aria-label","Event Stream"),Qr.title="Event Stream";let r=I(h,"18px","currentColor",1.5);r&&Qr.appendChild(r);let o=it.clearChatButtonWrapper,a=it.closeButtonWrapper,s=o||a;s&&s.parentNode===Pt?Pt.insertBefore(Qr,s):Pt.appendChild(Qr),Qr.addEventListener("click",()=>{We?Xr():Yr()})}}else!ye&&M&&(Xr(),Qr&&(Qr.remove(),Qr=null),Ae?.clear(),Se?.destroy(),Ae=null,Se=null,Ie?.reset(),Ie=null,Te=null);if(!1===n.launcher?.enabled&&Kp&&(Kp.destroy(),Kp=null),!1===n.launcher?.enabled&&Jp&&(Jp.remove(),Jp=null),!1!==n.launcher?.enabled&&!Kp&&!Jp){let{instance:t,element:r}=Wl({config:n,plugins:c,onToggle:Up});Kp=t,t||(Jp=r),e.appendChild(r)}Kp&&Kp.update(n),lc(),Lt&&void 0!==n.launcher?.subtitle&&(Lt.textContent=n.launcher.subtitle);let T=n.layout?.header;if(T?.layout!==te&&Pt){let e=T?Yi(n,T,{showClose:ie(),onClose:()=>Pl(!1,"user")}):Di({config:n,showClose:ie(),onClose:()=>Pl(!1,"user")});nt.replaceHeader(e),Pt=nt.header.element,Tt=nt.header.iconHolder,Et=nt.header.headerTitle,Lt=nt.header.headerSubtitle,It=nt.header.closeButton,te=T?.layout,lc()}else if(T){if(Tt&&(Tt.style.display=!1===T.showIcon?"none":""),Et&&(Et.style.display=!1===T.showTitle?"none":""),Lt&&(Lt.style.display=!1===T.showSubtitle?"none":""),It){let e=ie()&&!1!==T.showCloseButton;It.style.display=e?"":"none"}if(it.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){it.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=it;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=!1!==n.layout?.showHeader;Pt&&(Pt.style.display=E?"":"none");let L=!1!==n.layout?.showFooter;Bt&&(Bt.style.display=L?"":"none"),fr(),Ni(),Y!==ee?Y?Pl(X,"auto"):(le=!0,Ll()):X!==Z&&Pl(X,"auto"),Z=X,ee=Y,Qp(),lu();let P=JSON.stringify(n.toolCall)!==JSON.stringify(o),B=JSON.stringify(n.messageActions)!==JSON.stringify(a),R=JSON.stringify(n.layout?.messages)!==JSON.stringify(s),H=n.loadingIndicator?.render!==p?.render||n.loadingIndicator?.renderIdle!==p?.renderIdle||n.loadingIndicator?.showBubble!==p?.showBubble,$=n.iterationDisplay!==u,W=(n.features?.showReasoning??!0)!==(m??!0)||(n.features?.showToolCalls??!0)!==(g??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(f)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(y);(!0===n.future?.v5Defaults!==r||P||B||R||H||$||W)&&ha&&(Ga++,pl(ct,ha.getMessages(),ue));let D=n.features?.streamAnimation?.type;if(D!==b&&D&&"none"!==D){let t=sa(D,n.features?.streamAnimation?.plugins);t&&ci(t,e)}let O=n.launcher??{},F=O.headerIconHidden??!1,z=n.layout?.header?.showIcon,q=F||!1===z,j=O.headerIconName,K=O.headerIconSize??V;if(Tt){let e=Pt,t=e?.querySelector(".persona-flex-col");if(q)Tt.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Tt.style.display="",Tt.style.height=K,Tt.style.width=K,e&&t&&(e.contains(Tt)?Tt.nextSibling!==t&&(Tt.remove(),e.insertBefore(Tt,t)):e.insertBefore(Tt,t)),j){let e=parseFloat(K)||24,t=xe(j,.6*e,"currentColor",1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,Tt.replaceChildren(t)):Tt.textContent=O.agentIconText??"💬"}else if(O.iconUrl){let e=Tt.querySelector("img");if(e)e.src=O.iconUrl,e.style.height=K,e.style.width=K;else{let e=document.createElement("img");e.src=O.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=K,e.style.width=K,Tt.replaceChildren(e)}}else{let e=Tt.querySelector("svg"),t=Tt.querySelector("img");(e||t)&&Tt.replaceChildren(),Tt.textContent=O.agentIconText??"💬"}let r=Tt.querySelector("img");r&&(r.style.height=K,r.style.width=K)}}let J=n.layout?.header?.showTitle,Q=n.layout?.header?.showSubtitle;if(Et&&(Et.style.display=!1===J?"none":""),Lt&&(Lt.style.display=!1===Q?"none":""),It){let e=ie()&&!1!==n.layout?.header?.showCloseButton;if(It.style.display=e?"":"none",!se()){let e=O.closeButtonSize??"";It.style.height=e,It.style.width=e,It.style.minWidth=e,It.style.minHeight=e}let t=O.closeButtonPlacement??"inline",{closeButtonWrapper:r}=it,o="top-right"===t,a=r?.classList.contains("persona-absolute");if(r&&o!==a)if(r.remove(),o){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=Jd?.railColumn??lt;e.style.position="relative",e.appendChild(r)}else{let e=O.clearChat?.placement??"inline",t=O.clearChat?.enabled??!0;r.className=t&&"inline"===e?"":"persona-ml-auto",Pt&&Pt.appendChild(r)}if(It.style.color=O.closeButtonColor||Hi.actionIconColor,O.closeButtonBackgroundColor?(It.style.backgroundColor=O.closeButtonBackgroundColor,It.classList.remove("hover:persona-bg-gray-100")):(It.style.backgroundColor="",It.classList.add("hover:persona-bg-gray-100")),O.closeButtonBorderWidth||O.closeButtonBorderColor){let e=O.closeButtonBorderWidth||"0px",t=O.closeButtonBorderColor||"transparent";It.style.border=`${e} solid ${t}`,It.classList.remove("persona-border-none")}else It.style.border="",It.classList.add("persona-border-none");O.closeButtonBorderRadius?(It.style.borderRadius=O.closeButtonBorderRadius,It.classList.remove("persona-rounded-full")):(It.style.borderRadius="",It.classList.add("persona-rounded-full")),O.closeButtonPaddingX?(It.style.paddingLeft=O.closeButtonPaddingX,It.style.paddingRight=O.closeButtonPaddingX):(It.style.paddingLeft="",It.style.paddingRight=""),O.closeButtonPaddingY?(It.style.paddingTop=O.closeButtonPaddingY,It.style.paddingBottom=O.closeButtonPaddingY):(It.style.paddingTop="",It.style.paddingBottom=""),Pi(It,O.closeButtonIconName??"x",{iconSize:se()?Tl:void 0,iconText:O.closeButtonIconText??"×"});let s=O.closeButtonTooltipText??"Close chat",i=O.closeButtonShowTooltip??!0;It.setAttribute("aria-label",s),r&&Bo({anchor:It,trigger:r,text:()=>It?.getAttribute("aria-label")??s,enabled:i})}let{clearChatButton:re,clearChatButtonWrapper:oe}=it;if(re){let e=O.clearChat??{},t=e.enabled??!0,r=n.layout?.header?.showClearChat,o=void 0!==r?r:t,a=e.placement??"inline";if(oe){oe.style.display=o?"":"none";let{closeButtonWrapper:e}=it;!se()&&e&&!e.classList.contains("persona-absolute")&&(o?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===a,r=oe.classList.contains("persona-absolute");if(!se()&&t!==r&&o){if(oe.remove(),t){oe.className="persona-absolute persona-top-4 persona-z-50",oe.style.right="48px";let e=Jd?.railColumn??lt;e.style.position="relative",e.appendChild(oe)}else{oe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oe.style.right="";let e=it.closeButtonWrapper;Pt&&e&&e.parentElement===Pt?Pt.insertBefore(oe,e):Pt&&Pt.appendChild(oe)}let e=it.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(o){if(!se()){let t=e.size??"";re.style.height=t,re.style.width=t,re.style.minWidth=t,re.style.minHeight=t}let t=e.iconColor??"";if(re.style.color=t||Hi.actionIconColor,Pi(re,e.iconName??"refresh-cw",{iconSize:se()?El:void 0}),e.backgroundColor?(re.style.backgroundColor=e.backgroundColor,re.classList.remove("hover:persona-bg-gray-100")):(re.style.backgroundColor="",re.classList.add("hover:persona-bg-gray-100")),e.borderWidth||e.borderColor){let t=e.borderWidth||"0px",r=e.borderColor||"transparent";re.style.border=`${t} solid ${r}`,re.classList.remove("persona-border-none")}else re.style.border="",re.classList.add("persona-border-none");e.borderRadius?(re.style.borderRadius=e.borderRadius,re.classList.remove("persona-rounded-full")):(re.style.borderRadius="",re.classList.add("persona-rounded-full")),e.paddingX?(re.style.paddingLeft=e.paddingX,re.style.paddingRight=e.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),e.paddingY?(re.style.paddingTop=e.paddingY,re.style.paddingBottom=e.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let r=e.tooltipText??"Clear chat",n=e.showTooltip??!0;re.setAttribute("aria-label",r),oe&&Bo({anchor:re,trigger:oe,text:()=>re?.getAttribute("aria-label")??r,enabled:n})}}let ae=n.actionParsers&&n.actionParsers.length?n.actionParsers:[cc],de=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[uc.message,uc.messageAndClick];G=mc({parsers:ae,handlers:de,getSessionMetadata:_,updateSessionMetadata:U,emit:N.emit,documentRef:typeof document<"u"?document:null}),ue=Jc(n,G,pe),(()=>{let e=Ld();if(e&&Nd?.matches(e,we(),!1===n.persistState)||!e&&!Nd)return;Nd?.destroy(),Nd=e?Pd(e):null;let t={...Rd};Nd?t.visitorStore=Nd:delete t.visitorStore,Rd=t,ha.setHistoryInternals(Rd)})(),ha.updateConfig(n),Ic(),(!0===n.features?.history?.enabled!==v||n.features?.history?.provider!==w||n.getIdentityProof!==x||n.clientToken!==C)&&(Jd?.closeHistory({restoreFocus:!1}),Jd?.installHistoryProvider()),Jd?.syncHistoryChromeImpl(),vc(),ec()&&!Jd&&gc().catch(()=>{}),pl(ct,ha.getMessages(),ue),Oa(),Cd(),(()=>{let e=cr();`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`===md&&e.icon===nd||xd()})(),_l(ha.isStreaming()),S!==n.contextMentions&&mu();let ce=!0===n.voiceRecognition?.enabled,ge=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),fe=$e(n.voiceRecognition?.provider);if(ce&&(ge||fe))if(Dt&&Ot){let e=n.voiceRecognition??{},t=n.sendButton??{},r=e.iconName??"mic",o=e.iconSize,a=parseFloat(o??"")||qo;Dt.classList.add(Fo),Dt.classList.toggle(zo,!o),Dt.style.width=o??"",Dt.style.height=o??"",Dt.style.minWidth=o??"",Dt.style.minHeight=o??"";let s=e.iconColor??t.textColor;Dt.innerHTML="";let i=xe(r,a,s||"currentColor",1.5);i?Dt.appendChild(i):Dt.textContent="🎤";let l=e.backgroundColor??t.backgroundColor;Dt.style.backgroundColor=l||"",Dt.style.color=s||"var(--persona-text, #111827)",e.borderWidth?(Dt.style.borderWidth=e.borderWidth,Dt.style.borderStyle="solid"):(Dt.style.borderWidth="",Dt.style.borderStyle=""),e.borderColor?Dt.style.borderColor=e.borderColor:Dt.style.borderColor="",e.paddingX?(Dt.style.paddingLeft=e.paddingX,Dt.style.paddingRight=e.paddingX):(Dt.style.paddingLeft="",Dt.style.paddingRight=""),e.paddingY?(Dt.style.paddingTop=e.paddingY,Dt.style.paddingBottom=e.paddingY):(Dt.style.paddingTop="",Dt.style.paddingBottom="");let d=e.tooltipText??"Start voice recognition",c=e.showTooltip??!1;Dt.setAttribute("aria-label",d),Ot&&Bo({anchor:Dt,trigger:Ot,text:()=>Dt?.getAttribute("aria-label")??d,enabled:c}),Ot.style.display="",Dt.disabled=Nl()||ha.isStreaming()&&!Rl()}else{let e=Ko(n);if(e){Dt=e.button,Ot=e.wrapper;let t=$t&&$t.parentElement===Ht?$t:null;Ht?Ht.insertBefore(Ot,t):yt?.appendChild(Ot),an&&(an.micButton=Dt),an?.addListener(Dt,"click",Np),Dt.disabled=Nl()||ha.isStreaming()&&!Rl()}}else Dt&&Ot&&(Ot.style.display="none",$e(n.voiceRecognition?.provider)?ha.isVoiceActive()&&ha.toggleVoice():cp&&Mp());if(qp(),!0===n.attachments?.enabled){if(zt&&Ft){zt.style.display="";let e=n.attachments??{};qt&&(qt.accept=(e.allowedTypes??on).join(","),qt.multiple=(e.maxFiles??4)>1),Sr&&Sr.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}else{let e=n.attachments??{};jt||(jt=ne("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),jt.style.display="none",(mt.parentElement??yt).insertBefore(jt,mt)),qt||(qt=document.createElement("input"),qt.type="file",qt.accept=(e.allowedTypes??on).join(","),qt.multiple=(e.maxFiles??4)>1,qt.style.display="none",qt.setAttribute("aria-label","Attach files"),(mt.parentElement??yt).insertBefore(qt,mt)),zt=ne("div","persona-send-button-wrapper"),Ft=ne("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Fo} ${zo}`),Ft.type="button",Ft.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";Ft.style.fontSize="18px",Ft.style.lineHeight="1";let r=xe(t,qo,"currentColor",1.5);r?Ft.appendChild(r):Ft.textContent="📎",Ft.addEventListener("click",e=>{e.preventDefault(),qt?.click()}),zt.appendChild(Ft);let o=e.buttonTooltipText??"Attach file";Bo({anchor:Ft,trigger:zt,text:()=>Ft?.getAttribute("aria-label")??o}),Rt?Rt.append(zt):yt.appendChild(zt),an&&(an.attachmentButton=Ft,an.attachmentInput=qt??void 0,an.attachmentPreviews=jt??void 0),!Sr&&qt&&jt&&(Sr=fo.fromConfig(e,Er),Sr.setPreviewsContainer(jt),an?.addListener(qt,"change",async()=>{Sr&&qt?.files&&(await Sr.handleFileSelect(qt.files),qt.value="")}))}if(lt.querySelector(".persona-attachment-drop-overlay")?.remove(),lt.appendChild(Gc(n.attachments?.dropOverlay)),Ft){let e=n.attachments??{},t=e.buttonTooltipText??"Attach file";Ft.setAttribute("aria-label",t),Ft.textContent="";let r=xe(e.buttonIconName??"paperclip",qo,"currentColor",1.5);r?Ft.appendChild(r):Ft.textContent="📎",zt&&Bo({anchor:Ft,trigger:zt,text:()=>Ft?.getAttribute("aria-label")??t})}}else zt&&(zt.style.display="none"),Sr&&Sr.clearAttachments(),lt.querySelector(".persona-attachment-drop-overlay")?.remove();let Ce=n.sendButton??{},ke=Ce.useIcon??!1,Me=Ce.iconText??"↑",Ee=Ce.iconName,Le=Ce.tooltipText??"Send message",Pe=Ce.showTooltip??!1,Be=Ce.size,Ne=parseFloat(Be??"")||40,De=Ce.backgroundColor,Oe=Ce.textColor;if(ke){if(ft.style.width=Be??"",ft.style.height=Be??"",ft.style.minWidth=Be??"",ft.style.minHeight=Be??"",ft.style.fontSize="18px",ft.style.lineHeight="1",ft.style.color=Oe||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!ha.isStreaming())if(ft.innerHTML="",Ee){let e=parseFloat(Ce.iconSize??"")||Math.round(.5*Ne),t=Oe?.trim()||"currentColor",r=Ce.iconStrokeWidth??2,n=xe(Ee,e,t,r),o=xe(Ce.stopIconName??"square",e,t,r);n&&o?ft.appendChild(Vo(n,o)):n?ft.appendChild(n):ft.textContent=Me}else ft.textContent=Me;ft.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Fo}`,De?(ft.style.backgroundColor=De,ft.classList.remove("persona-bg-persona-primary")):(ft.style.backgroundColor="",ft.classList.add("persona-bg-persona-primary"))}else ft.textContent=n.copy?.sendButtonLabel??"Send",ft.style.width="",ft.style.height="",ft.style.minWidth="",ft.style.minHeight="",ft.style.fontSize="",ft.style.lineHeight="",ft.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",De?(ft.style.backgroundColor=De,ft.classList.remove("persona-bg-persona-accent")):ft.classList.add("persona-bg-persona-accent"),Oe?ft.style.color=Oe:ft.classList.add("persona-text-white");Ce.borderWidth?(ft.style.borderWidth=Ce.borderWidth,ft.style.borderStyle="solid"):(ft.style.borderWidth="",ft.style.borderStyle=""),Ce.borderColor?ft.style.borderColor=Ce.borderColor:ft.style.borderColor="",Ce.paddingX?(ft.style.paddingLeft=Ce.paddingX,ft.style.paddingRight=Ce.paddingX):(ft.style.paddingLeft="",ft.style.paddingRight=""),Ce.paddingY?(ft.style.paddingTop=Ce.paddingY,ft.style.paddingBottom=Ce.paddingY):(ft.style.paddingTop="",ft.style.paddingBottom=""),ha.isStreaming()||ft.setAttribute("aria-label",Le),zl(),$t&&Bo({anchor:ft,trigger:$t,text:()=>ft.getAttribute("aria-label")??Le,enabled:Pe}),Mn(),Xo();let Fe=Sa(Ar.getState().activeModeIds,n.composer?.modes);Ar.setActiveModeIds(Fe),Br().length>0!=!!Dr&&xn(),Dr?.render(Fe,Br());for(let e of[...Or.keys()])Ca(e,n.composer?.modeGroups)||Or.delete(e);Or.forEach(e=>e.repaint()),$r?.repaint(),fn?.resolve();let je=ks(n,se());if(Jo(),je){ct.style.maxWidth=je,ct.style.marginLeft="auto",ct.style.marginRight="auto",ct.style.width="100%",Ct.style.maxWidth=je,Ct.style.marginLeft="auto",Ct.style.marginRight="auto",Ct.style.width="100%";for(let e of[yt,ht,jt,bt])e&&(e.style.maxWidth=je,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{ct.style.maxWidth="",ct.style.marginLeft="",ct.style.marginRight="",ct.style.width="",Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight="",Ct.style.width="";for(let e of[yt,ht,jt,bt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let _e=n.statusIndicator??{};if(He(bt,yt,_e),Re(bt,_e,ha?.getStatus()??"idle"),ha){let e=ha.getStatus();rt(bt,"idle"===(Ve=e)?_e.idleText??cn.idle:"connecting"===Ve?_e.connectingText??cn.connecting:"connected"===Ve?_e.connectedText??cn.connected:"error"===Ve?_e.errorText??cn.error:"paused"===Ve?_e.pausedText??cn.paused:"resuming"===Ve?_e.resumingText??cn.resuming:cn[Ve],_e,e)}var Ve;bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Ue="left"===_e.align?"persona-text-left":"center"===_e.align?"persona-text-center":"persona-text-right";bt.classList.add(Ue),sn(),ql(),An(),Je()},open(){ie()&&Pl(!0,"api")},close(){ie()&&Pl(!1,"api")},toggle(){ie()&&Pl(!le,"api")},reconnect(){ha.reconnectNow()},clearChat(){Jn=!1,s.clear(),o.clear(),a.clear(),i.clear(),ha.clearMessages(),n.layout?.topFade&&(dt.scrollTop=0),dt.removeAttribute("data-persona-top-fade"),qa.clear(),$i();try{localStorage.removeItem(qc),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qc}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==qc)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let e=new CustomEvent("persona:clear-chat",{detail:{timestamp:(new Date).toISOString()}});window.dispatchEvent(e),R?.clear&&Zs(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),$={},G.syncFromMetadata(),Sr?.clearAttachments(),ui(),Vr(void 0),zr(void 0),Ja(),Ae?.clear(),Ie?.reset(),Le?.update()},setMessage:e=>!(!mt||ha.isStreaming()||Nl()||(!le&&ie()&&Pl(!0,"system"),mt.value=e,mt.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(ha.isStreaming()||Hl())return!1;let t=e?.trim()||mt.value.trim();return!!t&&(!le&&ie()&&Pl(!0,"system"),mt.value="",mt.style.height="auto",Mr(),np(t,{consumeDraft:!1}),!0)},getComposerState:()=>Ar.getState(),setQuote(e){let t=e?.text?.trim();t&&zr({...e,text:t})},clearQuote(){zr(void 0)},startVoiceRecognition:()=>!ha.isStreaming()&&($e(n.voiceRecognition?.provider)?(ha.isVoiceActive()||ha.isBargeInActive()||(!le&&ie()&&Pl(!0,"system"),Bs.manuallyDeactivated=!1,Vs(),ha.toggleVoice().then(()=>{Bs.active=ha.isVoiceActive(),js("user"),ha.isVoiceActive()&&Ep()})),!0):!!cp||!!kp()&&(!le&&ie()&&Pl(!0,"system"),Bs.manuallyDeactivated=!1,Vs(),Ap("user"),!0)),stopVoiceRecognition:()=>$e(n.voiceRecognition?.provider)?!(!ha.isVoiceActive()&&!ha.isBargeInActive()||((ha.isBargeInActive()?ha.deactivateBargeIn():ha.toggleVoice()).then(()=>{Bs.active=!1,Bs.manuallyDeactivated=!0,Vs(),js("user"),Bp()}),0)):!!cp&&(Bs.manuallyDeactivated=!0,Vs(),Mp("user"),!0),injectMessage:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectMessage(e)),injectAssistantMessage(e){!le&&ie()&&Pl(!0,"system");let t=ha.injectAssistantMessage(e);return de&&(de=!1,ce&&(clearTimeout(ce),ce=null),setTimeout(()=>{ha&&!ha.isStreaming()&&ha.continueConversation()},100)),t},injectUserMessage:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectUserMessage(e)),injectSystemMessage:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectSystemMessage(e)),injectMessageBatch:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectMessageBatch(e)),injectComponentDirective:e=>(!le&&ie()&&Pl(!0,"system"),ha.injectComponentDirective(e)),injectTestMessage(e){!le&&ie()&&Pl(!0,"system"),ha.injectTestEvent(e)},connectStream:async(e,t)=>ha.connectStream(e,t),__pushEventStreamEvent(e){ye&&(qe(),ze(e.type,e.payload))},showEventStream(){ye&&Yr()},hideEventStream(){We&&Xr()},isEventStreamVisible:()=>We,listConversations:e=>ha.listConversations(e),getActiveConversationId:()=>ha.getActiveConversationId(),openConversation:(e,t)=>fc(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus})),startNewConversation:e=>fc(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){wc()},deleteConversation:e=>fc(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>fc(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>fc(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>fc(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>fc(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Nd;if(!e)return null;let t=await e.get();return e===Nd?t:null},getHistoryIdentityStatus(){let e=Jd?.historyProvider;return e?e.getIdentityStatus():ec()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>ec()?fc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0!==e?.focus?{focus:e.focus}:{}})):Promise.resolve(),hideHistory(e){Jd?.closeHistory(void 0!==e?.restoreFocus?{restoreFocus:e.restoreFocus}:void 0)},isHistoryVisible:()=>Ue,showArtifacts(){vd(n)&&(Jn=!1,Xn=!0,_o(),Wn?.setMobileOpen(!0))},hideArtifacts(){vd(n)&&(Jn=!0,_o())},upsertArtifact:e=>vd(n)?("panel"===On(n.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Jn=!1,Xn=!0),ha.upsertArtifact(e)):null,selectArtifact(e){vd(n)&&ha.selectArtifact(e)},clearArtifacts(){vd(n)&&ha.clearArtifacts()},getArtifacts:()=>ha?.getArtifacts()??[],getSelectedArtifactId:()=>ha?.getSelectedArtifactId()??null,focusInput:()=>!(Y&&!le&&!se()||!mt||(mt.focus(),0)),async resolveApproval(e,t,r){let n=ha.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!n?.approval)throw new Error(`Approval not found: ${e}`);if("webmcp"!==n.approval.toolType)return ha.resolveApproval(n.approval,t,r);ha.resolveWebMcpApproval(n.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Fa();let r=ha?ha.getMessages():[];Ma=t,Ia=!0,Ta=Pa(r),La=Ba(r),Oa(r)})(e)},clearFollowUpSuggestions(){Fa()},getMessages:()=>ha.getMessages(),getStatus:()=>ha.getStatus(),getPersistentMetadata:()=>({...$}),updatePersistentMetadata(e){U(e)},on:(e,t)=>N.on(e,t),off(e,t){N.off(e,t)},isOpen:()=>ie()&&le,isVoiceActive:()=>Bs.active,toggleReadAloud(e){ha.toggleReadAloud(e)},stopReadAloud(){ha.stopSpeaking()},getReadAloudState:e=>ha.getReadAloudState(e),onReadAloudChange:e=>ha.onReadAloudChange(e),getState:()=>({open:ie()&&le,launcherEnabled:Y,voiceActive:Bs.active,streaming:ha.isStreaming()}),showCSATFeedback(e){!le&&ie()&&Pl(!0,"system");let t=ct.querySelector(".persona-feedback-container");t&&t.remove();let r=Fc({onSubmit:async(t,r)=>{ha.isClientTokenMode()&&await ha.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});ct.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(e){!le&&ie()&&Pl(!0,"system");let t=ct.querySelector(".persona-feedback-container");t&&t.remove();let r=zc({onSubmit:async(t,r)=>{ha.isClientTokenMode()&&await ha.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e});ct.appendChild(r),r.scrollIntoView({behavior:"smooth",block:"end"})},submitCSATFeedback:async(e,t)=>ha.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>ha.submitNPSFeedback(e,t),destroy(){Vd(),null!=Hd&&(clearInterval(Hd),Hd=null),s.clear(),o.clear(),a.clear(),i.clear(),Zo.forEach(e=>e()),ot.remove(),st?.remove(),Kp?.destroy(),Jp?.remove(),ma&&It.removeEventListener("click",ma)}};if((r?.debugTools||n.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Lu,getMessages:Lu.getMessages,getStatus:Lu.getStatus,getMetadata:Lu.getPersistentMetadata,updateMetadata:Lu.updatePersistentMetadata,clearHistory:()=>Lu.clearChat(),setVoiceActive:e=>e?Lu.startVoiceRecognition():Lu.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Zo.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<"u"){let t=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.focusInput()};if(window.addEventListener("persona:focusInput",r),Zo.push(()=>{window.removeEventListener("persona:focusInput",r)}),ye){let e=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.showEventStream()},r=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.hideEventStream()};window.addEventListener("persona:showEventStream",e),window.addEventListener("persona:hideEventStream",r),Zo.push(()=>{window.removeEventListener("persona:showEventStream",e),window.removeEventListener("persona:hideEventStream",r)})}let n=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.showHistory()},o=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.hideHistory()};window.addEventListener("persona:showHistory",n),window.addEventListener("persona:hideHistory",o),Zo.push(()=>{window.removeEventListener("persona:showHistory",n),window.removeEventListener("persona:hideHistory",o)});let a=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.showArtifacts()},s=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.hideArtifacts()},i=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||r?.artifact&&Lu.upsertArtifact(r.artifact)},l=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==t||"string"==typeof r?.id&&Lu.selectArtifact(r.id)},d=e=>{let r=e.detail;(!r?.instanceId||r.instanceId===t)&&Lu.clearArtifacts()};window.addEventListener("persona:showArtifacts",a),window.addEventListener("persona:hideArtifacts",s),window.addEventListener("persona:upsertArtifact",i),window.addEventListener("persona:selectArtifact",l),window.addEventListener("persona:clearArtifacts",d),Zo.push(()=>{window.removeEventListener("persona:showArtifacts",a),window.removeEventListener("persona:hideArtifacts",s),window.removeEventListener("persona:upsertArtifact",i),window.removeEventListener("persona:selectArtifact",l),window.removeEventListener("persona:clearArtifacts",d)})}let Pu=function(e){return e?!0===e?{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}(n.persistState);if(Pu&&ie()){let t=function(e){try{let t="local"===e?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}(Pu.storage),r=`${Pu.keyPrefix}widget-open`,n=`${Pu.keyPrefix}widget-voice`,o=`${Pu.keyPrefix}widget-voice-mode`;if(t){let a=Pu.persist?.openState&&"true"===t.getItem(r),s=Pu.persist?.voiceState&&"true"===t.getItem(n),i=Pu.persist?.voiceState&&"true"===t.getItem(o);if(a&&(Kp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lu.open(),setTimeout(()=>{if(s||i)Lu.startVoiceRecognition();else if(Pu.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),Pu.persist?.openState&&(N.on("widget:opened",()=>{t.setItem(r,"true")}),N.on("widget:closed",()=>{t.setItem(r,"false")})),Pu.persist?.voiceState&&(N.on("voice:state",e=>{t.setItem(n,e.active?"true":"false")}),N.on("user:message",e=>{t.setItem(o,e.viaVoice?"true":"false")})),Pu.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(n),t.removeItem(o)},a=()=>e();window.addEventListener("persona:clear-chat",a),Zo.push(()=>{window.removeEventListener("persona:clear-chat",a)})}}}if(q&&ie()&&(Kp?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lu.open()},0)),Il(),!Ya){let e=_e(()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))});Zo.push(e)}C=()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))},ha.getMessages().length>0&&dl(),T=()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))};let Bu=(e=>ge?()=>{}:(fe.add(e),()=>{fe.delete(e)}))(()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue))});Zo.push(Bu);let Nu=bd(()=>{ha&&(Ga++,qa.clear(),pl(ct,ha.getMessages(),ue),yd()?.updateInlineArtifactBlocks(ct,Kn.artifacts,{suppressTransition:!0}),_o())});return Zo.push(Nu),Lu},Qc=(e,t)=>{let r=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,t*parseFloat(o[1])/100):420},Zc=(e,t)=>{let r=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0",e.style.minWidth=r?"":"0"},ep=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=""},tp=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ep(e)},rp=e=>{e.style.transition=""},np=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},op=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ap=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},sp=(e,t,r,n)=>{if(!t)return e.style.padding="",e.style.background="",void(e.style.boxSizing="");e.style.boxSizing="border-box",e.style.padding=r,e.style.background=n},ip=(e,t)=>vi(t)?((e,t)=>{let{ownerDocument:r}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if("BODY"===o||"HTML"===o)throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),l=r.createElement("div"),d=r.createElement("aside"),c=r.createElement("div"),p=!(t?.launcher?.enabled??1)||(t?.launcher?.autoExpand??!1);i.dataset.personaDockRole="push-track",l.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),n.insertBefore(s,e),l.appendChild(e);let u=null,h=()=>{u?.disconnect(),u=null},m=null,g=()=>{m=!0===t?.launcher?.detachedPanel?(e=>{let t=xs(e),r=t.components?.panel,n=(e,r)=>null==e||""===e?r:es(t,e)??e;return{inset:n(r?.inset,Wa),canvasBackground:n(r?.canvasBackground,Da)}})(t):null};g();let f=()=>{((e,t,r,n,o,a,s,i)=>{let l=xi(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,n,o)=>{o?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,n),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(n))})(e,t,r,n,d),((e,t,r,n,o,a)=>{let s=a?t:e;"left"===o?s.firstElementChild!==n&&s.replaceChildren(n,r):s.lastElementChild!==n&&s.replaceChildren(r,n)})(e,t,r,n,l.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=l.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,g=a?.launcher?.mobileBreakpoint??640,f=null!=h&&h.innerWidth<=g;if(m&&f&&s)return e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),np(t),rp(n),tp(n),op(r),ap(o,n),sp(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??pn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",void(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",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0"));if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),tp(n),((e,t)=>{!1!==t?(e.style.maxHeight="100vh",e.style.maxHeight=t):e.style.maxHeight=""})(n,l.maxHeight),sp(n,c&&s,p,u),"overlay"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",np(t),rp(n),op(r),ap(o,n);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=l.width,n.style.maxWidth=l.width,n.style.minWidth=l.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=a,n.style.transform=d,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2","right"===l.side?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if("push"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",rp(n),ep(n),ap(o,n);let a=Qc(l.width,e.clientWidth),i=Math.max(0,e.clientWidth),d=l.animate?"margin-left 180ms ease":"none",c="right"===l.side?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=`${i+a}px`,t.style.transition=d,t.style.marginLeft=`${c}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${i}px`,r.style.maxWidth=`${i}px`,r.style.minWidth=`${i}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=l.width,n.style.minWidth=l.width,n.style.maxWidth=l.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",np(t),ep(n),op(r),ap(o,n);let a="emerge"===l.reveal;a?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let i=s?l.width:"0px",d=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease"+(c?", padding 180ms ease":""):"none",u=!s;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(n,l.maxHeight),n.style.overflow=a||u?"hidden":"visible",n.style.transition=d,a){n.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Qc(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;o.style.width=t,o.style.minWidth=t,o.style.maxWidth=t,o.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},y=null,b=()=>{y?.(),y=null,!0===t?.launcher?.detachedPanel&&"auto"===t?.colorScheme&&(y=Ss(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===xi(t).reveal&&(typeof ResizeObserver>"u"||(u=new ResizeObserver(()=>{f()}),u.observe(s))),p&&!v&&"true"!==s.dataset.personaDockMobileFullscreen&&(v=!0,((e,t)=>{let r=e.parentElement;if(!r)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(n);let o=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),o&&!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."+(!1===t.maxHeight?" 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.")})(s,xi(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===xi(t).reveal?(i.appendChild(l),i.appendChild(d),s.appendChild(i)):(s.appendChild(l),s.appendChild(d)),w(),b(),{mode:"docked",host:c,shell:s,syncWidgetState(e){let t=!e.launcherEnabled||e.open;p!==t&&(p=t,w())},updateConfig(e){t=e,!1===(t?.launcher?.enabled??!0)&&(p=!0),g(),w(),b()},destroy(){x?.removeEventListener("resize",C),y?.(),y=null,h(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Zc(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Zc(r,e)},destroy(){r.remove()}}})(e,t),lp=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let n=r.cloneNode(!0);e.insertBefore(n,e.firstChild)},dp=[],cp=()=>[...dp],pp=e=>{let t,r=(e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if("string"==typeof e){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e})(e.target),n=!0===e.useShadowDom,o=r.ownerDocument,a=e.config,s=ip(r,a),i=[],l=()=>{s.syncWidgetState(t.getState())},d=()=>{let d=((e,t)=>{let a=!(t?.launcher?.enabled??1)||vi(t),s=o.createElement("div");if(s.setAttribute("data-persona-root","true"),a&&(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0",s.style.minWidth="0"),n){let t=e.attachShadow({mode:"open"});t.appendChild(s),lp(t,o)}else e.appendChild(s),lp(e,o);return r.id&&s.setAttribute("data-persona-instance",r.id),s})(s.host,a);t=Xc(d,a,{debugTools:e.debugTools}),i.forEach(e=>e()),i=[t.on("widget:opened",l),t.on("widget:closed",l)],l()},c=()=>{i.forEach(e=>e()),i=[],t.destroy()};d(),e.onChatReady?.();let p=new Proxy({update(e){let n=dc(a??{},e),o=vi(a),i=vi(n),p=wi(a),u=wi(n);o===i&&p===u?(a=n,s.updateConfig(a),t.update(e),l()):(e=>{c(),s.destroy(),s=ip(r,e),a=e,d()})(n)},destroy(){c(),s.destroy();let t=dp.indexOf(p);-1!==t&&dp.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,n){if("host"===r)return s.host;if(r in e)return Reflect.get(e,r,n);let o=t[r];return"function"==typeof o?o.bind(t):o}});return dp.push(p),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=p),p},up=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),hp=new Set(["button","a","input","select","textarea","details","summary"]),mp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),gp=/\b(product|card|item|listing|result)\b/i,fp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,yp=3e3,bp=100;function vp(e){let t="string"==typeof e.className?e.className:"";if(gp.test(t)||e.id&&gp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&gp.test(r.value))return!0}return!1}function wp(e){return fp.test((e.textContent??"").trim())}function xp(e){let t=e.querySelectorAll("a[href]");for(let e=0;e<t.length;e++){let r=t[e].getAttribute("href")??"";if(r&&"#"!==r&&!r.toLowerCase().startsWith("javascript:"))return!0}return!1}function Cp(e){let t=e.match(fp);return t?t[0]:null}function Sp(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 e=t.getAttribute("href");return{title:t.textContent.trim(),href:e&&"#"!==e?e:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return r?.textContent?.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function kp(e){return vp(e)&&wp(e)&&(xp(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function Ap(e){return!vp(e)||wp(e)||!xp(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}var Mp=[{id:"commerce-card",scoreElement:e=>kp(e),shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if("static"===r.interactivity){let e=r.text.trim();return!!(0===e.length||fp.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===kp(e))return null;let{title:r,href:n}=Sp(e),o=Cp((e.textContent??"").trim())??Cp(t.text)??"",a=function(e){let t=[],r=e=>{let r=e.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(e=>r(e.textContent??"")),e.querySelectorAll('[role="button"]').forEach(e=>r(e.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(e=>{r(e.value??"")}),t.slice(0,6)}(e);return[n&&r?`[${r}](${n})${o?`: ${o}`:""}`:r?`${r}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>Ap(e),formatSummary(e,t){if(0===Ap(e))return null;let{title:r,href:n}=Sp(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Ip(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Tp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Ep(e){let t=e.tagName.toLowerCase(),r=e.getAttribute("role");return"a"===t&&e.hasAttribute("href")?"navigable":"input"===t||"select"===t||"textarea"===t||"textbox"===r||"combobox"===r||"listbox"===r||"spinbutton"===r?"input":"button"===t||"button"===r||hp.has(t)||r&&mp.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function Lp(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return!1}catch{}return!("none"===e.style.display||"hidden"===e.style.visibility)}function Pp(e){let t={},r=e.id;r&&(t.id=r);let n=e.getAttribute("href");n&&(t.href=n);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let l=e.getAttribute("role");l&&(t.role=l);for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];n.name.startsWith("data-")&&(t[n.name]=n.value)}return t}function Bp(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Ip(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of Tp){let n=e.getAttribute(r);if(n){let o=`${t}[${r}="${Ip(n)}"]`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(e=>Ip(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${n}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function Np(e,t){let r=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Bp(e),tagName:r,text:n,role:e.getAttribute("role"),interactivity:Ep(e),attributes:Pp(e)}}function Rp(e,t,r,n){let o=function(e){return"static"===e?bp:yp}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,n);r>0&&(o+=r,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function Hp(e,t){for(let r of e)if(t.el!==r.el&&r.formattingRule?.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function $p(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",o=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,i=t.mode??"structured",l=t.maxCandidates??Math.max(500,10*r),d=e.rules??Mp;return"simple"===i&&e.rules&&e.rules.length>0?(typeof console<"u"&&"function"==typeof console.warn&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.'),d=[]):"simple"===i&&(d=[]),{mode:i,maxElements:r,maxCandidates:l,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],n=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(up.has(s)){a=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Lp(t)){a=o.nextNode();continue}let i=Np(t,e.maxTextLength),l=i.text.length>0,d=Object.keys(i.attributes).length>0&&!Object.keys(i.attributes).every(e=>"role"===e);if(!l&&!d){a=o.nextNode();continue}n.has(i.selector)||(n.add(i.selector),r.push(i))}a=o.nextNode()}let s=[],i=[];for(let e of r)"static"!==e.interactivity?s.push(e):i.push(e);return[...s,...i].slice(0,e.maxElements)}(t,r):function(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,o=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(up.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Lp(t)){i=s.nextNode();continue}let d=Np(t,e.maxTextLength),c=d.text.length>0,p=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(e=>"role"===e);if(!c&&!p){i=s.nextNode();continue}if(n.has(d.selector)){i=s.nextNode();continue}n.add(d.selector);let{score:u,formattingRule:h}=Rp(t,d,e.rules,r);o.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}o.sort((e,t)=>{let r="static"===e.enriched.interactivity?1:0,n="static"===t.enriched.interactivity?1:0;return r!==n?r-n:t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex});let l=[];for(let t of o){if(l.length>=e.maxElements)break;Hp(l,t)||l.push(t)}return l.sort((e,t)=>{let r="static"===e.enriched.interactivity?1:0,n="static"===t.enriched.interactivity?1:0;return r!==n?r-n:1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let n=e.formattingRule.formatSummary(e.el,e.enriched,r);n&&(t=n)}let n={...e.enriched};return t&&(n.formattedSummary=t),n})}(t,r):[]}var Wp=100;function Dp(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",n=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&n.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||o[t.interactivity].push(t);if(o.clickable.length>0){let e=o.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,Wp)}" (clickable)`);n.push(`Interactive elements:\n${e.join("\n")}`)}if(o.navigable.length>0){let e=o.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,Wp)}" (navigable)`);n.push(`Navigation links:\n${e.join("\n")}`)}if(o.input.length>0){let e=o.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,Wp)}" (input)`);n.push(`Form inputs:\n${e.join("\n")}`)}if(o.static.length>0){let e=o.static.map(e=>`- ${e.selector}: "${e.text.substring(0,Wp)}"`);n.push(`Content:\n${e.join("\n")}`)}return n.join("\n\n")}var Op={components:{panel:{borderRadius:"0",shadow:"none"}}},Fp={id:"shop",label:"Shopping Assistant",config:{theme:{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"}}},launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"🛍️",position:"bottom-right",width:j},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"]}},zp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Op}},qp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Op}},jp={shop:Fp,minimal:zp,fullscreen:qp};function _p(e){return jp[e]}var Vp=typeof document<"u"?document.currentScript?.src??null:null,Up=(e,t=`host ${e} alongside it`)=>()=>{let r=Vp?.replace(/index\.global\.js($|\?)/,`${e}$1`);return r&&r!==Vp?import(r):Promise.reject(new Error(`Could not derive the ${e} URL from the widget script URL (${Vp??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))};return(e=>{It=e})(Up("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),qe(Up("markdown-parsers.js")),wt(Up("client-stream.js")),Ur(Up("client-history.js")),Mn(Up("ui-extras.js")),Nn(Up("session-actions.js")),Ic(Up("history-shell.js")),(e=>{to=e})(Up("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),Ta(Up("context-mentions.js")),Ba(Up("context-mentions-inline.js")),xc(Up("history-view.js")),hi(Up("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),Zl(Up("approval-ui.js")),Xn(Up("voice-runtime.js")),gd(Up("artifacts-ui.js")),rc(Up("forms-ui.js")),de(Up("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),Rt(Up("webmcp-runtime.js")),ao(Up("session-reconnect.js")),od(Up("event-stream-view.js")),(e=>l(r({},"__esModule",{value:!0}),e))(u)})();
|
|
2
2
|
/*! Bundled license information:
|
|
3
3
|
|
|
4
4
|
lucide:
|