@runtypelabs/persona 4.25.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/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-Db61aI9J.d.cts → types-BwKTZhg9.d.cts} +14 -0
- package/dist/animations/{types-Db61aI9J.d.ts → types-BwKTZhg9.d.ts} +14 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/animations-extra.d.cts +14 -0
- package/dist/animations-extra.d.ts +14 -0
- package/dist/approval-ui-QAKWNFNM.js +1 -0
- package/dist/approval-ui.cjs +2 -2
- package/dist/approval-ui.d.cts +186 -8
- package/dist/approval-ui.d.ts +186 -8
- package/dist/approval-ui.js +2 -2
- package/dist/{artifacts-ui-IGB5YKLO.js → artifacts-ui-NJGMM27I.js} +1 -1
- package/dist/artifacts-ui.cjs +4 -4
- package/dist/artifacts-ui.d.cts +186 -8
- package/dist/artifacts-ui.d.ts +186 -8
- package/dist/artifacts-ui.js +5 -5
- package/dist/chunk-2ANTRKTV.js +1 -0
- package/dist/chunk-4HPTPUC6.js +1 -0
- package/dist/chunk-6V3MNEKB.js +1 -0
- package/dist/chunk-GKPCIQPB.js +1 -0
- package/dist/chunk-HGUCGM3K.js +9 -0
- package/dist/chunk-IO5VVUKP.js +3 -0
- package/dist/chunk-J4J3Y2P2.js +1 -0
- package/dist/chunk-K6HKIP5K.js +1 -0
- package/dist/chunk-K7NA7G7J.js +1 -0
- package/dist/chunk-MXUTS3LB.js +1 -0
- package/dist/chunk-PDPVORUF.js +1 -0
- package/dist/chunk-QRKGQPU7.js +1 -0
- package/dist/chunk-S6PBWE75.js +1 -0
- package/dist/chunk-T7QM7YMF.js +1 -0
- package/dist/chunk-TR2H475E.js +1 -0
- package/dist/chunk-UPO4GUFC.js +1 -0
- package/dist/chunk-ZC66NAIR.js +1 -0
- package/dist/client-history-GOZWBDA5.js +1 -0
- package/dist/client-history.js +1 -0
- package/dist/client-stream-42FOI3EC.js +4 -0
- package/dist/client-stream.js +5 -0
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions-E7HJYWO6.js +161 -0
- package/dist/{context-mentions-inline-I2RDEBAK.js → context-mentions-inline-QVESLW55.js} +1 -1
- package/dist/context-mentions.cjs +7 -7
- package/dist/context-mentions.d.cts +186 -8
- package/dist/context-mentions.d.ts +186 -8
- package/dist/context-mentions.js +8 -8
- package/dist/event-stream-view-FOIJHFQO.js +1 -0
- package/dist/event-stream-view.cjs +1 -1
- package/dist/event-stream-view.d.cts +189 -31
- package/dist/event-stream-view.d.ts +189 -31
- package/dist/event-stream-view.js +1 -1
- package/dist/forms-ui.d.cts +227 -667
- package/dist/forms-ui.d.ts +227 -667
- package/dist/history-shell-QDQ44PSE.js +3 -0
- package/dist/history-shell.js +3 -0
- package/dist/{history-view-BD6OXLNA.js → history-view-NCFBI5GR.js} +2 -2
- package/dist/history-view.cjs +2 -2
- package/dist/history-view.d.cts +35 -1
- package/dist/history-view.d.ts +35 -1
- package/dist/history-view.js +2 -2
- package/dist/index.cjs +80 -74
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +233 -738
- package/dist/index.d.ts +233 -738
- package/dist/index.global.js +3 -215
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +81 -75
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +3 -67
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +22 -22
- package/dist/runtype-tts-entry-NFBVWR7N.js +1 -0
- package/dist/runtype-tts.js +1 -1
- package/dist/session-actions-ISSKSI66.js +1 -0
- package/dist/session-actions.js +1 -0
- package/dist/session-reconnect.d.cts +186 -8
- package/dist/session-reconnect.d.ts +186 -8
- package/dist/smart-dom-reader.cjs +13 -13
- package/dist/smart-dom-reader.d.cts +186 -8
- package/dist/smart-dom-reader.d.ts +186 -8
- package/dist/smart-dom-reader.js +11 -11
- package/dist/theme-editor-preview.cjs +116 -98
- package/dist/theme-editor-preview.d.cts +188 -8
- package/dist/theme-editor-preview.d.ts +188 -8
- package/dist/theme-editor-preview.js +49 -54
- package/dist/theme-editor.cjs +2 -2
- package/dist/theme-editor.d.cts +187 -23
- package/dist/theme-editor.d.ts +187 -23
- package/dist/theme-editor.js +2 -2
- package/dist/theme-reference.d.cts +14 -0
- package/dist/theme-reference.d.ts +14 -0
- package/dist/ui-extras-entry-WAYFKVNW.js +3 -0
- package/dist/ui-extras.js +72 -0
- package/dist/voice-runtime-XLU6YK2N.js +17 -0
- package/dist/voice-runtime.cjs +17 -1
- package/dist/voice-runtime.d.cts +11656 -232
- package/dist/voice-runtime.d.ts +11656 -232
- package/dist/voice-runtime.js +17 -1
- package/dist/voice-worklet-player.cjs +19 -4
- package/dist/voice-worklet-player.d.cts +9 -10
- package/dist/voice-worklet-player.d.ts +9 -10
- package/dist/voice-worklet-player.js +19 -4
- package/dist/webmcp-polyfill.js +1 -1
- package/dist/webmcp-runtime-V6ZWW3PI.js +6 -0
- package/dist/webmcp-runtime.cjs +2 -2
- package/dist/webmcp-runtime.d.cts +1 -33
- package/dist/webmcp-runtime.d.ts +1 -33
- package/dist/webmcp-runtime.js +2 -2
- package/dist/widget.css +1 -1
- package/package.json +11 -5
- package/src/approval-paused-tool-settle.test.ts +325 -0
- package/src/client-approve.test.ts +311 -0
- package/src/client-history-eager.ts +9 -0
- package/src/client-history-loader.ts +23 -0
- package/src/client-history.ts +579 -0
- package/src/client-resume.ts +177 -0
- package/src/client-stream-eager.ts +12 -0
- package/src/client-stream-loader.ts +25 -0
- package/src/client-stream.ts +1880 -0
- package/src/client.test.ts +31 -1
- package/src/client.ts +293 -2607
- package/src/components/approval-actions.test.ts +27 -0
- package/src/components/approval-actions.ts +27 -3
- package/src/components/message-bubble.test.ts +19 -0
- package/src/components/message-bubble.ts +2 -0
- package/src/components/registry.ts +6 -6
- package/src/components/tool-bubble.test.ts +9 -0
- package/src/components/tool-bubble.ts +1 -0
- package/src/history-shell-bundle.test.ts +54 -0
- package/src/history-shell-eager.ts +12 -0
- package/src/history-shell-loader.ts +27 -0
- package/src/history-shell.ts +2362 -0
- package/src/history-view-loader.ts +2 -0
- package/src/history-view.ts +3 -0
- package/src/index-core.ts +6 -0
- package/src/index-global.ts +90 -248
- package/src/index.ts +13 -0
- package/src/install.ts +6 -4
- package/src/internal/runtype-history-provider.test.ts +1 -0
- package/src/internal/runtype-history-provider.ts +28 -13
- package/src/plugins/registry.ts +8 -8
- package/src/session-actions-chunk.test.ts +55 -0
- package/src/session-actions-eager.ts +11 -0
- package/src/session-actions-loader.ts +37 -0
- package/src/session-actions.ts +909 -0
- package/src/session-history.test.ts +3 -1
- package/src/session.ts +895 -1538
- package/src/session.voice.test.ts +1171 -5
- package/src/styles/widget.css +58 -0
- package/src/theme-editor/state.ts +91 -91
- package/src/types.ts +204 -5
- package/src/ui-ask-user-sheet.ts +382 -0
- package/src/ui-extras-eager.ts +10 -0
- package/src/ui-extras-entry.ts +9 -0
- package/src/ui-extras-loader.ts +26 -0
- package/src/ui.artifact-rail-resize.test.ts +2 -1
- package/src/ui.ask-user-chunk.test.ts +93 -0
- package/src/ui.history-chunk.test.ts +2 -1
- package/src/ui.history-config-provider.test.ts +2 -1
- package/src/ui.history-confirm-fallback.test.ts +142 -0
- package/src/ui.history-controller.test.ts +2 -1
- package/src/ui.history-lifecycle.test.ts +2 -1
- package/src/ui.history-render-hooks.test.ts +2 -1
- package/src/ui.history-shell.test.ts +2 -1
- package/src/ui.rail-overlay.test.ts +2 -1
- package/src/ui.rail-resize.test.ts +2 -1
- package/src/ui.rail-trigger-pending.test.ts +2 -1
- package/src/ui.ts +340 -2770
- package/src/utils/attachment-manager.ts +67 -67
- package/src/utils/constants.ts +3 -0
- package/src/utils/context-mention-controller.ts +323 -323
- package/src/utils/context-mention-manager.ts +40 -40
- package/src/utils/context-mention-orchestrator.ts +28 -0
- package/src/utils/event-stream-buffer.ts +50 -50
- package/src/utils/event-stream-store.ts +43 -43
- package/src/utils/throughput-tracker.ts +34 -34
- package/src/utils/virtual-scroller.ts +67 -67
- package/src/utils/visitor-store.test.ts +50 -0
- package/src/utils/visitor-store.ts +23 -5
- package/src/voice/__fixtures__/voice-wire/README.md +1 -0
- package/src/voice/__fixtures__/voice-wire/client/cancel.json +3 -0
- package/src/voice/__fixtures__/voice-wire/client/context.json +4 -0
- package/src/voice/__fixtures__/voice-wire/client/delegation_result.json +6 -0
- package/src/voice/__fixtures__/voice-wire/client/delegation_update.json +6 -0
- package/src/voice/__fixtures__/voice-wire/client/ping.json +3 -0
- package/src/voice/__fixtures__/voice-wire/client/playback_progress.json +5 -0
- package/src/voice/__fixtures__/voice-wire/client/start.json +3 -0
- package/src/voice/__fixtures__/voice-wire/server/artifact.json +11 -0
- package/src/voice/__fixtures__/voice-wire/server/attached.json +4 -0
- package/src/voice/__fixtures__/voice-wire/server/audio_clear.json +4 -0
- package/src/voice/__fixtures__/voice-wire/server/audio_end.json +3 -0
- package/src/voice/__fixtures__/voice-wire/server/delegation_cancelled.json +5 -0
- package/src/voice/__fixtures__/voice-wire/server/delegation_completed.json +8 -0
- package/src/voice/__fixtures__/voice-wire/server/delegation_started.json +15 -0
- package/src/voice/__fixtures__/voice-wire/server/error.json +6 -0
- package/src/voice/__fixtures__/voice-wire/server/metrics.json +10 -0
- package/src/voice/__fixtures__/voice-wire/server/pong.json +3 -0
- package/src/voice/__fixtures__/voice-wire/server/session_config.json +16 -0
- package/src/voice/__fixtures__/voice-wire/server/transcript_final.json +7 -0
- package/src/voice/__fixtures__/voice-wire/server/transcript_interim.json +4 -0
- package/src/voice/__fixtures__/voice-wire/server/transcript_partial.json +6 -0
- package/src/voice/__fixtures__/voice-wire/server/transcript_update.json +10 -0
- package/src/voice/__fixtures__/voice-wire/server/warning.json +5 -0
- package/src/voice/audio-playback-manager.test.ts +57 -0
- package/src/voice/audio-playback-manager.ts +120 -98
- package/src/voice/browser-voice-provider.ts +37 -37
- package/src/voice/fallback-speech-engine.ts +22 -16
- package/src/voice/keyed-voice-transcript.ts +314 -0
- package/src/voice/mic-state-styles.ts +182 -0
- package/src/voice/read-aloud-controller.ts +46 -44
- package/src/voice/runtype-speech-engine.ts +35 -33
- package/src/voice/runtype-voice-provider.ts +680 -189
- package/src/voice/session-voice-wiring.ts +266 -0
- package/src/voice/voice-delegation.test.ts +71 -0
- package/src/voice/voice-delegation.ts +364 -0
- package/src/voice/voice-turn-tracker.ts +6 -6
- package/src/voice/voice.test.ts +1060 -8
- package/src/voice/worklet-playback-engine.test.ts +81 -0
- package/src/voice/worklet-playback-engine.ts +21 -3
- package/src/voice-runtime-loader.ts +4 -1
- package/src/voice-runtime.ts +7 -0
- package/src/webmcp-runtime-entry.ts +41 -39
- package/dist/approval-ui-3NMYNXBD.js +0 -1
- package/dist/chunk-5EIIHQLQ.js +0 -1
- package/dist/chunk-7CO4T5KB.js +0 -1
- package/dist/chunk-EFJBUH5F.js +0 -1
- package/dist/chunk-R2TMIMDI.js +0 -3
- package/dist/chunk-UTVLOTWB.js +0 -9
- package/dist/context-mentions-45MODWOY.js +0 -161
- package/dist/event-stream-view-GL3ADRY2.js +0 -1
- package/dist/runtype-tts-entry-UJAEF7NZ.js +0 -1
- package/dist/voice-runtime-7DA7MJH4.js +0 -1
- package/dist/webmcp-runtime-JI7T4QYF.js +0 -6
package/dist/index.global.js
CHANGED
|
@@ -1,219 +1,7 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var FE=Object.create;var wc=Object.defineProperty;var UE=Object.getOwnPropertyDescriptor;var qE=Object.getOwnPropertyNames;var VE=Object.getPrototypeOf,$E=Object.prototype.hasOwnProperty;var yo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var mx=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),jE=(e,t)=>{for(var o in t)wc(e,o,{get:t[o],enumerable:!0})},gx=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of qE(t))!$E.call(e,r)&&r!==o&&wc(e,r,{get:()=>t[r],enumerable:!(n=UE(t,r))||n.enumerable});return e};var no=(e,t,o)=>(o=e!=null?FE(VE(e)):{},gx(t||!e||!e.__esModule?wc(o,"default",{value:e,enumerable:!0}):o,e)),zE=e=>gx(wc({},"__esModule",{value:!0}),e);var fg=mx(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.Allow=me.ALL=me.COLLECTION=me.ATOM=me.SPECIAL=me.INF=me._INFINITY=me.INFINITY=me.NAN=me.BOOL=me.NULL=me.OBJ=me.ARR=me.NUM=me.STR=void 0;me.STR=1;me.NUM=2;me.ARR=4;me.OBJ=8;me.NULL=16;me.BOOL=32;me.NAN=64;me.INFINITY=128;me._INFINITY=256;me.INF=me.INFINITY|me._INFINITY;me.SPECIAL=me.NULL|me.BOOL|me.INF|me.NAN;me.ATOM=me.STR|me.NUM|me.SPECIAL;me.COLLECTION=me.ARR|me.OBJ;me.ALL=me.ATOM|me.COLLECTION;me.Allow={STR:me.STR,NUM:me.NUM,ARR:me.ARR,OBJ:me.OBJ,NULL:me.NULL,BOOL:me.BOOL,NAN:me.NAN,INFINITY:me.INFINITY,_INFINITY:me._INFINITY,INF:me.INF,SPECIAL:me.SPECIAL,ATOM:me.ATOM,COLLECTION:me.COLLECTION,ALL:me.ALL};me.default=me.Allow});var Kc=mx(lo=>{"use strict";var T0=lo&&lo.__createBinding||(Object.create?(function(e,t,o,n){n===void 0&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}):(function(e,t,o,n){n===void 0&&(n=o),e[n]=t[o]})),E0=lo&&lo.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&T0(t,e,o)};Object.defineProperty(lo,"__esModule",{value:!0});lo.Allow=lo.MalformedJSON=lo.PartialJSON=lo.parseJSON=lo.parse=void 0;var xo=fg();Object.defineProperty(lo,"Allow",{enumerable:!0,get:function(){return xo.Allow}});E0(fg(),lo);var jc=class extends Error{};lo.PartialJSON=jc;var zc=class extends Error{};lo.MalformedJSON=zc;function iC(e,t=xo.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return P0(e.trim(),t)}lo.parseJSON=iC;var P0=(e,t)=>{let o=e.length,n=0,r=h=>{throw new jc(`${h} at position ${n}`)},a=h=>{throw new zc(`${h} at position ${n}`)},i=()=>(m(),n>=o&&r("Unexpected end of input"),e[n]==='"'?d():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||xo.Allow.NULL&t&&o-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||xo.Allow.BOOL&t&&o-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||xo.Allow.BOOL&t&&o-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||xo.Allow.INFINITY&t&&o-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||xo.Allow._INFINITY&t&&1<o-n&&o-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||xo.Allow.NAN&t&&o-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),d=()=>{let h=n,y=!1;for(n++;n<o&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(h,++n-Number(y)))}catch(x){a(String(x))}else if(xo.Allow.STR&t)try{return JSON.parse(e.substring(h,n-Number(y))+'"')}catch{return JSON.parse(e.substring(h,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,m();let h={};try{for(;e[n]!=="}";){if(m(),n>=o&&xo.Allow.OBJ&t)return h;let y=d();m(),n++;try{let x=i();h[y]=x}catch(x){if(xo.Allow.OBJ&t)return h;throw x}m(),e[n]===","&&n++}}catch{if(xo.Allow.OBJ&t)return h;r("Expected '}' at end of object")}return n++,h},u=()=>{n++;let h=[];try{for(;e[n]!=="]";)h.push(i()),m(),e[n]===","&&n++}catch{if(xo.Allow.ARR&t)return h;r("Expected ']' at end of array")}return n++,h},p=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(xo.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(y))}}let h=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==o&&!(xo.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(h,n))}catch{e.substring(h,n)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(h,e.lastIndexOf("e")))}catch(x){a(String(x))}}},m=()=>{for(;n<o&&`
|
|
2
|
-
\r `.includes(e[n]);)n++};return i()},k0=iC;lo.parse=k0});var AR={};jE(AR,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Sg,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Cg,ASK_USER_QUESTION_TOOL_NAME:()=>Ll,AgentWidgetClient:()=>Zs,AgentWidgetSession:()=>ci,AttachmentManager:()=>ta,BrowserSpeechEngine:()=>ea,DEFAULT_COMPONENTS:()=>cw,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ax,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Gs,DEFAULT_PALETTE:()=>iw,DEFAULT_SEMANTIC:()=>dw,DEFAULT_WIDGET_CONFIG:()=>Tx,HistoryProviderError:()=>pn,PRESETS:()=>yy,PRESET_FULLSCREEN:()=>hy,PRESET_MINIMAL:()=>gy,PRESET_SHOP:()=>my,ReadAloudController:()=>di,SUGGEST_REPLIES_CLIENT_TOOL:()=>Yc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>vg,SUGGEST_REPLIES_TOOL_NAME:()=>Vn,THEME_ZONES:()=>pw,VERSION:()=>xr,WEBMCP_TOOL_PREFIX:()=>El,applyFeaturePreferences:()=>Qh,applyThemeVariables:()=>na,attachHeaderToContainer:()=>aa,buildComposer:()=>da,buildDefaultHeader:()=>vh,buildHeader:()=>Sr,buildHeaderWithLayout:()=>yi,buildMinimalHeader:()=>xh,builtInClientToolsForDispatch:()=>si,canonicalArtifactDisplayMode:()=>Bo,collectEnrichedPageContext:()=>vM,componentRegistry:()=>Mn,createActionManager:()=>ld,createAgentExperience:()=>up,createAskUserQuestionBubble:()=>xC,createBubbleWithLayout:()=>Qw,createCSATFeedback:()=>lp,createComboButton:()=>ju,createComponentMiddleware:()=>YA,createComponentStreamParser:()=>sp,createDefaultSanitizer:()=>ig,createDirectivePostprocessor:()=>Fx,createDropdownMenu:()=>ia,createFlexibleJsonStreamParser:()=>TC,createIconButton:()=>la,createImagePart:()=>lu,createJsonStreamParser:()=>su,createLabelButton:()=>bh,createLocalStorageAdapter:()=>np,createMarkdownProcessor:()=>Ml,createMarkdownProcessorFromConfig:()=>Tl,createMessageActions:()=>Th,createNPSFeedback:()=>dp,createPlainTextParser:()=>nu,createRegexJsonParser:()=>ru,createSplitButton:()=>qw,createStandardBubble:()=>bi,createTextPart:()=>un,createTheme:()=>ql,createThemeObserver:()=>fi,createToggleGroup:()=>Uw,createTypingIndicator:()=>ca,createWidgetHostLayout:()=>cd,createXmlParser:()=>au,defaultActionHandlers:()=>ma,defaultJsonActionParser:()=>id,defaultParseRules:()=>py,detectColorScheme:()=>$l,directivePostprocessor:()=>Ux,ensureAskUserQuestionSheet:()=>ri,escapeHtml:()=>hr,extractComponentDirectiveFromMessage:()=>ip,fileToImagePart:()=>LC,formatEnrichedContext:()=>xM,generateAssistantMessageId:()=>Zr,generateMessageId:()=>sC,generateStableSelector:()=>fy,generateUserMessageId:()=>ti,getActiveTheme:()=>An,getAgentWidgetHandles:()=>iM,getColorScheme:()=>oa,getDisplayText:()=>iu,getHeaderLayout:()=>Ch,getImageParts:()=>kC,getPreset:()=>SM,hasComponentDirective:()=>dd,hasImages:()=>li,headerLayouts:()=>zu,initAgentWidget:()=>lM,isAskUserQuestionMessage:()=>yr,isComponentDirectiveType:()=>QA,isDockedMountMode:()=>yt,isHistoryProviderError:()=>ZC,isSuggestRepliesMessage:()=>Js,isWebMcpToolName:()=>Yr,isWelcomeVisible:()=>ds,latestAgentSuggestions:()=>Jc,listRegisteredStreamAnimations:()=>uh,loadMarkdownParsers:()=>qc,markdownPostprocessor:()=>ag,mergeWithDefaults:()=>Ya,normalizeContent:()=>PC,normalizeMediaType:()=>Jr,onMarkdownParsersReady:()=>ei,parseAskUserQuestionPayload:()=>br,parseSuggestRepliesPayload:()=>xg,parseWidgetPreferenceSlice:()=>Xh,pickBestVoice:()=>Ol,pluginRegistry:()=>ad,registerIcons:()=>Ix,registerStreamAnimationPlugin:()=>mi,removeAskUserQuestionSheet:()=>os,renderComponentDirective:()=>ap,renderLoadingIndicatorWithFallback:()=>Mh,renderLucideIcon:()=>ae,resolveArtifactDisplay:()=>pg,resolveArtifactDisplayMode:()=>qn,resolveConfigPreferences:()=>sd,resolveDockConfig:()=>Oo,resolveSanitizer:()=>Vc,resolveTokens:()=>Wu,resolveWelcomeConfig:()=>xi,stripWebMcpPrefix:()=>ug,themeToCssVariables:()=>Bu,unregisterStreamAnimationPlugin:()=>ch,validateImageFile:()=>IC,validateTheme:()=>oh});var Ga=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var lm=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var dm=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var fl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var cm=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var um=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var pm=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var fm=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Xa=[["path",{d:"M20 6 9 17l-5-5"}]];var ml=[["path",{d:"m6 9 6 6 6-6"}]];var mm=[["path",{d:"m15 18-6-6 6-6"}]];var gm=[["path",{d:"m9 18 6-6-6-6"}]];var $s=[["path",{d:"m18 15-6-6-6 6"}]];var hm=[["circle",{cx:"12",cy:"12",r:"10"}]];var ym=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var bm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var vm=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Ac=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Qa=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var xm=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Mc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Tc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Cm=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var Sm=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var gl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var hl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var js=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var yl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var wm=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Am=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Ec=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Mm=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Tm=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Em=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var bl=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Pm=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var km=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Lm=[["path",{d:"M5 12h14"}]];var Pc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Im=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Rm=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Hm=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Wm=[["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"}]];var Bm=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Dm=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Om=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var _m=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Nm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var kc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Fm=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Um=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var qm=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Vm=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var $m=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var jm=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var zm=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Km=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var vl=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Tt=(e,t=24,o="currentColor",n=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(n)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let i=a[0],d=a[1];if(!d)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(d).forEach(([u,p])=>{u!=="stroke"&&c.setAttribute(u,String(p))}),r.appendChild(c)}),r};var hx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Sn(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];hx(a)&&hx(r)?o[n]=Sn(a,r):o[n]=r}return o}var Gm=Symbol("persona.defaultsProvenance"),Xm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Lc(e,t=""){return Object.entries(e).flatMap(([o,n])=>{let r=t?`${t}.${o}`:o;return Xm(n)?Lc(n,r):[r]})}function yx(e,t){for(let o of t.split(".")){if(!Xm(e)||!Object.prototype.hasOwnProperty.call(e,o))return"absent";if(e=e[o],e===void 0)return"clear"}return"explicit"}function bx(e,t){return e?.[Gm]??t.filter(o=>yx(e,o)==="explicit")}function Qm(e,t){return Object.defineProperty(e,Gm,{value:t,enumerable:!0,configurable:!0}),e}function Ym(e,t,o){return Qm(e,bx(t,Lc(o)))}function vx(e,t,o){let n=t[Gm];if(n)return n;let r=new Set(bx(e,o));for(let a of o){let i=yx(t,a);i==="clear"&&r.delete(a),i==="explicit"&&r.add(a)}return[...r]}function xx(e,t,o){let n={...e};for(let r of t){if(o.includes(r))continue;let a=r.split("."),i=n;for(let d of a.slice(0,-1)){let c=i[d];if(!Xm(c)){i=void 0;break}i[d]={...c},i=i[d]}i&&delete i[a[a.length-1]]}return n}var Cx="var(--persona-components-panel-width)",Jm=Symbol("persona.panelAliasProvenance"),zs=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),Ic=(e,t)=>zs(e,t)&&e[t]!==void 0,KE=e=>({launcherWidth:Ic(e?.launcher,"width"),legacyLauncherWidth:Ic(e,"launcherWidth"),sidebarWidth:Ic(e?.launcher,"sidebarWidth"),dockWidth:Ic(e?.launcher?.dock,"width")}),fr=e=>{let t=e?.[Jm];return t?{...t}:KE(e)},Zm=(e,t)=>(Object.defineProperty(e,Jm,{value:t,enumerable:!0,configurable:!0}),e),eg=(e,t)=>Zm(e,fr(t)),Sx=(e,t)=>{let o=t[Jm];if(o)return{...o};let n=fr(e);return zs(t,"launcherWidth")&&(n.legacyLauncherWidth=t.launcherWidth!==void 0),zs(t,"launcher")&&t.launcher===void 0?(n.launcherWidth=!1,n.sidebarWidth=!1,n.dockWidth=!1,n):(zs(t.launcher,"width")&&(n.launcherWidth=t.launcher?.width!==void 0),zs(t.launcher,"sidebarWidth")&&(n.sidebarWidth=t.launcher?.sidebarWidth!==void 0),zs(t.launcher,"dock")&&t.launcher?.dock===void 0?n.dockWidth=!1:zs(t.launcher?.dock,"width")&&(n.dockWidth=t.launcher?.dock?.width!==void 0),n)};var Gs="min(440px, calc(100vw - 24px))",Ax="440px",Sl="40px",tg="How can I help...",mr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Xs={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},GE={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Gs,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Sl,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)"},XE={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:GE,copy:{inputPlaceholder:tg,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",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:mr,reasoningDisplay:Xs,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1},QE={},YE={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Ks={launcher:YE,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 Xr(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function Mx(e){let t=Xr(e)==="v5"?Ks:QE;return Sn(XE,t)}var Tx=Mx();function wx(e,t){if(!(!e&&!t))return e?t?Sn(e,t):e:t}function Ya(e){let t=Mx(e);return e?Ym(eg({...t,...e,theme:wx(t.theme,e.theme),darkTheme:wx(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 o=t.features?.artifacts,n=e.features?.artifacts,r=t.features?.scrollToBottom,a=e.features?.scrollToBottom,i=t.features?.scrollBehavior,d=e.features?.scrollBehavior,c=t.features?.streamAnimation,u=e.features?.streamAnimation,p=t.features?.askUserQuestion,m=e.features?.askUserQuestion,h=t.features?.history,y=e.features?.history,x=o===void 0&&n===void 0?void 0:{...o,...n,layout:{...o?.layout,...n?.layout}},C=r===void 0&&a===void 0?void 0:{...r,...a},E=i===void 0&&d===void 0?void 0:{...i,...d},A=c===void 0&&u===void 0?void 0:{...c,...u},M=p===void 0&&m===void 0?void 0:{...p,...m,styles:{...p?.styles,...m?.styles}},L=h===void 0&&y===void 0?void 0:{...h,...y,copy:{...h?.copy,...y?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...C!==void 0?{scrollToBottom:C}:{},...E!==void 0?{scrollBehavior:E}:{},...x!==void 0?{artifacts:x}:{},...A!==void 0?{streamAnimation:A}:{},...M!==void 0?{askUserQuestion:M}:{},...L!==void 0?{history:L}:{}}})(),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,Ks):Ym(eg(t),void 0,Ks)}var I=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o};var Q=(e,t={},...o)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),t.attrs)for(let[a,i]of Object.entries(t.attrs))n.setAttribute(a,i);if(t.style){let a=n.style,i=t.style;for(let d of Object.keys(i)){let c=i[d];c!=null&&(a[d]=c)}}let r=o.filter(a=>a!=null);return r.length>0&&n.append(...r),n},bo=(...e)=>e.filter(Boolean).join(" ");var vt=e=>{let{fallbackImport:t,resetOnSetLoader:o=!1}=e,n=null,r=null,a=null;return{setLoader:p=>{n=p,o&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(n??t)().then(m=>(r=m,m)).catch(m=>{throw a=null,m}),a),provide:p=>{r=p},getSync:()=>r}};var{setLoader:JE,load:ZE}=vt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Ex=JE,Rc=ZE;var e0={activity:Ga,"arrow-down":lm,"arrow-up":um,"arrow-up-right":cm,bot:fm,"chevron-down":ml,"chevron-up":$s,"chevron-right":gm,"chevron-left":mm,check:Xa,clipboard:bm,"clipboard-copy":ym,"code-xml":Ac,copy:Qa,file:yl,"file-code":gl,"file-spreadsheet":hl,"file-text":js,"image-plus":Am,loader:Mm,"loader-circle":Ec,mic:Pm,paperclip:Im,quote:Wm,"refresh-cw":Bm,search:Dm,send:Om,"shield-alert":_m,"shield-check":Nm,"shield-x":kc,square:Fm,"thumbs-down":qm,"thumbs-up":Vm,upload:zm,"volume-2":Km,x:vl,"at-sign":pm,"arrow-left":dm,"arrow-right":fl,"external-link":Cm,ellipsis:Tc,"ellipsis-vertical":Mc,menu:Em,"panel-left":Pc,plus:Hm,minus:Lm,pencil:Rm,trash:jm,"trash-2":$m,download:xm,maximize:Tm,minimize:km,"message-square":bl,star:Um,eye:Sm,history:wm},t0=["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"],wl=new Map(Object.entries(e0)),Ja=new Set,Hc=!1,Wc=new Set,Px=e=>{let t=[...Wc];e&&Wc.clear();for(let o of t)try{o()}catch{}},kx=e=>Hc?()=>{}:(Wc.add(e),()=>{Wc.delete(e)}),Lx=()=>{let e=0;for(let t of[...Ja]){let o=wl.get(t.name);if(!o)continue;Ja.delete(t),e++;let n=Tt(o,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},Ix=e=>{for(let[t,o]of Object.entries(e))wl.set(t,o);Lx()>0&&!Hc&&Px(!1)};var og=!1,o0=()=>{Rc().then(e=>{if(!Hc){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))wl.has(t)||wl.set(t,o);Hc=!0,Lx(),Px(!0)}}).catch(e=>{og=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},n0=(e,t,o)=>{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(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n},ae=(e,t=24,o="currentColor",n=2)=>{let r=wl.get(e);if(r)return Tt(r,t,o,n);if(t0.includes(e)){og&&(og=!1);let a=n0(t,o,n);if(Ja.size>=500){let i=Ja.values().next().value;i&&Ja.delete(i)}return Ja.add({el:a,name:e,size:t,color:o,strokeWidth:n}),o0(),a}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};var r0=["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"],s0="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",a0="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",i0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Bc=(e,t)=>{let o=I("div",["persona-message-bubble",e,...r0].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Dc=e=>{let t=I("button",e.expandable?s0:a0);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},ng=(e,t,o)=>{e.innerHTML="";let n=Tt(t?$s:ml,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Za=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=I("div","persona-flex persona-items-center");ng(n,o.expanded,o.iconColor);let r=I("div",o.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(n),e.append(t,r),n},Oc=e=>{let t=I("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 o=e.renderPreview?.();i0(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},_c=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&ng(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"},Nc=(e,t,o)=>{let n=o.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${o.previewKind}"]`);if(!r||!a)return;r.setAttribute("aria-expanded",n?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&ng(c,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};function Fc(e,t){let o=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[o]:{...t==="tool"?mr:Xs,...e?.future?.v5Defaults===!0?Ks.features?.[o]:{},...e?.features?.[o]}}}}function Qr(e,t){let o=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[o]?.variant??(e?.future?.v5Defaults?"row":"card")}function Al(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 gr(e,t,o,n){if(Qr(o,n)!=="row")return e;e.className=`persona-message-bubble persona-${n}-bubble persona-activity-row`,e.dataset.activityKind=n,n==="tool"&&o.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let a=n==="tool"?t.toolCall:t.reasoning,i=a?.status!=="complete",d=t.approval?.status??t.toolCall?.approvalStatus,c=d==="denied"?"denied":d==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?a?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let u=I("span","persona-activity-icon");u.dataset.activityIcon=c;let p={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=n==="reasoning"?o.features?.reasoningDisplay?.iconName:void 0,h=m?ae(m,16,"currentColor",2):c==="pending"?Tt(hm,16,"currentColor",2):c==="awaiting-approval"?Tt(vm,16,"currentColor",2):ae(p[c],16,"currentColor",2);h&&u.appendChild(h),r.querySelector(".persona-reasoning-header-icon")?.remove();let y=n==="tool"?"toolCallDisplay":"reasoningDisplay",x=o.features?.[y]?.iconVisibility??(o.future?.v5Defaults?"active":"always");if((x==="always"||x==="active"&&c!=="done")&&r.prepend(u),n==="tool"&&a){let M=I("span","persona-activity-duration");i&&a.startedAt&&M.setAttribute("data-tool-elapsed",String(a.startedAt));let L=(n==="tool"?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);M.textContent=L===void 0?"":Al(L),r.appendChild(M)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function Rx(e){let t=new Set,o=new Set,n=new Set,r=new Map,a=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,d,c,u={}){let p=d==="tool"?i.toolCall:i.reasoning;if(!(!p||o.has(i.id))&&(!t.has(i.id)&&p.status!=="complete"&&p.chunks?.some(Boolean)&&(t.add(i.id),u.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&p.status==="complete"&&!n.has(i.id))){if(n.add(i.id),u.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,d)},u.autoCollapseDelay??1e3))}},manual(i){o.add(i),a(i)},prune(i){for(let d of new Set([...t,...o,...n]))i.has(d)||(a(d),t.delete(d),o.delete(d),n.delete(d))},clear(){for(let i of r.keys())a(i);t.clear(),o.clear(),n.clear()}}}function Hx(e,t,o,n){let r=I("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let a=I("button","");a.type="button",a.dataset.expandHeader="true",a.dataset.bubbleType="tool",a.setAttribute("aria-expanded",String(o));let i=I("div","");typeof n=="string"?i.textContent=n:i.appendChild(n),Za(a,i,{expandable:!0,expanded:o,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let d=I("div","persona-border-t");return d.id=`activity-details-${e.id}`,d.style.display=o?"":"none",a.setAttribute("aria-controls",d.id),r.append(a,d),gr(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:d}}var l0=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),Qs=(e,t,o)=>{let n=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=l0(t,o)||n&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!n),e.classList.toggle("persona-mb-2",n)},rg=(e,t,o)=>{!t.parentElement||e.parentElement!==t.parentElement||(o.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function Wx(e,t){let o=e.voiceRecognition,n=t.voiceRecognition;return o?.enabled===!0!=(n?.enabled===!0)||o?.provider?.type!==n?.provider?.type||o?.provider?.custom!==n?.provider?.custom||o?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(o?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function vo(e){return e?.type==="runtype"||e?.type==="custom"}var d0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Bx(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,o=typeof t=="function"?t():t;return!!o&&typeof o.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:d0()}catch{return!1}}var{setLoader:c0,load:u0,provide:vB,getSync:sg}=vt({fallbackImport:()=>import("./markdown-parsers-entry")}),Uc=new Set,p0=()=>{let e=[...Uc];Uc.clear();for(let t of e)try{t()}catch{}},Dx=c0,qc=()=>{let e=sg();return e?Promise.resolve(e):u0().then(t=>(p0(),t))},ei=e=>sg()?()=>{}:(Uc.add(e),()=>{Uc.delete(e)});var Un=sg;var f0=e=>{if(!e)return;let t={},o=e;if(o.heading){let n=o.heading;t.heading=(r,a,i)=>n({type:"heading",raw:i,depth:a,text:r,tokens:[]})}if(o.code){let n=o.code;t.code=(r,a,i)=>n({type:"code",raw:"",text:r,lang:a,escaped:i})}if(o.blockquote){let n=o.blockquote;t.blockquote=r=>n({type:"blockquote",raw:"",text:r,tokens:[]})}if(o.table){let n=o.table;t.table=(r,a)=>n({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:a})}if(o.link){let n=o.link;t.link=(r,a,i)=>n({type:"link",raw:"",href:r,title:a??null,text:i,tokens:[]})}if(o.image){let n=o.image;t.image=(r,a,i)=>n({type:"image",raw:"",href:r,title:a??null,text:i})}if(o.list){let n=o.list;t.list=(r,a,i)=>n({type:"list",raw:"",ordered:a,start:i,loose:!1,items:[],itemsHtml:r})}if(o.listitem){let n=o.listitem;t.listitem=(r,a,i)=>n({type:"list_item",raw:"",task:a,checked:i,loose:!1,text:r,tokens:[]})}if(o.paragraph){let n=o.paragraph;t.paragraph=r=>n({type:"paragraph",raw:"",text:r,tokens:[]})}if(o.codespan){let n=o.codespan;t.codespan=r=>n({type:"codespan",raw:"",text:r})}if(o.strong){let n=o.strong;t.strong=r=>n({type:"strong",raw:"",text:r,tokens:[]})}if(o.em){let n=o.em;t.em=r=>n({type:"em",raw:"",text:r,tokens:[]})}if(o.del){let n=o.del;t.del=r=>n({type:"del",raw:"",text:r,tokens:[]})}if(o.html){let n=o.html;t.html=r=>n({type:"html",raw:r,text:r})}if(o.text){let n=o.text;t.text=r=>n({type:"text",raw:r,text:r})}if(o.checkbox){let n=o.checkbox;t.checkbox=r=>n({checked:r})}return o.hr&&(t.hr=o.hr),o.br&&(t.br=o.br),t},Ml=e=>{let t=null;return o=>{let n=Un();if(!n)return hr(o);if(!t){let{Marked:r}=n,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let i=f0(e?.renderer);i&&t.use({renderer:i})}return t.parse(o)}},Tl=e=>e?Ml({markedOptions:e.options,renderer:e.renderer}):Ml(),m0=Ml(),ag=e=>m0(e),hr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),_x=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Ox=e=>`%%FORM_PLACEHOLDER_${e}%%`,Nx=(e,t)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let i=Ox(t.length);return t.push({token:i,type:String(a.type)}),i}}catch{return n}return n}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,r)=>{let a=Ox(t.length);return t.push({token:a,type:r}),a}),o},Fx=e=>{let t=Tl(e);return o=>{let n=[],r=Nx(o,n),a=t(r);return n.forEach(({token:i,type:d})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${_x(d)}"></div>`;a=a.replace(c,p)}),a}},Ux=e=>{let t=[],o=Nx(e,t),n=ag(o);return t.forEach(({token:r,type:a})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${_x(a)}"></div>`;n=n.replace(i,c)}),n};var g0={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"]},h0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ig=()=>{let e=null;return t=>{let o=Un();if(!o)return hr(t);if(!e){let{DOMPurify:n}=o;e=n(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let i=a.attrValue;i.toLowerCase().startsWith("data:")&&!h0.test(i)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,g0)}},Vc=e=>e===!1?null:typeof e=="function"?e:ig();var qx=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Vx=e=>e.includes("|"),$x=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(o=>o.trim())},y0=e=>`| ${e.join(" | ")} |`,b0=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,v0=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),jx=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
3
|
-
`),o=!1;for(let n=0;n<t.length-1;n++){let r=t[n],a=t[n+1];if(!Vx(r)||qx.test(r)||!qx.test(a))continue;let i=$x(r).length;if(i<1)continue;let d=b0(i);t[n+1]!==d&&(t[n+1]=d,o=!0);let c=n+2;for(;c<t.length;c++){let u=t[c];if(u.trim()===""||!Vx(u))break;let p=y0(v0($x(u),i));t[c]!==p&&(t[c]=p,o=!0)}n=c-1}return o?t.join(`
|
|
4
|
-
`):e};var zx="var(--persona-md-table-scroll-fade, 24px)",Kx=new WeakSet;function Xx(e){e.querySelectorAll("table").forEach(o=>{if(o.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",o.replaceWith(r),r.appendChild(o)})}function Gx(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let n=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty("--persona-fade-l",n<=1?"0px":zx),e.style.setProperty("--persona-fade-r",r<=1?"0px":zx)}function lg(e){Kx.has(e)||(Kx.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&Gx(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Gx)}var El="webmcp:",dg=new Map,Yx=e=>{dg.clear();for(let t of e){let o=t.title?.trim();o&&dg.set(t.name,o)}},$c=e=>dg.get(ug(e)),cg=null,Jx=e=>{cg=e};function Zx(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${x0(t.join(""))}`}function Qx(e,t){let o=3735928559^t,n=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);o=Math.imul(o^a,2654435761),n=Math.imul(n^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&n)+(o>>>0)}function x0(e){let t=Qx(e,0).toString(36),o=Qx(e,2654435761).toString(36);return`${t}.${o}`}var ug=e=>e.startsWith(El)?e.slice(El.length):e,Yr=e=>e.startsWith(El),eC=()=>cg?cg():import("@mcp-b/webmcp-polyfill");var{setLoader:C0,load:S0}=vt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),tC=C0,oC=S0;function Bo(e){return e==="card"?"collapsed":e}function Jr(e){return e.split(";",1)[0].trim().toLowerCase()}function w0(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if(Jr(r)===t)return{mode:Bo(a),selector:Jr(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if(Jr(r)===n)return{mode:Bo(a),selector:n}}function pg(e,t){let o=e?.display,n=typeof o=="string"?{default:o}:o??{};if(t.file&&n.files){if(typeof n.files=="string")return{mode:Bo(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?Jr(t.file.mimeType):void 0,c=d?w0(n.files.byMediaType,d):void 0;if(d&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:d,selector:c.selector}};if(n.files.default)return{mode:Bo(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:Bo(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Bo(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Bo(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:Bo(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function qn(e,t){return pg(e,t).mode}function Pl(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var A0="agent_",M0="flow_";function nC(e){return e.startsWith(A0)?{kind:"agentId",agentId:e}:e.startsWith(M0)?{kind:"flowId",flowId:e}:null}function rC(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let n=o.indexOf(":");if(n>0){let i=o.slice(0,n),d=o.slice(n+1);if(i==="runtype"){let u=nC(d);if(u)return u;throw new Error(`[Persona] target "runtype:${d}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(d).payload}}let r=nC(o);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function sC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ti(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Zr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function aC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var es=no(Kc(),1);var Ll="ask_user_question",kl=8,oi="data-persona-ask-sheet-for",L0="Other",I0="Other\u2026",dC="Type your own answer here",cC="Send",R0="Next",H0="Back",W0="Submit all",B0="Skip",D0=3,mg="data-ask-current-index",gg="data-ask-question-count",uC="data-ask-answers",hg="data-ask-grouped",pC="data-ask-layout",O0=e=>e.layout==="pills"?"pills":"rows",_0=e=>e.getAttribute(pC)==="pills"?"pills":"rows",lC=!1,fC=e=>e.replace(/["\\]/g,"\\$&"),yr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ll,Gc=e=>e?.features?.askUserQuestion??{},br=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:o};try{let r=n.join(""),a=(0,es.parse)(r,es.STR|es.OBJ|es.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},Il=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>kl&&!lC&&(lC=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${kl}.`)),t.slice(0,kl)},N0=e=>Il(e)[0]??null,F0=(e,t)=>Il(e)[t]??null,mC=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},gC=(e,t,o)=>{if(e!=="rows")return null;let n=I("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let r=I("span","persona-ask-row-check");n.appendChild(r)}else{let r=I("span","persona-ask-row-badge");r.textContent=String(o+1),n.appendChild(r)}return n},U0=(e,t,o,n)=>{let a=I("button",o==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let i=I("span","persona-ask-row-content"),d=I("span","persona-ask-row-label");if(d.textContent=e.label,i.appendChild(d),e.description){let u=I("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}a.appendChild(i);let c=gC(o,n,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},q0=e=>{let o=I("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return o.setAttribute("aria-hidden","true"),o},V0=(e,t,o,n)=>{let a=I("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!o){for(let p=0;p<D0;p++)a.appendChild(q0(n));return a}if(c.forEach((p,m)=>{a.appendChild(U0(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?L0:I0;if(n==="rows"){let m=I("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let h=I("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??dC,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let x=gC(n,i,c.length);x&&m.appendChild(x),a.appendChild(m)}else{let m=I("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??p,a.appendChild(m)}}return a},hC=(e,t)=>{let n=I("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??dC,r.setAttribute("data-ask-free-text-input","true"),n.appendChild(r),t!=="rows"){let a=I("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??cC,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},$0=e=>{let t=I("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=I("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??cC,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},j0=(e,t,o)=>{let n=I("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 r=I("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=o.backLabel??H0,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,n.appendChild(r);let a=I("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=I("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=o.skipLabel??B0,i.setAttribute("data-ask-user-action","skip"),a.appendChild(i);let d=I("button","persona-ask-nav-next persona-pointer-events-auto");d.type="button";let c=e===t-1;return d.textContent=c?o.submitAllLabel??W0:o.nextLabel??R0,d.setAttribute("data-ask-user-action",c?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Ys=e=>{let t=e.getAttribute(uC);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},yC=(e,t)=>{e.setAttribute(uC,JSON.stringify(t))},cn=e=>{let t=Number(e.getAttribute(mg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},z0=(e,t)=>{e.setAttribute(mg,String(Math.max(0,Math.floor(t))))},ni=e=>{let t=Number(e.getAttribute(gg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ts=e=>e.getAttribute(hg)==="true",K0=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let n={};return t.forEach((r,a)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(o,i)){let d=o[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},G0=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},Xc=(e,t)=>{let{payload:o}=br(t),n=Il(o),r=Ys(e),a={},i=new Set;return n.forEach((d,c)=>{let u=typeof d?.question=="string"?d.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,c)&&(a[u]=r[c]))}),a},bC=e=>{let t=Ys(e),o=cn(e),n=t[o],r=new Set;typeof n=="string"?r.add(n):Array.isArray(n)&&n.forEach(c=>r.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{let u=c.getAttribute("data-option-label")??"",p=r.has(u);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(a).map(c=>c.getAttribute("data-option-label")??"")),d=e.querySelector('[data-ask-free-text-input="true"]');d&&(typeof n=="string"&&n.length>0&&!i.has(n)?(d.value=n,d.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):d.value="")},vC=e=>{if(!ts(e))return;let t=Ys(e),o=cn(e),n=t[o],r=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let d=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=d.length===0}},yg=(e,t,o)=>{let n=Gc(o),r=_0(e),{payload:a,complete:i}=br(t),d=ts(e),c=cn(e),u=ni(e),p=d?F0(a,c):N0(a),m=!!p?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=d?`${c+1}/${u}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let M=typeof p?.question=="string"?p.question:"";x.textContent=M,x.classList.toggle("persona-ask-question-skeleton",!M&&!i)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let M=V0(p,n,i,r);C.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(hC(n,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!E?e.appendChild($0(n)):(!m||d)&&E&&E.remove(),e.setAttribute("data-multi-select",m?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(d){let M=j0(c,u,n);A?A.replaceWith(M):e.appendChild(M)}else A&&A.remove();bC(e),vC(e)},X0=(e,t,o)=>{let n=Gc(t),r=O0(n),a=e.toolCall.id,i=Il(o),d=Math.max(1,i.length),c=d>1,u=K0(e,i),p=c?G0(e,d):0,m=I("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(oi,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(gg,String(d)),m.setAttribute(mg,String(p)),m.setAttribute(hg,c?"true":"false"),m.setAttribute(pC,r),yC(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),mC(m,n);let h=I("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=I("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let x=I("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",h.appendChild(x),m.appendChild(h);let E=I("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),m.appendChild(E),r!=="rows"&&m.appendChild(hC(n,r)),yg(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Q0=(e,t,o)=>{let{payload:n}=br(t),r=Math.max(1,Il(n).length);r>ni(e)&&(e.setAttribute(gg,String(r)),r>1&&!ts(e)&&e.setAttribute(hg,"true")),yg(e,t,o)},xC=(e,t)=>{let o=I("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let n=Gc(t);mC(o,n);let r=I("span","persona-ask-stub-label"),{complete:a}=br(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},ri=(e,t,o)=>{if(!o||!yr(e)||Gc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${oi}]`).forEach(u=>{u.getAttribute(oi)!==r&&u.remove()});let i=o.querySelector(`[${oi}="${fC(r)}"]`);if(i){Q0(i,e,t);return}let{payload:d}=br(e),c=X0(e,t,d);o.appendChild(c)},os=(e,t)=>{if(!e)return;let o=t?`[${oi}="${fC(t)}"]`:`[${oi}]`;e.querySelectorAll(o).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},bg=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ns=(e,t)=>{let o=Ys(e),n=cn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,yC(e,o),bC(e),vC(e)},Qc=(e,t,o,n)=>{let r=ni(e),a=Math.max(0,Math.min(r-1,n));z0(e,a),yg(e,t,o)};var Vn="suggest_replies";var vg={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},Yc={name:Vn,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:vg,origin:"sdk",annotations:{readOnlyHint:!0}},SC=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Js=e=>e.variant==="tool"&&e.toolCall?.name===Vn,xg=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let n=o.flatMap(r=>{if(typeof r=="string"){let d=r.trim();return d?[d]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let i={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(i.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(i.description=a.description.trim()),[i]});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},Jc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Js(o))continue;let n=xg(o.toolCall?.args);return n.length>0?n:null}return null},CC=new Set,Y0=(e,t,o)=>{let n=`${e}:${t}:${o}`;CC.has(n)||(CC.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},rs=e=>{let t=e?.suggestions?.followUps,o=e?.features?.suggestReplies,n=i=>{let d=t?.[i],c=o?.[i];d===void 0||c===void 0||d!==c&&Y0(i,c,d)};e&&(n("enabled"),n("expose"));let r=t?.enabled??o?.enabled??!0,a=r?t?.expose??o?.expose??!1:!1;return{enabled:r,expose:a}};var Cg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:kl,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},Sg={name:Ll,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:Cg,origin:"sdk",annotations:{readOnlyHint:!0}},si=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(Sg),rs(e).expose&&t.push(Yc),t};var J0=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),Z0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let o=J0(t.toolName);return o?{call:{toolCallId:t.toolCallId,toolName:o,args:Z0(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:o,result:t.result}}:null},wg=(e,t)=>{let o=[],n=[],r=[],a="",i,d=()=>{n.length!==0&&(o.push({role:"assistant",content:"",createdAt:a,toolCalls:n},{role:"tool",content:"",createdAt:a,toolResults:r}),n=[],r=[])};for(let c of e){let u=eP(c);if(u){let m=c.agentMetadata?.clientToolAnswer?.batch;n.length>0&&(m===void 0||m!==i)&&d(),n.length===0&&(a=c.createdAt,i=m),n.some(h=>h.toolCallId===u.call.toolCallId)||(n.push(u.call),r.push(u.result));continue}let p=t(c);p&&(d(),o.push(p))}return d(),o};var vr=no(Kc(),1),Zc=e=>e.replace(/\\n/g,`
|
|
5
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ai=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},tP=e=>{let t=e.completedAt??Date.now(),o=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},wC=e=>e.status==="complete"?tP(e):e.status==="pending"?"Waiting":"",oP=15e3,nP=1200,AC=(e,t)=>{let o=t?.durationMs??oP,n=t?.chars??nP;return typeof e.durationMs=="number"?e.durationMs<o:(e.chunks??[]).join("").length<n},rP=e=>{let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var MC=e=>e.status==="complete"?rP(e):"Using tool...",eu=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Hl=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return eu(t)},tu=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return eu(t)},Ag=(e,t,o)=>{if(!t)return o;let n=e.name?.trim()||"tool",r=Hl(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,r)},ou=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),n=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,i;for(;(i=r.exec(o))!==null;)i.index>a&&Rl(n,o.slice(a,i.index),[]),i[1]!==void 0?Rl(n,i[1],["bold"]):i[2]!==void 0?Rl(n,i[2],["italic"]):i[3]!==void 0&&Rl(n,i[3],["dim"]),a=i.index+i[0].length;return a<o.length&&Rl(n,o.slice(a),[]),n},Rl=(e,t,o)=>{let n=t.split("{duration}");for(let r=0;r<n.length;r++)n[r]&&e.push({text:n[r],styles:o}),r<n.length-1&&e.push({text:"{duration}",styles:o,isDuration:!0})},sP=()=>{let e=null,t=0,o=n=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
6
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,d=n.match(i);if(d&&d[1])try{return d[1].replace(/\\n/g,`
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=o(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Wl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},nu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ru=()=>{let e=sP();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},su=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,vr.parse)(o,vr.STR|vr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Zc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Zc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},TC=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?Zc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Zc(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return i(a.on_load_text)||i(a.text)||null;case"message":case"message_and_click":case"checkout":return i(a.text)||null;default:return i(a.text)||i(a.display_text)||i(a.message)||null}return i(a.text)||i(a.display_text)||i(a.message)||i(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let i=a.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let d=(0,vr.parse)(a,vr.STR|vr.OBJ),c=r(d);c!==null&&(t=c)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},au=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var EC="4.25.0";var xr=EC;var ii="[Image]";function PC(e){return typeof e=="string"?[{type:"text",text:e}]:e}function iu(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function li(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function kC(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function un(e){return{type:"text",text:e}}function lu(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function LC(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function IC(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var RC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],iP=["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"],Cr=[...RC,...iP];function lP(e){return RC.includes(e)||e.startsWith("image/")}function du(e){return lP(e.type)}function HC(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function WC(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;du(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=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function BC(e,t=Cr,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function dP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function DC(e,t){let o=dP(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var cP=["user","assistant","system"],uP=0;function OC(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function cu(e){return typeof e=="string"?e:void 0}function pP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?un(t.text):null;case"image":return typeof t.image=="string"?lu(t.image,{mimeType:cu(t.mimeType),alt:cu(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?HC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...cu(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...cu(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function fP(e,t){let o=OC(t),n=e.map(i=>OC(i.timestamp)),r=new Array(e.length),a=0;for(;a<n.length;){let i=n[a];if(i!==null){r[a]=i,a+=1;continue}let d=a;for(;d+1<n.length&&n[d+1]===null;)d+=1;let c=d-a+1,u=a>0?r[a-1]:null,p=d+1<n.length?n[d+1]:null,m=p!==null&&o!==null?Math.min(p,o):p??o;for(let h=0;h<c;h+=1)r[a+h]=m!==null?m-(c-h):u!==null?u+h+1:uP+h;a=d+1}return r.map(i=>new Date(i).toISOString())}function _C(e,t){let o=fP(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!cP.includes(r.role))return;let i=r.role,d=o[a];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};n.push({id:r.id,role:i,content:"",createdAt:d,agentMetadata:c});return}if(typeof r.displayContent=="string"){n.push({id:r.id,role:i,content:r.displayContent,createdAt:d});return}if(typeof r.content=="string"){n.push({id:r.id,role:i,content:r.content,createdAt:d});return}if(Array.isArray(r.content)){let c=r.content.map(pP).filter(p=>p!==null),u=iu(c);n.push({id:r.id,role:i,content:u||(li(c)?ii:""),createdAt:d,...c.length>0&&{contentParts:c}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function Bl(e){let t=e.content;if(typeof t!="string"||t==="")return;let o=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof o=="string"&&o===t))return t}function Dl(e,t){let o=new Map;for(let n of e)o.set(n.id,n);for(let n of t)o.set(n.id,n);return[...o.values()].sort((n,r)=>{let a=new Date(n.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(i)&&a!==i)return a-i;let d=n.sequence??0,c=r.sequence??0;return d!==c?d-c:n.id.localeCompare(r.id)})}var mP="https://api.runtype.com/v1/dispatch",NC="https://api.runtype.com",Fe=class extends Error{constructor(t,o,n){super(o),this.name="HistoryClientError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}},FC=32768,Mg=49152,UC=e=>{let t=e??{},o=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:o,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},qC=e=>"reason"in e?e.reason:void 0,VC="The identity proof was not admitted; account history is unavailable",Tg="The identity proof was rejected",$C="The request carried no visitor credential",jC="The stored visitor belongs to a different signed-in user",Eg=(e,t)=>e instanceof Fe&&e.code===t;function gP(e){let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var Pg=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),zC=e=>e.slice().sort((t,o)=>new Date(t.createdAt).getTime()-new Date(o.createdAt).getTime()),KC=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function hP(e){switch(e){case"json":return su;case"regex-json":return ru;case"xml":return au;default:return nu}}var GC=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function yP(e,t){if(!e)return t;let o=e.trim(),n=t.trim();if(o.length===0)return t;if(n.length===0)return e;let r=GC(o);if(!GC(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=Wl(e);return Wl(t)!==null&&i===null?t:e}var Zs=class{constructor(t={},o={}){this.config=t;this.historyInternals=o;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??mP,this.headers={"Content-Type":"application/json","X-Persona-Version":xr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??hP(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return oC().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:Yx,getToolDisplayTitle:$c,loadPolyfill:eC});return this.pendingWebMcpConfirmHandler!==void 0&&n.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=n,n}).catch(o=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",o),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,n){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,o,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:n,targetProviders:r}=this.config;if(!n)return{agentId:t,flowId:o};let a=rC(n,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||NC}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let o=await this.initSession(),n=!1;for(;;){let r=o.conversationId,a=await this.readVisitorToken();if(o.durableRecovery?.enabled!==!0||!r||!a)throw new Fe("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,d=new URLSearchParams({sessionId:o.sessionId,after:t.after}),c=await fetch(`${i}?${d}`,{method:"GET",headers:{"X-Persona-Version":xr,"X-Visitor-Token":a},signal:t.signal});if(c.status===401&&!n){n=!0,o=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||t&&new Date<t.expiresAt||this.sessionWarmLatch===t?null:(this.sessionWarmLatch=t,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.sessionInitPromise)return this.sessionInitPromise;let t=this.sessionInitPromise=this._doInitSession().then(o=>this.sessionInitPromise!==t?this.initSession():(this.clientSession=o,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(o),o)).finally(()=>{this.sessionInitPromise===t&&(this.sessionInitPromise=null)});return t}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let o=this.getHistoryIdentityStatus(),n=o.state===t.state&&qC(o)===qC(t);if(this.historyIdentityStatus=t,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let o=this.isHistoryCapable()&&!t.omitVisitorFields,n=!t.omitVisitorFields,r=null;(o||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let a=this.routing(),i=a.agentId??a.flowId,d=o||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...o&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(o||n)&&r?{visitorToken:r}:{},...o&&t.identityProof?{identityProof:t.identityProof}:{},...d?{conversationId:d}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":xr},body:JSON.stringify(c),signal:t.signal});if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(o&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),d)throw new Fe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new Fe("history_disabled","Durable recovery is disabled for this surface"):(o||t.durableResume)&&u.status===401&&m.error==="visitor_required"?new Fe("visitor_required","Visitor credential no longer resolves"):d&&u.status===404?new Fe("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):u.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let p=await u.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{targetId:p.targetId}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,o=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!o)return this.ordinaryInit(t,!1);let n=await this.readVisitorToken();if(t&&n)try{let r=await this.createClientSession({conversationId:t,durableResume:o});return o&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Eg(r,"not_found")&&!Eg(r,"visitor_required")&&!Eg(r,"history_disabled"))throw r;return o&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,o){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.doOrdinaryInit(t,o)):this.doOrdinaryInit(t,o)}async doOrdinaryInit(t,o){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),a=await this.claimFirstConversation(r);return this.finishInit(a,t,o)}async reinitWithProof(t){let o=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:o,identityProof:t}),a=this.finishInit(r,n,!1);return this.clientSession=a,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),a}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,o,n){let r=t.conversationId;return r&&o&&(n||r!==o)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:o,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let o=!1;return{session:t,commit:()=>{o||(o=!0,this.clientSession=t,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{o=!0}}}async prepareConversationSession(t,o){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Fe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let n=o?.proof??null;if(!await this.readVisitorToken()&&!n)throw new Fe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let a=await this.createClientSession({conversationId:t,identityProof:n});return this.prepared(a)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":xr},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.sessionWarmLatch=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:o})}historyUrl(t,o){let n=new URLSearchParams;for(let[a,i]of Object.entries(o))i===void 0||i===""||n.set(a,String(i));let r=n.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let o=this.config.features?.history?.scope;return o||(this.config.getIdentityProof?"verified-user":"browser")}async resolveChatIdentityProof(t){t?.throwIfAborted();let o=this.config.identityProvider;if(o===void 0)return;let n=this.config.getIdentityProof;if(!o.trim()||!n)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,a;try{let i=Promise.resolve().then(()=>n());r=t?await Promise.race([i,new Promise((d,c)=>{a=()=>c(t.reason),t.addEventListener("abort",a,{once:!0}),t.aborted&&a()})]):await i}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{a&&t?.removeEventListener("abort",a)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:o,token:r}}async resolveIdentityProof(t,o){let n=this.config.getIdentityProof;if(!n)return o&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;o&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await n()??null}catch{throw o&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Fe("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Fe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return o&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,o,n){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(o);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Fe("proof_not_admitted",VC);return r}async readErrorCode(t){let o=await t.json().catch(()=>({}));return typeof o.error=="string"?o.error:typeof o.message=="string"?o.message:""}async recoverFromUnauthorized(t,o,n){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Fe("invalid_identity_proof",Tg);if(r.includes("visitor token required"))throw new Fe("visitor_token_missing",$C);if(r.includes("visitor_identity_mismatch")){if(!o)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Fe("visitor_identity_mismatch",jC);return this.reinitWithProof(o)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Fe("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,o){let n=await this.readErrorCode(t);if(t.status===404)return new Fe("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new Fe("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&n.includes("identity_proof_not_admitted"))return o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Fe("proof_not_admitted",VC);if(t.status===401){let r=n.toLowerCase();return r.includes("invalid_identity_proof")?(o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Fe("invalid_identity_proof",Tg)):r.includes("visitor token required")?new Fe("visitor_token_missing",$C):r.includes("visitor_identity_mismatch")?new Fe("visitor_identity_mismatch",jC):new Fe("unauthorized",n||"History request was not authorized")}return new Fe("request_failed",n||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,o,n){let r=t?.toLowerCase()??null;if(o){if(r==="admitted"){n&&this.setHistoryIdentityStatus({state:"verified"});return}throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Fe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Fe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Fe("identity_contract_violation","Server admitted an identity proof that was never sent");n&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,o){this.assertHistoryUsable();let n=o.trackIdentity!==!1,r=await this.initSession(),a=null;this.resolveHistoryScope(o.scope)==="verified-user"&&(a=await this.resolveIdentityProof(r,n),a&&(r=await this.bindIdentity(r,a,n)));let i=this.historyInternals.visitorStore,d=!1;for(;;){let c=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!o.visitorTokenOptional)throw new Fe("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...o.query,sessionId:r.sessionId}),{method:o.method,headers:{"X-Persona-Version":xr,...u?{"X-Visitor-Token":u}:{},...a?{"X-Identity-Proof":a}:{},...o.body!==void 0?{"Content-Type":"application/json"}:{}},...o.body!==void 0?{body:JSON.stringify(o.body)}:{},...o.keepalive?{keepalive:!0}:{}});if(p.status===401&&!d){d=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),a,n);continue}if(!p.ok)throw await this.historyErrorFor(p,n);let m=p.headers.get("X-History-Identity-Status"),h=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new Fe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,a!==null,n),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Fe("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let o=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(o?.data)?o.data:[]).map(UC),nextCursor:typeof o?.nextCursor=="string"?o.nextCursor:null}}async getConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...o?.messageCursor?{messageCursor:o.messageCursor}:{}},...o?.scope?{scope:o.scope}:{}});return{summary:UC(n),messages:Array.isArray(n?.messages)?n.messages:[],nextMessageCursor:typeof n?.nextMessageCursor=="string"?n.nextMessageCursor:null,conversationRevision:typeof n?.conversationRevision=="string"?n.conversationRevision:null}}async finalizeDisplayProjections(t,o){this.assertHistoryUsable();let n=0;for(let c of o){let u=c.displayContent.length;if(u>FC)throw new Fe("payload_too_large",`displayContent exceeds the ${FC} character limit`);n+=u}if(n>Mg)throw new Fe("payload_too_large",`Display projection batch exceeds the ${Mg} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,a=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:o},scope:"browser",keepalive:n<=Mg,trackIdentity:!1}),d=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return d&&this.clientSession?.conversationId===t&&(r?.revision()??0)===a&&this.historyInternals.setStoredConversationRevision?.(d),{conversationRevision:d}}async deleteConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...o?.scope?{scope:o.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async deleteAllConversations(t){let o=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){let n=aC();this.currentClientTurnId=n;let r=()=>this.currentClientTurnId===n,a=i=>{r()&&o(i)};o({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},d=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=d,M=A.durableRecovery?.enabled===!0;if(M&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let L=await this.createClientSession({...M||this.isHistoryCapable()?{conversationId:A.conversationId,durableResume:M}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&L.conversationId!==A.conversationId||M&&L.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");d=this.finishInit(L,A.conversationId??null,!1),this.clientSession=d,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(d)};Date.now()>=d.expiresAt.getTime()-6e4&&await c();let u=await this.buildPayload(t.messages),p=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,m=this.isHistoryCapable(),h={sessionId:d.sessionId,messages:t.messages.filter(Pg).map(A=>{let M=m?Bl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...M!==void 0&&{displayContent:M}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...u.inputs&&Object.keys(u.inputs).length>0&&{inputs:u.inputs},...u.context&&{context:u.context},turnId:n,...t.interrupt&&{submitMode:"interrupt"}},y=async()=>{i();let A=d.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.sendWithClientToolsDiff(d.sessionId,u.clientTools,async M=>{i();let L=await this.resolveChatIdentityProof(t.signal);i();let b={...h,sessionId:d.sessionId,...M,...L&&{identityProof:L}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...b,...L&&{identityProof:{provider:L.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":xr,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(b),signal:t.signal})})},x=await y();if(i(),x.response.status===401){let A=await x.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),x=await y(),i())}let{response:C,commit:E}=x;if(!C.ok){let A=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401&&A.error==="invalid_identity_proof"){let L=new Fe("invalid_identity_proof",Tg);throw a({type:"error",error:L}),L}if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let L=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:L}),L}if(C.status===429){let L=new Error(A.hint||"Message limit reached for this session.");throw a({type:"error",error:L}),L}if(C.status===410&&A.error==="conversation_deleted"){let L=new Fe("conversation_deleted","This conversation was deleted");throw a({type:"error",error:L}),L}let M=new Error(A.error||"Failed to send message");throw a({type:"error",error:M}),M}if(!C.body){let A=new Error("No response body received");throw a({type:"error",error:A}),A}E(),a({type:"status",status:"connected"});try{await this.streamResponse(C.body,a,t.assistantMessageId)}finally{a({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!(d instanceof Fe)&&!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&a({type:"error",error:d}),d}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,n,r){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,n,r)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(n,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,n,r){let a=!!(o&&o.length>0),i=a?Zx(o):void 0,d=this.clientToolsFingerprintSessionId===t,c=a&&d&&this.lastSentClientToolsFingerprint===i,u=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let h=0;;h++){if(m=await n({...a&&(p||!c)&&o?{clientTools:o}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),m.status===409&&h===0&&a&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,n){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||NC}/resume`,i,d=null;if(r){let p=await this.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(d=await this.readVisitorToken())}let c={"Content-Type":"application/json",...d?{"X-Visitor-Token":d}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let u={executionId:t,toolOutputs:o,streamResponse:n?.streamResponse??!0,...n?.after?{after:n.after}:{}};if(i&&(u.sessionId=i),r&&i){let p=[...si(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(i,p,y=>{let x={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(a,{method:"POST",headers:c,body:JSON.stringify(x),signal:n?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(a,{method:"POST",headers:c,body:JSON.stringify(u),signal:n?.signal})}latestMentionContext(t){for(let o=t.length-1;o>=0;o--){let n=t[o];if(n.role==="user")return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async buildContextAggregate(t){let o={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let n=this.latestMentionContext(t);return n&&Object.assign(o,n),Object.keys(o).length?o:null}normalizeComposerOptions(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}applyInlineAgentModel(t,o){let n=o?.selectedModelId;return!n||!("model"in t)?t:this.config.composer?.models?.some(a=>a.id===n)?{...t,model:n}:t}async buildAgentPayload(t,o){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=wg(zC(t),u=>Pg(u)&&(u.role==="user"||u.role==="assistant"||u.role==="system")&&(!u.variant||u.variant==="assistant")?KC(u):null),a=this.normalizeComposerOptions(o),i={agent:this.applyInlineAgentModel(this.config.agent??{agentId:n},a),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};a&&(i.composerOptions=a);let d=[...si(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];d.length>0&&(i.clientTools=d);let c=await this.buildContextAggregate(t);return c&&(i.context=c),i}async buildPayload(t,o){let n=wg(zC(t),u=>Pg(u)?KC(u):null),r=this.routing(),a={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[u,p]of Object.entries(r.targetPayload))u!=="messages"&&(a[u]=p);let i=[...si(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];i.length>0&&(a.clientTools=i);let d=await this.buildContextAggregate(t);d&&(a.context=d);let c=this.normalizeComposerOptions(o);if(c&&(a.composerOptions=c),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...a},config:this.config});if(u&&typeof u=="object"){let p=u;return a.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=a.clientTools),p}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return a}async handleCustomSSEEvent(t,o,n,r,a,i){if(!this.parseSSEEvent)return!1;try{let d=await this.parseSSEEvent(t);if(d===null)return!1;let c=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=m,r(m),m},u=p=>n.current?n.current:c(p);if(d.text!==void 0){d.partId!==void 0&&i.current!==null&&d.partId!==i.current&&(n.current&&(n.current.streaming=!1,r(n.current)),c(d.partId)),d.partId!==void 0&&(i.current=d.partId);let p=u(d.partId);d.partId!==void 0&&!p.partId&&(p.partId=d.partId),p.content+=d.text,r(p)}return d.done&&(n.current&&(n.current.streaming=!1,r(n.current)),i.current=null,o({type:"status",status:"idle"})),d.error&&(i.current=null,o({type:"error",error:new Error(d.error)})),!0}catch(d){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",d),!1}}async streamResponse(t,o,n,r){let a=t.getReader(),i=new TextDecoder,d="",c=Date.now(),u=0,p=()=>c+u++,m=j=>{let P=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,U=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,G=j.tools?j.tools.map(Z=>({...Z,chunks:Z.chunks?[...Z.chunks]:void 0})):void 0;return{...j,reasoning:P,toolCall:U,tools:G}},h=j=>{if(j.role!=="assistant"||j.variant)return!0;let P=Array.isArray(j.contentParts)&&j.contentParts.length>0,U=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||P||U||!!j.stopReason},y=j=>{h(j)&&o({type:"message",message:m(j)})},x=null,C=null,E={current:null},A={current:null},M=null,L="",b=new Map,S=new Map,T=new Map,B=new Map,_=new Map,X=n,$=!1,k=()=>{if(x)return x;let j,P="",U=M;return!$&&X?(j=X,$=!0,P=r??""):X&&U?j=`${X}_${U}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:j,role:"assistant",content:P,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(x),x},H=j=>{let P=B.get(j);if(P)return P;let U={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:j,status:"streaming",chunks:[]}};return B.set(j,U),y(U),U},F=new Set,W=new Map,oe=new Set,V=new Map,de=j=>{if(!j)return!1;let P=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return P==="emit_artifact_markdown"||P==="emit_artifact_component"},ce=j=>{let P=_.get(j);if(P)return P;let U={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:j,status:"pending"}};return _.set(j,U),y(U),U},ge=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let P=Number(j);if(!Number.isNaN(P)&&Number.isFinite(P))return P;let U=Date.parse(j);if(!Number.isNaN(U))return U}return Date.now()},Pe=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},Ae=new Map,ve=new Map,Gt=(j,P)=>{let U=Pe(P),G=ve.get(j.id),Z=yP(G,U);j.rawContent=Z;let J=Ae.get(j.id),pe=Ze=>{let $e=j.content??"";Ze.trim()!==""&&($e.trim().length===0||Ze.startsWith($e)||Ze.trimStart().startsWith($e.trim()))&&(j.content=Ze)},xe=()=>{if(J){let Ze=J.close?.();Ze instanceof Promise&&Ze.catch(()=>{})}Ae.delete(j.id),ve.delete(j.id),j.streaming=!1,y(j)};if(!J){pe(U),xe();return}let Ce=Wl(Z);if(Ce!==null&&Ce.trim()!==""){pe(Ce),xe();return}let ut=Ze=>{let $e=typeof Ze=="string"?Ze:Ze?.text??null;if($e!==null&&$e.trim()!=="")return $e;let pt=J.getExtractedText();return pt!==null&&pt.trim()!==""?pt:U},Dt;try{Dt=J.processChunk(Z)}catch{pe(U),xe();return}if(Dt instanceof Promise){Dt.then(Ze=>{pe(ut(Ze)),xe()}).catch(()=>{pe(U),xe()});return}pe(ut(Dt)),xe()},Bt=null,Me=(j,P,U,G)=>{j.rawContent=P,Ae.has(j.id)||Ae.set(j.id,this.createStreamParser());let Z=Ae.get(j.id),J=P.trim().startsWith("{")||P.trim().startsWith("[");if(J&&ve.set(j.id,P),Z.__isPlainTextParser===!0){j.content=G!==void 0?P:j.content+U,ve.delete(j.id),Ae.delete(j.id),j.rawContent=void 0,y(j);return}let xe=Z.processChunk(P);if(xe instanceof Promise)xe.then(Ce=>{let ut=typeof Ce=="string"?Ce:Ce?.text??null;ut!==null&&ut.trim()!==""?(j.content=ut,y(j)):!J&&!P.trim().startsWith("<")&&(j.content=G!==void 0?P:j.content+U,ve.delete(j.id),Ae.delete(j.id),j.rawContent=void 0,y(j))}).catch(()=>{j.content=G!==void 0?P:j.content+U,ve.delete(j.id),Ae.delete(j.id),j.rawContent=void 0,y(j)});else{let Ce=typeof xe=="string"?xe:xe?.text??null;Ce!==null&&Ce.trim()!==""?(j.content=Ce,y(j)):!J&&!P.trim().startsWith("<")&&(j.content=G!==void 0?P:j.content+U,ve.delete(j.id),Ae.delete(j.id),j.rawContent=void 0,y(j))}},N=(j,P)=>{let U=P??j.content;if(U==null||U===""){j.streaming=!1,y(j);return}let Z=ve.get(j.id)??Pe(U);j.rawContent=Z;let J=Ae.get(j.id),pe=null,xe=!1;if(J&&(pe=J.getExtractedText(),pe===null&&(pe=Wl(Z)),pe===null)){let Ce=J.processChunk(Z);Ce instanceof Promise?(xe=!0,Ce.then(ut=>{let Dt=typeof ut=="string"?ut:ut?.text??null;Dt!==null&&(j.content=Dt,j.streaming=!1,Ae.delete(j.id),ve.delete(j.id),y(j))}).catch(()=>{})):pe=typeof Ce=="string"?Ce:Ce?.text??null}if(!xe){pe!==null&&pe.trim()!==""?j.content=pe:ve.has(j.id)||(j.content=Pe(U));let Ce=Ae.get(j.id);if(Ce){let ut=Ce.close?.();ut instanceof Promise&&ut.catch(()=>{}),Ae.delete(j.id)}ve.delete(j.id),j.streaming=!1,y(j)}},Oe=(j,P,U)=>{let G=S.get(j);if(G)return G;let Z={id:`nested-${P}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...U?{variant:U}:{},...U==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:P}};return S.set(j,Z),y(Z),Z},Ve=[],Mo,uo=new Map,Xt=0,_o="agent",De=!1,Qe=null,ke=null,Gn=this.config.iterationDisplay??"separate";for(Mo=()=>{for(let j=0;j<Ve.length;j++){let P=Ve[j];if(!De&&_o!=="flow"&&typeof P.stepType=="string"&&(_o="flow"),P.type==="reasoning_start"){let U=typeof P.id=="string"?P.id:null,G=typeof P.parentToolCallId=="string"&&P.parentToolCallId?P.parentToolCallId:null;if(U&&G){b.set(U,G),Oe(U,G,"reasoning");continue}let Z=P.id,J=H(Z);J.reasoning=J.reasoning??{id:Z,status:"streaming",chunks:[]},J.reasoning.startedAt=J.reasoning.startedAt??Date.now(),J.reasoning.completedAt=void 0,J.reasoning.durationMs=void 0,(P.scope==="loop"||P.scope==="turn")&&(J.reasoning.scope=P.scope),J.streaming=!0,J.reasoning.status="streaming",y(J)}else if(P.type==="reasoning_delta"){let U=typeof P.id=="string"?P.id:null;if(U&&b.has(U)&&S.has(U)){let J=S.get(U),pe=P.delta;pe&&J.reasoning&&(J.reasoning.chunks.push(String(pe)),y(J));continue}let G=P.id,Z=H(G);Z.reasoning=Z.reasoning??{id:G,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??Date.now(),P.delta&&Z.reasoning.chunks.push(P.delta),Z.reasoning.status="streaming",Z.streaming=!0,y(Z)}else if(P.type==="reasoning_complete"){let U=typeof P.id=="string"?P.id:null;if(U&&b.has(U)&&S.has(U)){let pe=S.get(U);if(pe.reasoning){let xe=typeof P.text=="string"?P.text:"";xe&&pe.reasoning.chunks.length===0&&pe.reasoning.chunks.push(xe),pe.reasoning.status="complete",pe.streaming=!1,y(pe)}b.delete(U),S.delete(U);continue}let G=P.id,Z=typeof P.text=="string"?P.text:"";!B.get(G)&&(Z||P.scope==="loop")&&H(G);let J=B.get(G);if(J?.reasoning){(P.scope==="loop"||P.scope==="turn")&&(J.reasoning.scope=P.scope),Z&&J.reasoning.chunks.length===0&&J.reasoning.chunks.push(Z),J.reasoning.status="complete",J.reasoning.completedAt=Date.now();let pe=J.reasoning.startedAt??Date.now();J.reasoning.durationMs=Math.max(0,(J.reasoning.completedAt??Date.now())-pe),J.streaming=!1,y(J)}}else if(P.type==="tool_start"){x&&(x.streaming=!1,y(x),x=null),typeof P.iteration=="number"&&(Xt=P.iteration);let U=P.toolCallId,G=P.toolName;if(de(G)){F.add(U);continue}let Z=ce(U),J=Z.toolCall??{id:U,status:"pending"};J.name=G??J.name,J.status="running",J.success=void 0,J.error=void 0,J.duration=void 0,P.parameters!==void 0&&(J.args=P.parameters),J.startedAt=J.startedAt??ge(P.startedAt),J.completedAt=void 0,J.durationMs=void 0,Z.toolCall=J,Z.streaming=!0,P.executionId&&(Z.agentMetadata={executionId:P.executionId,iteration:P.iteration}),y(Z)}else if(P.type==="tool_output_delta"){let U=P.toolCallId;if(F.has(U))continue;let G=ce(U),Z=G.toolCall??{id:U,status:"running"};Z.startedAt=Z.startedAt??Date.now();let J=P.delta;J&&(Z.chunks=Z.chunks??[],Z.chunks.push(String(J))),Z.status="running",G.toolCall=Z,G.streaming=!0,P.executionId&&(G.agentMetadata=G.agentMetadata??{executionId:P.executionId,iteration:Xt}),y(G)}else if(P.type==="tool_complete"){let U=P.toolCallId;if(F.has(U)){F.delete(U);continue}let G=ce(U),Z=G.toolCall??{id:U,status:"running"};Z.status="complete",P.result!==void 0&&(Z.result=P.result),Z.name=P.toolName??Z.name,Z.success=P.success,Z.error=P.error,Z.completedAt=Date.now();let J=P.executionTime;if(typeof J=="number")Z.durationMs=J,Z.duration=J;else{let pe=Z.startedAt??Date.now();Z.durationMs=Math.max(0,(Z.completedAt??Date.now())-pe)}G.toolCall=Z,G.streaming=!1,P.executionId&&(G.agentMetadata=G.agentMetadata??{executionId:P.executionId,iteration:P.iteration??Xt}),y(G)}else if(P.type==="await"&&P.toolName){let U=typeof P.toolCallId=="string"&&P.toolCallId.length>0?P.toolCallId:void 0,G=U??P.toolId??`local-${p()}`,Z=ce(G),J=P.toolName,pe=P.origin==="webmcp"&&!Yr(J)?`webmcp:${J}`:J,xe=Yr(pe),Ce=Z.toolCall??{id:G,status:"pending"};Ce.name=pe,Ce.args=P.parameters,Ce.status=xe?"running":"complete",Ce.chunks=Ce.chunks??[],Ce.startedAt=Ce.startedAt??ge(P.awaitedAt),xe?(Ce.completedAt=void 0,Ce.duration=void 0,Ce.durationMs=void 0):Ce.completedAt=Ce.completedAt??Ce.startedAt,Z.toolCall=Ce,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:P.executionId??Z.agentMetadata?.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},y(Z)}else if(P.type==="text_start"){let U=typeof P.id=="string"?P.id:null,G=typeof P.parentToolCallId=="string"&&P.parentToolCallId?P.parentToolCallId:null;if(U&&G){b.set(U,G);continue}let Z=x;Z&&(_o==="flow"?(N(Z),Bt=Z):(Z.streaming=!1,y(Z)),x=null),M=typeof P.id=="string"?P.id:M,L=""}else if(P.type==="text_delta"){let U=typeof P.id=="string"?P.id:null,G=U?b.get(U):void 0;if(U&&G){let pe=typeof P.delta=="string"?P.delta:"",xe=(T.get(U)??"")+pe;if(T.set(U,xe),xe.trim()==="")continue;let Ce=Oe(U,G);Ce.agentMetadata={...Ce.agentMetadata,executionId:P.executionId,parentToolId:G},Me(Ce,xe,pe,void 0);continue}if(M=typeof P.id=="string"?P.id:M,_o==="flow"){let pe=typeof P.delta=="string"?P.delta:"";if(L+=pe,L.trim()==="")continue;let xe=k();xe.agentMetadata={executionId:P.executionId,iteration:Xt},Me(xe,L,pe,void 0),C=xe;continue}let Z=typeof P.delta=="string"?P.delta:"";L+=Z;let J=k();J.agentMetadata={executionId:P.executionId,iteration:Xt,turnId:Qe??void 0,agentName:ke?.agentName},Me(J,L,Z,void 0),C=J}else if(P.type==="text_complete"){let U=typeof P.id=="string"?P.id:null;if(U&&b.has(U)){let Z=S.get(U);Z&&N(Z),b.delete(U),T.delete(U),S.delete(U);continue}let G=x;G&&(_o==="flow"?(N(G),Bt=G):((G.content??"")===""&&typeof P.text=="string"&&(G.content=P.text),G.streaming=!1,y(G)),x=null),M=null,L=""}else if(P.type==="step_complete"){if(P.stepType==="tool")continue;if(P.success===!1){let U=P.error||"Step failed";o({type:"error",error:new Error(U)});let G=x;G&&G.streaming&&(G.streaming=!1,y(G)),o({type:"status",status:"idle"});continue}{let U=Bt;Bt=null;let G=P.stopReason,J=(P.result&&typeof P.result=="object"?P.result:null)?.response;if(U)G&&(U.stopReason=G),J!=null?Gt(U,J):U.streaming!==!1&&(Ae.delete(U.id),ve.delete(U.id),U.streaming=!1,y(U));else{let pe=J!=null&&J!=="";if(pe||G){let xe=k();G&&(xe.stopReason=G),pe?N(xe,J):(xe.streaming=!1,y(xe))}}continue}}else if(P.type==="execution_start")_o=P.kind==="flow"?"flow":"agent",De=!0,_o==="agent"&&(ke={executionId:P.executionId,agentId:P.agentId??"virtual",agentName:P.agentName??""});else if(P.type==="turn_start"){let U=typeof P.iteration=="number"?P.iteration:Xt;if(U!==Xt){if(Gn==="separate"&&U>1){let G=x;G&&(G.streaming=!1,y(G),x=null)}Xt=U}Qe=typeof P.id=="string"?P.id:null,C=null}else if(P.type==="tool_input_delta"){let U=P.toolCallId;if(U){let G=_.get(U);G?.toolCall&&(G.toolCall.chunks=G.toolCall.chunks??[],G.toolCall.chunks.push(P.delta??""),y(G))}}else if(P.type==="tool_input_complete"){if(F.has(P.toolCallId))continue;let U=ce(P.toolCallId),G=U.toolCall;G.args=P.parameters,G.name=P.toolName??G.name,y(U)}else if(P.type==="turn_complete"){let U=P.stopReason,G=x??C;if(U&&G!==null){let Z=P.id;(!Z||G.agentMetadata?.turnId===Z)&&(G.stopReason=U,y(G))}Qe===P.id&&(Qe=null)}else if(P.type==="media_start"){let U=String(P.id);uo.set(U,{mediaType:typeof P.mediaType=="string"?P.mediaType:void 0,toolCallId:P.toolCallId,parts:[]})}else if(P.type==="media_delta"){let U=uo.get(String(P.id));U&&typeof P.delta=="string"&&U.parts.push(P.delta)}else if(P.type==="media_complete"){let U=String(P.id),G=uo.get(U);uo.delete(U);let Z=(typeof P.mediaType=="string"?P.mediaType:void 0)??G?.mediaType??"application/octet-stream",J=typeof P.data=="string"?P.data:void 0,pe=typeof P.url=="string"?P.url:G&&G.parts.length>0?G.parts.join(""):void 0,xe=null;if(J)xe={type:"media",data:J,mediaType:Z};else if(pe){let Ze=Z.toLowerCase();xe={type:Ze==="image"||Ze.startsWith("image/")?"image-url":"file-url",url:pe,mediaType:Z}}let Ce=P.toolCallId??G?.toolCallId,ut=xe?[xe]:[],Dt=[];for(let Ze of ut){if(!Ze||typeof Ze!="object")continue;let $e=Ze,pt=typeof $e.type=="string"?$e.type:void 0,Qt=typeof $e.mediaType=="string"?$e.mediaType.toLowerCase():"",Et=null,fo="";if(pt==="media"){let ft=typeof $e.data=="string"?$e.data:void 0;if(!ft)continue;fo=Qt.length>0?Qt:"application/octet-stream",Et=`data:${fo};base64,${ft}`}else if(pt==="image-url"){let ft=typeof $e.url=="string"?$e.url:void 0;if(!ft)continue;fo=Qt,Et=ft}else if(pt==="file-url"){let ft=typeof $e.url=="string"?$e.url:void 0;if(!ft)continue;fo=Qt,Et=ft}else continue;if(Et)if(pt==="image-url"||fo.startsWith("image/"))Dt.push({type:"image",image:Et,...fo.includes("/")?{mimeType:fo}:{}});else if(fo.startsWith("audio/"))Dt.push({type:"audio",audio:Et,mimeType:fo});else if(fo.startsWith("video/"))Dt.push({type:"video",video:Et,mimeType:fo});else{let ft=fo||"application/octet-stream";Dt.push({type:"file",data:Et,mimeType:ft,filename:gP(ft)})}}if(Dt.length>0){let Ze=p(),$e=Ce,Qt={id:`agent-media-${typeof $e=="string"&&$e.length>0?`${$e}-${Ze}`:String(Ze)}`,role:"assistant",content:"",contentParts:Dt,createdAt:new Date().toISOString(),streaming:!1,sequence:Ze,agentMetadata:{executionId:P.executionId,iteration:Xt}};y(Qt);let Et=x;Et&&(Et.streaming=!1,y(Et)),x=null,E.current=null}}else if(P.type==="execution_complete"){let U=x;U&&(P.kind==="flow"&&U.streaming!==!1?N(U):(U.streaming=!1,y(U)),x=null),M=null,L="",Bt=null,o({type:"status",status:"idle",terminal:!0})}else if(P.type==="execution_error"){let U=typeof P.error=="string"?P.error:P.error?.message??"Execution error";o({type:"error",error:new Error(U)})}else if(P.type!=="ping"){if(P.type==="approval_start"){let U=P.approvalId??`approval-${p()}`,G={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:"pending",agentId:ke?.agentId??"virtual",executionId:P.executionId??ke?.executionId??"",toolName:P.toolName??"",toolType:P.toolType,description:P.description??`Execute ${P.toolName??"tool"}`,...typeof P.reason=="string"&&P.reason?{reason:P.reason}:{},parameters:P.parameters}};y(G)}else if(P.type==="approval_complete"){let U=P.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:P.decision??"approved",agentId:ke?.agentId??"virtual",executionId:P.executionId??ke?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};y(Z)}}else if(P.type==="artifact_start"||P.type==="artifact_delta"||P.type==="artifact_update"||P.type==="artifact_complete"){if(P.type==="artifact_start"){let U=P.artifactType,G=String(P.id),Z=typeof P.title=="string"?P.title:void 0,J=P.file,pe;if(J&&typeof J=="object"&&!Array.isArray(J)&&typeof J.path=="string"&&typeof J.mimeType=="string"&&(pe={path:J.path,mimeType:J.mimeType,...typeof J.language=="string"?{language:J.language}:{}}),o({type:"artifact_start",id:G,artifactType:U,title:Z,component:typeof P.component=="string"?P.component:void 0,...pe?{file:pe}:{}}),V.set(G,{markdown:"",title:Z,file:pe}),!oe.has(G)){oe.add(G);let xe=qn(this.config.features?.artifacts,{artifactType:U,...pe?{file:pe}:{}}),Ce=typeof P.component=="string"?P.component:void 0,ut={id:`artifact-ref-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Pl(xe,{artifactId:G,title:Z,artifactType:U,status:"streaming",...pe?{file:pe}:{},...Ce?{component:Ce}:{}})};W.set(G,ut),y(ut)}}else if(P.type==="artifact_delta"){let U=String(P.id),G=typeof P.delta=="string"?P.delta:String(P.delta??"");o({type:"artifact_delta",id:U,artDelta:G});let Z=V.get(U);Z&&(Z.markdown+=G)}else if(P.type==="artifact_update"){let U=P.props&&typeof P.props=="object"&&!Array.isArray(P.props)?P.props:{};o({type:"artifact_update",id:String(P.id),props:U,component:typeof P.component=="string"?P.component:void 0});let G=V.get(String(P.id));G&&(G.props={...G.props??{},...U})}else if(P.type==="artifact_complete"){let U=String(P.id);o({type:"artifact_complete",id:U});let G=W.get(U);if(G){G.streaming=!1;try{let Z=JSON.parse(G.rawContent??"{}");if(Z.props){Z.props.status="complete";let J=V.get(U);J?.markdown&&(Z.props.markdown=J.markdown),J?.file&&(Z.props.file=J.file),Z.component==="PersonaArtifactInline"&&J?.props&&Object.keys(J.props).length>0&&(Z.props.componentProps=J.props)}G.rawContent=JSON.stringify(Z)}catch{}V.delete(U),y(G),W.delete(U)}}}else if(P.type==="error"&&P.recoverable===!1&&P.error!=null&&P.error!==""){let U=typeof P.error=="string"?P.error:P.error?.message!=null?String(P.error.message):"Execution error";o({type:"error",error:new Error(U)});let G=x;G&&G.streaming&&(G.streaming=!1,y(G)),o({type:"status",status:"idle"})}}}Ve.length=0};;){let{done:j,value:P}=await a.read();if(j)break;d+=i.decode(P,{stream:!0});let U=d.split(`
|
|
8
|
-
|
|
9
|
-
`);d=U.pop()??"";for(let G of U){let Z=G.split(`
|
|
10
|
-
`),J="message",pe="",xe=null;for(let $e of Z)$e.startsWith("event:")?J=$e.replace("event:","").trim():$e.startsWith("data:")?pe+=$e.replace("data:","").trim():$e.startsWith("id:")&&(xe=$e.slice(3).trim());let Ce=()=>{xe!==null&&xe!==""&&o({type:"cursor",id:xe})};if(!pe){Ce();continue}let ut;try{ut=JSON.parse(pe)}catch($e){o({type:"error",error:$e instanceof Error?$e:new Error("Failed to parse chat stream payload")});continue}let Dt=ut!==null&&typeof ut=="object"&&!Array.isArray(ut)?ut:null,Ze=J!=="message"?J:typeof Dt?.type=="string"?Dt.type:"message";if(this.onSSEEvent?.(Ze,ut),this.parseSSEEvent){E.current=x;let $e=await this.handleCustomSSEEvent(ut,o,E,y,p,A);if(E.current&&E.current!==x&&(x=E.current),$e){Ce();continue}}Dt&&(Ve.push({...Dt,type:Ze}),Mo()),Ce()}}Mo()}};function bP(e){let t=0;for(let o of e.split(`
|
|
11
|
-
`)){let n=/^ {0,3}(`+)/.exec(o);n&&n[1].length>t&&(t=n[1].length)}return t}function XC(e,t){let o="`".repeat(Math.max(3,bP(t)+1));return`${o}${e}
|
|
12
|
-
${t}
|
|
13
|
-
${o}`}var vP=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function xP(e){let t=e?.text?.trim()??"";return t?XC(vP(e),t):""}function QC(e){let t=xP(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[un(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
14
|
-
|
|
15
|
-
`)}:{}}function uu(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function YC(e,t){let o=e.findIndex(r=>r.id===t);if(o===-1||e[o].role!=="user")return null;let n=o+1;for(;n<e.length&&e[n].role!=="user";)n+=1;return{start:o,end:n}}function kg(e,t){let o=e.findIndex(n=>n.id===t);if(o<=0)return null;for(let n=o-1;n>=0;n-=1)if(e[n].role==="user")return e[n].id;return null}function JC(e){for(let t=e.length-1;t>=0;t-=1){let o=e[t];if(o.role==="user"||o.streaming)return null;if(!(o.role!=="assistant"||o.variant))return kg(e,o.id)?o.id:null}return null}function Lg(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var pn=class extends Error{constructor(t,o,n){super(o),this.name="HistoryProviderError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function ZC(e){return e instanceof pn}function Ol(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(r=>r.name===o);if(n)return n}return e.find(o=>o.lang.startsWith("en"))??e[0]}var ea=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,o){if(!e.isSupported()){o.onError?.(new Error("Web Speech API is unavailable"));return}let n=window.speechSynthesis;n.cancel();let r=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let i=a.find(d=>d.name===t.voice);i&&(r.voice=i)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):Ol(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>o.onEnd?.(),r.onerror=i=>{let d=i.error;d==="canceled"||d==="interrupted"?o.onEnd?.():o.onError?.(new Error(d||"Speech synthesis failed"))},setTimeout(()=>{n.speak(r),o.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var di=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,o){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,o)}async play(t,o){let n=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(n!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(o,{onStart:()=>{n===this.generation&&this.set(t,"playing")},onEnd:()=>{n===this.generation&&this.set(null,"idle")},onError:()=>{n===this.generation&&this.set(null,"idle")}})}catch{n===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,o){this.activeId=o==="idle"?null:t,this.state=o;for(let n of this.listeners)n(this.activeId,this.state)}};var _l=class{constructor(){this.cancelled=!1}start(t){this.turnId=t,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(t){return!this.cancelled&&(!t||!this.turnId||t===this.turnId)}};var{setLoader:CP,load:SP}=vt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),eS=CP,Ig=SP;function Rg(e){if(!e)return"";let t=wP(e);return tS(t!==null?t:e)}function wP(e){let t=e.trim(),o=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(o&&(t=o[1].trim()),!t.startsWith("{"))return null;try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{}return null}function tS(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
16
|
-
`),t=t.replace(/\n{2,}/g,`
|
|
17
|
-
`),t.trim()}var Hg=null,oS=e=>{Hg=e},Wg=()=>Hg?Hg():import("./runtype-tts-entry");var{setLoader:AP,load:MP}=vt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),nS=AP,rS=MP;var TP=["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"];function EP(e,t){return TP.some(o=>e[o]!==t[o])}var $n=class extends Error{constructor(t,o){super(o),this.name="SessionHistoryError",this.code=t}};function Bg(e,t){let o=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(o);let 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 o.message?`${n}
|
|
18
|
-
|
|
19
|
-
_Details: ${o.message}_`:n}var Dg=e=>({isError:!0,content:[{type:"text",text:e}]}),PP=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,sS=e=>Yr(e)||e===Vn,ci=class e{constructor(t={},o,n={}){this.config=t;this.callbacks=o;this.historyInternals=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new _l;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new di(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,n=!!o?.name&&(Yr(o.name)||o.name===Vn&&rs(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&n&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(n),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Zs(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&Ig().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!n||!this.config.clientToken||Wg().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Bx(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=ea.isSupported()?new ea({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let n=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,i=t.browserFallback!==!1;if(n&&r&&a)return Wg().then(({RuntypeSpeechEngine:d,FallbackSpeechEngine:c})=>{let u=new d({host:n,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&o?new c(u,o,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.cleanupVoice();let n=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=Ig().then(async a=>{await n,r===this.voiceSetupGeneration&&this.wireVoiceProvider(a.createVoiceProvider(o))}).catch(a=>{console.error("Failed to setup voice:",a)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(o){console.error("Failed to setup voice:",o)}}wireVoiceProvider(t){try{this.voiceProvider=t;let o=this.voiceSetupGeneration,n=()=>this.voiceProvider===t&&o===this.voiceSetupGeneration,a=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{n()&&i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c,u)=>{if(n())if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.voiceTurns.start(u?.turnId),this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(u?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(i=>{n()&&(this.voiceLevel=Number.isFinite(i)?Math.max(0,Math.min(1,i)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{n()&&this.config.voiceRecognition?.onMetrics?.(i)}),this.voiceProvider.onError(i=>{n()&&(console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(i=>{n()&&(this.voiceStatus=i,this.voiceActive=i==="listening",(i==="listening"||i==="idle"||i==="disconnected")&&this.settlePendingVoiceTurn(i!=="listening"),this.callbacks.onVoiceStatusChanged?.(i))}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!vo(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.voiceSetupGeneration,o=()=>{let n=this.voiceProvider;!n?.prewarm||t!==this.voiceSetupGeneration||this.voiceActive||this.isBargeInActive()||Promise.resolve().then(()=>n.prewarm?.()).catch(()=>{})};if(!this.voiceProvider&&this.voiceSetupPromise){this.voiceSetupPromise.then(o,()=>{});return}o()}cleanupVoice(){let t=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let o=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(o)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new _l,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(t){try{await t.disconnect()}catch(o){console.error("Failed to disconnect voice:",o)}}settlePendingVoiceTurn(t){let o=t?this.pendingVoiceUserMessageId:null,n=this.pendingVoiceAssistantMessageId;!o&&!n||(n&&this.voiceTurns.cancel(),t&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(r=>r.id!==o&&r.id!==n?[r]:r.id===n&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(o=>{o&&this.client.getClientSession()===o&&this.setClientSession(o,t)})}setClientSession(t,o){this.clientSession=t,this.injectWelcomeMessage(t,o)}injectWelcomeMessage(t,o=!this.messages.length){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||!o)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:n?.createdAt??new Date().toISOString(),sequence:n?(n.sequence??0)-1:this.nextSequence()};this.appendMessage(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let o=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:n=>{this.handleHistoryContinuityChanged(n),o?.(n)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new $n("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let o=this.requireHistoryProvider(),n=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",a=n??(o.capabilities.scopes.includes(r)?r:o.capabilities.scopes[0]??r);if(!o.capabilities.scopes.includes(a))throw new pn("unsupported_scope","This history scope is not supported.");return{scope:a}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,o){this.callbacks.onHistoryNotice?.({code:t,message:o})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let o=this.projectionFinalizationPromise;o&&await o.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new $n("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,o){let n=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(o?.scope);await this.awaitHistorySettled();let a=++this.historyOpenEpoch,i=await n.getPage(t,{context:r});if(a!==this.historyOpenEpoch)throw new $n("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new $n("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(d)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=d.conversationId||t,this.activeConversationRevision=d.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,o,n){let r=this.requireHistoryProvider(),a=this.historyContext(n?.scope),i=o??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let d=`${t} ${i}`,c=this.olderPageRequests.get(d);if(c)return c;let u=this.fetchOlderPage(r,t,i,a).finally(()=>{this.olderPageRequests.delete(d)});return this.olderPageRequests.set(d,u),u}async fetchOlderPage(t,o,n,r){let a=this.messages[0]?.createdAt,i=await t.getPage(o,{cursor:n,...a?{beforeCreatedAt:a}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==o)return{messages:[],nextMessageCursor:i.nextCursor};let d=Dl(this.messages,i.messages);this.messages=this.sortMessages(d.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=i.nextCursor;for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,a=await o.prepareStartNew({context:n});if(r!==this.historyOpenEpoch)throw a.discard(),new $n("superseded","A later action won");await this.installFreshConversation(a)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,o){let n=this.requireHistoryProvider(),r=this.historyContext(o?.scope);await this.awaitHistorySettled(),await n.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,o,n){let r=this.requireHistoryProvider();if(!r.update)throw new $n("history_unavailable","This history provider cannot update conversations");let a=this.historyContext(n?.scope);return await this.awaitHistorySettled(),r.update(t,o,{context:a})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await o.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:n});return await this.recoverFromDestroyedConversation(n),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new $n("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let o=this.historyProvider;if(!o){this.historySendBlocked=!1,this.emitHistoryState();return}try{let n=await o.prepareStartNew({context:t});await this.installFreshConversation(n)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new $n("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let o=this.client.getClientSession();o&&o.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(o)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(o=>this.handleExternalCredentialChange(o))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let o=this.messages.length>0;o||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),o&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let o=this.historyProvider,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!o||!n)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let a=this.runBootReconciliation(o,n,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===a&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=a,a}async runBootReconciliation(t,o,n){this.activeConversationId=o;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,a=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&a&&r===a){this.activeConversationRevision=r;return}let i=await t.getPage(o,{context:n}),d=new Set(i.messages.map(m=>m.id)),c=this.messages.some(m=>d.has(m.id)),u=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>d.has(y.id)||y.id===m?!0:u!==void 0&&y.createdAt<u);p=Dl(h,i.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of i.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let o of t){let n=Bl(o);n!==void 0&&this.acknowledgedProjections.set(o.id,n)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let o=[];for(let n of this.messages){if(n.role!=="assistant"||n.streaming)continue;let r=Bl(n);r!==void 0&&this.acknowledgedProjections.get(n.id)!==r&&o.push({id:n.id,displayContent:r})}o.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:o.map(n=>n.id)}),this.enqueueProjectionFinalization(t,o))}enqueueProjectionFinalization(t,o){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,o,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,o,n){if(this.activeConversationId!==t)return;let r=o.filter(a=>this.acknowledgedProjections.get(a.id)!==a.displayContent);if(r.length===0){this.clearFinalizedMarker(t,o);return}try{let{conversationRevision:a}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&a&&(this.activeConversationRevision=a),this.clearFinalizedMarker(t,o)}catch(a){if(!n&&this.isTransientProjectionError(a)){await this.finalizeProjections(t,r,!0);return}if(a instanceof Fe&&(a.code==="not_found"||a.code==="conversation_deleted")){this.clearFinalizedMarker(t,o);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof Fe?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,o){let n=this.readPendingProjections();if(!n||n.conversationId!==t)return;let r=new Set(o.map(i=>i.id)),a=n.messageIds.filter(i=>!r.has(i));this.setPendingProjections(a.length?{conversationId:t,messageIds:a}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let o=[];for(let n of t.messageIds){let r=this.messages.find(a=>a.id===n);!r||typeof r.content!="string"||o.push({id:n,displayContent:r.content})}if(o.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,o),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof Fe&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,o,n,r,a){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent);return}catch(i){if(!e.isConversationDeleted(i))throw i;let d=await this.recoverFromDeletedConversation(r);if(!d)throw i;this.recordDispatchedProjections([d]),await this.client.dispatch({messages:[d],signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let o=this.messages.find(r=>r.id===t);if(!o)return null;let n={...o};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let a=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(a)}else{this.client.clearClientSession();let a=await this.client.initSession();this.bindActivatedSession(a)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(n),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===n.id)??n}updateConfig(t){let o=this.config.features?.artifacts?.display,n={...this.config,...t},r=Wx(this.config,n),a=EP(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&vo(n.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(o)!==JSON.stringify(n.features?.artifacts?.display);if(!a){this.client.updateConfig(n),i&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let d=this.client.getSSEEventCallback();this.client=new Zs(this.config,this.historyInternals),i&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),d&&this.client.setSSEEventCallback(d)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:n,llmContent:r,contentParts:a,id:i,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:p,rawContent:m}=t,y={id:i??(o==="user"?ti():o==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:n,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let n of t){let{role:r,content:a,llmContent:i,contentParts:d,id:c,createdAt:u,sequence:p,streaming:m=!1,voiceProcessing:h,rawContent:y}=n,C={id:c??(r==="user"?ti():r==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...i!==void 0&&{llmContent:i},...d!==void 0&&{contentParts:d},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};o.push(C)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:n={},text:r="",llmContent:a,id:i,createdAt:d,sequence:c}=t,u={text:r,component:o,props:n};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...a!==void 0&&{llmContent:a},...i!==void 0&&{id:i},...d!==void 0&&{createdAt:d},...c!==void 0&&{sequence:c}})}async applyMentionBundle(t,o,n){let r;try{r=await n()}catch{return}let a=r.blocks.join(`
|
|
20
|
-
|
|
21
|
-
`),i=[a,o].filter(Boolean).join(`
|
|
22
|
-
|
|
23
|
-
`),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(d){let u=[];a&&u.push(un(a)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(c){let u=[];i&&u.push(un(i)),u.push(...r.contentParts),t.contentParts=u}else a&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,o){let n=t.trim(),r=!!o?.replayFields&&(o.replayFields.llmContent!==void 0||o.replayFields.rawContent!==void 0||(o.replayFields.contextMentions?.length??0)>0);if(!n&&(!o?.contentParts||o.contentParts.length===0)&&(!o?.mentions||o.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let a=ti(),i=Zr();this.activeAssistantMessageId=null;let d=o?.contentParts&&li(o.contentParts)?ii:"",c={id:a,role:"user",content:n||d,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts},...o?.mentions&&o.mentions.refs.length>0&&{contextMentions:o.mentions.refs},...o?.contentSegments&&o.contentSegments.length>0&&{contentSegments:o.contentSegments},...o?.composerOptions&&{composerOptions:o.composerOptions},...o?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,o?.mentions){let m=this.messages.find(h=>h.id===a)??c;if(await this.applyMentionBundle(m,n,o.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(o?.quote&&!o.replayFields){let m=this.messages.find(y=>y.id===a)??c,h=QC({quote:o.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...o.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,u,i,a,{composerOptions:o?.composerOptions,interrupt:o?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=Bg(m,this.config.errorMessage);if(y){let x={id:i,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,o){let n=YC(this.messages,t);if(!n)return!1;let r=this.messages[n.start],a=o.replacement,i=a?a.text:r.content,d=a?a.contentParts:r.contentParts;if(!(!!i?.trim()||(d?.length??0)>0||!a&&(r.llmContent?.trim()?.length??0)>0))return!1;let u=a?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},p=a?this.toComposerOptionsPayload(a.options):r.composerOptions,m=a?a.contentSegments:r.contentSegments,h=a?a.options?.quote:void 0,y=a?a.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(i??"",{...d?.length?{contentParts:[...d]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...h?{quote:h}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=Zr();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let i=Bg(r,this.config.errorMessage);if(i){let d={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(d)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let n=o?.preserveAssistantId?o.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==n&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${o.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(r=>{this.webMcpApprovalResolvers.set(n,r)})}resolveWebMcpApproval(t,o){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:o,resolvedAt:Date.now()}}),n(o==="approved")}async resolveApproval(t,o,n){let r=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),d={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(d),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,u=c&&typeof c=="object"?c.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),p){let m=null;if(p instanceof Response){if(!p.ok){let h=await p.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof o=="string"?void 0:o;if(i===void 0&&typeof o=="string"){let p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(i={[h]:o})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=t.toolCall.id,c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===0){let p=typeof o=="string"?o:Object.entries(o).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${d}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let x=p[y],C=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";this.appendMessage({id:`ask-user-q-${d}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${d}-${h}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[a]:o},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.id;if(!o||!n){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(o);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=o;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}resolveWebMcpToolStartedAt(t){let n=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of n)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Vn?!1:(this.messages.find(n=>n.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,n,r=Date.now(),a){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:n,completedAt:r,duration:void 0,durationMs:Math.max(0,r-n)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let n=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=async c=>{let u=c.toolCall?.name,p=c.toolCall?.id;if(!u||!p)return null;let m=`${t}:${p}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),n.push(m);let h=this.markWebMcpToolRunning(c),y=c.agentMetadata?.webMcpToolCallId??u;if(u===Vn)return{dedupeKey:m,resumeKey:y,output:SC(),toolMessage:c,startedAt:h,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(u,c.toolCall?.args,r.signal),C;if(!x)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await x}catch(E){let A=E instanceof Error&&(E.name==="AbortError"||E.message.includes("aborted")||E.message.includes("abort"));return A||this.callbacks.onError?.(E instanceof Error?E:new Error(String(E))),this.markWebMcpToolComplete(c,Dg(A?"Aborted by cancel()":PP(E)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,Dg("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:C,toolMessage:c,startedAt:h,completedAt:Date.now()}},i;if(this.config.webmcp?.execution==="sequential"){i=[];for(let c of o)i.push(await a(c))}else i=await Promise.all(o.map(a));let d=[];try{if(d=i.filter(m=>m!==null),d.length===0)return;let c={};for(let m of d)c[m.resumeKey]=m.output;let u=await this.client.resumeFlow(t,c,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}let p=d[0].dedupeKey;for(let m of d){this.webMcpResolvedKeys.add(m.dedupeKey);let h=m.toolMessage.toolCall?.name,y=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...h===Vn?{suggestRepliesResolved:!0}:{},...h&&y?{clientToolAnswer:{toolCallId:y,toolName:h,args:m.toolMessage.toolCall?.args,result:m.output,batch:p}}:{}})}u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let p of d)this.markWebMcpToolComplete(p.toolMessage,Dg("Aborted by cancel()"),p.startedAt)}finally{for(let c of n)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.name,r=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!n)return;if(!r){let i=`${o}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i))return;this.webMcpInflightKeys.add(i);try{await this.resumeWithToolOutput(o,n,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(i)}catch(d){this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}finally{this.webMcpInflightKeys.delete(i)}return}let a=`${o}:${r}`;if(!(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(o,[t])}async resumeWithToolOutput(t,o,n,r){let a=await this.client.resumeFlow(t,{[o]:n},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!a.ok){let i=await a.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(o,n),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(n),n}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,n=qn(this.config.features?.artifacts,t),r=Pl(n,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(i=>i.id===o);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let o of this.artifacts.values()){let n=this.messages.find(i=>i.id===`artifact-ref-${o.id}`);if(!n)continue;let r=qn(this.config.features?.artifacts,o),a=Pl(r,{artifactId:o.id,title:o.title,artifactType:o.artifactType,status:o.status,...o.file?{file:o.file}:{},...o.presentation?{presentation:o.presentation}:{},...o.component?{component:o.component}:{},...o.props?{componentProps:o.props}:{},...o.markdown!==void 0?{markdown:o.markdown}:{}});n.rawContent!==a&&(n.rawContent=a,n.streaming=o.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let n=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(n)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=rS().then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,n,r)=>t.connectStream(o,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>Bg(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=Zr(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Rg(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ol(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=Rg(o.content||"");if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),n=this.messages.findIndex(r=>r.id===o.id);if(n===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,a)=>{if(a!==n)return r;let i={...r,...o};r.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(i.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(i.agentMetadata={...i.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let d=r.agentMetadata?.clientToolAnswer;if(d&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:d}),r.approval&&o.approval&&r.approval.id===o.approval.id){let m=r.approval,h=o.approval;i.approval={...m,...h,executionId:h.executionId||m.executionId,toolName:h.toolName||m.toolName,description:h.description||m.description,toolType:h.toolType??m.toolType,reason:h.reason??m.reason,parameters:h.parameters??m.parameters}}let c=o.toolCall?.name,u=o.agentMetadata?.executionId,p=o.toolCall?.id;if(c&&sS(c)&&u&&p&&o.agentMetadata?.awaitingLocalTool===!0){let m=`${u}:${p}`,h=this.webMcpInflightKeys.has(m),y=this.webMcpResolvedKeys.has(m),x=r.toolCall?.name,C=r.agentMetadata?.executionId===u&&r.toolCall?.id===p&&x!==void 0&&sS(x)&&r.toolCall?.status==="complete";(h||y||C)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,n)=>{let r=new Date(o.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let i=o.sequence??0,d=n.sequence??0;return i!==d?i-d:o.id.localeCompare(n.id)})}};var kP={add:e=>WC(e)},LP=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,pu={allowedTypes:Cr,maxFileSize:10*1024*1024,maxFiles:4};function IP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function RP(e){return e==="application/pdf"?js:e.startsWith("text/")?js:e.includes("word")?js:e.includes("excel")||e.includes("spreadsheet")?hl:e==="application/json"?gl:yl}var ta=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??pu.allowedTypes,maxFileSize:t.maxFileSize??pu.maxFileSize,maxFiles:t.maxFiles??pu.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:kP}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let o of this.attachments)this.renderPreview(o)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:pu.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let o=[];for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let r=BC(n,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,i);continue}let a={id:IP(),file:n,previewUrl:du(n)?URL.createObjectURL(n):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(a),this.renderPreview(a),o.push(a)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(o.map(n=>this.runAdd(n)))}async runAdd(t){let o=new AbortController;this.pendingAdds.set(t.id,o);let n=()=>this.destroyed||o.signal.aborted||this.pendingAdds.get(t.id)!==o||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:o.signal,onProgress:a=>{n()||t.status!=="uploading"||(t.progress=LP(a),this.updatePreview(t),this.notify())}});if(n())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(n())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===o&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let o=this.attachments.find(n=>n.id===t);!o||o.status!=="error"||this.destroyed||(o.status=this.hasCustomAdapter()?"uploading":"processing",o.progress=this.hasCustomAdapter()?0:void 0,o.error=void 0,this.updatePreview(o),this.notify(),this.runAdd(o))}abortAdd(t){let o=this.pendingAdds.get(t);o&&(this.pendingAdds.delete(t),o.abort())}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let n=this.attachments[o];this.abortAdd(t),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(o,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),n.status==="ready"&&n.contentPart&&this.releasePart(n.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let o=this.config.adapter?.remove;if(o)try{let n=o(t,{signal:new AbortController().signal});n&&typeof n.catch=="function"&&n.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(n){console.error("[AttachmentManager] adapter.remove failed:",n)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=du(t.file),n=I("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",o&&t.previewUrl){let p=I("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",n.appendChild(p)}else{let p=I("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=RP(t.file.type),h=Tt(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=I("span");y.textContent=DC(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",p.appendChild(y),n.appendChild(p)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),a=I("div","persona-attachment-progress");a.appendChild(I("div","persona-attachment-progress__bar"));let i=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),d=ae("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);d?i.appendChild(d):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(a,i),n.appendChild(r);let c=I("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let u=Tt(vl,10,"var(--persona-text-inverse, #ffffff)",2);u?c.appendChild(u):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(c),this.previewsContainer.appendChild(n),this.applyPreviewState(n,t)}updatePreview(t){let o=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);o&&this.applyPreviewState(o,t)}applyPreviewState(t,o){t.dataset.status=o.status;let n=o.status!=="ready"&&o.status!=="error";t.setAttribute("aria-busy",n?"true":"false"),t.title=o.status==="error"?`${o.file.name}: ${o.error??"Upload failed"}`:o.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let a=o.progress;r.style.width=typeof a=="number"?`${Math.round(a*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o,adapter:t?.adapter})}};var aS=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),HP=(e,t)=>e.length===t.length&&e.every((o,n)=>{let r=t[n];return o.id===r.id&&o.name===r.name&&o.mimeType===r.mimeType&&o.size===r.size&&o.status===r.status&&o.progress===r.progress&&o.error===r.error});function iS(){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,o=null,n=!1,r=!1,a=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let p=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),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:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},d=()=>(o||(o=i()),o),c=()=>{if(n=!1,r||t.size===0)return;let p=d();for(let m of[...t])try{m(p)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},u=()=>{o=null,!(r||n)&&(n=!0,queueMicrotask(c))};return{getState:d,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,u())},setAttachments:p=>{HP(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{aS(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{aS(e.activeModeIds,p)||(e.activeModeIds=[...p],u())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,u())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,u())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,u())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,u())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,u())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,u())},flush:()=>{n&&c()},destroy:()=>{r=!0,n=!1,t.clear()}}}var Do=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},lS=(e,t)=>{let o=I("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function dS(e,t={}){let o=Do(e,"[data-persona-composer-form]"),n=Do(e,"[data-persona-composer-input]");if(!o||!n){let A=`[Persona] composer surface is missing required element(s): ${[!o&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(o||n))throw new Error(A);return typeof console<"u"&&console.warn(A),null}let r={header:Do(e,"[data-persona-composer-header]"),body:Do(e,"[data-persona-composer-body]"),actionsStart:Do(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Do(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Do(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Do(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Do(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=lS("persona-widget-composer__header","data-persona-composer-header"),o.parentNode?o.parentNode.insertBefore(i,o):e.appendChild(i));let d=r.body??n.parentElement??o,c=(E,A,M,L,b)=>{if(A)return A;a.add(E);let S=lS(M,L);return b.appendChild(S),S},u=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",o),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",o),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],x=(E,A)=>E.target===A.target&&E.type===A.type&&E.handler===A.handler,C=Do(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:o,input:n,header:i,body:d,actionsStart:u,actionsEnd:p,suggestions:m,status:h,attachmentInput:C,attachmentPreviews:Do(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Do(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Do(e,"[data-persona-composer-submit]")??void 0,micButton:Do(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(E,A,M,L)=>{E.addEventListener(A,M,L),y.push({target:E,type:A,handler:M,options:L})},removeListener:(E,A,M,L)=>{E.removeEventListener(A,M,L),y=y.filter(b=>!x(b,{target:E,type:A,handler:M}))},destroy:()=>{for(let E of y)E.target.removeEventListener(E.type,E.handler,E.options);y=[]}}}var Wt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},co=1e5,ui=co+1;var WP=8,BP=8,Og=10,cS=200,uS=300,pS=0,mu=e=>Math.max(0,e);function fS(e){e.delayMs!==void 0&&(cS=mu(e.delayMs)),e.skipDelayMs!==void 0&&(uS=mu(e.skipDelayMs))}var DP=()=>Date.now()<pS,OP=e=>{pS=e>0?Date.now()+e:0},fu=new WeakMap,Ng="data-persona-tooltip-suppressed",_P=e=>typeof e.closest=="function"&&e.closest(`[${Ng}]`)!==null;function mS(e){fu.get(e)?.hide()}var gS=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,NP=e=>{let t=e.getRootNode?.();return gS(t)?t:e.ownerDocument.body},_g=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),FP=[...["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 ro(e){fu.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=WP,viewportPadding:d=BP}=e,c=()=>t.ownerDocument,u=()=>c().defaultView??window,p=null,m=null,h=null,y=null,x,C=!1,E=!1,A=!1,M=()=>(typeof n=="function"?n():n).trim(),L=()=>(typeof r=="function"?r():r??"").trim(),b=()=>mu(e.delayMs??cS),S=()=>mu(e.skipDelayMs??uS),T=()=>{x!==void 0&&(u().clearTimeout(x),x=void 0)},B=()=>{T();let ge=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,ge&&OP(S())},_=()=>{if(!p)return;let ge=c(),Pe=u(),Ae=t.getBoundingClientRect(),ve=p.getBoundingClientRect(),Gt=ge.documentElement.clientWidth||Pe.innerWidth,Bt=ge.documentElement.clientHeight||Pe.innerHeight,Me=Gt-d-ve.width,N=Ae.left+Ae.width/2-ve.width/2,Oe=_g(N,d,Me),Ve=Ae.top-d,Mo=Bt-d-Ae.bottom,uo=ve.height+i,Xt=Ve>=uo||Ve>=Mo?"top":"bottom",_o=Xt==="top"?Ae.top-i-ve.height:Ae.bottom+i,De=Bt-d-ve.height,Qe=_g(_o,d,De),ke=Ae.left+Ae.width/2,Gn=Math.max(Og,ve.width-Og),j=_g(ke-Oe,Og,Gn);p.dataset.placement=Xt,p.style.left=`${Oe}px`,p.style.top=`${Qe}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${j}px`)},X=()=>{if(A||!a||p||!t.isConnected||_P(t))return;let ge=M(),Pe=NP(t);if(!ge||!Pe)return;let Ae=c(),ve=u();p=Ae.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(ui);let Gt=ve.getComputedStyle?.(t);if(Gt){for(let uo of FP){let Xt=Gt.getPropertyValue(uo).trim();Xt&&p.style.setProperty(uo,Xt)}Gt.fontFamily&&(p.style.fontFamily=Gt.fontFamily)}m=Ae.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ge,p.appendChild(m);let Bt=L();Bt&&(h=Ae.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=Bt,p.appendChild(h));let Me=Ae.createElement("span");Me.className="persona-control-tooltip__arrow",p.appendChild(Me),Pe.appendChild(p),_(),p.dataset.state="open";let N=()=>{if(!t.isConnected){B();return}m&&(m.textContent=M()),h&&(h.textContent=L()),_()};ve.addEventListener("scroll",N,!0),ve.addEventListener("resize",N);let Oe=t.getRootNode(),Ve=gS(Oe)?Oe:Ae.documentElement,Mo=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||B()});Mo?.observe(Ve,{childList:!0,subtree:!0}),y=()=>{ve.removeEventListener("scroll",N,!0),ve.removeEventListener("resize",N),Mo?.disconnect()}},$=ge=>{if(!(A||p)){if(T(),ge||b()<=0||DP()){X();return}x=u().setTimeout(()=>{x=void 0,X()},b())}},k=()=>{C||E?$(E):B()},H=()=>{let ge=u();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(C=!0,k())},F=()=>{C=!1,k()},W=()=>{try{E=t.matches(":focus-visible")}catch{E=!0}k()},oe=()=>{E=!1,k()},V=()=>{C=!1,E=!1,B()},de=ge=>{ge.key==="Escape"&&V()};o.addEventListener("mouseenter",H),o.addEventListener("mouseleave",F),t.addEventListener("focus",W),t.addEventListener("blur",oe),t.addEventListener("keydown",de),t.addEventListener("click",V);let ce={get isOpen(){return p!==null},show:X,hide:B,reposition:_,destroy:()=>{A||(A=!0,B(),o.removeEventListener("mouseenter",H),o.removeEventListener("mouseleave",F),t.removeEventListener("focus",W),t.removeEventListener("blur",oe),t.removeEventListener("keydown",de),t.removeEventListener("click",V),fu.delete(t))}};return fu.set(t,ce),ce}function Fg(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let o=t.getComputedStyle(e).lineHeight;if(!o||!o.trim().endsWith("px"))return 20;let n=parseFloat(o);return Number.isFinite(n)&&n>0?n:20}function gu(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function hS(e,t){e.style.maxHeight=`${t*Fg(e)}px`,e.style.overflowY="auto"}function Nl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function yS(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function bS(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let o=e.metaKey===!0||e.ctrlKey===!0,n=t.submitKey??"enter";return n==="none"?!1:n==="mod-enter"?o:o||!yS(t)}function UP(e){return(e.submitKey??"enter")!=="enter"||yS(e)?"enter":"send"}function hu(e,t){e.setAttribute("enterkeyhint",UP(t))}function yu(e,t){let o=t?.autocomplete;e.setAttribute("autocomplete",typeof o=="string"&&o?o:"off");let n=(r,a)=>{a===void 0?e.removeAttribute(r):e.setAttribute(r,a)};n("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),n("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),n("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),n("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Ug(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Go="persona-composer-control",wn="persona-composer-control--glyph",Vg=40,Co=24,bu=(e,t,o)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let r=n.getComputedStyle(e);for(let a of o){let i=r.getPropertyValue(a).trim();i?t.style.setProperty(a,i):t.style.removeProperty(a)}},vu=(e,t)=>{let o=I("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??tg,o.dir="auto",hu(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Nl(o)}),yu(o,e?.composer?.inputAttributes),o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=gu(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${n*20}px`;o.style.maxHeight=r,o.style.overflowY="auto";let a=()=>{let d=o.style.maxHeight;if(d!==r){let u=parseFloat(d);if(Number.isFinite(u)&&u>0)return u}let c=n*Fg(o);return r=`${c}px`,o.style.maxHeight=r,c},i=()=>{o.addEventListener("input",()=>{o.style.height="auto";let d=Math.min(o.scrollHeight,a());o.style.height=`${d}px`})};return o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"}),{textarea:o,attachAutoResize:i}},VP="[data-persona-glyph-stack]",$g=(e,t,o="send")=>{let n=Q("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":o,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},xu=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,n=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",i=t.tooltipText??"Send message",d=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||Vg,y=t.backgroundColor,x=t.textColor,C=I("div","persona-send-button-wrapper"),E=Q("button",{className:bo("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${Go}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!y&&"persona-bg-persona-primary",!o&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:o?m:void 0,height:o?m:void 0,minWidth:o?m:void 0,minHeight:o?m:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:o&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:o?"0":t.paddingX||void 0,paddingRight:o?"0":t.paddingX||void 0,paddingTop:o?"0":t.paddingY||void 0,paddingBottom:o?"0":t.paddingY||void 0}}),A=null,M=null,L=null;if(o){let T=parseFloat(t.iconSize??"")||Math.round(h*.5),B=t.iconStrokeWidth??2,_=x?.trim()||"currentColor";if(r&&(A=ae(r,T,_,B)),M=ae(a,T,_,B),!t.iconSize)for(let X of[A,M])X&&(X.style.width=`var(--persona-components-composer-sendIconSize, ${T}px)`,X.style.height=`var(--persona-components-composer-sendIconSize, ${T}px)`);A&&M?(L=$g(A,M),E.appendChild(L)):A?E.appendChild(A):(E.textContent=n,M=null)}else E.textContent=c;E.setAttribute("aria-label",i),C.appendChild(E),ro({anchor:E,trigger:C,text:()=>E.getAttribute("aria-label")??"",enabled:p});let b="send";return{button:E,wrapper:C,setMode:T=>{if(T===b)return;b=T;let B=T==="stop"?d:i;E.setAttribute("aria-label",B),E.setAttribute("data-persona-send-mode",T),o?(E.querySelector(VP)??L)?.setAttribute("data-mode",T):E.textContent=T==="stop"?u:c},glyphStack:L}},pi=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let n=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",a=t.provider?.type==="custom";if(!(n||r||a))return null;let d=t.iconName??"mic",c=t.iconSize,u=parseFloat(c??"")||Co,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=I("div","persona-send-button-wrapper"),y=Q("button",{className:bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Go,!c&&wn),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ae(d,u,m||"currentColor",1.5);C?y.appendChild(C):y.textContent="\u{1F3A4}",h.appendChild(y);let E=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return ro({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??E,enabled:A}),{button:y,wrapper:h}},Cu=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=I("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??Cr).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=I("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Go} ${wn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=ae(r,Co,"currentColor",1.5);d?i.appendChild(d):i.textContent="\u{1F4CE}",i.addEventListener("click",u=>{u.preventDefault(),n.click()}),a.appendChild(i);let c=t.buttonTooltipText??"Attach file";return ro({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:a,input:n,previewsContainer:o}},Su=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=I("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status",""),Qs(n,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let a=I("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=r,a.style.color="inherit",a.style.textDecoration="none",n.appendChild(a)}else n.textContent=r;return n},wu=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function $P(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Au(e){let{anchor:t,content:o,placement:n="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:i,verticalOffset:d,zIndex:c=2147483e3,onOpen:u,onDismiss:p}=e,m=e.container??$P(t),h=!1,y=null,x=()=>{if(!h)return;let A=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${A.width}px`),i&&(o.style.maxWidth=`${A.width}px`);let M=o.getBoundingClientRect(),L=d?.()??null,b=L!=null?A.top+L:A.top,S=n==="top-start"||n==="top-end"?b-r-M.height:A.bottom+r,B=n==="bottom-end"||n==="top-end"?A.right-M.width:A.left,_=i?.()??null;if(_!=null){let X=Math.max(A.left,A.right-M.width);B=Math.min(Math.max(A.left+_,A.left),X)}o.style.top=`${S}px`,o.style.left=`${B}px`},C=()=>{h&&(h=!1,y&&(y(),y=null),o.remove())},E=()=>{if(h)return;h=!0,c!=null&&(o.style.zIndex=String(c)),m.appendChild(o),x();let A=(t.ownerDocument??document).defaultView??window,M=t.ownerDocument??document,L=()=>{if(!t.isConnected){C(),p?.("anchor-removed");return}x()},b=T=>{let B=typeof T.composedPath=="function"?T.composedPath():[];B.includes(o)||B.includes(t)||(C(),p?.("outside"))},S=A.setTimeout(()=>{M.addEventListener("pointerdown",b,!0)},0);A.addEventListener("scroll",L,!0),A.addEventListener("resize",L),y=()=>{A.clearTimeout(S),M.removeEventListener("pointerdown",b,!0),A.removeEventListener("scroll",L,!0),A.removeEventListener("resize",L)},u?.()};return{get isOpen(){return h},open:E,close:C,toggle:()=>h?C():E(),reposition:x,destroy:C}}var jP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',zP=["--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"],jg="data-persona-menu-focus",KP=new Set(["ArrowDown","ArrowUp","Home","End"]);function vS(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(jP)??e}var GP=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function xS(e){let t=e.label,o=!1,n=I("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Go} ${wn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(r);let a=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let W=e.getButtonSize?.()??"";r.style.width=W,r.style.height=W,r.style.minWidth=W,r.style.minHeight=W,r.style.lineHeight="1",r.replaceChildren();let oe=ae("plus",Co,"currentColor",1.5);oe?r.appendChild(oe):r.textContent="+"},d=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),a.setAttribute("aria-label",t)};d(),i();let c=[],u=-1,p=!1,m=()=>{let oe=a.getRootNode().activeElement;return oe instanceof HTMLElement?oe:null},h=()=>{let W=m();for(let oe of c){let V=!!W&&vS(oe)===W;oe.toggleAttribute(jg,V&&p)}},y=()=>c.filter(W=>W.isConnected||a.contains(W)).map(vS).filter(W=>!GP(W)),x=(W,oe)=>{W.forEach((V,de)=>{V.setAttribute("tabindex",de===oe?"0":"-1")})},C=W=>{let oe=y();if(oe.length===0)return;let V=(W%oe.length+oe.length)%oe.length;u=V,x(oe,V),oe[V].focus(),h()},E=()=>n.ownerDocument??document,A=null,M=null,L=null,b=()=>{A&&(E().removeEventListener("focusin",A,!0),A=null)},S=()=>{M&&(a.removeEventListener("focusin",M),M=null),L&&(a.removeEventListener("pointerdown",L,!0),L=null)},T=null,B=()=>(T||(T=Au({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),T),_=()=>T?.isOpen===!0,X=(W=!1)=>{if(_()){T?.close(),r.setAttribute("aria-expanded","false"),b(),S(),u=-1,p=!1;for(let oe of c)oe.removeAttribute(jg);W&&r.focus()}},$=(W=0,oe=!1)=>{if(o||_())return;p=oe,bu(r,a,zP),B().open(),r.setAttribute("aria-expanded","true");let V=y();x(V,-1),C(W<0?V.length-1:W),A=de=>{let ce=typeof de.composedPath=="function"?de.composedPath():[];ce.includes(a)||ce.includes(n)||X()},E().addEventListener("focusin",A,!0),M=()=>h(),a.addEventListener("focusin",M),L=()=>{p=!1},a.addEventListener("pointerdown",L,!0)},k=W=>{W.preventDefault(),W.stopPropagation(),_()?X(!0):$(0)},H=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,_()?C(0):$(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,_()?C(-1):$(-1,!0))},F=W=>{switch(KP.has(W.key)&&(p=!0),W.key){case"ArrowDown":W.preventDefault(),C(u+1);return;case"ArrowUp":W.preventDefault(),C(u-1);return;case"Home":W.preventDefault(),C(0);return;case"End":W.preventDefault(),C(y().length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),X(!0);return;case"Tab":X(!0);return;default:}};return r.addEventListener("click",k),r.addEventListener("keydown",H),a.addEventListener("keydown",F),{trigger:n,triggerButton:r,panel:a,setItems:W=>{for(let V of c)W.includes(V)||V.removeAttribute(jg);if(c=[...W],!_())return;let oe=y();x(oe,Math.min(u,oe.length-1)),h()},isOpen:_,open:()=>$(0),close:X,setLabel:W=>{W!==t&&(t=W,d())},applyButtonSize:i,destroy:()=>{o=!0,b(),S(),r.removeEventListener("click",k),r.removeEventListener("keydown",H),a.removeEventListener("keydown",F),T?.destroy(),T=null,n.remove(),a.remove(),c=[]}}}var jn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},CS="data-persona-composer-action",zg="data-persona-composer-disable-when-streaming",XP="core:overflow",QP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function YP(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let o=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(o))return o;let n=I("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 r=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(o)?o:null}function Kg(e){let t=e.clientWidth;if(!t)return 0;let o=e.ownerDocument?.defaultView;if(!o?.getComputedStyle)return t;let n=o.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-r)}var SS=(e,t)=>{!e||typeof console>"u"||console.warn(t)},JP=(e,t)=>t.includes(":")?t:`${e}:${t}`;function ZP(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let c=n.get(d.id);if(c){SS(t,`[Persona] composer action "${d.id}" is already contributed by ${wS(c)}; the ${wS(d)} copy is ignored.`);return}n.set(d.id,d),o.push(d)};for(let d of e.builtIns)a({id:d.id,placement:d.placement,presentation:"bar",order:d.order,sequence:r++,source:"core",builtIn:d});let i=(d,c,u)=>{let p=u?JP(u,d.id):d.id,m=d.order??jn.custom;d.placement==="end"&&m>=jn.send&&(SS(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${jn.send-1}.`),m=jn.send-1),a({id:p,placement:d.placement,presentation:d.presentation??"bar",order:m,sequence:r++,source:c,pluginId:u,action:d})};for(let d of e.configActions??[])i(d,"config");for(let d of e.plugins){if(!d.contributeComposerActions)continue;let c;try{c=d.contributeComposerActions(e.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${d.id}" contributeComposerActions failed:`,u);continue}for(let u of c??[])i(u,"plugin",d.id)}return o.sort((d,c)=>d.order===c.order?d.sequence-c.sequence:d.order-c.order)}var wS=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",AS=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,ek=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function tk(e,t){if(!e||e==="always")return!0;let o=ek(t);return e==="when-text"?o:!o}var ss=e=>e.kind==="custom",Gg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,ok=e=>{let t=Gg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},nk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function rk(e){let t="",o=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.nodeValue??"";return}if(n.nodeType!==Node.ELEMENT_NODE)return;let r=n;typeof r.matches=="function"&&r.matches(nk)||n.childNodes.forEach(o)};return o(e),t.trim()}var sk=e=>rk(e).length===0;function MS(e){let t=new Map,o=[],n=!1,r=()=>e.getButtonSize?.(),a=(k,H)=>{let F=k.button;if(!F)return;F.setAttribute("role","menuitem"),F.setAttribute("tabindex","-1"),F.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])F.style[V]="";F.style.lineHeight="1",H.tooltipText?F.setAttribute("title",H.tooltipText):F.removeAttribute("title"),F.replaceChildren();let W=I("span","persona-composer-overflow-menu__icon");if(H.iconName){let V=ae(H.iconName,16,"currentColor",1.5);V&&W.appendChild(V)}let oe=I("span","persona-composer-overflow-menu__label");oe.textContent=H.shortLabel??H.label,F.append(W,oe)},i=(k,H)=>{let F=k.button;if(!F)return;if(F.setAttribute("aria-label",H.label),H.pressed===void 0?F.removeAttribute("aria-pressed"):F.setAttribute("aria-pressed",H.pressed?"true":"false"),F.toggleAttribute(zg,H.disableWhenStreaming===!0),k.mode==="menu"){k.tooltip?.destroy(),k.tooltip=void 0,a(k,H);return}F.removeAttribute("role"),F.removeAttribute("tabindex"),F.removeAttribute("title");let W=r(),oe=!!H.shortLabel;if(F.className=bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Go,wn,oe&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),F.style.width=W&&!oe?W:"",F.style.height=W??"",F.style.minWidth=W&&!oe?W:"",F.style.minHeight=W??"",F.style.fontSize=oe?"":"18px",F.style.lineHeight="1",F.style.color=H.iconColor??"",F.style.backgroundColor=H.backgroundColor??"",F.replaceChildren(),H.iconName){let V=ae(H.iconName,Co,"currentColor",1.5);V&&F.appendChild(V)}if(oe){let V=I("span","persona-composer-action-button__label");V.textContent=H.shortLabel,F.appendChild(V)}else F.firstChild||(F.textContent=H.label);k.tooltip?.destroy(),k.tooltip=ro({anchor:F,trigger:k.element,text:()=>H.tooltipText??H.label,enabled:!!H.tooltipText})},d=(k,H)=>{let F=k.action,W=Q("button",{attrs:{type:"button"}}),oe=W;if(H==="bar"){let ce=I("div","persona-send-button-wrapper");ce.appendChild(W),oe=ce}oe.setAttribute(CS,k.id);let V={resolved:k,element:oe,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:H},de=ce=>{if(ce.preventDefault(),ce.stopPropagation(),V.busy||W.disabled)return;let ge=V.resolved.action;V.mode==="menu"&&y?.close(!0);let Pe;try{Pe=ge.onSelect(e.actionContext,ce)}catch(Ae){e.reportError(Ae,{actionId:V.resolved.id});return}!Pe||typeof Pe.then!="function"||(V.busy=!0,W.setAttribute("aria-busy","true"),Pe.catch(Ae=>{e.reportError(Ae,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",de),V.detach=()=>W.removeEventListener("click",de),i(V,F),V},c=k=>{let H=k.action,F;try{F=H.render({...e.actionContext,id:k.id,action:H})}catch(W){return e.reportError(W,{actionId:k.id}),null}return F?.element?(F.element.setAttribute(CS,k.id),F.element.toggleAttribute(zg,H.disableWhenStreaming===!0),{resolved:k,element:F.element,owned:!0,managed:!0,destroy:F.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(k,H)=>{if(k.builtIn){let W=k.builtIn.element;return W?{resolved:k,element:W,owned:!1,managed:k.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let F=k.action;return F?ss(F)?c(k):d(k,H):null},p=k=>{if(k.detach?.(),k.tooltip?.destroy(),k.detachMenuSlot?.(),k.detachMenuSlot=void 0,k.menuLabel?.remove(),k.menuLabel=void 0,k.menuSlot?.remove(),k.menuSlot=void 0,k.owned){try{k.destroy?.()}catch(H){e.reportError(H,{actionId:k.resolved.id})}k.element.remove()}},m=(k,H)=>{for(let F=0;F<H.length;F++){let W=H[F];if(!W.managed)continue;let oe=null;for(let V=F+1;V<H.length;V++){let de=H[V];if(!de.managed&&de.element.parentElement===k){oe=de.element;break}}oe?(W.element.parentElement!==k||W.element.nextSibling!==oe)&&k.insertBefore(W.element,oe):k.lastChild!==W.element&&k.appendChild(W.element)}},h=(k,H)=>{if(k.button){k.button.disabled=H;return}if(!k.owned)return;let F=k.element;F.toggleAttribute("data-disabled",H),F.setAttribute("aria-disabled",H?"true":"false");let W=F instanceof HTMLButtonElement||F instanceof HTMLSelectElement||F instanceof HTMLInputElement||F instanceof HTMLTextAreaElement?F:F.querySelector("button, select, input, textarea");W&&(W.disabled=H)},y=null,x=null,C=null,E=0,A=()=>{let k=e.getOverflow?.();return k?.enabled===!0?k:void 0},M=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=xS({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),L=k=>{x!==k&&(C?.disconnect(),x=k,E=Kg(k),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(H=>{let W=H[H.length-1]?.contentRect?.width??Kg(k);W!==E&&(E=W,X())}),C.observe(k)))},b=(k,H)=>{let F=YP(k.collapseAutoActionsBelow,H);if(F===null)return!1;let W=E||Kg(H);return W>0&&W<F},S=(k,H,F)=>{if(!H)return"bar";if(k.resolved.builtIn){let oe=QP(k.resolved.id);return oe&&H.includeBuiltIns?.includes(oe)?"menu":"bar"}let W=k.resolved.presentation;return W==="overflow"||W==="auto"&&F?"menu":"bar"},T=k=>{let H=k.menuSlot;if(!H)return;if(!sk(k.element)){k.menuLabel?.remove(),k.menuLabel=void 0;return}let F=ok(k.element);if(!F){k.menuLabel?.remove(),k.menuLabel=void 0;return}k.menuLabel||(k.menuLabel=I("span","persona-composer-overflow-menu__label")),k.menuLabel.textContent!==F&&(k.menuLabel.textContent=F),k.menuLabel.parentElement!==H&&H.appendChild(k.menuLabel)},B=(k,H)=>{if(k.mode===H)return k;let F=k.resolved.action;if(F&&!ss(F)){p(k),t.delete(k.resolved.id);let W=d(k.resolved,H);return t.set(k.resolved.id,W),W}if(H==="menu"){let W=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Ng]:""}});W.appendChild(k.element),mS(Gg(k.element)),k.menuSlot=W;let oe=V=>{let de=Gg(k.element);if(de.disabled)return;let ce=V.target===de||de.contains(V.target);y?.close(!0),ce||de.click()};W.addEventListener("click",oe,!0),k.detachMenuSlot=()=>W.removeEventListener("click",oe,!0),k.managed=!0,T(k)}else k.detachMenuSlot?.(),k.detachMenuSlot=void 0,k.menuLabel?.remove(),k.menuLabel=void 0,k.menuSlot?.remove(),k.menuSlot=void 0;return k.mode=H,k},_=(k,H)=>{let F=H.map(W=>W.menuSlot??W.element);for(F.forEach((W,oe)=>{let V=k.children[oe];V!==W&&(V?k.insertBefore(W,V):k.appendChild(W))});k.children.length>F.length;)k.lastElementChild?.remove()},X=()=>{if(n)return;let k=e.getBindings();if(!k)return;let H=e.getState(),F=H.phase==="streaming",W=A();W&&L(k.footer);let oe=W?b(W,k.footer):!1,V={start:[],end:[]},de=[];for(let ce of o){let ge=t.get(ce.id);if(!ge)continue;let Pe=ce.action,Ae=Pe?AS(Pe.visible,H,!0)&&tk(Pe.visibility,H):!0;if(ge.visible!==Ae&&(ge.visible=Ae,!Ae&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!Ae){if(ge=B(ge,S(ge,W,oe)),Pe){let ve=AS(Pe.disabled,H,!1)||Pe.disableWhenStreaming===!0&&F;h(ge,ve),!ss(Pe)&&Pe.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Pe.pressed?"true":"false")}ge.mode==="menu"?(T(ge),de.push(ge)):V[ce.placement].push(ge)}}if(de.length>0){let ce=M();_(ce.panel,de),ce.setItems(de.map(ve=>ve.menuSlot??ve.element)),ce.applyButtonSize();let ge=Number.isFinite(W?.order)?W?.order:jn.overflow,Pe=V.start.findIndex(ve=>ve.resolved.order>ge),Ae={resolved:{id:XP,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:ce.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(Pe<0?V.start.length:Pe,0,Ae)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(k.actionsStart,V.start),m(k.actionsEnd,V.end)};return{resolve:()=>{if(n)return;let k=ZP(e.collect()),H=new Set(k.map(F=>F.id));for(let[F,W]of t)H.has(F)||(p(W),t.delete(F));for(let F of k){let W=t.get(F.id);if(!W){let ce=u(F,"bar");ce&&t.set(F.id,ce);continue}let oe=W.resolved.action,V=F.action;if(!!oe!=!!V||oe&&V&&ss(oe)!==ss(V)||oe&&V&&ss(oe)&&ss(V)&&oe.render!==V.render){p(W),t.delete(F.id);let ce=u(F,W.mode);ce&&t.set(F.id,ce);continue}W.resolved=F,F.builtIn?(W.managed=F.builtIn.managed===!0||W.mode==="menu",F.builtIn.element&&W.mode==="bar"&&(W.element=F.builtIn.element)):V&&!ss(V)?i(W,V):V&&W.element.toggleAttribute(zg,V.disableWhenStreaming===!0)}o=k,X()},sync:X,getResolved:()=>o,getOverflowMenu:()=>y,destroy:()=>{if(!n){n=!0,C?.disconnect(),C=null,x=null;for(let k of t.values())p(k);t.clear(),y?.destroy(),y=null,o=[]}}}}var ak="core:model",ik=700,TS=16,lk=["--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"],ES=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function PS(e){let t=e.label??"Model",o=e.presentation??"native",n=null,r=c=>{let u=e.getSelectedModelId();return c.find(p=>p.id===u)??c[0]},a=()=>{let c=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),u="",p=()=>{let C=e.getModels(),E=C.map(A=>`${A.id}:${A.label}`).join("|");E!==u&&(u=E,c.replaceChildren(...C.map(A=>{let M=Q("option",{attrs:{value:A.id}});return M.textContent=A.label,M}))),c.value=r(C)?.id??""};p(),n=p;let m=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",m);let h=C=>C.stopPropagation();c.addEventListener("click",h);let{wrapper:y,chevron:x}=ES();return y.append(c,x),{element:y,destroy:()=>{n===p&&(n=null),c.removeEventListener("change",m),c.removeEventListener("click",h)}}},i=()=>{let c=Q("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"}}),u=I("span","persona-composer-model-picker-label"),p=I("span","persona-composer-model-picker-suffix");c.append(u,p);let m=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",x=null,C=()=>x?.isOpen===!0,E=(H=!1)=>{C()&&(x?.close(),c.setAttribute("aria-expanded","false"),H&&c.focus())},A=H=>{let F=[...h.values()];if(F.length===0)return;let W=(H%F.length+F.length)%F.length;F[W].focus()},M=H=>{if(C())return;x||(x=Au({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),bu(c,m,lk),x.open(),c.setAttribute("aria-expanded","true");let W=[...h.keys()].indexOf(r(e.getModels())?.id??"");A(H??(W>=0?W:0))},L=H=>{E(!0),e.onSelect(H)},b=H=>{H.preventDefault(),H.stopPropagation();let F=H.currentTarget.getAttribute("data-persona-model-option");F&&L(F)},S=H=>{let F=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":H.id}});if(H.icon){let ce=ae(H.icon,TS,"currentColor",1.5);if(ce){let ge=I("span","persona-composer-model-option-icon");ge.appendChild(ce),F.appendChild(ge)}}let W=I("span","persona-composer-model-option-body"),oe=I("span","persona-composer-model-option-label");if(oe.textContent=H.label,W.appendChild(oe),H.description){let ce=I("span","persona-composer-model-option-description");ce.textContent=H.description,W.appendChild(ce)}F.appendChild(W);let V=I("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let de=ae("check",TS,"currentColor",2);return de&&V.appendChild(de),F.appendChild(V),F.addEventListener("click",b),F},T=()=>{let H=e.getModels(),F=H.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(F!==y){y=F;for(let V of h.values())V.removeEventListener("click",b);h.clear(),m.replaceChildren(...H.map(V=>{let de=S(V);return h.set(V.id,de),de}))}let W=r(H);for(let[V,de]of h)de.setAttribute("aria-selected",String(V===W?.id));u.textContent=W?.label??"";let oe=e.getSuffix?.()??"";p.textContent=oe,c.setAttribute("aria-label",[t,[W?.label,oe].filter(Boolean).join(" ")].filter(Boolean).join(": "))};T(),n=T;let B=H=>{H.preventDefault(),H.stopPropagation(),C()?E(!0):M()},_=H=>{if(H.key==="ArrowDown"){H.preventDefault(),C()?A(0):M(0);return}H.key==="ArrowUp"&&(H.preventDefault(),C()?A(-1):M(-1))},X=H=>{let F=[...h.values()],W=F.indexOf(H.target?.closest?.(".persona-composer-model-option"));switch(H.key){case"ArrowDown":H.preventDefault(),A(W+1);return;case"ArrowUp":H.preventDefault(),A(W-1);return;case"Home":H.preventDefault(),A(0);return;case"End":H.preventDefault(),A(F.length-1);return;case"Escape":H.preventDefault(),H.stopPropagation(),E(!0);return;case"Tab":E(!0);return;default:}};c.addEventListener("click",B),c.addEventListener("keydown",_),m.addEventListener("keydown",X);let{wrapper:$,chevron:k}=ES();return $.append(c,k),{element:$,destroy:()=>{n===T&&(n=null),c.removeEventListener("click",B),c.removeEventListener("keydown",_),m.removeEventListener("keydown",X);for(let H of h.values())H.removeEventListener("click",b);h.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:ak,kind:"custom",placement:"end",order:ik,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var Xg="[data-persona-composer-chip-row]";function Mu(e){e.style.display=e.childElementCount>0?"flex":"none"}function Qg(e){let t=e.querySelector(Xg);if(t)return t;let o=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});o.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(o,n):e.appendChild(o),o}var dk=":scope > [data-persona-composer-mode]";function kS(e){let t=e.row,o="",n=!1,r=new Set(e.initialIds??[]),a=u=>{let p=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let x=I("span","persona-mention-chip-icon"),C=ae(u.iconName,12,"currentColor",1.5);C&&x.appendChild(C),p.appendChild(x)}let m=I("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,p.appendChild(m);let h=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),y=ae("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),e.onRemove(u.id)}),p.appendChild(h),p},i=()=>Array.from(t.querySelectorAll(dk)),d=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),Mu(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!h||h==="none"){p();return}u.addEventListener("animationend",p,{once:!0}),u.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let u of i())u.remove()};return{element:t,render:(u,p)=>{if(n)return;let m=p.filter(C=>u.includes(C.id)),h=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(h===o)return;o=h;let y=new Map;for(let C of i()){let E=C.getAttribute("data-persona-composer-mode");E&&m.some(M=>M.id===E)&&!C.hasAttribute("data-persona-chip-exit")?y.set(E,C):C.hasAttribute("data-persona-chip-exit")||d(C)}let x=t.firstChild;for(let C of m){let E=y.get(C.id);E||(E=a(C),r.has(C.id)||(E.setAttribute("data-persona-chip-enter",""),E.addEventListener("animationend",()=>E?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),E!==x&&t.insertBefore(E,x),x=E.nextSibling}Mu(t)},destroy:()=>{n=!0,c(),Mu(t)}}}var LS=e=>`core:mode:${e}`;var Yg=e=>Math.min(300+e,499),IS=e=>`core:mode-group:${e}`;function Tu(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function ck(e,t){return e?t?.find(o=>o.id===e)?.chipVisibility==="hidden":!1}function RS(e,t){return e?.length?e.filter(o=>!Tu(o.groupId,t)&&!ck(o.groupId,t)):[]}var uk=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function HS(e,t,o,n){let r=o.find(d=>d.id===t);if(!r)return[...e];let a=e.includes(t),i=new Set(e);if(a)i.delete(t);else{if(uk(r,n)==="single"){let d=o.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!d.includes(c)))}i.add(t)}return o.filter(d=>i.has(d.id)).map(d=>d.id)}function Eu(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function WS(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function BS(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var pk=16;function DS(e){let t=null;return{action:{id:IS(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let n=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,a="",i=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},d=u=>{let p=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let h=ae(u.iconName,pk,"currentColor",1.5);h&&p.appendChild(h)}let m=I("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,p.appendChild(m),p.addEventListener("click",i),p},c=()=>{let u=e.getGroup();u?.label?(n.setAttribute("role","group"),n.setAttribute("aria-label",u.label)):(n.removeAttribute("role"),n.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==a){a=m;for(let x of r.values())x.removeEventListener("click",i);r.clear();let y=p.map(x=>{let C=d(x);return r.set(x.id,C),C});n.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,x]of r)x.setAttribute("aria-pressed",String(h.includes(y)))};return c(),t=c,{element:n,destroy:()=>{t===c&&(t=null);for(let u of r.values())u.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}function OS(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let o="",n=!1,r=a=>{let i=I("span","persona-composer-quote-bar"),d=I("div","persona-composer-quote-content");if(a.sourceLabel){let m=I("div","persona-composer-quote-source");m.textContent=a.sourceLabel,d.appendChild(m)}let c=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=uu(a.text),d.appendChild(c);let u=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=ae("x",12,"currentColor",2);p?u.appendChild(p):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,d,u)};return{element:t,render:a=>{if(n)return;let i=a?`${a.sourceLabel??""}\0${a.text}`:"";if(i!==o){if(o=i,!a){t.replaceChildren(),t.style.display="none";return}r(a),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function _S(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let o,n=!1,r=(i,d,c,u)=>{let p=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":d,[c]:""}}),m=ae(i,12,"currentColor",2);return m?p.appendChild(m):p.textContent=d,p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),p},a=i=>{let d=uu(i.text??"",90);if(d)return d;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(n||i===o)return;if(o=i,!i){t.replaceChildren(),t.style.display="none";return}let d=I("span","persona-composer-pending-badge");d.textContent=e.label??"Sends next";let c=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=a(i),t.replaceChildren(d,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function NS(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),o=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});o.value=e.initialText;let n=()=>{o.style.height="auto",o.style.height=`${o.scrollHeight}px`};o.addEventListener("input",n);let r=I("div","persona-message-edit-actions"),a=(d,c,u,p)=>{let m=Q("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[u]:""},text:d});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),m},i=()=>{let d=o.value.trim();d&&e.onSave(d)};return r.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",i)),o.addEventListener("keydown",d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),e.onCancel();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}),t.append(o,r),{element:t,getValue:()=>o.value,focus:()=>{o.focus();let d=o.value.length;o.setSelectionRange(d,d),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function FS(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}}:{}}}function US(e,t){if(!e||typeof e.text!="string")return;let o=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(c=>o.has(c.sourceId)),r=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>a.has(c)),d=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:n}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...d?{selectedModelId:d}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function qS(e){let t=e.delay??500,o=null,n=!1,r=()=>{o!==null&&(clearTimeout(o),o=null)};return{schedule:()=>{n||(r(),o=setTimeout(()=>{o=null,e.write()},t))},flush:()=>{n||o===null||(r(),e.write())},cancel:r,destroy:()=>{n=!0,r()}}}function VS(e){return e.wrapped||e.text.includes(`
|
|
24
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function $S(){let e=!1;return{observe:(t,o)=>o?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function jS(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let o=t.getComputedStyle(e),n=Number.parseFloat(o.lineHeight),r=Number.parseFloat(o.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(r)&&r>0?r*1.4:0;if(!a)return!1;let i=(Number.parseFloat(o.paddingTop)||0)+(Number.parseFloat(o.paddingBottom)||0);return e.scrollHeight-i>a*1.5}function zS(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Jg(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 GS(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var fk=e=>typeof e?.then=="function";function KS(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function XS(e,t,o){let n;try{n=e(Jg(t),{signal:o})}catch(r){return{status:"error",error:r}}return fk(n)?Promise.resolve(n).then(r=>o.aborted?{status:"aborted"}:KS(t,r),r=>o.aborted?{status:"aborted"}:{status:"error",error:r}):KS(t,n)}var QS=/\s/;function mk(e,t,o){if(o==="input-start")return t===0;let n=t>0?e[t-1]:"";return o==="line-start"?n===""||n===`
|
|
25
|
-
`:n===""||QS.test(n)}function gk(e,t,o="@",n="anywhere",r=!1){if(!o||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let i=e[a];if(i===o)return mk(e,a,n)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(i===`
|
|
26
|
-
`||i==="\uFFFC"||!r&&QS.test(i))return null;a--}return null}function YS(e,t,o){for(let n of o){let r=gk(e,t,n.trigger,n.position??"anywhere",n.allowSpaces??!1);if(r)return{channel:n,match:r}}return null}function JS(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function ZS(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},o=(e.triggers??[]).map(n=>({trigger:n.trigger,position:n.triggerPosition??"anywhere",allowSpaces:n.allowSpaces??!1,sources:Array.isArray(n.sources)?n.sources:[],searchPlaceholder:n.searchPlaceholder,showButton:n.showButton===!0,buttonIconName:n.buttonIconName,buttonTooltipText:n.buttonTooltipText}));return[t,...o]}function ew(e){let{config:t,onOpen:o}=e,n=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",a=I("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Go} ${wn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),d=ae(n,Co,"currentColor",1.5);return d?i.appendChild(d):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),o()}),a.appendChild(i),ro({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:a}}var{setLoader:hk,load:yk}=vt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),tw=hk,Zg=yk;var{setLoader:bk,load:vk}=vt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),ow=bk,nw=vk;function Fl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let o=Q("span",{className:bo("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&&o.style.setProperty("--persona-mention-token-accent",e.color);let n=ae(e.iconName??"at-sign",13,"currentColor",2);if(n){let r=I("span","persona-mention-token-icon");r.appendChild(n),o.appendChild(r)}return o.appendChild(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),o}function rw(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let o=ZS(t).filter(b=>b.sources.length>0);if(o.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let n=o.filter(b=>b.sources.some(S=>typeof S.matchCommand=="function")),r=b=>n.some(S=>S.trigger?S.position==="line-start"?b.split(`
|
|
27
|
-
`).some(B=>B.startsWith(S.trigger)):(S.position==="anywhere"?b:b.split(`
|
|
28
|
-
`)[0]).startsWith(S.trigger):!1),a=(b,S)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${b}`,{detail:S}))}catch{}},i=!e.chipRow,d=e.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,u=null,p=e.textarea,m=null,h=null,y=null,x=null,C=()=>{if(c)return Promise.resolve(c);if(u)return u;let b=Zg().then(S=>(S.setMentionIconRenderer(ae),c=S.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:L,emit:a}),c)).catch(S=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",S),u===b&&(u=null),null));return u=b,b},E=()=>{nw().then(b=>{let S=b.mountInlineComposer({textarea:e.textarea,renderToken:B=>Fl(B,{render:t.renderMentionToken}),onMentionRemoved:B=>c?.untrackMention(B)});m=S.input,h=S.destroy;let T=p;T.replaceWith(S.element),p=S.element,x={next:S.element,prev:T},y?.(S.element,T),c?c.rebindComposer(S.input):u&&u.then(B=>B?.rebindComposer(S.input))}).catch(b=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",b)})};t.display==="inline"&&E();let A=[],M=new Map;for(let b of o){if(!b.showButton)continue;let S=ew({config:{...t,buttonIconName:b.buttonIconName,buttonTooltipText:b.buttonTooltipText},onOpen:()=>{C().then(T=>T?.openMenu(b.trigger))}});A.push(S),M.set(b.trigger,S.button)}let L=(b,S,T)=>{let B=M.get(S);B&&(B.setAttribute("aria-expanded",b?"true":"false"),b?B.setAttribute("aria-controls",T):B.removeAttribute("aria-controls"))};return{affordanceButtons:A.map(b=>b.wrapper),contextRow:d,handleInput:b=>{if(c){c.handleInput();return}if(!JS(b))return;let S=p,T=S.selectionStart??0;YS(S.value,T,o)&&C().then(B=>B?.handleInput())},handleKeydown:b=>{if(c?.isMenuOpen())return c.handleKeydown(b);if(b.key==="Backspace"&&c?.hasMentions()&&!x){let S=p,T=S.selectionStart===0&&S.selectionEnd===0;if((S.value.length===0||T)&&c.removeLastChip())return b.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async b=>r(b)?(c??await C())?.dispatchInlineCommand(b)??null:null,clear:()=>c?.clear(),prefetch:()=>{Zg().catch(()=>{})},onComposerSwap:b=>{y=b,x&&b(x.next,x.prev)},destroy:()=>{c?.destroy(),h?.();for(let b of A)b.wrapper.remove();i&&d.remove()}}}var Pu=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),ku={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"};var Iu="16px",Ru="transparent",xk=(()=>{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]=t===0?"0px":`${t/4}rem`;return e})(),Ul={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:xk,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"}},Lu={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"}},Xo={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:Gs,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Iu,canvasBackground:Ru,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"}}},Ck=Ul.colors.gray,Sk={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},aw={...Ul,colors:{...Ul.colors,gray:Ck}},wk={...Ul,colors:{...Ul.colors,gray:Sk},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},iw=aw,lw=Lu,Ak={...Lu,colors:{...Lu.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Lu.typography,fontSize:"14px",lineHeight:"1.5"}},dw=lw,Hu=Xo,Mk={...Xo,launcher:ku,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:{...Xo.input,borderRadius:"palette.radius.full"},introCard:{...Xo.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Xo.suggestion.chip,fontWeight:"400"},card:{...Xo.suggestion.card,fontWeight:"400"},list:{...Xo.suggestion.list,fontWeight:"400"}},panel:{...Xo.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Xo.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:{...Xo.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Xo.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:{...Xo.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...Xo.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)"}},cw=Hu,Tk=e=>Xr({future:e}),th=e=>Tk(e)==="v5"?{palette:wk,semantic:Ak,components:Mk}:{palette:aw,semantic:lw,components:Hu};function ao(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?ao(e,n):n}function Wu(e){let t={};function o(n,r){for(let[a,i]of Object.entries(n)){let d=`${r}.${a}`;if(typeof i=="string"){let c=ao(e,i);c!==void 0&&(t[d]={path:d,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&o(i,d)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function oh(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function uw(e,t){let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?o[n]=uw(a,r):o[n]=r}return o}function Ek(e,t){return t?uw(e,t):e}function ql(e,t={}){let o=th(t.future),n={palette:o.palette,semantic:o.semantic,components:o.components},r={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:Ek(n.components,e?.components)},a=e?.components?.activity;for(let u of["toolBubble","reasoningBubble"])for(let p of["rowHeight","labelSize","iconSize","indent","bodySurface"])a?.[p]!==void 0&&(r.components[u][p]=a[p]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&a?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let d=e?.components?.header;d?.padding!==void 0&&d.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let u=oh(r);if(!u.valid)throw new Error(`Theme validation failed: ${u.errors.map(p=>p.message).join(", ")}`)}if(t.plugins)for(let u of t.plugins)r=u.transform(r);return r}var eh=e=>e.trim()==="0"?"0px":e,sw="--persona-",Pk=e=>{if(!e)return;let t=e.trim().toLowerCase(),o;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?o=[0,1,2].map(d=>parseInt(i[d]+i[d],16)):(i.length===6||i.length===8)&&(o=[0,2,4].map(d=>parseInt(i.slice(d,d+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let d=i[1].split(/[,/\s]+/).filter(Boolean);d.length>=3&&(o=d.slice(0,3).map(c=>{let u=c.endsWith("%"),p=parseFloat(u?c.slice(0,-1):c);return u?p/100*255:p}))}}if(!o||o.some(i=>!Number.isFinite(i)))return;let[n,r,a]=o.map(i=>{let d=Math.max(0,Math.min(255,i))/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*n+.7152*r+.0722*a},kk=.179,so=(e,t)=>{for(let[o,...n]of t){let r;for(let a of n)if(r=a.charCodeAt(0)===61?a.slice(1):e[sw+a],r!==void 0)break;r!==void 0&&(e[sw+o]=r)}};function Bu(e){let t=Wu(e),o={};for(let[N,Oe]of Object.entries(t)){let Ve=N.replace(/\./g,"-");o[`--persona-${Ve}`]=Oe.value}so(o,[["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=o["--persona-components-launcher-foreground"];o["--persona-launcher-fg-muted"]=n&&n!==o["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:o["--persona-muted"],so(o,[["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"]]),so(o,[["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"]]),o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,so(o,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??Iu,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??Ru,so(o,[["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"]]),so(o,[["header-bg","components-header-background","surface"]]);let r=o["--persona-header-bg"],a=o["--persona-components-header-foreground"],i=a?`color-mix(in srgb, ${a} 72%, ${r})`:void 0;o["--persona-header-border"]=o["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${r})`:void 0)??o["--persona-divider"],so(o,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),o["--persona-header-title-fg"]=o["--persona-components-header-title-color"]??o["--persona-components-header-titleForeground"]??a??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitle-color"]??o["--persona-components-header-subtitleForeground"]??i??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??i??o["--persona-muted"],so(o,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let d=e.components?.header;d?.shadow&&(o["--persona-header-shadow"]=d.shadow),d?.borderBottom&&(o["--persona-header-border-bottom"]=d.borderBottom),d?.minHeight&&(o["--persona-header-min-height"]=d.minHeight);let c=o["--persona-components-history-railHeader-background"];c&&(o["--persona-history-rail-header-bg"]=c);let u=o["--persona-components-history-railHeader-border"];u&&(o["--persona-history-rail-header-border"]=u);let p=o["--persona-components-history-railHeader-minHeight"];p&&(o["--persona-history-rail-header-min-height"]=p);for(let[N,Oe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ve=o[`--persona-components-history-overlay-${N}`];Ve&&(o[`--persona-history-overlay-${Oe}`]=Ve)}for(let[N,Oe]of[["background","bg"],["borderRadius","radius"]]){let Ve=o[`--persona-components-history-menu-${N}`];Ve&&(o[`--persona-history-menu-${Oe}`]=Ve)}let m=e.components?.history?.motion;if(m){let N=Mo=>{if(Mo===void 0)return;let uo=String(Mo).trim();return/^\d+(\.\d+)?$/.test(uo)?`${uo}ms`:uo},Oe=N(m.enterDurationMs);Oe!==void 0&&(o["--persona-history-enter-ms"]=Oe);let Ve=N(m.exitDurationMs);Ve!==void 0&&(o["--persona-history-exit-ms"]=Ve),m.enterEasing&&(o["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(o["--persona-history-exit-easing"]=m.exitEasing)}let h=o["--persona-components-history-dangerForeground"];h&&(o["--persona-history-danger-fg"]=h),o["--persona-danger"]=o["--persona-components-history-confirm-dangerBackground"]??o["--persona-palette-colors-error-700"]??"#b42318",o["--persona-danger-fg"]=o["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let N of["scrim","shadow"]){let Oe=o[`--persona-components-history-confirm-${N}`];Oe&&(o[`--persona-history-confirm-${N}`]=Oe)}for(let[N,Oe]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ve=o[`--persona-components-tooltip-${N}`];Ve&&(o[`--persona-tooltip-${Oe}`]=Ve)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[N,Oe]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ve=o[`--persona-components-messageActions-${N}`];Ve&&(o[`--persona-message-action-${Oe}`]=Ve)}so(o,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=o["--persona-components-introCard-background"],x=o["--persona-components-introCard-shadow"],C=(!y||y==="transparent"||y==="none")&&(!x||x==="none"),E=o["--persona-components-introCard-padding"]??"1.5rem";o["--persona-intro-card-padding"]=C&&E==="1.5rem"?"1.5rem 0":E,so(o,[["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"]]),so(o,[["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 A=o["--persona-components-markdown-heading-h1-fontSize"];A&&(o["--persona-md-h1-size"]=A);let M=o["--persona-components-markdown-heading-h1-fontWeight"];M&&(o["--persona-md-h1-weight"]=M);let L=o["--persona-components-markdown-heading-h2-fontSize"];L&&(o["--persona-md-h2-size"]=L);let b=o["--persona-components-markdown-heading-h2-fontWeight"];b&&(o["--persona-md-h2-weight"]=b);let S=o["--persona-components-markdown-prose-fontFamily"];S&&S!=="inherit"&&(o["--persona-md-prose-font-family"]=S),so(o,[["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"]]),so(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),so(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),so(o,[["md-hr-color","components-markdown-hr-color","divider"]]),so(o,[["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 T=[["container","surface"],["surface","surface"],["border","border"]];for(let[N,Oe]of T){let Ve=o[`--persona-components-collapsibleWidget-${N}`]??o[`--persona-${Oe}`];Ve!==void 0&&(o[`--persona-cw-${N}`]=Ve,o[`--cw-${N}`]=Ve)}so(o,[["message-border","components-message-border","border"]]),so(o,[["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 B=e.components,_=B?.iconButton;_&&(_.background&&(o["--persona-icon-btn-bg"]=_.background),_.border&&(o["--persona-icon-btn-border"]=_.border),_.color&&(o["--persona-icon-btn-color"]=_.color),_.padding&&(o["--persona-icon-btn-padding"]=_.padding),_.borderRadius&&(o["--persona-icon-btn-radius"]=_.borderRadius),_.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=_.hoverBackground),_.hoverColor&&(o["--persona-icon-btn-hover-color"]=_.hoverColor),_.activeBackground&&(o["--persona-icon-btn-active-bg"]=_.activeBackground),_.activeBorder&&(o["--persona-icon-btn-active-border"]=_.activeBorder));let X=B?.labelButton;X&&(X.background&&(o["--persona-label-btn-bg"]=X.background),X.border&&(o["--persona-label-btn-border"]=X.border),X.color&&(o["--persona-label-btn-color"]=X.color),X.padding&&(o["--persona-label-btn-padding"]=X.padding),X.borderRadius&&(o["--persona-label-btn-radius"]=X.borderRadius),X.hoverBackground&&(o["--persona-label-btn-hover-bg"]=X.hoverBackground),X.fontSize&&(o["--persona-label-btn-font-size"]=X.fontSize),X.gap&&(o["--persona-label-btn-gap"]=X.gap));let $=B?.toggleGroup;$&&($.gap&&(o["--persona-toggle-group-gap"]=$.gap),$.borderRadius&&(o["--persona-toggle-group-radius"]=$.borderRadius));let k=B?.artifact;if(k?.toolbar){let N=k.toolbar;N.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=eh(N.toggleGroupGap)),N.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=eh(N.toggleGroupPadding)),N.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=ao(e,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=eh(N.copyBorderRadius)),N.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(k?.tab){let N=k.tab;N.background&&(o["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(o["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(o["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(o["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(o["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(o["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(o["--persona-artifact-tab-list-padding"]=N.listPadding)}if(k?.pane){let N=k.pane;if(N.toolbarBackground){let Oe=ao(e,N.toolbarBackground)??N.toolbarBackground;o["--persona-artifact-toolbar-bg"]=Oe}}if(k?.card){let N=k.card;N.background&&(o["--persona-artifact-card-bg"]=N.background),N.border&&(o["--persona-artifact-card-border"]=N.border),N.borderRadius&&(o["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(k?.inline){let N=k.inline;N.background&&(o["--persona-artifact-inline-bg"]=ao(e,N.background)??N.background),N.border&&(o["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(o["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=ao(e,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=ao(e,N.chromeBorder)??N.chromeBorder),N.titleColor&&(o["--persona-artifact-inline-title-color"]=ao(e,N.titleColor)??N.titleColor),N.mutedColor&&(o["--persona-artifact-inline-muted-color"]=ao(e,N.mutedColor)??N.mutedColor),N.frameHeight&&(o["--persona-artifact-inline-frame-height"]=N.frameHeight)}let H=B?.code;H&&(H.keywordColor&&(o["--persona-code-keyword-color"]=H.keywordColor),H.stringColor&&(o["--persona-code-string-color"]=H.stringColor),H.commentColor&&(o["--persona-code-comment-color"]=H.commentColor),H.numberColor&&(o["--persona-code-number-color"]=H.numberColor),H.tagColor&&(o["--persona-code-tag-color"]=H.tagColor),H.attrColor&&(o["--persona-code-attr-color"]=H.attrColor),H.propertyColor&&(o["--persona-code-property-color"]=H.propertyColor),H.lineNumberColor&&(o["--persona-code-line-number-color"]=H.lineNumberColor),H.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=H.gutterBorderColor),H.background&&(o["--persona-code-bg"]=ao(e,H.background)??H.background));let F=o["--persona-surface"],W=o["--persona-container"],oe=o["--persona-palette-colors-gray-100"]??"#f3f4f6",V=o["--persona-palette-colors-gray-200"]??"#e5e7eb",de=o["--persona-palette-colors-gray-300"]??"#d1d5db",ce=!W||W===F,ge=Pk(F??o["--persona-background"]),Pe=ce&&ge!==void 0&&ge<kk,Ae=Pe?"rgba(255, 255, 255, 0.08)":oe,ve=Pe?"rgba(255, 255, 255, 0.12)":V,Gt=Pe?"rgba(255, 255, 255, 0.16)":de,Bt=ce?Ae:W,Me=ce?ve:W;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??Bt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??Me,ce&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??Gt),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??Bt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??Bt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??Bt,o}var pw={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var Lk=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),fw=(e,t)=>{if(!t||!Lk(t))return e;let o=t.theme?.components?.panel?.width,n=t.darkTheme?.components?.panel?.width;return(oa(t)==="dark"?n??o:o)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Xr(t)==="v5"?"400px":"420px"}}}},Ik={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"}}},Vl={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)"}}}},nh=Ik,Rk={...nh,colors:{...nh.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"}}},Hk=Vl,Wk={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:{...Vl.components,button:{...Vl.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:{...Vl.components?.eventStream,badge:{...Vl.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"}}}}},Bk=e=>Xr({future:e})==="v5"?{palette:Rk,components:Wk}:{palette:nh,components:Hk},mw=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},$l=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Dk=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":$l()},oa=e=>Dk(e),Ok=(e,t={})=>ql(e,t),_k=(e,t={})=>{let o=Bk(t.future),n=Sn(o.components,e??{})??{};return ql({...n,palette:{...n.palette,colors:Xr(t)==="v5"?Sn(o.palette.colors,n.palette?.colors):{...o.palette.colors,...n.palette?.colors}}},{validate:!1,future:t.future})},An=e=>{let t=oa(e),o=mw(e?.theme),n=Pu(e)==="circle"?ku:{...Hu.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Sn({components:{launcher:n}},o),a=mw(e?.darkTheme);return fw(t==="dark"?_k(Sn(r??{},a??{}),{future:e?.future}):Ok(r,{future:e?.future}),e)},Nk=e=>Bu(e),na=(e,t)=>{let o=An(t),n=Nk(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",oa(t)),e.setAttribute("data-persona-defaults",Xr(t))},fi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e($l())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e($l());o.addEventListener?(o.addEventListener("change",n),t.push(()=>o.removeEventListener("change",n))):o.addListener&&(o.addListener(n),t.push(()=>o.removeListener(n)))}return()=>{t.forEach(o=>o())}};var as=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Du="24px",rh=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",jl=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let o=Number(t[1])/100;return o>0&&o<1?o:null},gw=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var hw=null;var sh=()=>{if(hw!==null)return hw;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},Fk="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Ou=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},_u=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),o=t.pop(),n={key:o,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")n.mod=!0;else if(r==="shift")n.shift=!0;else if(r==="alt"||r==="option")n.alt=!0;else return Ou("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(Ou("unsupported",e),null):(o==="space"&&(n.key=" "),n)},Uk=e=>Fk.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),yw=(e,t)=>{let o=_u(e);if(!o)return"";let n=sh(),r=Uk(o.key);if(!t&&n)return`${o.alt?"\u2325":""}${o.shift?"\u21E7":""}\u2318${r}`;let a=[t?n?"Meta":"Control":"Ctrl"];return o.alt&&a.push("Alt"),o.shift&&a.push("Shift"),a.push(r),a.join("+")},Nu=e=>yw(e,!1),zl=e=>yw(e,!0),qk=(e,t)=>t.key?.toLowerCase()===e.key&&(sh()?t.metaKey:t.ctrlKey)===e.mod&&!(sh()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Vk=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},bw=e=>{let t=new Map,o=e?.ownerDocument??(typeof document<"u"?document:null),n=(a,i)=>{if((a.scope??"widget")==="page")return!0;if(!e)return!1;let d=i.composedPath?.();return d?.length?d.includes(e):e.contains(i.target)},r=a=>{if(a.isComposing||!t.size)return;let i=a.composedPath?.()[0]??a.target;for(let d of t.values())if(qk(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&Vk(i))){a.preventDefault();try{d.run(a)}catch(c){Ou(`${d.id} threw on`,d.combo),console.warn(c)}return}};return o?.addEventListener("keydown",r),{register(a){let i=_u(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(d);return c?(Ou(`${c.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",zl(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var vw=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:h=>h.getAttribute("im-preserve")==="true",shouldReAppend:h=>h.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(h,y,x={}){h=p(h);let C=m(y),E=u(h,C,x),A=r(E,()=>d(E,h,C,M=>M.morphStyle==="innerHTML"?(a(M,h,C),Array.from(h.childNodes)):n(M,h,C)));return E.pantry.remove(),A}function n(h,y,x){let C=m(y);return a(h,C,x,y,y.nextSibling),Array.from(C.childNodes)}function r(h,y){if(!h.config.restoreFocus)return y();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return y();let{id:C,selectionStart:E,selectionEnd:A}=x,M=y();return C&&C!==document.activeElement?.getAttribute("id")&&(x=h.target.querySelector(`[id="${C}"]`),x?.focus()),x&&!x.selectionEnd&&A&&x.setSelectionRange(E,A),M}let a=(function(){function h(b,S,T,B=null,_=null){S instanceof HTMLTemplateElement&&T instanceof HTMLTemplateElement&&(S=S.content,T=T.content),B||(B=S.firstChild);for(let X of T.childNodes){if(B&&B!=_){let k=x(b,X,B,_);if(k){k!==B&&E(b,B,k),i(k,X,b),B=k.nextSibling;continue}}if(X instanceof Element){let k=X.getAttribute("id");if(b.persistentIds.has(k)){let H=A(S,k,B,b);i(H,X,b),B=H.nextSibling;continue}}let $=y(S,X,B,b);$&&(B=$.nextSibling)}for(;B&&B!=_;){let X=B;B=B.nextSibling,C(b,X)}}function y(b,S,T,B){if(B.callbacks.beforeNodeAdded(S)===!1)return null;if(B.idMap.has(S)){let _=document.createElement(S.tagName);return b.insertBefore(_,T),i(_,S,B),B.callbacks.afterNodeAdded(_),_}else{let _=document.importNode(S,!0);return b.insertBefore(_,T),B.callbacks.afterNodeAdded(_),_}}let x=(function(){function b(B,_,X,$){let k=null,H=_.nextSibling,F=0,W=X;for(;W&&W!=$;){if(T(W,_)){if(S(B,W,_))return W;k===null&&(B.idMap.has(W)||(k=W))}if(k===null&&H&&T(W,H)&&(F++,H=H.nextSibling,F>=2&&(k=void 0)),B.activeElementAndParents.includes(W))break;W=W.nextSibling}return k||null}function S(B,_,X){let $=B.idMap.get(_),k=B.idMap.get(X);if(!k||!$)return!1;for(let H of $)if(k.has(H))return!0;return!1}function T(B,_){let X=B,$=_;return X.nodeType===$.nodeType&&X.tagName===$.tagName&&(!X.getAttribute?.("id")||X.getAttribute?.("id")===$.getAttribute?.("id"))}return b})();function C(b,S){if(b.idMap.has(S))L(b.pantry,S,null);else{if(b.callbacks.beforeNodeRemoved(S)===!1)return;S.parentNode?.removeChild(S),b.callbacks.afterNodeRemoved(S)}}function E(b,S,T){let B=S;for(;B&&B!==T;){let _=B;B=B.nextSibling,C(b,_)}return B}function A(b,S,T,B){let _=B.target.getAttribute?.("id")===S&&B.target||B.target.querySelector(`[id="${S}"]`)||B.pantry.querySelector(`[id="${S}"]`);return M(_,B),L(b,_,T),_}function M(b,S){let T=b.getAttribute("id");for(;b=b.parentNode;){let B=S.idMap.get(b);B&&(B.delete(T),B.size||S.idMap.delete(b))}}function L(b,S,T){if(b.moveBefore)try{b.moveBefore(S,T)}catch{b.insertBefore(S,T)}else b.insertBefore(S,T)}return h})(),i=(function(){function h(M,L,b){return b.ignoreActive&&M===document.activeElement?null:(b.callbacks.beforeNodeMorphed(M,L)===!1||(M instanceof HTMLHeadElement&&b.head.ignore||(M instanceof HTMLHeadElement&&b.head.style!=="morph"?c(M,L,b):(y(M,L,b),A(M,b)||a(b,M,L))),b.callbacks.afterNodeMorphed(M,L)),M)}function y(M,L,b){let S=L.nodeType;if(S===1){let T=M,B=L,_=T.attributes,X=B.attributes;for(let $ of X)E($.name,T,"update",b)||T.getAttribute($.name)!==$.value&&T.setAttribute($.name,$.value);for(let $=_.length-1;0<=$;$--){let k=_[$];if(k&&!B.hasAttribute(k.name)){if(E(k.name,T,"remove",b))continue;T.removeAttribute(k.name)}}A(T,b)||x(T,B,b)}(S===8||S===3)&&M.nodeValue!==L.nodeValue&&(M.nodeValue=L.nodeValue)}function x(M,L,b){if(M instanceof HTMLInputElement&&L instanceof HTMLInputElement&&L.type!=="file"){let S=L.value,T=M.value;C(M,L,"checked",b),C(M,L,"disabled",b),L.hasAttribute("value")?T!==S&&(E("value",M,"update",b)||(M.setAttribute("value",S),M.value=S)):E("value",M,"remove",b)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&L instanceof HTMLOptionElement)C(M,L,"selected",b);else if(M instanceof HTMLTextAreaElement&&L instanceof HTMLTextAreaElement){let S=L.value,T=M.value;if(E("value",M,"update",b))return;S!==T&&(M.value=S),M.firstChild&&M.firstChild.nodeValue!==S&&(M.firstChild.nodeValue=S)}}function C(M,L,b,S){let T=L[b],B=M[b];if(T!==B){let _=E(b,M,"update",S);_||(M[b]=L[b]),T?_||M.setAttribute(b,""):E(b,M,"remove",S)||M.removeAttribute(b)}}function E(M,L,b,S){return M==="value"&&S.ignoreActiveValue&&L===document.activeElement?!0:S.callbacks.beforeAttributeUpdated(M,L,b)===!1}function A(M,L){return!!L.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return h})();function d(h,y,x,C){if(h.head.block){let E=y.querySelector("head"),A=x.querySelector("head");if(E&&A){let M=c(E,A,h);return Promise.all(M).then(()=>{let L=Object.assign(h,{head:{block:!1,ignore:!0}});return C(L)})}}return C(h)}function c(h,y,x){let C=[],E=[],A=[],M=[],L=new Map;for(let S of y.children)L.set(S.outerHTML,S);for(let S of h.children){let T=L.has(S.outerHTML),B=x.head.shouldReAppend(S),_=x.head.shouldPreserve(S);T||_?B?E.push(S):(L.delete(S.outerHTML),A.push(S)):x.head.style==="append"?B&&(E.push(S),M.push(S)):x.head.shouldRemove(S)!==!1&&E.push(S)}M.push(...L.values());let b=[];for(let S of M){let T=document.createRange().createContextualFragment(S.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(T)!==!1){if("href"in T&&T.href||"src"in T&&T.src){let B,_=new Promise(function(X){B=X});T.addEventListener("load",function(){B()}),b.push(_)}h.appendChild(T),x.callbacks.afterNodeAdded(T),C.push(T)}}for(let S of E)x.callbacks.beforeNodeRemoved(S)!==!1&&(h.removeChild(S),x.callbacks.afterNodeRemoved(S));return x.head.afterHeadMorphed(h,{added:C,kept:A,removed:E}),b}let u=(function(){function h(b,S,T){let{persistentIds:B,idMap:_}=M(b,S),X=y(T),$=X.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:b,newContent:S,config:X,morphStyle:$,ignoreActive:X.ignoreActive,ignoreActiveValue:X.ignoreActiveValue,restoreFocus:X.restoreFocus,idMap:_,persistentIds:B,pantry:x(),activeElementAndParents:C(b),callbacks:X.callbacks,head:X.head}}function y(b){let S=Object.assign({},t);return Object.assign(S,b),S.callbacks=Object.assign({},t.callbacks,b.callbacks),S.head=Object.assign({},t.head,b.head),S}function x(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function C(b){let S=[],T=document.activeElement;if(T?.tagName!=="BODY"&&b.contains(T))for(;T&&(S.push(T),T!==b);)T=T.parentElement;return S}function E(b){let S=Array.from(b.querySelectorAll("[id]"));return b.getAttribute?.("id")&&S.push(b),S}function A(b,S,T,B){for(let _ of B){let X=_.getAttribute("id");if(S.has(X)){let $=_;for(;$;){let k=b.get($);if(k==null&&(k=new Set,b.set($,k)),k.add(X),$===T)break;$=$.parentElement}}}}function M(b,S){let T=E(b),B=E(S),_=L(T,B),X=new Map;A(X,_,b,T);let $=S.__idiomorphRoot||S;return A(X,_,$,B),{persistentIds:_,idMap:X}}function L(b,S){let T=new Set,B=new Map;for(let{id:X,tagName:$}of b)B.has(X)?T.add(X):B.set(X,$);let _=new Set;for(let{id:X,tagName:$}of S)_.has(X)?T.add(X):B.get(X)===$&&_.add(X);for(let X of T)_.delete(X);return _}return h})(),{normalizeElement:p,normalizeParent:m}=(function(){let h=new WeakSet;function y(A){return A instanceof Document?A.documentElement:A}function x(A){if(A==null)return document.createElement("div");if(typeof A=="string")return x(E(A));if(h.has(A))return A;if(A instanceof Node){if(A.parentNode)return new C(A);{let M=document.createElement("div");return M.append(A),M}}else{let M=document.createElement("div");for(let L of[...A])M.append(L);return M}}class C{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],L=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;L&&L!=this.nextSibling;)M.push(L),L=L.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((L,b)=>{if(b instanceof Element){b.matches(M)&&L.push(b);let S=b.querySelectorAll(M);for(let T=0;T<S.length;T++)L.push(S[T])}return L},[])}insertBefore(M,L){return this.realParentNode.insertBefore(M,L)}moveBefore(M,L){return this.realParentNode.moveBefore(M,L)}get __idiomorphRoot(){return this.originalNode}}function E(A){let M=new DOMParser,L=A.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(L.match(/<\/html>/)||L.match(/<\/head>/)||L.match(/<\/body>/)){let b=M.parseFromString(A,"text/html");if(L.match(/<\/html>/))return h.add(b),b;{let S=b.firstChild;return S&&h.add(S),S}}else{let S=M.parseFromString("<body><template>"+A+"</template></body>","text/html").body.querySelector("template").content;return h.add(S),S}}return{normalizeElement:y,normalizeParent:x}})();return{morph:o,defaults:t}})();var Fu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;vw.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&n){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let i=r.textContent??"",d=a.textContent??"";if(i!==d)return}return!1}}}}})};var xw=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ah={index:-1,draft:""};function Cw(e){let{direction:t,history:o,currentValue:n,atStart:r,state:a}=e,i=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!i&&!r)return{handled:!1,state:a};if(!i){let d=o.length-1;return{handled:!0,value:o[d],state:{index:d,draft:n}}}if(a.index>0){let d=a.index-1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,state:a}}if(!i)return{handled:!1,state:a};if(a.index<o.length-1){let d=a.index+1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function Sw(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function ww(){return new Map}function Aw(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function Mw(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function Tw(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function Ew(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Pw(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function zn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ra(e,t){return zn(e)-e.scrollTop<=t}function kw(e){let{following:t,currentScrollTop:o,lastScrollTop:n,nearBottom:r,userScrollThreshold:a,isAutoScrolling:i=!1,pauseOnUpwardScroll:d=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:u=!1}=e,p=o-n;return i||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:o}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:o}:t&&d&&p<0?{action:"pause",delta:p,nextLastScrollTop:o}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:o}:{action:"none",delta:p,nextLastScrollTop:o}}function Lw(e){let{following:t,deltaY:o,nearBottom:n=!1,resumeWhenNearBottom:r=!1}=e;return t&&o<0?"pause":!t&&r&&o>0&&n?"resume":"none"}function Iw(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ih(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:o}}function Rw(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Kl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},$k=["pre","code","a","script","style"],Uu=e=>({type:e?.type??Kl.type,placeholder:e?.placeholder??Kl.placeholder,speed:e?.speed??Kl.speed,duration:e?.duration??Kl.duration,buffer:e?.buffer??Kl.buffer}),Ww=[{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"}],Gl=new Map;for(let e of Ww)Gl.set(e.name,e);var Bw=["wipe","glyph-cycle"],mi=e=>{Gl.set(e.name,e)},ch=e=>{Ww.some(t=>t.name===e)||Gl.delete(e)},uh=()=>Array.from(Gl.keys()),Xl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Gl.get(e)??null,qu=(e,t,o,n,r)=>{if(!r)return e;if(o?.bufferContent)return o.bufferContent(e,n);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
29
|
-
`);return a<0?"":e.slice(0,a)}return e},jk=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${o}-${n}`,r.style.setProperty("--char-index",String(n)),r.textContent=t,r},zk=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${o}-${n}`,r.style.setProperty("--word-index",String(n)),r.textContent=t,r},lh=/\s/,Kk=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let n=o;if(t.has(n.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},Gk=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=0;for(;d<a.length;)if(lh.test(a[d])){let c=d;for(;c<a.length&&lh.test(a[c]);)c+=1;i.appendChild(n.createTextNode(a.slice(d,c))),d=c}else{let c=n.createElement("span");c.className="persona-stream-word-group";let u=d;for(;u<a.length&&!lh.test(a[u]);)c.appendChild(jk(n,a[u],t,o.value)),o.value+=1,u+=1;i.appendChild(c),d=u}r.replaceChild(i,e)},Xk=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=a.split(/(\s+)/);for(let c of d)c&&(/^\s+$/.test(c)?i.appendChild(n.createTextNode(c)):(i.appendChild(zk(n,c,t,o.value)),o.value+=1));r.replaceChild(i,e)},Ql=(e,t,o,n)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((n?.skipTags??$k).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],c=i.nextNode();for(;c;)Kk(c,a)||d.push(c),c=i.nextNode();let u={value:n?.startIndex??0},p=t==="char"?Gk:Xk;for(let m of d)p(m,o,u);return r.innerHTML},Vu=(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},Yl=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},Hw=new WeakMap,Qk=(e,t)=>{if(!e.styles)return;let o=Hw.get(t);if(o||(o=new Set,Hw.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},dh=new WeakMap,Yk=(e,t)=>{if(!e.onAttach)return;let o=dh.get(t);if(o||(o=new Map,dh.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},Dw=e=>{let t=dh.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Jl=(e,t)=>{Qk(e,t),Yk(e,t)};var{setLoader:Jk,load:Zk}=vt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),Ow=Jk,_w=Zk;function ph(e,t=co){let o=e.style.position,n=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),i=a.position==="static"||a.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=o),e.style.zIndex=n,e.style.isolation=r}}var Zl=0,is=null;function fh(e=document){if(Zl++,Zl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;is={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:r},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${r}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Zl=Math.max(0,Zl-1),Zl===0&&is)){let o=e.body,n=e.defaultView??window;o.style.overflow=is.originalOverflow,o.style.position=is.originalPosition,o.style.top=is.originalTop,o.style.width=is.originalWidth,n.scrollTo(0,is.scrollY),is=null}}}var ed={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},yt=e=>(e?.launcher?.mountMode??"floating")==="docked",ls=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Oo=e=>{let t=e?.launcher?.dock,o=fr(e).dockWidth?t?.width:ao(An(e),"components.panel.width");return{side:t?.side??ed.side,width:o??ed.width,animate:t?.animate??ed.animate,reveal:t?.reveal??ed.reveal,maxHeight:t?.maxHeight??ed.maxHeight}};var mh=e=>e==="followUp"?"follow-up":e,gh=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let o=e.label.trim();if(!o)return null;let n=e.prompt?.trim()||o;return{id:e.id?.trim()||n||`suggestion-${t}`,label:o,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},Nw=new WeakSet,eL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,tL=e=>{eL()||e.forEach((t,o)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:o*60,easing:"ease-out",fill:"backwards"})})},hh=e=>{var L,b,S;let{item:t,index:o,surface:n,source:r,variant:a,streaming:i,config:d,plugins:c,chipsConfig:u,session:p,getTextarea:m,eventTarget:h,submitPrompt:y}=e,x=n==="followUp",C=t.behavior,E=()=>{if(p.isStreaming())return;let T={suggestion:{...t},surface:n,source:r,behavior:C},B=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:T,bubbles:!0,composed:!0,cancelable:!0}));if(x&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!B)return;for(let X of c)if(X.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let _=m();if(C==="fill"){_.value=t.prompt,_.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),_.focus();return}if(y){y(t.prompt);return}_.value="",p.sendMessage(t.prompt)},A=()=>{let T=I("button",`persona-suggestion persona-suggestion--${a}`);if(T.type="button",T.disabled=i,T.dataset.suggestionId=t.id,T.dataset.emphasis=t.emphasis,T.dataset.behavior=C,a==="chip"&&(u?.fontWeight&&(T.style.fontWeight=u.fontWeight),u?.paddingX&&(T.style.paddingLeft=u.paddingX,T.style.paddingRight=u.paddingX),u?.paddingY&&(T.style.paddingTop=u.paddingY,T.style.paddingBottom=u.paddingY)),t.icon){let _=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);_&&(_.classList.add("persona-suggestion__icon"),t.iconColor&&(_.style.color=t.iconColor),T.appendChild(_))}let B=I("span","persona-suggestion__copy");if(B.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&B.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),T.appendChild(B),a!=="chip"){let _=Tt(fl,16,"currentColor",1.8);_&&(_.classList.add("persona-suggestion__arrow"),T.appendChild(_))}return T.addEventListener("click",E),T},M=null;for(let T of c)if(T.renderSuggestion&&(M=T.renderSuggestion({suggestion:{...t},index:o,surface:n,source:r,variant:a,streaming:i,config:d,defaultRenderer:A,select:E}),M))break;return M??(M=A()),(L=M.dataset).suggestionId||(L.suggestionId=t.id),(b=M.dataset).behavior||(b.behavior=C),(S=M.dataset).emphasis||(S.emphasis=t.emphasis),M instanceof HTMLButtonElement||M.setAttribute("aria-disabled",i?"true":"false"),M},td=e=>{let t=[],o=[],n=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){a();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),y=4,x=h<=y,C=h>=p-y,E=m?!C:!x,A=m?!x:!C;e.toggleAttribute("data-scroll-left",E),e.toggleAttribute("data-scroll-right",A)},d=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",d,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(d):null;return c?.observe(e),{buttons:t,elements:o,destroy:()=>{e.removeEventListener("scroll",d),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,h,y,x,C)=>{e.replaceChildren(),t.length=0,o.length=0;let E=C?.source??"config",A=C?.surface??(E==="config"?"starter":"followUp"),M=A==="followUp",L=C?.variant??"chip",b=C?.behavior??"send",S=C?.overflow??"wrap",T=C?.config??{},B=C?.plugins??[],_=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,X=M?"followUps":"starters";!Nw.has(T)&&T.debug===!0&&L!=="chip"&&T.suggestions?.[X]?.overflow!==void 0&&(Nw.add(T),console.info(`[persona] suggestions.${X}.overflow applies to the "chip" variant only; the "${L}" variant manages its own stacking.`));let $=V=>V.map(gh).filter(de=>de!==null).map(de=>({...de,behavior:de.behavior??b})),k=$(p??[]);B.forEach(V=>{V.transformSuggestions&&(k=$(V.transformSuggestions({suggestions:k.map(de=>({...de})),surface:A,source:E,config:T})))});let H=_===void 0?k:k.slice(0,_);if(!H.length){e.hidden=!0,n=null,a();return}if(!M&&(y??m.getMessages()).some(de=>de.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=mh(A),e.dataset.variant=L,e.dataset.overflow=S;let F=document.createDocumentFragment(),W=m.isStreaming();H.forEach((V,de)=>{let ce=hh({item:V,index:de,surface:A,source:E,variant:L,streaming:W,config:T,plugins:B,chipsConfig:x,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:C?.submitPrompt});F.appendChild(ce),o.push(ce),[...ce instanceof HTMLButtonElement?[ce]:[],...Array.from(ce.querySelectorAll("button"))].forEach(Pe=>{t.includes(Pe)||(Pe.disabled=W,t.push(Pe))})}),e.appendChild(F),i(),d();let oe=JSON.stringify({normalized:H,surface:A,variant:L,source:E});oe!==n&&(n=oe,tL(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:H.map(V=>({...V})),surface:A,source:E,variant:L},bubbles:!0,composed:!0})),M&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:H.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var Qo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var oL="persona-header-control",nL="persona-header-control--glyph",rL="persona-header-control--sparse",sL=20,aL={x:[1.4,1.05]},Fw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",iL="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",$u=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=aL[t]??[1,1.5],d=!n;e.classList.toggle(nL,d),e.classList.toggle(rL,d&&a!==1);let c=parseFloat(n??"")||sL,u=ae(t,`${Math.round(c*a)}px`,"currentColor",i);u?(u.style.display="block",d||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},sa=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=Fw,size:d,iconSize:c,color:u,backgroundColor:p,borderWidth:m,borderColor:h,borderRadius:y,paddingX:x,paddingY:C,hidden:E,extraClassName:A,attrs:M}=e,L=I("div",i),b=!!(m||h),S=Q("button",{className:bo(oL,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!b&&"persona-border-none",!y&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...M},style:{width:d,height:d,minWidth:d,minHeight:d,display:E?"none":void 0,color:u||So.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:x,paddingRight:x,paddingTop:C,paddingBottom:C}});return r?$u(S,r,{iconSize:c,iconText:a}):a&&(S.textContent=a),L.appendChild(S),ro({anchor:S,trigger:L,text:()=>S.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:S,wrapper:L}},gi=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=Fw,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=sa({ariaLabel:d,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:n,size:r??i.closeButtonSize,iconSize:a,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!o});return{button:u,wrapper:p}},hi=(e,t={})=>{let{wrapperClassName:o=iL,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:u,wrapper:p}=sa({ariaLabel:d,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:o,size:n??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var So={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)"},yh={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)"},lL={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)"},Sr=e=>{let{config:t,showClose:o=!0}=e,n=Q("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:So.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},a=r.headerIconSize??Sl,i=r.closeButtonPlacement??"inline",d=r.headerIconHidden??!1,c=r.headerIconName,u=Q("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(!d)if(c){let S=parseFloat(a)||24,T=ae(c,S*.6,"currentColor",1);T?(T.style.width=`calc(${S}px * var(--persona-components-header-iconScale, 0.6))`,T.style.height=`calc(${S}px * var(--persona-components-header-iconScale, 0.6))`,u.replaceChildren(T)):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let S=I("img");S.src=t.launcher.iconUrl,S.alt="",S.className="persona-rounded-xl persona-object-cover",S.style.height=a,S.style.width=a,u.replaceChildren(S)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=I("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:So.titleColor,...yh}}),h=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:So.subtitleColor,...lL}});p.append(m,h),d?n.append(p):n.append(u,p);let y=r.clearChat??{},x=y.enabled??!0,C=y.placement??"inline",E=null,A=null;if(x){let T=hi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=T.button,A=T.wrapper,C==="top-right"&&(A.style.right="48px"),C==="inline"&&n.appendChild(A)}let M=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:L,wrapper:b}=gi(t,{showClose:o,wrapperClassName:M});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:L,closeButtonWrapper:b,clearChatButton:E,clearChatButtonWrapper:A}},aa=(e,t,o)=>{let n=o?.launcher??{},r=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function ia(e){let{items:t,onSelect:o,anchor:n,position:r="bottom-left",portal:a,onOpenChange:i}=e,d=I("div","persona-dropdown-menu persona-hidden");d.setAttribute("role","menu"),d.setAttribute("data-persona-theme-zone","dropdown"),a?(d.style.position="fixed",d.style.zIndex=String(ui)):(d.style.position="absolute",d.style.top="100%",d.style.marginTop="4px",r==="bottom-right"?d.style.right="0":d.style.left="0");for(let x of t){if(x.dividerBefore){let A=document.createElement("hr");d.appendChild(A)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",x.id),x.destructive&&C.setAttribute("data-destructive",""),x.icon){let A=ae(x.icon,16,"currentColor",1.5);A&&C.appendChild(A)}let E=document.createElement("span");E.textContent=x.label,C.appendChild(E),C.addEventListener("click",A=>{A.stopPropagation(),m(),o(x.id)}),d.appendChild(C)}let c=null;function u(){if(!a)return;let x=n.getBoundingClientRect();d.style.top=`${x.bottom+4}px`,r==="bottom-right"?(d.style.right=`${window.innerWidth-x.right}px`,d.style.left="auto"):(d.style.left=`${x.left}px`,d.style.right="auto")}function p(){let x=d.classList.contains("persona-hidden");u(),d.classList.remove("persona-hidden"),x&&i?.(!0),requestAnimationFrame(()=>{let C=E=>{!d.contains(E.target)&&!n.contains(E.target)&&m()};document.addEventListener("click",C,!0),c=()=>document.removeEventListener("click",C,!0)})}function m(){let x=!d.classList.contains("persona-hidden");d.classList.add("persona-hidden"),c?.(),c=null,x&&i?.(!1)}function h(){d.classList.contains("persona-hidden")?p():m()}function y(){m(),d.remove()}return a&&a.appendChild(d),{element:d,show:p,hide:m,toggle:h,destroy:y}}function la(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:c}=e,u=I("button",bo(!i&&"persona-icon-btn",a));u.type="button",u.setAttribute("aria-label",o),u.title=o;let p=ae(t,n??16,"currentColor",r??2);if(p&&u.appendChild(p),d&&u.addEventListener("click",d),c)for(let[m,h]of Object.entries(c))u.setAttribute(m,h);return u}function bh(e){let{icon:t,label:o,variant:n="default",size:r="sm",iconSize:a,className:i,onClick:d,aria:c}=e,u="persona-label-btn";n!=="default"&&(u+=" persona-label-btn--"+n),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=I("button",u);if(p.type="button",p.setAttribute("aria-label",o),t){let h=ae(t,a??14,"currentColor",2);h&&p.appendChild(h)}let m=I("span");if(m.textContent=o,p.appendChild(m),d&&p.addEventListener("click",d),c)for(let[h,y]of Object.entries(c))p.setAttribute(h,y);return p}function Uw(e){let{items:t,selectedId:o,onSelect:n,className:r}=e,a=I("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let i=o,d=[];function c(){for(let p of d)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let m;p.icon?m=la({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),n(p.id)}}):(m=I("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{i=p.id,c(),n(p.id)})),m.setAttribute("aria-pressed",p.id===i?"true":"false"),d.push({id:p.id,btn:m}),a.appendChild(m)}function u(p){i=p,c()}return{element:a,setSelected:u}}function qw(e){let{label:t,icon:o,iconSize:n,iconOnly:r,menuItems:a,onSelect:i,onPrimary:d,position:c="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:x}=e,C=I("div","persona-split-btn"+(h?" "+h:"")),E={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:d},A=r&&o?la({...E,icon:o,size:n??14}):bh({...E,icon:o,iconSize:n??14}),M=la({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(x?" "+x:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(A,M);let L=null,b=()=>{if(L)return L;let S=(typeof u=="function"?u():u)??void 0;return L=ia({items:a,onSelect:i,anchor:C,position:c,portal:S,onOpenChange:T=>{M.setAttribute("aria-expanded",T?"true":"false")}}),S||C.appendChild(L.element),L};return C.isConnected?b():requestAnimationFrame(()=>{L||b()}),M.addEventListener("click",S=>{S.stopPropagation(),b().toggle()}),{element:C,primaryButton:A,chevronButton:M,openMenu:()=>b().show(),closeMenu:()=>L?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{L?.destroy(),C.remove()}}}function ju(e){let{label:t,icon:o="chevron-down",menuItems:n,onSelect:r,position:a="bottom-left",portal:i,className:d,hover:c}=e,u=I("div","persona-combo-btn"+(d?" "+d:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=I("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let m=ae(o,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",u.appendChild(m)),c&&(u.style.borderRadius=c.borderRadius??"10px",u.style.padding=c.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=c.background??"",u.style.borderColor=c.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let h=ia({items:n,onSelect:x=>{u.setAttribute("aria-expanded","false"),r(x)},anchor:u,position:a,portal:i});i||u.appendChild(h.element);let y=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",x=>{if(x.stopPropagation(),y())return;let C=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",C?"false":"true"),h.toggle()}),u.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),u.click())}),{element:u,setLabel:x=>{p.textContent=x,u.setAttribute("aria-label",x)},open:()=>{u.setAttribute("aria-expanded","true"),h.show()},close:()=>{u.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let x=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",x?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),u.remove()}}}var vh=e=>{let t=Sr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>o()),n.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),o())}))}return t};function dL(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=sa({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?Nu(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",n.id),n.shortcut){let i=zl(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=ia({items:n.menuItems,onSelect:d=>o?.(d),anchor:a,position:"bottom-right"});a.appendChild(i.element),r.addEventListener("click",d=>{d.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>o?.(n.id));e.appendChild(a)}}var xh=e=>{let{config:t,showClose:o=!0,onClose:n,layoutHeaderConfig:r,onHeaderAction:a}=e,i=t?.launcher??{},d=I("div","persona-flex persona-items-center persona-justify-between");d.setAttribute("data-persona-theme-zone","header"),d.style.minHeight=So.minHeight,d.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",d.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",d.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",d.style.boxShadow="var(--persona-header-shadow, none)",d.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,u,p;if(c){let b=ju({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:S=>{let T=_=>{_===!1&&b.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:S}}))},B=c.onSelect(S);B instanceof Promise?B.then(T,()=>{}):T(B)},hover:c.hover,className:""});u=b.element,u.style.color=So.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=I("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=I("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=So.titleColor,Object.assign(p.style,yh),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let S=r.onTitleClick;u.addEventListener("click",T=>{T.target.closest("button")||S()}),u.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),S())})}let b=r?.titleRowHover;b&&(u.style.borderRadius=b.borderRadius??"10px",u.style.padding=b.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=b.background??"",u.style.borderColor=b.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}d.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=gi(t,{showClose:o,wrapperClassName:m});n&&h.addEventListener("click",n);let x=I("div","persona-flex persona-items-center persona-gap-1");c||dL(x,r?.trailingActions,r?.onAction??a);let C=i.clearChat??{},E=null,A=null;if(C.enabled??!0){let b=C.placement??"inline",S=hi(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});E=S.button,A=S.wrapper,b==="top-right"?A.style.right="48px":x.appendChild(A)}x.appendChild(y),d.appendChild(x);let M=I("div");M.style.display="none";let L=I("span");return L.style.display="none",{header:d,iconHolder:M,headerTitle:p,headerSubtitle:L,closeButton:h,closeButtonWrapper:y,clearChatButton:E,clearChatButtonWrapper:A}},zu={default:vh,minimal:xh},Ch=e=>zu[e]??zu.default,yi=(e,t,o)=>{if(t?.render){let i=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),d=I("div");d.style.display="none";let c=I("span"),u=I("span"),p=I("button");p.style.display="none";let m=I("div");return m.style.display="none",{header:i,iconHolder:d,headerTitle:c,headerSubtitle:u,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let n=t?.layout??"default",a=Ch(n)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var da=e=>{let{config:t}=e,o=Q("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=wu(),r=Q("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:i}=vu(t);i();let d=xu(t),c=pi(t),u=Cu(t),p=Su(t),m=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),r.append(u.input)),r.append(a);let h=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=Q("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&y.append(u.wrapper),c&&x.append(c.wrapper),x.append(d.wrapper),h.append(y,x),r.append(h),r.addEventListener("click",C=>{C.target!==d.button&&C.target!==d.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==u?.button&&C.target!==u?.wrapper&&a.focus()}),t?.statusIndicator?.mode==="transient"?o.append(n,p,r):o.append(n,r,p),{footer:o,suggestions:n,composerForm:r,header:m,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:x,setSendButtonMode:d.setMode}};var Vw=()=>{let e=Q("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=I("span","persona-pill-peek__icon"),o=Tt(bl,16,"currentColor",1.5);o&&t.appendChild(o);let n=I("span","persona-pill-peek__text"),r=I("span","persona-pill-peek__caret"),a=Tt($s,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},Ku=e=>{let{config:t}=e,o=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=wu(),r=Su(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=vu(t,{defaultMaxLines:5});i();let d=xu(t),c=pi(t),u=Cu(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),m=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let h=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&h.append(c.wrapper),h.append(d.wrapper),p.addEventListener("click",C=>{C.target!==d.button&&C.target!==d.wrapper&&C.target!==c?.button&&C.target!==c?.wrapper&&C.target!==u?.button&&C.target!==u?.wrapper&&a.focus()}),u&&p.append(u.input),p.append(m,a,h);let y=Q("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(y),u&&y.append(u.previewsContainer),o.append(n,p,r);let x=p;return{footer:o,suggestions:n,composerForm:p,header:y,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:x,leftActions:m,rightActions:h,setSendButtonMode:d.setMode}};var cL=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}},uL=(e,t)=>{if(!e)return null;let o=cL(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},pL=(e,t)=>{let o=I("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},fL=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},wh=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ah=320,Gw=320,mL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),gL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),hL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),yL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),bL=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let o of e){let n=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:o.label}}),r=I("span","persona-mention-chip-icon"),a=ae(o.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),n.appendChild(r),n.appendChild(Q("span",{className:"persona-mention-chip-label",text:o.label})),t.appendChild(n)}return t},vL=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(Fl(n.ref,{readonly:!0,render:t}))}return o},$w="\uE000",jw="\uE001",xL=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=h=>`${$w}${r}:${h}${jw}`,i=t.map((h,y)=>h.kind==="text"?h.text:a(y)).join(""),d=o(i);if(!t.every((h,y)=>h.kind==="text"||d.includes(a(y)))){e.replaceChildren(vL(t,n));return}e.innerHTML=d;let u=new RegExp(`${$w}${r}:(\\d+)${jw}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=p.nextNode();h;h=p.nextNode())m.push(h);for(let h of m){let y=h;for(let x=u.exec(y.data);x;x=u.exec(y.data)){let C=t[Number(x[1])],E=y.splitText(x.index);E.data=E.data.slice(x[0].length),C?.kind==="mention"&&E.parentNode?.insertBefore(Fl(C.ref,{readonly:!0,render:n}),E),y=E}}},CL=(e,t,o)=>{if(e.length===0)return null;try{let n=I("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let r=0,a=!1,i=()=>{a||(a=!0,n.remove(),o?.())};return e.forEach((d,c)=>{let u=I("img");u.alt=d.alt?.trim()||`Attached image ${c+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Ah}px`,u.style.maxHeight=`${Gw}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),fL(d.image)?(u.src=d.image,n.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):n}catch{return o?.(),null}},SL=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(n=>{if(!wh(n.audio))return;let r=I("audio");r.controls=!0,r.preload="metadata",r.src=n.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ah}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},wL=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(n=>{if(!wh(n.video))return;let r=I("video");r.controls=!0,r.preload="metadata",r.src=n.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ah}px`,r.style.maxHeight=`${Gw}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},AL=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(n=>{if(!wh(n.data))return;let r=I("a");r.href=n.data,r.download=n.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=n.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},ca=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="250ms";let 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 r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(n),e.appendChild(r),e},Mh=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:ca};if(t){let r=t(n);if(r!==null)return r}return ca()},ML=(e,t)=>{let o=I("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=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let r=I("img");r.src=n,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(r)}else o.textContent=n,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},zw=(e,t,o="div")=>{let n=I(o,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},od=(e,t="bubble")=>{let o=["persona-message-bubble"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return o},Kw={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"}},TL=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=Kw[o??"bubble"]??Kw.bubble;n.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Gu="custom:",EL=e=>`${Gu}${e}`,Xw=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),Th=(e,t,o,n)=>{let r=t.showCopy??!0,a=t.showUpvote??!1,i=t.showDownvote??!1,d=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&n?.canRegenerate===!0,u=(t.showEdit??!1)&&n?.canEdit===!0,p=(t.showQuote??!1)&&n?.canQuote!==!1,m=Xw(t,e.role);if(!r&&!a&&!i&&!d&&!c&&!u&&!p&&m.length===0){let L=I("div");return L.style.display="none",L.id=`actions-${e.id}`,L.setAttribute("data-actions-for",e.id),L}let h=t.visibility??"hover",y=t.align??"right",x=t.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],E={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],A=I("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${E} ${h==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let M=(L,b,S)=>{let T=la({icon:L,label:b,size:14,className:"persona-message-action-btn",chromeless:!0});return T.setAttribute("data-action",S),T};r&&A.appendChild(M("copy","Copy message","copy")),d&&A.appendChild(M("volume-2","Read aloud","read-aloud")),a&&A.appendChild(M("thumbs-up","Upvote","upvote")),i&&A.appendChild(M("thumbs-down","Downvote","downvote")),c&&A.appendChild(M("refresh-cw","Regenerate response","regenerate")),u&&A.appendChild(M("pencil","Edit message","edit")),p&&A.appendChild(M("quote","Quote message","quote"));for(let L of m)A.appendChild(M(L.iconName??"ellipsis",L.label,EL(L.id)));return A},bi=(e,t,o,n,r,a)=>{let i=o??{},d=i.layout??"bubble",c=i.avatar,u=i.timestamp,p=c?.show??!1,m=u?.show??!1,h=c?.position??"left",y=u?.position??"below",x=od(e.role,d),C=I("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let E=th(a?.widgetConfig?.future).components.message,A=a?.widgetConfig?.theme?.components?.message;TL(C,e.role,d,e.role==="user"?{...E.user,...A?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...E.assistant,...A?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),d==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=mL(e),L=e.content?.trim()??"",S=M.length>0&&L===ii,T=Uu(a?.widgetConfig?.features?.streamAnimation),B=a?.widgetConfig?.features?.streamAnimation?.plugins,_=e.role==="assistant"&&T.type!=="none"?Xl(T.type,B):null,X=e.role==="assistant"&&_?.isAnimating?.(e)===!0,$=e.role==="assistant"&&_!==null&&(!!e.streaming||X);$&&_?.bubbleClass&&C.classList.add(_.bubbleClass);let k=document.createElement("div");k.classList.add("persona-message-content"),e.streaming&&k.classList.add("persona-content-streaming"),$&&_&&(_.containerClass&&k.classList.add(_.containerClass),k.style.setProperty("--persona-stream-step",`${T.speed}ms`),k.style.setProperty("--persona-stream-duration",`${T.duration}ms`));let H=$?qu(e.content??"",T.buffer,_,e,!!e.streaming):e.content??"",F=()=>{let Me=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent});return $&&_?.wrap==="char"?Ql(Me,"char",e.id,{skipTags:_.skipTags}):$&&_?.wrap==="word"?Ql(Me,"word",e.id,{skipTags:_.skipTags}):Me},W=null;if(S?(W=document.createElement("div"),W.innerHTML=F(),W.style.display="none",k.appendChild(W)):e.contentSegments?.length?xL(k,e.contentSegments,Me=>t({text:Me,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):k.innerHTML=F(),$&&_?.useCaret&&!S&&L){let Me=Vu(),N=k.querySelectorAll(".persona-stream-char, .persona-stream-word"),Oe=N[N.length-1];if(Oe?.parentNode)Oe.parentNode.insertBefore(Me,Oe.nextSibling);else{let Ve=k.lastElementChild;Ve?Ve.appendChild(Me):k.appendChild(Me)}}if(m&&y==="inline"&&e.createdAt){let Me=zw(e,u,"span");Me.classList.add("persona-timestamp-inline");let N=k.lastElementChild;N?N.appendChild(Me):k.appendChild(Me)}if(M.length>0){let Me=CL(M,!S&&!!L,()=>{S&&W&&(W.style.display="")});Me?C.appendChild(Me):S&&W&&(W.style.display="")}let oe=gL(e);if(oe.length>0){let Me=SL(oe);Me&&C.appendChild(Me)}let V=hL(e);if(V.length>0){let Me=wL(V);Me&&C.appendChild(Me)}let de=yL(e);if(de.length>0){let Me=AL(de);Me&&C.appendChild(Me)}let ce=e.contentSegments?.length?null:bL(e.contextMentions);if(ce&&C.appendChild(ce),C.appendChild(k),m&&y==="below"&&e.createdAt){let Me=zw(e,u);Me.classList.add("persona-mt-1"),C.appendChild(Me)}let ge=e.role==="assistant"?uL(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Me=!!(H&&H.trim()),N=T.placeholder==="skeleton",Oe=N&&T.buffer==="line"&&Me;if(Me)Oe&&C.appendChild(Yl());else if(N)C.appendChild(Yl());else{let Ve=Mh("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ve&&C.appendChild(Ve)}}ge&&e.stopReason&&!e.streaming&&(L||(k.style.display="none"),C.appendChild(pL(e.stopReason,ge)));let Pe=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,Ae=a?.actionEligibility,ve=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&Ae?.canEdit===!0||n?.showQuote===!0&&Ae?.canQuote===!0||Xw(n,"user").length>0);if((Pe||ve)&&n){let Me=Th(e,ve?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,Ae);C.appendChild(Me)}if(!p||e.role==="system")return C;let Gt=I("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Bt=ML(c,e.role);return h==="right"||h==="left"&&e.role==="user"?Gt.append(C,Bt):Gt.append(Bt,C),Gt},Qw=(e,t,o,n,r,a)=>{let i=o??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):bi(e,t,o,n,r,a)};var PL=40,kL=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let o=null;try{o=t()}catch(n){console.warn("[persona] welcome.icon renderer threw",n)}if(!o){e.hidden=!0;return}e.appendChild(o),e.hidden=!1;return}if(t.type==="lucide"){let o=ae(t.name,PL);if(!o){e.hidden=!0;return}e.appendChild(o)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},Yw=(e,t,o={})=>{let n=Q("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let r=I("p","persona-welcome-kicker");r.hidden=!0;let a=I("h2","persona-welcome-title"),i=I("p","persona-welcome-subtitle"),d=Q("div",{className:"persona-welcome-head-text"},r,a),c=Q("div",{className:"persona-welcome-title-row"},n,d);return{host:Q("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:o.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,i,t),iconHolder:n,kicker:r,title:a,subtitle:i,starterSuggestions:t}},vi=(e,t,o)=>{t.hidden=!o,t.style.display=o?"":"none",e.classList.toggle("persona-gap-6",o),e.classList.toggle("persona-gap-3",!o)},Qu=(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==="",kL(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"),t.iconPlacement==="inline"?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")},LL="data-persona-welcome-plugin",Jw="data-persona-welcome-overlay",Xu="persona-welcome-overlay-active",Eh=new WeakMap,Ph=(e,t,o)=>{o.setAttribute(LL,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Jw,""),e.classList.contains(Xu)||(Eh.set(e,e.scrollTop),e.classList.add(Xu),e.scrollTop=0)},kh=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Jw),e.classList.contains(Xu)&&(e.classList.remove(Xu),e.scrollTop=Eh.get(e)??e.scrollTop,Eh.delete(e))},Zw=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Yu=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Q("div",{className:od("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:n==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Q("div",{className:"persona-flex"},r)),e.hidden=!1},eA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,tA=(e,t)=>{if(eA()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let o=e.getBoundingClientRect(),n=e.parentElement,r=0,a=0,i=0;if(n){let x=getComputedStyle(n);r=parseFloat(x.rowGap)||0;let C=e.previousElementSibling,E=e.nextElementSibling,M=n.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-n.scrollTop;a=Math.max(0,C?o.top-C.getBoundingClientRect().bottom-r:o.top-M),i=Math.max(0,E?E.getBoundingClientRect().top-o.bottom-r:0)}let d=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),u=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${o.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${a}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=d,t(m))};return m.finished.then(y).catch(y),m},oA=(e,t,o,n=260)=>{if(t<=1||eA()||typeof e.animate!="function"||!e.isConnected)return null;let r=o==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:n,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var IL="Hello \u{1F44B}",RL="I can answer questions and help you get things done here.",nA=new WeakSet,wo=(e,t)=>!!e&&e[t]!==void 0,HL=(e,t)=>{!e||e.debug!==!0||!t.length||nA.has(e)||(nA.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},xi=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let o=e?.welcome,n=e?.copy,r=e?.future?.v5Defaults===!0,a=o?.layout??(r?"centered":"top"),i=wo(o,"variant")?o.variant:n?.showWelcomeCard===!1?"none":"card",d=i==="hero"&&!r&&o?.layout===void 0?"on-first-message":wo(o,"dismiss")?o.dismiss:r||i==="hero"?"on-first-message":"never",c=[];wo(o,"title")&&wo(n,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),wo(o,"subtitle")&&wo(n,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),wo(o,"variant")&&wo(n,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&wo(o,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&o?.layout===void 0&&i==="hero"&&wo(o,"dismiss")&&o.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let u=o?.anchor??(a==="centered"&&t?"center":"bottom"),p=jl(o?.anchorComposerTop)!==null;return wo(o,"anchorComposerTop")&&!p&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),u!=="center"&&(wo(o,"anchorComposerTop")||wo(o,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),HL(e,c),{title:wo(o,"title")?o.title:n?.welcomeTitle??(r?"What can I help with?":IL),kicker:o?.kicker??"",subtitle:wo(o,"subtitle")?o.subtitle:n?.welcomeSubtitle??(r?"":RL),icon:o?.icon,align:o?.align==="start"||o?.align==="center"?o.align:a==="centered"?"center":void 0,iconPlacement:o?.icon&&typeof o.icon!="function"&&o.icon.placement==="inline"?"inline":"above",variant:i,dismiss:d,message:i==="hero"?void 0:o?.message,layout:a,anchor:u,anchorComposerTop:p?o.anchorComposerTop:"44%",composerGap:o?.composerGap?.trim()||Du}},rA=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",ds=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var WL="var(--persona-components-panel-maxWidth)",sA="var(--persona-components-panel-height)",BL="var(--persona-components-panel-maxHeight)",ua=e=>{let t=fr(e),o=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,n=e?.launcher?.heightOffset??0,r=n===0?`max(200px, ${sA})`:`max(200px, calc(${sA} - ${n}px))`;return{width:o??Cx,maxWidth:o??WL,height:r,maxHeight:BL}},aA="16px",Ih="10px",Rh="14px",iA=e=>{let t=e?.launcher?.enabled??!0,o=yt(e);if(ls(e)){let u=e?.launcher?.composerBar??{},p=I("div","persona-widget-wrapper persona-fixed persona-transition");p.setAttribute("data-persona-composer-bar",""),p.dataset.state="collapsed",p.dataset.expandedSize=u.expandedSize??"anchored",p.style.zIndex=String(e?.launcher?.zIndex??co);let m=I("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",p.appendChild(m);let h=I("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=u.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??co),{wrapper:p,panel:m,pillRoot:h}}if(o){let u=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),p=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(p),{wrapper:u,panel:p}}if(!t){let u=I("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),p=I("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=fr(e),y=m.launcherWidth||m.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?ua(e).width:"100%";return u.style.width=y,p.style.width="100%",u.appendChild(p),{wrapper:u,panel:p}}let r=e?.launcher??{},a=r.position&&Qo[r.position]?Qo[r.position]:Qo["bottom-right"],i=I("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??co);let d=I("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=ua(e);return d.style.width=c.width,d.style.maxWidth=c.maxWidth,i.appendChild(d),{wrapper:i,panel:d}},Hh=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":mh(e)}});return t.hidden=!0,t},lA=(e,t)=>{let o=Hh("starter"),n=Yw(e,o,{flatShadow:yt(e)}),r=xi(e);Qu(n,r),vi(t,n.host,ds(r,e?.initialMessages));let a=Zw();return Yu(a,r.message,e),{welcome:n,greetingHost:a}},DL=(e,t)=>{let o=I("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:r}=gi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:aA,iconSize:Ih});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,i=null,d=null;if(a){let B=hi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:aA,iconSize:Rh});i=B.button,d=B.wrapper,d.style.position="absolute",d.style.top="8px",d.style.right="32px",d.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=lA(e,u),{host:h,title:y,subtitle:x}=p,C=p.starterSuggestions,E=I("div","persona-widget-messages persona-flex persona-flex-col");E.style.gap="var(--persona-components-message-gap, 12px)";let A=Hh("followUp"),M=as(e,!0);M&&(E.style.maxWidth=M,E.style.marginLeft="auto",E.style.marginRight="auto",E.style.width="100%"),u.append(h,m,E,A);let L=Q("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"}}),b=Ku({config:e}),{root:S,textNode:T}=Vw();return o.append(c,r,u,L),d&&o.appendChild(d),{container:o,body:u,messagesWrapper:E,starterSuggestions:C,transcriptSuggestions:A,composerOverlay:L,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:h,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:y,introSubtitle:x,closeButton:n,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:d,iconHolder:I("span"),headerTitle:I("span"),headerSubtitle:I("span"),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:S,peekTextNode:T}},dA=(e,t=!0)=>{if(ls(e))return DL(e,t);let o=Q("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,r=e?.layout?.showHeader!==!1,a=n?yi(e,n,{showClose:t}):Sr({config:e,showClose:t}),i=Q("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=lA(e,i),{host:u,title:p,subtitle:m}=d,h=d.starterSuggestions,y=I("div","persona-widget-messages persona-flex persona-flex-col");y.style.gap="var(--persona-components-message-gap, 12px)";let x=Hh("followUp"),C=as(e,!1);C&&(y.style.maxWidth=C,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),i.append(u,c,y,x);let E=da({config:e}),A=e?.layout?.showFooter!==!1;r?aa(o,a,e):(a.header.style.display="none",aa(o,a,e)),o.append(i);let M=Q("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 A||(E.footer.style.display="none"),o.append(E.footer),o.append(M),{container:o,body:i,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:x,composerOverlay:M,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,welcomeHost:u,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:p,introSubtitle:m,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:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode}};var Wh=(e,t)=>{let o=I("button");o.type="button",o.innerHTML=`
|
|
30
|
-
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
31
|
-
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
32
|
-
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
33
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>
|
|
34
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
35
|
-
</span>
|
|
36
|
-
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
37
|
-
`,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=yt(a),c=Pu(a)==="circle";c?(o.dataset.personaLauncherVariant="circle",o.setAttribute("aria-label",i.title??"Open chat")):(o.removeAttribute("data-persona-launcher-variant"),o.removeAttribute("aria-label"));let u=o.querySelector("[data-role='launcher-title']");if(u){let b=i.title??"Chat Assistant";u.textContent=b,u.setAttribute("title",b)}let p=o.querySelector("[data-role='launcher-subtitle']");if(p){let b=i.subtitle??"Here to help you get answers fast";p.textContent=b,p.setAttribute("title",b)}let m=o.querySelector(".persona-flex-col");m&&(i.textHidden||d||c?m.style.display="none":m.style.display="");let h=o.querySelector("[data-role='launcher-icon']");if(h)if(i.agentIconHidden)h.style.display="none";else{let b=i.agentIconSize??"40px";if(h.style.height=b,h.style.width=b,i.agentIconBackgroundColor?(h.style.backgroundColor=i.agentIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),h.innerHTML="",i.agentIconName){let S=parseFloat(b)||24,T=ae(i.agentIconName,S*.6,"var(--persona-text-inverse, #ffffff)",1.5);T?(h.appendChild(T),h.style.display=""):(h.textContent=i.agentIconText??"\u{1F4AC}",h.style.display="")}else i.iconUrl?h.style.display="none":(h.textContent=i.agentIconText??"\u{1F4AC}",h.style.display="")}let y=o.querySelector("[data-role='launcher-image']");if(y){let b=i.agentIconSize??"40px";y.style.height=b,y.style.width=b,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let x=o.querySelector("[data-role='launcher-call-to-action-icon']");if(x){let b=i.callToActionIconSize??"32px";x.style.height=b,x.style.width=b,i.callToActionIconBackgroundColor?(x.style.backgroundColor=i.callToActionIconBackgroundColor,x.classList.remove("persona-bg-persona-primary")):(x.style.backgroundColor="",x.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(x.style.color=i.callToActionIconColor,x.classList.remove("persona-text-persona-call-to-action")):(x.style.color="",x.classList.add("persona-text-persona-call-to-action"));let S=0;if(i.callToActionIconPadding?(x.style.boxSizing="border-box",x.style.padding=i.callToActionIconPadding,S=(parseFloat(i.callToActionIconPadding)||0)*2):(x.style.boxSizing="",x.style.padding=""),i.callToActionIconHidden||c)x.style.display="none";else if(x.style.display=d?"none":"",x.innerHTML="",i.callToActionIconName){let T=parseFloat(b)||24,B=Math.max(T-S,8),_=ae(i.callToActionIconName,B,"currentColor",1.5);_?x.appendChild(_):x.textContent=i.callToActionIconText??"\u2197"}else x.textContent=i.callToActionIconText??"\u2197"}let C=i.position&&Qo[i.position]?Qo[i.position]:Qo["bottom-right"],E="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",A="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";o.className=d?A:`${E} ${C}`,d||(o.style.zIndex=String(i.zIndex??co));let M="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=i.border??M,o.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:L,d?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=i.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},r=()=>{o.removeEventListener("click",t),o.remove()};return e&&n(e),{element:o,update:n,destroy:r}},OL="teaser-dismissed",uA=new Set,cA=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${OL}`},_L=(e,t)=>{if(uA.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},NL=(e,t)=>{if(uA.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},FL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,UL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||yt(e??{})?null:t},pA=(e,t)=>{let o=I("div","persona-launcher-surface");o.setAttribute("data-persona-launcher-surface","true");let n=e??{},r=null,a=null,i=null,d=null,c=null,u=!1,p=!1,m=!1,h=!1,y=()=>(r?.frequency??"once")==="once"&&n.persistState!==!1,x=()=>{c!==null&&(clearTimeout(c),c=null)},C=()=>{!a||!u||(u=!1,a.hidden=!0)},E=oe=>{x(),m=!0,C(),NL(cA(n),oe&&y())},A=oe=>{!r||m||E(oe==="user"&&u)},M=()=>{c=null,!(!a||m||h)&&(p=!0,u=!0,a.hidden=!1,!(FL()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},L=()=>{!r||!a||m||p||h||_L(cA(n),y())||(x(),c=setTimeout(M,Math.max(0,r.delayMs??0)))},b=()=>{E(y()),t()},S=oe=>{oe.stopPropagation(),E(y())},B=Wh(e,()=>{A("user"),t()}),_=()=>{x(),d?.removeEventListener("click",b),i?.removeEventListener("click",S),a?.remove(),a=null,d=null,i=null,u=!1},X=()=>{d=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),d.addEventListener("click",b),i=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",S),a=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},d,i),o.insertBefore(a,B.element)},$=()=>{let oe=n.launcher?.position??"bottom-right",V=Qo[oe]??Qo["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",B.element.style.position="";return}o.className=bo("persona-launcher-surface",V),o.setAttribute("data-teaser",oe),o.style.zIndex=String(n.launcher?.zIndex??co),B.element.style.position="static"},k=oe=>{let V=UL(oe);if(r=V,!V){_();return}a||X(),d.textContent=V.text,i.hidden=V.dismissible===!1,i.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),L()},H=oe=>{n=oe,B.update(oe),k(oe),$()},F=(oe,V="user")=>{h=oe,oe&&A(V)},W=()=>{_(),B.destroy(),o.remove()};return o.appendChild(B.element),e&&(k(e),$()),{element:o,launcher:B,get teaser(){return a?{element:a,show:M,dismiss:E}:null},setPanelOpen:F,update:H,destroy:W}};var fA=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=iA(e),a=dA(e,t),i={wrapper:o,panel:n,pillRoot:r},d={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},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},u={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:i,panelElements:a,transcript:d,header:c,composer:u,replaceHeader:h=>(c.element.replaceWith(h.header),c.element=h.header,c.iconHolder=h.iconHolder,c.headerTitle=h.headerTitle,c.headerSubtitle=h.headerSubtitle,c.closeButton=h.closeButton,c.closeButtonWrapper=h.closeButtonWrapper,c.clearChatButton=h.clearChatButton,c.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{u.footer.replaceWith(h),u.footer=h}}},Bh=({config:e,plugins:t,onToggle:o})=>{let n=t.find(a=>a.renderLauncher);if(n?.renderLauncher){let a=n.renderLauncher({config:e,defaultRenderer:()=>Wh(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let r=pA(e,o);return{instance:r,element:r.element}};var qL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},VL=(e,t,o)=>`${qL(e)}plugin:${t}:${o}`,mA=e=>{let t=new Map,o=!1,n=()=>{if(o||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return o=!0,null}};return r=>{let a=i=>VL(e(),r,i);return{get:i=>{let d=a(i),c=n();if(c)try{return c.getItem(d)}catch{o=!0}return t.get(d)??null},set:(i,d)=>{let c=a(i),u=n();if(u)try{u.setItem(c,d);return}catch{o=!0}t.set(c,d)},remove:i=>{let d=a(i);t.delete(d);let c=n();if(c)try{c.removeItem(d)}catch{o=!0}}}}};var Ci=(e,t,o)=>{let n=o;for(let r of t){let a=I("span","persona-tool-char");a.style.setProperty("--char-index",String(n)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),n++}return n};var $L=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,t).join(`
|
|
38
|
-
`):""},Dh=(e,t,o)=>{Nc(e,t,{stateSet:o,previewKind:"reasoning",iconColor:"currentColor"})},Oh=(e,t,o=new Set)=>{t=Fc(t,"reasoning");let n=e.reasoning,r=Bc("persona-reasoning-bubble",e.id);if(!n)return gr(r,e,t,"reasoning");let a=t?.features?.reasoningDisplay??{},i=a.expandable??Xs.expandable,d=i&&o.has(e.id),c=n.status!=="complete",u=$L(e,a.previewMaxLines??Xs.previewMaxLines),p=Dc({expandable:i,expanded:d,bubbleType:"reasoning"}),m=I("div","persona-flex persona-flex-col persona-text-left"),h=I("span","persona-text-xs persona-text-persona-primary"),y=Qr(t,"reasoning")==="row",x=y&&!c?`Thought for ${Al(n.durationMs??(n.completedAt!==void 0&&n.startedAt!==void 0?n.completedAt-n.startedAt:void 0))}`:"Thinking...",C=t?.reasoning??{},E=String(n.startedAt??Date.now()),A=()=>{let V=I("span","");return V.setAttribute("data-tool-elapsed",E),V.textContent=tu(n),V},M=C.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:x,previewText:u,isActive:c,config:t??{},elapsed:tu(n),createElapsedElement:A});typeof M=="string"&&M.trim()?(h.textContent=M,m.appendChild(h)):M instanceof HTMLElement?m.appendChild(M):(h.textContent=x,m.appendChild(h));let L=I("span","persona-text-xs persona-text-persona-primary");L.textContent=wC(n),y||m.appendChild(L);let b=a.loadingAnimation??Xs.loadingAnimation,S=C.activeTextTemplate,T=C.completeTextTemplate,B=c?S:T,_=M instanceof HTMLElement,X=(V,de)=>{h.textContent="";let ce=ou(V,""),ge=0;for(let Pe of ce){let Ae=Pe.styles.length>0?(()=>{let ve=I("span",Pe.styles.map(Gt=>`persona-tool-text-${Gt}`).join(" "));return h.appendChild(ve),ve})():h;if(Pe.isDuration&&c)Ae.appendChild(A());else{let ve=Pe.isDuration?tu(n):Pe.text;de?ge=Ci(Ae,ve,ge):Ae.appendChild(document.createTextNode(ve))}}};if(!_&&B)if(L.style.display="none",h.style.display="",c&&b!=="none"){let V=C.loadingAnimationDuration??2e3;h.setAttribute("data-preserve-animation","true"),b==="pulse"?(h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${V}ms`),X(B,!1)):(h.classList.add(`persona-tool-loading-${b}`),h.style.setProperty("--persona-tool-anim-duration",`${V}ms`),b==="shimmer-color"&&(C.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor)),X(B,!0))}else X(B,!1);else if(!_&&c&&b!=="none"){h.style.display="";let V=C.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),b==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{h.classList.add(`persona-tool-loading-${b}`),h.style.setProperty("--persona-tool-anim-duration",`${V}ms`),b==="shimmer-color"&&(C.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor));let de=h.textContent||x;h.textContent="",Ci(h,de,0)}n.status==="complete"&&!y&&(h.style.display="none")}else _||(n.status==="complete"&&!y?h.style.display="none":h.style.display="");if(a.iconName&&!_){let V=I("span","persona-reasoning-header-icon"),de=ae(a.iconName,16,"currentColor",2);de&&(V.appendChild(de),p.appendChild(V))}let $="currentColor",k=Za(p,m,{expandable:i,expanded:d,iconColor:$,metaGap:!1}),H=Oc({bubble:r,previewKind:"reasoning",expanded:d,isActive:c,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:u,isActive:c,config:t??{}})});if(!i)return r.append(p,H),gr(r,e,t,"reasoning");let F=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=d?"":"none";let W=n.chunks.join(""),oe=I("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=W||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(oe),_c({expanded:d,header:p,toggleIcon:k,content:F,collapsedPreview:H,iconColor:$}),r.append(p,H,F),gr(r,e,t,"reasoning")};var gA=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return gA(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},jL=e=>{if(e!==null&&typeof e=="object")return!0;if(typeof e!="string")return!1;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"}catch{return!1}};function hA(e,t,o){let n=t.toolCall;if(!n)return;let r=o.toolCall??{},a=(d,c)=>{let u=Q("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":d.toLowerCase()},style:{backgroundColor:r.codeBlockBackgroundColor,borderColor:r.codeBlockBorderColor,borderWidth:r.codeBlockBorderColor?"1px":void 0}}),p=Q("div",{className:"persona-tool-detail-label",text:d,style:{color:r.labelTextColor}}),m=ai(c),h=Q("pre",{className:`persona-tool-detail-value${jL(c)?" persona-tool-detail-code":""}`,text:m,attrs:m.length>420||m.split(`
|
|
39
|
-
`).length>7?{tabindex:"0","aria-label":`${d} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),y=Q("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${d.toLowerCase()}`,title:`Copy ${d.toLowerCase()}`}}),x=ae("copy",14,"currentColor",1.7);x&&y.appendChild(x),u.append(p,h,y),e.appendChild(u)};gA(n.args)||a("Request",n.args);let i=n.status==="complete"&&n.result!==void 0?n.result:n.chunks?.join("");i!==void 0&&(typeof i!="string"||i.trim())&&a("Response",i),n.success===!1&&e.appendChild(Q("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var _h=new WeakMap;async function yA(e){let t=e.closest("[data-persona-tool-detail]"),o=t?.querySelector("pre");if(!o)return;let n=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(_h.get(e));try{await navigator.clipboard.writeText(o.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=ae("check",14,"currentColor",2);r&&e.replaceChildren(r)}catch{e.setAttribute("aria-label","Copy failed \u2014 try again"),e.title="Copy failed \u2014 try again"}_h.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",n),e.title=n;let r=ae("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),_h.delete(e)},1800))}var bA=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),zL=(e,t)=>{let o=e.toolCall;if(!o)return"";let n=(o.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
40
|
-
`);let r=ai(o.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
41
|
-
`):""},Nh=(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)"},KL=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??mr.collapsedMode,a=o?.success===!1?o.error||"Tool failed":zL(e,n?.previewMaxLines??mr.previewMaxLines),i=o?Qr(t,"tool")==="row"?`${o.status==="complete"?"Used":"Using"} ${o.name?.trim()||"tool"}`:MC(o):"";if(!o)return{summary:i,previewText:a,isActive:!1};let d=o.status!=="complete",c=t?.toolCall??{},u=i;return r==="tool-name"?u=o.name?.trim()||i:r==="tool-preview"&&a&&(u=a),d&&c.activeTextTemplate?u=Ag(o,c.activeTextTemplate,u):!d&&c.completeTextTemplate&&(u=Ag(o,c.completeTextTemplate,u)),o.success===!1&&(u+=" \xB7 Failed"),{summary:u,previewText:a,isActive:d}},Fh=(e,t,o,n)=>{Nc(e,t,{stateSet:o,previewKind:"tool",iconColor:bA(n?.toolCall??{},t.classList.contains("persona-activity-row"))})},Uh=(e,t,o=new Set)=>{t=Fc(t,"tool");let n=e.toolCall,r=t?.toolCall??{},a=Bc("persona-tool-bubble",e.id);if(r.backgroundColor&&(a.style.backgroundColor=r.backgroundColor),r.borderColor&&(a.style.borderColor=r.borderColor),r.borderWidth&&(a.style.borderWidth=r.borderWidth),r.borderRadius&&(a.style.borderRadius=r.borderRadius),a.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!n)return gr(a,e,t,"tool");let i=t?.features?.toolCallDisplay??{},d=i.expandable??mr.expandable,c=d&&o.has(e.id),{summary:u,previewText:p,isActive:m}=KL(e,t),h=Dc({expandable:d,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(h.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(h.style.paddingLeft=r.headerPaddingX,h.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(h.style.paddingTop=r.headerPaddingY,h.style.paddingBottom=r.headerPaddingY);let y=I("div","persona-flex persona-flex-col persona-text-left"),x=I("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(x.style.color=r.headerTextColor);let C=String(n.startedAt??Date.now()),E=()=>{let H=I("span","");return H.setAttribute("data-tool-elapsed",C),H.textContent=Hl(n),H},A=r.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:u,previewText:p,collapsedMode:i.collapsedMode??mr.collapsedMode,isActive:m,config:t??{},elapsed:Hl(n),createElapsedElement:E});typeof A=="string"&&A.trim()?(x.textContent=A,y.appendChild(x)):A instanceof HTMLElement?y.appendChild(A):(x.textContent=u,y.appendChild(x));let M=i.loadingAnimation??mr.loadingAnimation,L=r.activeTextTemplate,b=r.completeTextTemplate,S=m?L:b,T=A instanceof HTMLElement,B=(H,F)=>{x.textContent="";let W=n.name?.trim()||"tool",oe=ou(H,W),V=0;for(let de of oe){let ce=de.styles.length>0?(()=>{let ge=I("span",de.styles.map(Pe=>`persona-tool-text-${Pe}`).join(" "));return x.appendChild(ge),ge})():x;if(de.isDuration&&m)ce.appendChild(E());else{let ge=de.isDuration?Hl(n):de.text;F?V=Ci(ce,ge,V):ce.appendChild(document.createTextNode(ge))}}};if(!T)if(m&&M!=="none"){let H=r.loadingAnimationDuration??2e3;if(x.setAttribute("data-preserve-animation","true"),M==="pulse")x.classList.add("persona-tool-loading-pulse"),x.style.setProperty("--persona-tool-anim-duration",`${H}ms`),S&&B(S,!1);else if(x.classList.add(`persona-tool-loading-${M}`),x.style.setProperty("--persona-tool-anim-duration",`${H}ms`),M==="shimmer-color"&&(r.loadingAnimationColor&&x.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&x.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),S)B(S,!0);else{let F=x.textContent||u;x.textContent="",Ci(x,F,0)}}else S&&B(S,!1);let _=bA(r,Qr(t,"tool")==="row"),X=Za(h,y,{expandable:d,expanded:c,iconColor:_,metaGap:!0}),$=Oc({bubble:a,previewKind:"tool",expanded:c,isActive:m,previewText:p,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:p,isActive:m,config:t??{}})});if(!d)return a.append(h,$),gr(a,e,t,"tool");let k=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=c?"":"none",r.contentBackgroundColor&&(k.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(k.style.color=r.contentTextColor),r.contentPaddingX&&(k.style.paddingLeft=r.contentPaddingX,k.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(k.style.paddingTop=r.contentPaddingY,k.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)hA(k,e,t);else{if(n.name){let H=I("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?H.style.color=r.contentTextColor:r.headerTextColor&&(H.style.color=r.headerTextColor),H.textContent=n.name,k.appendChild(H)}if(n.args!==void 0){let H=I("div","persona-space-y-1"),F=I("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(F.style.color=r.labelTextColor),F.textContent="Arguments";let W=I("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Nh(W,r),W.textContent=ai(n.args),H.append(F,W),k.appendChild(H)}if(n.chunks&&n.chunks.length){let H=I("div","persona-space-y-1"),F=I("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(F.style.color=r.labelTextColor),F.textContent="Activity";let W=I("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Nh(W,r),W.textContent=n.chunks.join(""),H.append(F,W),k.appendChild(H)}if(n.success===!1&&k.appendChild(Q("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let H=I("div","persona-space-y-1"),F=I("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(F.style.color=r.labelTextColor),F.textContent="Result";let W=I("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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Nh(W,r),W.textContent=ai(n.result),H.append(F,W),k.appendChild(H)}if(n.status==="complete"&&typeof n.duration=="number"){let H=I("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(H.style.color=r.contentTextColor),H.textContent=`Duration: ${n.duration}ms`,k.appendChild(H)}}return _c({expanded:c,header:h,toggleIcon:X,content:k,collapsedPreview:$,iconColor:_}),a.append(h,$,k),gr(a,e,t,"tool")};var{setLoader:GL,load:XL,provide:YN,getSync:QL}=vt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),vA=GL,xA=XL;var CA=QL;var{setLoader:YL,load:JL}=vt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),SA=YL,qh=JL;var Vh=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),n?this.options.set(t,n):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,n])=>{this.register(o,n)})}},Mn=new Vh;var $h=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:ZL,load:eI,provide:aF,getSync:tI}=vt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Si=null,Ju=new Set,wA=e=>{if(Si)return Si;Si=e,e.initArtifactsUi({componentRegistry:Mn});for(let n of $h)Mn.has(n)||Mn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Un();t?e.__provideMarkdownParsers(t):ei(()=>{let n=Un();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>Rc());let o=[...Ju];Ju.clear();for(let n of o)try{n()}catch{}return e},AA=ZL,Zu=()=>eI().then(wA);var wr=()=>{if(Si)return Si;let e=tI();return e?wA(e):null},jh=e=>Si?()=>{}:(Ju.add(e),()=>{Ju.delete(e)});function Ao(e){return e?.features?.artifacts?.enabled===!0}function MA(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"),!Ao(t))return;let o=t.features?.artifacts?.layout,n=o?.paneBorder?.trim(),r=o?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function oI(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var TA=["panel","seamless","detached"];function zh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&TA.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Kh(e){return!e||!Ao(e)?!1:zh(e)==="detached"}function nd(e,t){if(!Ao(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),oI(e),MA(e,t);return}let o=t.features?.artifacts?.layout,n=zh(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",o.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=o?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[o?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[o?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[o?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[o?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[d,c]of i){let u=d?.trim();u?e.style.setProperty(c,u):e.style.removeProperty(c)}MA(e,t)}function rd(e,t){for(let d of TA)e.classList.remove(`persona-artifact-appearance-${d}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Ao(t))return;let o=t.features?.artifacts?.layout,n=zh(t);e.classList.add(`persona-artifact-appearance-${n}`);let r=o?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let i=o?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function EA(e,t){return!t||!Ao(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var nI=new Set(["__proto__","prototype","constructor"]),rI=new Set(["collapsed","card","panel","inline"]),PA=new Set(["markdown","component"]),sI=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tp=e=>!nI.has(e),Gh=e=>typeof e=="string"&&rI.has(e),fa=e=>Object.keys(e).length>0;function Kn(e,t,o,n){e.push({path:t,code:o,message:n})}var aI="Ignored because this key is not part of the persisted preference schema.",ep="Ignored an unsupported value.",iI="Expected collapsed, panel, or inline.",lI='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',kA={kind:"mode",message:ep},wi={kind:"string",message:"Expected a CSS length string."},Ar={kind:"boolean"},dI={paneWidth:wi,paneMaxWidth:wi,paneMinWidth:wi,expandedPanelWidth:wi,resizableMinWidth:wi,resizableMaxWidth:wi,expandLauncherPanelWhenOpen:Ar,resizable:Ar},cI={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Ar,showReasoning:Ar,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:ep},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:ep},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:ep},expandable:Ar,grouped:Ar}},reasoningDisplay:{kind:"object",children:{expandable:Ar,activePreview:Ar}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:kA,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:kA,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:PA,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:PA}}},filePreview:{kind:"object",children:{enabled:Ar}},layout:{kind:"object",children:dI}}}}};function LA(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Kn(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Kn(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Kn(n,o,"invalid_value",t.message);case"mode":return Gh(e)?Bo(e):Kn(n,o,"invalid_value",t.message);case"modeMap":{if(!pa(e))return Kn(n,o,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[i,d]of Object.entries(e)){let c=r?i:Jr(i);tp(i)&&(r?r.has(i):sI.test(c))?Gh(d)?a[c]=Bo(d):Kn(n,`${o}.${i}`,"invalid_value",iI):Kn(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":lI)}return fa(a)?a:void 0}case"object":{if(t.bareMode&&Gh(e))return Bo(e);if(!pa(e))return Kn(n,o,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=d=>o?`${o}.${d}`:d;for(let d of Object.keys(e))(!tp(d)||!r.includes(d))&&Kn(n,a(d),"unknown_key",aI);let i={};for(let d of r){let c=t.children[d],u=LA(e[d],c,a(d),n);if(c.deprecated&&e[d]!==void 0&&Kn(n,a(d),"deprecated_key",c.deprecated),u===void 0)continue;let p=c.alias??d,m=i[p];i[p]=pa(m)&&pa(u)?{...m,...u}:u}return fa(i)?i:void 0}}}function Xh(e){let t=[];return{preferences:(e===null?void 0:LA(e,cI,"",t))??{},issues:t}}function Ai(e){if(Array.isArray(e))return e.map(Ai);if(!pa(e))return e;let t={};for(let[o,n]of Object.entries(e))tp(o)&&n!==void 0&&(t[o]=Ai(n));return t}function IA(e,t){let o=Ai(e);for(let[n,r]of Object.entries(t)){if(!tp(n)||r===void 0)continue;let a=o[n];o[n]=pa(a)&&pa(r)?IA(a,r):Ai(r)}return o}function uI(e){let t={},o;for(let r of e){let a=Xh(r).preferences;o=RA(o,a.artifacts?.display),t=IA(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function pI(e,t){if(t===void 0)return e===void 0?void 0:Ai(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...fa(r)?{byMediaType:r}:{}};return fa(a)?a:void 0}function RA(e,t){if(t===void 0)return e===void 0?void 0:Ai(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byType,...o.byKind,...t.byType,...t.byKind},a=pI(o.files,t.files),i={...n?{default:n}:{},...fa(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return fa(i)?i:void 0}function Qh(e={},t){let o=uI(t),n={...e};if(o.showToolCalls!==void 0&&(n.showToolCalls=o.showToolCalls),o.showReasoning!==void 0&&(n.showReasoning=o.showReasoning),o.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...o.toolCallDisplay}),o.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...o.reasoningDisplay}),o.artifacts){let r=e.artifacts??{},a={...r};if(o.artifacts.display!==void 0){let i=RA(r.display,o.artifacts.display);i!==void 0&&(a.display=i)}o.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:o.artifacts.filePreview.enabled}),o.artifacts.layout&&(a.layout={...r.layout,...o.artifacts.layout}),n.artifacts=a}return n}function sd(e){let t=e.preferences;return!t||!fa(t)?e:{...e,features:Qh(e.features??{},[t])}}function fI(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function mI(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function gI(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function hI(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function Yh(e,t){let n=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function HA(e,t,o,n,r,a,i=200){let d=fI(r,200),c=hI(t,o,n,i);c=Math.max(d,c);let u=mI(a);return u!==null&&(c=Math.min(c,u)),gI(e,d,c)}var{setLoader:yI,load:bI,provide:fF,getSync:vI}=vt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),WA=yI,BA=bI;var DA=vI;var Jh=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let n=new Set(t.map(a=>a.id));return[...o.filter(a=>!n.has(a.id)),...t].sort((a,i)=>(i.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ad=new Jh;var OA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xI=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),_A=(e,t,o)=>{if(!OA(e)||!OA(t)||xI.has(o))return t;let n={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete n[r];continue}let a=o?`${o}.${r}`:r;n[r]=_A(e[r],t[r],a)}return n};function op(e,t){let o=Lc(Ks),n=vx(e,t,o),r=Qm(xx(_A(e,t,""),o,n),n);return Zm(Ya(r),Sx(e,t))}var NA=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>o(r,a)),o=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:o,emit:(r,a)=>{e.get(r)?.forEach(i=>{try{i(a)}catch(d){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var CI=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},SI=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let n=0;for(let r=o;r<t.length;r+=1){let a=t[r];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(o,r+1)}return null},id=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=CI(e),o=SI(t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||!n.action)return null;let{action:r,...a}=n;return{type:String(r),payload:a,raw:n}}catch{return null}},Zh=e=>typeof e=="string"?e:e==null?"":String(e),ma={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Zh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=Zh(o.element);if(n&&t.document?.querySelector){let r=t.document.querySelector(n);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Zh(o.text)}}},FA=e=>Array.isArray(e)?e.map(t=>String(t)):[],ld=e=>{let t=new Set(FA(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(FA(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let i=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!i&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let d=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:a.message})||null,null):null;if(!d)return null;t.add(a.message.id),n();let c={action:d,message:a.message};e.emit("action:detected",c);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",c)},m=u(d,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:o}};var wI=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},AI=e=>e.map(t=>({...t,streaming:!1})),MI=e=>e.map(t=>({...t,status:"complete"})),np=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?wI(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?AI(o.messages):void 0,artifacts:o.artifacts?MI(o.artifacts):void 0};n.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var TI=e=>{let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},UA=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let o=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}catch{}return TI(e)},EI=async(e,t)=>{let o=await UA(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await UA(`${e}\0${t}`)}`}};var qA=(e,t,o)=>{let n="",r="",a="",i=!1,d=!1,c=0,u=null,p=null,m=new Set,h=()=>{if(o||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},y=()=>{let T=h();if(!T)return u;try{return T.getItem(n)}catch{return i=!0,u}},x=(T,B)=>{if(d||T===u)return;let _=u;u=T,c+=1;let X={previousToken:_,token:T,source:B,revision:c};for(let $ of m)$(X)},C=T=>{d||T.key!==null&&T.key!==n||x(T.key===null?null:T.newValue??null,"external")},E=(async()=>{let T=await EI(e,t);n=T.storageKey,r=T.leaseKey,a=T.lockName,u=y(),!o&&typeof window<"u"&&window.addEventListener("storage",C)})(),A=T=>new Promise(B=>setTimeout(B,T)),M=()=>{let T=h();if(!T)return null;try{let B=T.getItem(r);if(!B)return null;let _=JSON.parse(B);return typeof _?.expiresAt=="number"&&typeof _?.ownerNonce=="string"?_:null}catch{return null}},L=T=>{let B=h();if(B)try{M()?.ownerNonce===T&&B.removeItem(r)}catch{}},b=T=>new Promise(B=>{let _=setTimeout(X,T);function X(){clearTimeout(_),window.removeEventListener("storage",$),B()}function $(k){(k.key===null||k.key===r)&&X()}window.addEventListener("storage",$)}),S=async T=>{let B=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,_=Date.now()+15e3;for(;Date.now()<_;){let X=h();if(!X)break;let $=Date.now(),k=M();if(k&&k.expiresAt>$&&k.ownerNonce!==B){await b(Math.min(k.expiresAt-$,500));continue}try{X.setItem(r,JSON.stringify({ownerNonce:B,expiresAt:$+1e4}))}catch{i=!0;break}if(await A(20+Math.random()*40),M()?.ownerNonce!==B){await b(500);continue}p=B;try{return await T()}finally{p=null,L(B)}}return T()};return{ready:E,async get(){return await E,x(y(),"external"),u},async set(T){await E;let B=h();if(B)try{B.setItem(n,T)}catch{i=!0}x(T,"local")},async clear(){await E;let T=h();if(T)try{T.removeItem(n)}catch{i=!0}x(null,"local")},revision(){return c},subscribe(T){return m.add(T),()=>{m.delete(T)}},async withFirstInitLock(T){await E;let B=globalThis.navigator?.locks;return B?.request?B.request(a,()=>T()):h()?S(T):T()},matches(T,B,_){return T===e&&B===t&&_===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),p&&L(p)}}};var{setLoader:PI,load:kI}=vt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),VA=PI,ey=kI;var ty=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Mr=e=>Object.freeze({...e}),$A=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),jA=e=>e?Mr(e):null;function zA(e){let{plugins:t,config:o}=e,n=!1,r=!1,a=!1,i=!1,d=null,c=[],u=()=>{for(let b of c.splice(0))try{b()}catch(S){ty("renderHistoryView cleanup",S)}},p=(b,S)=>{for(let T of t){let B=T[b];if(B)try{let _=B(S);if(_)return _}catch(_){ty(b,_)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),h={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:Mr(b.identityStatus),pendingAction:jA(b.pendingAction),copy:Mr(b.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:$A(b.conversation),active:b.active,pending:b.pending,open:b.open,requestDelete:b.requestDelete,defaultRenderer:b.defaultRenderer})):null,state:b=>i?p("renderHistoryState",Object.freeze({...m(),state:Mr(b.state),identityStatus:Mr(b.identityStatus),copy:Mr(b.copy),...b.retry?{retry:b.retry}:{},...b.startNewConversation?{startNewConversation:b.startNewConversation}:{},defaultRenderer:b.defaultRenderer})):null},y=t.flatMap(b=>(b.railSections??[]).map(S=>({...S,placement:S.placement??"above-conversations",items:[],render:T=>S.render(Object.freeze({collapsed:T,presentation:e.getPresentation(),actions:C}))}))),x=e.createView({slots:h,renderDom:!1,onModelChange:()=>L(),railSections:y}),C=Object.freeze({...x.operations,close:e.close}),E=()=>(i=!0,x.setDomRenderEnabled(!0),x.element),A=b=>Object.freeze({conversations:Object.freeze(b.conversations.map($A)),activeConversationId:b.activeConversationId,state:Mr(b.state),pendingAction:jA(b.pendingAction),identityStatus:Mr(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:Mr(x.copy),actions:C,defaultRenderer:E,requestRender:()=>L(),onCleanup:S=>{c.push(S)}}),M=()=>{i=!1;let b=null;for(let T of t)if(T.renderHistoryView){try{b=T.renderHistoryView(A(x.getModel()))}catch(B){ty("renderHistoryView",B),b=null}if(b)break}let S=!b||b.contains(x.element);return i=S,x.setDomRenderEnabled(S),b??x.element};function L(){if(!(!a||n||r)){r=!0;try{u();let b=M();if(b===d)return;let S=d;d=b,e.onElementChanged(b,S)}finally{r=!1}}}return a=!0,L(),{view:x,get element(){return d??x.element},requestRender:L,dispose:()=>{n=!0,u()}}}var LI=null;function KA(){return LI}var II=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),RI=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),oy=e=>RI.get(e)??"Conversation history is unavailable right now.";function HI(e){if(e instanceof pn)return e;if(e instanceof Fe){let t=II.get(e.code)??"unavailable";return new pn(t,oy(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new pn("unavailable",oy("unavailable"))}function GA(e){let t=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],n={scopes:o},r=d=>{if(!o.includes(d))throw new pn("unsupported_scope",oy("unsupported_scope"))},a=async(d,c)=>{r(d);try{return await c()}catch(u){throw HI(u)}},i=d=>{let c=!1;return{conversationId:d.session.conversationId??"",conversationRevision:d.session.conversationRevision??"",async commit(){c||(c=!0,d.commit(),await e.onActivationCommitted(d.session))},discard(){c||(c=!0,d.discard())}}};return{capabilities:n,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(d){return t().subscribeHistoryIdentityStatus(d)},subscribeAvailability(d){return t().subscribeHistoryAvailability(d)},async list(d){return a(d.context.scope,async()=>{let c=await t().listConversations({...d.cursor?{cursor:d.cursor}:{},...d.limit!==void 0?{limit:d.limit}:{},...d.targetId?{targetId:d.targetId}:{},scope:d.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(d,c){return a(c.context.scope,async()=>{let u=await t().getConversation(d,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),p=_C(u.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:u.summary,messages:Dl([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(d,c){return a(c.context.scope,async()=>i(await t().prepareConversationSession(d)))},async prepareStartNew(d){return a(d.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(d,c){await a(c.context.scope,()=>t().deleteConversation(d,{scope:c.context.scope}))},async deleteAll(d){return a(d.context.scope,()=>t().deleteAllConversations({...d.targetId!==void 0?{targetId:d.targetId}:{},scope:d.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var WI=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],XA={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function ny(e){if(!e)return XA;let t={...XA};for(let o of WI){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var BI="button:not([disabled])";function rp(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,o=Math.random().toString(36).slice(2,8),n=`persona-history-confirm-title-${o}`,r=`persona-history-confirm-desc-${o}`,a=Q("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=Q("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),d=Q("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},Q("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:n},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Q("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},a,i));for(let u of[a,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";a.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",a.style.background="transparent",a.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=Q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},d);return new Promise(u=>{let p=!1,m=y=>{p||(p=!0,c.removeEventListener("keydown",h,!0),c.remove(),t?.focus(),u(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let x=Array.from(d.querySelectorAll(BI));if(x.length===0)return;let C=x[0],E=x[x.length-1],A=document.activeElement;y.shiftKey&&(A===C||!d.contains(A))?(y.preventDefault(),E.focus()):!y.shiftKey&&A===E&&(y.preventDefault(),C.focus())}c.addEventListener("keydown",h,!0),c.addEventListener("pointerdown",y=>{y.target===c&&m(!1)}),a.addEventListener("click",()=>m(!1)),i.addEventListener("click",()=>m(!0)),e.host.appendChild(c),a.focus()})}var Mi=no(Kc(),1);function DI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function OI(e,t){if(!DI(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function sp(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e;try{let r=(0,Mi.parse)(o,Mi.STR|Mi.OBJ),a=OI(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function QA(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ap(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=Mn.get(e.component);if(!a){if($h.includes(e.component)){Zu().catch(()=>{});let d=I("div","persona-w-full");return d.setAttribute("data-persona-artifact-pending","true"),d}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:n,config:o,updateProps:d=>{r&&r(d)}};try{return a(e.props,i)}catch(d){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,d),null}}function YA(){let e=sp();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function JA(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function dd(e){let t=JA(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function ip(e){let t=JA(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let n=o;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var _I=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function lp(e){let{onSubmit:t,onDismiss:o,title:n="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,ratingLabels:u=_I}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,y.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let T=1;T<=5;T++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${T} star${T>1?"s":""}: ${u[T-1]}`),B.title=u[T-1],B.dataset.rating=String(T),B.innerHTML=`
|
|
42
|
-
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
43
|
-
<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>
|
|
44
|
-
</svg>
|
|
45
|
-
`,B.addEventListener("click",()=>{m=T,A.forEach((_,X)=>{let $=X<T;_.classList.toggle("selected",$),_.setAttribute("aria-checked",X===T-1?"true":"false")})}),A.push(B),E.appendChild(B)}h.appendChild(E);let M=null;if(c){let T=document.createElement("div");T.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),T.appendChild(M),h.appendChild(T)}let L=document.createElement("div");L.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=d,b.addEventListener("click",()=>{o?.(),p.remove()});let S=document.createElement("button");return S.type="button",S.className="persona-feedback-btn persona-feedback-btn-submit",S.textContent=i,S.addEventListener("click",async()=>{if(m===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let T=M?.value.trim()||void 0;await t(m,T),p.remove()}catch(T){S.disabled=!1,S.textContent=i,console.error("[CSAT Feedback] Failed to submit:",T)}}),L.appendChild(b),L.appendChild(S),h.appendChild(L),p.appendChild(h),p}function dp(e){let{onSubmit:t,onDismiss:o,title:n="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let h=null,y=document.createElement("div");y.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,x.appendChild(C);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,x.appendChild(E),y.appendChild(x);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=u;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,M.appendChild(L),M.appendChild(b);let S=document.createElement("div");S.className="persona-feedback-numbers";let T=[];for(let k=0;k<=10;k++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-number-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`Rating ${k} out of 10`),H.textContent=String(k),H.dataset.rating=String(k),k<=6?H.classList.add("persona-feedback-detractor"):k<=8?H.classList.add("persona-feedback-passive"):H.classList.add("persona-feedback-promoter"),H.addEventListener("click",()=>{h=k,T.forEach((F,W)=>{F.classList.toggle("selected",W===k),F.setAttribute("aria-checked",W===k?"true":"false")})}),T.push(H),S.appendChild(H)}A.appendChild(M),A.appendChild(S),y.appendChild(A);let B=null;if(c){let k=document.createElement("div");k.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"),k.appendChild(B),y.appendChild(k)}let _=document.createElement("div");_.className="persona-feedback-actions";let X=document.createElement("button");X.type="button",X.className="persona-feedback-btn persona-feedback-btn-skip",X.textContent=d,X.addEventListener("click",()=>{o?.(),m.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=i,$.addEventListener("click",async()=>{if(h===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let k=B?.value.trim()||void 0;await t(h,k),m.remove()}catch(k){$.disabled=!1,$.textContent=i,console.error("[NPS Feedback] Failed to submit:",k)}}),_.appendChild(X),_.appendChild($),y.appendChild(_),m.appendChild(y),m}var Ti="persona-chat-history",UI=30*1e3,qI=641,Ei="data-persona-composer-reason",VI={"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 $I(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let n of o){if(n.kind!=="file"||!n.type.startsWith("image/"))continue;let r=n.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=VI[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith("image/")&&t.push(n);return t}function cp(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function jI(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function zI(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var ry=e=>!e||typeof e!="object"?{}:{...e},ZA=e=>e.map(t=>({...t,streaming:!1})),eM=(e,t,o)=>{let n=e?.markdown?Tl(e.markdown):null,r=Vc(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,i=d=>{let c=d.text??"",u=d.message.rawContent??null;if(t){let h=t.process({text:c,raw:u??c,message:d.message,streaming:d.streaming});h!==null&&(c=h.text,h.persist||(d.message.__skipPersist=!0),h.resubmit&&!d.streaming&&o&&o())}let p=Un()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...d,text:c,raw:u??d.text??""});m=r?r(h):h}else if(n){let h=d.streaming?jx(c):c,y=n(h);m=r&&p?r(y):y}else m=hr(c);return m};return d=>{try{return i(d)}catch(c){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),hr(d.text??"")}}};function tM(e){let t=I("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",n=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,i=ae(o,n,r,a);if(i&&t.appendChild(i),e?.label){let d=I("span","persona-drop-overlay-label");d.textContent=e.label,t.appendChild(d)}return t}var KI=(e,t)=>{let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];o[n]=a?{...a,...r}:r}return o},GI=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:KI(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),up=(e,t,o)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=Ya(t),r=new Set,a=new Set,i=Rx((s,l)=>{_t.delete(s);let f=Array.from(he.querySelectorAll("[data-message-id]")).find(g=>g.dataset.messageId===s);f&&(l==="tool"?Fh(s,f,r,n):Dh(s,f,a))}),d=new Map,c=()=>{fS({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};c();let u=n.features;n=sd(n);let p=ad.getForInstance(n.plugins),m=bw(e),h=[],y=!1,x=mA(()=>n),C=null,E=null,A=null,M=!1,L=null,b=s=>{C=s,s.initApprovalUi({webMcpToolTitle:$c});let l=s.createBuiltInApprovalPlugin(d);E=l.plugin,A=l.teardown},S=()=>{if(C)return C;let s=CA();return s?(b(s),s):(xA().then(l=>{M||C||(b(l),L?.())}).catch(()=>{}),null)},T=!1,B=!1,_=null,X=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=DA();if(v){v.enhanceWithForms(s,l,f,g);return}BA().then(()=>{T||B||!_||(B=!0,_())}).catch(()=>{})};n.components&&Mn.registerAll(n.components);let $=NA(),H=n.persistState===!1?null:n.storageAdapter??np(),F=!!n.clientToken&&typeof n.reconnectStream!="function",W={},oe=null,V,de=new Promise(s=>{V=s}),ce,ge=!1,Pe=s=>{if(n.onStateLoaded)try{let l=n.onStateLoaded(s);if(l&&typeof l=="object"&&"state"in l){let{state:f,open:g}=l;return g&&(ge=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(H?.load)try{let s=H.load();if(s&&typeof s.then=="function")oe=s.then(l=>Pe(l??{messages:[],metadata:{}}));else{let f=Pe(s??{messages:[],metadata:{}});f.metadata&&(W=ry(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),ce=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=Pe({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}oe||V();let Ae=()=>W,ve=s=>{W=s({...W})??{},Ea()},Gt=n.actionParsers&&n.actionParsers.length?n.actionParsers:[id],Bt=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ma.message,ma.messageAndClick],Me=ld({parsers:Gt,handlers:Bt,getSessionMetadata:Ae,updateSessionMetadata:ve,emit:$.emit,documentRef:typeof document<"u"?document:null});Me.syncFromMetadata();let N=n.launcher?.enabled??!0,Oe=n.launcher?.autoExpand??!1,Ve=n.autoFocusInput??!1,Mo=Oe,uo=N,Xt=n.layout?.header?.layout,_o=!1,De=()=>ls(n),Qe=()=>N||De(),ke=De()?!1:N?Oe:!0,Gn=!1,j=null,P=()=>{Gn=!0,j&&clearTimeout(j),j=setTimeout(()=>{Gn&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Gn=!1)},1e4)},U=eM(n,Me,P),G=n.features?.showReasoning??!0,Z=n.features?.showToolCalls??!0,J=n.features?.showEventStreamToggle??!1,pe=n.features?.scrollToBottom??{},xe=n.features?.scrollBehavior??{},Ce=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",Dt=`${Ce()}event-stream`,Ze=null,$e=n.features?.eventStream?.maxEvents??2e3,pt=null,Qt=null,Et=null,fo=!1,ft=null,fn=!1,Tr=null,gp=0,by=(s,l)=>{pt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},hp=(s,l)=>{Qt?.processEvent(s,l),pt?by(s,l):Et&&(Et.length>=$e&&Et.shift(),Et.push({type:s,payload:l}))},ud=()=>{pt||!J||(Et??(Et=[]),qh().then(s=>{if(fo||pt||!J)return;Ze=new s.EventStreamStore(Dt),pt=new s.EventStreamBuffer($e,Ze),Qt=Qt??new s.ThroughputTracker,Ze.open().then(()=>pt?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=Et??[];Et=null;for(let f of l)Qt?.processEvent(f.type,f.payload),by(f.type,f.payload)}).catch(()=>{}))};J&&ud();let Pt=!1,Ft=null,yp=()=>{},Xn=()=>{},vy=()=>{},xy=()=>{},bp=()=>{},wM=()=>fn||Pt&&Ft==="panel",ga={onCopy:s=>{$.emit("message:copy",s),R?.isClientTokenMode()&&R.submitMessageFeedback(s.id,"copy").catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",l)}),n.messageActions?.onCopy?.(s)},onFeedback:s=>{$.emit("message:feedback",s),R?.isClientTokenMode()&&R.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},MR=n.statusIndicator??{},vp=(s,l=n.statusIndicator??{})=>s==="idle"?l.idleText??Wt.idle:s==="connecting"?l.connectingText??Wt.connecting:s==="connected"?l.connectedText??Wt.connected:s==="error"?l.errorText??Wt.error:s==="paused"?l.pausedText??Wt.paused:s==="resuming"?l.resumingText??Wt.resuming:Wt[s];function Pi(s,l,f,g){if(!De()&&(f.mode==="transient"||s.classList.contains("persona-mb-2"))&&(rg(s,To,f),Qs(s,f,g)),!s.hasAttribute(Ei))if(g==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=l,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=l}let No=fA({config:n,showClose:Qe()}),{wrapper:Ge,panel:be,pillRoot:Yt}=No.shell,_e=No.panelElements,{container:le,body:te,messagesWrapper:he,starterSuggestions:xp,transcriptSuggestions:ki,suggestions:Er,textarea:ie,sendButton:Se,composerForm:To,statusText:Ye,welcomeHost:Jt,welcomeIconHolder:AM,greetingHost:Fo,introKicker:MM,introTitle:TM,introSubtitle:EM,closeButton:qe,iconHolder:kt,headerTitle:Pr,headerSubtitle:cs,header:we,footer:Le,actionsRow:PM}=_e,Cp=_e.leftActions,pd=_e.rightActions,Tn=_e.sendButtonWrapper,Cy=_e.setSendButtonMode,re=_e.micButton,Uo=_e.micButtonWrapper,At=_e.attachmentButton,Eo=_e.attachmentButtonWrapper,xt=_e.attachmentInput,Po=_e.attachmentPreviewsContainer;le.classList.add("persona-relative"),te.classList.add("persona-relative");let kM=12,Li=()=>pe.label??"",LM=()=>pe.iconName??"arrow-down",IM=()=>pe.enabled!==!1,qo=()=>xe.mode??"anchor-top",kr=()=>qo()==="follow"||qo()==="anchor-top"&&Ui,Ii=()=>xe.anchorTopOffset??16,RM=()=>xe.restorePosition??"bottom",Sy=()=>xe.pauseOnInteraction===!0,wy=()=>xe.showActivityWhilePinned!==!1,Ay=()=>xe.announce===!0,Sp=()=>xe.scrollbar??"on-scroll",Ut=I("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");Ut.type="button",Ut.style.display="none",Ut.setAttribute("data-persona-scroll-to-bottom","true");let Ri=I("span","persona-flex persona-items-center"),wp=I("span",""),us=I("span","");us.setAttribute("data-persona-scroll-to-bottom-count",""),us.style.display="none",Ut.append(Ri,wp,us),le.appendChild(Ut);let Yo=I("div","persona-stream-anchor-spacer");Yo.setAttribute("aria-hidden","true"),Yo.setAttribute("data-persona-anchor-spacer",""),Yo.style.flexShrink="0",Yo.style.pointerEvents="none",Yo.style.height="0px",Yo.style.display="none",te.appendChild(Yo);let Qn=I("div","persona-sr-only");Qn.setAttribute("aria-live","polite"),Qn.setAttribute("aria-atomic","true"),Qn.setAttribute("role","status"),Qn.setAttribute("data-persona-live-region",""),Object.assign(Qn.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"}),le.appendChild(Qn);let Hi=null,fd=null,md=s=>{!Ay()||!s||(fd=s,Hi===null&&(Hi=setTimeout(()=>{Hi=null,fd&&Ay()&&(Qn.textContent=fd),fd=null},400)))},Wi=()=>{let s=e.ownerDocument.defaultView??window;return(n.launcher?.mobileFullscreen??!0)&&s.innerWidth<=(n.launcher?.mobileBreakpoint??640)&&(N||yt(n))||n.launcher?.fullHeight===!0&&!n.launcher.sidebarMode&&!yt(n)},ps=()=>xi(n,Wi()),gd="empty",hd=0,Ap=()=>hd||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,fs=()=>{let l=Le.style.display==="none"?0:Le.offsetHeight;Ut.style.bottom=`${l+Ap()+kM}px`};fs();let Mp=()=>{xa||(Le.style.marginBottom=hd>0?`${hd}px`:"")},yd=()=>{let s=rh(n,De()),l=ps();e.setAttribute("data-persona-welcome-fullscreen",String(Wi())),e.setAttribute("data-persona-welcome-layout",l.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",n.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom");let g=Le.style.display==="none"?0:Le.offsetHeight,v=l.anchor==="center"&&gd==="empty"?jl(l.anchorComposerTop)??jl("44%"):null,w=v!==null&&l.layout==="centered"&&n.welcome?.anchor===void 0&&n.welcome?.anchorComposerTop===void 0,O=w?getComputedStyle(te):null,z=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,q=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,K=Math.max(0,(parseFloat(O?.paddingBottom??"")||0)-(s==="overlay"?z+q:0)),Y=w?te.getBoundingClientRect().top-le.getBoundingClientRect().top:0,se=!w||Jt.hidden?0:(Jt.querySelector("[data-persona-welcome-plugin]")??Jt).offsetHeight,ue=v===null||De()?0:w?Math.max(0,Math.round((le.clientHeight-Y-se-K-g)/2)):gw({columnHeight:le.clientHeight,footerHeight:g,fraction:v});e.style.setProperty("--persona-composer-overlay-height",`${g}px`),e.style.setProperty("--persona-composer-lift",`${s==="overlay"?ue:0}px`),hd=s==="block"?ue:0,Mp(),fs()},My=()=>{let s=!!Li();Ut.setAttribute("aria-label",Li()||"Jump to latest"),Ut.title=Li(),Ut.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),Ri.innerHTML="";let l=ae(LM(),"14px","currentColor",2);l?(Ri.appendChild(l),Ri.style.display=""):Ri.style.display="none",wp.textContent=Li(),wp.style.display=s?"":"none"};My();let nt=null,Ot=null,ye=iS(),HM=s=>{try{le.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};ye.subscribe(HM);let En=()=>{ye.setText(ie?.value??"")},ms=()=>{ye.setMentionRefs(Ot?.getMentionRefs()??[])},WM=s=>({id:s.id,name:s.file.name,mimeType:s.file.type,size:s.file.size,status:s.status,progress:s.progress,error:s.error}),Ty=s=>{let l=Object.freeze(s.map(WM));ye.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}ef()};ye.setSelectedModelId(n.composer?.selectedModelId);let Bi=()=>n.composer?.modes??[],ha=()=>RS(Bi(),n.composer?.modeGroups);{let s=Eu(n.composer?.defaultActiveModeIds??[],Bi());s.length&&ye.setActiveModeIds(s)}function Ey(s){if(ye.getState().selectedModelId!==s){ye.setSelectedModelId(s),Lr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function bd(s){ye.setActiveModeIds(s),Yn?.render(s,ha()),ya.forEach(l=>l.repaint()),kn?.resolve(),Vd(),mn()}function Tp(s){bd(HS(ye.getState().activeModeIds,s,Bi(),n.composer?.modeGroups))}let Lr=null,Ep=null,Yn=null,ya=new Map,Ir=null;function Pn(s){ye.setQuote(s),Ir?.render(ye.getState().quote),mn(),bb()}let Py=!1;function Pp(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Py&&n.debug===!0&&(Py=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Rr=null;function ba(s){ye.setPendingSubmission(s),Rr?.render(ye.getState().pendingSubmission),mn()}let BM=s=>{let l=ya.get(s);if(l)return l;let f=DS({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>Bi().filter(g=>g.groupId===s),getActiveIds:()=>ye.getState().activeModeIds,onSelect:g=>Tp(g)});return ya.set(s,f),f},DM=()=>{let s=[],l=ye.getState().activeModeIds,f=new Set;if(Bi().forEach((g,v)=>{if(Tu(g.groupId,n.composer?.modeGroups)){let w=g.groupId;if(f.has(w))return;f.add(w);let O=BM(w);O.action.order=Yg(v),O.action.label=n.composer?.modeGroups?.find(z=>z.id===w)?.label??w,s.push(O.action);return}s.push({id:LS(g.id),kind:"button",placement:"start",order:Yg(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>Tp(g.id)})}),n.composer?.models?.length&&!p.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!Lr||Ep!==g)&&(Ep=g,Lr=PS({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>ye.getState().selectedModelId,onSelect:v=>Ey(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(Lr.action)}return s},kp=null,ky=p.find(s=>s.renderHeader);if(ky?.renderHeader){let s=ky.renderHeader({config:n,defaultRenderer:()=>{let l=Sr({config:n,showClose:Qe()});return aa(le,l,n),l.header},onClose:()=>mt(!1,"user")});if(s){let l=we;l&&(l.replaceWith(s),we=s,No.header.element=s)}}let Ly=()=>{ft&&(te.style.display="none",Le.parentNode?.insertBefore(ft.element,Le),ft.update())},Lp=()=>{if(!pt){ud();return}if(fn=!0,ft?Ly():qh().then(l=>{ft||!fn||!pt||(ft=l.createEventStreamView({buffer:pt,getFullHistory:()=>pt.getAllFromStore(),onClose:()=>va(),config:n,plugins:p,getThroughput:()=>Qt?.getMetric()??{status:"idle"},renderIconByName:ae}),Ly())}).catch(()=>{va()}),st){st.style.boxShadow=`inset 0 0 0 1.5px ${So.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&st.classList.add(f))}let s=()=>{if(!fn)return;let l=Date.now();l-gp>=200&&(ft?.update(),gp=l),Tr=requestAnimationFrame(s)};gp=0,Tr=requestAnimationFrame(s),jt(),$.emit("eventStream:opened",{timestamp:Date.now()})},va=()=>{if(fn){if(fn=!1,ft&&ft.element.remove(),te.style.display="",st){st.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&st.classList.remove(l))}Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),jt(),$.emit("eventStream:closed",{timestamp:Date.now()})}},st=null;if(J){let s=n.features?.eventStream?.classNames,l="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"+(s?.toggleButton?" "+s.toggleButton:"");st=I("button",l),st.style.width="28px",st.style.height="28px",st.style.color=So.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let f=Tt(Ga,"18px","currentColor",1.5);f&&st.appendChild(f);let g=_e.clearChatButtonWrapper,v=_e.closeButtonWrapper,w=g||v;w&&w.parentNode===we?we.insertBefore(st,w):we.appendChild(st),st.addEventListener("click",()=>{fn?va():Lp()})}let Iy=s=>{let l=n.attachments;if(!l?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=I("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(l.allowedTypes??Cr).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},xa=!1,Ry=s=>{let l=p.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=y?R.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>nx(),storage:x(l.id),onSubmit:v=>{!R||R.isStreaming()||hc(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Hn()||xt?.click()},models:f?.models,selectedModelId:ye.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>Ey(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{kp?.()}:void 0})},Hy=Ry(()=>da({config:n}).footer);Hy&&(No.replaceComposer(Hy),Le=No.composer.footer,xa=!0);let et=null,OM=s=>{To=s.form,ie=s.input,Tn=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(Se=s.sendButton),s.micButton&&(re=s.micButton,Uo=s.micButton.parentElement),s.found.status&&(Ye=s.found.status),s.found.suggestions&&(Er=s.found.suggestions),s.attachmentButton&&(At=s.attachmentButton,Eo=s.attachmentButton.parentElement),xt=s.attachmentInput??null,Po=s.attachmentPreviews??null,s.found.actionsRow&&(PM=s.found.actionsRow),Cp=s.found.actionsStart,pd=s.found.actionsEnd};function Ip(){let s=ie;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;yu(s,l),f&&s.setAttribute("aria-label",f),hu(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Nl(s)}),hS(s,gu(n.composer?.maxLines,De()?5:3))}let Wy=s=>{et=dS(s,{debug:n.debug===!0}),et&&OM(et),Ip()};Iy(Le),Wy(Le),En();let Di=as(n,De());Di&&(he.style.maxWidth=Di,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%",Fo.style.maxWidth=Di,Fo.style.marginLeft="auto",Fo.style.marginRight="auto",Fo.style.width="100%",xp.style.maxWidth=Di,ki.style.maxWidth=Di,ki.style.marginLeft="auto",ki.style.marginRight="auto",ki.style.width="100%");let By=()=>{let s=as(n,De());if(!(!s||De()))for(let l of[To,Er,Po,Ye])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};By();let Dy=()=>{!n.attachments?.enabled||!xt||!Po||(nt?nt.remountPreviews(Po):(nt=ta.fromConfig(n.attachments,Ty),nt.setPreviewsContainer(Po)),et?.addListener(xt,"change",s=>{let l=s.target;nt?.handleFileSelect(l.files),l.value=""}),le.querySelector(".persona-attachment-drop-overlay")||le.appendChild(tM(n.attachments.dropOverlay)))};Dy();let _M=()=>Ot?.prefetch(),Oy=()=>{if(!n.contextMentions?.enabled||!ie)return;let s=et?.header??null,l=s?Qg(s):void 0;if(Ot=rw({config:n,textarea:ie,anchor:To??ie,getMessages:()=>R.getMessages(),liveRegionHost:le,chipRow:l}),Ot&&!l){let f=ie;f.parentElement?.insertBefore(Ot.contextRow,f)}};Oy();let kn=null,NM={getState:()=>ye.getState(),getValue:()=>ie?.value??"",setValue:s=>{ie&&(ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),En())},submit:()=>{zS(et?.form??null)},openAttachmentPicker:()=>{Hn()||xt?.click()},toggleVoice:()=>{kp?.()},requestRender:()=>kn?.resolve()},FM=()=>{let s=[];return(Ot?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:jn.mention+g,element:f,managed:!0})}),Eo&&s.push({id:"core:attachment",placement:"start",order:jn.attachment,element:Eo}),Uo&&s.push({id:"core:mic",placement:"end",order:jn.mic,element:Uo}),Tn&&s.push({id:"core:send",placement:"end",order:jn.send,element:Tn}),s},_y=()=>{kn?.destroy(),kn=MS({getBindings:()=>et,collect:()=>({builtIns:FM(),configActions:[...DM(),...n.composer?.actions??[]],plugins:p,contributionContext:{config:n,getState:()=>ye.getState(),requestRender:()=>kn?.resolve()},debug:n.debug===!0}),actionContext:NM,getState:()=>ye.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),kn.resolve()};_y();let Rp=()=>{if(Yn?.destroy(),Yn=null,!ha().length)return;let s=et?.header;s&&(Yn=kS({row:Qg(s),onRemove:l=>Tp(l),initialIds:ye.getState().activeModeIds}),Yn.render(ye.getState().activeModeIds,ha()))};Rp();let Ny=()=>{Ir?.destroy(),Ir=null,Rr?.destroy(),Rr=null;let s=et?.header;s&&(Ir=OS({onDismiss:()=>Pn(void 0)}),s.appendChild(Ir.element),Ir.render(ye.getState().quote),Pp()==="defer-one"&&(Rr=_S({onEdit:()=>fE(),onRemove:()=>ba(void 0)}),s.appendChild(Rr.element),Rr.render(ye.getState().pendingSubmission)))};Ny();let Hp=$S(),UM=()=>{let s=et?.header?.querySelector(Xg);if(s)return s.childElementCount>0;let l=ye.getState();return l.mentionRefs.length>0||Eu(l.activeModeIds,ha()).length>0};function mn(){let s=ye.getState(),l=Hp.observe(jS(ie),s.text);Le.toggleAttribute("data-persona-composer-compact",VS({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:UM(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0}))}function Fy(){n.composer?.layout==="single-row"&&!De()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}Fy(),ye.subscribe(()=>{kn?.sync(),ef(),Ud(),mn(),bb()}),Ud();let Uy=!1,qM=s=>{if(Uy||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(Uy=!0,console.warn(`[persona] layout.slots.${l.join(" and layout.slots.")} ${l.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.`))};(()=>{let s=n.layout?.slots??{};qM(s);let l=g=>{switch(g){case"body-top":return te.querySelector("[data-persona-intro-card]");case"messages":return he;case"footer-top":return Er;case"composer":return To;case"footer-bottom":return Ye;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")we.insertBefore(v,we.firstChild);else if(g==="header-right")we.appendChild(v);else{let w=we.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(v,w.nextSibling):we.appendChild(v)}break;case"body-top":{let w=te.querySelector("[data-persona-intro-card]");w?w.replaceWith(v):te.insertBefore(v,te.firstChild);break}case"body-bottom":te.appendChild(v);break;case"footer-top":Er.replaceWith(v);break;case"footer-bottom":Ye.replaceWith(v);break;default:break}};for(let[g,v]of Object.entries(s))if(v)try{let w=v({config:n,defaultContent:()=>l(g)});w&&f(g,w)}catch(w){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${g}":`,w)}})(),he.addEventListener("click",s=>{let l=s.target;if(!(l instanceof Element))return;let f=l.closest("button[data-persona-copy-tool-detail]");f&&(s.preventDefault(),s.stopPropagation(),yA(f))});let Wp=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let g=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;Or(),La();let w=f.getAttribute("data-bubble-type");if(g.classList.contains("persona-activity-row")){i.manual(v);let O=g.parentElement?.closest("[data-persona-tool-group]");O?.dataset.messageId&&i.manual(O.dataset.messageId)}if(w==="reasoning")a.has(v)?a.delete(v):a.add(v),Dh(v,g,a);else if(w==="tool")r.has(v)?r.delete(v):r.add(v),Fh(v,g,r,n);else if(w==="approval"&&C){let z=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",q=d.get(v)??z;d.set(v,!q),C.updateApprovalDetailsUI(v,g,n,d)}_t.delete(v)};he.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Wp(s))}),he.addEventListener("click",s=>{s.detail===0&&s.target.closest(".persona-activity-row")&&Wp(s)}),he.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),Wp(s))}),he.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=he.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),w=xw(v);!w||w===v||(l.setData("text/plain",w),s.preventDefault())});let Bp=new Map,qy=null,Vy="idle",VM={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},$M=(s,l)=>{let{icon:f,label:g}=VM[l];s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",l==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",l!=="idle"),s.classList.toggle("persona-message-action-loading",l==="loading");let v=ae(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},$y=()=>{he.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;$M(l,g&&g===qy?Vy:"idle")})};he.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest("[data-actions-for]");if(!g)return;let v=g.getAttribute("data-actions-for");if(!v)return;let w=f.getAttribute("data-action");if(w==="copy"){let z=R.getMessages().find(q=>q.id===v);if(z&&ga.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{f.classList.add("persona-message-action-success");let K=Tt(Xa,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let Y=Tt(Qa,14,"currentColor",2);Y&&(f.innerHTML="",f.appendChild(Y))},2e3)}).catch(K=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",K)}),ga.onCopy(z)}}else if(w==="read-aloud")R.toggleReadAloud(v);else if(w==="upvote"||w==="downvote"){let z=(Bp.get(v)??null)===w,q=w==="upvote"?"thumbs-up":"thumbs-down";if(z){Bp.delete(v),f.classList.remove("persona-message-action-active");let K=ae(q,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K))}else{let K=w==="upvote"?"downvote":"upvote",Y=g.querySelector(`[data-action="${K}"]`);if(Y){Y.classList.remove("persona-message-action-active");let tt=ae(K==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(Y.innerHTML="",Y.appendChild(tt))}Bp.set(v,w),f.classList.add("persona-message-action-active");let se=ae(q,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(se)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Ue=R.getMessages().find(rt=>rt.id===v);Ue&&ga.onFeedback&&ga.onFeedback({type:w,messageId:Ue.id,message:Ue})}}else if(w==="regenerate")vd?.regenerate(v);else if(w==="edit")vd?.edit(v);else if(w==="quote")vd?.quote(v);else if(w?.startsWith(Gu)){let O=w.slice(Gu.length),z=n.messageActions?.custom?.find(K=>K.id===O),q=R.getMessages().find(K=>K.id===v);if(!z||!q)return;try{z.onSelect(q)}catch(K){console.error(`[AgentWidget] messageActions.custom "${O}" onSelect failed:`,K)}}});let vd=null;he.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest(".persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let w=f.getAttribute("data-approval-action");if(!w)return;let O=w==="approve"?"approved":"denied",q=R.getMessages().find(Y=>Y.id===v);if(!q?.approval)return;let K=g.querySelector("[data-approval-buttons]");K&&K.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),q.approval.toolType==="webmcp"?R.resolveWebMcpApproval(v,O):R.resolveApproval(q.approval,O)});let je=null,jy=!1,Oi=null,gs=()=>{},_i="none",xd=null,Jo={artifacts:[],selectedId:null},Jn=!1,gn=!1,Ni=!1,Ca=!1,zy=()=>Ca||Jo.artifacts.some(s=>qn(n.features?.artifacts,s)==="panel"),Cd=()=>Jo.artifacts.length>0&&!Jn&&zy(),it={current:null},Dp=(s,l)=>{let f=R.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",w=f?.file,O=f?.artifactType??"markdown";if(!g){let K=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(K){let se=R.getMessages().find(ue=>ue.id===K);if(se?.rawContent)try{let ue=JSON.parse(se.rawContent);g=ue?.props?.markdown,v=ue?.props?.title||v,ue?.props?.file&&typeof ue.props.file=="object"&&(w=ue.props.file),!f&&typeof ue?.props?.artifactType=="string"&&(O=ue.props.artifactType)}catch{}}}return{markdown:g,title:v,file:w,artifactType:O}};he.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-download-artifact");if(!g||n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:g})===!0)return;let{markdown:w,title:O,file:z}=Dp(f,g);if(!w)return;let q=wr();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:O,markdown:w,file:z}))}),he.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-artifact-custom-action");if(!g)return;let v=f.closest("[data-artifact-inline]"),w=v?null:f.closest("[data-open-artifact]"),O=v?v.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,q=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(rt=>rt.id===g);if(!q)return;let{markdown:K,title:Y,file:se,artifactType:ue}=Dp(f,O??""),Ue={artifactId:O,title:Y,artifactType:ue,markdown:K,file:se};try{Promise.resolve(q.onClick(Ue)).catch(()=>{})}catch{}}),he.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-copy-artifact");if(!g)return;let v=R.getArtifactById(g),w=wr();if(!w)return;let O="";if(v)O=w.artifactCopyText(v);else{let{markdown:z,file:q,artifactType:K}=Dp(f,g);K==="markdown"&&(O=w.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}O&&navigator.clipboard.writeText(O).then(()=>{let z=Tt(Xa,16,"currentColor",2);z&&(f.replaceChildren(z),setTimeout(()=>{let q=Tt(Qa,16,"currentColor",2);q&&f.replaceChildren(q)},1500))}).catch(()=>{})}),he.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-expand-artifact-inline");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(Jn=!1,Ca=!0,gn=!0,Ni=!0,R.selectArtifact(g),hn())}),he.addEventListener("click",s=>{let l=s.target;if(l.closest("[data-download-artifact]")||l.closest("[data-artifact-custom-action]"))return;let f=l.closest("[data-open-artifact]");if(!f)return;let g=f.getAttribute("data-open-artifact");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(s.preventDefault(),s.stopPropagation(),Jn=!1,Ca=!0,R.selectArtifact(g),hn())}),he.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let l=s.target;!l.hasAttribute("data-open-artifact")&&!l.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),l.click())});let Sa=_e.composerOverlay,wa=(s,l,f)=>{let g=l.trim();if(!g||!it.current)return;let v=s.getAttribute("data-tool-call-id")??"",w=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:g,answers:f.structured,values:f.values??(f.source==="multi"?g.split(", "):[g]),isFreeText:w,source:f.source},bubbles:!0,composed:!0})),os(Sa,v);let O=it.current.getMessages().find(z=>z.toolCall?.id===v);O?.agentMetadata?.awaitingLocalTool?it.current.resolveAskUserQuestion(O,f.structured??g):it.current.sendMessage(g)},hs=s=>{let l=it.current;if(!l)return;let f=s.getAttribute("data-tool-call-id")??"",g=l.getMessages().find(v=>v.toolCall?.id===f);g&&l.persistAskUserQuestionProgress(g,{answers:Xc(s,g),currentIndex:cn(s)})},Ky=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),Op=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=cn(s),f=ni(s);if(l>=f-1)return;let g=it.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(Qc(s,g,n,l+1),hs(s))};Sa.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let w=g.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),os(Sa,w);let O=it.current?.getMessages().find(z=>z.toolCall?.id===w);O?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(O),it.current?.resolveAskUserQuestion(O,"(dismissed)"));return}if(v==="pick"){let w=f.getAttribute("data-option-label");if(!w)return;let O=g.getAttribute("data-multi-select")==="true",z=ts(g);if(z&&O){let q=Ys(g)[cn(g)],K=new Set(Array.isArray(q)?q:[]);K.has(w)?K.delete(w):K.add(w),ns(g,Array.from(K)),hs(g);return}if(z){ns(g,w),hs(g),Op(g);return}if(O){let q=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",q?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!q);let K=g.querySelector('[data-ask-user-action="submit-multi"]');K&&(K.disabled=bg(g).length===0);return}wa(g,w,{source:"pick",values:[w]});return}if(v==="submit-multi"){let w=bg(g);if(w.length===0)return;wa(g,w.join(", "),{source:"multi",values:w});return}if(v==="open-free-text"){let w=g.querySelector('[data-ask-free-text-row="true"]');w&&(w.classList.remove("persona-hidden"),w.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let O=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!O.trim())return;if(ts(g)){ns(g,O.trim()),hs(g),Op(g);return}wa(g,O,{source:"free-text"});return}if(v==="next"||v==="back"){if(!it.current)return;let w=g.getAttribute("data-tool-call-id")??"",O=it.current.getMessages().find(se=>se.toolCall?.id===w);if(!O)return;let q=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let se=Ys(g)[cn(g)];(typeof se!="string"||se!==q)&&ns(g,q)}let K=v==="next"?1:-1,Y=cn(g)+K;Qc(g,O,n,Y),hs(g);return}if(v==="submit-all"){if(!it.current)return;let w=g.getAttribute("data-tool-call-id")??"",O=it.current.getMessages().find(se=>se.toolCall?.id===w);if(!O)return;let q=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&ns(g,q);let K=Xc(g,O);it.current.persistAskUserQuestionProgress(O,{answers:K,currentIndex:cn(g)});let Y=Ky(K);wa(g,Y||"(submitted)",{source:"submit-all",structured:K});return}if(v==="skip"){if(!it.current)return;let w=g.getAttribute("data-tool-call-id")??"",O=it.current.getMessages().find(ue=>ue.toolCall?.id===w);if(!O)return;let z=ts(g),q=cn(g),K=ni(g),Y=q>=K-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),os(Sa,w),O.agentMetadata?.awaitingLocalTool&&(it.current.markAskUserQuestionResolved(O),it.current.resolveAskUserQuestion(O,"(dismissed)"));return}ns(g,"");let se=g.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),Y){let ue=Xc(g,O),Ue=Ky(ue);wa(g,Ue||"(skipped)",{source:"submit-all",structured:ue});return}Qc(g,O,n,q+1),hs(g);return}}),Sa.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;s.preventDefault();let v=f.value;if(v.trim()){if(ts(g)){ns(g,v.trim()),hs(g),Op(g);return}wa(g,v,{source:"free-text"})}});let Gy=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let l=s.target;if(l?.tagName==="INPUT"||l?.tagName==="TEXTAREA"||l?.isContentEditable)return;let f=Sa.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let g=Number(s.key),w=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[g-1];w&&(s.preventDefault(),w.click())};document.addEventListener("keydown",Gy);let Ln=null,St=null,Fi=null,Sd=null,wd=()=>{},Xy=!1,Ad="",Md="";function _p(){Sd?.(),Sd=null}let jM=()=>{let s=Oa&&Ds?.isConnected?Ds:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},Qy=()=>{if(!Ln||!St)return;let s=e.classList.contains("persona-artifact-welded-split"),l=e.ownerDocument.defaultView??window,f=l.innerWidth<=640;if(!s||e.classList.contains("persona-artifact-narrow-host")||f){St.style.removeProperty("position"),St.style.removeProperty("left"),St.style.removeProperty("top"),St.style.removeProperty("bottom"),St.style.removeProperty("width"),St.style.removeProperty("z-index");return}let g=Ln.firstElementChild;if(!g||g===St)return;let v=10;St.style.position="absolute",St.style.top="0",St.style.bottom="0",St.style.width=`${v}px`,St.style.zIndex="5";let w=Yh(Ln,l),O=g.offsetWidth+w/2-v/2;St.style.left=`${Math.max(0,O)}px`},Td=()=>{},Yy=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:N||yt(n)},Ed=()=>!Ao(n)||!Cd()||e.classList.contains("persona-artifact-narrow-host")||Yy()||(e.ownerDocument.defaultView??window).innerWidth<qI?"none":Kh(n)?"detached":"welded",hn=()=>{if(!je||!Ao(n))return;nd(e,n),rd(e,n),Td();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=be.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=Cd();je.setVisible(f),je.update(Jo),Jn?(je.setMobileOpen(!1),je.element.classList.add("persona-hidden"),je.backdrop?.classList.add("persona-hidden"),gn=!1,Ni=!1):Jo.artifacts.length>0&&zy()?(je.element.classList.remove("persona-hidden"),je.setMobileOpen(!0)):(je.setMobileOpen(!1),je.element.classList.add("persona-hidden"),je.backdrop?.classList.add("persona-hidden"),gn=!1,Ni=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if(je.setExpandToggleVisible(g),je.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),je.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),je.setCustomActions(n.features?.artifacts?.toolbarActions??[]),je.setTabFade(n.features?.artifacts?.layout?.tabFade),je.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!Ni&&(gn=!1),gn!==Xy){let w=je.element;gn?(Ad=w.style.width,Md=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(Ad&&(w.style.width=Ad),Md&&(w.style.maxWidth=Md),Ad="",Md=""),Xy=gn}e.classList.toggle("persona-artifact-expanded",gn),je.setExpanded(gn);let v=Ed();v!==_i&&(_i=v,gs()),wd()};if(Ao(n)){be.style.position="relative";let s=I("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),l=I("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(le),Ln=l,l.appendChild(s),be.appendChild(l);let f=v=>{jy||je||(je=v.createArtifactPane(n,{onSelect:w=>it.current?.selectArtifact(w),onDismiss:()=>{Jn=!0,hn()},onToggleExpand:()=>{let w=!gn,O=Jo.selectedId??Jo.artifacts[Jo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:O,expanded:w})!==!0&&(gn=w,w||(Ni=!1),hn())}}),je.element.classList.add("persona-hidden"),l.appendChild(je.element),je.backdrop&&be.appendChild(je.backdrop),wd(),hn())},g=wr();g?f(g):(jh(()=>{let v=wr();v&&f(v)}),Zu().catch(()=>{})),wd=()=>{if(!Ln||!je)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){Fi?.(),Fi=null,_p(),St&&(St.remove(),St=null),je.element.style.removeProperty("width"),je.element.style.removeProperty("maxWidth");return}if(!St){let w=I("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");w.setAttribute("role","separator"),w.setAttribute("aria-orientation","vertical"),w.setAttribute("aria-label","Resize artifacts panel"),w.tabIndex=0;let O=e.ownerDocument,z=O.defaultView??window,q=K=>{if(!je||K.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;K.preventDefault(),_p();let Y=K.clientX,se=je.element.getBoundingClientRect().width,ue=n.features?.artifacts?.layout,Ue=tt=>{let Ho=Ln.getBoundingClientRect().width,Ct=e.classList.contains("persona-artifact-welded-split"),Mt=Yh(Ln,z),ho=Ct?0:w.getBoundingClientRect().width||6,Rt=se-(tt.clientX-Y),lt=HA(Rt,Ho,Mt,ho,ue?.resizableMinWidth,ue?.resizableMaxWidth,jM());je.element.style.width=`${lt}px`,je.element.style.maxWidth="none",Qy()},rt=()=>{O.removeEventListener("pointermove",Ue),O.removeEventListener("pointerup",rt),O.removeEventListener("pointercancel",rt),Sd=null;try{w.releasePointerCapture(K.pointerId)}catch{}};Sd=rt,O.addEventListener("pointermove",Ue),O.addEventListener("pointerup",rt),O.addEventListener("pointercancel",rt);try{w.setPointerCapture(K.pointerId)}catch{}};w.addEventListener("pointerdown",q),St=w,Ln.insertBefore(w,je.element),Fi=()=>{w.removeEventListener("pointerdown",q)}}if(St){let w=Cd();St.classList.toggle("persona-hidden",!w),Qy()}},Td=()=>{if(!N||!je||(n.launcher?.sidebarMode??!1)||yt(n)&&Oo(n).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,O=n.launcher?.mobileFullscreen??!0,z=n.launcher?.mobileBreakpoint??640;if(O&&w.innerWidth<=z||!EA(n,N))return;let q=ua(n).width,K=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Cd()?(be.style.width=K,be.style.maxWidth=K):(be.style.width=q,be.style.maxWidth=q)},typeof ResizeObserver<"u"&&(Oi=new ResizeObserver(()=>{hn()}),Oi.observe(be))}else be.appendChild(le);De()&&Yt&&(_e.peekBanner&&Yt.appendChild(_e.peekBanner),Yt.appendChild(Le)),e.appendChild(Ge),Yt&&e.appendChild(Yt);let Np=()=>{let s=Yy()||De()&&n.launcher?.composerBar?.expandedSize==="fullscreen"||n.launcher?.fullHeight===!0&&!n.launcher?.sidebarMode&&!yt(n);if(he.style.gap=s?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",he.style.setProperty("--persona-transcript-gap",he.style.gap),De()){be.style.width="100%",be.style.maxWidth="100%";let Ee=n.launcher?.composerBar??{},Ne=Ge.dataset.state==="expanded",We=Ee.expandedSize??"anchored";if(!(Ne&&We!=="fullscreen")){le.style.background="",le.style.border="",le.style.borderRadius="",le.style.overflow="",le.style.boxShadow="";return}let Vt=n.theme?.components?.panel,Wo=An(n),ur=(pr,Vs)=>pr==null||pr===""?Vs:ao(Wo,pr)??pr,am="1px solid var(--persona-border)",qs="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",im="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";le.style.background="var(--persona-surface, #ffffff)",le.style.border=ur(Vt?.border,am),le.style.borderRadius=ur(Vt?.borderRadius,im),le.style.boxShadow=ur(Vt?.shadow,qs),le.style.overflow="hidden";return}let l=yt(n),f=n.launcher?.sidebarMode??!1,g=l||f||(n.launcher?.fullHeight??!1),v=n.launcher?.enabled===!1,w=n.launcher?.detachedPanel===!0,O=n.theme?.components?.panel,z=n.darkTheme?.components?.panel,q=oa(n)==="dark"?Sn(O??{},z??{}):O,K=An(n),Y=(Ee,Ne)=>Ee==null||Ee===""?Ne:ao(K,Ee)??Ee,se=e.ownerDocument.defaultView??window,ue=n.launcher?.mobileFullscreen??!0,Ue=n.launcher?.mobileBreakpoint??640,rt=se.innerWidth<=Ue,tt=ue&&rt&&N,Ho=l&&ue&&rt,Ct=n.launcher?.position??"bottom-left",Mt=Ct==="bottom-left"||Ct==="top-left",ho=n.launcher?.zIndex??co,Rt=(Ee,Ne,We)=>`var(--persona-components-panel-modes-${Ee}-${Ne}, ${We})`,lt=q?.modes?.floating,On=Y(lt?.border??q?.border,Rt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),_n=Y(lt?.shadow??q?.shadow,Rt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),an=Y(lt?.borderRadius??q?.borderRadius,Rt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),ln=w&&!tt&&!Ho,zr=tt||Ho?"mobile":ln?"floating":l?"docked":f?"sidebar":v?"inline":"floating",Nn=q?.modes?.[zr];ln?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let vn=ln?On:f||tt?"none":On,Kr=ln?_n:tt?"none":f?Mt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":v?"none":_n;l&&!tt&&!ln&&(Kr="none",vn="none");let pl=ln?an:f||tt?"0":an,Us=Y(Nn?.border??q?.border,Rt(zr,"border",vn)),D=Y(Nn?.shadow??q?.shadow,Rt(zr,"shadow",Kr)),Ie=Y(Nn?.borderRadius??q?.borderRadius,Rt(zr,"borderRadius",pl)),Re=Ed(),ne=Re==="detached",dt=Re==="welded";e.classList.toggle("persona-artifact-detached-split",ne),e.classList.toggle("persona-artifact-welded-split",dt);let Nt="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)))))",gt=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Ao(n)&&Kh(n)&&v&&!l;e.classList.toggle("persona-artifact-chat-flush",gt);let Ht=ne||gt?"none":D,zt=ne?On:dt?"none":Us,Te=ne?an:Ie;gt&&(zt="none",Te="0");let ht=Nn?.borderRadius!=null&&Nn.borderRadius!==""||q?.borderRadius!=null&&q.borderRadius!=="",He=gt&&!ht?"0":Ie,Kt=te.scrollTop;e.style.cssText="",Ge.style.cssText="",be.style.cssText="",le.style.cssText="",te.style.cssText="",xa||(Le.style.cssText=""),fn&&(te.style.display="none"),(g||v)&&(e.style.minWidth="0");let dn=()=>{if(Kt<=0)return;(te.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(te.scrollTop===Kt)return;let Ne=te.scrollHeight-te.clientHeight;Ne<=0||(te.scrollTop=Math.min(Kt,Ne))})};if(tt){Ge.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"),Ge.style.cssText=`
|
|
46
|
-
position: fixed !important;
|
|
47
|
-
inset: 0 !important;
|
|
48
|
-
width: 100% !important;
|
|
49
|
-
height: 100% !important;
|
|
50
|
-
max-height: 100% !important;
|
|
51
|
-
margin: 0 !important;
|
|
52
|
-
padding: 0 !important;
|
|
53
|
-
display: flex !important;
|
|
54
|
-
flex-direction: column !important;
|
|
55
|
-
z-index: ${ho} !important;
|
|
56
|
-
background-color: var(--persona-surface, #ffffff) !important;
|
|
57
|
-
`,be.style.cssText=`
|
|
58
|
-
position: relative !important;
|
|
59
|
-
display: flex !important;
|
|
60
|
-
flex-direction: column !important;
|
|
61
|
-
flex: 1 1 0% !important;
|
|
62
|
-
width: 100% !important;
|
|
63
|
-
max-width: 100% !important;
|
|
64
|
-
height: 100% !important;
|
|
65
|
-
min-height: 0 !important;
|
|
66
|
-
margin: 0 !important;
|
|
67
|
-
padding: 0 !important;
|
|
68
|
-
box-shadow: none !important;
|
|
69
|
-
border-radius: 0 !important;
|
|
70
|
-
`,le.style.cssText=`
|
|
71
|
-
display: flex !important;
|
|
72
|
-
flex-direction: column !important;
|
|
73
|
-
flex: 1 1 0% !important;
|
|
74
|
-
width: 100% !important;
|
|
75
|
-
height: 100% !important;
|
|
76
|
-
min-height: 0 !important;
|
|
77
|
-
max-height: 100% !important;
|
|
78
|
-
overflow: hidden !important;
|
|
79
|
-
border-radius: 0 !important;
|
|
80
|
-
border: none !important;
|
|
81
|
-
`,te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",Le.style.flexShrink="0",Mp(),_o=!0,dn();return}let eo=ua(n);if(!f&&!l)v&&g?(be.style.width="100%",be.style.maxWidth="100%"):(be.style.width=eo.width,be.style.maxWidth=eo.maxWidth);else if(l)if(Oo(n).reveal==="emerge"&&!w){let Ne=Oo(n).width;be.style.width=Ne,be.style.maxWidth=Ne}else be.style.width="100%",be.style.maxWidth="100%";if(Td(),be.style.boxShadow=Ht,be.style.borderRadius=He,ne?be.style.border="none":dt&&(be.style.border=Us),le.style.border=zt,le.style.borderRadius=Te,le.style.boxShadow=ne&&!gt?Nt:"",gt&&(le.style.background="transparent",te.style.background="transparent",Le.style.background="transparent",Le.style.borderTop="none"),dt){let Ee=n.features?.artifacts?.layout;xd=Ee?.unifiedSplitOuterRadius?.trim()||Ee?.paneBorderRadius?.trim()||Ie}else xd=null;let ct=Nn?.border!=null||q?.border!=null;if(l&&!tt&&!ln&&!ne&&!dt&&!ct&&(le.style.border="none",Oo(n).side==="right"?le.style.borderLeft="1px solid var(--persona-border)":le.style.borderRight="1px solid var(--persona-border)"),l&&!tt&&dt&&!ct&&(Oo(n).side==="right"?be.style.borderLeft="1px solid var(--persona-border)":be.style.borderRight="1px solid var(--persona-border)"),g&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),Ge.style.display="flex",Ge.style.flexDirection="column",Ge.style.flex="1 1 0%",Ge.style.minHeight="0",Ge.style.maxHeight="100%",Ge.style.height="100%",v&&(Ge.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.height="100%",ne||(be.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.overflow="hidden",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",Le.style.flexShrink="0"),v&&(ln||ne||gt)&&!l&&(gt||(Ge.style.padding="var(--persona-panel-inset)"),Ge.style.background="var(--persona-panel-canvas-bg)"),Ge.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"),!f&&!v&&!l&&(Qo[Ct]??Qo["bottom-right"]).split(" ").forEach(Ne=>Ge.classList.add(Ne)),f){let Ee=fr(n).sidebarWidth?n.launcher?.sidebarWidth??"420px":ao(An(n),"components.panel.width")??"420px";w?Ge.style.cssText=`
|
|
82
|
-
position: fixed !important;
|
|
83
|
-
top: var(--persona-panel-inset) !important;
|
|
84
|
-
bottom: var(--persona-panel-inset) !important;
|
|
85
|
-
width: ${Ee} !important;
|
|
86
|
-
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
87
|
-
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
88
|
-
margin: 0 !important;
|
|
89
|
-
padding: 0 !important;
|
|
90
|
-
display: flex !important;
|
|
91
|
-
flex-direction: column !important;
|
|
92
|
-
z-index: ${ho} !important;
|
|
93
|
-
${Mt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
94
|
-
`:Ge.style.cssText=`
|
|
95
|
-
position: fixed !important;
|
|
96
|
-
top: 0 !important;
|
|
97
|
-
bottom: 0 !important;
|
|
98
|
-
width: ${Ee} !important;
|
|
99
|
-
height: 100vh !important;
|
|
100
|
-
max-height: 100vh !important;
|
|
101
|
-
margin: 0 !important;
|
|
102
|
-
padding: 0 !important;
|
|
103
|
-
display: flex !important;
|
|
104
|
-
flex-direction: column !important;
|
|
105
|
-
z-index: ${ho} !important;
|
|
106
|
-
${Mt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
107
|
-
`,be.style.cssText=`
|
|
108
|
-
position: relative !important;
|
|
109
|
-
display: flex !important;
|
|
110
|
-
flex-direction: column !important;
|
|
111
|
-
flex: 1 1 0% !important;
|
|
112
|
-
width: 100% !important;
|
|
113
|
-
max-width: 100% !important;
|
|
114
|
-
height: 100% !important;
|
|
115
|
-
min-height: 0 !important;
|
|
116
|
-
margin: 0 !important;
|
|
117
|
-
padding: 0 !important;
|
|
118
|
-
box-shadow: ${Ht} !important;
|
|
119
|
-
border-radius: ${He} !important;
|
|
120
|
-
${ne?"border: none !important;":dt?`border: ${Us} !important;`:""}
|
|
121
|
-
`,be.style.setProperty("width","100%","important"),be.style.setProperty("max-width","100%","important"),le.style.cssText=`
|
|
122
|
-
display: flex !important;
|
|
123
|
-
flex-direction: column !important;
|
|
124
|
-
flex: 1 1 0% !important;
|
|
125
|
-
width: 100% !important;
|
|
126
|
-
height: 100% !important;
|
|
127
|
-
min-height: 0 !important;
|
|
128
|
-
max-height: 100% !important;
|
|
129
|
-
overflow: hidden !important;
|
|
130
|
-
border-radius: ${Te} !important;
|
|
131
|
-
border: ${zt} !important;
|
|
132
|
-
${ne&&!gt?`box-shadow: ${Nt} !important;`:""}
|
|
133
|
-
${gt?"background: transparent !important;":""}
|
|
134
|
-
`,xa||(Le.style.cssText=`
|
|
135
|
-
flex-shrink: 0 !important;
|
|
136
|
-
border-top: none !important;
|
|
137
|
-
padding: 8px 16px 12px 16px !important;
|
|
138
|
-
${gt?"background: transparent !important;":""}
|
|
139
|
-
`)}if(!v&&!l){let Ee="max-height: -moz-available !important; max-height: stretch !important;",Ne=f?"":"padding-top: 1.25em !important;",We=f?"":`z-index: ${n.launcher?.zIndex??co} !important;`;Ge.style.cssText+=Ee+Ne+We}Mp(),dn()},Fp=()=>{e.style.setProperty("--persona-content-max-width",as(n,De()))},Jy=!1;function Zy(){n.layout?.topFade&&te.scrollTop>1?te.setAttribute("data-persona-top-fade","true"):te.removeAttribute("data-persona-top-fade")}let Up=()=>{Zy();let s=rh(n,De());De()&&n.composer?.placement&&n.debug===!0&&!Jy&&(Jy=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=ps();e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",gd),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??Du),yd()},eb=()=>{if(De())return;let s=yt(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!N)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,w=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=w)return;let O=ua(n);be.style.height=O.height,be.style.maxHeight=O.maxHeight};Np(),na(e,n),nd(e,n),rd(e,n),Fp(),Up(),gs=()=>{Np(),eb(),na(e,n),nd(e,n),rd(e,n),Fp(),Up(),xd?e.style.setProperty("--persona-artifact-welded-outer-radius",xd):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Xn(),yp()};let fe=[];fe.push(()=>{jy=!0}),fe.push(()=>{h.forEach(s=>s()),m.destroy()}),fe.push(()=>{document.removeEventListener("keydown",Gy)}),fe.push(()=>{Hi!==null&&clearTimeout(Hi)});let In=null,Rn=null;fe.push(()=>{In?.(),In=null,Rn?.(),Rn=null}),Oi&&fe.push(()=>{Oi?.disconnect(),Oi=null}),fe.push(()=>{Fi?.(),Fi=null,_p(),St&&(St.remove(),St=null),je?.element.style.removeProperty("width"),je?.element.style.removeProperty("maxWidth"),je?.destroy()}),J&&fe.push(()=>{fo=!0,Et=null,Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),ft?.destroy(),ft=null,pt?.destroy(),pt=null,Ze=null});let ys=null,tb=()=>{ys&&(ys(),ys=null),n.colorScheme==="auto"&&(ys=fi(()=>{na(e,n)}))};tb(),fe.push(()=>{ys&&(ys(),ys=null)}),fe.push(()=>{M=!0,A?.()}),fe.push(()=>{T=!0});let ob=!1;fe.push(()=>{ob=!0});let qp=(s,l)=>{let f=Xl(s,l);return f||!Bw.includes(s)?f:(_w().then(g=>{if(ob)return;mi(g.wipe),mi(g.glyphCycle);let v=Xl(s,l);v&&Jl(v,e)}).catch(()=>{}),null)},Pd=n.features?.streamAnimation;if(Pd?.type&&Pd.type!=="none"){let s=qp(Pd.type,Pd.plugins);s&&Jl(s,e),fe.push(()=>Dw(e))}let Zn=td(Er),nb=td(xp),rb=td(ki),bs=[Zn,nb,rb];fe.push(()=>{bs.forEach(s=>s.destroy())});let vs=null,R,xs=null,sb=!1,ab=0,ib=null,lb=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),db=s=>{for(let l=s.length-1;l>=0;l--)if(Js(s[l]))return s[l].id??null;return null},cb=!1,zM=()=>{cb||n.debug!==!0||(cb=!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".'))},ub=!1,pb=!1,fb=(s,l)=>{ub||n.debug!==!0||!l.enabled||l.expose||sb||pb&&(R.isStreaming()||s.some(Js)||(ub=!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.")))},Cs=s=>{if(!R)return;let l=s??R.getMessages(),f=se=>{se.render([],R,ie,l)},g=se=>{bs.forEach(ue=>{ue!==se&&f(ue)})};xs&&(lb(l)>ab||db(l)!==ib)&&(xs=null);let v=rs(n);fb(l,v);let w=v.enabled?Jc(l):null,O=xs??w,z=xs?"host":"agent";if(O){let se=n.suggestions?.followUps,ue=se?.placement??(se?"auto":"composer"),rt=(ue==="auto"?De()?"composer":"after-message":ue)==="after-message"?rb:Zn;g(rt),rt.render(O,R,ie,l,n.suggestionChipsConfig,{source:z,surface:"followUp",variant:se?.variant??"chip",behavior:se?.behavior??"send",overflow:se?.overflow??"wrap",maxItems:se?.maxItems??4,config:n,plugins:p,submitPrompt:gc});return}if(l.some(se=>se.role==="user")){bs.forEach(f);return}let q=n.future?.v5Defaults===!0,K=Wi(),Y=n.suggestions?.starters??(q?{}:void 0);if(Y){let se=ds(ps(),l),ue=Y.placement??"auto",Ue=ue==="auto"?se?"welcome":"composer":ue;if(Ue==="welcome"&&!se){zM(),bs.forEach(f);return}let rt=Ue==="welcome"?nb:Zn;g(rt),rt.render(Y.items??n.suggestionChips,R,ie,l,n.suggestionChipsConfig,{surface:"starter",variant:Y.variant??(q&&!K?"chip":"card"),behavior:Y.behavior??"send",overflow:Y.overflow??"wrap",maxItems:Y.maxItems??(q&&!K?3:4),config:n,plugins:p,submitPrompt:gc});return}g(Zn),Zn.render(n.suggestionChips,R,ie,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:n,plugins:p,submitPrompt:gc})},mb=()=>{xs&&(xs=null,Cs())},KM=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){mb();return}let f=R?R.getMessages():[];xs=l,sb=!0,ab=lb(f),ib=db(f),Cs(f)},Vo=!1,_t=ww(),Aa=new Map,Ss=new Map,Hr=new Map,ws=null,Wr=null;function As(){if(!ws)return;let s=ws;ws=null,Wr?.destroy(),Wr=null,_t.delete(s),le.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),R&&Zo(he,R.getMessages(),U)}let Ms=0,GM=Un()!==null,$o=Pw(),jo=0,Br=null,ko=!1,kd=!1,Dr=0,$t=null,Ts=null,Vp=!1,Ma=!1,Es=null,Ui=!0,Ld=!1,Ta=null,Id=!1,Or=()=>{Id=!0,JM()},$p=null,XM=4,er=24,QM=80,YM=1e3,tr=null,gb=()=>{e.setAttribute("data-persona-scrollbar",Sp()),Sp()!=="on-scroll"&&(tr!==null&&clearTimeout(tr),tr=null,te.removeAttribute("data-persona-scrollbar-visible"))},JM=()=>{Sp()==="on-scroll"&&(te.setAttribute("data-persona-scrollbar-visible",""),tr!==null&&clearTimeout(tr),tr=setTimeout(()=>{tr=null,ra(te,er)&&te.removeAttribute("data-persona-scrollbar-visible")},YM))};gb(),fe.push(()=>{tr!==null&&clearTimeout(tr)});let jp=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};mn();let hb=n.voiceRecognition?.autoResume??!1,or=s=>{$.emit("voice:state",{active:Xe.active,source:s,timestamp:Date.now()})},yn=()=>{ve(s=>({...s,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},ZM=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=ry(W.voiceState),l=!!s.active,f=Number(s.timestamp??0);Xe.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<UI&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,vo(n.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Xe.active=R.isVoiceActive(),or("restore"),R.isVoiceActive()&&za()}):bc("restore"))},1e3)},eT=()=>R?ZA(R.getMessages()).filter(s=>!s.__skipPersist):[],Rd=null,yb=(s,l)=>{typeof console<"u"&&console.error(s,l)},Hd=(s,l)=>{let f=()=>{try{let O=s();return!O||typeof O.then!="function"?null:Promise.resolve(O).catch(z=>{yb(l,z)})}catch(O){return yb(l,O),null}},g=Rd,v=g?g.then(()=>f()??void 0):f();if(!v)return;let w=v.finally(()=>{Rd===w&&(Rd=null)});Rd=w};function Ea(s){if(!H?.save)return;let l=s?ZA(s):R?eT():[],f=F&&R?.getResumableHandle();f&&(W={...W,durableResume:{executionId:f.executionId,after:f.lastEventId}});let g={messages:l,metadata:W,artifacts:Jo.artifacts,selectedArtifactId:Jo.selectedId,...Ps?{draft:Ps}:{}};Hd(()=>H.save(g),"[AgentWidget] Failed to persist state:")}let Ps,Wd=()=>!H?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,qi=qS({write:()=>{if(!Wd())return;let s=ye.getState(),l=FS({text:s.text,mentionRefs:s.mentionRefs,contentSegments:$f(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(Ps)&&(Ps=l,Ea())}});function bb(){Wd()&&qi.schedule()}function zp(){qi.flush()}function vb(s){if(!Wd())return;let l=US(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(Ps=s,ie&&!ie.value&&(ie.value=l.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),En()),l.selectedModelId&&(ye.setSelectedModelId(l.selectedModelId),Lr?.repaint()),bd(l.activeModeIds??[]),l.quote&&Pn(l.quote),qi.cancel())}function Bd(){qi.cancel(),Ps&&(Ps=void 0,Wd()&&Ea())}let Pa=null,xb=()=>Ge.querySelector("#persona-scroll-container")||te,ka=()=>{Pa!==null&&(cancelAnimationFrame(Pa),Pa=null),ko=!1},Cb=()=>{Br!==null&&(cancelAnimationFrame(Br),Br=null),kd=!1,ka()},tT=()=>Vo&&Gp()&&(qo()!=="anchor-top"||wy()),Kp=()=>{let s=Li()||"Jump to latest",l=tT();Ut.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Dr>0?(us.textContent=String(Dr),us.style.display="",Ut.setAttribute("aria-label",`${s} (${Dr} new)`)):(us.textContent="",us.style.display="none",Ut.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},Sb=()=>{Dr!==0&&(Dr=0,Kp())},oT=()=>{let s=$t?.spacerHeight??0;return s<=0?ra(te,er):Nd(s)-te.scrollTop-te.clientHeight<=er},Gp=()=>kr()?!$o.isFollowing():!oT(),Xp=()=>!!R&&R.getMessages().length>0,jt=()=>{if(!IM()||wM()){Ut.parentNode&&Ut.remove(),Ut.style.display="none";return}Ut.parentNode!==le&&le.appendChild(Ut),fs();let l=zn(te)>0&&Gp()&&Xp();l?Kp():Sb(),Ut.style.display=l?"":"none"},La=()=>{$o.pause()&&(Cb(),jt())},Lo=()=>{$o.resume(),Sb(),jt()},_r=(s=!1)=>{kr()&&Xp()&&$o.isFollowing()&&(!s&&!Vo||(Br!==null&&(cancelAnimationFrame(Br),Br=null),kd=!0,Br=requestAnimationFrame(()=>{Br=null,kd=!1,$o.isFollowing()&&nT(xb(),s?220:140)})))},wb=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,w=l(),O=w-v;if(ka(),Math.abs(O)<1){ko=!0,s.scrollTop=w,jo=s.scrollTop,ko=!1;return}let z=performance.now();ko=!0;let q=Y=>1-Math.pow(1-Y,3),K=Y=>{if(!g()){ka();return}let se=l();se!==w&&(w=se,O=w-v);let ue=Y-z,Ue=Math.min(ue/f,1),rt=q(Ue),tt=v+O*rt;s.scrollTop=tt,jo=s.scrollTop,Ue<1?Pa=requestAnimationFrame(K):(s.scrollTop=w,jo=s.scrollTop,Pa=null,ko=!1)};Pa=requestAnimationFrame(K)},nT=(s,l=500)=>{let f=zn(s)-s.scrollTop;if(Math.abs(f)<1){jo=s.scrollTop;return}if(Math.abs(f)>=QM){ka(),ko=!0,s.scrollTop=zn(s),jo=s.scrollTop,ko=!1;return}wb(s,()=>zn(s),l,()=>$o.isFollowing())},Dd=()=>{if(!Xp()){jt();return}let s=xb();ko=!0,s.scrollTop=zn(s),jo=s.scrollTop,ko=!1,jt()},ks=s=>{let l=0,f=s;for(;f&&f!==te;)l+=f.offsetTop,f=f.offsetParent;return l},rT=()=>{let s=te.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??te.ownerDocument.getSelection()},Od=()=>Iw(rT(),te),Qp=()=>{if(RM()!=="last-user-turn")return!1;let s=R?.getMessages()??[];if(s.length<2)return!1;let l=[...s].reverse().find(w=>w.role==="user");if(!l)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l.id):l.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),g=te.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,ks(g)-Ii()),zn(te));return ko=!0,te.scrollTop=v,jo=te.scrollTop,ko=!1,qo()==="follow"&&!ra(te,er)&&$o.pause(),jt(),!0},_d=s=>{let l=Math.max(0,Math.round(s));Yo.style.height=`${l}px`,Yo.style.display=l>0?"":"none",$t&&($t.spacerHeight=Math.max(0,s))},Nd=s=>{let l=parseFloat(getComputedStyle(te).paddingBottom)||0,f=0;for(let v of Array.from(te.children)){if(v===Yo||v.offsetHeight===0)continue;let w=ks(v)+v.offsetHeight;w>f&&(f=w)}let g=te.scrollHeight-s;return f>0?Math.min(f+l,g):g},sT=()=>{if(!$t||$t.spacerHeight<=0)return;let s=Nd($t.spacerHeight),l=Math.max(0,Math.round(te.scrollTop)+te.clientHeight-s+er);l<$t.spacerHeight&&(_d(l),jt())},bn=()=>{Ts!==null&&(cancelAnimationFrame(Ts),Ts=null),ka(),$t=null,Yo.style.height="0px",Yo.style.display="none"},Ab=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Yp=s=>te.querySelector(`[data-message-id="${Ab(s)}"]`),Mb=s=>{Ts!==null&&cancelAnimationFrame(Ts),Ts=requestAnimationFrame(()=>{Ts=null;let l=Ab(s),f=te.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=ks(f),v=$t?.spacerHeight??0,w=Nd(v),{targetScrollTop:O,spacerHeight:z}=ih({anchorOffsetTop:g,topOffset:Ii(),viewportHeight:te.clientHeight,contentHeight:w,slack:er});$t={initialSpacerHeight:z,contentHeightAtAnchor:w,spacerHeight:z},_d(z),wb(te,()=>f.isConnected?Math.max(0,ks(f)-Ii()):O,220)})},Io=()=>{if(qo()!=="anchor-top"||!$t||!Ta)return;let s=Yp(Ta);if(!s)return;ka();let l=$t.spacerHeight,f=Nd(l),{targetScrollTop:g,spacerHeight:v}=ih({anchorOffsetTop:ks(s),topOffset:Ii(),viewportHeight:te.clientHeight,contentHeight:f,slack:er});$t={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},_d(v),ko=!0,te.scrollTop=g,jo=te.scrollTop,ko=!1,jt()},aT=()=>{if(kr()){if(!$o.isFollowing()||ra(te,1))return;_r(!Vo);return}if($t&&$t.initialSpacerHeight>0){let s=te.scrollHeight-$t.spacerHeight,l=Rw({initialSpacerHeight:$t.initialSpacerHeight,contentHeightAtAnchor:$t.contentHeightAtAnchor,currentContentHeight:s});l!==$t.spacerHeight&&_d(l)}jt()},iT=s=>{let l=qo();l==="follow"?(Lo(),_r(!0)):l==="anchor-top"&&(Ui=!1,Ld=!0,Id=!1,Ta=s,Mb(s))},lT=()=>{if(qo()==="anchor-top"){if(Ld){Ui=!1;return}Ui=!0,bn(),Lo(),_r(!0)}},dT=96,cT=s=>{if(Es===null)return!0;let l=Yp(Es),f=Yp(s);if(!l||!f)return!0;let g=ks(f)-ks(l);return Ii()+g>te.clientHeight-dT},uT=s=>{if(qo()!=="anchor-top"||!Ld||Id||Od())return;let l=Es===null;for(let f of s){if(!l){f.id===Es&&(l=!0);continue}if(Ew(f)){if(f.id===Ta||!cT(f.id))return;Ta=f.id,Mb(f.id);return}}},pT=s=>{let l=new Map;s.forEach(f=>{let g=jp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&($.emit("assistant:message",f),!Ma&&(qo()!=="anchor-top"||wy())&&Gp()&&(Dr+=1,Kp(),jt(),md(Dr===1?"1 new message below.":`${Dr} new messages below.`))),f.role==="assistant"&&g?.streaming&&f.streaming===!1&&$.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(g?f.approval.status!=="pending"&&$.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):$.emit("approval:requested",{approval:f.approval,message:f}))}),jp.clear(),l.forEach((f,g)=>{jp.set(g,f)})},Vi=(s,l)=>{let f=l==="user"?"user":"assistant",g=n.layout?.messages?.[f],v=g?.width??"content",w=g?.maxWidth??(v==="full"?`var(--persona-message-${f}-max-width, 100%)`:void 0);s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${l}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",l==="user"),s.setAttribute("data-message-role",l),s.setAttribute("data-message-width",v),w?s.style.setProperty("--persona-message-row-max-width",w):s.style.removeProperty("--persona-message-row-max-width")},nr=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Vi(f,l),f},fT=(s,l,f)=>{let g=new Set;for(let D of l){let Ie=D.variant==="tool"?"tool":D.variant==="reasoning"?"reasoning":null;if(!Ie||Qr(n,Ie)!=="row")continue;let Re=Ie==="tool"?n.features?.toolCallDisplay:n.features?.reasoningDisplay;Re?.expandable!==!1&&(g.add(D.id),i.observe(D,Ie,Ie==="tool"?r:a,Re))}let v=document.createElement("div"),O=(()=>{let D=p.find(Ie=>Ie.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),z=(D,Ie)=>Ie==null?!1:typeof Ie=="string"?(D.textContent=Ie,!0):(D.appendChild(Ie),!0),q=new Set,K=new Map,Y=new Set,se=p.some(D=>D.renderAskUserQuestion),ue=[],Ue=[],rt=n.enableComponentStreaming!==!1,tt=n.approval!==!1,Ho=[],Ct=n.messageActions,Mt=Ct?.showRegenerate===!0&&Ct.enabled!==!1&&it.current?.isStreaming()!==!0?JC(l):null,ho=Ct?.showEdit===!0&&Ct.enabled!==!1,Rt=Ct?.showQuote===!0&&Ct.enabled!==!1,lt=null,On=n.features?.reasoningDisplay?.completedVisibility,_n=D=>On==="removed"?!0:On==="removed-when-short"?AC(D,n.features?.reasoningDisplay?.shortThinkThreshold):!1,an=n.features?.toolCallDisplay?.completedVisibility==="removed",ln=D=>D.variant==="reasoning"&&D.reasoning?.status==="complete"?_n(D.reasoning):an&&D.variant==="tool"&&D.toolCall?.status==="complete";if(l.forEach(D=>{if(ln(D))return;if(q.add(D.id),K.set(D.id,D.role),ws===D.id&&Wr){let He=nr(D.id,D.role);He.setAttribute("data-persona-message-edit-stub","true"),He.setAttribute("data-preserve-runtime","true"),v.appendChild(He),lt={messageId:D.id,element:Wr.element};return}let Ie=se&&yr(D),Re=tt&&D.variant==="approval"&&!!D.approval,ne=!Ie&&D.role==="assistant"&&!D.variant&&rt&&dd(D);!Re&&Hr.has(D.id)&&(s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Hr.delete(D.id)),!ne&&Ss.has(D.id)&&(s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Ss.delete(D.id));let dt=yr(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt={canRegenerate:Mt===D.id,canEdit:ho&&Lg(D),canQuote:Rt&&!D.variant&&(D.content?.trim().length??0)>0},po=`${Nt.canRegenerate?"r":""}${Nt.canEdit?"e":""}${Nt.canQuote?"q":""}`,Zt=Sw(D,Ms)+dt+`:${po}`,gt=Ie||Re||ne?null:Aw(_t,D.id,Zt);if(gt){v.appendChild(gt.cloneNode(!0)),yr(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(Y.add(D.toolCall.id),ri(D,n,_e.composerOverlay));return}let Ht=null,zt=p.find(He=>!!(D.variant==="reasoning"&&He.renderReasoning||D.variant==="tool"&&He.renderToolCall||!D.variant&&He.renderMessage)),Te=n.layout?.messages;if(yr(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){Aa.delete(D.id),s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Js(D)&&rs(n).enabled)return;if(yr(D)&&n.features?.askUserQuestion?.enabled!==!1){let He=p.find(Kt=>typeof Kt.renderAskUserQuestion=="function");if(He&&it.current){let Kt=Aa.get(D.id),dn=Kt!==Zt,eo=null;if(dn){let{payload:Ne,complete:We}=br(D),Gr=D.id,Vt=()=>it.current?.getMessages().find(Wo=>Wo.id===Gr);eo=He.renderAskUserQuestion({message:D,payload:Ne,complete:We,resolve:Wo=>{let ur=Vt();ur&&it.current?.resolveAskUserQuestion(ur,Wo)},dismiss:()=>{let Wo=Vt();Wo?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(Wo),it.current?.resolveAskUserQuestion(Wo,"(dismissed)"))},config:n})}let ct=Kt!=null;if(dn&&eo===null&&!ct){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(Y.add(D.toolCall.id),ri(D,n,_e.composerOverlay));return}let Ee=nr(D.id,D.role);Ee.setAttribute("data-ask-plugin-stub","true"),Ee.setAttribute("data-preserve-runtime","true"),v.appendChild(Ee),ue.push({messageId:D.id,fingerprint:Zt,bubble:eo});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(Y.add(D.toolCall.id),ri(D,n,_e.composerOverlay));return}}else if(Re){let He=S();if(!He){v.appendChild(nr(D.id,D.role));return}let Kt=p.find(Ee=>typeof Ee.renderApproval=="function")??E,eo=Hr.get(D.id)!==Zt,ct=null;if(eo&&Kt?.renderApproval){let Ee=D.id,Ne=(We,Gr)=>{let Vt=it.current?.getMessages().find(Wo=>Wo.id===Ee);Vt?.approval&&(Vt.approval.toolType==="webmcp"?it.current?.resolveWebMcpApproval(Vt.id,We):it.current?.resolveApproval(Vt.approval,We,Gr))};ct=Kt.renderApproval({message:D,defaultRenderer:()=>He.createApprovalBubble(D,n,d),config:n,approve:We=>Ne("approved",We),deny:We=>Ne("denied",We)})}if(eo&&ct===null)s.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Hr.delete(D.id),Ht=He.createApprovalBubble(D,n,d);else{let Ee=nr(D.id,D.role);Ee.setAttribute("data-approval-plugin-stub","true"),Ee.setAttribute("data-preserve-runtime","true"),v.appendChild(Ee),Ho.push({messageId:D.id,fingerprint:Zt,bubble:ct});return}}else if(zt)if(D.variant==="reasoning"&&D.reasoning&&zt.renderReasoning){if(!G)return;Ht=zt.renderReasoning({message:D,defaultRenderer:()=>Oh(D,n,a),config:n})}else if(D.variant==="tool"&&D.toolCall&&zt.renderToolCall){if(!Z)return;Ht=zt.renderToolCall({message:D,defaultRenderer:()=>Uh(D,n,r),config:n})}else zt.renderMessage&&(Ht=zt.renderMessage({message:D,defaultRenderer:()=>{let He=bi(D,f,Te,n.messageActions,ga,{loadingIndicatorRenderer:O,widgetConfig:n,actionEligibility:Nt});return D.role!=="user"&&X(He,D,n,R),He},config:n}));if(!Ht&&ne){let He=ip(D);if(He){let Kt=Ss.get(D.id),dn=Kt!==Zt,eo=n.wrapComponentDirectiveInBubble!==!1&&Mn.getOptions(He.component)?.bubbleChrome!==!1,ct=null;if(dn){let Ee=ap(He,{config:n,message:D,transform:f});if(Ee&&He.component==="PersonaArtifactInline"){let Ne=Ee.hasAttribute("data-artifact-inline")?Ee:Ee.querySelector("[data-artifact-inline]"),We=Ne?.getAttribute("data-artifact-inline")??"",Gr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,Vt=We?s.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${Gr}"]`)??null:null;Ne&&Vt&&Vt!==Ne&&wr()?.hasLiveInlineArtifactBlock(Vt)&&(Ne===Ee?Ee=Vt:Ne.replaceWith(Vt))}if(Ee)if(eo){let Ne=document.createElement("div");if(Ne.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ne.id=`bubble-${D.id}`,Ne.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=f({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ne.appendChild(We)}Ne.appendChild(Ee),ct=Ne}else{let Ne=document.createElement("div");if(Ne.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ne.id=`bubble-${D.id}`,Ne.setAttribute("data-message-id",D.id),Ne.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=f({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Ne.appendChild(We)}Ne.appendChild(Ee),ct=Ne}}if(ct||Kt!=null){let Ee=nr(D.id,D.role);Ee.setAttribute("data-component-directive-stub","true"),Ee.setAttribute("data-preserve-runtime","true"),v.appendChild(Ee),Ue.push({messageId:D.id,fingerprint:Zt,bubble:ct});return}}}if(!Ht)if(D.variant==="reasoning"&&D.reasoning){if(!G)return;Ht=Oh(D,n,a)}else if(D.variant==="tool"&&D.toolCall){if(!Z)return;Ht=Uh(D,n,r)}else if(D.variant==="approval"&&D.approval){if(n.approval===!1)return;let He=S();if(!He)return;Ht=He.createApprovalBubble(D,n,d)}else{let He=n.layout?.messages;He?.renderUserMessage&&D.role==="user"?Ht=He.renderUserMessage({message:D,config:n,streaming:!!D.streaming}):He?.renderAssistantMessage&&D.role==="assistant"?Ht=He.renderAssistantMessage({message:D,config:n,streaming:!!D.streaming}):Ht=bi(D,f,He,n.messageActions,ga,{loadingIndicatorRenderer:O,widgetConfig:n,actionEligibility:Nt}),D.role!=="user"&&Ht&&X(Ht,D,n,R)}let ht=nr(D.id,D.role);ht.appendChild(Ht),Mw(_t,D.id,Zt,ht),v.appendChild(ht)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let Re=Ie.getAttribute("data-persona-ask-sheet-for");Re&&!Y.has(Re)&&os(_e.composerOverlay,Re)}),n.features?.toolCallDisplay?.grouped){let D=[],Ie=[],Re=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(ne=>{if(ne.variant==="tool"&&ne.toolCall&&Z){if(an&&ne.toolCall.status==="complete")return;Ie.push(ne);return}ne.variant==="reasoning"&&(!G||ne.reasoning?.status==="complete"&&_n(ne.reasoning))||((Ie.length>1||Re&&Ie.length>0)&&D.push(Ie),Ie=[])}),(Ie.length>1||Re&&Ie.length>0)&&D.push(Ie),D.forEach(ne=>{let dt=ne.map(Te=>Array.from(v.children).find(ht=>ht instanceof HTMLElement&&ht.getAttribute("data-wrapper-id")===Te.id)).filter(Te=>!!Te);if(dt.length<(Re?1:2))return;let Nt=nr(`tool-group-${ne[0].id}`,"assistant");if(Nt.setAttribute("data-persona-tool-group-row","true"),n.features?.toolCallDisplay?.groupedMode==="collapsible"){let Te=`tool-group-${ne[0].id}`,ht=ne.some(ct=>ct.toolCall?.status!=="complete"),He={...ne[0],id:Te,toolCall:{id:Te,name:`${ne.length} tools`,status:ht?"running":"complete",chunks:ne.flatMap(ct=>ct.toolCall?.chunks??[]),success:!ne.some(ct=>ct.toolCall?.success===!1)}};g.add(Te),i.observe(He,"tool",r,n.features.toolCallDisplay);let Kt=`${ht?"Using":"Used"} ${ne.length} tools`,dn=n.toolCall?.renderGroupedSummary?.({messages:ne,toolCalls:ne.map(ct=>ct.toolCall),defaultSummary:Kt,config:n}),eo=Hx(He,n,r.has(Te),dn??Kt);eo.bubble.classList.add("persona-tool-group"),eo.body.dataset.personaToolGroupStack="true",dt[0].before(Nt),Nt.appendChild(eo.bubble),dt.forEach((ct,Ee)=>{ct.style.setProperty("--persona-message-row-max-width","100%"),ct.style.setProperty("--persona-activity-stagger",`${Ee*40}ms`),ct.classList.add("persona-activity-group-child"),eo.body.appendChild(ct)});return}let po=document.createElement("div");po.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",po.setAttribute("data-persona-tool-group","true");let Zt=document.createElement("div");Zt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Zt.id=`tool-group-summary-${ne[0].id}`;let gt=`Called ${ne.length} ${ne.length===1?"tool":"tools"}`,Ht=n.toolCall?.renderGroupedSummary?.({messages:ne,toolCalls:ne.map(Te=>Te.toolCall).filter(Te=>!!Te),defaultSummary:gt,config:n});z(Zt,Ht)||(Zt.textContent=gt);let zt=document.createElement("div");zt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.id=`tool-group-stack-${ne[0].id}`,zt.setAttribute("data-persona-tool-group-stack","true"),po.appendChild(Zt),Re||po.appendChild(zt),Nt.appendChild(po),dt[0].before(Nt),dt.forEach((Te,ht)=>{if(Re){Te.remove();return}Te.style.setProperty("--persona-message-row-max-width","100%");let He=document.createElement("div");He.className="persona-tool-group-item persona-relative",He.setAttribute("data-persona-tool-group-item","true"),ht<dt.length-1&&He.setAttribute("data-persona-tool-group-connector","true"),He.appendChild(Te),zt.appendChild(He)})})}i.prune(g),Tw(_t,q);let zr=D=>D.variant==="tool"&&!Z||D.variant==="reasoning"&&!G||ln(D),Nn=l.some(D=>D.role==="assistant"&&D.streaming&&!zr(D)),vn=l.length-1;for(;vn>=0&&zr(l[vn]);)vn--;let Kr=vn>=0?l[vn]:void 0,pl=vn<l.length-1,Us=Kr?.role==="assistant"&&!Kr.streaming&&Kr.variant!=="approval"&&!pl;if(Vo&&l.some(D=>D.role==="user")&&!Nn&&!Us){let D={config:n,streaming:!0,location:"standalone",defaultRenderer:ca},Ie=p.find(ne=>ne.renderLoadingIndicator),Re=null;if(Ie?.renderLoadingIndicator&&(Re=Ie.renderLoadingIndicator(D)),Re===null&&n.loadingIndicator?.render&&(Re=n.loadingIndicator.render(D)),Re===null&&(Re=ca()),Re){let ne=document.createElement("div"),dt=n.loadingIndicator?.showBubble!==!1,Nt=n.layout?.messages?.layout??"bubble";ne.className=dt?od("assistant",Nt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),ne.setAttribute("data-typing-indicator","true"),dt&&(ne.style.color="var(--persona-message-assistant-text, var(--persona-text))",Nt!=="flat"&&(ne.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",ne.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),ne.appendChild(Re);let po=nr("typing-indicator","assistant");po.appendChild(ne),v.appendChild(po)}}if(!Vo&&l.length>0){let D=l[l.length-1],Ie={config:n,lastMessage:D,messageCount:l.length},Re=p.find(dt=>dt.renderIdleIndicator),ne=null;if(Re?.renderIdleIndicator&&(ne=Re.renderIdleIndicator(Ie)),ne===null&&n.loadingIndicator?.renderIdle&&(ne=n.loadingIndicator.renderIdle(Ie)),ne){let dt=document.createElement("div"),Nt=n.loadingIndicator?.showBubble!==!1;dt.className=Nt?["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(" "),dt.setAttribute("data-idle-indicator","true"),dt.appendChild(ne);let po=nr("idle-indicator","assistant");po.appendChild(dt),v.appendChild(po)}}if(Xx(v),Fu(s,v),lg(s),lt){let{messageId:D,element:Ie}=lt,Re=s.querySelector(`#wrapper-${D}`);Re&&Ie.parentElement!==Re&&(Vi(Re,K.get(D)??"user"),Re.replaceChildren(Ie))}if(ue.length>0)for(let{messageId:D,fingerprint:Ie,bubble:Re}of ue){let ne=s.querySelector(`#wrapper-${D}`);ne&&(Vi(ne,K.get(D)??"assistant"),Re!==null&&(ne.replaceChildren(Re),ne.setAttribute("data-bubble-fp",Ie),Aa.set(D,Ie)))}if(Aa.size>0)for(let D of Aa.keys())q.has(D)||Aa.delete(D);if(Ue.length>0)for(let{messageId:D,fingerprint:Ie,bubble:Re}of Ue){let ne=s.querySelector(`#wrapper-${D}`);ne&&(Vi(ne,K.get(D)??"assistant"),Re!==null&&(ne.replaceChildren(Re),ne.setAttribute("data-bubble-fp",Ie),Ss.set(D,Ie)))}if(Ss.size>0)for(let D of Ss.keys())q.has(D)||Ss.delete(D);if(Ho.length>0)for(let{messageId:D,fingerprint:Ie,bubble:Re}of Ho){let ne=s.querySelector(`#wrapper-${D}`);ne&&(Vi(ne,K.get(D)??"assistant"),Re!==null&&(ne.replaceChildren(Re),ne.setAttribute("data-bubble-fp",Ie),Hr.set(D,Ie)))}if(Hr.size>0)for(let D of Hr.keys())q.has(D)||Hr.delete(D)},Jp=!1,Fd=()=>{Jp||(Jp=!0,qc().catch(()=>{Jp=!1}))},Zo=(s,l,f)=>{l.length>0&&Fd(),fT(s,l,f),$y()},$i=null,mT=()=>{if($i)return;let s=f=>{let g=f.composedPath();g.includes(Ge)||Yt&&g.includes(Yt)||mt(!1,"user")};$i=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},Tb=()=>{if(!$i)return;(e.ownerDocument??document).removeEventListener("pointerdown",$i,!0),$i=null};fe.push(()=>Tb());let ji=null,gT=()=>{if(ji)return;let s=f=>{f.key==="Escape"&&(f.isComposing||mt(!1,"user"))};ji=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Eb=()=>{if(!ji)return;(e.ownerDocument??document).removeEventListener("keydown",ji,!0),ji=null};fe.push(()=>Eb());let zi=!1,Pb=new Set,hT=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},Ia=()=>{if(!De())return;let s=_e.peekBanner,l=_e.peekTextNode;if(!s||!l)return;if(ke){s.classList.remove("persona-pill-peek--visible");return}let f=R?.getMessages()??[],g;for(let Ct=f.length-1;Ct>=0;Ct--){let Mt=f[Ct];if(Mt.role==="assistant"&&Mt.content){g=Mt;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,w=!!g.streaming,O=hT(),z=Uu(O),q=z.type!=="none"?qp(z.type,O?.plugins):null,K=q?.isAnimating?.(g)===!0,Y=q!==null&&(w||K);Y&&q&&!Pb.has(q.name)&&(Jl(q,e),Pb.add(q.name));let se=Y&&q?.containerClass?q.containerClass:null,ue=l.dataset.personaPeekStreamClass??null;ue&&ue!==se&&(l.classList.remove(ue),delete l.dataset.personaPeekStreamClass),se&&ue!==se&&(l.classList.add(se),l.dataset.personaPeekStreamClass=se),Y?(l.style.setProperty("--persona-stream-step",`${z.speed}ms`),l.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Ue=Y?qu(v,z.buffer,q,g,w):v;if(Y&&z.placeholder==="skeleton"&&w&&(!Ue||!Ue.trim())){let Ct=document.createElement("div"),Mt=Yl();Mt.classList.add("persona-pill-peek__skeleton"),Ct.appendChild(Mt),Fu(l,Ct)}else{let Ct=Math.max(0,Ue.length-100),Mt=Ue.length>100?Ue.slice(-100):Ue,ho=hr(Mt);if(!Y||!q){let Rt=Ue.length>100?`\u2026${Mt}`:Mt;l.textContent!==Rt&&(l.textContent=Rt)}else{let Rt=ho;(q.wrap==="char"||q.wrap==="word")&&(Rt=Ql(ho,q.wrap,`peek-${g.id}`,{skipTags:q.skipTags,startIndex:Ct}));let lt=document.createElement("div");if(lt.innerHTML=Rt,q.useCaret&&Mt.length>0){let On=Vu(),_n=lt.querySelectorAll(".persona-stream-char, .persona-stream-word"),an=_n[_n.length-1];an?.parentNode?an.parentNode.insertBefore(On,an.nextSibling):lt.appendChild(On)}Fu(l,lt),q.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:z.speed,duration:z.duration})}}let Ho=Vo||zi;s.classList.toggle("persona-pill-peek--visible",Ho)};if(De()){let s=_e.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),mt(!0,"user")};s.addEventListener("pointerdown",g),fe.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{zi||(zi=!0,Ia())},f=()=>{zi&&(zi=!1,Ia())};be.addEventListener("pointerenter",l),be.addEventListener("pointerleave",f),fe.push(()=>{be.removeEventListener("pointerenter",l),be.removeEventListener("pointerleave",f)}),Yt&&(Yt.addEventListener("pointerenter",l),Yt.addEventListener("pointerleave",f),fe.push(()=>{Yt.removeEventListener("pointerenter",l),Yt.removeEventListener("pointerleave",f)}))}let yT=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,w=l.expandedMaxWidth??"880px",O=l.expandedTopOffset??"5vh",z=l.modalMaxWidth??"880px",q=l.modalMaxHeight??"min(90vh, 800px)",K="calc(100vw - 32px)",Y="var(--persona-pill-area-height, 80px)",se=Ge.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Yt){let ue=Yt.style;ue.bottom=g,ue.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=z,se.maxWidth=K,se.maxHeight=q,se.height=q;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${g} + ${Y})`,se.top=O,se.width=w,se.maxWidth=K}},Ki=()=>{if(ke&&Fd(),!Qe())return;if(De()){let K=(n.launcher?.composerBar??{}).expandedSize??"anchored",Y=ke?"expanded":"collapsed";Ge.dataset.state=Y,Ge.dataset.expandedSize=K,Yt&&(Yt.dataset.state=Y,Yt.dataset.expandedSize=K),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),yT(ke),le.style.display=ke?"flex":"none",gs(),ke?(mT(),gT()):(Tb(),Eb()),Ia();return}let s=yt(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,w=g&&v&&N,O=Oo(n).reveal;ke?(Ge.style.removeProperty("display"),Ge.style.display=s?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-95","persona-opacity-0"),be.classList.add("persona-scale-100","persona-opacity-100"),Lt?(Lt.setPanelOpen(!0),Lt.element.style.display="none"):go&&(go.style.display="none")):(s?s&&(O==="overlay"||O==="push")&&!w?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.setProperty("display","none","important"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.display="",Ge.classList.add("persona-pointer-events-none","persona-opacity-0"),be.classList.remove("persona-scale-100","persona-opacity-100"),be.classList.add("persona-scale-95","persona-opacity-0")),Lt?(Lt.setPanelOpen(!1),Lt.element.style.display=s?"none":""):go&&(go.style.display=s?"none":""))},mt=(s,l="user")=>{if(!Qe()||ke===s)return;let f=ke;ke=s,Ki();let g=(()=>{let w=n.launcher?.sidebarMode??!1,O=e.ownerDocument.defaultView??window,z=n.launcher?.mobileFullscreen??!0,q=n.launcher?.mobileBreakpoint??640,K=O.innerWidth<=q,Y=yt(n)&&z&&K,se=De()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||z&&K&&N||Y||se})();if(ke&&g){if(!In){let w=e.getRootNode(),O=w instanceof ShadowRoot?w.host:e.closest(".persona-host");O&&(In=ph(O,n.launcher?.zIndex??co))}Rn||(Rn=fh(e.ownerDocument))}else ke||(In?.(),In=null,Rn?.(),Rn=null);ke&&(dl(),Qp()||(qo()==="follow"?_r(!0):Dd()));let v={open:ke,source:l,timestamp:Date.now()};ke&&!f?$.emit("widget:opened",v):!ke&&f&&$.emit("widget:closed",v),$.emit("widget:state",{open:ke,launcherEnabled:N,voiceActive:Xe.active,streaming:R.isStreaming()})},Nr={inputDisabled:!1,sendDisabled:!1},Hn=()=>Nr.inputDisabled,Zp=()=>vo(n.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),Ls=()=>Nr.inputDisabled||Nr.sendDisabled,bT=()=>(Nr.inputDisabled?Nr.inputReason:void 0)??(Nr.sendDisabled?Nr.sendReason:void 0);function ef(){if(!Se)return;if(ye.getState().phase==="streaming"){Se.disabled=!1;return}let s=nt?!nt.isReady():!1;Se.disabled=Ls()||s}function Ud(){if(!Tn)return;let s=ye.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;Tn.toggleAttribute("data-persona-send-hidden",l)}function vT(){let s=bT();if(De()){let l=To??Le;s?l.setAttribute("title",s):l.removeAttribute("title"),Le.toggleAttribute(Ei,!!s);return}if(s){Ye.setAttribute("role","status"),Ye.setAttribute("aria-live","polite"),Ye.setAttribute(Ei,""),Ye.textContent=s,Qs(Ye,n.statusIndicator??{},"idle");return}if(Ye.hasAttribute(Ei)&&(Ye.removeAttribute("role"),Ye.removeAttribute("aria-live"),Ye.removeAttribute(Ei),y)){let l=R.getStatus();Pi(Ye,vp(l),n.statusIndicator??{},l)}}function tf(){let s=Ug(n.composer?.inputDisabled),l=Ug(n.composer?.sendDisabled);Nr={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},ye.setInputDisabled(s.disabled),ye.setSendDisabled(l.disabled);let f=ye.getState().phase==="streaming",g=s.disabled,v=f||g;ie&&(ie instanceof HTMLTextAreaElement?ie.disabled=g:ie.setAttribute("contenteditable",g?"false":"true"),ie.setAttribute("aria-disabled",g?"true":"false")),At&&(At.disabled=g),xt&&(xt.disabled=g);for(let w of Ot?.affordanceButtons??[])w.querySelectorAll("button").forEach(O=>{O.disabled=g});re&&(re.disabled=g||f&&!Zp()),bs.forEach(w=>{w.elements.forEach(O=>{O.toggleAttribute("data-disabled",v),O instanceof HTMLButtonElement||O.setAttribute("aria-disabled",v?"true":"false")}),w.buttons.forEach(O=>{O.disabled=v})}),af.forEach(w=>{w.toggleAttribute("data-disabled",v),w instanceof HTMLButtonElement?w.disabled=v:w.setAttribute("aria-disabled",v?"true":"false"),w.querySelectorAll("button").forEach(O=>{O.disabled=v})}),Le.dataset.personaComposerStreaming=f?"true":"false",Le.dataset.personaComposerInputDisabled=g?"true":"false",Le.dataset.personaComposerSendDisabled=Ls()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(w=>{(w instanceof HTMLButtonElement||w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement)&&(w.disabled=f)}),ef(),vT()}let Gi=s=>{ye.setStreaming(s),Cy(s?"stop":"send"),tf()},Is=()=>{Xe.active||ie&&ie.focus()};$.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Is(),200)});let Rs=null,Xi=!1,of=!Jt.hidden,Fr=null,nf=!oe,qd=null;fe.push(()=>{qd?.cancel(),qd=null});let xT=s=>{let l=rA(s);if(l===gd)return;gd=l,e.setAttribute("data-persona-conversation-state",l);let f=Ap();yd(),nf&&(qd?.cancel(),qd=oA(Le,l==="active"?f:Ap(),l==="active"?"drop":"rise",ps().layout==="centered"?320:260)),Io()},kb=null,Lb,Ib=null,Ra=null,rf=!1,Ha=s=>{let l=ps(),f=`${l.variant}|${l.layout}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==kb||l.icon!==Lb)&&(kb=f,Lb=l.icon,Qu({host:Jt,iconHolder:AM,kicker:MM,title:TM,subtitle:EM,starterSuggestions:xp},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==Ib&&(Ib=g,Yu(Fo,l.message,n));let v=s??(R?R.getMessages():n.initialMessages);xT(v);let w=Xi,O=!w&&ds(l,v),z=O!==of;if(of=O,Ra){Fr?.cancel(),Fr=null,w!==rf&&(rf=w,w?kh(te,Jt,null):Ph(te,Jt,Ra)),vi(te,Jt,!w);return}if(z&&!O&&!w&&l.dismiss==="on-first-message"&&nf){Fr=tA(Jt,K=>{Fr===K&&(Fr=null),!of&&!Ra&&(vi(te,Jt,!1),Io()),K?.cancel()});return}if(Fr){if(!O&&!w)return;Fr.cancel(),Fr=null}let q=!Jt.hidden;vi(te,Jt,O),!O&&q&&Io()},sf=[],af=[],lf=!1,Rb=null,Hb,Wb=()=>{af.length=0;let s=sf.splice(0,sf.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};fe.push(Wb);let CT=(s,l)=>{let f=gh(s,l);if(!f)return n.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),I("span");let g=n.suggestions?.starters,v=hh({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:y?R.isStreaming():!1,config:n,plugins:p,chipsConfig:n.suggestionChipsConfig,session:R,getTextarea:()=>ie,eventTarget:Jt,submitPrompt:gc});return af.push(v),v},df=()=>{if(lf)return;lf=!0;let s=ps();Rb=`${s.variant}|${s.layout}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,Hb=s.icon;try{Wb(),kh(te,Jt,Ra),Ra=null,rf=!1;let l=R?R.getMessages():n.initialMessages,f=ds(s,l),g=0,v=null;for(let w of p)if(w.renderWelcome&&(v=w.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>Jt,sendMessage:O=>{if(!R||R.isStreaming())return;let z=O.trim();z&&R.sendMessage(z)},requestRender:()=>df(),renderStarter:O=>CT(O,g++),storage:x(w.id),onCleanup:O=>{sf.push(O)}}),v))break;v&&v!==Jt&&(Ra=v,Ph(te,Jt,v))}finally{lf=!1}Ha()},ST=()=>{let s=ps();`${s.variant}|${s.layout}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===Rb&&s.icon===Hb||df()},Vd=()=>{Ha(),xa||(ie.placeholder=BS(ye.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(Se.textContent=n.copy?.sendButtonLabel??"Send")),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},wT=!!n.setStoredConversationId,Wa=s=>ve(l=>{let f={...l};return delete f[s],f}),$d=s=>{let l=W[s];return typeof l=="string"?l:null},Bb=()=>{let s=W.durableResume;if(!s||typeof s!="object")return null;let l=s;return typeof l.executionId=="string"&&l.executionId.length>0&&typeof l.after=="string"&&l.after.length>0?{executionId:l.executionId,after:l.after}:null};n.clientToken&&(n={...n,getStoredSessionId:()=>$d("sessionId"),setStoredSessionId:s=>{ve(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>Wa("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>$d("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{ve(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>Wa("conversationId"))});let Db=()=>n.clientToken??null,Ob=s=>qA(s,Ce(),n.persistState===!1),_b=Db(),en=_b?Ob(_b):null,rr={...en?{visitorStore:en}:{},historyBootstrapReady:de,getStoredMessageCursor:()=>$d("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){Wa("historyMessageCursor");return}ve(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=W.pendingDisplayProjections;if(!s||typeof s!="object")return null;let l=s;return typeof l.conversationId!="string"||!Array.isArray(l.messageIds)?null:{conversationId:l.conversationId,messageIds:l.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){Wa("pendingDisplayProjections");return}ve(l=>({...l,pendingDisplayProjections:s}))},getStoredResumableHandle:Bb,setStoredResumableHandle:s=>{if(!s){Wa("durableResume");return}ve(l=>({...l,durableResume:s}))},shouldResumeDurableConversation:()=>F&&Bb()!==null,...wT?{}:{getStoredConversationRevision:()=>$d("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){Wa("conversationRevision");return}ve(l=>({...l,conversationRevision:s}))}}};if(F){let s=n.onExecutionState,l=e.ownerDocument.defaultView,f=!1,g=()=>f=!0,v=()=>f=!1;l?.addEventListener("pagehide",g),l?.addEventListener("pageshow",v),fe.push(()=>{l?.removeEventListener("pagehide",g),l?.removeEventListener("pageshow",v)}),n={...n,reconnectStream:n.reconnectStream??(w=>R.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!f)&&rr.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),s?.(w)}}}let AT=()=>{let s=Db();if(s&&en?.matches(s,Ce(),n.persistState===!1)||!s&&!en)return;en?.destroy(),en=s?Ob(s):null;let l={...rr};en?l.visitorStore=en:delete l.visitorStore,rr=l,R.setHistoryInternals(rr)},Hs=null,MT=()=>{Hs==null&&(Hs=setInterval(()=>{let s=he.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(Hs),Hs=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=f.closest(".persona-activity-row")?Al(l-g):eu(l-g))})},100))},cf=(s,l)=>{if(Object.is(s,l))return!0;if(s===null||l===null||typeof s!="object"||typeof l!="object")return!1;if(Array.isArray(s)||Array.isArray(l))return!Array.isArray(s)||!Array.isArray(l)||s.length!==l.length?!1:s.every((O,z)=>cf(O,l[z]));let f=s,g=l,v=Object.keys(f),w=Object.keys(g);return v.length===w.length&&v.every(O=>Object.prototype.hasOwnProperty.call(g,O)&&cf(f[O],g[O]))},Nb=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},uf=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!dd(s),TT=(s,l,f)=>{if(s.length!==l.length)return!1;let g=s[f.index],v=l[f.index];return!g||!v||g.id!==f.id||v.id!==f.id?!1:(!Object.is(g.content,v.content)||!Object.is(g.rawContent,v.rawContent)||!Object.is(g.llmContent,v.llmContent))&&uf(g)&&uf(v)&&cf(Nb(g),Nb(v))},pf=null,Ba=null,Ws=null,sr=null,ff=null,ET=s=>{if(!F)return Ea(s);ff=s,queueMicrotask(()=>{ff===s&&(ff=null,Ea(s))})},jd=s=>{pf=s;let l,f;Ba=null;for(let v=s.length-1;v>=0;v-=1){let w=s[v];if(!l&&w.role==="user"&&(l=w),!f&&w.role==="assistant"&&(f=w),!Ba&&uf(w)&&(Ba={index:v,id:w.id}),l&&f&&Ba)break}Zo(he,s,U),wr()?.updateInlineArtifactBlocks(he,Jo.artifacts,{suppressTransition:Vo}),MT(),Ha(s),Cs(s),_r(!Vo),pT(s),s.length===0&&(bn(),Ui=!0,Ld=!1,Ta=null,Id=!1),!Vp||Ma?(Vp=!0,Es=l?.id??null,$p=f?.id??null):l&&l.id!==Es?(Es=l.id,iT(l.id)):f&&f.id!==$p&&lT(),f&&($p=f.id),uT(s);let g=Xe.lastUserMessageId;l&&l.id!==g&&(Xe.lastUserMessageId=l.id,$.emit("user:message",l)),Xe.lastUserMessageWasVoice=!!l?.viaVoice,ET(s),Ia()},mf=()=>{sr!==null&&(cancelAnimationFrame(sr),sr=null);let s=Ws;Ws=null,s&&jd(s)},Fb=()=>{sr!==null&&cancelAnimationFrame(sr),sr=null,Ws=null},PT=s=>{let l=Ws??pf;if(Vo&&l&&Ba&&TT(l,s,Ba)){Ws=s,sr===null&&(sr=requestAnimationFrame(()=>{sr=null;let f=Ws;Ws=null,f&&jd(f)}));return}if(s.length===0){Fb(),jd(s);return}mf(),jd(s)};R=new ci(n,{onMessagesChanged(s){PT(s)},onStatusChanged(s){let l=n.statusIndicator??{};Pi(Ye,(g=>g==="idle"?l.idleText??Wt.idle:g==="connecting"?l.connectingText??Wt.connecting:g==="connected"?l.connectedText??Wt.connected:g==="error"?l.errorText??Wt.error:g==="paused"?l.pausedText??Wt.paused:g==="resuming"?l.resumingText??Wt.resuming:Wt[g])(s),l,s),bp()},onStreamingChanged(s){s||(R?.getMessages().length===0?Fb():mf()),Vo=s,Gi(s),bp(),R&&Zo(he,R.getMessages(),U),s||(_r(!0),sT(),pb=!0,R&&fb(R.getMessages(),rs(n))),jt(),md(s?"Responding\u2026":"Response complete."),Ia()},onVoiceStatusChanged(s){if($.emit("voice:status",{status:s,timestamp:Date.now()}),!(s!=="disconnected"&&!vo(n.voiceRecognition?.provider)))switch(s){case"listening":cr(),za();break;case"processing":cr(),LE();break;case"speaking":cr(),IE();break;default:s==="idle"&&R.isBargeInActive()?(cr(),za(),re?.setAttribute("aria-label","End voice session")):(Xe.active=!1,cr(),or("system"),yn());break}},onArtifactsState(s){Jo=s,s.artifacts.length===0&&(Ca=!1),wr()?.updateInlineArtifactBlocks(he,s.artifacts,{suppressTransition:Vo}),hn(),Ea()},onHistoryStateChanged(s){vy(s)},onHistoryNotice(s){xy(s)},onReconnect(s){let{executionId:l,lastEventId:f}=s.handle;s.phase==="paused"?$.emit("stream:paused",{executionId:l,after:f}):s.phase==="resuming"?$.emit("stream:resuming",{executionId:l,after:f,attempt:s.attempt??1}):$.emit("stream:resumed",{executionId:l,after:f})}},rr),it.current=R,fe.push(()=>R.cancel()),fe.push(()=>{R.destroy(),en?.destroy(),en=null});let gf=null;if(R.onReadAloudChange((s,l)=>{qy=s,Vy=l,$y();let f=s??gf;s&&(gf=s);let g=f?R.getMessages().find(v=>v.id===f)??null:null;$.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(gf=null)}),y=!0,Vp=!0,n.voiceRecognition?.enabled===!0&&vo(n.voiceRecognition.provider))try{R.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let kT=720,LT=250,Je=ny(n.features?.history?.copy),zo=null,hf=!1,at=null,zd=null,Kd="conversation",yf=null,mo=null,Wn=null,Gd=R.getHistoryState(),bf=null,Qi=0,vf=null,Xd=null,Qd=null,xf=`persona-history-${Math.random().toString(36).slice(2,8)}`,Cf=()=>n.features?.history?.enabled===!0,Bn=()=>Cf()&&!!zo&&!hf,Ub=()=>{let s=R.getStatus();return Vo||s==="paused"||s==="resuming"},Sf=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=zo?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},Da=()=>zd?.scope??Sf(),qb=()=>R.getClientSession()?.targetId??null,Vb=s=>`${s.state}:${"reason"in s?s.reason:""}`,IT=s=>{let l=Vb(s);l!==bf&&(bf=l,$.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Yd=s=>{s&&(Qn.textContent="",Qn.textContent=s)},$b=null,jb=null,RT=()=>{if(!Cf())return null;let s=KA();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:($b!==l&&($b=l,jb=l()),jb):R.isClientTokenMode()?GA({client:R.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>R.bindActivatedSession(f),getClient:()=>R.getClient()}):null},zb=()=>{Xd?.(),Xd=null,Qd?.(),Qd=null,hf=!1,zo=RT();let s={...rr};zo?s.historyProvider=zo:delete s.historyProvider,rr=s,R.setHistoryInternals(rr),zo&&(Xd=zo.subscribeAvailability?.(l=>{hf=!l,l||Ro({restoreFocus:!1}),qr()})??null,Qd=zo.subscribeIdentityStatus(l=>IT(l)),bf=Vb(zo.getIdentityStatus()))},wf=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!N||yt(n)))return"panel";let l=Ln??le;return(l.getBoundingClientRect().width||l.clientWidth)>=kT?"rail":"panel"},tn=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Jd="data-persona-history-suppressed",Ko=null,Ur=null,Bs=null,Yi=null,Af=null,Kb="",Gb=()=>we===Af?Kb:n.layout?.showHeader===!1?"none":"",HT=()=>Ft==="panel"&&!!Bs&&Yi===Bs.element&&n.layout?.showHeader!==!1&&Gb()!=="none",WT=()=>{for(let s of Array.from(we.children))s!==Ko&&s.setAttribute(Jd,"")},BT=()=>{for(let s of Array.from(le.querySelectorAll(`[${Jd}]`)))s.removeAttribute(Jd)},DT=()=>{let s=Bs;if(!s)return;if(Array.from(we.children).some(g=>g!==Ko&&!g.hasAttribute(Jd))){Ur&&Ur!==we&&(Ur.style.removeProperty("min-height"),Ur=null);let g=we.offsetHeight;g>0&&(we.style.minHeight=`${g}px`,Ur=we)}Ko||(Ko=I("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==Ko&&Ko.replaceChildren(f),Ko.parentNode!==we&&we.appendChild(Ko),WT()},Xb=()=>{Ur&&(Ur.style.removeProperty("min-height"),Ur=null),Ko&&(Bs?.setHeaderPlacement("inline"),Ko.remove(),Ko=null,BT())},Zd=null,Mf=()=>{if(Zd){if(te.style.display="none",tn(te,!0),Le.hidden=!0,tn(Le,!0),HT()){DT(),we.style.display=Gb(),tn(we,!1);return}Xb(),we.style.display="none",tn(we,!0)}};yp=Mf;let OT=s=>{let l=te.style.display,f=Le.hidden,g=Le,v=we,w=we.style.display;Af=v,Kb=w,Zd=()=>{Zd=null,Xb(),Af=null,te.style.display=l,tn(te,!1),g.hidden=f,tn(g,!1),Le!==g&&(Le.hidden=!1,tn(Le,!1)),v.style.display=w,tn(v,!1),we!==v&&(we.style.display=n.layout?.showHeader===!1?"none":"",tn(we,!1))},Le.parentNode?.insertBefore(s,Le),Mf()},Oa=null,Ds=null,Ji=null,_a=null,Qb=()=>[we,_e.closeButtonWrapper,_e.clearChatButtonWrapper,te,Le],_T=52,ec=()=>n.features?.history?.rail?.collapsible!==!1,Na=()=>n.features?.history?.rail?.side==="right"?"right":"left",Tf=200,Ef=400,Pf=s=>Math.min(Ef,Math.max(Tf,Math.round(s))),NT=()=>n.features?.history?.rail?.resizable===!0,Zi,FT=()=>{if(Zi===void 0&&(Zi=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${Ce()}rail-width`));s&&(Zi=s)}catch{}return Zi},el=()=>Pf(FT()??n.features?.history?.rail?.width??260),UT=s=>{if(Zi=s,n.persistState!==!1)try{window.localStorage.setItem(`${Ce()}rail-width`,String(s))}catch{}},tc=()=>ec()&&n.features?.history?.rail?.collapsedBehavior==="overlay",qt=!1,Yb=s=>{let l=I("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},qT=()=>{let s=n.features?.history?.rail?.brand;if(!s)return;let l=!1,f;return g=>{if(s.render)try{return s.render({collapsed:g})??null}catch(v){return l||(l=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=Yb(s.iconUrl):f=s.icon?ae(s.icon,20):null),f?f.cloneNode(!0):null}},VT=()=>n.features?.history?.rail?.sections?.map(s=>{let l=!1,f=g=>{l||(l=!0,console.warn("[persona] history rail section threw",s.id,g))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(g=>{let v;return{id:g.id,label:g.label,badge:g.badge,iconNode:()=>{if(v!==void 0)return v;try{g.renderIcon?v=g.renderIcon()??null:g.iconUrl?v=Yb(g.iconUrl):v=g.icon?ae(g.icon,20):null}catch(w){f(w),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(w){f(w)}}}})}})??[],$T=s=>{let l=VT();for(let f of s)l.some(g=>g.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):l.push(f);return l.length?l:void 0},tl=null,Jb=()=>`${Ce()}rail-collapsed`,kf=()=>{if(tl===null&&(tl=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(Jb());s&&(tl=s==="1")}catch{}return tl},Lf=s=>{if(tl=s,n.persistState!==!1)try{window.localStorage.setItem(Jb(),s?"1":"0")}catch{}},ol=()=>Ft==="rail"&&ec()&&!tc()&&kf(),If=()=>{},Zb=()=>{if(tc()){If();return}Lf(!kf()),at?.view.setCollapsed(ol()),Xn(),Io()},Rf=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!_u(s)?null:{combo:s,hint:Nu(s),aria:zl(s)}},ev=()=>{h.forEach(l=>l()),h=[];let s=Rf();s&&h.push(m.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Pt&&Ft==="rail"&&ec()||Ua(),run:()=>tc()?If():Zb()}));for(let l of n.layout?.header?.trailingActions??[])l.shortcut&&h.push(m.register({id:`header-action-${l.id}`,combo:l.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${l.id}"]`);f?f.click():n.layout?.header?.onAction?.(l.id)}}));for(let l of p)for(let f of l.shortcuts??[])h.push(m.register({...f,id:`${l.id}:${f.id}`}))};ev();let jT=300,oc="var(--persona-history-overlay-margin,8px)",on=null,ar=null,nc=0,ir=null,Fa=null,Os=!1,Hf=0,tv=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ua=()=>Bn()&&tc()&&(Ft??wf())==="rail",zT=()=>Pt&&!qt,nl=()=>{Fa!==null&&clearTimeout(Fa),Fa=null},KT=()=>{ey().catch(()=>{})},ov=()=>{nl(),qt&&(Fa=setTimeout(()=>{Fa=null,!(Os||!qt)&&(ir?.contains(document.activeElement)||Ro({restoreFocus:!1}))},jT))},GT=(s,l)=>{let f=ir?.getBoundingClientRect();if(!f)return!1;let g=on?.getBoundingClientRect(),v=g?Math.min(g.top,f.top):f.top;return s>=f.left&&s<=f.right&&l>=v&&l<=f.bottom||!!g&&s>=g.left&&s<=g.right&&l>=g.top&&l<=g.bottom},Wf=s=>{qt&&(Os=GT(s.clientX,s.clientY),Os?nl():Fa===null&&ov())},nv=s=>{Pt||!Ua()||(qt=!0,sl({invoker:on,keyboard:s?.keyboard===!0}).then(()=>{Pt?!Os&&document.activeElement!==on&&Ro():qt=!1}))},rv=()=>{let s=Yi?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",qt?Je.expandLabel:Je.collapseLabel),s.setAttribute("aria-expanded",qt?"false":"true"))},sv=()=>{Lf(!1);let s=at;if(!qt||!s){sl({invoker:on});return}let l=document.activeElement===on;qt=!1,rc(),s.element.remove(),Df(s.element),rv(),l&&ac(),Io(),qr()},XT=()=>{Lf(!0),Ro()};If=()=>{!Pt||qt?sv():XT()};let QT=()=>{let s=Rf(),l=sa({ariaLabel:Je.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":xf,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{Os=!0,nl(),!(tv()||Date.now()<Hf)&&nv()}),f.addEventListener("mouseleave",()=>{Os=!1,Hf=0,ov()}),f.addEventListener("focus",()=>{Pt||KT()}),f.addEventListener("click",g=>{Bn()&&(g.detail!==0&&tv()&&!Pt?nv():sv())}),on=f,ar=l.wrapper},rl=()=>{if(ar&&!ar.isConnected&&(ar=null,on=null),!Ua()){ar?.remove(),ar=null,on=null;return}on||QT();let s=ar,l=on;if(!s||!l)return;let f=Na()!=="right"?we.firstChild:null;(f??we.lastChild)!==s&&we.insertBefore(s,f),s.style.display=zT()||nc>0?"none":"",l.setAttribute("aria-label",Je.expandLabel),l.setAttribute("aria-expanded",Pt?"true":"false"),ir&&Xn()},av=s=>{if(!qt)return;let l=s.target;l instanceof Node&&(ir?.contains(l)||ar?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||Ro({restoreFocus:!1}))};document.addEventListener("pointerdown",av,!0),fe.push(()=>{document.removeEventListener("pointerdown",av,!0),document.removeEventListener("pointermove",Wf),qa?.(),nl()});let Bf=null,qa=null,iv=16,lv=s=>{UT(Pf(s)),Xn(),Io()},YT=()=>{let s=I("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(Tf)),s.setAttribute("aria-valuemax",String(Ef)),s.addEventListener("pointerdown",l=>{let f=Ds;if(!f||l.button!==0)return;l.preventDefault(),qa?.();let g=l.clientX,v=f.getBoundingClientRect().width||el(),w=Na()==="right"?-1:1,O=v,z=e.ownerDocument;f.style.transition="none";let q=Y=>{O=Pf(v+w*(Y.clientX-g)),f.style.flex=`0 0 ${O}px`,s.setAttribute("aria-valuenow",String(O))},K=()=>{qa=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",K),z.removeEventListener("pointercancel",K),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}lv(O)};qa=K,z.addEventListener("pointermove",q),z.addEventListener("pointerup",K),z.addEventListener("pointercancel",K);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=Na()==="right"?-iv:iv,g=el(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Tf:l.key==="End"?Ef:null;v!==null&&(l.preventDefault(),lv(v))}),s},JT=(s,l)=>{if(!NT()||ol()){qa?.(),Bf?.remove();return}let f=Bf??YT();Bf=f,f.setAttribute("aria-label",Je.resizeLabel),f.setAttribute("aria-valuenow",String(el())),f.nextElementSibling!==l&&s.insertBefore(f,l)};Xn=()=>{at?.view.setRailSide(Na());let s=Na()==="right",l=ir;if(l){let z=on?on.getBoundingClientRect().bottom-le.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round(z))}px + ${oc})`,l.style.width=`${el()}px`,l.style.left=s?"":oc,l.style.right=s?oc:""}let f=Ds,g=Oa,v=Ji;if(!f||!g||!v)return;f.style.flex=`0 0 ${ol()?_T:el()}px`;let w="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":w,f.style.borderLeft=s?w:"";let O=s?v:f;g.firstElementChild!==O&&g.append(O,s?f:v),JT(g,s?f:v)};let dv=s=>{if(_a&&Ds){_a.replaceWith(s),_a=null,Xn();return}let l=I("div","persona-history-rail-shell");l.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=I("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let g=I("div","persona-history-rail-host");g.style.cssText="display:flex;min-height:0;overflow:hidden",le.insertBefore(l,we.parentNode===le?we:te);for(let v of Qb())v?.parentNode===le&&f.appendChild(v);l.append(g,f),g.appendChild(s),Oa=l,Ds=g,Ji=f,Xn()},ZT=()=>{if(Oa)return;let s=I("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",_a=s,dv(s),Io()},cv=()=>{_a&&(rc(),Io())},eE=s=>{let l=I("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${oc};display:flex;overflow:hidden;z-index:${ui-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,le.style.position="relative",le.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",Wf),ir=l,Xn(),rv()},rc=()=>{Zd?.(),ir&&(Os&&(Hf=Date.now()+150),document.removeEventListener("pointermove",Wf),ir.remove(),ir=null);let s=Oa;if(s){qa?.();for(let l of Qb())l&&s.contains(l)&&le.insertBefore(l,s);s.remove(),Oa=null,Ds=null,Ji=null,_a=null}},uv=s=>{Yi=s,s.id=xf,s.style.flex="1 1 auto",s.style.minHeight="0"},Df=s=>{uv(s),(Ft!=="rail"||qt)&&cv(),Ft!=="rail"?OT(s):qt?eE(s):dv(s)},sc=()=>{if(rl(),Sv(),!Pt||!at)return;let s=wf();if(s===Ft)return;let l=document.activeElement,f=l instanceof HTMLElement&&(at.element.contains(l)||Ko?.contains(l)===!0)?l:null;rc(),at.element.remove(),at.view.setHeaderPlacement("inline"),Ft=s,at.view.setPresentation(s),at.view.setCollapsed(ol()),at.requestRender(),at.element.isConnected||Df(at.element),f?.isConnected?f.focus():ac(),jt(),Io(),qr()},pv=(s,l)=>Ko?.querySelector(l)??s.querySelector(l),ac=()=>{let s=at?.element??Yi;if(!s)return;let l=pv(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=pv(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},sl=async s=>{if(!Bn()||Pt)return;let l=zo;if(!l)return;if(!qt&&Ua()&&kf()){rl();return}ic();let f=++Qi;Kd=s?.returnSurface??"conversation",yf=s?.invoker??mo;let g=Ua()&&!qt;g&&(nc+=1,rl(),ZT());let v;try{v=await ey()}catch{Yd(Je.openHistoryLabel),g&&(nc-=1,f===Qi&&(cv(),rl()));return}if(g&&(nc-=1),f!==Qi||Pt)return;zd={scope:Sf()},Ft=wf(),Pt=!0;let w=Ft==="panel"&&n.layout?.showHeader!==!1&&we.style.display!=="none"?"external":"inline",O=n.features?.history?.rowAvatar,z=Rf(),q=z?{hint:z.hint,aria:z.aria}:null,K={provider:l,context:zd,targetId:qb(),presentation:Ft,collapsible:ec(),collapsed:ol(),railSide:Na(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:qT(),onToggleCollapse:Zb,...q?{collapseShortcut:q}:{},headerPlacement:w,showScopeStatus:n.features?.history?.showScopeStatus!==!1,showDelete:n.features?.history?.showDelete!==!1,showDeleteAll:n.features?.history?.showDeleteAll!==!1,...n.features?.history?.listActions?.length?{listActions:n.features.history.listActions}:{},rowAvatar:O===!1?!1:typeof O=="string"?O:n.launcher?.iconUrl,activeConversationId:R.getActiveConversationId(),...n.features?.history?.grouping?{grouping:n.features.history.grouping}:{},...n.features?.history?.copy?{copy:n.features.history.copy}:{},...n.features?.history?.pageSize!==void 0?{pageSize:n.features.history.pageSize}:{},onSelect:Y=>_f(Y,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Y=>_s(Y),attachTooltip:ro,onStartNew:()=>Nf({focusComposer:!0}),onClose:()=>Ro(),onRequestDeleteConversation:Y=>Cv(Y),onRequestClearHistory:()=>aE(),...l.resetDevice?{onRequestResetIdentity:()=>iE()}:{}};at=zA({plugins:p,config:n,getPresentation:()=>Ft??"panel",getReturnSurface:()=>Kd,close:()=>Ro(),createView:({slots:Y,renderDom:se,onModelChange:ue,railSections:Ue})=>(Bs=v.createHistoryView({...K,railSections:$T(Ue),slots:Y,renderDom:se,onModelChange:ue,onAnnounce:Yd}),Bs),onElementChanged:(Y,se)=>{if(!se?.isConnected)return Df(Y);uv(Y),se.replaceWith(Y),Mf()}}),at.view.setNewConversationRequired(Gd.recovery==="new_conversation_required"),s?.focus!==!1&&(Ft!=="rail"||s?.keyboard===!0)&&ac(),jt(),Io(),qr(),$.emit("history:opened",{presentation:Ft,returnSurface:Kd,timestamp:Date.now()})},ic=()=>{},Ro=s=>{if(!Pt)return;Qi+=1;let l=Kd,f=yf,g=at,v=s?.restoreFocus!==!1;Pt=!1;let w=!1,O=null,z=()=>{if(!w){if(w=!0,ic=()=>{},O!==null&&clearTimeout(O),qt=!1,nl(),rc(),g?.dispose(),g?.view.destroy(),g?.element.remove(),at===g&&(at=null,Bs=null,Yi=null,Ft=null,zd=null,yf=null),jt(),Io(),qr(),v){let K=f??mo;K?.isConnected?K.focus():Is()}$.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},q=g&&g.element===g.view.element?g.view.playExit():null;if(!q){z();return}ic=z,O=setTimeout(z,LT),q.then(z)},fv=s=>{if(!(s.key!=="Escape"||!Pt||!at)){if(Ft==="rail"){let l=s.target;if(!(l instanceof Node)||!(at.element.contains(l)||qt&&ar?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),Ro()}};le.addEventListener("keydown",fv),fe.push(()=>le.removeEventListener("keydown",fv));let lc=null,mv=!1,al=()=>{if(!Pr)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&lc?.trim()||null;Pr.textContent=l??n.launcher?.title??"Chat Assistant";let f=Pr.closest(".persona-combo-btn");if(!f)return;let g=!s||R.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",g?"false":"true"),f.setAttribute("aria-haspopup",g?"true":"false"),g||f.setAttribute("aria-expanded","false"),f.style.cursor=g?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=g?"":"none")},tE=s=>{s!==lc&&(lc=s,al())},_s=s=>{mv=s?.starred===!0,tE(s&&s.title.trim()||null),al()};al(),le.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=R.getActiveConversationId();f&&(l==="delete"?Cv(f):l==="star"&&R.canUpdateConversations()&&Ff(f,{starred:!mv}).catch(()=>{}))});let dc=0,oE=250,cc=null,uc=()=>{cc&&clearTimeout(cc),cc=null};fe.push(uc);let gv=()=>{uc();let s=Rs;s&&(Xi=!0,s.hidden=!1,he.style.display="none",Ha())},pc=()=>{dc+=1,uc(),Rs&&(Rs.remove(),Rs=null,Xi=!1,he.style.removeProperty("display"),tn(Le,!1),Ha())},nE=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;he.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Of=(s,l)=>Q("div",{className:bo("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),hv=()=>Q("div",{className:"persona-conversation-loading-body"},Of("58%",!1),Of("72%",!0),Of("44%",!1)),yv=s=>{Rs?.remove(),Rs=s,s.hidden=!Xi,te.insertBefore(s,he),uc(),Xi||(cc=setTimeout(gv,oE)),tn(Le,!0)},rE=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:hv},l=null,f=p.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),yv(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Je.openConversationLoadingLabel}},l??hv()))},sE=s=>{let l=()=>{_f(s,{focusComposer:!0}).catch(()=>{})},f=Bn()?()=>{pc(),sl()}:void 0,g=(z,q)=>{let K=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return K.addEventListener("click",q),K},v=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:Je.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},g(Je.openConversationRetryLabel,l),f?g(Je.openConversationBackLabel,f):null)),w=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Je.openConversationErrorTitle,retryLabel:Je.openConversationRetryLabel,backLabel:Je.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),O=null;for(let z of p)if(z.renderHistoryOpenError){try{O=z.renderHistoryOpenError(w)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),O=null}if(O)break}yv(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},O??v())),gv()};$.on("history:closed",()=>{Rs&&tn(Le,!0)});let _f=async(s,{focusComposer:l=!1}={})=>{let f=Da(),g=!!at;at?.view.setActiveConversationId(s),pc();let v=dc;rE(),Pt&&(Ft==="panel"||qt)&&Ro({restoreFocus:!1}),Ma=!0;try{await R.openConversation(s,{scope:f})}catch(w){throw v===dc&&sE(s),w}finally{Ma=!1}v===dc&&(pc(),_t.clear(),bn(),Lo(),Qp()||Dd(),nE(),lr(),g||_s(null),$.emit("history:conversationOpened",{conversationId:s,title:lc,scope:f,timestamp:Date.now()}),l&&Is())},Nf=async({focusComposer:s=!1}={})=>{pc(),await R.startNewConversation({scope:Da()}),_s(null),_t.clear(),bn(),Lo(),Dd(),lr();let l=R.getActiveConversationId();at?.view.setActiveConversationId(l),$.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),Pt&&(Ft==="panel"||qt)&&Ro({restoreFocus:!1}),s&&Is()},Ff=async(s,l)=>{let f=await R.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return at?.view.applyConversationSummary(f),!at&&s===R.getActiveConversationId()&&_s(f),f},bv=async s=>{let l=Da(),f=R.getActiveConversationId()===s;await R.deleteConversation(s,{scope:l}),at?.view.removeConversationSummary(s),f&&(_s(null),_t.clear(),bn(),Lo(),lr()),$.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},vv=async s=>{let l=s?.scope??Da(),f=s?.allTargets?null:s?.targetId??qb(),g=await R.clearConversationHistory({...f?{targetId:f}:{},scope:l});return _s(null),_t.clear(),bn(),Lo(),lr(),$.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},xv=async()=>{if(!zo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await R.resetHistoryDevice()).remoteRevocationConfirmed}finally{_s(null),R.clearArtifacts(),_t.clear(),pf=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),W={},Me.syncFromMetadata(),H?.clear&&Hd(()=>H.clear(),"[AgentWidget] Failed to clear storage adapter:"),bn(),Lo(),lr(),Ro({restoreFocus:!1}),Is(),ke||Lt?.launcher.element.focus()}return Yd(s?Je.identityResetNotice:Je.identityResetUnconfirmedNotice),$.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},Uf=()=>Ln?be:le,Cv=async s=>await rp({host:Uf(),title:Je.deleteConversationConfirmTitle,description:Je.deleteConversationConfirm,confirmLabel:Je.deleteConversationConfirmLabel,cancelLabel:Je.confirmCancelLabel})?(await bv(s),"deleted"):"cancelled",aE=async()=>{let s=Da()==="verified-user";return await rp({host:Uf(),title:Je.clearHistoryConfirmTitle,description:s?Je.clearHistoryVerifiedConfirm:Je.clearHistoryConfirm,confirmLabel:Je.clearHistoryConfirmLabel,cancelLabel:Je.confirmCancelLabel})?(await vv(),"cleared"):"cancelled"},iE=async()=>{if(!await rp({host:Uf(),title:Je.resetIdentityConfirmTitle,description:Je.resetIdentityConfirm,confirmLabel:Je.resetIdentityConfirmLabel,cancelLabel:Je.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await xv();return{outcome:"reset",remoteRevocationConfirmed:l}},nn=I("button","persona-history-earlier");nn.type="button",nn.textContent=Je.showEarlierMessagesLabel,nn.setAttribute("data-persona-history-earlier",""),Object.assign(nn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let lr=()=>{if(!(Bn()&&!!Gd.nextMessageCursor&&!!R.getActiveConversationId())){nn.remove();return}nn.textContent=Je.showEarlierMessagesLabel,nn.parentNode!==te&&te.insertBefore(nn,te.firstChild)};nn.addEventListener("click",()=>{let s=R.getActiveConversationId(),l=Gd.nextMessageCursor;if(!s||!l||nn.disabled)return;nn.disabled=!0;let f=te.scrollHeight,g=te.scrollTop;R.loadOlderMessages(s,l,{scope:Da()}).then(()=>{te.scrollTop=g+(te.scrollHeight-f),Io()}).catch(()=>{}).finally(()=>{nn.disabled=!1,lr()})});let lE=()=>{let s=sa({ariaLabel:Je.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return s.button.addEventListener("click",l=>{if(!(!Bn()||Ub())){if(Pt){Ro();return}sl({invoker:s.button,keyboard:l.detail===0})}}),s},Sv=()=>{if(!Bn()){Wn?.remove(),mo=null,Wn=null;return}if(Wn&&!Wn.isConnected&&(mo=null,Wn=null),!mo&&we){let g=lE();mo=g.button,Wn=g.wrapper;let v=_e.clearChatButtonWrapper||_e.closeButtonWrapper;v?.parentNode&&we.contains(v)?v.parentNode.insertBefore(Wn,v):we.appendChild(Wn)}if(!mo||!Wn)return;let s=Ua()||Pt&&Ft==="rail";if(Wn.style.display=s?"none":"",s){document.activeElement===mo&&ac();return}let l=Ub();mo.disabled=l,mo.setAttribute("aria-disabled",l?"true":"false");let f=l?Je.openHistoryBusyLabel:Je.openHistoryLabel;mo.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(mo.removeAttribute("aria-expanded"),mo.removeAttribute("aria-controls")):(mo.setAttribute("aria-expanded",Pt?"true":"false"),mo.setAttribute("aria-controls",xf))},fc=!1,dE=()=>{let s=_e.clearChatButton;if(s){if(Bn()){fc||(vf=s.getAttribute("aria-label")??"",fc=!0),s.setAttribute("aria-label",Je.newConversationLabel),s.removeAttribute("title");return}fc&&(fc=!1,vf&&s.setAttribute("aria-label",vf))}},qr=()=>{Je=ny(n.features?.history?.copy),Sv(),rl(),dE(),lr()};bp=qr,vy=s=>{Gd=s,at?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),Gi(s.sendBlocked||Vo),lr()},xy=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(_t.clear(),bn(),Lo()),Yd(s.message),at?.view.refresh()},zb(),qr(),fe.push(()=>{Xd?.(),Qd?.(),Qi+=1,ic(),at?.dispose(),at?.view.destroy(),at=null}),n.clientToken&&(n.features?.history?.enabled===!0||n.sessionInit==="mount")&&R.initClientSession().then(()=>{if(Bn())return R.reconcileBootConversation({scope:Sf()})}).then(()=>{lr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)});let qf=()=>R.warmClientSession(),wv=s=>{let l=n.sessionInit??"input",f=et?.input??ie,g=s.target;f&&(s.type==="input"?(l==="input"||l==="focus")&&g===f&&s.inputType&&f.value.trim():l==="focus"&&(s.type==="keyup"?g===f&&s.key==="Tab":(et?.form??To)?.contains(g)))&&qf()},Av=["input","pointerdown","keyup"];Av.forEach(s=>e.addEventListener(s,wv));let Mv,Vf,Tv=()=>{let s=Vf;Vf=void 0;try{typeof s=="function"&&s()}catch{}},Ev=()=>{let s=n.clientToken&&typeof n.sessionInit=="function"?n.sessionInit:void 0;if(s!==Mv){Tv(),Mv=s;try{Vf=s?.({warm:qf,mount:e})}catch{}}};Ev(),fe.push(()=>{Av.forEach(s=>e.removeEventListener(s,wv)),Tv()}),(J||n.onSSEEvent)&&R.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),hp(s,l)});let Pv=()=>{let s=n.resume??(F?rr.getStoredResumableHandle?.():null);s&&typeof n.reconnectStream=="function"&&R.resumeFromHandle(s)};oe?oe.then(s=>{if(s){if(s.metadata&&(W=ry(s.metadata),Me.syncFromMetadata()),s.messages?.length){Ma=!0;try{R.hydrateMessages(s.messages)}finally{Ma=!1}Fd()}s.artifacts?.length&&R.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),vb(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{nf=!0,V(),Pv()}):(vb(ce),Pv());let cE=()=>{!De()||ke||!(n.launcher?.composerBar?.expandOnSubmit??!0)||mt(!0,"auto")},uE=(s,l)=>s?l?{refs:[...s.refs,...l.refs],finalize:async()=>{let[f,g]=await Promise.allSettled([s.finalize(),l.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),g.status==="fulfilled"?v.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),GI(v)}}:s:l,$f=()=>{let l=ie.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},dr=!1,Ns=null,mc=()=>{ie.value="",ie.style.height="auto",En(),ll()},jf="data-persona-composer-notice",Va=null;function pE(s){md(s),!(De()||!Ye)&&(Ye.hasAttribute(Ei)||(Ye.setAttribute(jf,""),Ye.setAttribute("role","status"),Ye.setAttribute("aria-live","polite"),Ye.textContent=s,Qs(Ye,n.statusIndicator??{},"idle"),Va&&clearTimeout(Va),Va=setTimeout(()=>{if(Va=null,!!Ye?.hasAttribute(jf)&&(Ye.removeAttribute(jf),Ye.removeAttribute("role"),Ye.removeAttribute("aria-live"),y)){let l=R.getStatus();Pi(Ye,vp(l),n.statusIndicator??{},l)}},4e3)))}function fE(){let s=ye.getState().pendingSubmission;s&&(ba(void 0),ie&&(ie.value=s.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),En()),s.options.selectedModelId&&(ye.setSelectedModelId(s.options.selectedModelId),Lr?.repaint()),s.options.activeModeIds?.length&&bd(s.options.activeModeIds),s.options.quote&&Pn(s.options.quote),ie?.focus())}let mE=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},kv=(s={})=>{let l=(s.overrideText??ie?.value??"").trim();return s.resolveInlineCommand&&l?(Ot?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>Lv(s,l,f)):Lv(s,l,null)},Lv=(s,l,f)=>{if(f?.kind==="action"){mc(),Ot?.clear(),ms();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,w=s.pending?.contentParts,O=(nt?.hasAttachments()??!1)||(w?.length??0)>0;if(!GS({text:v,hasAttachments:O,attachmentsReady:nt?.isReady()??!0,hasMentions:Ot?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Hn(),sendDisabled:Ls()}))return;let z=R.isStreaming()?Pp():"block";if(z==="defer-one"&&!s.pending){if(ye.getState().pendingSubmission){pE("One message is already queued. Edit or remove it first.");return}gE({intent:s,sendText:v,serverMentions:g});return}let q={text:v,mentionRefs:[...Ot?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:$f(),options:{...ye.getState().selectedModelId&&{selectedModelId:ye.getState().selectedModelId},...ye.getState().activeModeIds.length>0&&{activeModeIds:[...ye.getState().activeModeIds]},...ye.getState().quote&&{quote:{...ye.getState().quote}}},viaVoice:s.viaVoice};s.pending&&(q.options={...s.pending.options},q.contentSegments=s.pending.contentSegments,q.mentionRefs=[...s.pending.mentionRefs],q.viaVoice=s.pending.viaVoice);let K=()=>{if(w?.length)return[...w];if(!nt?.hasAttachments())return;let tt=[...nt.getContentParts()];return q.text&&tt.push(un(q.text)),tt};q.contentParts=K();let Y=()=>{As(),cE();let tt=Ot?.collectForSubmit()??null,Ho=uE(tt,g),Ct=K();s.consumeDraft!==!1&&mc();let Mt={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},ho=z==="interrupt";ho&&R.cancel(),R.sendMessage(q.text,{contentParts:Ct,mentions:Ho??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:Mt,...q.options.quote&&{quote:q.options.quote},...ho&&{interrupt:!0}}),nt?.hasAttachments()&&nt.clearAttachments(),tt&&Ot?.clear(),ms();let Rt=ye.getState().activeModeIds,lt=WS(Rt,n.composer?.modes);lt.length!==Rt.length&&bd(lt),ye.getState().quote&&Pn(void 0),Bd(),Hp.release(),mn()},se=n.composer?.onBeforeSend;if(!se){Y();return}let ue=new AbortController;Ns=ue;let Ue=tt=>{if(Ns=null,tt.status==="error"){mE(tt.error);return}tt.status==="proceed"&&Y()},rt=XS(se,q,ue.signal);if(!(rt instanceof Promise)){Ue(rt);return}return ye.setPreparing(!0),rt.then(Ue).finally(()=>ye.setPreparing(!1))};function gE(s){let l=ye.getState(),f=nt?.hasAttachments()??!1,g=f?[...nt.getContentParts()]:[];f&&s.sendText&&g.push(un(s.sendText));let v=Jg({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Ot?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:$f(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});ba(v),s.intent.consumeDraft!==!1&&mc(),f&&nt.clearAttachments(),Ot?.clear(),ms(),l.quote&&Pn(void 0),Bd(),Hp.release(),mn(),md("Message queued. It sends when the response finishes.")}function hE(){let s=ye.getState().pendingSubmission;s&&(ba(void 0),hc(s.text,{consumeDraft:!1,pending:s}))}function yE(s){if(n.messageActions?.showEdit!==!0)return;let l=R.getMessages().find(f=>f.id===s);!l||!Lg(l)||ws!==s&&(As(),ws=s,Wr=NS({messageId:s,initialText:l.content,onSave:f=>bE(s,f),onCancel:()=>As()}),_t.delete(s),Zo(he,R.getMessages(),U),Wr.focus())}function bE(s,l){let f=Wr;if(ws=null,Wr=null,f?.destroy(),_t.delete(s),!R.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Zo(he,R.getMessages(),U);return}Io()}function vE(s){if(R.isStreaming())return;let l=kg(R.getMessages(),s);l&&(As(),R.resubmitFrom(l,{reason:"retry"})&&Io())}vd={regenerate:vE,edit:yE,quote:s=>{let f=R.getMessages().find(g=>g.id===s)?.content?.trim();f&&(Pn({text:f,messageId:s}),ie?.focus())}};let il=async s=>{if(!dr){dr=!0;try{await kv({resolveInlineCommand:!0,...s})}finally{dr=!1}}};function gc(s){Ls()||(mc(),hc(s,{consumeDraft:!1}))}let hc=(s,l)=>{if(dr)return;dr=!0;let f=()=>{dr=!1};try{let g=kv({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},xE=s=>{if(s.preventDefault(),R.isStreaming()){R.cancel(),Qt?.reset(),ft?.update();return}dr||il()},CE=()=>n.features?.composerHistory!==!1,zf={...ah},Kf=!1,ll=()=>{zf={...ah}},SE=()=>R.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),wE=s=>{if(!ie)return;Kf=!0,ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),Kf=!1;let l=ie.value.length;ie.setSelectionRange(l,l)},AE=s=>{Kf||(s.isComposing||Ot?.handleInput(s.inputType??void 0),ll())},ME=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Nl(ie)}),TE=s=>{if(ie&&!Hn()&&!(!s.isComposing&&Ot?.handleKeydown(s))){if(CE()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=ie.selectionStart===0&&ie.selectionEnd===0,f=Cw({direction:s.key==="ArrowUp"?"up":"down",history:SE(),currentValue:ie.value,atStart:l,state:zf});if(zf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&wE(f.value);return}}if(bS(s,ME())){if(R.isStreaming()){if(s.preventDefault(),Pp()==="block"||dr||Ls())return;ll(),il();return}if(dr){s.preventDefault();return}if(Ls()){s.preventDefault();return}ll(),s.preventDefault(),Se.click()}}},Iv=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(le)){if(Ns){Ns.abort(),Ns=null,s.preventDefault(),s.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),Qt?.reset(),ft?.update(),ll(),s.preventDefault(),s.stopImmediatePropagation())}},EE=async s=>{if(n.attachments?.enabled!==!0||!nt||Hn())return;let l=$I(s.clipboardData);l.length!==0&&(s.preventDefault(),await nt.handleFiles(l))},rn=null,Dn=!1,$a=null,wt=null,Gf=()=>n.voiceRecognition?.completionBehavior==="review";function Fs(s){re?.setAttribute("data-state",s),s==="recording"?kE():Jf()}let Rv="--persona-voice-level",Xf=.5,ja=null,Qf=-1,yc=0,Hv=()=>{let s=[],l=Uo??re?.parentElement??null;return l&&s.push(l),Le&&s.push(Le),s},Yf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==Qf){Qf=l;for(let f of Hv())f.style.setProperty(Rv,String(l))}},PE=()=>{Qf=-1,yc=0;for(let s of Hv())s.style.removeProperty(Rv)};function kE(){if(ja!==null)return;if(typeof requestAnimationFrame!="function"){Yf(y?R.getVoiceLevel()??Xf:Xf);return}let s=()=>{ja=requestAnimationFrame(s);let l=y?R.getVoiceLevel():null;if(l===null){Yf(Xf);return}yc+=(l-yc)*.3,Yf(yc)};ja=requestAnimationFrame(s)}function Jf(){ja!==null&&(cancelAnimationFrame(ja),ja=null),PE()}let Wv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,bc=(s="user")=>{if(Dn||R.isStreaming())return;let l=Wv();if(!l)return;rn=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;rn.continuous=f.provider?.browser?.continuous??!0,rn.interimResults=!0,rn.lang=f.provider?.browser?.language??"en-US";let v=ie.value;rn.onresult=w=>{let O="",z="";for(let K=0;K<w.results.length;K++){let Y=w.results[K],se=Y[0].transcript;Y.isFinal?O+=se+" ":z=se}let q=v+O+z;ie.value=q,En(),$a&&clearTimeout($a),(O||z)&&($a=window.setTimeout(()=>{if(ie.value.trim()&&rn&&Dn){if(Vr(),Gf())return;il({viaVoice:!0})}},g))},rn.onerror=w=>{w.error!=="no-speech"&&Vr()},rn.onend=()=>{if(Dn){let w=ie.value.trim();!Gf()&&w&&w!==v.trim()&&il({viaVoice:!0}),Vr()}};try{if(rn.start(),Dn=!0,Xe.active=!0,s!=="system"&&(Xe.manuallyDeactivated=!1),or(s),yn(),mn(),re){let w=n.voiceRecognition??{};wt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||Co};let O=w.recordingBackgroundColor,z=w.recordingIconColor,q=w.recordingBorderColor;if(re.classList.add("persona-voice-recording"),Fs("recording"),re.style.backgroundColor=O??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let K=re.querySelector("svg");K&&K.setAttribute("stroke",z)}q&&(re.style.borderColor=q),re.setAttribute("aria-label","Stop voice recognition")}}catch{Vr("system")}},Vr=(s="user")=>{if(Dn){if(Dn=!1,$a&&(clearTimeout($a),$a=null),rn){try{rn.stop()}catch{}rn=null}if(Xe.active=!1,or(s),yn(),mn(),re){if(re.classList.remove("persona-voice-recording"),Fs("idle"),wt){re.style.backgroundColor=wt.backgroundColor,re.style.color=wt.color,re.style.borderColor=wt.borderColor;let l=re.querySelector("svg");l&&l.setAttribute("stroke",wt.color||"currentColor"),wt=null}re.setAttribute("aria-label","Start voice recognition")}}},Zf=()=>{if(!re||wt)return;let s=n.voiceRecognition??{};wt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||Co}},em=(s,l)=>{if(!re)return;let f=re.querySelector("svg");f&&f.remove();let g=wt?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||Co),v=ae(s,g,l,1.5);v&&re.appendChild(v)},vc=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},za=()=>{if(!re)return;Zf();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(vc(),re.classList.add("persona-voice-recording"),Fs("recording"),re.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=re.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(re.style.borderColor=g),re.setAttribute("aria-label","Stop voice recognition")},LE=()=>{if(!re)return;Zf();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??wt?.color??"",v=s.processingBackgroundColor??wt?.backgroundColor??"",w=s.processingBorderColor??wt?.borderColor??"";vc(),re.classList.add("persona-voice-processing"),Fs("processing"),re.style.backgroundColor=v,re.style.borderColor=w;let O=g||"currentColor";re.style.color=O,em(f,O),re.setAttribute("aria-label","Processing voice input"),l==="none"&&(re.style.cursor="default")},IE=()=>{if(!re)return;Zf();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??wt?.color??"":wt?.color??""),w=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),O=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":wt?.borderColor??"");vc(),re.classList.add("persona-voice-speaking"),Fs("speaking"),re.style.backgroundColor=w,re.style.borderColor=O;let z=v||"currentColor";re.style.color=z,em(g,z);let q=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",q),l==="none"&&(re.style.cursor="default"),l==="barge-in"&&re.classList.add("persona-voice-recording")},cr=()=>{re&&(vc(),Fs("idle"),wt&&(re.style.backgroundColor=wt.backgroundColor??"",re.style.color=wt.color??"",re.style.borderColor=wt.borderColor??"",em(wt.iconName,wt.color||"currentColor"),wt=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},tm=()=>{if(!Hn()){if(vo(n.voiceRecognition?.provider)){let s=R.getVoiceStatus(),l=R.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,yn(),or("user"),cr()});return}R.toggleVoice().then(()=>{Xe.active=R.isVoiceActive(),Xe.manuallyDeactivated=!R.isVoiceActive(),yn(),or("user"),R.isVoiceActive()?za():cr()});return}if(Dn){let s=ie.value.trim();Xe.manuallyDeactivated=!0,yn(),Vr("user"),s&&!Gf()&&il()}else Xe.manuallyDeactivated=!1,yn(),bc("user")}};kp=tm;let Bv=()=>R.prewarmVoice(),Dv=()=>{let s=n.voiceRecognition;return s?.enabled!==!0?!1:s.prewarm??(n.clientToken?"hover":!1)},Ov=s=>{Dv()==="hover"&&re?.contains(s.target)&&Bv()},_v=["pointerover","pointerdown","focusin"];_v.forEach(s=>e.addEventListener(s,Ov));let Nv,Fv=null,om,Uv=()=>{let s=om;om=void 0;try{typeof s=="function"&&s()}catch{}},nm=()=>{let s=Dv(),l=typeof s=="function"&&re?s:void 0,f=l?re:null;if(!(l===Nv&&f===Fv)&&(Uv(),Nv=l,Fv=f,!(!l||!f)))try{om=l({warm:Bv,micButton:f,mount:e})}catch{}};nm(),fe.push(()=>{_v.forEach(s=>e.removeEventListener(s,Ov)),Uv()}),re&&fe.push(()=>{vo(n.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),cr()):Vr("system")});let RE=$.on("assistant:complete",()=>{ye.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||hE()},0)});fe.push(RE);let HE=$.on("assistant:complete",()=>{hb&&(Xe.active||Xe.manuallyDeactivated||hb==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(vo(n.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Xe.active=R.isVoiceActive(),or("auto"),R.isVoiceActive()&&za()}):bc("auto"))},600))});fe.push(HE);let WE=$.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});fe.push(WE);let qv=()=>{mt(!ke,"user")},Lt=null,go=null;if(N&&!De()){let{instance:s,element:l}=Bh({config:n,plugins:p,onToggle:qv});Lt=s,s||(go=l)}Lt?e.appendChild(Lt.element):go&&e.appendChild(go),Ki(),Cs(),Vd(),df(),Gi(R.isStreaming()),Qp()||(qo()==="follow"?_r(!0):Dd()),ZM(),Ve&&(!N||De()?setTimeout(()=>Is(),0):ke&&setTimeout(()=>Is(),200));let $r=null,Vv=()=>{$r&&($r.disconnect(),$r.observe(Le),$r.observe(le),$r.observe(Jt))},$v=Wi(),dl=()=>{if(De()){fs(),Ki();return}let s=yt(n),l=n.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,g=n.launcher?.mobileFullscreen??!0,v=n.launcher?.mobileBreakpoint??640,w=f.innerWidth<=v,O=g&&w&&N;try{if(O){gs(),_i=Ed();return}let z=!1;_o&&(_o=!1,gs(),z=!0);let q=Ed();if(!z&&q!==_i&&(gs(),z=!0),_i=q,z&&wd(),!N&&!s){be.style.height="",be.style.width="";return}if(!l&&!s){let K=ua(n);be.style.width=K.width,be.style.maxWidth=K.maxWidth}Td(),eb()}finally{fs(),yd();let z=Wi();if(z!==$v&&($v=z,Ha(),Cs()),Ki(),ke&&N){let K=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),Y=n.launcher?.sidebarMode??!1,se=n.launcher?.mobileFullscreen??!0,ue=yt(n)&&se&&K,Ue=Y||se&&K&&N||ue;if(Ue&&!Rn){let rt=e.getRootNode(),tt=rt instanceof ShadowRoot?rt.host:e.closest(".persona-host");tt&&!In&&(In=ph(tt,n.launcher?.zIndex??co)),Rn=fh(e.ownerDocument)}else Ue||(In?.(),In=null,Rn?.(),Rn=null)}}};dl();let xc=e.ownerDocument.defaultView??window;if(xc.addEventListener("resize",dl),fe.push(()=>xc.removeEventListener("resize",dl)),typeof ResizeObserver<"u"){$r=new ResizeObserver(()=>{yd()}),Vv(),fe.push(()=>{$r?.disconnect(),$r=null});let s=new ResizeObserver(()=>{sc()});s.observe(le),fe.push(()=>s.disconnect())}xc.addEventListener("resize",sc),fe.push(()=>xc.removeEventListener("resize",sc)),jo=te.scrollTop;let jv=zn(te),zv=()=>{Zy();let s=te.scrollTop,l=zn(te),f=l<jv;if(jv=l,!kr()){jo=s,jt();return}let{action:g,nextLastScrollTop:v}=kw({following:$o.isFollowing(),currentScrollTop:s,lastScrollTop:jo,nearBottom:ra(te,er),userScrollThreshold:XM,isAutoScrolling:ko||kd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(jo=v,g==="resume"){Od()||Lo();return}g==="pause"&&La()};if(te.addEventListener("scroll",zv,{passive:!0}),fe.push(()=>te.removeEventListener("scroll",zv)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{aT(),lg(he)});s.observe(he),s.observe(te),fe.push(()=>s.disconnect())}let Kv=()=>{kr()&&$o.isFollowing()&&Od()&&La()},Gv=te.ownerDocument;Gv.addEventListener("selectionchange",Kv),fe.push(()=>{Gv.removeEventListener("selectionchange",Kv)});let BE=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Xv=s=>{BE.has(s.key)&&(Or(),Sy()&&kr()&&$o.isFollowing()&&La())},Qv=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(Or(),Sy()&&kr()&&$o.isFollowing()&&La())};te.addEventListener("keydown",Xv),te.addEventListener("focusin",Qv),fe.push(()=>{te.removeEventListener("keydown",Xv),te.removeEventListener("focusin",Qv)});let Yv=s=>{if(s.deltaY!==0&&Or(),!kr())return;let l=Lw({following:$o.isFollowing(),deltaY:s.deltaY,nearBottom:ra(te,er),resumeWhenNearBottom:!0});l==="pause"?La():l==="resume"&&!Od()&&Lo()};te.addEventListener("wheel",Yv,{passive:!0}),te.addEventListener("touchmove",Or,{passive:!0}),te.addEventListener("pointerdown",Or,{passive:!0}),fe.push(()=>{te.removeEventListener("touchmove",Or),te.removeEventListener("pointerdown",Or)}),fe.push(()=>te.removeEventListener("wheel",Yv)),Ut.addEventListener("click",()=>{bn(),te.scrollTop=te.scrollHeight,jo=te.scrollTop,Lo(),_r(!0),jt()}),fe.push(()=>Ut.remove()),fe.push(()=>{Cb(),bn()});let Jv=()=>{qe&&(vs&&(qe.removeEventListener("click",vs),vs=null),Qe()?(qe.style.display="",vs=()=>{mt(!1,"user")},qe.addEventListener("click",vs)):qe.style.display="none")};Jv(),(()=>{let{clearChatButton:s}=_e;s&&s.addEventListener("click",()=>{if(Bn()){Nf({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}R.clearMessages(),n.layout?.topFade&&(te.scrollTop=0),te.removeAttribute("data-persona-top-fade"),_t.clear(),Lo(),os(_e.composerOverlay);try{localStorage.removeItem(Ti),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ti}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ti)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),H?.clear&&Hd(()=>H.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},Me.syncFromMetadata(),nt?.clearAttachments(),Bd(),ba(void 0),Pn(void 0),As(),pt?.clear(),Qt?.reset(),ft?.update()})})();let Zv=[["keydown",TE],["input",AE],["input",En],["input",ms],["keyup",ms],["paste",EE],["focus",_M]],ex=s=>{if(s)for(let[l,f]of Zv)et?.addListener(s,l,f)},DE=s=>{if(s)for(let[l,f]of Zv)et?.removeListener(s,l,f)},tx=()=>{et&&(et.addListener(et.form,"submit",xE),et.addListener(et.footer,"click",ms),ex(ie),re&&et.addListener(re,"click",tm),nm())};tx();let ox=()=>{Ot?.onComposerSwap((s,l)=>{DE(l),ie=s,et&&(et.input=s),ex(s),Ip(),tf(),En()})};ox();let rm=!1;function nx(){if(!rm){rm=!0;try{let s=ie?.value??"",l=Le.ownerDocument??document,f=ie?l.activeElement===ie:!1;Jf(),et?.destroy(),et=null,Ot?.destroy(),Ot=null;let g=null,v=()=>(g=De()?Ku({config:n}):da({config:n}),g.footer),w=Ry(v)??v();No.replaceComposer(w),Le=No.composer.footer;let O=g!==null&&w===g.footer;xa=!O,Cy=O?g.setSendButtonMode:()=>{},Iy(Le),Wy(Le),By(),Dy(),Oy(),ox(),_y(),Rp(),Ny(),tx();let z=bs.indexOf(Zn);if(Zn.destroy(),Zn=td(Er),z>=0&&(bs[z]=Zn),ie&&(ie.value=s),En(),ms(),Vd(),Cs(),Gi(R.isStreaming()),n.statusIndicator?.mode==="transient"&&!De()){let q=R.getStatus();Pi(Ye,vp(q),n.statusIndicator,q)}Xe.active&&Fs("recording"),gs(),Vv(),fs(),mn(),Ud(),f&&ie?.focus()}finally{rm=!1}}}let cl=e.ownerDocument??document;cl.addEventListener("keydown",Iv,!0);let rx=()=>{zp()},sx=()=>{cl.visibilityState==="hidden"&&zp()};typeof window<"u"&&(window.addEventListener("pagehide",rx),cl.addEventListener("visibilitychange",sx),fe.push(()=>{window.removeEventListener("pagehide",rx),cl.removeEventListener("visibilitychange",sx)}));let ax="persona-attachment-drop-active",ul=0,sm=()=>{ul=0,le.classList.remove(ax)},Ka=()=>n.attachments?.enabled===!0&&nt!==null&&!Hn(),ix=s=>{!cp(s.dataTransfer)||!Ka()||(ul++,ul===1&&le.classList.add(ax))},lx=s=>{!cp(s.dataTransfer)||!Ka()||(ul--,ul<=0&&sm())},dx=s=>{!cp(s.dataTransfer)||!Ka()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},cx=s=>{if(!cp(s.dataTransfer)||!Ka())return;s.preventDefault(),s.stopPropagation(),sm();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&nt.handleFiles(l)},jr=!0;le.addEventListener("dragenter",ix,jr),le.addEventListener("dragleave",lx,jr),e.addEventListener("dragover",dx,jr),e.addEventListener("drop",cx,jr);let Cc=e.ownerDocument,ux=s=>{Ka()&&s.preventDefault()},px=s=>{Ka()&&s.preventDefault()};Cc.addEventListener("dragover",ux),Cc.addEventListener("drop",px),fe.push(()=>{et?.destroy(),et=null,Jf(),kn?.destroy(),kn=null,Yn?.destroy(),Yn=null,Ir?.destroy(),Ir=null,Rr?.destroy(),Rr=null,Lr=null,Ep=null,zp(),qi.destroy(),Va&&clearTimeout(Va),As(),Ns?.abort(),Ns=null,nt?.destroy(),nt=null,ye.destroy(),cl.removeEventListener("keydown",Iv,!0),Ot?.destroy()}),fe.push(()=>{le.removeEventListener("dragenter",ix,jr),le.removeEventListener("dragleave",lx,jr),e.removeEventListener("dragover",dx,jr),e.removeEventListener("drop",cx,jr),Cc.removeEventListener("dragover",ux),Cc.removeEventListener("drop",px),sm()}),fe.push(()=>{R.cancel()}),Lt?fe.push(()=>{Lt?.destroy()}):go&&fe.push(()=>{go?.remove()});let It={update(s){let l=n.future?.v5Defaults===!0,f=n.toolCall,g=n.messageActions,v=n.layout?.messages,w=n.colorScheme,O=n.loadingIndicator,z=n.iterationDisplay,q=n.features?.showReasoning,K=n.features?.showToolCalls,Y=n.features?.toolCallDisplay,se=n.features?.reasoningDisplay,ue=n.features?.streamAnimation?.type,Ue=n.features?.history?.enabled===!0,rt=n.features?.history?.provider,tt=n.getIdentityProof,Ho=n.clientToken,Ct=n.contextMentions;n=op({...n,features:u},s),u=n.features,n=sd(n),c(),Np(),na(e,n),nd(e,n),rd(e,n),Xn(),hn(),n.colorScheme!==w&&tb();let Mt=ad.getForInstance(n.plugins);p.length=0,p.push(...Mt),ev(),N=n.launcher?.enabled??!0,Oe=n.launcher?.autoExpand??!1,G=n.features?.showReasoning??!0,Z=n.features?.showToolCalls??!0,pe=n.features?.scrollToBottom??{};let ho=qo();xe=n.features?.scrollBehavior??{},ho!==qo()&&(bn(),Lo()),gb(),My(),jt();let Rt=J;if(J=n.features?.showEventStreamToggle??!1,J&&!Rt){if(pt||(ud(),R.setSSEEventCallback((ee,ze)=>{n.onSSEEvent?.(ee,ze),hp(ee,ze)})),!st&&we){let ee=n.features?.eventStream?.classNames,ze="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");st=I("button",ze),st.style.width="28px",st.style.height="28px",st.style.color=So.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let Ke=Tt(Ga,"18px","currentColor",1.5);Ke&&st.appendChild(Ke);let ot=_e.clearChatButtonWrapper,bt=_e.closeButtonWrapper,io=ot||bt;io&&io.parentNode===we?we.insertBefore(st,io):we.appendChild(st),st.addEventListener("click",()=>{fn?va():Lp()})}}else!J&&Rt&&(va(),st&&(st.remove(),st=null),pt?.clear(),Ze?.destroy(),pt=null,Ze=null,Qt?.reset(),Qt=null,Et=null);if(n.launcher?.enabled===!1&&Lt&&(Lt.destroy(),Lt=null),n.launcher?.enabled===!1&&go&&(go.remove(),go=null),n.launcher?.enabled!==!1&&!Lt&&!go){let{instance:ee,element:ze}=Bh({config:n,plugins:p,onToggle:qv});Lt=ee,ee||(go=ze),e.appendChild(ze)}Lt&&Lt.update(n),al(),cs&&n.launcher?.subtitle!==void 0&&(cs.textContent=n.launcher.subtitle);let lt=n.layout?.header;if(lt?.layout!==Xt&&we){let ee=lt?yi(n,lt,{showClose:Qe(),onClose:()=>mt(!1,"user")}):Sr({config:n,showClose:Qe(),onClose:()=>mt(!1,"user")});No.replaceHeader(ee),we=No.header.element,kt=No.header.iconHolder,Pr=No.header.headerTitle,cs=No.header.headerSubtitle,qe=No.header.closeButton,Xt=lt?.layout,al()}else if(lt){if(kt&&(kt.style.display=lt.showIcon===!1?"none":""),Pr&&(Pr.style.display=lt.showTitle===!1?"none":""),cs&&(cs.style.display=lt.showSubtitle===!1?"none":""),qe){let ee=Qe()&<.showCloseButton!==!1;qe.style.display=ee?"":"none"}if(_e.clearChatButtonWrapper){let ee=lt.showClearChat;if(ee!==void 0){_e.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:ze}=_e;ze&&!ze.classList.contains("persona-absolute")&&(ee?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let _n=n.layout?.showHeader!==!1;we&&(we.style.display=_n?"":"none");let an=n.layout?.showFooter!==!1;Le&&(Le.style.display=an?"":"none"),fs(),jt(),N!==uo?N?mt(Oe,"auto"):(ke=!0,Ki()):Oe!==Mo&&mt(Oe,"auto"),Mo=Oe,uo=N,dl(),Jv();let Nn=JSON.stringify(n.toolCall)!==JSON.stringify(f),vn=JSON.stringify(n.messageActions)!==JSON.stringify(g),Kr=JSON.stringify(n.layout?.messages)!==JSON.stringify(v),pl=n.loadingIndicator?.render!==O?.render||n.loadingIndicator?.renderIdle!==O?.renderIdle||n.loadingIndicator?.showBubble!==O?.showBubble,Us=n.iterationDisplay!==z,D=(n.features?.showReasoning??!0)!==(q??!0)||(n.features?.showToolCalls??!0)!==(K??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(Y)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(se);(n.future?.v5Defaults===!0!==l||Nn||vn||Kr||pl||Us||D)&&R&&(Ms++,Zo(he,R.getMessages(),U));let Re=n.features?.streamAnimation?.type;if(Re!==ue&&Re&&Re!=="none"){let ee=qp(Re,n.features?.streamAnimation?.plugins);ee&&Jl(ee,e)}let ne=n.launcher??{},dt=ne.headerIconHidden??!1,Nt=n.layout?.header?.showIcon,po=dt||Nt===!1,Zt=ne.headerIconName,gt=ne.headerIconSize??Sl;if(kt){let ee=we,ze=ee?.querySelector(".persona-flex-col");if(po)kt.style.display="none",ee&&ze&&!ee.contains(ze)&&ee.insertBefore(ze,ee.firstChild);else{if(kt.style.display="",kt.style.height=gt,kt.style.width=gt,ee&&ze&&(ee.contains(kt)?kt.nextSibling!==ze&&(kt.remove(),ee.insertBefore(kt,ze)):ee.insertBefore(kt,ze)),Zt){let ot=parseFloat(gt)||24,bt=ae(Zt,ot*.6,"currentColor",1);bt?(bt.style.width=`calc(${ot}px * var(--persona-components-header-iconScale, 0.6))`,bt.style.height=`calc(${ot}px * var(--persona-components-header-iconScale, 0.6))`,kt.replaceChildren(bt)):kt.textContent=ne.agentIconText??"\u{1F4AC}"}else if(ne.iconUrl){let ot=kt.querySelector("img");if(ot)ot.src=ne.iconUrl,ot.style.height=gt,ot.style.width=gt;else{let bt=document.createElement("img");bt.src=ne.iconUrl,bt.alt="",bt.className="persona-rounded-xl persona-object-cover",bt.style.height=gt,bt.style.width=gt,kt.replaceChildren(bt)}}else{let ot=kt.querySelector("svg"),bt=kt.querySelector("img");(ot||bt)&&kt.replaceChildren(),kt.textContent=ne.agentIconText??"\u{1F4AC}"}let Ke=kt.querySelector("img");Ke&&(Ke.style.height=gt,Ke.style.width=gt)}}let Ht=n.layout?.header?.showTitle,zt=n.layout?.header?.showSubtitle;if(Pr&&(Pr.style.display=Ht===!1?"none":""),cs&&(cs.style.display=zt===!1?"none":""),qe){let ee=Qe()&&n.layout?.header?.showCloseButton!==!1;if(qe.style.display=ee?"":"none",!De()){let to=ne.closeButtonSize??"";qe.style.height=to,qe.style.width=to,qe.style.minWidth=to,qe.style.minHeight=to}let ze=ne.closeButtonPlacement??"inline",{closeButtonWrapper:Ke}=_e,ot=ze==="top-right",bt=Ke?.classList.contains("persona-absolute");if(Ke&&ot!==bt)if(Ke.remove(),ot){Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let to=Ji??le;to.style.position="relative",to.appendChild(Ke)}else{let to=ne.clearChat?.placement??"inline",oo=ne.clearChat?.enabled??!0;Ke.className=oo&&to==="inline"?"":"persona-ml-auto",we&&we.appendChild(Ke)}if(qe.style.color=ne.closeButtonColor||So.actionIconColor,ne.closeButtonBackgroundColor?(qe.style.backgroundColor=ne.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let to=ne.closeButtonBorderWidth||"0px",oo=ne.closeButtonBorderColor||"transparent";qe.style.border=`${to} solid ${oo}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");ne.closeButtonBorderRadius?(qe.style.borderRadius=ne.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),ne.closeButtonPaddingX?(qe.style.paddingLeft=ne.closeButtonPaddingX,qe.style.paddingRight=ne.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),ne.closeButtonPaddingY?(qe.style.paddingTop=ne.closeButtonPaddingY,qe.style.paddingBottom=ne.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom=""),$u(qe,ne.closeButtonIconName??"x",{iconSize:De()?Ih:void 0,iconText:ne.closeButtonIconText??"\xD7"});let io=ne.closeButtonTooltipText??"Close chat",Cn=ne.closeButtonShowTooltip??!0;qe.setAttribute("aria-label",io),Ke&&ro({anchor:qe,trigger:Ke,text:()=>qe?.getAttribute("aria-label")??io,enabled:Cn})}let{clearChatButton:Te,clearChatButtonWrapper:ht}=_e;if(Te){let ee=ne.clearChat??{},ze=ee.enabled??!0,Ke=n.layout?.header?.showClearChat,ot=Ke!==void 0?Ke:ze,bt=ee.placement??"inline";if(ht){ht.style.display=ot?"":"none";let{closeButtonWrapper:io}=_e;!De()&&io&&!io.classList.contains("persona-absolute")&&(ot?io.classList.remove("persona-ml-auto"):io.classList.add("persona-ml-auto"));let Cn=bt==="top-right",to=ht.classList.contains("persona-absolute");if(!De()&&Cn!==to&&ot){if(ht.remove(),Cn){ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px";let Fn=Ji??le;Fn.style.position="relative",Fn.appendChild(ht)}else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let Fn=_e.closeButtonWrapper;we&&Fn&&Fn.parentElement===we?we.insertBefore(ht,Fn):we&&we.appendChild(ht)}let oo=_e.closeButtonWrapper;oo&&!oo.classList.contains("persona-absolute")&&(Cn?oo.classList.add("persona-ml-auto"):oo.classList.remove("persona-ml-auto"))}}if(ot){if(!De()){let oo=ee.size??"";Te.style.height=oo,Te.style.width=oo,Te.style.minWidth=oo,Te.style.minHeight=oo}let io=ee.iconColor??"";if(Te.style.color=io||So.actionIconColor,$u(Te,ee.iconName??"refresh-cw",{iconSize:De()?Rh:void 0}),ee.backgroundColor?(Te.style.backgroundColor=ee.backgroundColor,Te.classList.remove("hover:persona-bg-gray-100")):(Te.style.backgroundColor="",Te.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let oo=ee.borderWidth||"0px",Fn=ee.borderColor||"transparent";Te.style.border=`${oo} solid ${Fn}`,Te.classList.remove("persona-border-none")}else Te.style.border="",Te.classList.add("persona-border-none");ee.borderRadius?(Te.style.borderRadius=ee.borderRadius,Te.classList.remove("persona-rounded-full")):(Te.style.borderRadius="",Te.classList.add("persona-rounded-full")),ee.paddingX?(Te.style.paddingLeft=ee.paddingX,Te.style.paddingRight=ee.paddingX):(Te.style.paddingLeft="",Te.style.paddingRight=""),ee.paddingY?(Te.style.paddingTop=ee.paddingY,Te.style.paddingBottom=ee.paddingY):(Te.style.paddingTop="",Te.style.paddingBottom="");let Cn=ee.tooltipText??"Clear chat",to=ee.showTooltip??!0;Te.setAttribute("aria-label",Cn),ht&&ro({anchor:Te,trigger:ht,text:()=>Te?.getAttribute("aria-label")??Cn,enabled:to})}}let He=n.actionParsers&&n.actionParsers.length?n.actionParsers:[id],Kt=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ma.message,ma.messageAndClick];Me=ld({parsers:He,handlers:Kt,getSessionMetadata:Ae,updateSessionMetadata:ve,emit:$.emit,documentRef:typeof document<"u"?document:null}),U=eM(n,Me,P),AT(),R.updateConfig(n),Ev(),(n.features?.history?.enabled===!0!==Ue||n.features?.history?.provider!==rt||n.getIdentityProof!==tt||n.clientToken!==Ho)&&(Ro({restoreFocus:!1}),zb()),qr(),sc(),Zo(he,R.getMessages(),U),Cs(),Vd(),ST(),Gi(R.isStreaming()),Ct!==n.contextMentions&&nx();let dn=n.voiceRecognition?.enabled===!0,eo=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),ct=vo(n.voiceRecognition?.provider);if(dn&&(eo||ct))if(!re||!Uo){let ee=pi(n);if(ee){re=ee.button,Uo=ee.wrapper;let ze=Tn&&Tn.parentElement===pd?Tn:null;pd?pd.insertBefore(Uo,ze):To?.appendChild(Uo),et&&(et.micButton=re),et?.addListener(re,"click",tm),re.disabled=Hn()||R.isStreaming()&&!Zp()}}else{let ee=n.voiceRecognition??{},ze=n.sendButton??{},Ke=ee.iconName??"mic",ot=ee.iconSize,bt=parseFloat(ot??"")||Co;re.classList.add(Go),re.classList.toggle(wn,!ot),re.style.width=ot??"",re.style.height=ot??"",re.style.minWidth=ot??"",re.style.minHeight=ot??"";let io=ee.iconColor??ze.textColor;re.innerHTML="";let Cn=ae(Ke,bt,io||"currentColor",1.5);Cn?re.appendChild(Cn):re.textContent="\u{1F3A4}";let to=ee.backgroundColor??ze.backgroundColor;to?re.style.backgroundColor=to:re.style.backgroundColor="",io?re.style.color=io:re.style.color="var(--persona-text, #111827)",ee.borderWidth?(re.style.borderWidth=ee.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),ee.borderColor?re.style.borderColor=ee.borderColor:re.style.borderColor="",ee.paddingX?(re.style.paddingLeft=ee.paddingX,re.style.paddingRight=ee.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),ee.paddingY?(re.style.paddingTop=ee.paddingY,re.style.paddingBottom=ee.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let oo=ee.tooltipText??"Start voice recognition",Fn=ee.showTooltip??!1;re.setAttribute("aria-label",oo),Uo&&ro({anchor:re,trigger:Uo,text:()=>re?.getAttribute("aria-label")??oo,enabled:Fn}),Uo.style.display="",re.disabled=Hn()||R.isStreaming()&&!Zp()}else re&&Uo&&(Uo.style.display="none",vo(n.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():Dn&&Vr());if(nm(),n.attachments?.enabled===!0){if(!Eo||!At){let ee=n.attachments??{};Po||(Po=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Po.style.display="none",(ie.parentElement??To).insertBefore(Po,ie)),xt||(xt=document.createElement("input"),xt.type="file",xt.accept=(ee.allowedTypes??Cr).join(","),xt.multiple=(ee.maxFiles??4)>1,xt.style.display="none",xt.setAttribute("aria-label","Attach files"),(ie.parentElement??To).insertBefore(xt,ie)),Eo=I("div","persona-send-button-wrapper"),At=I("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Go} ${wn}`),At.type="button",At.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let ze=ee.buttonIconName??"paperclip";At.style.fontSize="18px",At.style.lineHeight="1";let Ke=ae(ze,Co,"currentColor",1.5);Ke?At.appendChild(Ke):At.textContent="\u{1F4CE}",At.addEventListener("click",bt=>{bt.preventDefault(),xt?.click()}),Eo.appendChild(At);let ot=ee.buttonTooltipText??"Attach file";ro({anchor:At,trigger:Eo,text:()=>At?.getAttribute("aria-label")??ot}),Cp?Cp.append(Eo):To.appendChild(Eo),et&&(et.attachmentButton=At,et.attachmentInput=xt??void 0,et.attachmentPreviews=Po??void 0),!nt&&xt&&Po&&(nt=ta.fromConfig(ee,Ty),nt.setPreviewsContainer(Po),et?.addListener(xt,"change",async()=>{nt&&xt?.files&&(await nt.handleFileSelect(xt.files),xt.value="")}))}else{Eo.style.display="";let ee=n.attachments??{};xt&&(xt.accept=(ee.allowedTypes??Cr).join(","),xt.multiple=(ee.maxFiles??4)>1),nt&&nt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles,adapter:ee.adapter})}if(le.querySelector(".persona-attachment-drop-overlay")?.remove(),le.appendChild(tM(n.attachments?.dropOverlay)),At){let ee=n.attachments??{},ze=ee.buttonTooltipText??"Attach file";At.setAttribute("aria-label",ze),At.textContent="";let Ke=ae(ee.buttonIconName??"paperclip",Co,"currentColor",1.5);Ke?At.appendChild(Ke):At.textContent="\u{1F4CE}",Eo&&ro({anchor:At,trigger:Eo,text:()=>At?.getAttribute("aria-label")??ze})}}else Eo&&(Eo.style.display="none"),nt&&nt.clearAttachments(),le.querySelector(".persona-attachment-drop-overlay")?.remove();let We=n.sendButton??{},Gr=We.useIcon??!1,Vt=We.iconText??"\u2191",Wo=We.iconName,ur=We.tooltipText??"Send message",am=We.showTooltip??!1,qs=We.size,im=parseFloat(qs??"")||Vg,pr=We.backgroundColor,Vs=We.textColor;if(Gr){if(Se.style.width=qs??"",Se.style.height=qs??"",Se.style.minWidth=qs??"",Se.style.minHeight=qs??"",Se.style.fontSize="18px",Se.style.lineHeight="1",Vs?Se.style.color=Vs:Se.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(Se.innerHTML="",Wo){let ee=parseFloat(We.iconSize??"")||Math.round(im*.5),ze=Vs?.trim()||"currentColor",Ke=We.iconStrokeWidth??2,ot=ae(Wo,ee,ze,Ke),bt=ae(We.stopIconName??"square",ee,ze,Ke);ot&&bt?Se.appendChild($g(ot,bt)):ot?Se.appendChild(ot):Se.textContent=Vt}else Se.textContent=Vt;Se.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Go}`,pr?(Se.style.backgroundColor=pr,Se.classList.remove("persona-bg-persona-primary")):(Se.style.backgroundColor="",Se.classList.add("persona-bg-persona-primary"))}else Se.textContent=n.copy?.sendButtonLabel??"Send",Se.style.width="",Se.style.height="",Se.style.minWidth="",Se.style.minHeight="",Se.style.fontSize="",Se.style.lineHeight="",Se.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",pr?(Se.style.backgroundColor=pr,Se.classList.remove("persona-bg-persona-accent")):Se.classList.add("persona-bg-persona-accent"),Vs?Se.style.color=Vs:Se.classList.add("persona-text-white");We.borderWidth?(Se.style.borderWidth=We.borderWidth,Se.style.borderStyle="solid"):(Se.style.borderWidth="",Se.style.borderStyle=""),We.borderColor?Se.style.borderColor=We.borderColor:Se.style.borderColor="",We.paddingX?(Se.style.paddingLeft=We.paddingX,Se.style.paddingRight=We.paddingX):(Se.style.paddingLeft="",Se.style.paddingRight=""),We.paddingY?(Se.style.paddingTop=We.paddingY,Se.style.paddingBottom=We.paddingY):(Se.style.paddingTop="",Se.style.paddingBottom=""),R.isStreaming()||Se.setAttribute("aria-label",ur),Ud(),Tn&&ro({anchor:Se,trigger:Tn,text:()=>Se.getAttribute("aria-label")??ur,enabled:am}),Fy(),Up();let fx=Eu(ye.getState().activeModeIds,n.composer?.modes);ye.setActiveModeIds(fx),ha().length>0!==!!Yn&&Rp(),Yn?.render(fx,ha());for(let ee of[...ya.keys()])Tu(ee,n.composer?.modeGroups)||ya.delete(ee);ya.forEach(ee=>ee.repaint()),Lr?.repaint(),kn?.resolve();let Sc=as(n,De());if(Fp(),Sc){he.style.maxWidth=Sc,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%",Fo.style.maxWidth=Sc,Fo.style.marginLeft="auto",Fo.style.marginRight="auto",Fo.style.width="100%";for(let ee of[To,Er,Po,Ye])ee&&(ee.style.maxWidth=Sc,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%")}else{he.style.maxWidth="",he.style.marginLeft="",he.style.marginRight="",he.style.width="",Fo.style.maxWidth="",Fo.style.marginLeft="",Fo.style.marginRight="",Fo.style.width="";for(let ee of[To,Er,Po,Ye])ee&&(ee.style.maxWidth="",ee.style.marginLeft="",ee.style.marginRight="",ee.style.width="")}let xn=n.statusIndicator??{};if(rg(Ye,To,xn),Qs(Ye,xn,R?.getStatus()??"idle"),R){let ee=R.getStatus();Pi(Ye,(Ke=>Ke==="idle"?xn.idleText??Wt.idle:Ke==="connecting"?xn.connectingText??Wt.connecting:Ke==="connected"?xn.connectedText??Wt.connected:Ke==="error"?xn.errorText??Wt.error:Ke==="paused"?xn.pausedText??Wt.paused:Ke==="resuming"?xn.resumingText??Wt.resuming:Wt[Ke])(ee),xn,ee)}Ye.classList.remove("persona-text-left","persona-text-center","persona-text-right");let NE=xn.align==="left"?"persona-text-left":xn.align==="center"?"persona-text-center":"persona-text-right";Ye.classList.add(NE),Ip(),tf(),mn(),yp()},open(){Qe()&&mt(!0,"api")},close(){Qe()&&mt(!1,"api")},toggle(){Qe()&&mt(!ke,"api")},reconnect(){R.reconnectNow()},clearChat(){Jn=!1,i.clear(),r.clear(),a.clear(),d.clear(),R.clearMessages(),n.layout?.topFade&&(te.scrollTop=0),te.removeAttribute("data-persona-top-fade"),_t.clear(),Lo();try{localStorage.removeItem(Ti),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ti}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ti)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),H?.clear&&Hd(()=>H.clear(),"[AgentWidget] Failed to clear storage adapter:"),W={},Me.syncFromMetadata(),nt?.clearAttachments(),Bd(),ba(void 0),Pn(void 0),As(),pt?.clear(),Qt?.reset(),ft?.update()},setMessage(s){return!ie||R.isStreaming()||Hn()?!1:(!ke&&Qe()&&mt(!0,"system"),ie.value=s,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(R.isStreaming()||Ls())return!1;let l=s?.trim()||ie.value.trim();return l?(!ke&&Qe()&&mt(!0,"system"),ie.value="",ie.style.height="auto",En(),hc(l,{consumeDraft:!1}),!0):!1},getComposerState(){return ye.getState()},setQuote(s){let l=s?.text?.trim();l&&Pn({...s,text:l})},clearQuote(){Pn(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:vo(n.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!ke&&Qe()&&mt(!0,"system"),Xe.manuallyDeactivated=!1,yn(),R.toggleVoice().then(()=>{Xe.active=R.isVoiceActive(),or("user"),R.isVoiceActive()&&za()})),!0):Dn?!0:Wv()?(!ke&&Qe()&&mt(!0,"system"),Xe.manuallyDeactivated=!1,yn(),bc("user"),!0):!1},stopVoiceRecognition(){return vo(n.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,yn(),or("user"),cr()}),!0):Dn?(Xe.manuallyDeactivated=!0,yn(),Vr("user"),!0):!1},injectMessage(s){return!ke&&Qe()&&mt(!0,"system"),R.injectMessage(s)},injectAssistantMessage(s){!ke&&Qe()&&mt(!0,"system");let l=R.injectAssistantMessage(s);return Gn&&(Gn=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),l},injectUserMessage(s){return!ke&&Qe()&&mt(!0,"system"),R.injectUserMessage(s)},injectSystemMessage(s){return!ke&&Qe()&&mt(!0,"system"),R.injectSystemMessage(s)},injectMessageBatch(s){return!ke&&Qe()&&mt(!0,"system"),R.injectMessageBatch(s)},injectComponentDirective(s){return!ke&&Qe()&&mt(!0,"system"),R.injectComponentDirective(s)},injectTestMessage(s){!ke&&Qe()&&mt(!0,"system"),R.injectTestEvent(s)},async connectStream(s,l){return R.connectStream(s,l)},__pushEventStreamEvent(s){J&&(ud(),hp(s.type,s.payload))},showEventStream(){J&&Lp()},hideEventStream(){fn&&va()},isEventStreamVisible(){return fn},listConversations(s){return R.listConversations(s)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(s,l){return _f(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return Nf({focusComposer:s?.focus===!0})},warmSession(){qf()},deleteConversation(s){return bv(s)},renameConversation(s,l){return Ff(s,{title:l})},setConversationStarred(s,l){return Ff(s,{starred:l})},clearConversationHistory(s){return vv(s)},resetHistoryIdentity(){return xv()},async getVisitorToken(){let s=en;if(!s)return null;let l=await s.get();return s===en?l:null},getHistoryIdentityStatus(){return zo?zo.getIdentityStatus():Cf()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return sl({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){Ro(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return Pt},showArtifacts(){Ao(n)&&(Jn=!1,Ca=!0,hn(),je?.setMobileOpen(!0))},hideArtifacts(){Ao(n)&&(Jn=!0,hn())},upsertArtifact(s){return Ao(n)?(qn(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Jn=!1,Ca=!0),R.upsertArtifact(s)):null},selectArtifact(s){Ao(n)&&R.selectArtifact(s)},clearArtifacts(){Ao(n)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return N&&!ke&&!De()||!ie?!1:(ie.focus(),!0)},async resolveApproval(s,l,f){let v=R.getMessages().find(w=>w.variant==="approval"&&w.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){R.resolveWebMcpApproval(v.id,l);return}return R.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){KM(s)},clearFollowUpSuggestions(){mb()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...W}},updatePersistentMetadata(s){ve(s)},on(s,l){return $.on(s,l)},off(s,l){$.off(s,l)},isOpen(){return Qe()&&ke},isVoiceActive(){return Xe.active},toggleReadAloud(s){R.toggleReadAloud(s)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(s){return R.getReadAloudState(s)},onReadAloudChange(s){return R.onReadAloudChange(s)},getState(){return{open:Qe()&&ke,launcherEnabled:N,voiceActive:Xe.active,streaming:R.isStreaming()}},showCSATFeedback(s){!ke&&Qe()&&mt(!0,"system");let l=he.querySelector(".persona-feedback-container");l&&l.remove();let f=lp({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});he.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!ke&&Qe()&&mt(!0,"system");let l=he.querySelector(".persona-feedback-container");l&&l.remove();let f=dp({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});he.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return R.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return R.submitNPSFeedback(s,l)},destroy(){mf(),Hs!=null&&(clearInterval(Hs),Hs=null),i.clear(),r.clear(),a.clear(),d.clear(),fe.forEach(s=>s()),Ge.remove(),Yt?.remove(),Lt?.destroy(),go?.remove(),vs&&qe.removeEventListener("click",vs)}};if(((o?.debugTools??!1)||!!n.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,l={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:f=>f?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=l,fe.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),l=K=>{let Y=K.detail;(!Y?.instanceId||Y.instanceId===s)&&It.focusInput()};if(window.addEventListener("persona:focusInput",l),fe.push(()=>{window.removeEventListener("persona:focusInput",l)}),J){let K=se=>{let ue=se.detail;(!ue?.instanceId||ue.instanceId===s)&&It.showEventStream()},Y=se=>{let ue=se.detail;(!ue?.instanceId||ue.instanceId===s)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",K),window.addEventListener("persona:hideEventStream",Y),fe.push(()=>{window.removeEventListener("persona:showEventStream",K),window.removeEventListener("persona:hideEventStream",Y)})}let f=K=>{let Y=K.detail;(!Y?.instanceId||Y.instanceId===s)&&It.showHistory()},g=K=>{let Y=K.detail;(!Y?.instanceId||Y.instanceId===s)&&It.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),fe.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=K=>{let Y=K.detail;(!Y?.instanceId||Y.instanceId===s)&&It.showArtifacts()},w=K=>{let Y=K.detail;(!Y?.instanceId||Y.instanceId===s)&&It.hideArtifacts()},O=K=>{let Y=K.detail;Y?.instanceId&&Y.instanceId!==s||Y?.artifact&&It.upsertArtifact(Y.artifact)},z=K=>{let Y=K.detail;Y?.instanceId&&Y.instanceId!==s||typeof Y?.id=="string"&&It.selectArtifact(Y.id)},q=K=>{let Y=K.detail;(!Y?.instanceId||Y.instanceId===s)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",O),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),fe.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",O),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let sn=jI(n.persistState);if(sn&&Qe()){let s=zI(sn.storage),l=`${sn.keyPrefix}widget-open`,f=`${sn.keyPrefix}widget-voice`,g=`${sn.keyPrefix}widget-voice-mode`;if(s){let v=sn.persist?.openState&&s.getItem(l)==="true",w=sn.persist?.voiceState&&s.getItem(f)==="true",O=sn.persist?.voiceState&&s.getItem(g)==="true";if(v&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{It.open(),setTimeout(()=>{if(w||O)It.startVoiceRecognition();else if(sn.persist?.focusInput){let z=e.querySelector("textarea");z&&z.focus()}},100)},0)),sn.persist?.openState&&($.on("widget:opened",()=>{s.setItem(l,"true")}),$.on("widget:closed",()=>{s.setItem(l,"false")})),sn.persist?.voiceState&&($.on("voice:state",z=>{s.setItem(f,z.active?"true":"false")}),$.on("user:message",z=>{s.setItem(g,z.viaVoice?"true":"false")})),sn.clearOnChatClear){let z=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},q=()=>z();window.addEventListener("persona:clear-chat",q),fe.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(ge&&Qe()&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{It.open()},0)),Ia(),!GM){let s=ei(()=>{R&&(Ms++,_t.clear(),Zo(he,R.getMessages(),U))});fe.push(s)}L=()=>{R&&(Ms++,_t.clear(),Zo(he,R.getMessages(),U))},R.getMessages().length>0&&Fd(),_=()=>{R&&(Ms++,_t.clear(),Zo(he,R.getMessages(),U))};let OE=kx(()=>{R&&(Ms++,_t.clear(),Zo(he,R.getMessages(),U))});fe.push(OE);let _E=jh(()=>{R&&(Ms++,_t.clear(),Zo(he,R.getMessages(),U),wr()?.updateInlineArtifactBlocks(he,Jo.artifacts,{suppressTransition:!0}),hn())});return fe.push(_E),It};var oM=(e,t)=>{let o=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(n)return Math.max(0,parseFloat(n[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(o);return r?Math.max(0,t*parseFloat(r[1])/100):420},XI=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},QI=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},YI=(e,t)=>{let o=e.parentElement;if(!o)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(n);let r=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!r||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},nM=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0",e.style.minWidth=o?"":"0"},ly=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=""},rM=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ly(e)},sy=e=>{e.style.transition=""},ay=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=""},iy=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},pp=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},JI=(e,t,o,n,r)=>{r?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,n),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(n))},ZI=(e,t,o,n,r,a)=>{let i=a?t:e;r==="left"?i.firstElementChild!==n&&i.replaceChildren(n,o):i.lastElementChild!==n&&i.replaceChildren(o,n)},eR=e=>{let t=An(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:ao(t,r)??r;return{inset:n(o?.inset,Iu),canvasBackground:n(o?.canvasBackground,Ru)}},sM=(e,t,o,n)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=n},tR=(e,t,o,n,r,a,i,d)=>{let c=Oo(a),u=c.reveal==="push",p=d!=null,m=d?.inset??"",h=d?.canvasBackground??"";JI(e,t,o,n,u),ZI(e,t,o,n,c.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let y=e.ownerDocument.defaultView,x=a?.launcher?.mobileFullscreen??!0,C=a?.launcher?.mobileBreakpoint??640,E=y!=null?y.innerWidth<=C:!1;if(x&&E&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ay(t),sy(n),rM(n),iy(o),pp(r,n),sM(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",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??co),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),rM(n),XI(n,c.maxHeight),sM(n,p&&i,m,h),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ay(t),sy(n),iy(o),pp(r,n);let M=c.animate?"transform 180ms ease":"none",L=c.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":L;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=c.width,n.style.maxWidth=c.width,n.style.minWidth=c.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=M,n.style.transform=b,n.style.pointerEvents=i?"auto":"none",n.style.zIndex="2",c.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",sy(n),ly(n),pp(r,n);let M=oM(c.width,e.clientWidth),L=Math.max(0,e.clientWidth),b=c.animate?"margin-left 180ms ease":"none",S=c.side==="right"?i?-M:0:i?0:-M;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=`${L+M}px`,t.style.transition=b,t.style.marginLeft=`${S}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${L}px`,o.style.maxWidth=`${L}px`,o.style.minWidth=`${L}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=c.width,n.style.minWidth=c.width,n.style.maxWidth=c.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ay(t),ly(n),iy(o),pp(r,n);let M=c.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=i?c.width:"0px",b=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",S=!i;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",QI(n,c.maxHeight),n.style.overflow=M||S?"hidden":"visible",n.style.transition=b,M){n.style.alignItems=c.side==="right"?"flex-start":"flex-end";let T=p?`calc(${oM(c.width,e.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=T,r.style.minWidth=T,r.style.maxWidth=T,r.style.boxSizing="border-box"}}},oR=(e,t)=>{let o=e.ownerDocument.createElement("div");return nM(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){nM(o,n)},destroy(){o.remove()}}},nR=(e,t)=>{let{ownerDocument:o}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,i=o.createElement("div"),d=o.createElement("div"),c=o.createElement("div"),u=o.createElement("aside"),p=o.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;d.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),n.insertBefore(i,e),c.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},x=null,C=()=>{x=t?.launcher?.detachedPanel===!0?eR(t):null};C();let E=()=>{tR(i,d,c,u,p,t,m,x)},A=null,M=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=fi(()=>{C(),E()}))},L=()=>{y(),Oo(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{E()}),h.observe(i)))},b=!1,S=()=>{E(),L(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,YI(i,Oo(t)))},T=i.ownerDocument.defaultView,B=()=>{S()};return T?.addEventListener("resize",B),Oo(t).reveal==="push"?(d.appendChild(c),d.appendChild(u),i.appendChild(d)):(i.appendChild(c),i.appendChild(u)),S(),M(),{mode:"docked",host:p,shell:i,syncWidgetState(_){let X=_.launcherEnabled?_.open:!0;m!==X&&(m=X,S())},updateConfig(_){t=_,(t?.launcher?.enabled??!0)===!1&&(m=!0),C(),S(),M()},destroy(){T?.removeEventListener("resize",B),A?.(),A=null,y(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),i.remove()}}},cd=(e,t)=>yt(t)?nR(e,t):oR(e,t);var rR=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},aM=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let n=o.cloneNode(!0);e.insertBefore(n,e.firstChild)},fp=[],iM=()=>[...fp],lM=e=>{let t=rR(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=cd(t,r),i,d=[],c=(E,A)=>{let L=!(A?.launcher?.enabled??!0)||yt(A),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),L&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0",b.style.minWidth="0"),o){let S=E.attachShadow({mode:"open"});S.appendChild(b),aM(S,n)}else E.appendChild(b),aM(E,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},u=()=>{a.syncWidgetState(i.getState())},p=()=>{d.forEach(E=>E()),d=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},m=()=>{let E=c(a.host,r);i=up(E,r,{debugTools:e.debugTools}),p()},h=()=>{d.forEach(E=>E()),d=[],i.destroy()};m(),e.onChatReady?.();let y=E=>{h(),a.destroy(),a=cd(t,E),r=E,m()},x={update(E){let A=op(r??{},E),M=yt(r),L=yt(A),b=ls(r),S=ls(A);if(M!==L||b!==S){y(A);return}r=A,a.updateConfig(r),i.update(E),u()},destroy(){h(),a.destroy();let E=fp.indexOf(C);E!==-1&&fp.splice(E,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(x,{get(E,A,M){if(A==="host")return a.host;if(A in E)return Reflect.get(E,A,M);let L=i[A];return typeof L=="function"?L.bind(i):L}});return fp.push(C),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};var fM=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),sR=new Set(["button","a","input","select","textarea","details","summary"]),aR=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),dy=/\b(product|card|item|listing|result)\b/i,uy=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,iR=3e3,lR=100;function mM(e){let t=typeof e.className=="string"?e.className:"";if(dy.test(t)||e.id&&dy.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&dy.test(n.value))return!0}return!1}function gM(e){return uy.test((e.textContent??"").trim())}function hM(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=t[o].getAttribute("href")??"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function dR(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function dM(e){let t=e.match(uy);return t?t[0]:null}function cM(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 n=t.getAttribute("href");return{title:t.textContent.trim(),href:n&&n!=="#"?n:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function cR(e){let t=[],o=n=>{let r=n.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(n=>o(n.textContent??"")),e.querySelectorAll('[role="button"]').forEach(n=>o(n.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{o(n.value??"")}),t.slice(0,6)}var uR="commerce-card",pR="result-card";function uM(e){return!mM(e)||!gM(e)||!hM(e)&&!dR(e)?0:5200}function pM(e){return!mM(e)||gM(e)||!hM(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var py=[{id:uR,scoreElement(e){return uM(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let n=o.text.trim();return!!(n.length===0||uy.test(n)&&n.length<32)}return!0},formatSummary(e,t){if(uM(e)===0)return null;let{title:o,href:n}=cM(e),r=dM((e.textContent??"").trim())??dM(t.text)??"",a=cR(e);return[n&&o?`[${o}](${n})${r?`: ${r}`:""}`:o?`${o}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
140
|
-
`)}},{id:pR,scoreElement(e){return pM(e)},formatSummary(e,t){if(pM(e)===0)return null;let{title:o,href:n}=cM(e);return[n&&o?`[${o}](${n})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
141
|
-
`)}}];function fR(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function mR(e){let t=e.options??{},o=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,d=t.mode??"structured",c=t.maxCandidates??Math.max(500,o*10),u=e.rules??py;return d==="simple"&&e.rules&&e.rules.length>0?(fR(),u=[]):d==="simple"&&(u=[]),{mode:d,maxElements:o,maxCandidates:c,excludeSelector:n,maxTextLength:r,visibleOnly:a,root:i,rules:u}}function cy(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var gR=["data-testid","data-product","data-action","data-id","data-name","data-type"];function hR(e){let t=e.tagName.toLowerCase(),o=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||o==="textbox"||o==="combobox"||o==="listbox"||o==="spinbutton"?"input":t==="button"||o==="button"||sR.has(t)||o&&aR.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function yM(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function yR(e){let t={},o=e.id;o&&(t.id=o);let n=e.getAttribute("href");n&&(t.href=n);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let i=e.getAttribute("value");i&&(t.value=i);let d=e.getAttribute("name");d&&(t.name=d);let c=e.getAttribute("role");c&&(t.role=c);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function fy(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${cy(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of gR){let a=e.getAttribute(r);if(a){let i=`${t}[${r}="${cy(a)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let o=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(o.length>0){let r=`${t}.${o.map(i=>cy(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let d=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(d>=0){let c=`${r}:nth-of-type(${d+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function bR(e){return e==="static"?lR:iR}function bM(e,t){let o=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:fy(e),tagName:o,text:n,role:e.getAttribute("role"),interactivity:hR(e),attributes:yR(e)}}function vR(e,t,o,n){let r=bR(t.interactivity),a=null;for(let i of o){let d=i.scoreElement(e,t,n);d>0&&(r+=d,i.formatSummary&&!a&&(a=i))}return{score:r,formattingRule:a}}function xR(e,t){for(let o of e)if(t.el!==o.el&&o.formattingRule?.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function CR(e,t){let o={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,r=[],a=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),d=i.currentNode;for(;d&&r.length<e.maxCandidates;){if(d.nodeType===Node.ELEMENT_NODE){let u=d,p=u.tagName.toLowerCase();if(fM.has(p)){d=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){d=i.nextNode();continue}}catch{}if(e.visibleOnly&&!yM(u)){d=i.nextNode();continue}let m=bM(u,e.maxTextLength),h=m.text.length>0,y=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(E=>E==="role");if(!h&&!y){d=i.nextNode();continue}if(n.has(m.selector)){d=i.nextNode();continue}n.add(m.selector);let{score:x,formattingRule:C}=vR(u,m,e.rules,o);r.push({el:u,domIndex:a,enriched:m,score:x,formattingRule:C}),a+=1}d=i.nextNode()}r.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let c=[];for(let u of r){if(c.length>=e.maxElements)break;xR(c,u)||c.push(u)}return c.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:m===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),c.map(u=>{let p;if(u.formattingRule?.formatSummary){let h=u.formattingRule.formatSummary(u.el,u.enriched,o);h&&(p=h)}let m={...u.enriched};return p&&(m.formattedSummary=p),m})}function SR(e,t){let o=[],n=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&o.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,u=c.tagName.toLowerCase();if(fM.has(u)){a=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!yM(c)){a=r.nextNode();continue}let p=bM(c,e.maxTextLength),m=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(y=>y==="role");if(!m&&!h){a=r.nextNode();continue}n.has(p.selector)||(n.add(p.selector),o.push(p))}a=r.nextNode()}let i=[],d=[];for(let c of o)c.interactivity!=="static"?i.push(c):d.push(c);return[...i,...d].slice(0,e.maxElements)}function vM(e={}){let t=mR(e),o=t.root??document.body;return o?t.mode==="simple"?SR(t,o):CR(t,o):[]}var mp=100;function xM(e,t={}){if(e.length===0)return"No page elements found.";let o=t.mode??"structured",n=[];if(o==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
|
|
142
|
-
${a.map(i=>`- ${i.split(`
|
|
143
|
-
`).join(`
|
|
144
|
-
`)}`).join(`
|
|
145
|
-
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)o==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,mp)}" (clickable)`);n.push(`Interactive elements:
|
|
146
|
-
${a.join(`
|
|
147
|
-
`)}`)}if(r.navigable.length>0){let a=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,mp)}" (navigable)`);n.push(`Navigation links:
|
|
148
|
-
${a.join(`
|
|
149
|
-
`)}`)}if(r.input.length>0){let a=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,mp)}" (input)`);n.push(`Form inputs:
|
|
150
|
-
${a.join(`
|
|
151
|
-
`)}`)}if(r.static.length>0){let a=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,mp)}"`);n.push(`Content:
|
|
152
|
-
${a.join(`
|
|
153
|
-
`)}`)}return n.join(`
|
|
154
|
-
|
|
155
|
-
`)}var wR={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"}}},CM={components:{panel:{borderRadius:"0",shadow:"none"}}},my={id:"shop",label:"Shopping Assistant",config:{theme:wR,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gs},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"]}},gy={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:CM}},hy={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:CM}},yy={shop:my,minimal:gy,fullscreen:hy};function SM(e){return yy[e]}var Be=typeof document<"u"?document.currentScript?.src??null:null;Jx(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});Dx(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});oS(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});tw(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});ow(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});VA(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});Ow(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"animations-extra.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the animations-extra.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin.`)):import(e)});vA(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"approval-ui.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the approval-ui.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host approval-ui.js alongside it.`)):import(e)});eS(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"voice-runtime.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the voice-runtime.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host voice-runtime.js alongside it.`)):import(e)});AA(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"artifacts-ui.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the artifacts-ui.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host artifacts-ui.js alongside it.`)):import(e)});WA(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"forms-ui.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the forms-ui.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host forms-ui.js alongside it.`)):import(e)});Ex(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"icons-extra.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the icons-extra.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host icons-extra.js alongside it, or register the icons they use via registerIcons().`)):import(e)});tC(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"webmcp-runtime.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the webmcp-runtime.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host webmcp-runtime.js alongside it.`)):import(e)});nS(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"session-reconnect.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the session-reconnect.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host session-reconnect.js alongside it.`)):import(e)});SA(()=>{let e=Be?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===Be?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${Be??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return zE(AR);})();
|
|
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)})();
|
|
156
2
|
/*! Bundled license information:
|
|
157
3
|
|
|
158
|
-
lucide
|
|
159
|
-
lucide/dist/esm/icons/arrow-down.mjs:
|
|
160
|
-
lucide/dist/esm/icons/arrow-left.mjs:
|
|
161
|
-
lucide/dist/esm/icons/arrow-right.mjs:
|
|
162
|
-
lucide/dist/esm/icons/arrow-up-right.mjs:
|
|
163
|
-
lucide/dist/esm/icons/arrow-up.mjs:
|
|
164
|
-
lucide/dist/esm/icons/at-sign.mjs:
|
|
165
|
-
lucide/dist/esm/icons/bot.mjs:
|
|
166
|
-
lucide/dist/esm/icons/check.mjs:
|
|
167
|
-
lucide/dist/esm/icons/chevron-down.mjs:
|
|
168
|
-
lucide/dist/esm/icons/chevron-left.mjs:
|
|
169
|
-
lucide/dist/esm/icons/chevron-right.mjs:
|
|
170
|
-
lucide/dist/esm/icons/chevron-up.mjs:
|
|
171
|
-
lucide/dist/esm/icons/circle.mjs:
|
|
172
|
-
lucide/dist/esm/icons/clipboard-copy.mjs:
|
|
173
|
-
lucide/dist/esm/icons/clipboard.mjs:
|
|
174
|
-
lucide/dist/esm/icons/clock.mjs:
|
|
175
|
-
lucide/dist/esm/icons/code-xml.mjs:
|
|
176
|
-
lucide/dist/esm/icons/copy.mjs:
|
|
177
|
-
lucide/dist/esm/icons/download.mjs:
|
|
178
|
-
lucide/dist/esm/icons/ellipsis-vertical.mjs:
|
|
179
|
-
lucide/dist/esm/icons/ellipsis.mjs:
|
|
180
|
-
lucide/dist/esm/icons/external-link.mjs:
|
|
181
|
-
lucide/dist/esm/icons/eye.mjs:
|
|
182
|
-
lucide/dist/esm/icons/file-code.mjs:
|
|
183
|
-
lucide/dist/esm/icons/file-spreadsheet.mjs:
|
|
184
|
-
lucide/dist/esm/icons/file-text.mjs:
|
|
185
|
-
lucide/dist/esm/icons/file.mjs:
|
|
186
|
-
lucide/dist/esm/icons/history.mjs:
|
|
187
|
-
lucide/dist/esm/icons/image-plus.mjs:
|
|
188
|
-
lucide/dist/esm/icons/loader-circle.mjs:
|
|
189
|
-
lucide/dist/esm/icons/loader.mjs:
|
|
190
|
-
lucide/dist/esm/icons/maximize.mjs:
|
|
191
|
-
lucide/dist/esm/icons/menu.mjs:
|
|
192
|
-
lucide/dist/esm/icons/message-square.mjs:
|
|
193
|
-
lucide/dist/esm/icons/mic.mjs:
|
|
194
|
-
lucide/dist/esm/icons/minimize.mjs:
|
|
195
|
-
lucide/dist/esm/icons/minus.mjs:
|
|
196
|
-
lucide/dist/esm/icons/panel-left.mjs:
|
|
197
|
-
lucide/dist/esm/icons/paperclip.mjs:
|
|
198
|
-
lucide/dist/esm/icons/pencil.mjs:
|
|
199
|
-
lucide/dist/esm/icons/plus.mjs:
|
|
200
|
-
lucide/dist/esm/icons/quote.mjs:
|
|
201
|
-
lucide/dist/esm/icons/refresh-cw.mjs:
|
|
202
|
-
lucide/dist/esm/icons/search.mjs:
|
|
203
|
-
lucide/dist/esm/icons/send.mjs:
|
|
204
|
-
lucide/dist/esm/icons/shield-alert.mjs:
|
|
205
|
-
lucide/dist/esm/icons/shield-check.mjs:
|
|
206
|
-
lucide/dist/esm/icons/shield-x.mjs:
|
|
207
|
-
lucide/dist/esm/icons/square.mjs:
|
|
208
|
-
lucide/dist/esm/icons/star.mjs:
|
|
209
|
-
lucide/dist/esm/icons/thumbs-down.mjs:
|
|
210
|
-
lucide/dist/esm/icons/thumbs-up.mjs:
|
|
211
|
-
lucide/dist/esm/icons/trash-2.mjs:
|
|
212
|
-
lucide/dist/esm/icons/trash.mjs:
|
|
213
|
-
lucide/dist/esm/icons/upload.mjs:
|
|
214
|
-
lucide/dist/esm/icons/volume-2.mjs:
|
|
215
|
-
lucide/dist/esm/icons/x.mjs:
|
|
216
|
-
lucide/dist/esm/lucide.mjs:
|
|
4
|
+
lucide:
|
|
217
5
|
(**
|
|
218
6
|
* @license lucide v1.18.0 - ISC
|
|
219
7
|
*
|
|
@@ -221,4 +9,4 @@ lucide/dist/esm/lucide.mjs:
|
|
|
221
9
|
* See the LICENSE file in the root directory of this source tree.
|
|
222
10
|
*)
|
|
223
11
|
*/
|
|
224
|
-
//# sourceMappingURL=index
|
|
12
|
+
//# sourceMappingURL=index.global.js.map
|