@runtypelabs/persona 4.34.0 → 4.35.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/activity-ui.d.cts +3 -3
- package/dist/activity-ui.d.ts +3 -3
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.d.cts +3 -3
- package/dist/approval-ui.d.ts +3 -3
- package/dist/artifacts-ui.d.cts +3 -3
- package/dist/artifacts-ui.d.ts +3 -3
- package/dist/background-runtime.d.cts +1 -1
- package/dist/background-runtime.d.ts +1 -1
- package/dist/{chunk-CxNPSY-b.js → chunk-B1P8w9_X.js} +1 -1
- package/dist/{chunk-CV8EPIhT.js → chunk-B30Jdgg6.js} +1 -1
- package/dist/{chunk-6CUrH_jm.js → chunk-Bzo9GaAi.js} +1 -1
- package/dist/chunk-CNBMBx-Y.js +2 -0
- package/dist/chunk-Cd8mp8Sv.js +1 -0
- package/dist/chunk-CsfE8WRG.js +1 -0
- package/dist/{chunk-Co3VVwGe.js → chunk-D2pHRNEq.js} +0 -0
- package/dist/chunk-D3kZO8u-.js +1 -0
- package/dist/chunk-DAthf5H3.js +1 -0
- package/dist/{chunk-YMkMvAsa.js → chunk-DZ_aillY.js} +1 -1
- package/dist/{chunk-6C23QQdP.js → chunk-DgJV9zbK.js} +1 -1
- package/dist/chunk-Dv6KtIT1.js +1 -0
- package/dist/chunk-Dws8IrdR.js +1 -0
- package/dist/{chunk-DsWv3EGF.js → chunk-ThxxD8oK.js} +1 -1
- package/dist/client-dispatch.js +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/composer-actions-runtime.cjs +1 -1
- package/dist/composer-actions-runtime.d.cts +3 -3
- package/dist/composer-actions-runtime.d.ts +3 -3
- package/dist/composer-actions-runtime.js +1 -1
- package/dist/{composer-input-i_FiUp6J.d.cts → composer-input-BSDNPOqV.d.cts} +1 -1
- package/dist/{composer-input-i_FiUp6J.d.ts → composer-input-BSDNPOqV.d.ts} +1 -1
- package/dist/{composer-store-DhGNgG7Z.d.cts → composer-store-DC-gAjtN.d.cts} +1 -1
- package/dist/{composer-store-DhGNgG7Z.d.ts → composer-store-DC-gAjtN.d.ts} +1 -1
- package/dist/{context-mention-manager-DL-xwGfL.d.cts → context-mention-manager-CCpeoGL2.d.cts} +2 -2
- package/dist/{context-mention-manager-DL-xwGfL.d.ts → context-mention-manager-CCpeoGL2.d.ts} +2 -2
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.cjs +1 -1
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/context-mentions.js +1 -1
- package/dist/{defaults-Bga2Xrsp.d.cts → defaults-tj5RcN8r.d.cts} +1 -1
- package/dist/{defaults-Bga2Xrsp.d.ts → defaults-tj5RcN8r.d.ts} +1 -1
- package/dist/dictation-runtime.d.cts +2 -2
- package/dist/dictation-runtime.d.ts +2 -2
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-kLdyPcmk.d.cts → fallback-speech-engine-gkhbjLiZ.d.cts} +1 -1
- package/dist/{fallback-speech-engine-kLdyPcmk.d.ts → fallback-speech-engine-gkhbjLiZ.d.ts} +1 -1
- package/dist/{feature-preferences-CmwZGKrf.d.cts → feature-preferences-CerDWGZ7.d.cts} +1 -1
- package/dist/{feature-preferences-CmwZGKrf.d.ts → feature-preferences-CerDWGZ7.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/{history-confirm-dialog-i46-lPN_.d.cts → history-confirm-dialog-CrkSB3Ra.d.cts} +1 -1
- package/dist/{history-confirm-dialog-i46-lPN_.d.ts → history-confirm-dialog-CrkSB3Ra.d.ts} +1 -1
- package/dist/history-shell.d.cts +6 -6
- package/dist/history-shell.d.ts +6 -6
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +32 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +40 -40
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/launcher.global.js +1 -1
- package/dist/{loading-label-runtime-loader-Ccr3ETd3.d.cts → loading-label-runtime-loader-fWIRrhUF.d.cts} +1 -1
- package/dist/{loading-label-runtime-loader-Ccr3ETd3.d.ts → loading-label-runtime-loader-fWIRrhUF.d.ts} +1 -1
- package/dist/loading-label-runtime.d.cts +1 -1
- package/dist/loading-label-runtime.d.ts +1 -1
- package/dist/{message-bubble-C6AVaH7f.d.cts → message-bubble-Czc0lOHr.d.cts} +1 -1
- package/dist/{message-bubble-C6AVaH7f.d.ts → message-bubble-Czc0lOHr.d.ts} +1 -1
- package/dist/{plugin-kit-BVggqE3C.d.cts → plugin-kit-C30jE-cw.d.cts} +3 -1
- package/dist/{plugin-kit-BVggqE3C.d.ts → plugin-kit-C30jE-cw.d.ts} +3 -1
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.d.cts +1 -1
- package/dist/plugin-kit.d.ts +1 -1
- package/dist/plugin-kit.js +1 -1
- package/dist/preferences-runtime.d.cts +1 -1
- package/dist/preferences-runtime.d.ts +1 -1
- package/dist/{preview-BMdRffo4.d.cts → preview-D-osV3FU.d.cts} +2 -2
- package/dist/{preview-BMdRffo4.d.ts → preview-D-osV3FU.d.ts} +2 -2
- package/dist/{registry-B16l8s1b.d.cts → registry-B6w91tx0.d.cts} +1 -1
- package/dist/{registry-B16l8s1b.d.ts → registry-B6w91tx0.d.ts} +1 -1
- package/dist/{session-CtZHe7fc.d.cts → session-BUQrs3Of.d.cts} +10 -9
- package/dist/{session-CtZHe7fc.d.ts → session-BUQrs3Of.d.ts} +10 -9
- package/dist/session-reconnect.d.cts +2 -2
- package/dist/session-reconnect.d.ts +2 -2
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +43 -43
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +3 -3
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-reference.d.cts +2 -2
- package/dist/theme-reference.d.ts +2 -2
- package/dist/{tool-loading-animation-D2cyFvmM.d.cts → tool-loading-animation-B7XUf8TN.d.cts} +1 -1
- package/dist/{tool-loading-animation-D2cyFvmM.d.ts → tool-loading-animation-B7XUf8TN.d.ts} +1 -1
- package/dist/{turn-activity-ui-Do1Nd-Ow.d.cts → turn-activity-ui-CohuNMHT.d.cts} +2 -2
- package/dist/{turn-activity-ui-Do1Nd-Ow.d.ts → turn-activity-ui-CohuNMHT.d.ts} +2 -2
- package/dist/turn-activity-ui.d.cts +1 -1
- package/dist/turn-activity-ui.d.ts +1 -1
- package/dist/{types-BC7MRxO5.d.cts → types-9i0xcAMT.d.cts} +52 -0
- package/dist/{types-BC7MRxO5.d.ts → types-9i0xcAMT.d.ts} +52 -0
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +2 -2
- package/dist/voice-runtime.d.ts +2 -2
- package/dist/voice-runtime.js +1 -1
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-B8g46vS0.d.ts → webmcp-runtime-entry-XNaXa-9h.d.cts} +9 -1
- package/dist/{webmcp-runtime-entry-B8g46vS0.d.cts → webmcp-runtime-entry-XNaXa-9h.d.ts} +9 -1
- package/dist/webmcp-runtime.cjs +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/webmcp-runtime.js +1 -1
- package/package.json +2 -2
- package/src/client-dispatch.ts +13 -0
- package/src/client.ts +37 -2
- package/src/client.webmcp-require-confirm.test.ts +212 -0
- package/src/components/composer-model-picker.ts +0 -14
- package/src/components/composer-overflow-menu.ts +0 -15
- package/src/components/composer-tokens.ts +0 -20
- package/src/generated/runtype-openapi-contract.ts +13 -0
- package/src/plugin-kit.test.ts +101 -0
- package/src/plugin-kit.ts +29 -1
- package/src/session.ts +6 -2
- package/src/session.webmcp.test.ts +32 -0
- package/src/types.ts +35 -0
- package/src/ui.composer-models.test.ts +5 -7
- package/src/ui.composer-overflow.test.ts +14 -21
- package/src/utils/context-mention-controller.test.ts +56 -0
- package/src/webmcp-bridge.test.ts +102 -0
- package/src/webmcp-runtime-entry.ts +29 -1
- package/dist/chunk-BAkaTZpd.js +0 -1
- package/dist/chunk-BEDTp-dm.js +0 -1
- package/dist/chunk-C-rux8Q9.js +0 -1
- package/dist/chunk-CNhThrLX.js +0 -1
- package/dist/chunk-CzLEhoB_.js +0 -2
- package/dist/chunk-Dqa_GOcj.js +0 -1
- package/dist/chunk-NUNdcnAZ.js +0 -1
package/dist/index.global.js
CHANGED
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
6
|
*/
|
|
7
|
-
var AgentWidget=function(e){var t,r,o,n,a,s,i,l,d,c,p,u,h=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);let m=Symbol.for("persona.defaultsProvenance"),g=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function f(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let o=t?`${t}.${e}`:e;return g(r)?f(r,o):[o]})}function b(e,t){let r=t.split(".");for(let t=0;t<r.length;t++){let o=r[t];if(!g(e)||!Object.prototype.hasOwnProperty.call(e,o))return"absent";if(void 0===(e=e[o])||t<r.length-1&&!g(e))return"clear"}return"explicit"}function y(e,t){return e?.[m]??t.filter(t=>"explicit"===b(e,t))}function v(e,t){return Object.defineProperty(e,m,{value:t,enumerable:!0,configurable:!0}),e}function w(e,t,r){return v(e,y(t,f(r)))}function x(e,t,r){let o=t[m];if(o)return o;let n=new Set(y(e,r));for(let e of r){let r=b(t,e);"clear"===r&&n.delete(e),"explicit"===r&&n.add(e)}return[...n]}function C(e,t,r){let o={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),n=o;for(let e of t.slice(0,-1)){let t=n[e];if(!g(t)){n=void 0;break}n[e]={...t},n=n[e]}n&&delete n[t[t.length-1]]}return o}let S=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function k(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=S(t)&&S(o)?k(t,o):o}return r}let A=e=>{if("string"!=typeof e)return;let t=e.trim(),r=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(t)?.[1];if(r){let e=3===r.length?[...r].map(e=>e+e).join(""):r;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let o=/^rgba?\(\s*([^)]*)\)$/i.exec(t);if(!o)return;let n=o[1].trim().split(/\s*[,/]\s*|\s+/);if(4===n.length&&/^(?:1(?:\.0+)?|100%)$/.test(n[3])&&n.pop(),3!==n.length)return;let a=n.map(e=>/^\d+(?:\.\d+)?%?$/.test(e)?Number.parseFloat(e)*(e.endsWith("%")?2.55:1):NaN);return a.some(e=>!Number.isFinite(e)||e<0||e>255)?void 0:a},M=e=>e.reduce((e,t,r)=>{let o=t/255;return e+(o<=.04045?o/12.92:((o+.055)/1.055)**2.4)*[.2126,.7152,.0722][r]},0),I=e=>"#"+e.map(e=>Math.round(e).toString(16).padStart(2,"0")).join(""),T=(e,t,r)=>I(e.map(e=>e+(t-e)*r)),E=e=>M(e)>.179?"#000000":"#ffffff",L=e=>{let t=A(e?.neutral);return t?M(t)<.18?"dark":"light":void 0},B=(e,t)=>t.split(" ").map(t=>`${e}.${t}`),R=[...B("launcher","closeButtonSize closeButtonColor closeButtonBackgroundColor closeButtonBorderWidth closeButtonBorderColor closeButtonBorderRadius closeButtonPaddingX closeButtonPaddingY"),...B("launcher.clearChat","size iconColor backgroundColor borderWidth borderColor borderRadius paddingX paddingY"),...B("sendButton","size iconSize iconStrokeWidth backgroundColor textColor borderWidth borderColor paddingX paddingY"),...B("voiceRecognition","iconSize iconColor backgroundColor borderColor borderWidth paddingX paddingY recordingIconColor recordingBackgroundColor recordingBorderColor processingIconColor processingBackgroundColor processingBorderColor speakingIconColor speakingBackgroundColor speakingBorderColor"),...B("toolCall","shadow backgroundColor borderColor borderWidth borderRadius headerBackgroundColor headerTextColor headerPaddingX headerPaddingY contentBackgroundColor contentTextColor contentPaddingX contentPaddingY codeBlockBackgroundColor codeBlockBorderColor codeBlockTextColor toggleTextColor labelTextColor loadingAnimationColor loadingAnimationSecondaryColor loadingAnimationDuration"),...B("approval","backgroundColor borderColor shadow titleColor descriptionColor reasonColor approveButtonColor approveButtonTextColor denyButtonColor denyButtonTextColor parameterBackgroundColor parameterTextColor"),...B("features.askUserQuestion.styles","sheetBackground sheetBorder sheetShadow pillBackground pillBackgroundSelected pillTextColor pillTextColorSelected pillBorderRadius customInputBackground"),...B("features.artifacts.layout","paneBackground panePadding paneBorderRadius paneShadow chatShadow paneBorder paneBorderLeft unifiedSplitOuterRadius documentToolbarIconColor documentToolbarToggleActiveBackground documentToolbarToggleActiveBorderColor documentToolbarToggleActiveColor tabFadeSize"),...B("suggestionChipsConfig","fontWeight paddingX paddingY")],P=["voice.recording.border","voice.processing.icon","voice.processing.background","voice.speaking.icon","approval.requested.text","approval.approve.foreground","approval.deny.foreground","approval.deny.background","reasoningBubble.shadow","toolBubble.shadow"],N=[...R,"suggestionChips","copy.welcomeTitle","copy.welcomeSubtitle","copy.showWelcomeCard","features.suggestReplies.enabled","features.suggestReplies.expose",...["theme","darkTheme"].flatMap(e=>P.map(t=>`${e}.components.${t}`))],$=Symbol.for("persona.styleProvenance"),W=(e,t)=>{for(let r of t.split(".")){if("object"!=typeof e||!e)return;e=e[r]}return e},H=e=>{let t=e?.[$];if(!t)return N.filter(t=>"explicit"===b(e,t));let r=new Set(t.explicit);return N.forEach(o=>{W(e,o)!==t.values[o]&&("explicit"===b(e,o)?r.add(o):r.delete(o))}),[...r]},D=(e,t)=>(Object.defineProperty(e,$,{value:{explicit:t,values:Object.fromEntries(N.map(t=>[t,W(e,t)]))},enumerable:!0,configurable:!0}),e),O=(e,t)=>D(e,H(t)),F=(e,t)=>{let r=e?.[$];return r&&Object.prototype.hasOwnProperty.call(r.values,t)&&W(e,t)===r.values[t]?r.explicit.includes(t):"explicit"===b(e,t)},z=(e,t)=>F(e,t)?W(e,t):void 0,q=(e,t,r)=>{let o=e,n=r??o?.colorScheme??L(o?.brand)??"light",a="dark"===n||"auto"===n&&(typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches);return F(e,`theme.components.${t}`)||a&&F(e,`darkTheme.components.${t}`)},j={defaultProvenance:y,suppliedPath:b,hasExplicitThemeStyle:q,getExplicitLegacyStyle:z},_=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,o=null,n=null,a=null;return{setLoader:e=>{o=e,r&&(n=null,a=null)},load:()=>{if(n)return Promise.resolve(n);if(a)return a;let e=o??t;try{return a=e().then(e=>(n=e,e)).catch(e=>{throw a=null,e}),a}catch(e){return Promise.reject(e)}},provide:e=>{n=e},getSync:()=>n}},{setLoader:U,load:V,provide:K,getSync:Q}=_({fallbackImport:()=>import("@runtypelabs/persona/activity-ui")}),J=U,G=V,Y=Q,{setLoader:X,load:Z,provide:ee}=_({fallbackImport:()=>import("@runtypelabs/persona/turn-activity-ui")}),te=X,re=null,oe=()=>Promise.all([Z(),G()]).then(([e,t])=>(Object.assign(t.turnUi,e),re=e)),ne=(e,t=24,r="currentColor",o=2)=>{if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");for(let[e,a]of Object.entries({width:String(t),height:String(t),viewBox:"0 0 24 24",fill:"none",stroke:r,"stroke-width":String(o),"stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"}))n.setAttribute(e,a);for(let t of e){if(!Array.isArray(t)||t.length<2)continue;let e=t[0],r=t[1];if(!r)continue;let o=document.createElementNS("http://www.w3.org/2000/svg",e);for(let[e,t]of Object.entries(r))"stroke"!==e&&o.setAttribute(e,String(t));n.appendChild(o)}return n},{setLoader:ae,load:se}=_({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),ie=ae,le=se,de=[["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"}]],ce=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]],pe=[["path",{d:"M20 6 9 17l-5-5"}]],ue=[["path",{d:"m18 15-6-6-6 6"}]],he=[["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"}]],me=[["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"}]],ge=[["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"}]],fe=[["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"}]],be=[["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"}]],ye=[["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"}]],ve=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]],we={activity:de,"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":[["path",{d:"m6 9 6 6 6-6"}]],"chevron-up":ue,"chevron-right":[["path",{d:"m9 18 6-6-6-6"}]],"chevron-left":[["path",{d:"m15 18-6-6 6-6"}]],check:pe,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:he,file:be,"file-code":me,"file-spreadsheet":ge,"file-text":fe,"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"}]],"square-text":[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 8h10M7 12h10M7 16h6"}]],"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"}]],"voice-bars":[["path",{d:"M4 10v4"}],["path",{d:"M8 6v12"}],["path",{d:"M12 3v18"}],["path",{d:"M16 7v10"}],["path",{d:"M20 10v4"}]],x:ve,"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":ce,"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"}]],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":ye,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"}]]},xe="brain.toolbox.wrench.circle.database.terminal.user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.ellipsis-vertical.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".split("."),Ce=new Map(Object.entries(we)),Se=new Map,ke=!1,Ae=new Set,Me=e=>{let t=[...Ae];e&&Ae.clear();for(let e of t)try{e()}catch{}},Ie=()=>{let e=0;for(let[t,r]of Se){let o=Ce.get(r);if(!o)continue;Se.delete(t),e++;let n=ne(o);if(n)for(t.removeAttribute("data-persona-icon-pending");n.firstChild;)t.appendChild(n.firstChild)}return e},Te=()=>ke?null:le().then(e=>(e=>{if(!ke){for(let[t,r]of Object.entries(e))Ce.has(t)||Ce.set(t,r);ke=!0,Ie(),Me(!0)}})(e.EXTRA_LUCIDE_ICONS)),Ee=(e,t=24,r="currentColor",o=2)=>{let n=Ce.get(e);if(n)return ne(n,t,r,o);if(xe.includes(e)){let n=((e,t,r)=>{let o=ne([],e,t,r);return o.setAttribute("data-persona-icon-pending","true"),o})(t,r,o);return Se.size>=500&&Se.delete(Se.keys().next().value),Se.set(n,e),Te()?.catch(e=>{console.warn("[Persona] Failed to load the icons-extra chunk",e)}),n}return console.warn(`Unknown Persona icon "${e}". Use registerIcons().`),null},{setLoader:Le,load:Be,provide:Re,getSync:Pe}=_({fallbackImport:()=>import("@runtypelabs/persona/composer-actions-runtime")}),Ne=Le,$e=Be,We=Pe,{setLoader:He,load:De,provide:Oe,getSync:Fe}=_({fallbackImport:()=>import("@runtypelabs/persona/loading-label-runtime")}),ze=He,qe=De,je=Fe,{setLoader:_e,load:Ue,getSync:Ve,provide:Ke}=_({fallbackImport:()=>import("@runtypelabs/persona/dictation-runtime")}),Qe=_e,Je=Ue,Ge=Ve,{setLoader:Ye,load:Xe,provide:Ze,getSync:et}=_({fallbackImport:()=>import("./markdown-parsers-entry")}),tt=new Set,rt=Ye,ot=()=>{let e=et();return e?Promise.resolve(e):Xe().then(e=>((()=>{let e=[...tt];tt.clear();for(let t of e)try{t()}catch{}})(),e))},nt=e=>et()?()=>{}:(tt.add(e),()=>{tt.delete(e)}),at=et,st=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},it=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),void 0!==t.text&&(o.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))o.setAttribute(e,r);if(t.style){let e=o.style,r=t.style;for(let t of Object.keys(r)){let o=r[t];null!=o&&(e[t]=o)}}let n=r.filter(e=>null!=e);return n.length>0&&o.append(...n),o},lt=(...e)=>e.filter(Boolean).join(" "),dt={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"};function ct(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a,onOpenChange:s}=e,i=st("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="100001"):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px","bottom-right"===n?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=Ee(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let o=document.createElement("span");o.textContent=e.label,t.appendChild(o),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=o.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===n?(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)&&!o.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 pt(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,chromeless:s,onClick:i,aria:l}=e,d=st("button",lt(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=Ee(t,o??16,"currentColor",n??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 ut(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==o&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let c=st("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=Ee(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=st("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 ht(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=st("div","persona-toggle-group"+(n?" "+n:""));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=pt({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),o(e.id)}}):(t=st("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(),o(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 mt(e){let{label:t,icon:r,iconSize:o,iconOnly:n,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=st("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},b=n&&r?pt({...f,icon:r,size:o??14}):ut({...f,icon:r,iconSize:o??14}),y=pt({icon:"chevron-down",label:c,size:p??14,className:"persona-split-btn-chevron"+(m?" "+m:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});g.append(b,y);let v=null,w=()=>{if(v)return v;let e=("function"==typeof d?d():d)??void 0;return v=ct({items:a,onSelect:s,anchor:g,position:l,portal:e,onOpenChange:e=>{y.setAttribute("aria-expanded",e?"true":"false")}}),e||g.appendChild(v.element),v};return g.isConnected?w():requestAnimationFrame(()=>{v||w()}),y.addEventListener("click",e=>{e.stopPropagation(),w().toggle()}),{element:g,primaryButton:b,chevronButton:y,openMenu:()=>w().show(),closeMenu:()=>v?.hide(),toggleMenu:()=>w().toggle(),destroy:()=>{v?.destroy(),g.remove()}}}function gt(e){let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=st("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=st("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=Ee(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=ct({items:o,onSelect:e=>{d.setAttribute("aria-expanded","false"),n(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()}}}let ft=new class{#e=new Map;#t=new Map;register(e,t,r){this.#e.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.#e.set(e,t),r?this.#t.set(e,r):this.#t.delete(e)}unregister(e){this.#e.delete(e),this.#t.delete(e)}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}getOptions(e){return this.#t.get(e)}getAllNames(){return Array.from(this.#e.keys())}clear(){this.#e.clear(),this.#t.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}};function bt(e,t){return e.components&&Object.prototype.hasOwnProperty.call(e.components,t)?e.components[t]:ft.get(t)}function yt(e,t){return e.components&&Object.prototype.hasOwnProperty.call(e.components,t)?void 0:ft.getOptions(t)}let vt=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:wt,load:xt,provide:Ct,getSync:St}=_({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),kt=null,At=new Set,Mt=e=>{if(kt)return kt;kt=e,e.initArtifactsUi({componentRegistry:ft,loadingLabels:je(),buttons:{createIconButton:pt,createLabelButton:ut,createSplitButton:mt,createToggleGroup:ht}});for(let t of vt)ft.has(t)||ft.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=at();t?e.__provideMarkdownParsers(t):nt(()=>{let t=at();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader!==ie&&e.__setIconsExtraLoader(le);let r=[...At];At.clear();for(let e of r)try{e()}catch{}return e},It=wt,Tt=()=>Promise.all([xt(),qe()]).then(([e])=>Mt(e)),Et=()=>{if(kt)return kt;if(!je())return null;let e=St();return e?Mt(e):null},Lt=e=>kt?()=>{}:(At.add(e),()=>{At.delete(e)}),{setLoader:Bt,load:Rt,provide:Pt,getSync:Nt}=_({fallbackImport:()=>import("./ui-extras-entry")}),$t=Bt,Wt=Rt,Ht=Nt,{setLoader:Dt,load:Ot,getSync:Ft}=_({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),zt=Dt,qt=Ot,jt=Ft;function _t(e){return"runtype"===e?.type||"custom"===e?.type}function Ut(e){let t=e.voiceRecognition;return _t(t?.provider)&&("custom"!==t?.provider?.type||!!t.dictation?.provider||!t.dictation&&"review"!==t.completionBehavior)}let Vt=e=>{let t=[],r=(e,r,o)=>{e&&!r&&t.push(o())};r(!0,We(),$e),r(!0,at(),ot);let o=!0===e.turnActivity?.enabled;r(o,re,oe);let n=o||!1!==e.features?.showToolCalls||!1!==e.features?.showReasoning;r(n,Y(),G),r(n||"none"!==e.loadingLabel?.animation&&(!!e.loadingLabel?.animate||"label"===(e.loadingIndicator?.variant??(e.future?.v5Defaults?"label":"dots"))),je(),qe),r(!1!==e.voiceRecognition?.enabled,Ge(),Je),r(!1!==e.voiceRecognition?.enabled&&Ut(e),jt(),qt),r(!0===e.features?.artifacts?.enabled,Et(),Tt),r(!0===e.contextMentions?.enabled,Ht(),Wt);let a=Te();return a&&t.push(a),t};function Kt(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Qt(e,t){return Kt(e)-e.scrollTop<=t}function Jt(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))}}function Gt(){let e=null,t=()=>{null!==e&&cancelAnimationFrame(e),e=null};return{get active(){return null!==e},cancel:t,start(r,o,n,a,s,i=()=>!0){t();let l=r.scrollTop,d=performance.now();if(Math.abs(o()-l)<1)return r.scrollTop=o(),a(),void s();let c=p=>{if(!i())return t(),void s();let u=Math.min(Math.max(0,(p-d)/n),1);r.scrollTop=l+(o()-l)*(1-(1-u)**3),a(),u<1?e=requestAnimationFrame(c):(e=null,s())};e=requestAnimationFrame(c)}}}function Yt(e,t,r,o,n){let a,s=Gt(),i=!1,l=!1,d=e=>{e&&(l=!1),s.active&&(s.cancel(),a=e,l=!!e,n())},c=e=>{["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"," "].includes(e.key)&&d(e)},p=e=>{0!==e.deltaY&&d(e)};return e.addEventListener("wheel",p,{passive:!0}),e.addEventListener("touchstart",d,{passive:!0}),e.addEventListener("pointerdown",d,{passive:!0}),t.addEventListener("keydown",c),{get active(){return s.active},cancel:d,get interrupted(){return l},interruptedBy:e=>a===e,start(t){if(i)return;s.cancel(),l=!1,a=void 0;let n="smooth"===(t.features?.scrollToBottom?.scrollBehavior??(t.future?.v5Defaults?"smooth":"instant")),d=t.features?.scrollToBottom?.scrollDurationMs??220,c=Number.isFinite(d)&&d>=0?d:220,p="function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches;!n||p||0===c?(e.scrollTop=Kt(e),r(),o()):s.start(e,()=>Kt(e),c,r,o)},destroy(){i=!0,s.cancel(),e.removeEventListener("wheel",p),e.removeEventListener("touchstart",d),e.removeEventListener("pointerdown",d),t.removeEventListener("keydown",c)}}}function Xt(e,t,r){let o=st("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");o.type="button",o.setAttribute("data-persona-scroll-to-bottom-visible","false"),o.disabled=!0,o.tabIndex=-1,o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-scroll-to-bottom","true");let n=st("span","persona-flex persona-items-center persona-justify-center");n.setAttribute("aria-hidden","true");let a=st("span",""),s=st("span","");s.setAttribute("data-persona-scroll-to-bottom-count",""),o.append(n,a,s);let i,l,d,c={},p={activity:"idle",visible:!1,hovered:!1,focused:!1,reducedMotion:!1},u="",h="function"==typeof matchMedia?matchMedia("(prefers-reduced-motion: reduce)"):void 0,m=[],g=()=>{let e=getComputedStyle(o);return{width:`${o.offsetWidth}px`,backgroundColor:e.backgroundColor,borderColor:e.borderColor,color:e.color}};p.reducedMotion=h?.matches??!1;let f=e=>console.warn("Persona scroll icon failed",e),b=()=>({config:c,state:{...p},view:t,signal:d.signal}),y=()=>{d?.abort();try{l?.destroy?.()}catch(e){f(e)}l=void 0,d=void 0,n.innerHTML="",u=""},v=()=>{if(l?.element)return;let t=c.features?.scrollToBottom,r="generating-below"===p.activity&&"dots"===(t?.streamingIndicator??(c.future?.v5Defaults?"dots":"arrow")),o="approval-below"===p.activity?"shield-check":t?.iconName??"arrow-down",a=r?"dots":`arrow:${o}`;if(u!==a)if(u=a,n.innerHTML="",r){let e=st("span","persona-scroll-to-bottom-dots");for(let t=0;t<3;t++){let r=st("span","");r.style.animationDelay=150*t+"ms",e.appendChild(r)}n.appendChild(e)}else{let t=e(o,"14px","currentColor",2);t&&n.appendChild(t)}},w=e=>{let t=!1===c.features?.scrollToBottom?.enabled?void 0:c.features?.scrollToBottom?.renderIcon;if(t!==i){if(y(),i=t,i){d=new AbortController;try{let e=i(b());l=e&&"element"in e?e:e?{element:e}:void 0,l?.element&&n.appendChild(l.element)}catch(e){f(e),y()}}}else if(e&&l?.update)try{l.update(b())}catch(e){f(e),y()}v()},x=e=>Object.keys(e).some(t=>e[t]!==p[t]),C=e=>{let t=x(e);p=e,w(t)},S=()=>C({...p,hovered:!0}),k=()=>C({...p,hovered:!1}),A=()=>C({...p,focused:!0}),M=()=>C({...p,focused:!1}),I=()=>C({...p,reducedMotion:h?.matches??!1}),T=new AbortController;for(let[e,t]of[["mouseenter",S],["mouseleave",k],["focus",A],["blur",M]])o.addEventListener(e,t,{signal:T.signal});return h?.addEventListener?.("change",I),{element:o,update(e,t,n=!1,i=0,l=!1){let d=c.features?.scrollToBottom,u=e.features?.scrollToBottom,h=c.future?.v5Defaults!==e.future?.v5Defaults||["enabled","iconName","label","approvalLabel","streamingIndicator","transition","scrollBehavior","scrollDurationMs"].some(e=>d?.[e]!==u?.[e]);c=e;let f=c.features?.scrollToBottom;t&&=!1!==f?.enabled;let b=o.getRootNode().activeElement===o;o.setAttribute("data-persona-scroll-to-bottom-visible",String(t));let y=!1===f?.enabled?"none":f?.transition??(c.future?.v5Defaults?"fade":"none");o.setAttribute("data-persona-scroll-to-bottom-transition",y),n&&t?o.setAttribute("data-persona-scroll-to-bottom-streaming",""):o.removeAttribute("data-persona-scroll-to-bottom-streaming"),o.style.display=t||"none"!==y?"":"none",o.disabled=!t,o.tabIndex=t?0:-1,o.setAttribute("aria-hidden",String(!t)),!t&&b&&(o.blur(),r&&(r.hasAttribute("tabindex")||(r.tabIndex=-1),r.focus({preventScroll:!0})));let v=l&&t,C=p.visible&&t&&"approval-below"===p.activity!==v;(C||!t)&&m.forEach(e=>e.cancel());let S=C&&!p.reducedMotion&&"function"==typeof o.animate?g():null,k=f?.approvalLabel??"Approval needed",A=v&&k?k:f?.label??"",M=f?.label||"Jump to latest";o.setAttribute("aria-label",v?`${k||"Approval needed"} below. ${M}`:`${M}${i>0?` (${i} new)`:""}${n&&t?" (response streaming below)":""}`),o.title=A,o.setAttribute("data-persona-scroll-to-bottom-has-label",String(!!A)),v?o.setAttribute("data-persona-scroll-to-bottom-approval",""):o.removeAttribute("data-persona-scroll-to-bottom-approval"),a.textContent=A,a.style.display=A?"":"none";let I=v?0:i;s.textContent=I>0?String(I):"",s.style.display=I>0?"":"none";let T=v?"approval-below":n&&t?"generating-below":"idle",E={...p,visible:t,hovered:t&&p.hovered,focused:t&&p.focused,activity:T},L=h||x(E);p=E,w(L),S&&(e=>{let t=getComputedStyle(o),r=t.getPropertyValue("--persona-motion-duration-base"),n=parseFloat(r)*(r.includes("ms")?1:1e3);if(0===n)return;let s={duration:n>0?n:200,easing:t.getPropertyValue("--persona-motion-easing").trim()||"ease-out"},i="none"===a.style.display?null:{overflow:"hidden"};m=[o.animate([{...e,...i},{...g(),...i}],s)],i&&m.push(a.animate([{opacity:0},{opacity:1}],s))})(S)},destroy(){m.forEach(e=>e.cancel()),y(),T.abort(),h?.removeEventListener?.("change",I),o.remove()}}}let Zt="webmcp:",er=new Map,tr=e=>{er.clear();for(let t of e){let e=t.title?.trim();e&&er.set(t.name,e)}},rr=e=>er.get(sr(e)),or=null;function nr(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`${ar(e,0).toString(36)}.${ar(e,2654435761).toString(36)}`}(t.join(""))}`}function ar(e,t){let r=3735928559^t,o=1103547991^t;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);r=Math.imul(r^n,2654435761),o=Math.imul(o^n,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)}let sr=e=>e.startsWith("webmcp:")?e.slice(7):e,ir=e=>e.startsWith(Zt),lr=()=>or?or():import("@mcp-b/webmcp-polyfill");function dr(e){return"webmcp"===e.toolType&&!e.executionId}function cr(e){let t=e.approval,r="pending"===t?.status&&dr(t),o=!1,n=t=>t.name&&ir(t.name)&&(o=!0,"complete"!==t.status||!0===e.agentMetadata?.awaitingLocalTool&&void 0===t.result&&void 0===t.success)?{...t,status:"complete",interrupted:!0,success:!1,error:"The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.",approvalStatus:"pending"===t.approvalStatus?"timeout":t.approvalStatus,startedAt:void 0===t.completedAt?void 0:t.startedAt}:t,a=e.toolCall?n(e.toolCall):void 0,s=e.tools?.map(n);return{...e,streaming:!o&&!r&&e.streaming,...r?{approval:{...t,status:"timeout",interrupted:!0}}:{},...a?{toolCall:a}:{},...s?{tools:s}:{},...o&&e.agentMetadata?.awaitingLocalTool?{agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}}:{}}}let pr=(e,t,r)=>{let o="transient"===t.mode,n=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)||o&&n&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},ur=(e,t,r)=>{t.parentElement&&e.parentElement===t.parentElement&&("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))},hr=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mr=e=>e.includes("|"),gr=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())},fr=e=>`| ${e.join(" | ")} |`,br=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,yr=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),vr=e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let o=t[e],n=t[e+1];if(!mr(o)||hr.test(o)||!hr.test(n))continue;let a=gr(o).length;if(a<1)continue;let s=br(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()||!mr(e))break;let o=fr(yr(gr(e),a));t[i]!==o&&(t[i]=o,r=!0)}e=i-1}return r?t.join("\n"):e},wr=(e,t)=>t?(at()?.stabilizeStreamingMarkdown??vr)(e):e,xr=e=>{let t=null;return r=>{let o=at();if(!o)return Ar(r);if(!t){let{Marked:r}=o,n=e?.markedOptions;t=new r({gfm:n?.gfm??!0,breaks:n?.breaks??!0,pedantic:n?.pedantic,silent:n?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,o)=>e({type:"heading",raw:o,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,o)=>e({type:"code",raw:"",text:t,lang:r,escaped:o})}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,o)=>e({type:"link",raw:"",href:t,title:r??null,text:o,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,o)=>e({type:"image",raw:"",href:t,title:r??null,text:o})}if(r.list){let e=r.list;t.list=(t,r,o)=>e({type:"list",raw:"",ordered:r,start:o,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,o)=>e({type:"list_item",raw:"",task:r,checked:o,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)}},Cr=e=>e?xr({markedOptions:e.options,renderer:e.renderer}):xr(),Sr=xr(),kr=e=>Sr(e),Ar=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Mr=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Ir=e=>`%%FORM_PLACEHOLDER_${e}%%`,Tr=(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=Ir(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 o=Ir(t.length);return t.push({token:o,type:r}),o}),r},Er={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".split("."),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".split(".")},Lr=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Br=()=>{let e=null;return t=>{let r=at();if(!r)return Ar(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:")&&!Lr.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,Er)}},Rr=e=>!1===e?null:"function"==typeof e?e:Br(),Pr="var(--persona-md-table-scroll-fade, 24px)",Nr=new WeakSet;function $r(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,o=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":Pr),e.style.setProperty("--persona-fade-r",o<=1?"0px":Pr)}function Wr(e){Nr.has(e)||(Nr.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&$r(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach($r)}let{setLoader:Hr,load:Dr,provide:Or,getSync:Fr}=_({fallbackImport:()=>import("./client-stream")}),zr=Hr,qr=Dr,jr=Fr,{setLoader:_r,load:Ur,provide:Vr,getSync:Kr}=_({fallbackImport:()=>import("./client-dispatch")}),Qr=_r,Jr=Ur,Gr=Kr,{setLoader:Yr,load:Xr}=_({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Zr=Yr,eo=Xr,{setLoader:to,load:ro}=_({fallbackImport:()=>import("@runtypelabs/persona/voice-client-tools")}),oo=to,no=ro;function ao(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function so(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function io(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}t=h(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}),r=h((e,r,o)=>{var n,a,s=o&&o.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=o&&o.__exportStar||function(e,t){for(var r in e)"default"!==r&&!Object.prototype.hasOwnProperty.call(t,r)&&s(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let l=t();function d(e,t=l.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return c(e.trim(),t)}Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return l.Allow}}),i(t(),e),n=class extends Error{},e.PartialJSON=n,a=class extends Error{},e.MalformedJSON=a,e.parseJSON=d;let c=(e,t)=>{let r=e.length,o=0,s=e=>{throw new n(`${e} at position ${o}`)},i=e=>{throw new a(`${e} at position ${o}`)},d=()=>(m(),o>=r&&s("Unexpected end of input"),'"'===e[o]?c():"{"===e[o]?p():"["===e[o]?u():"null"===e.substring(o,o+4)||l.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):"true"===e.substring(o,o+4)||l.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):"false"===e.substring(o,o+5)||l.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):"Infinity"===e.substring(o,o+8)||l.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):"-Infinity"===e.substring(o,o+9)||l.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):"NaN"===e.substring(o,o+3)||l.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):h()),c=()=>{let n=o,a=!1;for(o++;o<r&&('"'!==e[o]||a&&"\\"===e[o-1]);)a="\\"===e[o]&&!a,o++;if('"'==e.charAt(o))try{return JSON.parse(e.substring(n,++o-Number(a)))}catch(e){i(String(e))}else if(l.Allow.STR&t)try{return JSON.parse(e.substring(n,o-Number(a))+'"')}catch{return JSON.parse(e.substring(n,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},p=()=>{o++,m();let n={};try{for(;"}"!==e[o];){if(m(),o>=r&&l.Allow.OBJ&t)return n;let a=c();m(),o++;try{n[a]=d()}catch(e){if(l.Allow.OBJ&t)return n;throw e}m(),","===e[o]&&o++}}catch{if(l.Allow.OBJ&t)return n;s("Expected '}' at end of object")}return o++,n},u=()=>{o++;let r=[];try{for(;"]"!==e[o];)r.push(d()),m(),","===e[o]&&o++}catch{if(l.Allow.ARR&t)return r;s("Expected ']' at end of array")}return o++,r},h=()=>{if(0===o){"-"===e&&i("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(l.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}i(String(r))}}let n=o;for("-"===e[o]&&o++;e[o]&&-1===",]}".indexOf(e[o]);)o++;o==r&&!(l.Allow.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(n,o))}catch{"-"===e.substring(n,o)&&s("Not sure what '-' is");try{return JSON.parse(e.substring(n,e.lastIndexOf("e")))}catch(e){i(String(e))}}},m=()=>{for(;o<r&&" \n\r\t".includes(e[o]);)o++};return d()};e.parse=d})();let lo="ask_user_question",co="data-persona-ask-sheet-for",po="Type your own answer here",uo="Send",ho="data-ask-question-count",mo="data-ask-answers",go="data-ask-grouped",fo=!1,bo=e=>e.replace(/["\\]/g,"\\$&"),yo=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,vo=e=>e?.features?.askUserQuestion??{},wo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:o};let n=t.chunks;if(!n||0===n.length)return{payload:null,complete:o};try{let e=n.join(""),t=(0,r.parse)(e,r.STR|r.OBJ|r.ARR);if(t&&"object"==typeof t)return{payload:t,complete:o}}catch{}return{payload:null,complete:o}},xo=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!fo&&(fo=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Co={sheetBackground:"--persona-ask-sheet-bg",sheetBorder:"--persona-ask-sheet-border",sheetShadow:"--persona-ask-sheet-shadow",pillBackground:"--persona-ask-pill-bg",pillBackgroundSelected:"--persona-ask-pill-bg-selected",pillTextColor:"--persona-ask-pill-fg",pillTextColorSelected:"--persona-ask-pill-fg-selected",pillBorderRadius:"--persona-ask-pill-radius",customInputBackground:"--persona-ask-input-bg"},So=(e,t)=>{Object.entries(Co).forEach(([r,o])=>{let n=z(t,`features.askUserQuestion.styles.${r}`);"string"==typeof n&&n?e.style.setProperty(o,n):e.style.removeProperty(o)})},ko=(e,t,r)=>{if("rows"!==e)return null;let o=st("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let e=st("span","persona-ask-row-check");o.appendChild(e)}else{let e=st("span","persona-ask-row-badge");e.textContent=String(r+1),o.appendChild(e)}return o},Ao=e=>{let t=st("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},Mo=(e,t)=>{let r=st("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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=e.freeTextPlaceholder??po,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),"rows"!==t){let t=st("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??uo,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Io=e=>{let t=e.getAttribute(mo);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},To=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Eo=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Lo=e=>"true"===e.getAttribute(go),Bo=(e,t,r)=>{let o=vo(r),n=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=wo(t),i=Lo(e),l=To(e),d=Eo(e),c=i?((e,t)=>xo(e)[t]??null)(a,l):(e=>xo(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,o)=>{let n=st("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");n.setAttribute("role","group"),n.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++)n.appendChild(Ao(o));return n}if(s.forEach((e,t)=>{n.appendChild(((e,t,r,o)=>{let n=st("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(n.type="button",n.setAttribute("role",o?"checkbox":"button"),n.setAttribute("aria-pressed","false"),n.setAttribute("data-ask-user-action","pick"),n.setAttribute("data-option-index",String(t)),n.setAttribute("data-option-label",e.label),"rows"===r){let a=st("span","persona-ask-row-content"),s=st("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=st("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}n.appendChild(a);let i=ko(r,o,t);i&&n.appendChild(i)}else n.textContent=e.label,e.description&&(n.title=e.description);return n})(e,t,o,a))}),!1!==e?.allowFreeText){let e="rows"===o?"Other":"Other…";if("rows"===o){let r=st("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=st("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??po,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=ko(o,a,s.length);d&&r.appendChild(d),n.appendChild(r)}else{let r=st("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,n.appendChild(r)}}return n})(c,o,s,n);g.replaceWith(e)}if("rows"!==n){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(Mo(o,n))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=st("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=st("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??uo,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(o)),e.setAttribute("data-multi-select",p?"true":"false");let b=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let o=st("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=st("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=r.backLabel??"Back",n.setAttribute("data-ask-user-action","back"),n.disabled=0===e,o.appendChild(n);let a=st("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=st("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=st("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),o.appendChild(a),o})(l,d,o);b?b.replaceWith(t):e.appendChild(t)}else b&&b.remove();(e=>{let t=Io(e)[To(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(e=>{let t=e.getAttribute("data-option-label")??"",o=r.has(t);e.setAttribute("aria-pressed",o?"true":"false"),e.classList.toggle("persona-ask-pill-selected",o)});let n=new Set(Array.from(o).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!n.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Lo(e))return;let t=Io(e)[To(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!r);let n=e.querySelector('[data-ask-user-action="submit-multi"]');n&&(n.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},Ro=(e,t,r)=>{if(!r||!yo(e)||!1===vo(t).enabled)return;let o=e.toolCall.id;r.querySelectorAll(`[${co}]`).forEach(e=>{e.getAttribute(co)!==o&&e.remove()});let n=r.querySelector(`[${co}="${bo(o)}"]`);if(n)return void((e,t,r)=>{So(e,r);let{payload:o}=wo(t),n=Math.max(1,xo(o).length);n>Eo(e)&&(e.setAttribute(ho,String(n)),n>1&&!Lo(e)&&e.setAttribute(go,"true")),Bo(e,t,r)})(n,e,t);let{payload:a}=wo(e),s=((e,t,r)=>{let o=vo(t),n=(e=>"pills"===e.layout?"pills":"rows")(o),a=e.toolCall.id,s=xo(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 o={};return t.forEach((e,t)=>{let n="string"==typeof e?.question?e.question:"";if(n&&Object.prototype.hasOwnProperty.call(r,n)){let e=r[n];("string"==typeof e||Array.isArray(e))&&(o[t]=e)}}),o})(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=st("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(co,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(ho,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(go,l?"true":"false"),p.setAttribute("data-ask-layout",n),((e,t)=>{e.setAttribute(mo,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==o.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),So(p,t);let u=st("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=st("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=st("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=st("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");return g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==n&&p.appendChild(Mo(o,n)),Bo(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},Po=(e,t)=>{if(!e)return;let r=t?`[${co}="${bo(t)}"]`:`[${co}]`;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)})},No="suggest_replies",$o={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},Wo={name:No,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:$o,origin:"sdk",annotations:{readOnlyHint:!0}},Ho=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,Do=(e,t=4)=>{let r=e;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}let o=r?.suggestions;if(!Array.isArray(o))return[];let n=o.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>t?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of ${t}; extra suggestions dropped.`),n.slice(0,t)):n},Oo=(e,t=4)=>{for(let r=e.length-1;r>=0;r--){let o=e[r];if("user"===o.role)return null;if(!Ho(o))continue;let n=Do(o.toolCall?.args,t);return n.length>0?n:null}return null},Fo=new Set,zo=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,o=e=>{let o=t?.[e],n=r?.[e];void 0!==o&&void 0!==n&&o!==n&&((e,t,r)=>{let o=`${e}:${t}:${r}`;Fo.has(o)||(Fo.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,n,o)};e&&(o("enabled"),o("expose"));let n=t?.enabled??r?.enabled??!0;return{enabled:n,expose:!!n&&(t?.expose??r?.expose??!1)}},qo={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},jo={name:lo,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:qo,origin:"sdk",annotations:{readOnlyHint:!0}},_o=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(jo),zo(e).expose&&t.push((e=>{let t=e?.suggestions?.followUps?.maxItems,r="number"==typeof t&&Number.isFinite(t)?Math.max(1,Math.floor(t)):e?.future?.v5Defaults?5:4;return 4===r?Wo:{...Wo,parametersSchema:{...$o,properties:{suggestions:{...$o.properties.suggestions,maxItems:r,description:`1-${r} short, distinct follow-up replies, phrased in the user's voice.`}}}}})(e)),t},Uo=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Vo=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),Ko=()=>(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return null===e?null:{text:e,raw:r};let n=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/)?.[1]||e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/)?.[1];if(!t)return null;try{return Uo(t)}catch{return t}})(r);return null!==n&&(e=n),t=r.length,null===e?null:{text:e,raw:r}},close:async()=>{}}})(),Qo=()=>{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 null!==e||""===e?{text:e||"",raw:o}:null;try{let t=(0,r.parse)(o,r.STR|r.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?Uo(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=Uo(t.text)))}catch{}return t=o.length,null===e?null:{text:e,raw:o}},close:()=>{}}},Jo=()=>{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}},Go="4.34.0",{setLoader:Yo,load:Xo,provide:Zo}=_({fallbackImport:()=>import("./client-history")}),en=Yo,tn=Xo;o=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let rn=e=>"reason"in e?e.reason:void 0;n=class{#e;#t;#r;#o;#n;#a;#s;#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#b;#y;#v;#w;#x;#C;#S;#k;#A;constructor(e={},t={}){if(this.#u=0,this.#h=new Set,this.#m=null,this.clientSession=null,this.#g=null,this.#f=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#b=null,this.#y=!1,this.#v=!1,this.#w=!1,this.#x=null,this.#C=new Set,this.#S=new Set,this.webMcpBridge=null,this.#k=null,this.#M=null,this.#I=null,this.#n=e,this.#o=t,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??"https://api.runtype.com/v1/dispatch",this.#t={"Content-Type":"application/json","X-Persona-Version":Go,...e.headers},this.#r=!!e.debug,this.#a=e.streamParser??function(e){switch(e){case"json":return Qo;case"regex-json":return Ko;case"xml":return Jo;default:return Vo}}(e.parserType),this.#s=e.contextProviders??[],this.#i=e.requestMiddleware,this.#l=e.customFetch,this.#d=e.parseSSEEvent,this.#c=e.getHeaders,!0===e.webmcp?.enabled&&(this.#k=this.#T(e.webmcp))}#T(e){return eo().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:tr,getToolDisplayTitle:rr,loadPolyfill:lr});return void 0!==this.#A&&r.setConfirmHandler(this.#A),this.webMcpBridge=r,r}).catch(e=>(this.#k=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",e),null))}#E(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):!0===this.#n.webmcp?.enabled?(this.#k||=this.#T(this.#n.webmcp),this.#k):Promise.resolve(null)}updateConfig(e){this.#n=e}setHistoryInternals(e){this.#o=e}cancelStreams(){if(this.#u+=1,this.#n.backgroundConversations)for(let e of this.#h)e.cancel().catch(()=>{})}setSSEEventCallback(e){this.#p=e}setWebMcpConfirmHandler(e){this.#A=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return!0===this.webMcpBridge?.isOperational()}getVoiceClientTools(){if(!0!==this.#n.webmcp?.enabled)return null;let e=()=>this.#E(),t={open:async e=>(await no()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await((await e())?.snapshotForDispatch())??[];return{tools:t,fingerprint:nr(t)}},onChange:t=>{let r=null,o=!1;return e().then(e=>{e&&!o&&(r=e.watchToolChanges(t))}),()=>{o=!0,r?.()}},execute:async(t,r,o)=>{let n=await e();return n?n.executeVoiceToolCall(t,r,o):{status:"failed",error:{message:"WebMCP runtime failed to load."}}}};return t}executeWebMcpToolCall(e,t,r,o){return!0===this.#n.webmcp?.enabled?this.#E().then(n=>n?n.executeToolCall(e,t,r,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]}):null}getSSEEventCallback(){return this.#p}isClientTokenMode(){return!!this.#n.clientToken}#L(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.#n;if(!r)return{agentId:e,flowId:t};let n=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let e=r.slice(0,o),n=r.slice(o+1);if("runtype"===e){let e=ao(n);if(e)return e;throw Error(`[Persona] target "runtype:${n}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw 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(n).payload}}let n=ao(r);if(n)return n;let a=t?.default;if(a)return{kind:"payload",payload:a(r).payload};throw 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,o);return"agentId"===n.kind?{agentId:n.agentId}:"flowId"===n.kind?{flowId:n.flowId}:{targetPayload:n.payload}}isAgentMode(){return!(!this.#n.agent&&!this.#L().agentId)}#B(){return this.#n.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||"https://api.runtype.com"}#R(e){return`${this.#B()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),r=!1;for(;;){let n=t.conversationId,a=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!n||!a)throw new o("visitor_token_missing","Durable recovery is not enabled for this client session");let s=`${this.#B()}/v1/client/conversations/${encodeURIComponent(n)}/executions/${encodeURIComponent(e.executionId)}/events`,i=new URLSearchParams({sessionId:t.sessionId,after:e.after}),l=await fetch(`${s}?${i}`,{method:"GET",headers:{"X-Persona-Version":Go,"X-Visitor-Token":a},signal:e.signal});if(401!==l.status||r){if(!l.ok)throw await(await tn()).historyErrorFor(this.#P(),l,!0);return l}{r=!0;let e=await tn();t=await e.recoverFromUnauthorized(this.#P(),await e.readErrorCode(this.#P(),l),null,!0)}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#g||e&&new Date<e.expiresAt||this.#f===e?null:(this.#f=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#g)return this.#g;let e=this.#g=this.#N().then(t=>this.#g===e?(this.clientSession=t,this.#f=!1,this.resetClientToolsFingerprint(),this.#n.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#g===e&&(this.#g=null)});return e}#$(){return!0===this.#n.features?.history?.enabled&&this.isClientTokenMode()&&!this.#y}async readVisitorToken(){let e=this.#o.visitorStore;return e?(await e.ready,await e.get()??null):null}#W(){if(!this.#y){this.#H({state:"unavailable",reason:"history_disabled"}),this.#y=!0,!this.#v&&typeof console<"u"&&(this.#v=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.#o.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#S])e(!1)}}getHistoryIdentityStatus(){return this.#x??this.#D()}subscribeHistoryIdentityStatus(e){return this.#C.add(e),()=>{this.#C.delete(e)}}subscribeHistoryAvailability(e){return this.#S.add(e),this.#y&&e(!1),()=>{this.#S.delete(e)}}#D(){return this.isClientTokenMode()?!0!==this.#n.features?.history?.enabled||this.#y?{state:"unavailable",reason:"history_disabled"}:this.#O():{state:"unavailable",reason:"ineligible_mode"}}#O(){let e=this.#x;return"browser_only"===e?.state?e:this.#F()}#F(){return"browser"===this.#n.features?.history?.scope?{state:"browser_only",reason:"configured_browser_scope"}:this.#n.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#H(e){let t=this.getHistoryIdentityStatus(),r=t.state===e.state&&rn(t)===rn(e);if(this.#x=e,!r){this.#o.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#C])t(e)}}async#z(e){return new((Gr()??await Jr()).ClientDispatch)(this.#q()).createClientSession(e)}async#N(){return new((Gr()??await Jr()).ClientDispatch)(this.#q()).initializeSession()}async#j(e){let t=this.#n.getStoredSessionId?.()||null,r=this.#n.getStoredConversationId?.()||null,o=await this.#z({storedSessionId:t,identityProof:e}),n=this.#_(o,r,!1);return this.clientSession=n,this.#g=null,this.#f=!1,this.resetClientToolsFingerprint(),n}#_(e,t,r){let o=e.conversationId;return o&&t&&(r||o!==t)&&this.#o.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:o}),this.#n.setStoredSessionId?.(e.sessionId),o&&(this.#n.setStoredConversationId?.(o),this.#o.setStoredConversationRevision?.(e.conversationRevision??null)),e}#U(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#f=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error("prepareConversationSession() only available in client token mode");if(!this.#$())throw new o("history_disabled","Visitor history is disabled for this surface");await this.#o.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new o("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let n=await this.#z({conversationId:e,identityProof:r});return this.#U(n)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.#o.historyBootstrapReady;let e=await this.#z({});return this.#U(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#$()&&this.#H(this.#F())}clearClientSession(){this.clientSession=null,this.#g=null,this.#f=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#b=null}async sendFeedback(e){if(!this.isClientTokenMode())throw Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw Error("No active session. Please initialize session first.");return new((Gr()??await Jr()).ClientDispatch)(this.#q()).sendFeedback(e)}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#V(e){e?.throwIfAborted();let t=this.#n.identityProvider;if(void 0===t)return;let r,o,n=this.#n.getIdentityProof;if(!t.trim()||!n)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,r)=>{o=()=>r(e.reason),e.addEventListener("abort",o,{once:!0}),e.aborted&&o()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{o&&e?.removeEventListener("abort",o)}if("string"!=typeof r||!r.trim())throw Error("A fresh identity proof is required to send this message.");return{provider:t,token:r}}#M;#K(){let e=this;return this.#M??={get config(){return e.#n},headers:this.#t,getHeaders:this.#c,debug:this.#r,clientApiBase:()=>e.#B(),getClientApiUrl:t=>e.#R(t),getWebMcpBridge:()=>e.#E(),sendWithClientToolsDiff:(t,r,o,n)=>e.#Q(t,r,o,n),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#I;#P(){let e=this;return this.#I??={HistoryClientError:o,get config(){return e.#n},get historyInternals(){return e.#o},get clientSession(){return e.clientSession},clientApiBase:()=>e.#B(),setHistoryIdentityStatus:t=>e.#H(t),browserOnlyStatus:()=>e.#O(),derivedBrowserOnly:()=>e.#F(),reinitWithProof:t=>e.#j(t),isHistoryCapable:()=>e.#$(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await tn()).listConversations(this.#P(),e)}async getConversation(e,t){return(await tn()).getConversation(this.#P(),e,t)}async finalizeDisplayProjections(e,t){return(await tn()).finalizeDisplayProjections(this.#P(),e,t)}async deleteConversation(e,t){return(await tn()).deleteConversation(this.#P(),e,t)}async deleteAllConversations(e){return(await tn()).deleteAllConversations(this.#P(),e)}async resetVisitor(){return(await tn()).resetVisitor(this.#P())}async dispatch(e,t){e.signal?.throwIfAborted(),qr().catch(()=>{});let r=this.isClientTokenMode(),o=this.isAgentMode(),n=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;r&&(this.#m=n),t({type:"status",status:"connecting"});let a=Gr()??await Jr().catch(e=>{let o=e instanceof Error?e:Error(String(e));throw r&&this.#m!==n||t({type:"error",error:o}),o});if(e.signal?.throwIfAborted(),r&&this.#m!==n)throw new DOMException("Turn superseded","AbortError");let s=new a.ClientDispatch(this.#q());return r?s.dispatchClientToken(e,t,n):o?s.dispatchAgent(e,t):s.dispatchProxy(e,t)}#q(){let e=this;return Object.setPrototypeOf({HistoryClientError:o,get claimInFlight(){return e.#w},set claimInFlight(t){e.#w=t},get clientToolsFingerprintSessionId(){return e.clientToolsFingerprintSessionId},set clientToolsFingerprintSessionId(t){e.clientToolsFingerprintSessionId=t},get lastSentClientToolsFingerprint(){return e.lastSentClientToolsFingerprint},set lastSentClientToolsFingerprint(t){e.lastSentClientToolsFingerprint=t},get sentNonEmptyClientToolsSessionId(){return e.#b},set sentNonEmptyClientToolsSessionId(t){e.#b=t},get historyInternals(){return e.#o},markHistoryUnavailable:()=>e.#W(),apiUrl:this.#e,contextProviders:this.#s,requestMiddleware:this.#i,customFetch:this.#l,get clientSession(){return e.clientSession},set clientSession(t){e.clientSession=t},isCurrentTurn:t=>e.#m===t,isHistoryCapable:()=>e.#$(),createClientSession:t=>e.#z(t),finishInit:(t,r,o)=>e.#_(t,r,o),resetSessionWarmLatch:()=>{e.#f=!1},resetClientToolsFingerprint:()=>e.resetClientToolsFingerprint(),clearClientSession:()=>e.clearClientSession(),resolveChatIdentityProof:t=>e.#V(t),routing:()=>e.#L(),builtInClientTools:_o,streamResponse:(...t)=>e.#J(...t)},this.#K())}async processStream(e,t,r,o,n,a,s){t({type:"status",status:"connected"});try{await this.#J(e,t,r,o,n,a,s)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t,r){return(await qr()).resolveApproval(this.#K(),e,t,r)}async#Q(e,t,r,o){return new((Gr()??await Jr()).ClientDispatch)(this.#q()).sendWithClientToolsDiff(e,t,r,o)}async resumeFlow(e,t,r){return(await qr()).resumeFlow(this.#K(),e,t,r)}async#J(e,t,r,o,n,a,s){let{streamResponse:i}=jr()??await qr();return i({config:()=>this.#n,streamGeneration:()=>this.#u,streamReaders:this.#h,createStreamParser:this.#a,parseSSEEvent:this.#d,onSSEEvent:(e,t)=>this.#p?.(e,t)},e,t,r,o,n,a,s)}},a=class extends Error{constructor(e,t,r){super(t),this.name="HistoryProviderError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let{setLoader:on,load:nn}=_({fallbackImport:()=>import("@runtypelabs/persona/background-runtime")}),an=on,sn=nn,{setLoader:ln,load:dn,provide:cn,getSync:pn}=_({fallbackImport:()=>import("./session-actions")}),un=ln,hn=dn,mn=pn;function gn(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function fn(e){return{type:"text",text:e}}let bn=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yn=[...bn,"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 vn(e){return function(e){return bn.includes(e)||e.startsWith("image/")}(e.type)}function wn(e,t=yn,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 xn(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"}let Cn=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function Sn(e){return"card"===e?"collapsed":e}function kn(e){return e.split(";",1)[0].trim().toLowerCase()}function An(e,t){let r=e?.display,o="string"==typeof r?{default:r}:r??{};if(t.file&&o.files){if("string"==typeof o.files)return{mode:Sn(o.files),matchedBy:{type:"files"}};let e=t.file.mimeType?kn(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,o]of r)if(kn(e)===t)return{mode:Sn(o),selector:kn(e)};let o=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(kn(e)===o)return{mode:Sn(t),selector:o}}(o.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(o.files.default)return{mode:Sn(o.files.default),matchedBy:{type:"files"}}}let n=o.byKind?.[t.artifactType];if(n)return{mode:Sn(n),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:Sn(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:Sn(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:Sn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Mn(e,t){return An(e,t).mode}function In(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 Tn(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function En(e,t){let r=e.findIndex(e=>e.id===t);return r>=0&&"user"===e[r].role&&!e.slice(r+1).some(e=>"operator"===e.role)}function Ln(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;--t){if("operator"===e[t].role)return null;if("user"===e[t].role)return e[t].id}return null}function Bn(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 Rn(){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 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,r.parse)(o,r.STR|r.OBJ),o);t&&(e=t)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function Pn(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=bt(r,e.component);if(!a){if(vt.includes(e.component)){Tt().catch(()=>{});let e=st("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=t.context??{message:o,config:r,signal:t.signal??(new AbortController).signal,updateProps:e=>{n&&n(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Nn(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 $n(e){let t=Nn(e);if(!t)return!1;try{let e=JSON.parse(t);return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component}catch{return!1}}function Wn(e){let t=Nn(e);if(!t)return null;try{let e=JSON.parse(t);if("object"==typeof e&&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}function Hn(e,t=e.contentParts??e.llmContent??e.rawContent??e.content){let r=e.content;if("string"!=typeof r)return;let o=e.contentParts??e.llmContent??e.rawContent??r;return""===r&&(t===o||JSON.stringify(t)===JSON.stringify(o))||"string"==typeof t&&t===r?void 0:r}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(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a})}function On(e){for(let t of["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)"]){let r=e.find(e=>e.name===t);if(r)return r}return e.find(e=>e.lang.startsWith("en"))??e[0]}function Fn(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?e:t)}s=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?.(Error("Web Speech API is unavailable"));let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(n.voice=e)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):On(a));void 0!==t.rate&&(n.rate=t.rate),void 0!==t.pitch&&(n.pitch=t.pitch),n.onend=()=>r.onEnd?.(),n.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{o.speak(n),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},i=class{#e=null;#t=null;#r="idle";#o=new Set;#n=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#r:"idle"}activeMessageId(){return this.#t}onChange(e){return this.#o.add(e),()=>this.#o.delete(e)}toggle(e,t){if(this.#t===e){if("playing"===this.#r)return void(this.#e?.supportsPause?(this.#e.pause(),this.#s(e,"paused")):this.stop());if("paused"===this.#r)return this.#e?.resume(),void this.#s(e,"playing");if("loading"===this.#r)return void this.stop()}this.play(e,t)}async play(e,t){let r=++this.#n;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#n)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#n&&this.#s(e,"playing")},onEnd:()=>{r===this.#n&&this.#s(null,"idle")},onError:()=>{r===this.#n&&this.#s(null,"idle")}})}catch{r===this.#n&&this.#s(null,"idle")}}stop(){this.#n++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#o)e(this.#t,this.#r)}},l=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!(this.#t||e&&this.#e&&e!==this.#e)}};let zn=null,qn=()=>zn?zn():import("./voice/runtype-tts-entry"),{setLoader:jn,load:_n}=_({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Un=jn,Vn=_n,Kn="apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.modelMessageTransform.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId".split(".");function Qn(e,t){let r=e instanceof Error?e:Error(String(e));if("string"==typeof t)return t;if("function"==typeof t)return t(r);let o=r.message.trim(),n=/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.?)$/i.test(o),a=/^(Chat backend|Agent execution) request failed: \d{3}\b/.test(o),s=n?"Sorry: I couldn't reach the assistant. Please check your connection and try again.":a?"Sorry: the chat service couldn't complete the request. Please try again.":"Sorry: the chat encountered an unexpected error. Please reload the page and try again.";return o?`${s}\n\n_Details: ${o}_`:s}d=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};let Jn=e=>ir(e)||"suggest_replies"===e;c=class e{#e;#t;#r;#o;#n(e){if(this.#a("cancel"),this.#r=!1,this.#e={runId:`run-${io()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:new Set},e)for(let t of this.messages)"assistant"===t.role&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;null!==this.#o&&clearTimeout(this.#o),this.#o=null;let r=this.#e;if(this.#e=null,r){let t=r;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#s(){if(!this.#e||null!==this.#o)return;let e=this.#e;this.#o=setTimeout(()=>{this.#o=null,this.#e===e&&(!this.#r&&(this.streaming||this.#u||this.#G()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#r?"error":"success"))},0)}#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#b;#y;#v;#w;#x;#C;#S;#k;#A;#T;#E;#L;#B;#R;#$;#W;#D;#O;#F;#H;#z;#N;#j;#_;#U;#V;#M;#K;#I;#P;#q;#Q;#J;constructor(e={},t,r={}){this.config=e,this.callbacks=t,this.historyInternals=r,this.status="idle",this.#e=null,this.#r=!1,this.#o=null,this.streaming=!1,this.#i=new Map,this.abortController=null,this.#d=Date.now(),this.clientSession=null,this.agentExecution=null,this.#c=null,this.#p=null,this.#u=!1,this.#m=null,this.#g=null,this.#f=null,this.#b=null,this.#y=null,this.#v=null,this.artifacts=new Map,this.#w=null,this.webMcpInflightKeys=new Set,this.webMcpResolvedKeys=new Set,this.webMcpResolveControllers=new Set,this.#x=0,this.webMcpApprovalResolvers=new Map,this.#C=0,this.approvalTokens=new Map,this.webMcpAwaitBatches=new Map,this.#S=null,this.#k=null,this.#A=0,this.#T=0,this.#E=!1,this.#L="disconnected",this.#B=null,this.#R=null,this.#$=null,this.#W=0,this.#D=0,this.#O=null,this.#F=Promise.resolve(),this.#H=!1,this.#z=null,this.#N=!1,this.#j=null,this.#_=new Map,this.#U=null,this.#V=new Map,this.#M=null,this.#K=null,this.#I=!1,this.#P=null,this.#q=null,this.#Q=!1,this.#J=null,this.#Y=null,this.#X=null,this.#Z=new l,this.#ee=Promise.resolve(),this.#te=null,this.#re=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new i(()=>this.#oe()),this.#ne=null,this.#ae=0,this.handleEvent=(e,t=!1)=>{if(this.#m)return void this.#m.push({event:e,readOnlyReplay:t});let r=this.#re,o=!1;if(r&&("error"===e.type||"status"===e.type&&"error"===e.status?r.failed=!0:"message"===e.type&&"assistant"===e.message.role&&(r.dropped||this.ttsSpokenMessageIds.add(e.message.id),r.ids.includes(e.message.id)||r.ids.push(e.message.id),o=!0)),"message"===e.type){this.#e&&!t&&"assistant"===e.message.role&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||"approval"===e.message.variant&&"pending"===e.message.approval?.status)&&this.#se("needs-attention"),o&&r.onUpdate?.(),"approval"===e.message.variant&&e.message.approval&&"pending"!==e.message.approval.status&&this.#i.set(e.message.id,this.#l),"assistant"===e.message.role&&!e.message.variant&&e.message.streaming&&(this.#p=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&hn().catch(()=>{});let n=e.message.toolCall,a=!!n?.name&&(ir(n.name)||"suggest_replies"===n.name&&zo(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&a&&!t&&!0===this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool&&this.#ie(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution&&this.agentExecution.executionId===e.message.agentMetadata.executionId?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.#h=e.checkpoint,this.#le(e.id);else if("status"===e.type){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0},this.#se("running")),"idle"===e.status&&!e.terminal&&this.#de())return void this.#ce();if("error"===e.status?this.#se("failed"):e.terminal&&"idle"===e.status&&this.#se("completed"),this.#pe(e.status),"connecting"===e.status)this.#ue(!0);else if("idle"===e.status||"error"===e.status){this.#G()||this.#he(),0===this.webMcpResolveControllers.size&&(this.#ue(!1),this.abortController=null,this.#me(),this.#ge());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;"running"===this.agentExecution?.status&&("error"===e.status?this.agentExecution.status="error":t||(this.agentExecution.status="complete")),this.#fe()}}else"error"===e.type?(this.#se("failed"),this.#pe("error"),this.#he(),0===this.webMcpResolveControllers.size&&(this.#ue(!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.#be(e)},this.historyInternals=this.#ye(r),this.messages=[...e.initialMessages??[]].map(e=>({...cr(e),sequence:e.sequence??this.#ve()})),this.messages=this.#we(this.messages),this.client=new n(e,this.historyInternals),this.#xe(),this.#Ce();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:"complete"});null!=e.initialSelectedArtifactId&&(this.#w=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Se(),this.callbacks.onStatusChanged(this.status),this.#ke(),this.#Ae()}#Ae(){this.config.voiceRecognition?.provider&&qt().catch(()=>{})}#ke(){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&&qn().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.#E}getVoiceStatus(){return this.#L}getVoiceNotice(){return this.#S?.takeNotice?.()??null}getVoiceDisclosure(){return this.#S?.getDisclosure?.()??null}getVoiceLevel(){return this.#S?.onLevel?this.#T:null}getVoiceInterruptionMode(){return this.#S?.getInterruptionMode?this.#S.getInterruptionMode():"none"}stopVoicePlayback(){this.#S?.stopPlayback&&(this.#Z.cancel(),this.#te?.cancel(),this.#S.stopPlayback())}isBargeInActive(){return this.#S?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#S?.deactivateBargeIn&&await this.#S.deactivateBargeIn()}#Y;#X;#Z;#ee;#te;#re;#oe(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=s.isSupported()?new s({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,n=this.config.clientToken,a=!1!==e.browserFallback;if(r&&o&&n)return qn().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:o,clientToken:n,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 n&&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 Error("Voice configuration not provided");this.cleanupVoice();let r=this.#ee,o=++this.#A;this.#k=qt().then(async e=>{await r,o===this.#A&&this.#Me(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{o===this.#A&&(this.#k=null)})}catch(e){console.error("Failed to setup voice:",e)}}#Me(e,t){this.#S=t;let r=this;e.wireSessionVoice({session:this,provider:()=>r.#S,generation:()=>r.#A,get keyed(){return r.#te},set keyed(e){r.#te=e},get pendingUser(){return r.#Y},set pendingUser(e){r.#Y=e},get pendingAssistant(){return r.#X},set pendingAssistant(e){r.#X=e},turns:()=>r.#Z,busy:()=>r.#Ie(),setStreaming:e=>r.#ue(e),setDelegation:e=>{r.#re=e},setLevel:e=>{r.#T=e},setStatus:e=>{r.#L=e,r.#E="listening"===e},settlePending:e=>r.#Te(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#A;if(!this.#S&&this.#k&&await this.#k,e===this.#A)if(this.#S)if(this.#E)await this.#S.stopListening();else{this.stopSpeaking();try{await this.#S.startListening()}catch(e){console.error("Failed to start voice:",e)}}else console.error("Voice not configured")}prewarmVoice(){if(!_t(this.config.voiceRecognition?.provider))return void this.warmClientSession();let e=this.#A,t=()=>{let t=this.#S;t?.prewarm&&e===this.#A&&(this.#E||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#S&&this.#k?this.#k.then(t,()=>{}):t()}#Ie(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#u||"resuming"===this.status}cleanupVoice(){let e=null!==this.#S;if(this.#A++,this.#k=null,this.#S){let e=this.#S;this.#S=null,this.#ee=this.#Ee(e)}this.#E=!1,this.#L="disconnected",this.#Te(!0),this.#te?.settle(),this.#te=null,this.#Z=new l,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#Ee(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#Te(e){let t=e?this.#Y:null,r=this.#X;(t||r)&&(r&&this.#Z.cancel(),e&&(this.#Y=null),this.#X=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.#ue(!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.#K=this.historyInternals.getStoredConversationRevision?.()??null,this.#I=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e: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.#Le(e,t)}#Le(e,t=!this.messages.length){if(this.#H||!e.config.welcomeMessage||!t)return;let r=this.messages[0],o={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:r?.createdAt??(new Date).toISOString(),sequence:r?(r.sequence??0)-1:this.#ve()};this.#Be(o)}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){e.historyProvider!==this.historyInternals.historyProvider&&(this.#W+=1,this.#D+=1,this.config.backgroundConversations&&this.cancel(),this.#Re()),this.historyInternals=this.#ye(e),this.client.setHistoryInternals(this.historyInternals),this.#xe()}destroy(){this.#Re(),this.#W+=1,this.#D+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#P?.(),this.#P=null,this.#q=null}#ye(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#Pe(e),t?.(e)}}}get#Ne(){return this.historyInternals.historyProvider??null}#$e(){let e=this.#Ne;if(!e)throw new d("history_unavailable","No conversation history provider is installed");return e}#We(e){let t=this.#$e(),r=e??this.config.features?.history?.scope,o=this.config.getIdentityProof?"verified-user":"browser",n=r??(t.capabilities.scopes.includes(o)?o:t.capabilities.scopes[0]??o);if(!t.capabilities.scopes.includes(n))throw new a("unsupported_scope","This history scope is not supported.");return{scope:n}}getHistoryState(){return{activeConversationId:this.#B,conversationRevision:this.#R,nextMessageCursor:this.#$,recovery:this.#z,sendBlocked:this.#N}}getActiveConversationId(){return this.#B}#He(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#De(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#j;e&&await e.catch(()=>{});let t=this.#U;t&&await t.catch(()=>{})}#Oe(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new d("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#$e().list({...e?.cursor?{cursor:e.cursor}:{},...void 0===e?.limit?{}:{limit:e.limit},...void 0===e?.targetId?{}:{targetId:e.targetId},context:this.#We(e?.scope)})}async openConversation(e,t){let r=this.#$e();"background"===t?.busy&&this.assertBackgroundSwitchable(),"stop"===t?.busy&&this.cancel(),"background"!==t?.busy&&this.#Oe();let o=this.#We(t?.scope),n=++this.#W,a=this.#D;if("background"===t?.busy&&await this.#Fe(),await this.awaitHistorySettled(),n!==this.#W)throw new d("superseded","A later selection won");let s=await r.getPage(e,{context:o});if(n!==this.#W)throw new d("superseded","A later selection won");let i=await r.prepareOpen(e,{context:o}),l=this.#F.then(async()=>{if(n!==this.#W)throw i.discard(),new d("superseded","A later selection won");"stop"===t?.busy&&this.cancel();try{"background"===t?.busy?this.assertBackgroundSwitchable():this.#Oe()}catch(e){throw i.discard(),e}let o=this.#B,l=this.#e;t?.onBeforeCommit?.(),"background"===t?.busy&&(this.#m=[]),this.#H=!0,this.#O=a;try{if(await this.#ze(i),a!==this.#D||r!==this.#Ne)throw new d("superseded","The history identity changed");if("background"===t?.busy&&o&&this.#c){let e={conversationId:o,handle:this.#c,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#w,streamCheckpoint:this.#h};this.#g?.save(e)}this.#B=i.conversationId||e,this.#R=i.conversationRevision||s.conversationRevision||null,this.#$=s.nextCursor,this.#z=null,this.#N=!1,this.#qe();for(let e of s.messages)this.#V.set(e.id,e.content);this.#je();let n=this.#g?.take(this.#B);return this.hydrateMessages(n?.messages??s.messages),n&&(this.hydrateArtifacts(n.artifacts,n.selectedArtifactId,!0),this.#_e(n)),t?.onCommitted?.(),this.#He(),{summary:s.summary,nextMessageCursor:s.nextCursor}}finally{this.#H=!1,this.#O=null;let e=this.#m;if(this.#m=null,e&&this.#e===l&&this.#B===o)for(let{event:t,readOnlyReplay:r}of e)this.handleEvent(t,r)}}),c=l.then(()=>{},()=>{});this.#F=c,this.#j=c;try{return await l}finally{this.#j===c&&(this.#j=null)}}loadOlderMessages(e,t,r){let o=this.#$e(),n=this.#We(r?.scope),a=t??this.#$;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let s=`${e} ${a}`,i=this.#_.get(s);if(i)return i;let l=this.#Ue(o,e,a,n).finally(()=>{this.#_.delete(s)});return this.#_.set(s,l),l}async#Ue(e,t,r,o){let n=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...n?{beforeCreatedAt:n}:{},context:o});if(this.#B&&this.#B!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=this.#Ve(a.messages),i=Dn(this.messages,s);this.messages=this.#we(i.map(e=>this.#Ke(e))),this.#$=a.nextCursor;for(let e of a.messages)this.#V.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#He(),{messages:s,nextMessageCursor:a.nextCursor}}#Ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let r=t.get(e.id);if(r){if(this.webMcpApprovalResolvers.has(r.id)||r.approval&&dr(r.approval)&&r.approval.id===e.approval?.id&&"pending"!==r.approval.status&&"pending"===e.approval?.status)return r;let t=r.agentMetadata?.executionId,o=[...r.toolCall?[r.toolCall]:[],...r.tools??[]];if(t&&o.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return r}return cr(e)})}async startNewConversation(e){let t=this.#$e(),r=this.#We(e?.scope),o=++this.#W,n=this.#D;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:r}),s=this.#F.then(async()=>{if(o!==this.#W)throw a.discard(),new d("superseded","A later action won");e?.onBeforeCommit?.(),this.#H=!0,this.#O=n;try{await this.#ze(a)}finally{this.#H=!1,this.#O=null}if(n!==this.#D||t!==this.#Ne)throw new d("superseded","The history identity changed");this.#Qe(!1,!0),this.#B=a.conversationId||null,this.#R=a.conversationRevision||null,this.#$=null,this.#z=null,this.#N=!1,this.#je(),this.clientSession&&this.#Le(this.clientSession),e?.onCommitted?.(),this.#He()}),i=s.then(()=>{},()=>{});this.#F=i,this.#j=i;try{await s}finally{this.#j===i&&(this.#j=null)}}async#Je(e,t=!1){this.#Qe(t),await this.#ze(e),this.#B=e.conversationId||null,this.#R=e.conversationRevision||null,this.#$=null,this.#z=null,this.#N=!1,this.#je(),this.#He()}async deleteConversation(e,t){let r=this.#$e(),o=this.#We(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:o}),this.#g?.clear(e),e===this.#B&&await this.#Ge(o)}async updateConversation(e,t,r){let o=this.#$e();if(!o.update)throw new d("history_unavailable","This history provider cannot update conversations");let n=this.#We(r?.scope);return await this.awaitHistorySettled(),o.update(e,t,{context:n})}canUpdateConversations(){return"function"==typeof this.#Ne?.update}async clearConversationHistory(e){let t=this.#$e(),r=this.#We(e?.scope);await this.awaitHistorySettled();let o=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return this.#Re(),await this.#Ge(r),o}async resetHistoryDevice(){let e=this.#$e();if(!e.resetDevice)throw new d("history_unavailable","This history provider cannot reset the device");this.#Re(),this.#W+=1,this.#D+=1,this.#U=null;try{return await e.resetDevice()}finally{this.#Qe(),this.#B=null,this.#R=null,this.#$=null,this.#z=null,this.#N=!1,this.#He()}}async#Ge(e){this.#W+=1,this.#D+=1,this.#U=null,this.#Qe(),this.#B=null,this.#R=null,this.#$=null,this.#N=!0,this.#z=null,this.#He(),await this.#Ye(e)}async#Ye(e){let t=this.#Ne;if(t)try{let r=await t.prepareStartNew({context:e});await this.#Je(r)}catch{this.#N=!0,this.#z="new_conversation_required",this.#He(),this.#De("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}else this.#N=!1,this.#He()}async#Xe(){if("new_conversation_required"===this.#z&&this.#Ne&&(this.#z=null,await this.#Ye(this.#We()),"new_conversation_required"===this.#z))throw new d("new_conversation_required","A new conversation is required before sending")}async#ze(e){if(await e.commit(),null!==this.#O&&this.#O!==this.#D)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(null===this.#O||this.#O===this.#D)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#B=e.conversationId,this.#R=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#H||this.#Le(e))}#je(){this.#B?this.config.setStoredConversationId?.(this.#B):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#R),this.historyInternals.setStoredMessageCursor?.(this.#$)}#qe(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ze(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#V.clear(),this.#et(null)}#Qe(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ae++,this.messages=[],this.#qe(),this.#_.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#ue(!1),this.#pe("idle"),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a("cancel")}#Pe(e){this.#Re(),this.#W+=1,this.#D+=1,this.#U=null,this.#N=!0,this.#Qe(),this.#B=e.conversationId,this.#R=null,this.#$=null,this.#z=null,this.#He(),this.#De("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#j=Promise.resolve().then(()=>{this.#N=!1,this.#j=null,this.#He()})}#xe(){let e=this.historyInternals.visitorStore??null;e!==this.#q&&(this.#P?.(),this.#P=null,this.#q=e,e&&(this.#P=e.subscribe(e=>this.#ot(e))))}#ot(e){if("external"!==e.source||null===e.previousToken)return;this.#Re(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#W+=1,this.#D+=1,this.#U=null,this.#Q=!0,this.#J=null;let t=this.messages.length>0;t||null!==this.#B||null!==(this.config.getStoredConversationId?.()??null)?this.#Qe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#_.clear(),this.#et(null)),this.#B=null,this.#R=null,this.#$=null,this.#z=null,this.#He(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#De("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#nt(){return this.#Q?(this.#J||=this.#at().finally(()=>{this.#J=null}),this.#J):Promise.resolve()}async#at(){if(this.isClientTokenMode())try{this.bindActivatedSession(await this.client.initSession()),this.#Q=!1}catch{}else this.#Q=!1}reconcileBootConversation(e){let t=this.#Ne,r=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#B;if(!t||!r)return Promise.resolve();let o=this.#We(e?.scope);this.#N=!0,this.#He();let n=this.#st(t,r,o).finally(()=>{this.#N=null!==this.#z,this.#j===n&&(this.#j=null),this.#He()});return this.#j=n,n}async#st(e,t,r){this.#B=t;let o=this.clientSession?.conversationRevision??this.#R??null,n=this.#I?this.#K:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#I=!1,this.#$=this.historyInternals.getStoredMessageCursor?.()??this.#$,await this.replayPendingProjections(),o&&n&&o===n)return void(this.#R=o);let a,s=await e.getPage(t,{context:r}),i=this.#Ve(s.messages),l=new Set(s.messages.map(e=>e.id)),d=this.messages.some(e=>l.has(e.id)),c=s.messages[0]?.createdAt;if(d){let e=this.#c?this.#p:null;a=Dn(this.messages.filter(t=>!(!l.has(t.id)&&t.id!==e)||void 0!==c&&t.createdAt<c),i).map(e=>this.#Ke(e))}else a=i.map(e=>this.#Ke(e));this.#$=s.nextCursor,this.#R=s.conversationRevision||o||null,this.#V.clear();for(let e of s.messages)this.#V.set(e.id,e.content);this.#je(),this.#t=void 0,this.messages=this.#we(a),this.callbacks.onMessagesChanged([...this.messages])}#it(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#et(e){this.#M=e,this.historyInternals.setPendingDisplayProjections?.(e)}#lt(){return this.historyInternals.getPendingDisplayProjections?.()??this.#M}#dt(e){if(this.#it())for(let t of e){let e=Hn(t);void 0!==e&&this.#V.set(t.id,e)}}#ge(){if(!this.#it())return;let e=this.#B;if(!e)return;let t=[];for(let e of this.messages){if("assistant"!==e.role||e.streaming)continue;let r=Hn(e);void 0!==r&&this.#V.get(e.id)!==r&&t.push({id:e.id,displayContent:r})}0!==t.length&&(this.#et({conversationId:e,messageIds:t.map(e=>e.id)}),this.#ct(e,t))}#ct(e,t){let r=(this.#U??Promise.resolve()).catch(()=>{}).then(()=>this.#pt(e,t,!1)).finally(()=>{this.#U===r&&(this.#U=null)});this.#U=r}async#pt(e,t,r){if(this.#B!==e)return;let n=t.filter(e=>this.#V.get(e.id)!==e.displayContent);if(0===n.length)this.#ut(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,n);for(let e of n)this.#V.set(e.id,e.displayContent);this.#B===e&&r&&(this.#R=r),this.#ut(e,t)}catch(a){if(!r&&this.#ht(a))return void await this.#pt(e,n,!0);if(a instanceof o&&("not_found"===a.code||"conversation_deleted"===a.code))return void this.#ut(e,t);this.#De("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ht(e){return e instanceof o?"request_failed"===e.code:e instanceof Error}#ut(e,t){let r=this.#lt();if(!r||r.conversationId!==e)return;let o=new Set(t.map(e=>e.id)),n=r.messageIds.filter(e=>!o.has(e));this.#et(n.length?{conversationId:e,messageIds:n}:null)}async replayPendingProjections(){if(!this.#it())return;let e=this.#lt();if(!e)return;if(this.#B&&e.conversationId!==this.#B)return void this.#et(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.#et(null):(this.#ct(e.conversationId,t),await(this.#U?.catch(()=>{})))}#me(){this.#B&&(this.#R=null,this.historyInternals.setStoredConversationRevision?.(null))}async#mt(){await this.awaitHistorySettled(),await this.#nt(),"new_conversation_required"===this.#z&&await this.#Xe()}static#gt(e){return e instanceof o&&"conversation_deleted"===e.code}async#ft(t,r,o,n,a){let s=this.#e,i=e=>{this.#e===s&&this.handleEvent(e)};this.#dt(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},i)}catch(t){if(r.signal.aborted||this.#e!==s||!e.#gt(t))throw t;let l=await this.#bt(n);if(!l)throw t;this.#dt([l]),await this.client.dispatch({messages:[l],signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},i)}}async#bt(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#W+=1,this.#D+=1,this.#U=null,this.#Qe(!0),this.#B=null,this.#R=null,this.#$=null,this.#H=!0;try{let e=this.#Ne;if(e){let t=await e.prepareStartNew({context:this.#We()});await this.#Je(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#N=!0,this.#z="new_conversation_required",this.#He(),this.#De("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#H=!1}return this.#Be(r),this.#ue(!0),this.#De("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},o=function(e,t){let r=e.voiceRecognition,o=t.voiceRecognition;return!0===r?.enabled!=(!0===o?.enabled)||r?.provider?.type!==o?.provider?.type||r?.provider?.custom!==o?.provider?.custom||Ut(e)!==Ut(t)||r?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),a=function(e,t){return Kn.some(r=>e[r]!==t[r])}(this.config,r);a&&(this.cancel(),this.#Re()),this.config=r,o&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&Ut(r)&&this.setupVoice());let s=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!a)return this.client.updateConfig(r),void(s&&this.#yt());this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let i=this.client.getSSEEventCallback();this.#W+=1,this.#D+=1,this.client=new n(this.config,this.historyInternals),s&&this.#yt(),this.#Ce(),i&&this.client.setSSEEventCallback(i)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#vt(e);return this.upsertMessage(t),t}#vt(e){let{role:t,content:r,llmContent:o,contentParts:n,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e;return{id:a??("user"===t?so():"assistant"===t?io():`${"operator"===t?"operator":"system"}-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:r,createdAt:s??(new Date).toISOString(),sequence:i??this.#ve(),streaming:l,...void 0!==o&&{llmContent:o},...void 0!==n&&{contentParts:n},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p},...void 0!==e.dispatchError&&{dispatchError:e.dispatchError},...void 0!==e.author&&{author:{...e.author}}}}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=e.map(e=>this.#vt(e));return this.messages=this.#we([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:n,id:a,createdAt:s,sequence:i}=e,l={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...void 0!==n&&{llmContent:n},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}updateComponentProps(e,t){let r=this.messages.find(t=>t.id===e),o=r&&Wn(r);return!(!r||"assistant"!==r.role||r.variant||!o||(this.upsertMessage({...r,rawContent:JSON.stringify({text:r.content,component:o.component,props:t})}),0))}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!(!t||"assistant"!==t.role||t.variant||!Wn(t)||(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),0))}async#wt(e,t,r){let o;try{o=await r()}catch{return}let n=o.blocks.join("\n\n"),a=[n,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=o.contentParts.length>0;if(s){let t=[];n&&t.push(fn(n)),t.push(...o.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(fn(a)),t.push(...o.contentParts),e.contentParts=t}else n&&(e.llmContent=a);Object.keys(o.context).length>0&&(e.mentionContext=o.context)}async sendMessage(e,t){let r=e.trim(),o=!!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||o))return;this.#re&&!t?.voiceTurn&&(this.#re.failed=!0,this.#re=null),(this.#j||this.#U||this.#N||this.#Q)&&await this.#mt(),this.stopSpeaking(),this.client.cancelStreams(),this.abortController?.abort(),this.#n(),this.#rt(),this.#ae++,this.#tt();let n=t?.voiceTurn?.userMessageId,a=n?this.messages.find(e=>e.id===n&&"user"===e.role):void 0,s=a?.id??so(),i=io();this.#p=null;let l=t?.contentParts&&gn(t.contentParts)?"[Image]":"",d={id:s,role:"user",content:r||l,createdAt:(new Date).toISOString(),sequence:this.#ve(),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.#Be(d),this.#ue(!0);let c=new AbortController;this.abortController=c;let p=this.#e;if(t?.mentions){let e=this.messages.find(e=>e.id===s)??d;if(await this.#wt(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:[fn(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 u=(new Date).toISOString(),h=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:u}]:[...this.messages],m=(a??this.messages.find(e=>e.id===s))?.createdAt??u,g=((e,t)=>{let r=new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!Cn(e))return[];let{toolCallId:o,name:n}=e;if("string"!=typeof o||!o||"string"!=typeof n||!n||r.has(o))return[];r.add(o);let a=Cn(e.arguments)?e.arguments:{},s=e.result??null;return[{id:`voice-tool-${o}`,role:"assistant",variant:"tool",content:"",createdAt:t,streaming:!1,toolCall:{id:o,name:n,status:"complete",args:a,result:s},agentMetadata:{clientToolAnswer:{toolCallId:o,toolName:n,args:a,result:s}}}]})})(t?.voiceTurn?.priorToolResults,m);for(let e of g)this.messages.some(t=>t.id===e.id)||(this.#Be(e),h.push({...e,createdAt:u}));let f=g.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:r,args:o,result:n}=e.clientToolAnswer;return{toolCallId:t,name:r,arguments:o,result:n}});try{await this.#ft(h,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...f.length>0&&{voicePriorToolResults:f}})}catch(e){if(this.#e!==p||"resuming"===this.status||this.#u)return;this.#re&&(this.#re.failed=!0);let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));t||this.#xt(e),this.#pe("idle"),this.#ue(!1),this.abortController=null,this.#a(t?"cancel":"error",p),t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(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 o=r+1;for(;o<e.length&&"user"!==e[o].role;)o+=1;return{start:r,end:o}}(this.messages,e);if(!r||!En(this.messages,e))return!1;let o=this.messages[r.start],n=t.replacement,a=n?n.text:o.content,s=n?n.contentParts:o.contentParts;if(!(a?.trim()||(s?.length??0)>0||!n&&(o.llmContent?.trim()?.length??0)>0))return!1;let i=n?void 0:{...void 0!==o.llmContent&&{llmContent:o.llmContent},...void 0!==o.rawContent&&{rawContent:o.rawContent},...o.mentionContext&&{mentionContext:o.mentionContext},...o.contextMentions&&{contextMentions:o.contextMentions},...o.quote&&{quote:o.quote}},l=n?this.#Ct(n.options):o.composerOptions,d=n?n.contentSegments:o.contentSegments,c=n?n.options?.quote:void 0,p=n?n.viaVoice:o.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}#Ct(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.#j||this.#U||this.#N||this.#Q)&&await this.#mt(),this.abortController?.abort(),this.#tt(),this.#n();let e=io();this.#p=null,this.#ue(!0);let t=new AbortController;this.abortController=t;let r=this.#e,o=[...this.messages];try{await this.client.dispatch({messages:o,signal:t.signal,assistantMessageId:e},e=>{this.#e===r&&this.handleEvent(e)})}catch(e){if(this.#e!==r||"resuming"===this.status||this.#u)return;let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));t||this.#xt(e),this.#a(t?"cancel":"error",r),this.#pe("idle"),this.#ue(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;this.#e||this.#n(),t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#p=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.#ue(!0);let n=this.#e,a={};try{await this.client.processStream(e,e=>{if(this.#e!==n)return;let r=this.#l;this.#l=a;try{this.handleEvent(e,t?.readOnlyReplay)}finally{this.#l=r}},t?.assistantMessageId,t?.seedContent,this.abortController?.signal,t?.readOnlyReplay?this.messages:void 0,t?.readOnlyReplay?this.#h:void 0),this.#St(a)}catch(e){if(this.#e!==n)return;if("resuming"===this.status||this.#u)return void this.#kt(a);this.#St(a),this.#pe("error"),0===this.webMcpResolveControllers.size&&(this.#ue(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Ce(){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{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do{t="webmcp-"+ ++this.#C}while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let r={id:t,status:"pending",agentId:"",executionId:"",toolName:e.toolName,...e.toolCallId?{toolCallId:e.toolCallId}:{},toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(t=>{this.webMcpApprovalResolvers.set(o,t),e.signal?.addEventListener("abort",()=>this.resolveWebMcpApproval(o,"timeout"),{once:!0})})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(t=>t.id===e);o?.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#ne;#ae;#At(e){let t=this.#ne??={s:this,setStreaming:e=>this.#ue(e),appendMessage:e=>this.#Be(e),nextSequence:()=>this.#ve(),settleApprovalPausedToolCall:e=>this.#Mt(e),resumeAfter:e=>this.#c?.executionId===e?this.#c.lastEventId:void 0},r=mn();if(r)return e(r,t);let o=this.#ae;return hn().then(r=>o===this.#ae?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,r){return this.#At((o,n)=>o.resolveApproval(n,e,t,r))}resolveAskUserQuestion(e,t){return this.#At((r,o)=>r.resolveAskUserQuestion(o,e,t))}resolveWebMcpToolCall(e){return this.#At((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}:{}}})}#ie(e){let t=e.agentMetadata?.executionId,r=e.toolCall?.id;if(!t||!r){let t=this.#x;return void queueMicrotask(()=>{t===this.#x&&this.resolveWebMcpToolCall(e)})}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}#fe(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#x;queueMicrotask(()=>{if(e===this.#x)for(let e of[...this.webMcpAwaitBatches.keys()])this.#It(e)})}#It(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.#At((t,o)=>t.resolveWebMcpToolCallBatch(o,e,r))}#rt(){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.#x++}cancel(){this.client.cancelStreams(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ae++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ue(!1),this.#pe("idle"),this.#a("cancel")}clearMessages(){this.client.cancelStreams(),this.#Re(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ae++,this.#t=void 0,this.messages=[],this.agentExecution=null,this.#Ze(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ue(!1),this.#pe("idle"),this.callbacks.onMessagesChanged([...this.messages]),this.#a("cancel")}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#w}selectArtifact(e){this.#w=e,this.#Se()}clearArtifacts(){this.#Ze()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,r="markdown"===e.artifactType?{id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,r),this.#w=t,this.#Se(),!1!==e.transcript&&this.#Tt(r),r}#Tt(e){let t=`artifact-ref-${e.id}`,r=In(Mn(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}}),o=this.messages.find(e=>e.id===t);o?(o.rawContent=r,o.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:"",rawContent:r})}#yt(){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 o=In(Mn(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!==o&&(r.rawContent=o,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ze(){(0!==this.artifacts.size||null!==this.#w)&&(this.artifacts.clear(),this.#w=null,this.#Se())}#Se(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#w})}#be(e){switch(e.type){case"artifact_start":"markdown"===e.artifactType?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.#w=e.id;break;case"artifact_delta":{let t=this.artifacts.get(e.id);"markdown"===t?.artifactType&&(t.markdown=(t.markdown??"")+e.artDelta);break}case"artifact_update":{let t=this.artifacts.get(e.id);"component"===t?.artifactType&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case"artifact_complete":{let t=this.artifacts.get(e.id);t&&(t.status="complete");break}default:return}this.#Se()}hydrateMessages(e){this.client.cancelStreams(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ae++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.#t=void 0,this.messages=this.#we(e.map(e=>({...cr(e),streaming:!1,sequence:e.sequence??this.#ve()}))),this.#ue(!1),this.#pe("idle"),this.callbacks.onMessagesChanged([...this.messages]),this.#a("cancel")}hydrateArtifacts(e,t=null,r=!1){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:r?t.status:"complete"});this.#w=t,this.#Se()}assertBackgroundSwitchable(){let e=this.config.backgroundConversations;if(!0!==e?.capabilities?.durableExecution||!0!==e.capabilities?.readOnlyReplay||"function"!=typeof e.reconnectStream)throw new d("background_unavailable","This backend does not support background conversations");if(this.config.parseSSEEvent)throw new d("background_unavailable","Background replay requires the native event parser");if(this.#G()||this.webMcpResolveControllers.size||this.webMcpAwaitBatches.size||(this.streaming||this.#u)&&(!this.#c||!this.#B))throw new d("conversation_busy","This turn cannot safely continue in the background")}async#Fe(){if(this.#g)return;let e=this.config.backgroundConversations,t=this.#D,{BackgroundConversationController:r}=await sn();if(t!==this.#D||e!==this.config.backgroundConversations)throw new d("superseded","The history identity changed");if(this.#g)return;this.#g=new r(e,e=>{this.#Et(e)});let o=!0;this.#f=this.#Ne?.subscribeIdentityStatus(()=>{o||(this.#g?.clear(),this.cancel())})??null,o=!1}#Re(){this.#g?.clear(),this.#g=null,this.#f?.(),this.#f=null}#se(e){let t=this.#c?.executionId??this.agentExecution?.executionId,r=this.#B;if(!this.config.backgroundConversations||!t||!r)return;let o={conversationId:r,executionId:t,status:e,detached:!1};this.#Et(o)}#Et(e){try{this.config.onConversationExecutionState?.(e)}catch{}try{this.callbacks.onConversationExecutionState?.(e)}catch{}}#Lt(){let e=this.config.backgroundConversations,t=this.#B;return e&&t?r=>e.reconnectStream({...r,conversationId:t}):this.config.reconnectStream}#_e(e){this.#n(e.handle.executionId),this.#p=e.handle.assistantMessageId;let t=this.messages.find(e=>e.id===this.#p);t&&(t.streaming=e.streamCheckpoint?.openAssistant??!0),this.#h=e.streamCheckpoint,this.agentExecution={executionId:e.handle.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0},this.#c=e.handle,this.#Bt(!0),this.#se(e.observedStatus??"running"),this.#ce()}#le(e){let t=this.agentExecution?.executionId;if(!t||!this.#p||"running"!==this.agentExecution?.status)return;let r=null===this.#c;this.#c={executionId:t,lastEventId:e,assistantMessageId:this.#p,status:"running"},this.#Bt(r),r&&this.#se("running")}#de(){return null!==this.#c&&"function"==typeof this.#Lt()&&!0!==this.abortController?.signal.aborted&&0===this.webMcpResolveControllers.size&&0===this.webMcpAwaitBatches.size&&!this.#G()}#G(){return this.messages.some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata?.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)}#ce(){this.#u||this.#c&&"function"==typeof this.#Lt()&&(this.#u=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#c}),this.#ue(!0),this.#pe("resuming"),this.#Rt().then(e=>{this.#u&&this.#c&&e.begin()}))}#Rt(){return this.#b?Promise.resolve(this.#b):(this.#y||(this.#y=Vn().then(({createReconnectController:e})=>{let t=e(this.#Pt());return this.#b=t,t}),this.#y.catch(()=>{this.#y=null})),this.#y)}#Pt(){let e=this;return{get config(){return{...e.config,reconnectStream:e.#Lt()}},getResumable:()=>e.#c,clearResumable:()=>e.#he(),getStatus:()=>e.status,setStatus:t=>e.#pe(t),setStreaming:t=>e.#ue(t),setReconnecting:t=>{e.#u=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,isAwaitPending:()=>e.#G(),notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o,readOnlyReplay:!!e.config.backgroundConversations}),appendMessage:t=>e.#Be(t),settleParked:t=>e.#Nt(t),nextSequence:()=>e.#ve(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Qn(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#u?this.#b?.wake():this.#ce()}resumeFromHandle(e){if("function"!=typeof this.config.reconnectStream||this.#u)return;if(this.#n(e.executionId),this.#G())return this.#$t(e.executionId),void(this.#c={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#p??"",status:"running"});let t=this.#Wt(e.executionId)?io():this.#Ht();t||(t=io(),this.#Be({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#ve()})),this.#p=t,this.#$t(e.executionId),this.#c={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#ce()}#Nt(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#G()){if(!this.#Wt(e))return!1;this.#he()}if(this.#u=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ue(!1),this.abortController=null}return this.#pe("idle"),!0}#$t(e){this.agentExecution||={executionId:e,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}}#Wt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>!0===e?.interrupted))}#Ht(){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}#tt(){this.#u=!1,this.#b?.teardown(),this.#he()}#he(){this.#v&&=(clearTimeout(this.#v),null);let e=null!==this.#c;this.#c=null,this.#h=void 0,e&&this.config.onExecutionState?.(null)}#Bt(e){let t=this.config.onExecutionState;t&&(e?(this.#v&&=(clearTimeout(this.#v),null),t(this.#c)):this.#v||=setTimeout(()=>{this.#v=null,this.config.onExecutionState?.(this.#c)},500))}getResumableHandle(){return this.#c}#pe(e){"error"===e&&(this.#r=!0,this.#s()),this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ue(e){if(e||this.#s(),this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#St(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 o=Fn(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return On(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=Fn(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o?.voice,rate:o?.rate,pitch:o?.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()}#xt(e){for(let e of this.messages)e.streaming=!1;let t=Qn(e,this.config.errorMessage);t?this.#Be({id:io(),role:"assistant",content:t,dispatchError:!0,localOnly:!0,createdAt:(new Date).toISOString(),sequence:this.#ve()}):this.callbacks.onMessagesChanged([...this.messages])}#St(e){for(let[t,r]of[...this.#i])r===e&&(this.#i.delete(t),this.#Mt(t))}#kt(e){for(let[t,r]of this.#i)r===e&&this.#i.set(t,void 0)}#Mt(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,o=r&&this.messages.find(e=>e.toolCall?.id===r),n=o&&o.toolCall;if(!n||"complete"===n.status||"pending"===t.status)return;let a={...n,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({...o,streaming:!1,toolCall:a})}#Be(e){let t=this.#Ke(e),r=this.messages[this.messages.length-1];this.messages=!r||this.#Dt(r,t)<=0?[...this.messages,t]:this.#we([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Ke(e),r=this.messages.findIndex(e=>e.id===t.id);if(-1===r)return void this.#Be(t);this.messages=this.messages.map((e,o)=>{if(o!==r||e.toolCall?.name&&ir(e.toolCall.name)&&"complete"===e.toolCall.status&&t.toolCall?.id===e.toolCall.id&&"complete"!==t.toolCall.status&&("pending"===t.toolCall.status&&!t.toolCall.name||!e.toolCall.interrupted&&(void 0!==e.toolCall.result||void 0!==e.toolCall.success)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let n={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(n.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(n.agentMetadata={...n.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&n.agentMetadata&&!n.agentMetadata.clientToolAnswer&&(n.agentMetadata={...n.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,o=t.approval;n.approval={...r,...o,executionId:o.executionId||r.executionId,toolCallId:o.toolCallId||r.toolCallId,toolName:o.toolName||r.toolName,description:o.description||r.description,toolType:o.toolType??r.toolType,reason:o.reason??r.reason,parameters:o.parameters??r.parameters}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&Jn(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),o=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&Jn(a)&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;(r||o||s)&&(n.agentMetadata={...n.agentMetadata??{},awaitingLocalTool:!1},n.toolCall=e.toolCall,n.streaming=e.streaming)}return n});let o=this.messages[r],n=this.messages[r-1],a=this.messages[r+1];(n&&this.#Dt(n,o)>0||a&&this.#Dt(o,a)>0)&&(this.messages=this.#we(this.messages)),this.callbacks.onMessagesChanged([...this.messages])}#Ke(e){return void 0===e.sequence?{...e,sequence:this.#ve()}:{...e}}#ve(){return this.#d++}#Dt(e,t){let r=new Date(e.createdAt).getTime(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a}#we(e){return[...e].sort((e,t)=>this.#Dt(e,t))}};let Gn={add:e=>async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;vn(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})}(e)},Yn={allowedTypes:yn,maxFileSize:10485760,maxFiles:4};function Xn(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}p=class e{#e=[];#t;#r=new Set;#o=new Map;#n=null;#a=new Map;#s=new WeakMap;#i=!1;#l=!1;constructor(e={}){this.#t={allowedTypes:e.allowedTypes??Yn.allowedTypes,maxFileSize:e.maxFileSize??Yn.maxFileSize,maxFiles:e.maxFiles??Yn.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,preview:e.preview,widgetConfig:e.widgetConfig,instanceId:e.instanceId,renderAttachmentPreview:e.renderAttachmentPreview,adapter:e.adapter}}#d(){return"function"==typeof this.#t.adapter?.add}#c(){return this.#d()?this.#t.adapter:Gn}setPreviewsContainer(e){this.#n!==e&&this.#v(),this.#n=e}remountPreviews(e){if(this.#v(),this.#n=e,e){e.innerHTML="";for(let e of this.#e)this.#f(e)}this.#x()}updateConfig(e){if("allowedTypes"in e&&(this.#t.allowedTypes=e.allowedTypes?.length?e.allowedTypes:Yn.allowedTypes),"maxFileSize"in e&&(this.#t.maxFileSize=e.maxFileSize??Yn.maxFileSize),"maxFiles"in e&&(this.#t.maxFiles=e.maxFiles??Yn.maxFiles),"onFileRejected"in e&&(this.#t.onFileRejected=e.onFileRejected),void 0!==e.onAttachmentsChange&&(this.#t.onAttachmentsChange=e.onAttachmentsChange),"adapter"in e&&(this.#t.adapter=e.adapter),"preview"in e&&(this.#t.preview=e.preview),"widgetConfig"in e&&(this.#t.widgetConfig=e.widgetConfig),"instanceId"in e&&(this.#t.instanceId=e.instanceId),"renderAttachmentPreview"in e&&e.renderAttachmentPreview!==this.#t.renderAttachmentPreview)this.#t.renderAttachmentPreview=e.renderAttachmentPreview,this.remountPreviews(this.#n);else for(let e of this.#e)this.#b(e),this.#w(e)}isReady(){return this.#e.every(e=>"ready"===e.status)}getAttachments(){return[...this.#e]}getContentParts(){return this.#e.map(e=>e.contentPart).filter(e=>null!==e)}hasAttachments(){return this.#e.length>0}count(){return this.#e.length}async handleFileSelect(e){e&&0!==e.length&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#i)return;let t=[];for(let r of e){if(this.#e.length>=this.#t.maxFiles){this.#t.onFileRejected?.(r,"count");continue}let e=wn(r,this.#t.allowedTypes,this.#t.maxFileSize);if(!e.valid){let t=e.error?.includes("type")?"type":"size";this.#t.onFileRejected?.(r,t);continue}let o={id:Xn(),file:r,previewUrl:vn(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#d()?"uploading":"processing",progress:this.#d()?0:void 0};this.#e.push(o),this.#f(o),t.push(o),this.#w(o)}this.#x(),this.#m(),await Promise.all(t.map(e=>this.#p(e)))}async#p(e){let t=new AbortController;this.#a.set(e.id,t);let r=this.#c(),o=()=>this.#i||t.signal.aborted||this.#a.get(e.id)!==t||!this.#e.includes(e);try{let n=await r.add(e.file,{signal:t.signal,onProgress:t=>{o()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#b(e),this.#m())}});if(o())return void(this.#i&&this.#l&&this.#h(n,r));this.#s.set(e,r),e.contentPart=n,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(o())return;e.status="error",e.progress=void 0,e.error=t instanceof Error?t.message:String(t??"Upload failed")}finally{this.#a.get(e.id)===t&&this.#a.delete(e.id)}this.#b(e),this.#m()}retryAttachment(e){let t=this.#e.find(t=>t.id===e);!t||"error"!==t.status||this.#i||(t.status=this.#d()?"uploading":"processing",t.progress=this.#d()?0:void 0,t.error=void 0,this.#b(t),this.#m(),this.#p(t))}#u(e){let t=this.#a.get(e);t&&(this.#a.delete(e),t.abort())}removeAttachment(e){let t=this.#e.findIndex(t=>t.id===e);if(-1===t)return;let r=this.#e[t];this.#u(e),r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.#e.splice(t,1),this.#y(e),this.#r.delete(e);let o=this.#n?.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),"ready"===r.status&&r.contentPart&&this.#h(r.contentPart,this.#s.get(r)),this.#x(),this.#m()}async#h(e,t){try{await(t?.remove?.(e,{signal:(new AbortController).signal}))}catch(e){console.error("[AttachmentManager] adapter.remove failed:",e)}}clearAttachments(){this.#v(),this.#r.clear();for(let e of this.#e)this.#u(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.#e=[],this.#a.clear(),this.#n&&(this.#n.innerHTML=""),this.#x(),this.#m()}destroy(e){if(!this.#i){this.#i=!0,this.#v(),this.#l=!0===e?.release;for(let e of this.#a.values())e.abort();this.#a.clear();for(let e of this.#e)e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.#l&&"ready"===e.status&&e.contentPart&&this.#h(e.contentPart,this.#s.get(e));this.#e=[],this.#n=null}}#m(){this.#i||this.#t.onAttachmentsChange?.(this.getAttachments())}#g(e){let t={instanceId:this.#t.instanceId??"",state:Object.freeze({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error,lineCount:e.lineCount,kind:vn(e.file)?"image":"file",previewUrl:e.previewUrl}),config:{...this.#t.widgetConfig,attachments:{...this.#t.widgetConfig?.attachments,preview:this.#t.preview}},actions:{remove:()=>this.removeAttachment(e.id),retry:()=>this.retryAttachment(e.id)},defaultRenderer:()=>function(e){let t=st("div","persona-attachment-preview persona-relative persona-inline-block"),r=e,o="",n=e=>{r=e;let{state:n}=r,a=JSON.stringify([r.config.attachments?.preview,n.lineCount,n.previewUrl]);o!==a&&(o=a,(()=>{let{state:e}=r,o=r.config.attachments?.preview,n="image"===e.kind,a=n?o?.image:o?.file,s=n?o?.image?.layout??"thumbnail":o?.file?.layout??"tile";if(t.dataset.kind=e.kind,t.dataset.layout=s,t.dataset.fileIcon=String(!1!==o?.file?.icon),t.dataset.iconPlacement=o?.file?.iconPlacement??"start",t.dataset.removeVisibility=a?.remove?.visibility??"always",t.dataset.removePlacement=a?.remove?.placement??"overlap",t.replaceChildren(),n&&e.previewUrl){let r=it("img",{className:"persona-attachment-image",attrs:{src:e.previewUrl,alt:e.name},style:{objectFit:o?.image?.fit??"cover"}}),n=o?.image?.name??"hidden";if("chip"===s||"hidden"!==n){let o=st("div","persona-attachment-image-card");o.append(r),"hidden"!==n&&o.append(it("span",{className:"persona-attachment-file-name",text:"basename"===n?e.name.replace(/\.[^.]+$/,""):e.name})),t.append(o)}else t.append(r)}else{let r=st("div","persona-attachment-file"),n=e.mimeType,a=n.includes("spreadsheet")||n.includes("excel")?ge:"application/json"===n?me:"application/pdf"===n||n.startsWith("text/")||n.includes("word")?fe:be,s=(o?.file?.iconName?Ee(o.file.iconName,20,"currentColor",1.5):null)??ne(a,20,"currentColor",1.5);s&&!1!==o?.file?.icon&&(s.classList.add("persona-attachment-file-icon"),r.append(s));let i=st("div","persona-attachment-file-copy"),l=o?.file?.name??"hidden";"hidden"!==l&&i.append(it("span",{className:"persona-attachment-file-name",text:"basename"===l?e.name.replace(/\.[^.]+$/,""):e.name}));let d=o?.file?.metadata,c="size"===d?e.size<1024?`${e.size} B`:e.size<1048576?`${Math.round(e.size/1024)} KB`:`${(e.size/1048576).toFixed(1)} MB`:"line-count"===d&&void 0!==e.lineCount?`${e.lineCount} ${1===e.lineCount?"line":"lines"}`:"";c&&i.append(it("span",{className:"persona-attachment-file-metadata",text:c})),i.childNodes.length&&r.append(i);let p=o?.file?.badge??"type";"none"!==p&&r.append(it("span",{className:"persona-attachment-file-badge",text:"extension"===p?e.name.match(/\.([^.]+)$/)?.[1].toUpperCase()??xn(n,e.name):xn(n,e.name)})),t.append(r)}let i=it("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),l=st("div","persona-attachment-progress");l.append(st("div","persona-attachment-progress__bar"));let d=it("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=Ee("rotate-cw",12,"#ffffff",2);c?d.append(c):d.textContent="↻",d.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r.actions.retry()}),i.append(l,d);let p=it("button",{className:"persona-attachment-remove",attrs:{type:"button","aria-label":"Remove attachment"}}),u=ne(ve,10,"currentColor",2);u?p.append(u):p.textContent="×",p.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r.actions.remove()}),t.append(i),(("inline"===a?.remove?.placement?t.querySelector(".persona-attachment-file, .persona-attachment-image-card"):null)??t).append(p)})()),t.dataset.status=n.status,t.setAttribute("aria-busy",String("uploading"===n.status||"processing"===n.status)),t.title="error"===n.status?`${n.name}: ${n.error??"Upload failed"}`:n.name;let s=t.querySelector(".persona-attachment-progress__bar");s&&(s.style.width="number"==typeof n.progress?`${Math.round(100*n.progress)}%`:"")};return n(e),{element:t,update:n}}(t)};return t}#f(e){if(!this.#n)return;let t=this.#g(e),r=null;try{r=this.#t.renderAttachmentPreview?.(t)??null}catch(e){console.error("[AttachmentManager] preview renderer failed:",e)}r??=t.defaultRenderer();let o=r instanceof HTMLElement?{element:r}:r;o.element.dataset.attachmentId=e.id,this.#o.set(e.id,o),this.#n.appendChild(o.element)}#b(e){try{this.#o.get(e.id)?.update?.(this.#g(e))}catch(e){console.error("[AttachmentManager] preview update failed:",e)}}#y(e){let t=this.#o.get(e);if(t){this.#o.delete(e);try{t.destroy?.()}catch(e){console.error("[AttachmentManager] preview cleanup failed:",e)}finally{t.element.remove()}}}#v(){for(let e of this.#o.keys())this.#y(e)}async#w(e){let t=e.file;if(!this.#r.has(e.id)&&!("line-count"!==this.#t.preview?.file?.metadata||t.size>1048576)&&["text/plain","text/markdown","text/csv","application/json"].includes(t.type)){this.#r.add(e.id);try{let r=await new Promise((e,r)=>{let o=new FileReader;o.onload=()=>e(String(o.result??"")),o.onerror=()=>r(o.error),o.readAsText(t)});if(this.#i||!this.#e.includes(e)||r.includes("\0"))return;e.lineCount=""===r?0:r.split(/\r\n|\r|\n/).length-+!!/\r?\n$|\r$/.test(r),this.#b(e)}catch{}}}#x(){this.#n&&(this.#n.style.display=this.#e.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,preview:t?.preview,adapter:t?.adapter})}};let Zn=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function ea(){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,o=!1,n=!1,a=()=>(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(o=!1,n||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,!n&&!o&&(o=!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 o=t[r];return e.id===o.id&&e.name===o.name&&e.mimeType===o.mimeType&&e.size===o.size&&e.status===o.status&&e.progress===o.progress&&e.error===o.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Zn(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Zn(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:()=>{o&&s()},destroy:()=>{n=!0,o=!1,t.clear()}}}let ta=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},ra=(e,t)=>{let r=st("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r};function oa(e,t={}){let r=ta(e,"[data-persona-composer-form]"),o=ta(e,"[data-persona-composer-input]");if(!r||!o){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||o))throw Error(e);return typeof console<"u"&&console.warn(e),null}let n={header:ta(e,"[data-persona-composer-header]"),body:ta(e,"[data-persona-composer-body]"),actionsStart:ta(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:ta(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:ta(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:ta(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:ta(e,"[data-persona-composer-status]")},a=new Set,s=n.header;s||(a.add("header"),s=ra("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=n.body??o.parentElement??r,l=(e,t,r,o,n)=>{if(t)return t;a.add(e);let s=ra(r,o);return n.appendChild(s),s},d=l("actionsStart",n.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",n.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",n.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",n.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:o,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:ta(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:ta(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:ta(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:ta(e,"[data-persona-composer-submit]")??void 0,micButton:ta(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:n,addListener:(e,t,r,o)=>{e.addEventListener(t,r,o),h.push({target:e,type:t,handler:r,options:o})},removeListener:(e,t,r,o)=>{e.removeEventListener(t,r,o),h=h.filter(o=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(o,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let na="persona-composer-control",aa="persona-composer-control--glyph";["padding","rowGap","rowPadding","rowBorderRadius","fontSize","lineHeight","iconSize","iconGap","hoverBackground","focusBackground","descriptionColor","descriptionFontSize","dividerColor","dividerSpacing","minWidth","maxHeight"].map(e=>`--persona-components-composer-overflowMenu-${e}`);let sa=e=>Number.parseFloat(e)||0;function ia(e,t){let r=t.getComputedStyle(e);if("none"===r.display)return 0;let o=Array.from(e.children).filter(e=>{if(!(e instanceof t.HTMLElement))return!1;let r=t.getComputedStyle(e);return"none"!==r.display&&!["absolute","fixed"].includes(r.position)});return o.reduce((e,r)=>{let o=t.getComputedStyle(r);return e+("contents"===o.display?ia(r,t):Math.max(r.getBoundingClientRect().width,r.scrollWidth))+sa(o.marginLeft)+sa(o.marginRight)},0)+Math.max(0,o.length-1)*sa(r.columnGap)+sa(r.paddingLeft)+sa(r.paddingRight)}function la(e){let t=null,r=null,o=null,n=null,a=0,s=!0,i=!1,l=!1,d=()=>{null!==n&&t?.form.ownerDocument.defaultView?.cancelAnimationFrame(n),n=null,r?.disconnect(),o?.disconnect(),r=null,o=null,t?.form.ownerDocument.defaultView?.removeEventListener("resize",c)},c=()=>{if(l||null!==n)return;let r=t?.form.ownerDocument.defaultView;r&&(n=r.requestAnimationFrame(()=>{n=null,l||e.onMeasure()}))};return{measure:()=>{if(l)return s;let n=e.getSurface();if(n?.form!==t?.form||n?.input!==t?.input||n?.start!==t?.start||n?.end!==t?.end){d(),t=n,s=!0,i=!1,a=0;let e=t?.form.ownerDocument.defaultView;if(t&&e){if(e.addEventListener("resize",c),void 0!==e.ResizeObserver){r=new e.ResizeObserver(c);let o=[t.form,t.start,t.end,t.input];for(let e of o)r.observe(e)}void 0!==e.MutationObserver&&(o=new e.MutationObserver(e=>{e.some(e=>e.target!==t?.input||"attributes"!==e.type)&&c()}),o.observe(t.form,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["class","style","hidden"]}))}}t&&n&&(t.resizeInput=n.resizeInput);let p=t?.form.ownerDocument.defaultView;if(!t||!p)return!0;if(!t.form.clientWidth)return s;let u=p.getComputedStyle(t.form),h=Math.max(1,t.form.clientWidth-sa(u.paddingLeft)-sa(u.paddingRight)),m=ia(t.start,p)+ia(t.end,p),g=sa(u.columnGap);i=m+g+(i?16:0)>h,s=function(e,t,r,o){return e<=0?o:e>=t+2*r+120+(o?0:16)}(h,m,g,s);let f=t.input.getBoundingClientRect().width;if(!1!==t.resizeInput&&f>0&&f!==a&&"TEXTAREA"===t.input.tagName){a=f,t.input.style.height="auto";let e=sa(p.getComputedStyle(t.input).maxHeight)||1/0,r=Math.min(t.input.scrollHeight,e);t.input.style.height=`${r}px`}return s},toolbarCrowded:()=>i,refresh:c,destroy:()=>{l=!0,d(),t=null}}}let da="[data-persona-composer-chip-row]";function ca(e){let t=e.querySelector(da);if(t)return t;let r=it("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(r,o):e.appendChild(r),r}function pa(e){let t=it("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",o=!1,n=r=>{let o=st("span","persona-composer-quote-bar"),n=st("div","persona-composer-quote-content");if(r.sourceLabel){let e=st("div","persona-composer-quote-source");e.textContent=r.sourceLabel,n.appendChild(e)}let a=it("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=Tn(r.text),n.appendChild(a);let s=it("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=Ee("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(o,n,s)};return{element:t,render:e=>{if(o)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(n(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function ua(e){let t=it("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,o=!1,n=(e,t,r,o)=>{let n=it("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=Ee(e,12,"currentColor",2);return a?n.appendChild(a):n.textContent=t,n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n};return{element:t,render:a=>{if(o||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=st("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=it("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=Tn(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,n("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),n("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function ha(e){let t=it("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=it("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 o=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",o);let n=st("div","persona-message-edit-actions"),a=(e,t,r,o)=>{let n=it("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return n.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=>{"Escape"===t.key?(t.preventDefault(),t.stopPropagation(),e.onCancel()):"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,n),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function ma(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 ga(e,t,r,o){let n=r.find(e=>e.id===t);if(!n)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)(n,o)){let e=r.filter(e=>e.groupId===n.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)}function fa(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function ba(e){return!e.wrapped&&!e.text.includes("\n")&&!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function ya(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 o=parseFloat(r);return Number.isFinite(o)&&o>0?o:20}function va(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function wa(e,t){e.style.maxHeight=t*ya(e)+"px",e.style.overflowY="auto"}function xa(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 Ca(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function Sa(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?Ca(e)?"enter":"send":"enter"}(t))}function ka(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let o=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};o("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),o("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),o("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),o("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function Aa(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}}function Ma(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 Ia(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"})}function Ta(e,t,r){let o;try{o=e(Ma(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(o)?Promise.resolve(o).then(e=>r.aborted?{status:"aborted"}:Ia(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Ia(t,o)}let{setLoader:Ea,load:La}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ba=Ea,Ra=La,{setLoader:Pa,load:Na}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),$a=Pa,Wa=Na,Ha=400,Da=300,Oa=0,Fa=e=>Math.max(0,e);function za(e){void 0!==e.delayMs&&(Ha=Fa(e.delayMs)),void 0!==e.skipDelayMs&&(Da=Fa(e.skipDelayMs))}let qa=new WeakMap;function ja(e){qa.get(e)?.hide()}let _a=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Ua=e=>{let t=e.getRootNode?.();return _a(t)?t:e.closest("dialog[open]")??e.ownerDocument.body},Va=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Ka=[...["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 Qa(e){qa.get(e.anchor)?.destroy();let t,{anchor:r,trigger:o=r,text:n,hint:a,enabled:s=!0,gap:i=8,viewportPadding:l=8}=e,d=()=>r.ownerDocument,c=()=>d().defaultView??window,p=null,u=null,h=null,m=null,g=!1,f=!1,b=!1,y=()=>("function"==typeof n?n():n).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>Fa(e.delayMs??Ha),x=()=>Fa(e.skipDelayMs??Da),C=()=>{void 0!==t&&(c().clearTimeout(t),t=void 0)},S=()=>{C();let e=null!==p;m?.(),m=null,p?.remove(),p=null,u=null,h=null,e&&(e=>{Oa=e>0?Date.now()+e:0})(x())},k=()=>{if(!p)return;let e=d(),t=c(),o=r.getBoundingClientRect(),n=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-n.width,h=o.left+o.width/2-n.width/2,m=Va(h,l,u),g=o.top-l,f=s-l-o.bottom,b=g>=n.height+i||g>=f?"top":"bottom",y="top"===b?o.top-i-n.height:o.bottom+i,v=s-l-n.height,w=Va(y,l,v),x=o.left+o.width/2,C=Math.max(10,n.width-10),S=Va(x-m,10,C);p.dataset.placement=b,p.style.left=`${m}px`,p.style.top=`${w}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${S}px`)},A=()=>{if(b||!s||p||!r.isConnected||(e=>"function"==typeof e.closest&&null!==e.closest("[data-persona-tooltip-suppressed]"))(r))return;let e=y(),t=Ua(r);if(!e||!t)return;let o=d(),n=c();p=o.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=n.getComputedStyle?.(r);if(a){for(let e of Ka){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=o.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=o.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=o.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),k(),p.dataset.state="open";let g=()=>{if(!r.isConnected)return void S();u&&(u.textContent=y()),h&&(h.textContent=v());let e=Ua(r);p&&e&&p.parentNode!==e&&e.appendChild(p),k()};n.addEventListener("scroll",g,!0),n.addEventListener("resize",g);let f=r.closest("[data-persona-root]");f?.addEventListener("persona:internal:host-moved",g);let w=r.getRootNode(),x=_a(w)?w:o.documentElement,C=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});C?.observe(x,{childList:!0,subtree:!0}),m=()=>{n.removeEventListener("scroll",g,!0),n.removeEventListener("resize",g),f?.removeEventListener("persona:internal:host-moved",g),C?.disconnect()}},M=()=>{g||f?(e=>{b||p||(C(),e||w()<=0||Date.now()<Oa?A():t=c().setTimeout(()=>{t=void 0,A()},w()))})(f):S()},I=()=>{let e=c();e.matchMedia&&e.matchMedia("(hover: none)").matches||(g=!0,M())},T=()=>{g=!1,M()},E=()=>{try{f=r.matches(":focus-visible")}catch{f=!0}M()},L=()=>{f=!1,M()},B=()=>{g=!1,f=!1,S()},R=e=>{"Escape"===e.key&&B()};o.addEventListener("mouseenter",I),o.addEventListener("mouseleave",T),r.addEventListener("focus",E),r.addEventListener("blur",L),r.addEventListener("keydown",R),r.addEventListener("click",B);let P={get isOpen(){return null!==p},show:A,hide:S,reposition:k,destroy:()=>{b||(b=!0,S(),o.removeEventListener("mouseenter",I),o.removeEventListener("mouseleave",T),r.removeEventListener("focus",E),r.removeEventListener("blur",L),r.removeEventListener("keydown",R),r.removeEventListener("click",B),qa.delete(r))}};return qa.set(r,P),P}let Ja=(e,t,r,o)=>{let[n,a]=t.split(".");return[e?.theme,e?.darkTheme].some(e=>void 0!==e?.components?.[n]?.[a]?.[r])?`var(--persona-components-${t.replace(".","-")}-${r}, ${o})`:o},Ga=(e,t)=>{let r=e&&z(e,t);return"string"==typeof r&&r?r:void 0},Ya=(e,t,r,o)=>{let n=t.startsWith("var(");e.classList.toggle("persona-theme-padding",n),e.style.padding=n?"":t,n?e.style.setProperty("--persona-theme-padding",t):e.style.removeProperty("--persona-theme-padding"),r&&(e.style.paddingLeft=e.style.paddingRight=r),o&&(e.style.paddingTop=e.style.paddingBottom=o)},Xa=(e,t,r)=>{let o=t.startsWith("var(")&&t.includes("--persona-components-");e.classList.toggle("persona-control-size",o),o?e.style.setProperty("--persona-control-size",t):e.style.removeProperty("--persona-control-size"),e.style.width=e.style.height=t,e.style.minWidth=e.style.minHeight=r??""},Za=Symbol("persona.panelAliasProvenance"),es=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),ts=(e,t)=>es(e,t)&&void 0!==e[t],rs=e=>{let t=e?.[Za];return t?{...t}:(e=>({launcherWidth:ts(e?.launcher,"width"),legacyLauncherWidth:ts(e,"launcherWidth"),sidebarWidth:ts(e?.launcher,"sidebarWidth"),dockWidth:ts(e?.launcher?.dock,"width")}))(e)},os=(e,t)=>(Object.defineProperty(e,Za,{value:t,enumerable:!0,configurable:!0}),e),ns=(e,t)=>os(e,rs(t)),as=e=>!0===e?.layout?.embedded&&!1===e.launcher?.enabled&&!e.launcher.sidebarMode&&"floating"===(e.launcher.mountMode??"floating"),ss=e=>e?.layout?.showHeader??!as(e),is="min(440px, calc(100vw - 24px))",ls={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:400,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:is,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{inputPlaceholder:"How can I help...",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:"",streamingIndicator:"arrow",scrollBehavior:"instant",scrollDurationMs:220,transition:"none"},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",groupBoundary:"adjacent",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other…",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},ds={},cs={colorScheme:"light",errorDisplay:"block",messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:{resolvedDisplay:"row",primaryAction:"allow-once",keyboardShortcuts:"focused"},loadingIndicator:{variant:"label"},launcher:{variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:"dots",transition:"fade",scrollBehavior:"smooth"},userMessageCollapse:{enabled:!0},toolCallDisplay:{layout:"row",variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",groupAppearance:"inset",loadingAnimation:"shimmer"},reasoningDisplay:{appearance:"inset",layout:"row",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 ps(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function us(e){let t="v5"===ps(e)?cs:ds;return k(ls,t)}let hs=us();function ms(e,t){if(e||t)return e?t?k(e,t):e:t}function gs(e){let t=us(e);return e?O(w(ns({...t,...e,colorScheme:y(e,["colorScheme"]).includes("colorScheme")?e.colorScheme:e.brand?void 0:t.colorScheme,...t.approval||void 0!==e.approval?{approval:!1!==e.approval&&{...t.approval||{},...e.approval}}:{},theme:ms(t.theme,e.theme),darkTheme:ms(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,o=e.features?.artifacts,n=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?.userMessageCollapse,h=e.features?.userMessageCollapse,m=t.features?.history,g=e.features?.history,f=void 0===r&&void 0===o?void 0:{...r,...o,layout:{...r?.layout,...o?.layout}},b=void 0===n&&void 0===a?void 0:{...n,...a},y=void 0===s&&void 0===i?void 0:{...s,...i},v=void 0===l&&void 0===d?void 0:{...l,...d},w=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},x=void 0===m&&void 0===g?void 0:{...m,...g,copy:{...m?.copy,...g?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay,...void 0===e.features?.toolCallDisplay?.layout&&void 0!==e.features?.toolCallDisplay?.variant?{layout:e.features.toolCallDisplay.variant}:{}},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay,...void 0===e.features?.reasoningDisplay?.layout&&void 0!==e.features?.reasoningDisplay?.variant?{layout:e.features.reasoningDisplay.variant}:{}},...void 0===b?{}:{scrollToBottom:b},...void 0===y?{}:{scrollBehavior:y},...void 0===f?{}:{artifacts:f},...void 0===v?{}:{streamAnimation:v},...void 0===w?{}:{askUserQuestion:w},...void 0===x?{}:{history:x},...void 0!==u||void 0!==h?{userMessageCollapse:{...u,...h}}:{}}})(),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,cs),e):O(w(ns(t),void 0,cs))}let fs=(e,t)=>{let r=st("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??"How can I help...",r.dir="auto",Sa(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(r)}),ka(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 o=va(e?.composer?.maxLines,t?.defaultMaxLines??3),n=20*o+"px";return r.style.maxHeight=n,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!==n){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=o*ya(r);return n=`${t}px`,r.style.maxHeight=n,t})());r.style.height=`${e}px`})}}},bs="[data-persona-glyph-stack]",ys=new WeakMap,vs=(e,t,r=!0)=>{ys.set(e,t);let o=t?.sendButton??{},n=o.useIcon??!1,a="stop"===e.getAttribute("data-persona-send-mode")?"stop":"send",s=e=>Ga(t,`sendButton.${e}`),i=(e,r)=>Ja(t,"composer.send",e,r),l=s("size")||o.size;e.style.fontSize=n?"18px":"",e.style.lineHeight=n?"1":"",e.className=lt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${na}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!s("backgroundColor")&&"persona-bg-persona-primary",!n&&!s("textColor")&&"persona-text-white"),Xa(e,n?l||(i("size","")?i("size","var(--persona-composer-control-size, 40px)"):""):"",n?l:void 0);let d=i("foreground",n?"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":"#ffffff"),c=i("background",n?"var(--persona-button-primary-bg, var(--persona-primary, #111827))":"var(--persona-accent, #0f0f0f)");e.style.color=s("textColor")||("stop"===a&&i("foreground","")?`var(--persona-button-stop-fg, ${d})`:i("foreground","")||(n?d:"")),e.style.backgroundColor=(n?s("backgroundColor"):void 0)||(i("background","")?"stop"===a?`var(--persona-button-stop-bg, ${c})`:c:"");let p=s("borderWidth")||(i("borderWidth","")?i("borderWidth",o.borderWidth||"0px"):o.borderWidth||"");e.style.borderWidth=p,e.style.borderStyle=p?"solid":"",e.style.borderColor=s("borderColor")||(i("borderColor","")?i("borderColor",o.borderColor||"transparent"):o.borderColor||""),e.style.borderRadius=i("borderRadius","")?i("borderRadius","var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))"):"",Ya(e,i("padding",n?"0":"8px 16px"),n?void 0:s("paddingX")||(i("padding","")?void 0:o.paddingX),n?void 0:s("paddingY")||(i("padding","")?void 0:o.paddingY));let u=parseFloat(o.iconSize??"")||Math.round(.5*(parseFloat(o.size??"")||40));if(r)if(e.replaceChildren(),n){let t=o.iconStrokeWidth??2,r=o.iconName?Ee(o.iconName,u,"currentColor",t):null,n=Ee(o.stopIconName??"square",u,"currentColor",t);r&&n?e.appendChild(((e,t,r="send")=>{let o=it("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"),o.append(e,t),o})(r,n,a)):r?e.appendChild(r):e.textContent=o.iconText??"↑"}else e.textContent="stop"===a?t?.copy?.stopButtonLabel??"Stop":t?.copy?.sendButtonLabel??"Send";for(let r of Array.from(e.querySelectorAll("svg"))){r.style.width=r.style.height=s("iconSize")?"":i("iconSize",`var(--persona-components-composer-sendIconSize, ${u}px)`);let e=t?.sendButton?.iconStrokeWidth;r.style.strokeWidth=void 0===e?i("iconStrokeWidth",""):String(e)}},ws=e=>{let t=e?.sendButton,r=st("div","persona-send-button-wrapper"),o=it("button",{attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"}});return vs(o,e),o.setAttribute("aria-label",t?.tooltipText??"Send message"),r.appendChild(o),Qa({anchor:o,trigger:r,text:()=>o.getAttribute("aria-label")??"",enabled:t?.showTooltip??!1}),{button:o,wrapper:r,setMode:e=>{if(o.getAttribute("data-persona-send-mode")===e)return;o.setAttribute("data-persona-send-mode",e),o.setAttribute("aria-label","stop"===e?t?.stopTooltipText??"Stop generating":t?.tooltipText??"Send message");let r=ys.get(o);vs(o,r,!1),o.querySelector(bs)?.setAttribute("data-mode",e),r?.sendButton?.useIcon||(o.textContent="stop"===e?r?.copy?.stopButtonLabel??"Stop":r?.copy?.sendButtonLabel??"Send")},glyphStack:o.querySelector(bs)}},xs=(e,t,r="idle",o="none")=>{let n=t?.voiceRecognition??{},a=e=>Ga(t,`voiceRecognition.${e}`),s=(e,r)=>Ja(t,"voice.control",e,r),i=a("iconSize")||n.iconSize;Xa(e,i||(s("size","")?s("size","var(--persona-composer-control-size, 40px)"):""),i),e.classList.add(na),e.classList.toggle(aa,!i&&!s("size","")),e.style.fontSize="18px",e.style.lineHeight="1";let l=a("iconColor")||Ga(t,"sendButton.textColor")||s("foreground","var(--persona-text, #111827)"),d=a("backgroundColor")||Ga(t,"sendButton.backgroundColor")||s("background",n.backgroundColor||"transparent"),c=a("borderColor")||s("borderColor",n.borderColor||"transparent"),p=a("borderWidth")||s("borderWidth",n.borderWidth||"");e.style.borderWidth=p,e.style.borderStyle=p?"solid":"",e.style.borderRadius=s("borderRadius","")?s("borderRadius","var(--persona-button-radius)"):"",Ya(e,s("padding","")?s("padding","0px"):"",a("paddingX")||(s("padding","")?void 0:n.paddingX),a("paddingY")||(s("padding","")?void 0:n.paddingY));let u=a("recordingBackgroundColor")||"var(--persona-voice-recording-bg, #ef4444)",h=a("recordingIconColor")||"var(--persona-voice-recording-indicator, #ffffff)",m=a("recordingBorderColor")||`var(--persona-consumer-voice-recording-border, ${n.recordingBorderColor||c})`,g=l,f=d,b=c,y=n.iconName??"mic";if("recording"===r)g=h,f=u,b=m;else if("processing"===r)g=a("processingIconColor")||`var(--persona-consumer-voice-processing-icon, ${l})`,f=a("processingBackgroundColor")||`var(--persona-consumer-voice-processing-background, ${d})`,b=a("processingBorderColor")||`var(--persona-components-voice-processing-border, ${c})`,y=n.processingIconName??"loader";else if("speaking"===r){let e="barge-in"===o;g=a("speakingIconColor")||`var(--persona-consumer-voice-speaking-icon, ${e&&a("recordingIconColor")||l})`,f=a("speakingBackgroundColor")||`var(--persona-components-voice-speaking-background, ${e?u:d})`,b=a("speakingBorderColor")||`var(--persona-components-voice-speaking-border, ${e?m:c})`,y=n.speakingIconName??("cancel"===o?"square":e?"mic":"volume-2")}e.style.color=g,e.style.backgroundColor=f,e.style.borderColor=b,e.setAttribute("data-state",r);let v=parseFloat(n.iconSize??"")||24,w=Ee(y,v,"currentColor",1.5);if(e.replaceChildren(),w){let t=i||(s("iconSize","")?s("iconSize","var(--persona-composer-control-icon-size, 24px)"):"");w.style.width=w.style.height=t,!i&&s("iconSize","")&&(w.style.flexBasis=t),w.style.strokeWidth=s("iconStrokeWidth","1.5"),e.appendChild(w)}else e.textContent="🎤"},Cs=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled||!1===t.showButton)return null;let r=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),o="runtype"===t.provider?.type,n="custom"===t.provider?.type||"custom"===t.dictation?.provider?.type;if(!(r||o||n))return null;let a=st("div","persona-send-button-wrapper"),s=it("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-control",attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"}});xs(s,e),a.appendChild(s);let i=t.tooltipText??"Start voice recognition";return Qa({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??i,enabled:t.showTooltip??!1}),{button:s,wrapper:a}},Ss=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=st("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 o=st("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??yn).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let n=t.buttonIconName??"paperclip",a=st("div","persona-send-button-wrapper"),s=it("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${na} ${aa}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(n,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),o.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Qa({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:o,previewsContainer:r}},ks=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",o=st("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),pr(o,t,"idle");let n=t.idleText??"Online";if(t.idleLink){let e=st("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=n,e.style.color="inherit",e.style.textDecoration="none",o.appendChild(e)}else o.textContent=n;return o},As=()=>it("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Ms(e){let{config:t,onOpen:r}=e,o=t.buttonIconName??"plus",n=t.buttonTooltipText??"Add context",a=st("div","persona-send-button-wrapper"),s=it("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${na} ${aa}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":n,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(o,24,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Qa({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??n}),{button:s,wrapper:a}}let Is=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),Ts={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"},Es="16px",Ls="transparent",Bs={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:(()=>{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})(),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"}},Rs={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"}},Ps={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:is,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Es,canvasBackground:Ls,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"},operator:{background:"color-mix(in srgb, var(--persona-primary) 6%, var(--persona-container))",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"color-mix(in srgb, var(--persona-primary) 20%, var(--persona-container))",borderWidth:"1px",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"}}},Ns=Bs.colors.gray,$s={...Bs,colors:{...Bs.colors,gray:Ns}},Ws={...Bs,colors:{...Bs.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"}},Hs=$s,Ds=Rs,Os={...Rs,colors:{...Rs.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Rs.typography,fontSize:"14px",lineHeight:"1.5"}},Fs=Ds,zs=Ps,qs={...Ps,scrollToBottom:{...Ps.scrollToBottom,background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",size:"32px"},messageActions:{background:"transparent",border:"none",hoverBackground:"components.button.ghost.hoverBackground",hoverForeground:"semantic.colors.text",borderRadius:"palette.radius.md"},launcher:Ts,activity:{labelSize:"13px",iconSize:"16px",indent:"0px",transcriptGap:"0px",responseGap:"12px",groupIndent:"16px",groupGap:"2px",groupPadding:"2px 0",bodyPadding:"4px 0",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...Ps.input,borderRadius:"palette.radius.full"},introCard:{...Ps.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Ps.suggestion.chip,fontWeight:"400"},card:{...Ps.suggestion.card,fontWeight:"400"},list:{...Ps.suggestion.list,fontWeight:"400"}},panel:{...Ps.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Ps.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",iconPadding:"auto",controlSize:"28px",controlIconSize:"16px",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:{...Ps.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Ps.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:{...Ps.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"},operator:{...Ps.message.operator,background:"transparent",border:"semantic.colors.border",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"}},artifact:{...Ps.artifact,card:{background:"semantic.colors.surface",border:"1px solid var(--persona-border)",borderRadius:"palette.radius.lg",hoverBackground:"components.button.ghost.hoverBackground",hoverBorderColor:"semantic.colors.border"},inline:{background:"semantic.colors.surface",border:"1px solid var(--persona-border)",borderRadius:"palette.radius.lg",chromeBackground:"semantic.colors.surface",chromeBorder:"semantic.colors.border",titleColor:"semantic.colors.text",mutedColor:"semantic.colors.textMuted"}},composer:{...Ps.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",expandedPadding:"12px 16px",expandedBorderRadius:"24px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overflowMenu:{borderRadius:"12px"},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)"}},js=zs,_s=e=>"v5"===(e=>ps({future:e}))(e)?{palette:Ws,semantic:Os,components:qs}:{palette:$s,semantic:Ds,components:zs};function Us(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let e of r){if(null==o)return;o=o[e]}return"string"==typeof o&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Us(e,o):o}function Vs(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let o=`${n}.${a}`;if("string"==typeof s){let r=Us(e,s);void 0!==r&&(t[o]={path:o,value:r,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,o)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Ks(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 Qs(e,t){let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&o&&"object"==typeof o&&!Array.isArray(o)?Qs(t,o):o}return r}function Js(e,t={}){let r=_s(t.future),o=e?.components,n={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:o?Qs(r.components,o):r.components},a=o?.activity;for(let e of["toolBubble","reasoningBubble"]){let t=n.components[e]={...n.components[e]};for(let r of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[r]&&("bodySurface"!==r||void 0===o?.[e]?.bodySurface)&&(t[r]=a[r])}let s=o?.collapsibleWidget?.surface;"v4"===ps(t)&&void 0!==s&&void 0===a?.bodySurface&&(n.components.activity={...n.components.activity,bodySurface:s});let i=o?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(n.components.header.minimalPadding=n.components.header.padding);let l=o?.composer;n.components.composer={...n.components.composer},void 0!==l?.padding&&void 0===l.expandedPadding&&(n.components.composer.expandedPadding=l.padding),void 0!==o?.input?.borderRadius&&void 0===l?.expandedBorderRadius&&(n.components.composer.expandedBorderRadius=o.input.borderRadius);let d=o?.message;if(void 0!==d?.gap&&void 0===d.fullscreenGap&&(n.components.message.fullscreenGap=n.components.message.gap),!1!==t.validate){let e=Ks(n);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)n=e.transform(n);return n}let Gs=e=>"0"===e.trim()?"0px":e,Ys="--persona-",Xs=(e,t)=>{for(let[r,...o]of t){let t;for(let r of o)if(t=61===r.charCodeAt(0)?r.slice(1):e[Ys+r],void 0!==t)break;void 0!==t&&(e[Ys+r]=t)}},Zs=[["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-textMuted","palette-colors-gray-500"],["text-inverse","semantic-colors-textInverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["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"]];function ei(e){let t=(e=>{let t=Vs(e),r={};for(let[e,o]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=o.value;return r})(e);Xs(t,Zs),Xs(t,[["ask-sheet-bg","components-askUserQuestion-sheet-background"],["ask-sheet-border","components-askUserQuestion-sheet-border"],["ask-sheet-shadow","components-askUserQuestion-sheet-shadow"],["ask-pill-bg","components-askUserQuestion-pill-background"],["ask-pill-fg","components-askUserQuestion-pill-foreground"],["ask-pill-radius","components-askUserQuestion-pill-borderRadius"],["ask-pill-bg-selected","components-askUserQuestion-pill-selectedBackground"],["ask-pill-fg-selected","components-askUserQuestion-pill-selectedForeground"],["ask-input-bg","components-askUserQuestion-customInput-background"],["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"]]),(e=>{let t=e["--persona-components-launcher-foreground"];e["--persona-launcher-fg-muted"]=t&&t!==e["--persona-primary"]?`color-mix(in srgb, ${t} 70%, transparent)`:e["--persona-muted"]})(t),Xs(t,[["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"]]),Xs(t,[["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"]]),t["--persona-panel-border"]=t["--persona-components-panel-border"]??`1px solid ${t["--persona-border"]}`,Xs(t,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),t["--persona-panel-inset"]=t["--persona-components-panel-inset"]??"16px",t["--persona-panel-canvas-bg"]=t["--persona-components-panel-canvasBackground"]??"transparent",Xs(t,[["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"]]);let r=(r,o,n,a="")=>{if(r)for(let[s,i,l]of n){let n=r[a+s];n&&(t[`--persona-${o}${i}`]=l?Us(e,n)??n:n)}};Xs(t,[["header-bg","components-header-background","surface"]]);let o=t["--persona-header-bg"],n=t["--persona-components-header-foreground"],a=n?`color-mix(in srgb, ${n} 72%, ${o})`:void 0;t["--persona-header-border"]=t["--persona-components-header-border"]??(n?`color-mix(in srgb, ${n} 14%, ${o})`:void 0)??t["--persona-divider"],Xs(t,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),(e=>{if("auto"===e["--persona-components-header-iconPadding"]){let t=(e["--persona-components-header-iconBackground"]??e["--persona-primary"]).trim().toLowerCase(),r=t.match(/^(?:rgba?|hsla?)\(([^)]+)\)$/)?.[1].split(/[,\s/]+/).filter(Boolean);e["--persona-components-header-iconPadding"]="transparent"===t||/^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(t)||4===r?.length&&0===parseFloat(r[3])?"0px":"6px"}})(t),t["--persona-header-title-fg"]=t["--persona-components-header-title-color"]??t["--persona-components-header-titleForeground"]??n??t["--persona-primary"],t["--persona-header-subtitle-fg"]=t["--persona-components-header-subtitle-color"]??t["--persona-components-header-subtitleForeground"]??a??t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=t["--persona-components-header-actionIconForeground"]??a??t["--persona-muted"],Xs(t,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=16px"]]),r(e.components?.header,"header-",[["shadow","shadow"],["borderBottom","border-bottom"],["minHeight","min-height"]]),r(t,"history-rail-header-",[["background","bg"],["border","border"],["minHeight","min-height"]],"--persona-components-history-railHeader-"),r(t,"history-overlay-",[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]],"--persona-components-history-overlay-"),r(t,"history-menu-",[["background","bg"],["borderRadius","radius"]],"--persona-components-history-menu-");let s=e.components?.history?.motion;if(s){let e=e=>{if(void 0===e)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},r=e(s.enterDurationMs);void 0!==r&&(t["--persona-history-enter-ms"]=r);let o=e(s.exitDurationMs);void 0!==o&&(t["--persona-history-exit-ms"]=o),s.enterEasing&&(t["--persona-history-enter-easing"]=s.enterEasing),s.exitEasing&&(t["--persona-history-exit-easing"]=s.exitEasing)}let i=t["--persona-components-history-dangerForeground"];i&&(t["--persona-history-danger-fg"]=i),t["--persona-danger"]=t["--persona-components-history-confirm-dangerBackground"]??t["--persona-palette-colors-error-700"]??"#b42318",t["--persona-danger-fg"]=t["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let e of["scrim","shadow"]){let r=t[`--persona-components-history-confirm-${e}`];r&&(t[`--persona-history-confirm-${e}`]=r)}r(t,"tooltip-",[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]],"--persona-components-tooltip-"),!1===e.components?.tooltip?.arrow&&(t["--persona-tooltip-arrow-display"]="none"),r(t,"scroll-to-bottom-count-",[["background","bg"],["foreground","fg"],["border","border"],["borderRadius","radius"],["size","size"],["padding","padding"],["fontSize","font-size"],["fontWeight","font-weight"]],"--persona-components-scrollToBottom-countBadge-"),r(t,"scroll-to-bottom-approval-",[["background","bg"],["foreground","fg"],["border","border"],["fontWeight","font-weight"]],"--persona-components-scrollToBottom-approval-"),r(t,"message-action-",[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]],"--persona-components-messageActions-"),r(t,"user-collapse-",[["fadeHeight","fade-height"],["toggleForeground","toggle-fg"],["toggleFontSize","toggle-font-size"],["toggleFontWeight","toggle-font-weight"]],"--persona-components-userMessageCollapse-"),Xs(t,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let l=t["--persona-components-introCard-background"],d=t["--persona-components-introCard-shadow"],c=!(l&&"transparent"!==l&&"none"!==l||d&&"none"!==d),p=t["--persona-components-introCard-padding"]??"1.5rem";t["--persona-intro-card-padding"]=c&&"1.5rem"===p?"1.5rem 0":p,Xs(t,[["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"]]),Xs(t,[["panel-background","components-panel-background","surface"],["transcript-background","components-message-background","container"],["transcript-top-fade-background","components-message-topFadeBackground","transcript-background"],["composer-footer-background","components-composer-footerBackground","surface"],["composer-footer-padding","components-composer-footerPadding","=1rem 1.5rem"],["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"]]),r(t,"md-",[["h1-fontSize","h1-size"],["h1-fontWeight","h1-weight"],["h2-fontSize","h2-size"],["h2-fontWeight","h2-weight"]],"--persona-components-markdown-heading-");let u=t["--persona-components-markdown-prose-fontFamily"];u&&"inherit"!==u&&(t["--persona-md-prose-font-family"]=u),Xs(t,[["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"]]),Xs(t,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Xs(t,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Xs(t,[["md-hr-color","components-markdown-hr-color","divider"]]),Xs(t,[["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"]]);for(let[e,r]of[["container","surface"],["surface","surface"],["border","border"]]){let o=t[`--persona-components-collapsibleWidget-${e}`]??t[`--persona-${r}`];void 0!==o&&(t[`--persona-cw-${e}`]=o,t[`--cw-${e}`]=o)}Xs(t,[["message-border","components-message-border","border"]]),Xs(t,[["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"],["message-operator-padding","components-message-operator-padding"],["message-operator-max-width","components-message-operator-maxWidth"],["message-operator-font-size","components-message-operator-fontSize"],["message-operator-font-family","components-message-operator-fontFamily"],["message-operator-line-height","components-message-operator-lineHeight"]]);let h=e.components;r(h?.iconButton,"icon-btn-",[["background","bg"],["border","border"],["color","color"],["padding","padding"],["borderRadius","radius"],["hoverBackground","hover-bg"],["hoverColor","hover-color"],["activeBackground","active-bg"],["activeBorder","active-border"]]),r(h?.labelButton,"label-btn-",[["background","bg"],["border","border"],["color","color"],["padding","padding"],["borderRadius","radius"],["hoverBackground","hover-bg"],["fontSize","font-size"],["gap","gap"]]),r(h?.toggleGroup,"toggle-group-",[["gap","gap"],["borderRadius","radius"]]);let m=h?.artifact;if(m?.toolbar){let o=m.toolbar;r(o,"artifact-toolbar-icon-",[["iconHoverColor","hover-color"],["iconHoverBackground","hover-bg"],["iconPadding","padding"],["iconBorderRadius","radius"],["iconBorder","border"]]),o.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Gs(o.toggleGroupGap)),o.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=o.toggleBorderRadius),o.toggleGroupPadding&&(t["--persona-artifact-toolbar-toggle-group-padding"]=Gs(o.toggleGroupPadding)),r(o,"artifact-toolbar-toggle-group-",[["toggleGroupBorder","border"],["toggleGroupBorderRadius","radius"]]),o.toggleGroupBackground&&(t["--persona-artifact-toolbar-toggle-group-bg"]=Us(e,o.toggleGroupBackground)??o.toggleGroupBackground),r(o,"artifact-toolbar-copy-",[["copyBackground","bg"],["copyBorder","border"],["copyColor","color"]]),o.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Gs(o.copyBorderRadius)),o.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=o.copyPadding),o.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=o.copyMenuBackground,t["--persona-dropdown-bg"]=t["--persona-dropdown-bg"]??o.copyMenuBackground),o.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=o.copyMenuBorder,t["--persona-dropdown-border"]=t["--persona-dropdown-border"]??o.copyMenuBorder),o.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=o.copyMenuShadow,t["--persona-dropdown-shadow"]=t["--persona-dropdown-shadow"]??o.copyMenuShadow),o.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=o.copyMenuBorderRadius,t["--persona-dropdown-radius"]=t["--persona-dropdown-radius"]??o.copyMenuBorderRadius),o.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=o.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=t["--persona-dropdown-item-hover-bg"]??o.copyMenuItemHoverBackground),r(o,"artifact-toolbar-",[["iconBackground","icon-bg"],["toolbarBorder","border"]])}if(m?.tab&&r(m.tab,"artifact-tab-",[["background","bg"],["activeBackground","active-bg"],["activeBorder","active-border"],["borderRadius","radius"],["textColor","color"],["hoverBackground","hover-bg"],["listBackground","list-bg"],["listBorderColor","list-border-color"],["listPadding","list-padding"]]),m?.pane){let r=m.pane;r.toolbarBackground&&(t["--persona-artifact-toolbar-bg"]=Us(e,r.toolbarBackground)??r.toolbarBackground)}r(m?.card,"artifact-card-",[["background","bg",!0],["border","border"],["borderRadius","radius",!0],["hoverBackground","hover-bg",!0],["hoverBorderColor","hover-border",!0]]),r(m?.inline,"artifact-inline-",[["background","bg",!0],["border","border"],["borderRadius","radius",!0],["chromeBackground","chrome-bg",!0],["chromeBorder","chrome-border",!0],["titleColor","title-color",!0],["mutedColor","muted-color",!0],["frameHeight","frame-height"]]);let g=h?.code;g&&(r(g,"code-",[["keywordColor","keyword-color"],["stringColor","string-color"],["commentColor","comment-color"],["numberColor","number-color"],["tagColor","tag-color"],["attrColor","attr-color"],["propertyColor","property-color"],["lineNumberColor","line-number-color"],["gutterBorderColor","gutter-border-color"]]),g.background&&(t["--persona-code-bg"]=Us(e,g.background)??g.background));let f=t["--persona-surface"],b=t["--persona-container"],y=t["--persona-palette-colors-gray-100"]??"#f3f4f6",v=t["--persona-palette-colors-gray-200"]??"#e5e7eb",w=t["--persona-palette-colors-gray-300"]??"#d1d5db",x=!b||b===f,C=(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[o,n,a]=t.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return.2126*o+.7152*n+.0722*a})(f??t["--persona-background"]),S=x&&void 0!==C&&C<.179,k=S?"rgba(255, 255, 255, 0.16)":w,A=x?S?"rgba(255, 255, 255, 0.08)":y:b,M=x?S?"rgba(255, 255, 255, 0.12)":v:b;return t["--persona-icon-btn-hover-bg"]=t["--persona-icon-btn-hover-bg"]??A,t["--persona-icon-btn-active-bg"]=t["--persona-icon-btn-active-bg"]??M,x&&(t["--persona-icon-btn-active-border"]=t["--persona-icon-btn-active-border"]??k),t["--persona-label-btn-hover-bg"]=t["--persona-label-btn-hover-bg"]??A,t["--persona-artifact-tab-hover-bg"]=t["--persona-artifact-tab-hover-bg"]??A,t["--persona-artifact-card-hover-bg"]=t["--persona-artifact-card-hover-bg"]??A,t}let ti={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)"}}}},ri={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"}}},oi={...ri,colors:{...ri.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"}}},ni=ti,ai={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:{...ti.components,button:{...ti.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:{...ti.components?.eventStream,badge:{...ti.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"}}}}},si=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},ii=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",li=e=>(e=>{let t=e?.colorScheme??L(e?.brand)??"light";return"light"===t?"light":"dark"===t?"dark":ii()})(e),di=e=>{let t=li(e),r=k(((e,t="light",r,o=!1)=>{let n={};if(!e)return n;let a=A(e.accent);if(a){let e={};for(let[t,r]of[[50,.96],[100,.9],[200,.75],[300,.55],[400,.25]])e[t]=T(a,255,r);e[500]=I(a);for(let[t,r]of[[600,.15],[700,.3],[800,.45],[900,.6],[950,.75]])e[t]=T(a,0,r);let t=E(a);n.palette={colors:{primary:e,accent:e}},n.semantic={colors:{primary:e[500],accent:e[500],interactive:{default:e[500],hover:e[600],focus:e[500],active:e[700]}}},n.components={button:{primary:{background:e[500],foreground:t}},launcher:{background:e[500],foreground:t},header:o?{background:"semantic.colors.container",foreground:"semantic.colors.text",iconBackground:"transparent",iconForeground:"semantic.colors.text"}:{background:e[500],foreground:t,iconBackground:e[500],iconForeground:t},approval:{approve:{foreground:t}},message:o?{user:{background:"color-mix(in srgb, var(--persona-primary) 12%, var(--persona-container))",text:"semantic.colors.text"},operator:{border:"color-mix(in srgb, var(--persona-primary) 35%, var(--persona-border))"}}:{user:{background:e[500],text:t}}}}let s=A(e.neutral);if(s){let e="dark"===t,r=e===M(s)<.18?s:A(T(s,e?0:255,.9)),o=I(r),a=T(r,e?255:0,e?.06:.025),i=T(r,e?255:0,e?.2:.16),l=E(r),d={};for(let[e,t]of[[50,0],[100,.06],[200,.16],[300,.28],[400,.45],[500,.65],[600,.72],[700,.8],[800,.9],[900,.97],[950,1]])d[e]=T(r,"#ffffff"===l?255:0,t);n.palette={...n.palette,colors:{...n.palette?.colors,gray:d}},n.semantic={...n.semantic,colors:{...n.semantic?.colors,surface:o,background:o,container:a,border:i,divider:i,text:l,textMuted:T(r,"#ffffff"===l?255:0,.65)}},n.components={...n.components,panel:{background:o},header:{...n.components?.header,background:o,foreground:l},composer:{footerBackground:o}}}if(a){let e=A(n.semantic?.colors?.surface)??("dark"===t?[15,15,16]:[255,255,255]),r=I(a),o="#ffffff"===E(e)?255:0;for(let t=0;t<=1;t+=.1){r=T(a,o,t);let n=M(A(r)),s=M(e);if((Math.max(n,s)+.05)/(Math.min(n,s)+.05)>=4.5)break}n.components={...n.components,markdown:{link:{foreground:r}},input:{focus:{border:r,ring:r}}}}e.font?.trim()&&(n.semantic={...n.semantic,typography:{fontFamily:e.font}});let i={none:"0px",sm:"4px",md:"8px",lg:"16px"}[e.radius??"none"];e.radius&&i&&(n.palette={...n.palette,radius:{none:"0px",sm:i,md:i,lg:i,xl:i,"2xl":i}},n.components={...n.components,input:{...n.components?.input,borderRadius:i},header:{...n.components?.header,controlBorderRadius:i}});let l={compact:[13,44,8],comfortable:[14,48,12],spacious:[15,52,16]}[e.density??"comfortable"];if(e.density&&l){let[e,t,r]=l;n.semantic={...n.semantic,typography:{...n.semantic?.typography,fontSize:`${e}px`}},n.components={...n.components,header:{...n.components?.header,minHeight:`${t}px`,padding:`${r}px 16px`,minimalPadding:`${r}px 16px`},history:{railHeader:{minHeight:`${t}px`}},composer:{...n.components?.composer,fontSize:`${e}px`,padding:`${r}px`,gap:r/2+"px"},message:{...n.components?.message,gap:`${r}px`,user:{...n.components?.message?.user,fontSize:`${e}px`},assistant:{fontSize:`${e}px`},operator:{...n.components?.message?.operator,fontSize:`${e}px`}}}}if(e.elevation&&["flat","subtle","raised"].includes(e.elevation)){let t="flat"===e.elevation,a=t?"none":"subtle"===e.elevation?"0 2px 8px rgba(0, 0, 0, 0.08)":"0 12px 32px rgba(0, 0, 0, 0.18)",s=t?"1px solid var(--persona-border)":"1px solid color-mix(in srgb, var(--persona-border) 65%, transparent)";n.palette={...n.palette,shadows:{sm:a,md:a,lg:a,xl:a,"2xl":a}};let i=(e,r="")=>{let n={};if(o&&"message.assistant"===r)return n;for(let[o,l]of Object.entries(e))if(o.toLowerCase().endsWith("shadow")){n[o]=a;let r="shadow"===o?"border":o.replace(/Shadow$/,"Border");r in e&&(n[r]="string"==typeof e[r]&&e[r].includes("solid")?s:t?"semantic.colors.border":"color-mix(in srgb, var(--persona-border) 65%, transparent)")}else if(l&&"object"==typeof l){let e=i(l,r?`${r}.${o}`:o);Object.keys(e).length&&(n[o]=e)}return n},l=r?i(r):{};n.components=k(n.components,l),n.components={...n.components,panel:{...n.components?.panel,shadow:a,modes:{floating:{shadow:a,border:s},inline:{shadow:a,border:s},docked:{shadow:a,border:s},sidebar:{shadow:a,border:s},mobile:{shadow:a,border:s}}},launcher:{...n.components?.launcher,shadow:a,border:"semantic.colors.border"},composer:{...n.components?.composer,shadow:a,borderColor:"semantic.colors.border"},toolBubble:{shadow:a},reasoningBubble:{shadow:a}}}return n})(e?.brand,t,_s(e?.future).components,e?.future?.v5Defaults),si(e?.theme)),o=k({components:{launcher:"circle"===Is(e)?Ts:{...zs.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},...as(e)?{panel:{background:"transparent",modes:{inline:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"transparent"},message:{background:"transparent"},composer:{footerBackground:"transparent",footerBorder:"none",overlayBand:"transparent"}}:{}}},r),n=si(e?.darkTheme),a=((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,o=t.darkTheme?.components?.panel?.width;return null==("dark"===li(t)?o??r:r)?{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===ps(t)?"400px":"420px"}}}:e})("dark"===t?((e,t={})=>{let r=(e=>"v5"===ps({future:e})?{palette:oi,components:ai}:{palette:ri,components:ni})(t.future),o=k(r.components,e??{})??{};return Js({...o,palette:{...o.palette,colors:"v5"===ps(t)?k(r.palette.colors,o.palette?.colors):{...r.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})})(k(o??{},n??{}),{future:e?.future}):((e,t={})=>Js(e,t))(o,{future:e?.future}),e);return Object.defineProperty(a,ci,{value:[...P,"suggestion.chip.padding","suggestion.chip.fontWeight"].filter(r=>q(e,r,t))}),a},ci=Symbol("persona.themeConsumerPaths"),pi=new WeakMap,ui=(e,t)=>{hi(e,(e=>{let t=ei(e);t["--persona-suggestion-compat-padding"]="6px 12px",t["--persona-suggestion-compat-weight"]="500";for(let r of e[ci]??[]){let e=r.split(".").join("-"),o=t[`--persona-components-${e}`];void 0!==o&&(t["suggestion.chip.padding"===r?"--persona-suggestion-compat-padding":"suggestion.chip.fontWeight"===r?"--persona-suggestion-compat-weight":`--persona-consumer-${e}`]=o)}return t})(di(t)),t)},hi=(e,t,r)=>{for(let r of pi.get(e)??[])r in t||e.style.removeProperty(r);pi.set(e,Object.keys(t));for(let[r,o]of Object.entries(t))e.style.setProperty(r,o);e.setAttribute("data-persona-color-scheme",li(r)),e.setAttribute("data-persona-defaults",ps(r))},mi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(ii())});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)"),o=()=>e(ii());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(e=>e())}},gi=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),fi=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",bi=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},yi=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},vi=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},wi=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),o={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)o.mod=!0;else if("shift"===r)o.shift=!0;else{if("alt"!==r&&"option"!==r)return vi("unknown modifier in",e),null;o.alt=!0}return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(vi("unsupported",e),null):("space"===r&&(o.key=" "),o)},xi=(e,t)=>{let r=wi(e);if(!r)return"";let o=yi(),n=(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&&o)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${n}`;let a=[t?o?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(n),a.join("+")},Ci=e=>xi(e,!1),Si=e=>xi(e,!0),ki=(e,t)=>t.key?.toLowerCase()===e.key&&(yi()?t.metaKey:t.ctrlKey)===e.mod&&!(yi()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Ai=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},Mi=e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),o=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let o=r.composedPath?.();return o?.length?o.includes(e):e.contains(r.target)},n=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let n of t.values())if(ki(n.parsed,e)&&!1!==n.when?.()&&o(n,e)&&(n.allowInInput||!Ai(r))){e.preventDefault();try{n.run(e)}catch(e){vi(`${n.id} threw on`,n.combo),console.warn(e)}return}};return r?.addEventListener("keydown",n),{register(e){let r=wi(e.combo);if(!r)return()=>{};let o=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,n=t.get(o);return n?(vi(`${n.id} already owns`,e.combo),()=>{}):(t.set(o,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",Si(e.combo)),()=>{t.get(o)?.id===e.id&&t.delete(o),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",n)}}};u=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: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,n){if(!1===n.callbacks.beforeNodeAdded(t))return null;if(n.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),o(a,t,n),n.callbacks.afterNodeAdded(a),a}{let o=document.importNode(t,!0);return e.insertBefore(o,r),n.callbacks.afterNodeAdded(o),o}}let t=function(){function e(e,t,r){let o=e.idMap.get(t),n=e.idMap.get(r);if(!n||!o)return!1;for(let e of o)if(n.has(e))return!0;return!1}function t(e,t){let r=e,o=t;return r.nodeType===o.nodeType&&r.tagName===o.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===o.getAttribute?.("id"))}return function(r,o,n,a){let s=null,i=o.nextSibling,l=0,d=n;for(;d&&d!=a;){if(t(d,o)){if(e(r,d,o))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 n(e,t,o){let n=t;for(;n&&n!==o;){let t=n;n=n.nextSibling,r(e,t)}return n}function a(e,t,r,o){let n=o.target.getAttribute?.("id")===t&&o.target||o.target.querySelector(`[id="${t}"]`)||o.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let o=t.idMap.get(e);o&&(o.delete(r),o.size||t.idMap.delete(e))}}(n,o),s(e,n,r),n}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&&n(s,d,e),o(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);o(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)}}}(),o=function(){function e(e,r,o){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)n(e.name,a,"update",o)||a.getAttribute(e.name)!==e.value&&a.setAttribute(e.name,e.value);for(let e=l.length-1;0<=e;e--){let t=l[e];if(t&&!i.hasAttribute(t.name)){if(n(t.name,a,"remove",o))continue;a.removeAttribute(t.name)}}s(a,o)||t(a,i,o)}(8===a||3===a)&&e.nodeValue!==r.nodeValue&&(e.nodeValue=r.nodeValue)}function t(e,t,r){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==t.type){let a=t.value,s=e.value;o(e,t,"checked",r),o(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(n("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):n("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)o(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let o=t.value,a=e.value;if(n("value",e,"update",r))return;o!==a&&(e.value=o),e.firstChild&&e.firstChild.nodeValue!==o&&(e.firstChild.nodeValue=o)}}function o(e,t,r,o){let a=t[r];if(a!==e[r]){let s=n(r,e,"update",o);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):n(r,e,"remove",o)||e.removeAttribute(r)}}function n(e,t,r,o){return!("value"!==e||!o.ignoreActiveValue||t!==document.activeElement)||!1===o.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,o,n){return n.ignoreActive&&t===document.activeElement?null:(!1===n.callbacks.beforeNodeMorphed(t,o)||(t instanceof HTMLHeadElement&&n.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==n.head.style?a(t,o,n):(e(t,o,n),s(t,n)||r(n,t,o))),n.callbacks.afterNodeMorphed(t,o)),t)}}();function n(e,t,r,o){if(e.head.block){let n=t.querySelector("head"),s=r.querySelector("head");if(n&&s){let t=a(n,s,e);return Promise.all(t).then(()=>o(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return o(e)}function a(e,t,r){let o=[],n=[],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),o=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?o?n.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?o&&(n.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&n.push(t)}s.push(...i.values());let l=[];for(let t of s){let n=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(n)){if("href"in n&&n.href||"src"in n&&n.src){let e,t=new Promise(function(t){e=t});n.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(n),r.callbacks.afterNodeAdded(n),o.push(n)}}for(let t of n)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:o,kept:a,removed:n}),l}let s=function(){function e(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}function r(){let e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function o(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 a(e,t,r,o){for(let n of o){let o=n.getAttribute("id");if(t.has(o)){let t=n;for(;t;){let n=e.get(t);if(n??(n=new Set,e.set(t,n)),n.add(o),t===r)break;t=t.parentElement}}}}function s(e,t){let r=n(e),o=n(t),s=function(e,t){let r=new Set,o=new Map;for(let{id:t,tagName:n}of e)o.has(t)?r.add(t):o.set(t,n);let n=new Set;for(let{id:e,tagName:a}of t)n.has(e)?r.add(e):o.get(e)===a&&n.add(e);for(let e of r)n.delete(e);return n}(r,o),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,o),{persistentIds:s,idMap:i}}return function(t,n,a){let{persistentIds:i,idMap:l}=s(t,n),d=e(a),c=d.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(c))throw`Do not understand how to morph style ${c}`;return{target:t,newContent:n,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:o(t),callbacks:d.callbacks,head:d.head}}}(),{normalizeElement:i,normalizeParent:l}=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 o=r.querySelectorAll(e);for(let e=0;e<o.length;e++)t.push(o[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(o){if(null==o)return document.createElement("div");if("string"==typeof o)return r(function(t){let r=new DOMParser,o=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(o.match(/<\/html>/)||o.match(/<\/head>/)||o.match(/<\/body>/)){let n=r.parseFromString(t,"text/html");if(o.match(/<\/html>/))return e.add(n),n;{let t=n.firstChild;return t&&e.add(t),t}}{let o=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(o),o}}(o));if(e.has(o))return o;if(o instanceof Node){if(o.parentNode)return new t(o);{let e=document.createElement("div");return e.append(o),e}}{let e=document.createElement("div");for(let t of[...o])e.append(t);return e}}}}();return{morph:function(e,t,o={}){e=i(e);let a=l(t),d=s(e,a,o),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:o,selectionStart:n,selectionEnd:a}=r,s=t();return o&&o!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${o}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(n,a),s}(d,()=>n(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,o){let n=l(t);return r(e,n,o,t,t.nextSibling),Array.from(n.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let Ii=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;u.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement){if(t instanceof HTMLElement&&t.hasAttribute("data-persona-reuse")&&e.id===t.id)return!1;if(o){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"))return t instanceof HTMLElement&&(!t.hasAttribute("data-preserve-animation")||(e.dataset.personaLoadingLabel?e.dataset.personaLoadingAnimation!==t.dataset.personaLoadingAnimation:e.textContent!==t.textContent))&&void 0}}}}})},Ti={index:-1,draft:""},Ei=new WeakMap;function Li(e){if("string"==typeof e)return e.length;if(!e)return 0;if("object"!=typeof e)return JSON.stringify(e)?.length??0;let t=Ei.get(e);return void 0===t&&(t=JSON.stringify(e)?.length??0,Ei.set(e,t)),t}function Bi(e,t){return[e.id,e.role,e.author?.id??"",e.author?.displayName??"",e.author?.kind??"",e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.dispatchError?"1":"0",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)??"",Li(e.toolCall?.args),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??"",e.toolCall?.actionTitle??"",t].join("\0")}let Ri=["pre","code","a","script","style"],Pi=e=>({type:e?.type??"none",placeholder:e?.placeholder??"none",speed:e?.speed??120,duration:e?.duration??1800,buffer:e?.buffer??"none"}),Ni=[{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"}],$i=new Map;for(let e of Ni)$i.set(e.name,e);let Wi=["wipe","glyph-cycle"],Hi=e=>{$i.set(e.name,e)},Di=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:$i.get(e)??null,Oi=(e,t,r,o,n)=>{if(!n)return e;if(r?.bufferContent)return r.bufferContent(e,o);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},Fi=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},zi=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},qi=/\s/,ji=(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},_i=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(qi.test(a[i])){let e=i;for(;e<a.length&&qi.test(a[e]);)e+=1;s.appendChild(o.createTextNode(a.slice(i,e))),i=e}else{let e=o.createElement("span");e.className="persona-stream-word-group";let n=i;for(;n<a.length&&!qi.test(a[n]);)e.appendChild(Fi(o,a[n],t,r.value)),r.value+=1,n+=1;s.appendChild(e),i=n}n.replaceChild(s,e)},Ui=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(o.createTextNode(e)):(s.appendChild(zi(o,e,t,r.value)),r.value+=1));n.replaceChild(s,e)},Vi=(e,t,r,o)=>{if(!e||typeof document>"u")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set((o?.skipTags??Ri).map(e=>e.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)ji(l,a)||i.push(l),l=s.nextNode();let d={value:o?.startIndex??0},c="char"===t?_i:Ui;for(let e of i)c(e,r,d);return n.innerHTML},Ki=(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},Qi=(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},Ji=new WeakMap,Gi=new WeakMap,Yi=e=>{let t=Gi.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}},Xi=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=Ji.get(t);if(r||(r=new Set,Ji.set(t,r)),r.has(e.name)){let o=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${o}"]`))return;r.delete(e.name)}r.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Gi.get(t);if(r||(r=new Map,Gi.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)})(e,t)},{setLoader:Zi,load:el}=_({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),tl=Zi,rl=el;function ol(e,t=1e5){let r=e.style.position,o=e.style.zIndex,n=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=o,e.style.isolation=n}}let nl=0,al=null;function sl(e=document){if(nl++,1===nl){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;al={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,nl=Math.max(0,nl-1),0===nl&&al)){let t=e.body,r=e.defaultView??window;t.style.overflow=al.originalOverflow,t.style.position=al.originalPosition,t.style.top=al.originalTop,t.style.width=al.originalWidth,r.scrollTo(0,al.scrollY),al=null}}}let il=e=>"docked"===(e?.launcher?.mountMode??"floating"),ll=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),dl=e=>{let t=e?.launcher?.dock,r=rs(e).dockWidth?t?.width:Us(di(e),"components.panel.width");return{side:t?.side??"right",width:r??"420px",animate:t?.animate??!0,reveal:t?.reveal??"resize",maxHeight:t?.maxHeight??"100dvh"}},cl=e=>e.closest("[data-persona-instance]")?.dataset.personaInstance,pl=e=>"followUp"===e?"follow-up":e,ul=(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 o=e.prompt?.trim()||r;return{id:e.id?.trim()||o||`suggestion-${t}`,label:r,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},hl=new WeakSet,ml=e=>{let{item:t,index:r,surface:o,source:n,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,m="followUp"===o,g=t.behavior,f=()=>{if(c.isStreaming()||u.closest("[inert]"))return;let e={instanceId:cl(u),suggestion:{...t},surface:o,source:n,behavior:g},r=u.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(m&&u.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{instanceId:cl(u),suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of l)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:o,source:n,variant:a,config:i}))return;let s=p();"fill"===g?(s.value=t.prompt,s.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),s.focus()):h?h(t.prompt):(s.value="",c.sendMessage(t.prompt))},b=()=>{let e=st("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=g,"chip"===a){let t=i.suggestionChipsConfig===d?i:{suggestionChipsConfig:d},r=e=>F(t,`suggestionChipsConfig.${e}`),o=e=>q(i,`suggestion.chip.${e}`,"light")||q(i,`suggestion.chip.${e}`,"dark");d?.fontWeight&&(e.style.fontWeight=!r("fontWeight")&&o("fontWeight")?"var(--persona-suggestion-compat-weight, 500)":d.fontWeight);let n=o("padding");n&&(e.classList.add("persona-theme-padding"),e.style.setProperty("--persona-theme-padding","var(--persona-suggestion-compat-padding, 6px 12px)")),d?.paddingX&&(r("paddingX")||!n)&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(r("paddingY")||!n)&&(e.style.paddingTop=d.paddingY,e.style.paddingBottom=d.paddingY)}if(t.icon){let r=Ee(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=st("span","persona-suggestion__copy");if(r.appendChild(it("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==a&&r.appendChild(it("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(r),"chip"!==a){let t=ne(ce,16,"currentColor",1.8);t&&(t.classList.add("persona-suggestion__arrow"),e.appendChild(t))}return e.addEventListener("click",f),e},y=null;for(let e of l)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:r,surface:o,source:n,variant:a,streaming:s,config:i,defaultRenderer:b,select:f}),y))break;return y??=b(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute("aria-disabled",s?"true":"false"),y},gl=e=>{let t=[],r=[],o=null,n=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(n=null,e.toggleAttribute("data-edge-to-edge",e.hasAttribute("data-hide-scrollbar")&&(e.hasAttribute("data-persona-composer-suggestions")||"follow-up"===e.dataset.personaSuggestions)&&"chip"===e.dataset.variant&&"scroll"===e.dataset.overflow),e.hasAttribute("data-edge-to-edge")&&e.parentElement){let t=e.parentElement,r=getComputedStyle(t),o=parseFloat(r.paddingLeft)||0,n=parseFloat(r.paddingRight)||0;e.style.setProperty("--persona-suggestion-bleed-left",`${o}px`),e.style.setProperty("--persona-suggestion-bleed-right",`${n}px`);let a=t.closest(".persona-widget-container")?.querySelector("form"),s=t.getBoundingClientRect(),i=a?.getBoundingClientRect();e.style.setProperty("--persona-suggestion-inset-left",`${i?.width?i.left-s.left:o}px`),e.style.setProperty("--persona-suggestion-inset-right",`${i?.width?s.right-i.right:n}px`)}if(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,o=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=o<=4,i=o>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==n||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():n=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!==n&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n),n=null},render:(n,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",b=u?.behavior??"send",y=u?.overflow??"wrap",v=u?.config??{},w=u?.plugins??[];e.toggleAttribute("data-hide-scrollbar",!0===v.future?.v5Defaults),e.dataset.edgeStyle=v.suggestions?.[g?"followUps":"starters"]?.edgeStyle??"fade";let x="number"==typeof u?.maxItems?Math.max(0,Math.floor(u.maxItems)):void 0,C=g?"followUps":"starters";!hl.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(hl.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(ul).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??b})),k=S(n??[]);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,o=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(o=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=pl(m),e.dataset.variant=f,e.dataset.overflow=y;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((o,n)=>{let a=ml({item:o,index:n,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!==o&&(o=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:{instanceId:cl(e),suggestions:A.map(e=>({...e})),surface:m,source:h,variant:f},bubbles:!0,composed:!0})),g&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{instanceId:cl(e),suggestions:A.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},fl={"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"},bl={x:[1.4,1.05]},yl="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",vl=(e,t,r={})=>{let{iconSize:o,iconText:n}=r,[a,s]=bl[t]??[1,1.5],i=!o;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=Ee(t,`${Math.round((parseFloat(o??"")||16)*a)}px`,"currentColor",s);l?(l.style.display="block",i||(l.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((s/1.5).toFixed(4))})`),e.replaceChildren(l)):n&&(e.textContent=n)},wl=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:o,iconName:n,iconText:a,wrapperClassName:s=yl,size:i,iconSize:l,color:d,backgroundColor:c,borderWidth:p,borderColor:u,borderRadius:h,paddingX:m,paddingY:g,hidden:f,extraClassName:b,attrs:y}=e,v=st("div",s),w=!(!p&&!u),x=it("button",{className:lt("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",b),attrs:{type:"button","aria-label":t,...y},style:{width:i,height:i,minWidth:i,minHeight:i,display:f?"none":void 0,color:d||kl.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return n?vl(x,n,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Qa({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:o,enabled:r}),{button:x,wrapper:v}},xl=(e,t,r,o={})=>{let n=t?.launcher,a=n?.clearChat,s=e=>Ga(t,(e=>"close"===r?`launcher.closeButton${e[0].toUpperCase()}${e.slice(1)}`:`launcher.clearChat.${"color"===e?"iconColor":e}`)(e)),i=(e,o)=>Ja(t,`header.${r}`,e,o),l=(e,t,r)=>s(e)||i(t,r),d=o.buttonSize||s("size");Xa(e,d||i("size","var(--persona-header-control-size, 32px)"),d),!d&&""===i("size","")&&(e.style.width=e.style.height="");let c="close"===r?n?.closeButtonBackgroundColor:a?.backgroundColor;e.style.color=l("color","foreground",kl.actionIconColor),e.style.backgroundColor=s("backgroundColor")||(i("background","")?i("background",c||"transparent"):c||""),e.classList.toggle("hover:persona-bg-gray-100",!c&&!s("backgroundColor")&&""===i("background",""));let p="close"===r?n?.closeButtonBorderWidth:a?.borderWidth,u="close"===r?n?.closeButtonBorderColor:a?.borderColor,h=!!(p||u||i("borderWidth","")||i("borderColor",""));e.style.border=h?`${l("borderWidth","borderWidth",p||"0px")} solid ${l("borderColor","borderColor",u||"transparent")}`:"",e.classList.toggle("persona-border-none",!h);let m="close"===r?n?.closeButtonBorderRadius:a?.borderRadius;e.style.borderRadius=s("borderRadius")||(i("borderRadius","")?i("borderRadius","var(--persona-components-header-controlBorderRadius, 9999px)"):m||""),e.classList.toggle("persona-rounded-full",!e.style.borderRadius);let g="close"===r?n?.closeButtonPaddingX:a?.paddingX,f="close"===r?n?.closeButtonPaddingY:a?.paddingY,b=i("padding","0px");Ya(e,b,s("paddingX")||("0px"===b?g:void 0),s("paddingY")||("0px"===b?f:void 0));let y="close"===r?n?.closeButtonIconName??"x":a?.iconName??"refresh-cw";vl(e,y,{iconSize:o.iconSize,iconText:"close"===r?n?.closeButtonIconText??"×":void 0});let v=e.querySelector("svg");if(v){let e=bl[y]?.[0]??1,t=i("iconSize","");!o.iconSize&&t&&(v.style.width=v.style.height=`calc(${i("iconSize","var(--persona-header-control-icon-size, 16px)")} * ${e})`),i("iconStrokeWidth","")&&(v.style.strokeWidth=`calc(${i("iconStrokeWidth","var(--persona-components-header-controlStrokeWidth, 1.5)")} * ${1===e?1:.7})`)}},Cl=(e,t={})=>{let{showClose:r=!0,wrapperClassName:o=yl,buttonSize:n,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=wl({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:o,size:n??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 xl(d,e,"close",{buttonSize:n,iconSize:a}),{button:d,wrapper:c}},Sl=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:o,iconSize:n}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=wl({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:o??a.size,iconSize:n,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return xl(l,e,"clear",{buttonSize:o,iconSize:n}),{button:l,wrapper:d}},kl={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)"},Al={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)"},Ml={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)"},Il=e=>{let{config:t,showClose:r=!0}=e,o=it("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:kl.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)))"}}),n=t?.launcher??{},a=n.headerIconSize??"40px",s=n.closeButtonPlacement??"inline",i=n.headerIconHidden??!1,l=n.headerIconName,d=it("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,boxSizing:"content-box",padding:"var(--persona-components-header-iconPadding, 0px)",flexShrink:"0",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=Ee(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=st("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=st("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=it("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:kl.titleColor,...Al}}),u=it("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:kl.subtitleColor,...Ml}});c.append(p,u),i?o.append(c):o.append(d,c);let h=n.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,b=null;if(m){let e=Sl(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,b=e.wrapper,"top-right"===g&&(b.style.right="48px"),"inline"===g&&o.appendChild(b)}let{button:y,wrapper:v}=Cl(t,{showClose:r,wrapperClassName:"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"});return"top-right"!==s&&o.appendChild(v),{header:o,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:y,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:b}},Tl=(e,t,r)=>{let o=r?.launcher??{},n=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===n&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))},El=e=>{let t=Il({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},Ll=e=>{let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=t?.launcher??{},i=st("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=kl.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=n?.titleMenu;if(c){let e=gt({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,instanceId:e.element.closest("[data-persona-instance]")?.dataset.personaInstance}}))},o=c.onSelect(t);o instanceof Promise?o.then(r,()=>{}):r(o)},hover:c.hover,className:""});l=e.element,l.style.color=kl.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=st("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=st("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=kl.titleColor,Object.assign(d.style,Al),d.textContent=s.title??"Chat Assistant",l.appendChild(d),n?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=n.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=n?.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}=Cl(t,{showClose:r,wrapperClassName:p});o&&u.addEventListener("click",o);let m=st("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let o of t){let{button:t,wrapper:n}=wl({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Ci(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",o.id),o.shortcut){let e=Si(o.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(o.menuItems?.length){let e=ct({items:o.menuItems,onSelect:e=>r?.(e),anchor:n,position:"bottom-right"});n.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(o.id));e.appendChild(n)}}(m,n?.trailingActions,n?.onAction??a);let g=s.clearChat??{},f=null,b=null;if(g.enabled??1){let e=g.placement??"inline",r=Sl(t,{wrapperClassName:"top-right"===e?"persona-absolute persona-top-4 persona-z-50":p});f=r.button,b=r.wrapper,"top-right"===e?b.style.right="48px":m.appendChild(b)}m.appendChild(h),i.appendChild(m);let y=st("div");y.style.display="none";let v=st("span");return v.style.display="none",{header:i,iconHolder:y,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:b}},Bl={default:El,minimal:Ll},Rl=e=>Bl[e]??Bl.default,Pl=(e,t,r)=>{if(t?.render){let o=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),n=st("div");n.style.display="none";let a=st("span"),s=st("span"),i=st("button");i.style.display="none";let l=st("div");return l.style.display="none",{header:o,iconHolder:n,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let o=Rl(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&&(o.iconHolder.style.display="none"),!1===t.showTitle&&(o.headerTitle.style.display="none"),!1===t.showSubtitle&&(o.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(o.closeButton.style.display="none"),!1===t.showClearChat&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};function Nl(e,t){if(!t.defaultPrevented){for(let r of t.composedPath()){if(r===e)break;if(r instanceof Element&&r.matches('button, input, textarea, select, a[href], label, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="combobox"], [tabindex]'))return}(e.querySelector('[data-persona-composer-input][contenteditable="true"]')??e.querySelector("textarea[data-persona-composer-input]"))?.focus()}}let $l=e=>{let{config:t}=e,r=it("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=As(),n=it("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}=fs(t);s();let i=ws(t),l=Cs(t),d=Ss(t),c=ks(t),p=it("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(p),d&&(p.append(d.previewsContainer),n.append(d.input)),n.append(a);let u=it("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=it("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=it("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),n.append(u),n.addEventListener("click",e=>{Nl(n,e)}),"transient"===t?.statusIndicator?.mode?r.append(o,c,n):r.append(o,n,c),{footer:r,suggestions:o,composerForm:n,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}},Wl=e=>{let{config:t}=e,r=it("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=As(),n=ks(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=fs(t,{defaultMaxLines:5});s();let i=ws(t),l=Cs(t),d=Ss(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=it("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=it("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=it("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=>{Nl(c,e)}),d&&c.append(d.input),c.append(p,a,u);let h=it("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(o,c,n);let m=c;return{footer:r,suggestions:o,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:n,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 Hl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=it("span",{className:lt("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 o=Ee(e.iconName??"at-sign",13,"currentColor",2);if(o){let e=st("span","persona-mention-token-icon");e.appendChild(o),r.appendChild(e)}return r.appendChild(it("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let Dl="data-persona-user-collapse",Ol="data-persona-user-collapse-toggle",Fl=e=>!0===e.features?.userMessageCollapse?.enabled,zl=e=>{let t=e.features?.userMessageCollapse?.maxHeight;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:240},ql=e=>({showMoreLabel:e.copy?.showMoreLabel?.trim()||"Show more",showLessLabel:e.copy?.showLessLabel?.trim()||"Show less"}),jl=(e,t)=>e>t+48,_l=e=>`persona-user-collapse-${e}`,Ul=(e,t,r,o)=>{let{state:n}=o;t.setAttribute(Dl,n),t.style.setProperty("--persona-user-collapse-max-height",`${o.maxHeight}px`);let a=e.querySelector(`button[${Ol}]`);if("collapsed"!==n&&"expanded"!==n)return void a?.remove();a||(a=it("button",{className:"persona-user-collapse-toggle",attrs:{type:"button",id:`persona-user-collapse-toggle-${r}`,[Ol]:"","aria-controls":_l(r)}}),t.after(a));let s="expanded"===n;a.setAttribute("aria-expanded",s?"true":"false"),a.textContent=s?o.showLessLabel:o.showMoreLabel},Vl=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(":"))},Kl=(e={})=>{let t=e.loadingIndicator,r=e.future?.v5Defaults;if("label"===(t?.variant??(r?"label":"dots"))){let o=it("div",{className:"persona-loading-label",attrs:{role:"status"}});r&&!0!==t?.showBubble&&o.classList.add("persona-activity-row","persona-activity-header");let n=e.features?.toolCallDisplay,a=t?.iconVisibility??(!1!==n?.grouped&&"collapsible"===(n?.groupedMode??"collapsible")?n?.groupIconVisibility:void 0)??n?.iconVisibility,s=t?.iconName??"loader-circle";if("never"!==a&&(r||t?.iconName||t?.iconVisibility)){let e=Ee(s,16);e&&(e.classList.add("persona-activity-icon"),e.dataset.loadingIconAnimation=t?.iconAnimation??("loader-circle"===s?"spin":"none"),o.appendChild(e))}let i=it("span",{text:t?.label??"Thinking…"});return o.appendChild(i),je()?.applyLoadingLabel(i,e,"waiting"),o}let o=st("div","persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2");for(let e=0;e<3;e++){let t=st("div","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=250*e+"ms",o.appendChild(t)}let n=st("span","persona-sr-only");return n.textContent="Loading",o.appendChild(n),o},Ql=(e,t,r)=>t?.({config:r??{},streaming:!0,location:e,defaultRenderer:()=>Kl(r)})??Kl(r),Jl=(e,t,r="div")=>{let o=st(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return o.textContent=t.format?t.format(n):n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Gl=new Set(["persona-bg-persona-container","persona-text-persona-text","persona-border-persona-message-border"]),Yl=(e,t="bubble")=>{if("operator"===e){let e=Yl("assistant",t).flatMap(e=>"persona-message-assistant-bubble"===e?["persona-message-operator-bubble"]:Gl.has(e)?[]:[e]);return"flat"===t?[...e,"persona-px-3"]:e}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},Xl={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"}},Zl=(e,t,r="bubble",o)=>{if(!o)return;let n="user"===t||"operator"===t?t:"assistant",a=Xl[r??"bubble"]??Xl.bubble;o.padding&&(e.style.padding=`var(--persona-message-${n}-padding, ${a.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${n}-font-size, ${a.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${n}-line-height, ${a.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${n}-font-family, inherit)`)},ed=e=>`custom:${e}`,td=(e,t)=>"user"!==t&&"assistant"!==t&&"operator"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),rd=(e,t,r,o,n=!1)=>{let a=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&!0===o?.canRegenerate,c=(t.showEdit??!1)&&!0===o?.canEdit,p=(t.showQuote??!1)&&!1!==o?.canQuote,u=td(t,e.role);if(!(a||s||i||l||d||c||p||0!==u.length)){let t=st("div");return t.style.display="none",t.id=`actions-${e.id}`,t.setAttribute("data-actions-for",e.id),t}let h=t.visibility??(n&&o?.isLastAssistant?"always":"hover"),m=t.align??"right",g=t.layout??"pill-inside",f=st("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"}[m]} ${{"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[g]} ${"hover"===h?"persona-message-actions-hover":""} ${n?"persona-message-actions-adaptive":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let b=(e,t,r)=>{let o=pt({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return o.setAttribute("data-action",r),o};a&&f.appendChild(b("copy","Copy message","copy")),l&&f.appendChild(b("volume-2","Read aloud","read-aloud")),s&&f.appendChild(b("thumbs-up","Upvote","upvote")),i&&f.appendChild(b("thumbs-down","Downvote","downvote")),d&&f.appendChild(b("refresh-cw","Regenerate response","regenerate")),c&&f.appendChild(b("pencil","Edit message","edit")),p&&f.appendChild(b("quote","Quote message","quote"));for(let e of u)f.appendChild(b(e.iconName??"ellipsis",e.label,ed(e.id)));return f},od=(e,t,r,o,n,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=Yl(e.role,i),g=st("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id);let f="operator"===e.role;f&&!0===a?.widgetConfig?.future?.v5Defaults&&g.classList.add("persona-border"),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":f?"operator-message":"assistant-message");let b=_s(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message,v=a?.widgetConfig?.darkTheme?.components?.message;if(Zl(g,e.role,i,"user"===e.role?{...b.user,...y?.user,...v?.user}:f?{...b.operator,...y?.operator,...v?.operator}:{...b.assistant,...y?.assistant,...v?.assistant}),"flat"!==i||f?"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))"):f&&(g.style.backgroundColor="var(--persona-components-message-operator-background, var(--persona-container))",g.style.color="var(--persona-components-message-operator-text, var(--persona-text))"):(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"),f){let t=st("div","persona-message-author persona-text-xs persona-font-medium persona-mb-1"),r=a?.widgetConfig?.copy?.operatorLabel,o="string"==typeof r&&r.trim()?r.trim():"Human operator",n="string"==typeof e.author?.displayName?e.author.displayName.trim():"";t.textContent=n?`${n} · ${o}`:o,g.setAttribute("role","group"),g.setAttribute("aria-label",t.textContent),g.appendChild(t)}let w=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),x=e.content?.trim()??"",C=w.length>0&&"[Image]"===x,S=Pi(a?.widgetConfig?.features?.streamAnimation),k=a?.widgetConfig?.features?.streamAnimation?.plugins,A="assistant"===e.role&&"none"!==S.type?Di(S.type,k):null,M="assistant"===e.role&&!0===A?.isAnimating?.(e),I="assistant"===e.role&&null!==A&&(!!e.streaming||M);I&&A?.bubbleClass&&g.classList.add(A.bubbleClass);let T=document.createElement("div");T.classList.add("persona-message-content"),e.streaming&&T.classList.add("persona-content-streaming"),I&&A&&(A.containerClass&&T.classList.add(A.containerClass),T.style.setProperty("--persona-stream-step",`${S.speed}ms`),T.style.setProperty("--persona-stream-duration",`${S.duration}ms`));let E=I?Oi(e.content??"",S.buffer,A,e,!!e.streaming):e.content??"",L=()=>{let r=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return I&&"char"===A?.wrap?Vi(r,"char",e.id,{skipTags:A.skipTags}):I&&"word"===A?.wrap?Vi(r,"word",e.id,{skipTags:A.skipTags}):r},B=null;if(C?(B=document.createElement("div"),B.innerHTML=L(),B.style.display="none",T.appendChild(B)):e.contentSegments?.length?((e,t,r,o)=>{let n=Math.random().toString(36).slice(2,8),a=e=>`${n}:${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 o of e)"text"===o.kind?r.appendChild(document.createTextNode(o.text)):r.appendChild(Hl(o.ref,{readonly:!0,render:t}));return r})(t,o));e.innerHTML=s;let i=RegExp(`${n}:(\\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 n=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===n?.kind&&a.parentNode?.insertBefore(Hl(n.ref,{readonly:!0,render:o}),a),r=a}}})(T,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):T.innerHTML=L(),I&&A?.useCaret&&!C&&x){let e=Ki(),t=T.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=T.lastElementChild;t?t.appendChild(e):T.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=Jl(e,d,"span");t.classList.add("persona-timestamp-inline");let r=T.lastElementChild;r?r.appendChild(t):T.appendChild(t)}let R="user"===e.role?a?.userCollapse:void 0,P=R?((e,t)=>{let r=it("div",{className:"persona-user-collapse-region",attrs:{id:_l(e),[Dl]:"fit"}});return r.style.setProperty("--persona-user-collapse-max-height",`${t}px`),r})(e.id,R.maxHeight):null,N=P??g;if(w.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let o=st("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r?.())};return e.forEach((e,t)=>{let r=st("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;n+=1,r.addEventListener("error",()=>{a||(a=!0,n=Math.max(0,n-1),r.remove(),0===n&&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,o.appendChild(r)):(a=!0,n=Math.max(0,n-1),r.remove())}),0===n?(s(),null):o}catch{return r?.(),null}})(w,!C&&!!x,()=>{C&&B&&(B.style.display="")});e?N.appendChild(e):C&&B&&(B.style.display="")}let $=(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($.length>0){let e=(e=>{if(0===e.length)return null;try{let t=st("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!Vl(e.audio))return;let o=st("audio");o.controls=!0,o.preload="metadata",o.src=e.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})($);e&&N.appendChild(e)}let W=(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(W.length>0){let e=(e=>{if(0===e.length)return null;try{let t=st("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!Vl(e.video))return;let o=st("video");o.controls=!0,o.preload="metadata",o.src=e.video,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",o.style.maxHeight="320px",o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(W);e&&N.appendChild(e)}let H=(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(H.length>0){let e=(e=>{if(0===e.length)return null;try{let t=st("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!Vl(e.data))return;let o=st("a");o.href=e.data,o.download=e.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=e.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(H);e&&N.appendChild(e)}let D=e.contentSegments?.length?null:(e=>{if(!e||0===e.length)return null;let t=it("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=it("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),o=st("span","persona-mention-chip-icon"),n=Ee(r.iconName??"at-sign",13,"currentColor",2);n&&o.appendChild(n),e.appendChild(o),e.appendChild(it("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(D&&N.appendChild(D),N.appendChild(T),P&&R&&(g.appendChild(P),Ul(g,P,e.id,R)),p&&"below"===h&&e.createdAt){let t=Jl(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let O="assistant"===e.role?((e,t)=>{if(!e)return null;let r=(e=>{switch(e){case"max_tool_calls":return"Tool limit reached.";case"length":return"Output token limit reached.";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 o=t?.[e];return(void 0===o?r:o)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!E||!E.trim()),t="skeleton"===S.placeholder,r=t&&"line"===S.buffer&&e;if(e)r&&g.appendChild(Qi());else if(t)g.appendChild(Qi());else{let e=Ql("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}O&&e.stopReason&&!e.streaming&&(x||(T.style.display="none"),g.appendChild(((e,t)=>it("div",{className:"persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic",attrs:{"data-stop-reason":e,role:"note"},style:{opacity:"0.75"},text:t}))(e.stopReason,O)));let F=("assistant"===e.role||f)&&!e.streaming&&!e.voiceCaption&&(x.length>0||f&&td(o,"operator").length>0)&&!1!==o?.enabled,z=a?.actionEligibility,q="user"===e.role&&!e.streaming&&!1!==o?.enabled&&(!0===o?.showEdit&&!0===z?.canEdit||!0===o?.showQuote&&!0===z?.canQuote||td(o,"user").length>0);if((F||q)&&o){let t=rd(e,q?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:f?{...o,showCopy:x.length>0&&!1!==o.showCopy,showUpvote:!1,showDownvote:!1,showReadAloud:!1,showRegenerate:!1,showEdit:!1,showQuote:!1}:o,0,z,!0===a?.widgetConfig?.future?.v5Defaults&&void 0===o.visibility);g.appendChild(t)}if(!c||"system"===e.role)return g;let j=st("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),_=((e,t)=>{let r=st("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o="operator"===t,n="user"===t?e.userAvatar:o?e.operatorAvatar:e.assistantAvatar,a=()=>{r.classList.add(...o?["persona-bg-persona-container","persona-text-persona-text","persona-border"]:["user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white"])};if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=st("img");e.src=n,e.alt="user"===t?"User":o?"Operator":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,a();else r.textContent="user"===t?"U":o?"O":"A",a();return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?j.append(g,_):j.append(_,g),j},nd=(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)},ad=(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)}if(!r)return void(e.hidden=!0);e.appendChild(r),e.hidden=!1}else{if("lucide"===t.type){let r=Ee(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(it("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(it("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")},sd="data-persona-welcome-overlay",id="persona-welcome-overlay-active",ld=new WeakMap,dd=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(sd,""),e.classList.contains(id)||(ld.set(e,e.scrollTop),e.classList.add(id),e.scrollTop=0)},cd=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(sd),e.classList.contains(id)&&(e.classList.remove(id),e.scrollTop=ld.get(e)??e.scrollTop,ld.delete(e))},pd=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let o=r?.layout?.messages?.layout??"bubble",n=it("div",{className:Yl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===o?{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(it("div",{className:"persona-flex"},n)),e.hidden=!1},ud=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,hd=(e,t)=>{if(ud()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),o=e.parentElement,n=0,a=0,s=0;if(o){let t=getComputedStyle(o);n=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=o.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-o.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-n:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-n: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:-n+"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},md=(e,t,r,o=260)=>{if(t<=1||ud()||"function"!=typeof e.animate||!e.isConnected)return null;let n="drop"===r?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})},gd=new WeakSet,fd=(e,t)=>!!e&&void 0!==e[t],bd=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,o=e?.copy,n=!0===e?.future?.v5Defaults,a=r?.layout??(n?"centered":"top"),s=fd(r,"variant")?r.variant:!1===o?.showWelcomeCard?"none":"card",i="hero"!==s||n||void 0!==r?.layout?fd(r,"dismiss")?r.dismiss:n||"hero"===s?"on-first-message":"never":"on-first-message",l=[];for(let[e,t]of[["title","welcomeTitle"],["subtitle","welcomeSubtitle"],["variant","showWelcomeCard"]])fd(r,e)&&fd(o,t)&&l.push(`welcome.${e} and copy.${t} are both set; welcome.${e} wins. copy.${t} is deprecated.`);"hero"===s&&fd(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!n&&void 0===r?.layout&&"hero"===s&&fd(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??("none"!==s&&"centered"===a&&t?"center":"bottom"),c=null!==bi(r?.anchorComposerTop);return fd(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(fd(r,"anchorComposerTop")||fd(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{e&&!0===e.debug&&t.length&&!gd.has(e)&&(gd.add(e),t.forEach(e=>console.warn(`[persona] ${e}`)))})(e,l),{title:fd(r,"title")?r.title:o?.welcomeTitle??(n?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:fd(r,"subtitle")?r.subtitle:o?.welcomeSubtitle??(n?"":"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()||"24px"}},yd=e=>!(!e.content.trim()&&!e.contentParts?.some(e=>"text"!==e.type||e.text.trim())),vd=(e=[])=>e.some(e=>"user"===e.role||"operator"===e.role&&yd(e)||"assistant"===e.role&&(yd(e)||e.toolCall||e.tools?.length||e.reasoning||e.approval)),wd=e=>vd(e)?"active":"empty",xd=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!vd(t)),Cd="var(--persona-components-panel-height)",Sd=e=>{let t=rs(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===o?`max(200px, ${Cd})`:`max(200px, calc(${Cd} - ${o}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},kd=e=>{let t=rs(e);return t.launcherWidth||t.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?Sd(e).width:"100%"},Ad="16px",Md="10px",Id="14px",Td=e=>{let t=it("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":pl(e)}});return t.hidden=!0,t},Ed=(e,t)=>{let r=((e,t,r={})=>{let o=it("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let n=st("p","persona-welcome-kicker");n.hidden=!0;let a=st("h2","persona-welcome-title"),s=st("p","persona-welcome-subtitle"),i=it("div",{className:"persona-welcome-head-text"},n,a),l=it("div",{className:"persona-welcome-title-row"},o,i);return{host:it("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:o,kicker:n,title:a,subtitle:s,starterSuggestions:t}})(0,Td("starter"),{flatShadow:il(e)}),o=bd(e);ad(r,o),nd(t,r.host,xd(o,e?.initialMessages));let n=(()=>{let e=it("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return pd(n,o.message,e),{welcome:r,greetingHost:n}},Ld=(e,t)=>{let r=st("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 o=e=>{let t=e.launcher??{},o=il(e),n="circle"===Is(e);n?(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||o||n?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,o=Ee(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);o?(l.appendChild(o),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||n)c.style.display="none";else if(c.style.display=o?"none":"",c.innerHTML="",t.callToActionIconName){let o=Math.max((parseFloat(e)||24)-r,8),n=Ee(t.callToActionIconName,o,"currentColor",1.5);n?c.appendChild(n):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&fl[t.position]?fl[t.position]:fl["bottom-right"];r.className=o?"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}`,o||(r.style.zIndex=String(t.zIndex??1e5)),r.style.border=t.border??"1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",r.style.boxShadow=void 0===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))":""===t.shadow.trim()?"none":t.shadow,o?(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&&o(e),{element:r,update:o,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},Bd=new Set,Rd=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},Pd=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=(e=>{let t=e?.launcher?.enabled??!0,r=il(e);if(ll(e)){let t=e?.launcher?.composerBar??{},r=st("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??1e5);let o=st("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");o.style.width="100%",r.appendChild(o);let n=st("div","persona-widget-pill-root");return n.setAttribute("data-persona-composer-bar",""),n.dataset.state="collapsed",n.dataset.expandedSize=t.expandedSize??"anchored",n.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:o,pillRoot:n}}if(r){let e=st("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=st("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=st("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=st("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0");return t.style.width=kd(e),r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let o=e?.launcher??{},n=o.position&&fl[o.position]?fl[o.position]:fl["bottom-right"],a=st("div",`persona-widget-wrapper persona-fixed ${n} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=st("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=Sd(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(ll(e))return((e,t)=>{let r=st("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Cl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Ad,iconSize:Md});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=Sl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Ad,iconSize:Id});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=it("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=it("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}=Ed(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=st("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=Td("followUp"),b=gi(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 y=it("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"}}),v=Wl({config:e}),{root:w,textNode:x}=(()=>{let e=it("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=st("span","persona-pill-peek__icon"),r=ne(ye,16,"currentColor",1.5);r&&t.appendChild(r);let o=st("span","persona-pill-peek__text"),n=st("span","persona-pill-peek__caret"),a=ne(ue,16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}})();return r.append(i,n,l,y),s&&r.appendChild(s),{container:r,body:l,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:f,composerOverlay:y,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,welcomeHost:p,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:u,introSubtitle:h,closeButton:o,closeButtonWrapper:n,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:st("span"),headerTitle:st("span"),headerSubtitle:st("span"),header:i,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions,setSendButtonMode:v.setSendButtonMode,peekBanner:w,peekTextNode:x}})(e,t);let r=it("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,n=ss(e),a=o?Pl(e,o,{showClose:t}):Il({config:e,showClose:t}),s=it("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}=Ed(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=st("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=Td("followUp"),g=gi(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=$l({config:e}),b=!1!==e?.layout?.showFooter;n||(a.header.style.display="none"),Tl(r,a,e),r.append(s);let y=it("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(y),{container:r,body:s,messagesWrapper:h,starterSuggestions:u,transcriptSuggestions:m,composerOverlay:y,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:o,pillRoot:n},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}}},Nd=({config:e,plugins:t,onToggle:r})=>{let o=t.find(e=>e.renderLauncher);if(o?.renderLauncher){let t=o.renderLauncher({config:e,defaultRenderer:()=>Ld(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let n=((e,t)=>{let r=st("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let o=e??{},n=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(n?.frequency??"once")&&!1!==o.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(Bd.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(Rd(o),e&&h())},f=e=>{n&&!p&&g("user"===e&&d)},b=()=>{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"}))},y=()=>{g(h()),t()},v=e=>{e.stopPropagation(),g(h())},w=Ld(e,()=>{f("user"),t()}),x=()=>{m(),i?.removeEventListener("click",y),s?.removeEventListener("click",v),a?.remove(),a=null,i=null,s=null,d=!1},C=()=>{let e=o.launcher?.position??"bottom-right",t=fl[e]??fl["bottom-right"];a?(r.className=lt("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(o.launcher?.zIndex??1e5),w.element.style.position="static"):(r.className="persona-launcher-surface",r.removeAttribute("data-teaser"),r.style.zIndex="",w.element.style.position="")},S=e=>{let t=(e=>{let t=e?.launcher?.teaser;return t&&t.text&&!1!==e?.launcher?.enabled&&!il(e??{})?t:null})(e);n=t,t?(a||(i=it("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",y),s=it("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=it("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"),n&&a&&(p||c||u||((e,t)=>{if(Bd.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(Rd(o),h())||(m(),l=setTimeout(b,Math.max(0,n.delayMs??0))))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:b,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{o=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}})(e,r);return{instance:n,element:n.element}},$d=new WeakMap;async function Wd(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout($d.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=null;t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}$d.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o,$d.delete(e)},1800))}let{setLoader:Hd,load:Dd,provide:Od,getSync:Fd}=_({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),zd=Hd,qd=Dd,jd=Fd,{setLoader:_d,load:Ud}=_({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),Vd=_d,Kd=Ud;function Qd(e,t,r){return t?.trim()||(q(e,`artifact.${r}`)?`var(--persona-components-artifact-${r.split(".").join("-")})`:void 0)}function Jd(e){return!0===e?.features?.artifacts?.enabled}function Gd(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"),!Jd(t))return;let r=t.features?.artifacts?.layout,o=Qd(t,r?.paneBorder,"pane.border"),n=Qd(t,r?.paneBorderLeft,"pane.borderLeft");o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}let Yd=["panel","seamless","detached"];function Xd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Yd.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Zd(e){return!(!e||!Jd(e))&&"detached"===Xd(e)}function ec(e,t){if(!Jd(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.style.removeProperty("--persona-artifact-doc-toggle-active-color")}(e),void Gd(e,t);let r=t.features?.artifacts?.layout,o="detached"===Xd(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??o),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 n=Qd(t,r?.paneBackground,"pane.background");n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let a=Qd(t,r?.panePadding,"pane.padding");a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[Qd(t,r?.documentToolbarIconColor,"toolbar.iconColor"),"--persona-artifact-doc-toolbar-icon-color"],[Qd(t,r?.documentToolbarToggleActiveBackground,"toolbar.toggleActiveBackground"),"--persona-artifact-doc-toggle-active-bg"],[Qd(t,r?.documentToolbarToggleActiveBorderColor,"toolbar.toggleActiveBorderColor"),"--persona-artifact-doc-toggle-active-border"],[Qd(t,r?.documentToolbarToggleActiveColor,"toolbar.toggleActiveColor"),"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let o=t?.trim();o?e.style.setProperty(r,o):e.style.removeProperty(r)}Gd(e,t)}function tc(e,t){for(let t of Yd)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"),!Jd(t))return;let r=t.features?.artifacts?.layout,o=Xd(t);e.classList.add(`persona-artifact-appearance-${o}`);let n=Qd(t,r?.paneBorderRadius,"pane.borderRadius");n&&e.style.setProperty("--persona-artifact-pane-radius",n);let a=Qd(t,r?.paneShadow,"pane.shadow");a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=Qd(t,r?.chatShadow,"chat.shadow");s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}let rc=["__proto__","prototype","constructor"],oc=["collapsed","card","panel","inline"],nc=["markdown","component"],ac=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,sc=e=>"object"==typeof e&&!!e&&!Array.isArray(e),ic=e=>!rc.includes(e),lc=e=>oc.includes(e),dc=e=>Object.keys(e).length>0;function cc(e,t,r,o){e.push({path:t,code:r,message:o})}let pc="Ignored an unsupported value.",uc={kind:"mode"},hc={kind:"string",message:"Expected a CSS length string."},mc={kind:"boolean"},gc=(...e)=>({kind:"value",accepts:t=>e.includes(t)}),fc={paneWidth:hc,paneMaxWidth:hc,paneMinWidth:hc,expandedPanelWidth:hc,resizableMinWidth:hc,resizableMaxWidth:hc,expandLauncherPanelWhenOpen:mc,resizable:mc},bc={kind:"object",message:"Expected a preference object.",children:{showToolCalls:mc,showReasoning:mc,toolCallDisplay:{kind:"object",children:{layout:gc("row","card"),collapsedMode:gc("tool-call","tool-name","tool-preview"),groupedMode:gc("stack","summary","collapsible"),groupAppearance:gc("plain","inset"),groupSummary:gc("current-action","aggregate"),groupBoundary:gc("adjacent","iteration"),groupSummaryMaxItems:{kind:"value",accepts:e=>Number.isInteger(e)&&e>=0},loadingAnimation:gc("none","pulse","shimmer","shimmer-color","rainbow"),expandable:mc,grouped:mc}},reasoningDisplay:{kind:"object",children:{layout:gc("row","card"),appearance:gc("plain","inset","panel"),expandable:mc,activePreview:mc}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:uc,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:uc,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:nc,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:nc}}},filePreview:{kind:"object",children:{enabled:mc}},layout:{kind:"object",children:fc}}}}};function yc(e,t,r,o){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:cc(o,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:cc(o,r,"invalid_type",t.message);case"value":return t.accepts(e)?e:cc(o,r,"invalid_value",pc);case"mode":return lc(e)?Sn(e):cc(o,r,"invalid_value",pc);case"modeMap":{if(!sc(e))return cc(o,r,"invalid_type","Expected an object.");let n="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=n?t:kn(t);ic(t)&&(n?n.includes(t):ac.test(e))?lc(s)?a[e]=Sn(s):cc(o,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):cc(o,`${r}.${t}`,n?"unknown_key":"invalid_value",n?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return dc(a)?a:void 0}case"object":{if(t.bareMode&&lc(e))return Sn(e);if(!sc(e))return cc(o,r,"invalid_type",t.message??"Expected an object.");let n=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))ic(t)&&n.includes(t)||cc(o,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of n){let n=t.children[r],i=yc(e[r],n,a(r),o);if(n.deprecated&&void 0!==e[r]&&cc(o,a(r),"deprecated_key",n.deprecated),void 0===i)continue;let l=n.alias??r,d=s[l];s[l]=sc(d)&&sc(i)?{...d,...i}:i}return dc(s)?s:void 0}}}function vc(e){let t=[];return{preferences:(null===e?void 0:yc(e,bc,"",t))??{},issues:t}}function wc(e){if(Array.isArray(e))return e.map(wc);if(!sc(e))return e;let t={};for(let[r,o]of Object.entries(e))ic(r)&&void 0!==o&&(t[r]=wc(o));return t}function xc(e,t){let r=wc(e);for(let[e,o]of Object.entries(t)){if(!ic(e)||void 0===o)continue;let t=r[e];r[e]=sc(t)&&sc(o)?xc(t,o):wc(o)}return r}function Cc(e,t){if(void 0===t)return wc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return wc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byMediaType,...t.byMediaType},a={...o?{default:o}:{},...dc(n)?{byMediaType:n}:{}};return dc(a)?a:void 0}(r.files,t.files),s={...o?{default:o}:{},...dc(n)?{byKind:n}:{},...void 0===a?{}:{files:a}};return dc(s)?s:void 0}function Sc(e={},t){let r=function(e){let t,r={};for(let o of e){let e=vc(o).preferences;t=Cc(t,e.artifacts?.display),r=xc(r,e)}let o=r;return o.artifacts&&(void 0===t?delete o.artifacts.display:o.artifacts.display=t),o}(t),o={...e};for(let e of["showToolCalls","showReasoning"])void 0!==r[e]&&(o[e]=r[e]);for(let t of["toolCallDisplay","reasoningDisplay"])r[t]&&Object.assign(o,{[t]:{...e[t],...r[t]}});if(r.artifacts){let t=e.artifacts??{},n={...t};if(void 0!==r.artifacts.display){let e=Cc(t.display,r.artifacts.display);void 0!==e&&(n.display=e)}for(let e of["filePreview","layout"])r.artifacts[e]&&(n[e]={...t[e],...r.artifacts[e]});o.artifacts=n}return o}function kc(e){let t=e.preferences;return t&&dc(t)?{...e,features:Sc(e.features??{},[t])}:e}let{setLoader:Ac,load:Mc,provide:Ic,getSync:Tc}=_({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),Ec=Ac,Lc=Mc,Bc=Tc,Rc=new class{#e=new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.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.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Pc=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Nc=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),$c=(e,t,r)=>{if(!Pc(e)||!Pc(t)||Nc.has(r))return t;let o={...e};for(let n of Object.keys(t)){if(void 0===t[n]){delete o[n];continue}let a=r?`${r}.${n}`:n;o[n]=$c(e[n],t[n],a)}return o};function Wc(e,t){let r=f(cs),o=x(e,t,r),n=v(C($c(e,t,""),r,o),o);return D(n,((e,t)=>{if(t[$])return H(t);let r=new Set(H(e));for(let e of N){let o=b(t,e);"clear"===o&&r.delete(e),"explicit"===o&&r.add(e)}return[...r]})(e,t)),os(gs(n),((e,t)=>{let r=t[Za];if(r)return{...r};let o=rs(e);return es(t,"launcherWidth")&&(o.legacyLauncherWidth=void 0!==t.launcherWidth),es(t,"launcher")&&void 0===t.launcher?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(es(t.launcher,"width")&&(o.launcherWidth=void 0!==t.launcher?.width),es(t.launcher,"sidebarWidth")&&(o.sidebarWidth=void 0!==t.launcher?.sidebarWidth),es(t.launcher,"dock")&&void 0===t.launcher?.dock?o.dockWidth=!1:es(t.launcher?.dock,"width")&&(o.dockWidth=void 0!==t.launcher?.dock?.width),o)})(e,t))}let{setLoader:Hc,load:Dc,provide:Oc,getSync:Fc}=_({fallbackImport:()=>import("@runtypelabs/persona/config-diagnostics")}),zc=Hc,qc=Dc,jc=Fc,_c=[...R,"launcherWidth","suggestionChips","copy.welcomeTitle","copy.welcomeSubtitle","copy.showWelcomeCard","features.suggestReplies.enabled","features.suggestReplies.expose"],Uc=e=>{if(!e.debug)return;let t=jc();if(t)for(let r of e.current)r in t.LEGACY_MIGRATIONS&&(e.warned.has(r)||(console.warn(`[persona] ${r} is a supported legacy alias. Prefer ${t.LEGACY_MIGRATIONS[r]}. Compatibility behavior remains supported; clear the old field with an own undefined update when migrating.`),e.warned.add(r)));else qc().then(()=>Uc(e),()=>{})},Vc=e=>{let t={warned:new Set,current:new Set(_c.filter(t=>F(e,t))),debug:!0===e?.debug};return Uc(t),t},Kc=(e,t)=>{if((e=>void 0!==e[$])(t))e.current=new Set(_c.filter(e=>F(t,e)));else for(let r of _c){let o=b(t,r);"clear"===o&&e.current.delete(r),"explicit"===o&&e.current.add(r)}Object.prototype.hasOwnProperty.call(t,"debug")&&(e.debug=!0===t.debug),Uc(e)},Qc=({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 o=0;for(let e=r;e<t.length;e+=1){let n=t[e];if("{"===n&&(o+=1),"}"===n&&(--o,0===o))return t.slice(r,e+1)}return null})(t);if(!r)return null;let o=JSON.parse(r);if(!o||"object"!=typeof o||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Jc=e=>"string"==typeof e?e:null==e?"":String(e),Gc={message:e=>{if("message"===e.type)return{handled:!0,displayText:Jc(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,o=Jc(r.element);if(o&&t.document?.querySelector){let e=t.document.querySelector(o);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Jc(r.text)}}},Yc=e=>Array.isArray(e)?e.map(e=>String(e)):[],Xc=e=>{let t=new Set(Yc(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let o="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!o&&"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 n=o?e.parsers.reduce((e,t)=>e||t?.({text:o,message:r.message})||null,null):null;if(!n)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:n,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let o=e.captureResubmitGuard?.(),s=t(n,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{(!o||o())&&e.emit("action:resubmit",a)}});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(Yc(e.getSessionMetadata().processedActionMessageIds))}}},Zc=e=>e.map(e=>({...e,streaming:!1})),ep=e=>e.map(e=>({...e,status:"complete"})),tp=e=>`${e??"persona-"}state`,rp=(e=tp())=>{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 o=t();if(o)try{let t={...r,messages:r.messages?Zc(r.messages):void 0,artifacts:r.artifacts?ep(r.artifacts):void 0};o.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)}}}},op=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:np,load:ap}=_({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),sp=np,ip=ap,{setLoader:lp,load:dp,provide:cp,getSync:pp}=_({fallbackImport:()=>import("@runtypelabs/persona/history-shell")}),up=lp,hp=dp,mp=pp;function gp(){return null}let fp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function bp(e,t,r){let{onSubmit:o,onDismiss:n,title:a=("csat"===t?"How satisfied are you?":"How likely are you to recommend us?"),subtitle:s=("csat"===t?"Please rate your experience":"On a scale of 0 to 10"),commentPlaceholder:i=("csat"===t?"Share your thoughts (optional)...":"What could we do better? (optional)..."),submitText:l="Submit",skipText:d="Skip",showComment:c=!0}=e,p=document.createElement("div");p.className=`persona-feedback-container persona-feedback-${t}`,p.setAttribute("role","dialog"),p.setAttribute("aria-label","csat"===t?"Customer satisfaction feedback":"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=a,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=s,m.appendChild(f),h.appendChild(m);let{element:b,attentionTarget:y}=r(e=>{u=e});h.appendChild(b);let v=null;if(c){let e=document.createElement("div");e.className="persona-feedback-comment-container",v=document.createElement("textarea"),v.className="persona-feedback-comment",v.placeholder=i,v.rows=3,v.setAttribute("aria-label","Additional comments"),e.appendChild(v),h.appendChild(e)}let w=document.createElement("div");w.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",()=>{n?.(),p.remove()});let C=document.createElement("button");return C.type="button",C.className="persona-feedback-btn persona-feedback-btn-submit",C.textContent=l,C.addEventListener("click",async()=>{if(null===u)y.classList.add("persona-feedback-shake"),setTimeout(()=>y.classList.remove("persona-feedback-shake"),500);else{C.disabled=!0,C.textContent="Submitting...";try{let e=v?.value.trim()||void 0;await o(u,e),p.remove()}catch(e){C.disabled=!1,C.textContent=l,console.error(`[${t.toUpperCase()} Feedback] Failed to submit:`,e)}}}),w.appendChild(x),w.appendChild(C),h.appendChild(w),p.appendChild(h),p}function yp(e){return bp(e,"csat",t=>{let{ratingLabels:r=fp}=e,o=document.createElement("div");o.className="persona-feedback-rating persona-feedback-rating-csat",o.setAttribute("role","radiogroup"),o.setAttribute("aria-label","Satisfaction rating from 1 to 5");let n=[];for(let e=1;e<=5;e++){let a=document.createElement("button");a.type="button",a.className="persona-feedback-rating-btn persona-feedback-star-btn",a.setAttribute("role","radio"),a.setAttribute("aria-checked","false"),a.setAttribute("aria-label",`${e} star${e>1?"s":""}: ${r[e-1]}`),a.title=r[e-1],a.dataset.rating=String(e),a.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 ',a.addEventListener("click",()=>{t(e),n.forEach((t,r)=>{let o=r<e;t.classList.toggle("selected",o),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),n.push(a),o.appendChild(a)}return{element:o,attentionTarget:o}})}function vp(e){return bp(e,"nps",t=>{let{lowLabel:r="Not likely",highLabel:o="Very likely"}=e,n=document.createElement("div");n.className="persona-feedback-rating persona-feedback-rating-nps",n.setAttribute("role","radiogroup"),n.setAttribute("aria-label","Likelihood rating from 0 to 10");let a=document.createElement("div");a.className="persona-feedback-labels";let s=document.createElement("span");s.className="persona-feedback-label-low",s.textContent=r;let i=document.createElement("span");i.className="persona-feedback-label-high",i.textContent=o,a.appendChild(s),a.appendChild(i);let l=document.createElement("div");l.className="persona-feedback-numbers";let d=[];for(let e=0;e<=10;e++){let r=document.createElement("button");r.type="button",r.className="persona-feedback-rating-btn persona-feedback-number-btn",r.setAttribute("role","radio"),r.setAttribute("aria-checked","false"),r.setAttribute("aria-label",`Rating ${e} out of 10`),r.textContent=String(e),r.dataset.rating=String(e),e<=6?r.classList.add("persona-feedback-detractor"):e<=8?r.classList.add("persona-feedback-passive"):r.classList.add("persona-feedback-promoter"),r.addEventListener("click",()=>{t(e),d.forEach((t,r)=>{t.classList.toggle("selected",r===e),t.setAttribute("aria-checked",r===e?"true":"false")})}),d.push(r),l.appendChild(r)}return n.appendChild(a),n.appendChild(l),{element:n,attentionTarget:l}})}let wp="persona-chat-history",xp="data-persona-composer-reason",Cp="data-persona-composer-notice",Sp={"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 kp(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let Ap=e=>e&&"object"==typeof e?{...e}:{},Mp=e=>e.filter(e=>!(e=>!0===e.localOnly||"assistant"===e.role&&"string"==typeof e.id&&e.id.startsWith("reconnect-failed-"))(e)).map(e=>({...e,streaming:!1})),Ip=(e,t,r)=>{let o=e?.markdown?Cr(e.markdown):null,n=Rr(e?.sanitize);e?.postprocessMessage&&n&&void 0===e?.sanitize&&console.warn("[Persona] postprocessMessage HTML is sanitized: unsupported tags/attributes are stripped. Provide a custom sanitize function to allow them, or sanitize: false only for trusted HTML.");let a=!1,s=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!==at();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=n?n(t):t}else if(o){let e=wr(s,a.streaming),t=o(e);l=n&&d?n(t):t}else l=Ar(s);return l};return e=>{try{return s(e)}catch(t){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",t)),Ar(e.text??"")}}};function Tp(e){let t=st("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=Ee(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=st("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}let Ep=(e,t)=>{let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...o}:o}return r},Lp=(e,t,r)=>{if(null==e)throw 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);let n=e.getAttribute("data-persona-instance")||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;e.setAttribute("data-persona-instance",n),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let s,i,l=gs(t),u=(e=>{let t,r=0,o=!1,n=Promise.resolve(),a=()=>{},s=!0===e.inert,i=()=>{t?.remove(),t=void 0,e.removeAttribute("data-persona-preparing"),e.inert=s};return{get ready(){return n},prepare(s,l,d=!1){let c=++r;if(a(),!s.length){if(l(),c!==r)return;return i(),void(n=Promise.resolve())}!d&&!t&&(t=e.ownerDocument.createElement("style"),t.textContent="[data-persona-preparing],[data-persona-preparing] *{visibility:hidden!important}",e.append(t)),d||(e.setAttribute("data-persona-preparing",""),e.inert=!0);let p=new Promise((e,t)=>{a=()=>t(Error("Widget destroyed before ready"))});n=Promise.race([Promise.all(s),p]).then(()=>{if(o)throw Error("Widget destroyed before ready");if(c!==r||(l(),c!==r))return n;i()},e=>{if(!o&&c!==r)return n;throw e}),n.catch(()=>{})},destroy(){o=!0,++r,a(),i()}}})(e),h=r?.diagnostics??Vc(t),m=null,g=()=>{let t=je();if(s??=t?.createLoadingLabelLifecycle(e,()=>l),m)return m;let r=Y();return r&&t?(r.initActivityUi(Ee,t,j),i=r.createActivityLifecycle(e,()=>l,f,b,Ls,yd),m=r):null},f=new Set,b=new Set,y=new Map,v=new Map,w=new Map,x=new Set,C=e=>{if("user"===e.role&&Fl(l))return e.voiceProcessing&&x.add(e.id),{state:e.voiceProcessing?"live":x.has(e.id)?"settling":v.get(e.id)?w.get(e.id)?"expanded":"collapsed":"fit",maxHeight:zl(l),...ql(l)}},S=()=>{za({delayMs:l.tooltip?.delayMs??400,skipDelayMs:l.tooltip?.skipDelayMs??300})};S();let A=l.features;l=kc(l);let M,I,T=Rc.getForInstance(l.plugins),E=Mi(e),L=[],B=!1,R=(e=>{let t=new Map,r=!1,o=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return n=>{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(),n,t);return{get:e=>{let n=a(e),s=o();if(s)try{return s.getItem(n)}catch{r=!0}return t.get(n)??null},set:(e,n)=>{let s=a(e),i=o();if(i)try{return void i.setItem(s,n)}catch{r=!0}t.set(s,n)},remove:e=>{let n=a(e);t.delete(n);let s=o();if(s)try{s.removeItem(n)}catch{r=!0}}}}})(()=>l),P=null,N=null,$=null,W=!1,H=null,D=(e,t)=>{P=e,e.initApprovalUi({webMcpToolTitle:rr,popover:t,icons:{render:Ee,node:ne}});let r=e.createBuiltInApprovalPlugin(y);N=r.plugin,$=r.teardown},O=()=>{if(P)return P;let e=jd(),t=We();return e&&t?(D(e,t),e):(Promise.all([qd(),$e()]).then(([e,t])=>{W||P||(D(e,t),H?.())}).catch(()=>{}),null)},F=!1,z=!1,q=null,_=(e,t,r,o)=>{if(!e.querySelector("[data-tv-form]"))return;let n=Bc();n?n.enhanceWithForms(e,t,r,o):Lc().then(()=>{F||z||!q||(z=!0,q())}).catch(()=>{})},U=((e={instanceId:""})=>{let t=!1,r=new Map,o=(e,t)=>{r.get(e)?.delete(t)};return{on:(e,n)=>t?()=>{}:(r.has(e)||r.set(e,new Set),r.get(e).add(n),()=>o(e,n)),off:o,emit:(t,o)=>{r.get(t)?.forEach(t=>{try{t(o,e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})},dispose:()=>{t=!0,r.clear()}}})(Object.freeze({instanceId:n})),V=!1===l.persistState?null:l.storageAdapter??rp(tp("object"==typeof l.persistState?l.persistState.keyPrefix:void 0)),K=!!l.clientToken&&"function"!=typeof l.reconnectStream,Q={},J=null,G=new Promise(e=>{M=e}),X=()=>{},Z=new Promise(e=>{X=e}),ee=!1,te=e=>{if(l.onStateLoaded)try{let t=l.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(ee=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(V?.load)try{let e=V.load();if(e&&"function"==typeof e.then)J=e.then(e=>te(e??{messages:[],metadata:{}}));else{let t=te(e??{messages:[],metadata:{}});t.metadata&&(Q=Ap(t.metadata)),t.messages?.length&&(l={...l,initialMessages:t.messages}),t.artifacts?.length&&(l={...l,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),I=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(l.onStateLoaded)try{let e=te({messages:[],metadata:{}});e.messages?.length&&(l={...l,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}J||M();let re=()=>Q,oe=e=>{Q=e({...Q})??{},Gi()},ae=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Qc],se=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[Gc.message,Gc.messageAndClick],ie=Xc({parsers:ae,handlers:se,getSessionMetadata:re,updateSessionMetadata:oe,emit:U.emit,captureResubmitGuard:()=>{let e=xe;return()=>Se(e)},documentRef:typeof document<"u"?document:null});ie.syncFromMetadata();let le=l.launcher?.enabled??!0,ce=l.launcher?.autoExpand??!1,ue=l.autoFocusInput??!1,me=ce,ge=le,fe=l.layout?.header?.layout,be=!1,ye=()=>ll(l),ve=()=>le||ye(),we=!ye()&&(!le||ce),xe=0,Ce=!1,Se=e=>!Ce&&!$i&&e===xe,ke=()=>{xe++,Me=!1,null!==Ie&&clearTimeout(Ie),Ie=null},Ae=()=>{let e=xe;Se(e)&&setTimeout(()=>{Se(e)&&!ls.isStreaming()&&ls.continueConversation()},100)},Me=!1,Ie=null,Te=()=>{Se(xe)&&(Me=!0,Ie&&clearTimeout(Ie),Ie=setTimeout(()=>{Me&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4))},Le=Ip(l,ie,Te),Be=l.features?.showReasoning??!0,Re=l.features?.showToolCalls??!0,Pe=l.features?.showEventStreamToggle??!1,Ne=l.features?.scrollBehavior??{},He=()=>("object"==typeof l.persistState?l.persistState?.keyPrefix:void 0)??"persona-",De=`${He()}event-stream`,Oe=null,Fe=l.features?.eventStream?.maxEvents??2e3,ze=null,qe=null,_e=null,Ue=!1,Ve=null,Ke=!1,Qe=null,Ye=0,Xe=(e,t)=>{ze?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Ze=(e,t)=>{qe?.processEvent(e,t),ze?Xe(e,t):_e&&(_e.length>=Fe&&_e.shift(),_e.push({type:e,payload:t}))},et=()=>{!ze&&Pe&&(_e??=[],Kd().then(e=>{if(Ue||ze||!Pe)return;Oe=new e.EventStreamStore(De),ze=new e.EventStreamBuffer(Fe,Oe),qe??=new e.ThroughputTracker,Oe.open().then(()=>ze?.restore()).catch(e=>{l.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=_e??[];_e=null;for(let e of t)qe?.processEvent(e.type,e.payload),Xe(e.type,e.payload)}).catch(()=>{}))};Pe&&et();let tt=!1,rt=null,ot=()=>{},nt=()=>{},at=()=>{},it=()=>{},lt=()=>{},ct=e=>{U.emit("message:copy",e),ls?.isClientTokenMode()&&"operator"!==e.role&&ls.submitMessageFeedback(e.id,"copy").catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),l.messageActions?.onCopy?.(e)},pt=e=>{U.emit("message:feedback",e),ls?.isClientTokenMode()&&ls.submitMessageFeedback(e.messageId,e.type).catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),l.messageActions?.onFeedback?.(e)};l.statusIndicator;let ut=(e,t=l.statusIndicator??{})=>"idle"===e?t.idleText??dt.idle:"connecting"===e?t.connectingText??dt.connecting:"connected"===e?t.connectedText??dt.connected:"error"===e?t.errorText??dt.error:"paused"===e?t.pausedText??dt.paused:"resuming"===e?t.resumingText??dt.resuming:dt[e];function ht(e,t,r,o){if(!ye()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(ur(e,Rt,r),pr(e,r,o)),!e.hasAttribute(xp)&&!e.hasAttribute(Cp))if("idle"===o&&r.idleLink){e.textContent="";let o=document.createElement("a");o.href=r.idleLink,o.target="_blank",o.rel="noopener noreferrer",o.textContent=t,o.style.color="inherit",o.style.textDecoration="none",e.appendChild(o)}else e.textContent=t}let mt=Pd({config:l,showClose:ve()}),{wrapper:gt,panel:ft,pillRoot:vt}=mt.shell,wt=mt.panelElements,{container:xt,body:Ct,messagesWrapper:St,starterSuggestions:kt,transcriptSuggestions:At,suggestions:Mt,textarea:It,sendButton:Bt,composerForm:Rt,statusText:Pt,welcomeHost:Nt,welcomeIconHolder:$t,greetingHost:Dt,introKicker:Ot,introTitle:Ft,introSubtitle:zt,closeButton:Zt,iconHolder:er,headerTitle:tr,headerSubtitle:or,header:nr,footer:ar,actionsRow:sr}=wt,ir=wt.leftActions,lr=wt.rightActions,cr=wt.sendButtonWrapper,hr=wt.setSendButtonMode,mr=wt.micButton,gr=wt.micButtonWrapper,fr=wt.attachmentButton,br=wt.attachmentButtonWrapper,yr=wt.attachmentInput,vr=wt.attachmentPreviewsContainer;xt.classList.add("persona-relative"),Ct.classList.add("persona-relative");let wr=()=>Ne.mode??"anchor-top",xr=()=>"follow"===wr()||"anchor-top"===wr()&&ni,Cr=()=>Ne.anchorTopOffset??16,Sr=()=>!0===Ne.pauseOnInteraction,kr=()=>!1!==Ne.showActivityWhilePinned,Mr=()=>!0===Ne.announce,Ir=()=>Ne.scrollbar??"on-scroll",Tr=Xt(Ee,"transcript",Ct),Er=Tr.element;xt.appendChild(Er);let Lr=()=>Ct.parentElement??xt,Br=st("div","persona-panel-suggestions");Br.setAttribute("data-persona-panel-suggestions",""),Br.hidden=!0,xt.appendChild(Br);let Rr=st("div","persona-panel-suggestions-fade");Rr.setAttribute("aria-hidden","true"),Rr.hidden=!0,xt.appendChild(Rr);let Pr=st("div","persona-stream-anchor-spacer");Pr.setAttribute("aria-hidden","true"),Pr.setAttribute("data-persona-anchor-spacer",""),Pr.style.flexShrink="0",Pr.style.pointerEvents="none",Pr.style.height="0px",Pr.style.display="none",Ct.appendChild(Pr);let Nr=st("div","persona-sr-only");Nr.setAttribute("aria-live","polite"),Nr.setAttribute("aria-atomic","true"),Nr.setAttribute("role","status"),Nr.setAttribute("data-persona-live-region",""),Object.assign(Nr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),xt.appendChild(Nr);let $r=null,Hr=null,Dr=e=>{Mr()&&e&&(Hr=e,null===$r&&($r=setTimeout(()=>{$r=null,Hr&&Mr()&&(Nr.textContent=Hr),Hr=null},400)))},Or=()=>{let t=e.ownerDocument.defaultView??window;return(l.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(l.launcher?.mobileBreakpoint??640)&&(le||il(l))||!0===l.launcher?.fullHeight&&!l.launcher.sidebarMode&&!il(l)},Fr=()=>bd(l,Or()),zr="empty",jr=0,_r=()=>jr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Ur=(e,t=Ct)=>{let r=0,o=e;for(;o&&o!==t;)r+=o.offsetTop,o=o.offsetParent;return r},Vr=()=>{let e="none"===ar.style.display,t=Lr();if(ye()){let r=e||!ar.offsetHeight?0:Math.max(0,t.getBoundingClientRect().bottom-ar.getBoundingClientRect().top),o=Br.hidden?0:Math.max(0,t.getBoundingClientRect().bottom-Br.getBoundingClientRect().top);return void(Er.style.bottom=`${Math.max(r,o)+16}px`)}let r=e?0:ar.offsetHeight;if(r>0&&"overlay"===fi(l,ye())){let e=1/0;for(let r of ar.querySelectorAll(":scope > *, [data-persona-composer-header] > *"))!r.hidden&&r.offsetHeight&&"hidden"!==getComputedStyle(r).visibility&&(e=Math.min(e,Ur(r,t)));e<1/0&&(r-=e-Ur(ar,t))}Er.style.bottom=`${r+(e?0:_r())+16}px`};Vr();let Kr=()=>{if(!ye())return;let e="none"===ar.style.display?0:ar.offsetHeight;e>0?gt.style.setProperty("--persona-measured-pill-area-height",`${e+8}px`):gt.style.removeProperty("--persona-measured-pill-area-height"),gt.style.setProperty("--persona-pill-bottom",l.launcher?.composerBar?.bottomOffset??"16px")},Qr=()=>{Eo||(ar.style.marginBottom=jr>0?`${jr}px`:"")},Jr=()=>{let t=fi(l,ye()),r=Fr();e.setAttribute("data-persona-welcome-fullscreen",String(Or())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",l.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let o="none"===ar.style.display?0:ar.offsetHeight,n="center"===r.anchor&&"empty"===zr?bi(r.anchorComposerTop)??bi("44%"):null,a=null!==n&&"centered"===r.layout&&void 0===l.welcome?.anchor&&void 0===l.welcome?.anchorComposerTop,s=a?getComputedStyle(Ct):null,i=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,d=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,c=Math.max(0,(parseFloat(s?.paddingBottom??"")||0)-("overlay"===t?i+d:0)),p=a?Ct.getBoundingClientRect().top-xt.getBoundingClientRect().top:0,u=!a||Nt.hidden?0:(Nt.querySelector("[data-persona-welcome-plugin]")??Nt).offsetHeight,h=null===n||ye()?0:a?Math.max(0,Math.round((xt.clientHeight-p-u-c-o)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:xt.clientHeight,footerHeight:o,fraction:n});e.style.setProperty("--persona-composer-overlay-height",`${o}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),jr="block"===t?h:0,Qr(),Kr(),Vr(),Fa()};Tr.update(l,!1);let Gr=null,Yr=null,Xr=ea();Xr.subscribe(e=>{try{xt.dispatchEvent(new CustomEvent("persona:composer:state",{detail:{...e,instanceId:n},bubbles:!0,composed:!0}))}catch{}});let Zr=()=>{Xr.setText(It?.value??"")},eo=()=>{Xr.setMentionRefs(Yr?.getMentionRefs()??[])},to=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}),ro=()=>({allowedTypes:l.attachments?.allowedTypes,maxFileSize:l.attachments?.maxFileSize,maxFiles:l.attachments?.maxFiles,adapter:l.attachments?.adapter,onFileRejected:l.attachments?.onFileRejected,instanceId:n,widgetConfig:l,preview:l.attachments?.preview,renderAttachmentPreview:oo}),oo=e=>{for(let t of Rc.getForInstance(l.plugins))try{let r=t.renderAttachmentPreview?.(e);if(r)return r}catch(e){console.error(`[AgentWidget] plugin ${t.id} attachment preview failed:`,e)}return null},no=()=>{let e=p.fromConfig(l.attachments,t=>{Gr===e&&ao(t)});return e.updateConfig(ro()),e},ao=e=>{let t=Object.freeze(e.map(to));Xr.setAttachments(t);try{l.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}ic()};Xr.setSelectedModelId(l.composer?.selectedModelId);let so=()=>l.composer?.modes??[],io=()=>function(e,t,r=!1){return e?.length?e.filter(e=>!(function(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}(e.groupId,t)||function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)||r&&"overflow"!==e.presentation&&"auto"!==t?.find(t=>t.id===e.groupId)?.chipVisibility)):[]}(so(),l.composer?.modeGroups,!!l.future?.v5Defaults);{let e=fa(l.composer?.defaultActiveModeIds??[],so());e.length&&Xr.setActiveModeIds(e)}function lo(e){if(Xr.getState().selectedModelId!==e){Xr.setSelectedModelId(e),uo?.repaint();try{l.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function co(e){Xr.setActiveModeIds(e),ho?.render(e,io()),uo?.repaint(),_o?.resolve(),Dc(),en()}function po(t){let r=e.getRootNode(),o=r instanceof ShadowRoot?r.activeElement:e.ownerDocument.activeElement,n=(e=>`core:mode:${e}`)(t),a=_o?.getOverflowMenu(),s=o&&(o.closest("[data-persona-composer-action]")?.getAttribute("data-persona-composer-action")===n||a?.trigger.contains(o));if(co(ga(Xr.getState().activeModeIds,t,so(),l.composer?.modeGroups)),s&&!o.isConnected){let t=Array.from(e.querySelectorAll("[data-persona-composer-action]")).find(e=>e.getAttribute("data-persona-composer-action")===n)?.querySelector("button")??_o?.getOverflowMenu()?.triggerButton;t?.isConnected&&t.focus()}}let uo=null,ho=null,mo=null;function go(e){Xr.setQuote(e),mo?.render(Xr.getState().quote),en(),al()}let fo=!1;function bo(){let e=l.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?l.clientToken?"interrupt":(!fo&&!0===l.debug&&(fo=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let vo=null;function xo(e){Xr.setPendingSubmission(e),vo?.render(Xr.getState().pendingSubmission),en()}let Co=null,So=T.find(e=>e.renderHeader);if(So?.renderHeader){let e=So.renderHeader({config:l,defaultRenderer:()=>{let e=Il({config:l,showClose:ve()});return Tl(xt,e,l),e.header},onClose:()=>rc(!1,"user")});e&&nr&&(nr.replaceWith(e),nr=e,mt.header.element=e)}let ko=()=>{Ve&&(Ct.style.display="none",ar.parentNode?.insertBefore(Ve.element,ar),Ve.update())},Ao=()=>{if(!ze)return void et();if(td.cancel(),Ke=!0,Ve?ko():Kd().then(e=>{!Ve&&Ke&&ze&&(Ve=e.createEventStreamView({scroll:{createScrollToLatest:Yt,createScrollToBottomControl:Xt},buffer:ze,getFullHistory:()=>ze.getAllFromStore(),onClose:()=>Mo(),config:l,plugins:T,getThroughput:()=>qe?.getMetric()??{status:"idle"},renderIconByName:Ee,getResponseActive:Sl,getConfig:()=>l,getViewVisible:()=>Ke}),ko())}).catch(()=>{Mo()}),Io){Io.style.boxShadow=`inset 0 0 0 1.5px ${kl.actionIconColor}`;let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Io.classList.add(e))}let e=()=>{if(!Ke)return;let t=Date.now();t-Ye>=200&&(Ve?.update(),Ye=t),Qe=requestAnimationFrame(e)};Ye=0,Qe=requestAnimationFrame(e),Ql(),U.emit("eventStream:opened",{timestamp:Date.now()})},Mo=()=>{if(Ke){if(Ke=!1,Ve&&(Ve.update(),Ve.element.remove()),Ct.style.display="",Io){Io.style.boxShadow="";let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Io.classList.remove(e))}null!==Qe&&(cancelAnimationFrame(Qe),Qe=null),Ql(),U.emit("eventStream:closed",{timestamp:Date.now()})}},Io=null;if(Pe){let e=l.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:"");Io=st("button",t),Io.style.width="28px",Io.style.height="28px",Io.style.color=kl.actionIconColor,Io.type="button",Io.setAttribute("aria-label","Event Stream"),Io.title="Event Stream";let r=ne(de,"18px","currentColor",1.5);r&&Io.appendChild(r);let o=wt.clearChatButtonWrapper,n=wt.closeButtonWrapper,a=o||n;a&&a.parentNode===nr?nr.insertBefore(Io,a):nr.appendChild(Io),Io.addEventListener("click",()=>{Ke?Mo():Ao()})}let To=e=>{let t=l.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=st("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=st("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??yn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},Eo=!1,Lo=e=>{let t=T.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=l.composer,o=!!B&&ls.isStreaming();return t.renderComposer({config:l,defaultRenderer:e,requestRender:()=>$h(),storage:R(t.id),onSubmit:e=>{ls&&!ls.isStreaming()&&fu(e.trim(),{consumeDraft:!1})},streaming:o,disabled:o,openAttachmentPicker:()=>{nc()||yr?.click()},models:r?.models,selectedModelId:Xr.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>lo(e),onVoiceToggle:!0===l.voiceRecognition?.enabled?()=>{Co?.()}:void 0})},Bo=Lo(()=>$l({config:l}).footer);Bo&&(mt.replaceComposer(Bo),ar=mt.composer.footer,Eo=!0);let No=null;function $o(){let e=It;if(!e)return;let t=l.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");ka(e,t),r&&e.setAttribute("aria-label",r),Sa(e,{submitKey:l.composer?.submitKey,insertNewlineOnTouchEnter:l.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(e)}),wa(e,va(l.composer?.maxLines,ye()?5:3))}let Wo=e=>{No=oa(e,{debug:!0===l.debug}),No&&(e=>{Rt=e.form,It=e.input,cr=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(Bt=e.sendButton),e.micButton&&(mr=e.micButton,gr=e.micButton.parentElement),e.found.status&&(Pt=e.found.status),e.found.suggestions&&(Mt=e.found.suggestions),e.attachmentButton&&(fr=e.attachmentButton,br=e.attachmentButton.parentElement),yr=e.attachmentInput??null,vr=e.attachmentPreviews??null,e.found.actionsRow&&(sr=e.found.actionsRow),ir=e.found.actionsStart,lr=e.found.actionsEnd})(No),$o()};To(ar),Wo(ar),Zr();let Do=gi(l,ye());Do&&(St.style.maxWidth=Do,St.style.marginLeft="auto",St.style.marginRight="auto",St.style.width="100%",Dt.style.maxWidth=Do,Dt.style.marginLeft="auto",Dt.style.marginRight="auto",Dt.style.width="100%",kt.style.maxWidth=Do,At.style.maxWidth=Do,At.style.marginLeft="auto",At.style.marginRight="auto",At.style.width="100%");let Fo=()=>{let e=gi(l,ye());if(e&&!ye())for(let t of[Rt,Mt,vr,Pt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};Fo();let qo=()=>{l.attachments?.enabled&&yr&&vr&&(Gr?Gr.remountPreviews(vr):(Gr=no(),Gr.setPreviewsContainer(vr)),No?.addListener(yr,"change",e=>{let t=e.target;Gr?.handleFileSelect(t.files),t.value=""}),xt.querySelector(".persona-attachment-drop-overlay")||xt.appendChild(Tp(l.attachments.dropOverlay)))};qo();let jo=()=>{if(!l.contextMentions?.enabled||!It)return;let e=Ht();if(!e){let e=It;return void Wt().then(()=>{!Yr&&It===e&&e.isConnected&&(jo(),_o?.resolve())},()=>{})}let t=No?.header??null,r=t?ca(t):void 0;if(Yr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Ra,loadContextMentionsInline:Wa,renderLucideIcon:Ee,createMentionButton:Ms},config:l,textarea:It,anchor:Rt??It,getMessages:()=>ls.getMessages(),liveRegionHost:xt,chipRow:r}),Yr&&!r){let e=It;e.parentElement?.insertBefore(Yr.contextRow,e)}};jo();let _o=null,Uo={getState:()=>Xr.getState(),getValue:()=>It?.value??"",setValue:e=>{It&&(It.value=e,It.dispatchEvent(new Event("input",{bubbles:!0})),Zr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(No?.form??null)},openAttachmentPicker:()=>{nc()||yr?.click()},toggleVoice:()=>{Co?.()},requestRender:()=>_o?.resolve()},Vo=()=>{let e=[];return(Yr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),br&&e.push({id:"core:attachment",placement:"start",order:200,element:br}),gr&&e.push({id:"core:mic",placement:"end",order:800,element:gr}),cr&&e.push({id:"core:send",placement:"end",order:1e3,element:cr}),e},Ko=!1,Qo=()=>{if(Ko)return;let e=We();e&&(_o?.destroy(),_o=e.createComposerActionRenderer({deps:{renderLucideIcon:Ee,attachTooltip:Qa,hideTooltipFor:ja},getBindings:()=>No,collect:()=>({builtIns:Vo(),configActions:[...(uo??=We().createComposerCoreControls({getConfig:()=>l,getState:()=>Xr.getState(),getModes:so,getChipModes:io,hasComposerPlugin:()=>T.some(e=>e.renderComposer),renderIcon:Ee,onModelChange:lo,onModeChange:po}),uo.collect()),...l.composer?.actions??[]],plugins:T,contributionContext:{config:l,getState:()=>Xr.getState(),requestRender:()=>_o?.resolve()},debug:!0===l.debug}),actionContext:Uo,getState:()=>Xr.getState(),getOverflow:()=>l.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),_o.resolve())};Qo();let Jo=()=>{if(ho?.destroy(),ho=null,!io().length)return;let e=No?.header;if(!e)return;let t=We();t&&(ho=t.createComposerModeChipRow({renderIcon:Ee,row:ca(e),onRemove:e=>po(e),initialIds:Xr.getState().activeModeIds}),ho.render(Xr.getState().activeModeIds,io()))};Jo();let Go=()=>{mo?.destroy(),mo=null,vo?.destroy(),vo=null;let e=No?.header;e&&(mo=pa({onDismiss:()=>go(void 0)}),e.appendChild(mo.element),mo.render(Xr.getState().quote),"defer-one"===bo()&&(vo=ua({onEdit:()=>function(){let e=Xr.getState().pendingSubmission;e&&(xo(void 0),It&&(It.value=e.text,It.dispatchEvent(new Event("input",{bubbles:!0})),Zr()),e.options.selectedModelId&&(Xr.setSelectedModelId(e.options.selectedModelId),uo?.repaint()),e.options.activeModeIds?.length&&co(e.options.activeModeIds),e.options.quote&&go(e.options.quote),It?.focus())}(),onRemove:()=>xo(void 0)}),e.appendChild(vo.element),vo.render(Xr.getState().pendingSubmission)))};Go();let Yo=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),Xo=la({getSurface:()=>ye()||!No?null:{form:No.form,input:No.input,start:No.actionsStart,end:No.actionsEnd,resizeInput:"single-row"===l.composer?.layout},onMeasure:()=>en()}),Zo=()=>{let e=No?.header?.querySelector(da);if(e)return e.childElementCount>0;let t=Xr.getState();return t.mentionRefs.length>0||fa(t.activeModeIds,io()).length>0};function en(){let e=Xr.getState(),t=Xo.measure(),r="single-row"!==l.composer?.layout&&"single-row"!==l.composer?.attachmentLayout||t,o=Xo.toolbarCrowded();ar.hasAttribute("data-persona-composer-crowded")!==o&&ar.toggleAttribute("data-persona-composer-crowded",o),ar.hasAttribute("data-persona-composer-fit")!==r&&ar.toggleAttribute("data-persona-composer-fit",r);let n=Yo.observe(r&&function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),o=Number.parseFloat(r.lineHeight),n=Number.parseFloat(r.fontSize),a=Number.isFinite(o)&&o>0?o:Number.isFinite(n)&&n>0?1.4*n:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0),i=e.style.height,l=e.style.getPropertyPriority("height"),d="TEXTAREA"===e.tagName;d&&(e.style.height="auto");let c=e.scrollHeight-s;return d&&e.style.setProperty("height",i,l),c>1.5*a}(It),e.text);ar.toggleAttribute("data-persona-has-attachments",e.attachments.length>0),ar.toggleAttribute("data-persona-attachment-row-compact",ba({text:e.text,wrapped:n,hasAttachments:!1,hasChips:Zo(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}));let a=ba({text:e.text,wrapped:n,hasAttachments:e.attachments.length>0,hasChips:Zo(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission});ar.hasAttribute("data-persona-composer-compact")!==a&&ar.toggleAttribute("data-persona-composer-compact",a);let s=!a||!r||"single-row"!==l.composer?.layout;ar.hasAttribute("data-persona-composer-expanded")!==s&&ar.toggleAttribute("data-persona-composer-expanded",s)}function tn(){"single-row"!==l.composer?.layout||ye()?ar.removeAttribute("data-persona-composer-layout"):ar.setAttribute("data-persona-composer-layout","single-row"),l.composer?.attachmentLayout?ar.setAttribute("data-persona-attachment-layout",l.composer.attachmentLayout):ar.removeAttribute("data-persona-attachment-layout"),en()}tn(),Xr.subscribe(()=>{_o?.sync(),ic(),lc(),en(),al()}),lc();let rn=!1,on=e=>{if(rn||!0!==l.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(rn=!0,console.warn(`[persona] Ignoring deprecated layout.slots.${t.join(" / layout.slots.")}. Use message render hooks or the renderComposer plugin hook.`))},nn=new Map,an=new Map,sn=e=>{let t=nn.get(e);if(t)return t.element;let r=null;if("body-top"===e&&(r=Ct.querySelector("[data-persona-intro-card]")),"messages"===e)return St;if("composer"===e)return Rt;if("footer-top"===e&&(r=Mt),"footer-bottom"===e&&(r=Pt),r?.parentNode){let t=document.createComment(`persona:${e}`);r.before(t),nn.set(e,{anchor:t,element:r})}return r},ln=function(e){let t=new Map,r=(t,r)=>({slot:t,signal:r.abort.signal,config:e.config(),defaultContent:()=>e.defaultContent(t)}),o=(r,o)=>{t.delete(r),o.abort.abort();try{o.result.destroy?.()}catch(e){console.error(`[AgentWidget] Error destroying slot "${r}":`,e)}e.remove(r,o.result.element)};return{update(){let n=e.config().layout?.slots??{};for(let[e,r]of t)n[e]!==r.renderer&&o(e,r);for(let[a,s]of Object.entries(n)){if(!s)continue;let n=t.get(a);try{if(n){if(n.result.update){let t=n.result.update(r(a,n));void 0!==t&&t!==n.result.element&&(e.remove(a,n.result.element),n.result.element=t)}}else{n={renderer:s,abort:new AbortController,result:{element:null}},t.set(a,n);let e=s(r(a,n));n.result=null===e||"nodeType"in e?{element:e}:e}n.result.element&&e.mount(a,n.result.element)}catch(e){n&&o(a,n),console.error(`[AgentWidget] Error rendering slot "${a}":`,e)}}},remount(){for(let[r,o]of t)o.result.element&&e.mount(r,o.result.element)},detach(r){for(let o of r){let r=t.get(o);r&&e.remove(o,r.result.element)}},destroy(){for(let[e,r]of t)o(e,r)}}}({config:()=>l,defaultContent:sn,remove(e,t){if("messages"===e||"composer"===e)return;t?.remove(),an.get(e)?.remove(),an.delete(e);let r=nn.get(e);r&&(r.anchor.replaceWith(r.element),nn.delete(e))},mount(e,t){if(!("messages"===e||"composer"===e||t.parentNode&>.contains(t))){if("body-top"===e||"footer-top"===e||"footer-bottom"===e){let r=sn(e),o=nn.get(e);if(r&&o?.anchor.parentNode)return o.anchor.after(t),void(r!==t&&!t.contains(r)&&r.remove())}switch(e){case"header-left":nr.prepend(t);break;case"header-right":nr.append(t);break;case"header-center":{let e=nr.querySelector(".persona-flex-col");e?e.after(t):nr.append(t);break}case"body-top":Ct.prepend(t);break;case"body-bottom":Ct.append(t);break;case"footer-top":ar.prepend(t);break;case"footer-bottom":ar.append(t);break;case"transcript-top":{let r=document.createElement("div");r.setAttribute("data-persona-layout-slot",e),r.style.cssText="width:100%;min-width:0;max-width:var(--persona-content-max-width, 100%);margin-inline:auto;flex-shrink:0",r.append(t),St.before(r),an.set(e,r);break}case"composer-start":case"composer-end":case"composer-before-send":{let r="composer-start"===e?ir:"composer-end"===e?lr:cr?.parentElement;if(!r)break;let o=document.createElement("div");o.setAttribute("data-persona-layout-slot",e),o.style.cssText="display:flex;align-items:center;min-width:0;max-width:100%",o.append(t),"composer-start"===e?r.prepend(o):"composer-before-send"===e?cr?.before(o):r.append(o),an.set(e,o);break}}}}});on(l.layout?.slots??{}),ln.update();let dn=t=>{if(!l.onLinkClick||t.defaultPrevented||0!==t.button||t.ctrlKey||t.metaKey||t.shiftKey||t.altKey)return;let r=t.target;if(!(r instanceof Element))return;let o=r.closest("a[href]");if(!o||!e.contains(o)||o.hasAttribute("download")||o.closest("[data-persona-root]")!==e)return;let n=o.getAttribute("target")??o.ownerDocument.querySelector("base[target]")?.getAttribute("target");if((!n||"_self"===n.toLowerCase())&&/^(https?:|mailto:|tel:)/i.test(o.href))try{l.onLinkClick({url:o.href,anchor:o,originalEvent:t,preventDefault:()=>t.preventDefault()})}catch(e){console.error("[AgentWidget] onLinkClick failed:",e)}};e.addEventListener("click",dn),St.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(),Wd(r))}),St.addEventListener("click",e=>{let t=e.target;t instanceof Element&&t.closest('.persona-approval-head[data-action="toggle-params"]')&&(ci(),Jl())},{capture:!0});let cn=(e,t)=>{let r=e.querySelector(`[${Dl}]`),o=e.getAttribute("data-message-id");r&&o&&(ci(),Jl(),w.set(o,t),Cd(e,r,o,{state:t?"expanded":"collapsed",maxHeight:zl(l),...ql(l)},"toggle"))};St.addEventListener("click",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest(`button[${Ol}]`),o=r?.closest("[data-message-id]");r&&o&&(e.preventDefault(),cn(o,"true"!==r.getAttribute("aria-expanded")))}),St.addEventListener("focusin",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest(`[${Dl}="collapsed"]`)?.closest("[data-message-id]");r&&cn(r,!0)});let pn=e=>{let t=e.target.closest('button[data-expand-header="true"]');t&&un(t)},un=e=>{let t=e.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!t)return;let r=t.getAttribute("data-message-id");if(!r)return;ci(),Jl();let o=Zs;o&&vl();let n=o&&m?.holdScroll(t,Ct,o,gd,ud,hi,()=>Zs===o),a=e.getAttribute("data-bubble-type");if(t.classList.contains("persona-activity-row")){i?.manual(r);let e=t.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&i?.manual(e.dataset.messageId)}if("reasoning"===a||"tool"===a){let e="reasoning"===a,o=e?b:f;o.has(r)?o.delete(r):o.add(r),m&&(e?m.updateReasoningBubbleUI:m.updateToolBubbleUI)(r,t,o,l)}else if("approval"===a&&P){let e="expanded"===((!1===l.approval?void 0:l.approval)?.detailsDisplay??"collapsed"),o=y.get(r)??e;y.set(r,!o),P.updateApprovalDetailsUI(r,t,l,y)}n?.(),Ls.delete(r)};St.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),pn(e))}),St.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&pn(e)}),St.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),pn(e))}),St.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=St.getRootNode(),o="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!o||o.isCollapsed)return;let n=o.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(n);a&&a!==n&&(t.setData("text/plain",a),e.preventDefault())});let hn,mn=new Map,gn=new Map,bn=0,vn=()=>{St.querySelectorAll(".persona-tool-bubble[data-tool-call-id]").forEach(e=>{e.toggleAttribute("data-persona-revealed",gn.has(e.dataset.messageId))})},wn=()=>{window.clearTimeout(hn),hn=void 0,gn.forEach(e=>window.clearTimeout(e)),gn.clear(),vn()},xn=null,Cn="idle",Sn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},kn=()=>{St.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:o}=Sn[t];e.setAttribute("aria-label",o),e.title=o,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 n=Ee(r,14,"currentColor",2);n&&(e.innerHTML="",e.appendChild(n))})(e,t&&t===xn?Cn:"idle")})};St.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 n=t.getAttribute("data-action");if("copy"===n){let e=ls.getMessages().find(e=>e.id===o);if(e&&ct){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=ne(pe,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=ne(he,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),ct(e)}}else if("read-aloud"===n)ls.toggleReadAloud(o);else if("upvote"===n||"downvote"===n){let e="upvote"===n?"thumbs-up":"thumbs-down";if((mn.get(o)??null)===n){mn.delete(o),t.classList.remove("persona-message-action-active");let r=Ee(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let a="upvote"===n?"downvote":"upvote",s=r.querySelector(`[data-action="${a}"]`);if(s){s.classList.remove("persona-message-action-active");let e=Ee("upvote"===a?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(s.innerHTML="",s.appendChild(e))}mn.set(o,n),t.classList.add("persona-message-action-active");let i=Ee(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=ls.getMessages().find(e=>e.id===o);l&&pt&&pt({type:n,messageId:l.id,message:l})}}else if("regenerate"===n)An?.regenerate(o);else if("edit"===n)An?.edit(o);else if("quote"===n)An?.quote(o);else if(n?.startsWith("custom:")){let e=n.slice(7),r=l.messageActions?.custom?.find(t=>t.id===e),a=ls.getMessages().find(e=>e.id===o);if(!r||!a)return;try{r.onSelect(a)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let An=null;St.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 o=r.getAttribute("data-message-id");if(!o)return;let n=t.getAttribute("data-approval-action");if(!n)return;let a="approve"===n?"approved":"denied",s=ls.getMessages().find(e=>e.id===o);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"}),dr(s.approval)?ls.resolveWebMcpApproval(o,a):ls.resolveApproval(s.approval,a)});let In=null,Tn=!1,Rn=null,Nn=()=>{},Hn="none",Dn=null,On={artifacts:[],selectedId:null},Fn=!1,zn=!1,qn=!1,jn=!1,_n=()=>jn||On.artifacts.some(e=>"panel"===Mn(l.features?.artifacts,e)),Un=()=>On.artifacts.length>0&&!Fn&&_n(),Vn={current:null},Kn=(e,t)=>{let r=ls.getArtifactById(t),o=r?.markdown,n=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!o){let t=(e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]"))?.getAttribute("data-message-id");if(t){let e=ls.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);o=t?.props?.markdown,n=t?.props?.title||n,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:o,title:n,file:a,artifactType:s}};St.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===l.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:o,title:n,file:a}=Kn(t,r);if(!o)return;let s=Et();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:n,markdown:o,file:a}))}),St.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]"),n=o?null:t.closest("[data-open-artifact]"),a=o?o.getAttribute("data-artifact-inline"):n?.getAttribute("data-open-artifact")??null,s=(o?l.features?.artifacts?.inlineActions:l.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!s)return;let{markdown:i,title:d,file:c,artifactType:p}=Kn(t,a??""),u={artifactId:a,title:d,artifactType:p,markdown:i,file:c};try{Promise.resolve(s.onClick(u)).catch(()=>{})}catch{}}),St.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 o=ls.getArtifactById(r),n=Et();if(!n)return;let a="";if(o)a=n.artifactCopyText(o);else{let{markdown:e,file:o,artifactType:s}=Kn(t,r);"markdown"===s&&(a=n.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...o?{file:o}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=ne(pe,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=ne(he,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),St.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!==l.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})&&(Fn=!1,jn=!0,zn=!0,qn=!0,ls.selectArtifact(r),$a())}),St.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!==l.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:o})&&(e.preventDefault(),e.stopPropagation(),Fn=!1,jn=!0,ls.selectArtifact(o),$a())}),St.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 Qn=wt.composerOverlay,Jn=e=>{Wt().catch(()=>{}),Ro(e,l,Qn)},Gn=null,Yn={instanceId:n,mount:e,overlay:Qn,sessionRef:Vn,config:()=>l},Xn=!1,Zn=e=>t=>{let r=t.target,o=r?.closest?.("[data-persona-ask-sheet-for]");if(!o||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let n=r=>{Gn??=r.createAskUserSheetHandlers(Yn),Gn[e](t)},a=Ht();a?n(a):Xn||(Xn=!0,Wt().then(e=>{Xn=!1,o.isConnected&&n(e)},()=>{Xn=!1}))};Qn.addEventListener("click",Zn("click")),Qn.addEventListener("keydown",Zn("keydown"));let ta=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=Qn.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let o=Number(e.key),n=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[o-1];n&&(e.preventDefault(),n.click())};document.addEventListener("keydown",ta);let ra=null,sa=null,ia=()=>{},ya=!1,Ia="",Ea="",La=()=>{let e=fp?.railShell?fp.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360},Ba=()=>{},Pa=()=>{let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,o=l.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>o)&&(le||il(l))},Na=()=>!Jd(l)||!Un()||e.classList.contains("persona-artifact-narrow-host")||Pa()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":Zd(l)?"detached":"welded",$a=()=>{if(!In||!Jd(l))return;ec(e,l),tc(e,l),Ba();let t=l.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=ft.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let o=Un();In.setVisible(o),In.update(On),Fn?(In.setMobileOpen(!1),In.element.classList.add("persona-hidden"),In.backdrop?.classList.add("persona-hidden"),zn=!1,qn=!1):On.artifacts.length>0&&_n()?(In.element.classList.remove("persona-hidden"),In.setMobileOpen(!0)):(In.setMobileOpen(!1),In.element.classList.add("persona-hidden"),In.backdrop?.classList.add("persona-hidden"),zn=!1,qn=!1);let n=!0===l.features?.artifacts?.layout?.showExpandToggle;if(In.setExpandToggleVisible(n),In.setCopyButtonVisible(!0===l.features?.artifacts?.layout?.showCopyButton),In.setRefreshButtonVisible("function"==typeof l.features?.artifacts?.layout?.onDocumentToolbarRefresh),In.setCustomActions(l.features?.artifacts?.toolbarActions??[]),In.setStyleConfig(l),In.setTabFade(l.features?.artifacts?.layout?.tabFade),In.setRenderTabBar(l.features?.artifacts?.renderTabBar),!n&&!qn&&(zn=!1),zn!==ya){let e=In.element;zn?(Ia=e.style.width,Ea=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(Ia&&(e.style.width=Ia),Ea&&(e.style.maxWidth=Ea),Ia="",Ea=""),ya=zn}e.classList.toggle("persona-artifact-expanded",zn),In.setExpanded(zn);let a=Na();a!==Hn&&(Hn=a,Nn()),ia()};if(Jd(l)){ft.style.position="relative";let t=st("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=st("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(xt),ra=r,r.appendChild(t),ft.appendChild(r);let o=t=>{Tn||In||(In=t.createArtifactPane(l,{onSelect:e=>Vn.current?.selectArtifact(e),onDismiss:()=>{Fn=!0,$a()},onToggleExpand:()=>{let e=!zn,t=On.selectedId??On.artifacts[On.artifacts.length-1]?.id??null;!0!==l.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(zn=e,e||(qn=!1),$a())}}),sa=t.createArtifactResizer({mount:e,splitRoot:r,pane:In,getConfig:()=>l,chatMinWidth:La,isVisible:Un}),In.element.classList.add("persona-hidden"),r.appendChild(In.element),In.backdrop&&ft.appendChild(In.backdrop),ia(),$a())},n=Et();n?o(n):(Lt(()=>{let e=Et();e&&o(e)}),Tt().catch(()=>{})),ia=()=>sa?.update(),Ba=()=>{if(!le||!In||l.launcher?.sidebarMode||il(l)&&"emerge"===dl(l).reveal)return;let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,o=l.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=o||!function(e,t){return!(!t||!Jd(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(l,le))return;let n=Sd(l).width,a=l.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Un()?(ft.style.width=a,ft.style.maxWidth=a):(ft.style.width=n,ft.style.maxWidth=n)},typeof ResizeObserver<"u"&&(Rn=new ResizeObserver(()=>{$a()}),Rn.observe(ft))}else ft.appendChild(xt);ye()&&vt&&(wt.peekBanner&&vt.appendChild(wt.peekBanner),vt.appendChild(ar)),e.appendChild(gt),vt&&e.appendChild(vt);let Ha=()=>{let t=Pa()||ye()&&"fullscreen"===l.launcher?.composerBar?.expandedSize||!0===l.launcher?.fullHeight&&!l.launcher?.sidebarMode&&!il(l);if(St.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",St.style.setProperty("--persona-transcript-gap",St.style.gap),ye()){ft.style.width="100%",ft.style.maxWidth="100%";let e=l.launcher?.composerBar??{},t="expanded"===gt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return xt.style.background="",xt.style.border="",xt.style.borderRadius="",xt.style.overflow="",void(xt.style.boxShadow="");let o=l.theme?.components?.panel,n=di(l),a=(e,t)=>null==e||""===e?t:Us(n,e)??e;return xt.style.background="var(--persona-surface, #ffffff)",xt.style.border=a(o?.border,"1px solid var(--persona-border)"),xt.style.borderRadius=a(o?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),xt.style.boxShadow=a(o?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(xt.style.overflow="hidden")}let r=il(l),o=l.launcher?.sidebarMode??!1,n=as(l)||r||o||(l.launcher?.fullHeight??!1),a=!1===l.launcher?.enabled,s=!0===l.launcher?.detachedPanel,i=l.theme?.components?.panel,d=l.darkTheme?.components?.panel,c="dark"===li(l)?k(i??{},d??{}):i,p=di(l),u=(e,t)=>null==e||""===e?t:Us(p,e)??e,h=e.ownerDocument.defaultView??window,m=l.launcher?.mobileFullscreen??!0,g=l.launcher?.mobileBreakpoint??640,f=h.innerWidth<=g,b=m&&f&&le,y=r&&m&&f,v=l.launcher?.position??"bottom-left",w="bottom-left"===v||"top-left"===v,x=l.launcher?.zIndex??1e5,C=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,S=c?.modes?.floating,A=u(S?.border??c?.border,C("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),M=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)))")),I=u(S?.borderRadius??c?.borderRadius,C("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),T=s&&!b&&!y,E=b||y?"mobile":T?"floating":r?"docked":o?"sidebar":a?"inline":"floating",L=c?.modes?.[E];T?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let B=T?A:o||b?"none":A,R=T?M:b?"none":o?w?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":a?"none":M;r&&!b&&!T&&(R="none",B="none");let P=T?I:o||b?"0":I,N=u(L?.border??c?.border,C(E,"border",B)),$=u(L?.shadow??c?.shadow,C(E,"shadow",R)),W=u(L?.borderRadius??c?.borderRadius,C(E,"borderRadius",P)),H=Na(),D="detached"===H,O="welded"===H;e.classList.toggle("persona-artifact-detached-split",D),e.classList.toggle("persona-artifact-welded-split",O);let F="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)))))",z="flush"==("flush"===l.features?.artifacts?.layout?.chatSurface?"flush":"card")&&Jd(l)&&Zd(l)&&a&&!r;e.classList.toggle("persona-artifact-chat-flush",z);let q=D||z?"none":$,j=D?A:O?"none":N,_=D?I:W;z&&(j="none",_="0");let U=null!=L?.borderRadius&&""!==L.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,V=z&&!U?"0":W,K=Ct.scrollTop;e.style.cssText="",gt.style.cssText="",ft.style.cssText="",xt.style.cssText="",Ct.style.cssText="",Eo||(ar.style.cssText="",!1===l.layout?.showFooter&&(ar.style.display="none")),Ke&&(Ct.style.display="none"),(n||a)&&(e.style.minWidth="0");let Q=()=>{K<=0||(Ct.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(Ct.scrollTop===K)return;let e=Ct.scrollHeight-Ct.clientHeight;e<=0||(Ct.scrollTop=Math.min(K,e))})};if(b)return gt.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"),gt.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 `,ft.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 ",xt.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 ",Ct.style.flex="1 1 0%",Ct.style.minHeight="0",Ct.style.overflowY="auto",ar.style.flexShrink="0",Qr(),be=!0,void Q();let J=Sd(l);if(o||r){if(r)if("emerge"!==dl(l).reveal||s)ft.style.width="100%",ft.style.maxWidth="100%";else{let e=dl(l).width;ft.style.width=e,ft.style.maxWidth=e}}else a?(gt.style.width=kd(l),ft.style.width="100%",ft.style.maxWidth="100%"):(ft.style.width=J.width,ft.style.maxWidth=J.maxWidth);if(Ba(),ft.style.boxShadow=q,ft.style.borderRadius=V,D?ft.style.border="none":O&&(ft.style.border=N),xt.style.border=j,xt.style.borderRadius=_,xt.style.boxShadow=D&&!z?F:"",z&&(xt.style.background="transparent",Ct.style.background="transparent",ar.style.background="transparent",ar.style.borderTop="none"),O){let e=l.features?.artifacts?.layout;Dn=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||Qd(l,void 0,"split.outerRadius")||Qd(l,void 0,"pane.borderRadius")||W}else Dn=null;let G=null!=L?.border||null!=c?.border;if(!r||b||T||D||O||G||(xt.style.border="none","right"===dl(l).side?xt.style.borderLeft="1px solid var(--persona-border)":xt.style.borderRight="1px solid var(--persona-border)"),r&&!b&&O&&!G&&("right"===dl(l).side?ft.style.borderLeft="1px solid var(--persona-border)":ft.style.borderRight="1px solid var(--persona-border)"),n&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",as(l)&&(e.style.flex="1 1 0%"),a&&(e.style.width="100%"),gt.style.display="flex",gt.style.flexDirection="column",gt.style.flex="1 1 0%",gt.style.minHeight="0",gt.style.maxHeight="100%",gt.style.height="100%",a&&(gt.style.overflow="hidden"),ft.style.display="flex",ft.style.flexDirection="column",ft.style.flex="1 1 0%",ft.style.minHeight="0",ft.style.maxHeight="100%",ft.style.height="100%",D||(ft.style.overflow="hidden"),xt.style.display="flex",xt.style.flexDirection="column",xt.style.flex="1 1 0%",xt.style.minHeight="0",xt.style.maxHeight="100%",xt.style.overflow="hidden",Ct.style.flex="1 1 0%",Ct.style.minHeight="0",Ct.style.overflowY="auto",ar.style.flexShrink="0"),a&&(T||D||z)&&!r&&(z||(gt.style.padding="var(--persona-panel-inset)"),gt.style.background="var(--persona-panel-canvas-bg)"),gt.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||a||r||(fl[v]??fl["bottom-right"]).split(" ").forEach(e=>gt.classList.add(e)),o){let e=rs(l).sidebarWidth?l.launcher?.sidebarWidth??"420px":Us(di(l),"components.panel.width")??"420px";gt.style.cssText=s?`\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 `,ft.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: ${q} !important;\n border-radius: ${V} !important;\n ${D?"border: none !important;":O?`border: ${N} !important;`:""}\n `,ft.style.setProperty("width","100%","important"),ft.style.setProperty("max-width","100%","important"),xt.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: ${_} !important;\n border: ${j} !important;\n ${D&&!z?`box-shadow: ${F} !important;`:""}\n ${z?"background: transparent !important;":""}\n `,Eo||(ar.style.cssText=`\n flex-shrink: 0 !important;\n border-top: none !important;\n padding: 8px 16px 12px 16px !important;\n ${z?"background: transparent !important;":""}\n ${!1===l.layout?.showFooter?"display: none !important;":""}\n `)}if(!a&&!r){let e=o?"":"padding-top: 1.25em !important;",t=o?"":`z-index: ${l.launcher?.zIndex??1e5} !important;`;gt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}Qr(),Q()},Da=()=>{e.style.setProperty("--persona-content-max-width",gi(l,ye()))},Oa=!1;function Fa(){l.layout?.topFade&&Ct.scrollTop>1?Ct.setAttribute("data-persona-top-fade","true"):Ct.removeAttribute("data-persona-top-fade"),Rr.hidden=!ye()||Br.hidden||Ct.scrollHeight-Ct.clientHeight-Ct.scrollTop<=1,Rr.hidden||(Rr.style.bottom=xt.getBoundingClientRect().bottom-Br.getBoundingClientRect().top-xt.clientTop+"px")}let qa=()=>{Fa();let t=fi(l,ye());ye()&&l.composer?.placement&&!0===l.debug&&!Oa&&(Oa=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=Fr();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",zr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),Jr()},_a=()=>{if(ye())return;let t=il(l),r=l.launcher?.sidebarMode??!1;if(as(l)||t||r||l.launcher?.fullHeight||!le)return;let o=e.ownerDocument.defaultView??window,n=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640;if(n&&o.innerWidth<=a)return;let s=Sd(l);ft.style.height=s.height,ft.style.maxHeight=s.maxHeight};Ha(),ui(e,l),ec(e,l),tc(e,l),Da(),qa(),Nn=()=>{Ha(),_a(),ui(e,l),ec(e,l),tc(e,l),Da(),qa(),Dn?e.style.setProperty("--persona-artifact-welded-outer-radius",Dn):e.style.removeProperty("--persona-artifact-welded-outer-radius"),nt(),ot()};let Ua=[];Ua.push(()=>Xo.destroy()),Ua.push(()=>{Tn=!0}),Ua.push(()=>{L.forEach(e=>e()),E.destroy()}),Ua.push(()=>{document.removeEventListener("keydown",ta)}),Ua.push(()=>{null!==$r&&clearTimeout($r)});let Va=null,Ka=null;Ua.push(()=>{Va?.(),Va=null,Ka?.(),Ka=null}),Rn&&Ua.push(()=>{Rn?.disconnect(),Rn=null}),Ua.push(()=>{sa?.destroy(),sa=null,In?.element.style.removeProperty("width"),In?.element.style.removeProperty("maxWidth"),In?.destroy()}),Pe&&Ua.push(()=>{Ue=!0,_e=null,null!==Qe&&(cancelAnimationFrame(Qe),Qe=null),Ve?.destroy(),Ve=null,ze?.destroy(),ze=null,Oe=null});let Ja=null,Ga=()=>{if(Ja&&=(Ja(),null),"auto"===l.colorScheme){let e=li(l);Ja=mi(t=>{t!==e&&(e=t,Nn(),$a(),ls&&(Vs++,$d(St,ls.getMessages(),Le)))})}};Ga(),Ua.push(()=>{Ja&&=(Ja(),null)}),Ua.push(()=>{W=!0,$?.()}),Ua.push(()=>{F=!0});let Ya=!1;Ua.push(()=>{Ya=!0});let Xa=(t,r)=>{let o=Di(t,r);return o||!Wi.includes(t)?o:(rl().then(o=>{if(Ya)return;Hi(o.wipe),Hi(o.glyphCycle);let n=Di(t,r);n&&Xi(n,e)}).catch(()=>{}),null)},Za=l.features?.streamAnimation;if(Za?.type&&"none"!==Za.type){let t=Xa(Za.type,Za.plugins);t&&Xi(t,e),Ua.push(()=>Yi(e))}let es=gl(Mt),ts=gl(kt),os=gl(At),ns=gl(Br),is=[es,ts,os,ns];Ua.push(()=>{is.forEach(e=>e.destroy())});let ls,ds=null,cs=null,ps=!1,us=0,hs=null,ms=new Set;Ua.push(()=>ms.clear());let fs=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),bs=e=>{for(let t=e.length-1;t>=0;t--)if(Ho(e[t]))return e[t].id??null;return null},ys=!1,ws=!1,Ss=!1,ks=(e,t)=>{ws||!0!==l.debug||t.enabled&&!t.expose&&(ps||Ss&&(ls.isStreaming()||e.some(Ho)||(ws=!0,console.info("[persona] No suggest_replies call received. Declare the tool server-side or set suggestions.followUps.expose: true, and instruct the model when to use it. See UI-COMPONENTS.md."))))},As=e=>{if(!ls)return;let t=e??ls.getMessages();if(Mt.removeAttribute("data-persona-suggestions-below"),Mt.parentElement===ar&&ar.insertBefore(Mt,ar.firstChild),ms.size){let e=new Set(t.map(e=>e.id));for(let t of ms)e.has(t)||ms.delete(t)}let r=e=>{e.render([],ls,It,t)},o=e=>{is.forEach(t=>{t!==e&&r(t)})};cs&&(fs(t)>us||bs(t)!==hs)&&(cs=null);let n=zo(l);ks(t,n);let a=bs(t),s=!n.enabled||l.future?.v5Defaults&&a&&ms.has(a)?null:Oo(t,l.suggestions?.followUps?.maxItems??(l.future?.v5Defaults?5:4));if(l.future?.v5Defaults&&ls.isStreaming())return void is.forEach(r);let i=cs??s,d=cs?"host":"agent";if(i){let e=l.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),n="after-message"===("auto"===r?ye()?"composer":"after-message":r)?os:ye()?ns:es;return o(n),void n.render(i,ls,It,t,l.suggestionChipsConfig,{source:d,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??(l.future?.v5Defaults?"scroll":"wrap"),maxItems:e?.maxItems??(l.future?.v5Defaults?Or()?5:3:4),config:l,plugins:T,submitPrompt:gu})}if(t.some(e=>"user"===e.role))return void is.forEach(r);let c=!0===l.future?.v5Defaults,p=Or(),u=l.suggestions?.starters??(c?{}:void 0);if(u){let e=xd(Fr(),t),n=u.placement??"auto",a="auto"===n?e?"welcome":"composer":n;if("welcome"===a&&!e)return ys||!0!==l.debug||(ys=!0,console.warn('[persona] Starters are hidden: suggestions.starters.placement is "welcome", but welcome is disabled. Use "auto" or "composer".')),void is.forEach(r);Mt.toggleAttribute("data-persona-suggestions-below","below-composer"===a),"below-composer"===a?Rt.after(Mt):ar.insertBefore(Mt,ar.firstChild);let s="welcome"===a?ts:es;o(s),s.render(u.items??l.suggestionChips,ls,It,t,l.suggestionChipsConfig,{surface:"starter",variant:u.variant??(c&&!p?"chip":"card"),behavior:u.behavior??"send",overflow:u.overflow??"wrap",maxItems:u.maxItems??(c&&!p?3:4),config:l,plugins:T,submitPrompt:gu})}else o(es),es.render(l.suggestionChips,ls,It,t,l.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:l,plugins:T,submitPrompt:gu})},Is=()=>{if(!l.future?.v5Defaults||!ls)return;cs=null;let e=bs(ls.getMessages());e&&ms.add(e),As()},Ts=()=>{cs&&(cs=null,As())},Es=!1,Ls=new Map,Bs=new Set,Rs=new Map,Ps=new Map,Ns=new Map,$s=new Map,Ws=e=>{let t=$s.get(e);if($s.delete(e),Ns.delete(e),Ld(St,e)?.removeAttribute("data-preserve-runtime"),t){t.controller.abort();try{t.handle.destroy?.()}catch(e){console.error("[AgentWidget] Component cleanup failed:",e)}}};Ua.push(()=>{for(let e of $s.keys())Ws(e)});let Hs=new Map,Ds=new Map,Os=e=>{Ds.get(e)?.abort(),Ds.delete(e),Hs.delete(e)},Fs=()=>{for(let e of Ds.keys())Os(e)};Ua.push(Fs);let zs=null,qs=null;function js(){if(!zs)return;let e=zs;zs=null,qs?.destroy(),qs=null,Ls.delete(e),xt.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),ls&&$d(St,ls.getMessages(),Le)}let Vs=0,Ks=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),Qs=0,Js=null,Gs=!1,Ys=!1,Xs=0,Zs=null,ei=null,ti=!1,ri=!1,oi=null,ni=!0,ai=!1,si=null,ii=!1,ci=()=>{bn++,ii=!0,xi()},pi=null,hi=24,yi=null,vi=()=>{e.setAttribute("data-persona-scrollbar",Ir()),"on-scroll"!==Ir()&&(null!==yi&&clearTimeout(yi),yi=null,Ct.removeAttribute("data-persona-scrollbar-visible"))},xi=()=>{"on-scroll"===Ir()&&(Ct.setAttribute("data-persona-scrollbar-visible",""),null!==yi&&clearTimeout(yi),yi=setTimeout(()=>{yi=null,Qt(Ct,24)&&Ct.removeAttribute("data-persona-scrollbar-visible")},1e3))};vi(),Ua.push(()=>{null!==yi&&clearTimeout(yi)});let ki=new Map,Ai=!1,Ei=null,Li={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};en();let Ri=l.voiceRecognition?.autoResume??!1,Ni=()=>ls.isVoiceActive()||ls.isBargeInActive(),$i=!1,Fi=e=>{U.emit("voice:state",{active:Li.active,source:e,timestamp:Date.now()})},zi=()=>{oe(e=>({...e,voiceState:{active:Li.active,timestamp:Date.now(),manuallyDeactivated:Li.manuallyDeactivated}}))},qi=()=>{$i=!0,Li.active&&zi()};typeof window<"u"&&(window.addEventListener("pagehide",qi),Ua.push(()=>window.removeEventListener("pagehide",qi)));let ji=()=>ls?Mp(ls.getMessages()).filter(e=>!e.__skipPersist):[],_i=null,Ui=(e,t)=>{typeof console<"u"&&console.error(e,t)},Ji=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{Ui(t,e)}):null}catch(e){return Ui(t,e),null}},o=_i?_i.then(()=>r()??void 0):r();if(!o)return;let n=o.finally(()=>{_i===n&&(_i=null)});_i=n};function Gi(e){if(null!==el||!V?.save)return;let t=e?Mp(e):ls?ji():[],r=K&&ls?.getResumableHandle();r&&(Q={...Q,durableResume:{executionId:r.executionId,after:r.lastEventId}});let o={messages:t,metadata:Q,artifacts:On.artifacts,selectedArtifactId:On.selectedId,...Zi?{draft:Zi}:{}};Ji(()=>V.save(o),"[AgentWidget] Failed to persist state:")}let Zi,el=null,tl=()=>!(!V?.save||!1===l.persistState||"object"==typeof l.persistState&&!1===l.persistState.persist?.draft),nl=function(e){let t=e.delay??500,r=null,o=!1,n=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{o||(n(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{o||null===r||(n(),e.write())},cancel:n,destroy:()=>{o=!0,n()}}}({write:()=>{if(!tl())return;let e=Xr.getState(),t=ma({text:e.text,mentionRefs:e.mentionRefs,contentSegments:au(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Zi)&&(Zi=t,Gi())}});function al(){tl()&&nl.schedule()}function cl(){nl.flush()}function pl(e){if(!tl())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),n=o.length===(e.mentionRefs?.length??0)&&o.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,...n?{mentionRefs:o}:{},...n&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(l.contextMentions?.sources??[]).map(e=>e.id),modelIds:(l.composer?.models??[]).map(e=>e.id),modes:l.composer?.modes??[]});t&&(Zi=e,It&&!It.value&&(It.value=t.text,It.dispatchEvent(new Event("input",{bubbles:!0})),Zr()),t.selectedModelId&&(Xr.setSelectedModelId(t.selectedModelId),uo?.repaint()),co(t.activeModeIds??[]),t.quote&&go(t.quote),nl.cancel())}function hl(){nl.cancel(),Zi&&(Zi=void 0,tl()&&Gi())}let bl=Gt(),yl=()=>gt.querySelector("#persona-scroll-container")||Ct,vl=()=>{bl.cancel(),Gs=!1},Cl=()=>{null!==Js&&(cancelAnimationFrame(Js),Js=null),Ys=!1,vl()},Sl=()=>{let e=ls?.getStatus();return Es&&"paused"!==e&&"resuming"!==e&&"error"!==e&&!ls?.getMessages().some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)},Al=()=>Sl()&&_l()&&("anchor-top"!==wr()||kr()),Ml=()=>{let e="true"===Er.getAttribute("data-persona-scroll-to-bottom-visible");Tr.update(l,e,Al(),Xs,e&&Rl())},El=()=>{let e=Ct.getBoundingClientRect(),t=ar.getBoundingClientRect();return t.height>0&&t.bottom>e.top?Math.min(Ct.clientHeight,Math.max(0,t.top-e.top-Ct.clientTop)):Ct.clientHeight},Ll=e=>Ur(e)>Ct.scrollTop+El()-24,Bl=()=>(ls?.getMessages()??[]).filter(e=>"approval"===e.variant&&"pending"===e.approval?.status).map(e=>yd(e.id)).filter(e=>!!e?.isConnected),Rl=()=>Bl().some(Ll),Nl=e=>{let t=Ur(e);return t>=Ct.scrollTop&&t+e.offsetHeight<=Ct.scrollTop+El()},Hl=[],_l=()=>!(xr()&&Ks.isFollowing()||gd(Zs?.spacerHeight??0,!1)-Ct.scrollTop-El()<=24),Vl=()=>!!ls&&ls.getMessages().length>0,Ql=()=>{if(!1===l.features?.scrollToBottom?.enabled||Ke||tt&&"panel"===rt)return Tr.update(l,!1),void(Er.parentNode&&Er.remove());let e=Lr();Er.parentNode!==e&&e.insertBefore(Er,e===xt?Br:null),Vr();let t=Kt(Ct)>0,r=!td.active&&t&&_l()&&Vl();r||(Xs=0),Tr.update(l,r,Al(),Xs,r&&Rl())},Jl=()=>{Ks.pause()&&(Cl(),Ql())},Gl=()=>{Ks.resume(),0!==Xs&&(Xs=0,Ml()),Ql()},Xl=(e=!1)=>{!td.active&&xr()&&Vl()&&Ks.isFollowing()&&(e||Es)&&(null!==Js&&(cancelAnimationFrame(Js),Js=null),Ys=!0,Js=requestAnimationFrame(()=>{Js=null,Ys=!1,Ks.isFollowing()&&rd(yl(),e?220:140)}))},ed=(e,t,r,o=()=>!0)=>{vl(),Gs=!0,bl.start(e,t,r,()=>{Qs=e.scrollTop},()=>{Gs=!1},o)},td=Yt(Ct,xt,()=>{Qs=Ct.scrollTop},()=>{Gl(),Xl(!0),Ql(),(()=>{let e=Hl;Hl=[];for(let t of e){let e=yd(t)?.querySelector('[data-action="allow"]');if(e&&Nl(e))return void e.focus({preventScroll:!0})}})()},()=>{Hl=[],Ks.pause(),Ql()}),rd=(e,t=500)=>{let r=Kt(e)-e.scrollTop;Math.abs(r)<1?Qs=e.scrollTop:Math.abs(r)>=80?(vl(),Gs=!0,e.scrollTop=Kt(e),Qs=e.scrollTop,Gs=!1):ed(e,()=>Kt(e),t,()=>Ks.isFollowing())},sd=()=>{if(!Vl())return void Ql();let e=yl();Gs=!0,e.scrollTop=Kt(e),Qs=e.scrollTop,Gs=!1,Ql()},id=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=Ct.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??Ct.ownerDocument.getSelection()})(),Ct),ld=()=>{if("last-user-turn"!==(Ne.restorePosition??"bottom"))return!1;let e=ls?.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,'\\"'),o=Ct.querySelector(`[data-message-id="${r}"]`);if(!o)return!1;let n=Math.min(Math.max(0,Ur(o)-Cr()),Kt(Ct));return Gs=!0,Ct.scrollTop=n,Qs=Ct.scrollTop,Gs=!1,"follow"===wr()&&!Qt(Ct,24)&&Ks.pause(),Ql(),!0},ud=e=>{let t=Math.max(0,Math.round(e));Pr.style.height=`${t}px`,Pr.style.display=t>0?"":"none",Zs&&(Zs.spacerHeight=Math.max(0,e))},gd=(e,t=!0)=>{let r=parseFloat(getComputedStyle(Ct).paddingBottom)||0,o=0;for(let e of Ct.children){let t=e;t!==Pr&&0!==t.offsetHeight&&(o=Math.max(o,Ur(t)+t.offsetHeight))}let n=Ct.scrollHeight-e,a=o>0?Math.min(o+r,n):n;return t?a:a-r},fd=()=>{null!==ei&&(cancelAnimationFrame(ei),ei=null),td.cancel(),vl(),Zs=null,Pr.style.height="0px",Pr.style.display="none"},yd=e=>Ct.querySelector(`[data-message-id="${(e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'))(e)}"]`),vd=()=>{if("anchor-top"!==wr()||!Zs||!si)return;let e=yd(si);if(!e)return;vl();let t=Zs.spacerHeight,r=gd(t),{targetScrollTop:o,spacerHeight:n}=Jt({anchorOffsetTop:Ur(e),topOffset:Cr(),viewportHeight:Ct.clientHeight,contentHeight:r,slack:24});Zs={pending:0,initialSpacerHeight:n,contentHeightAtAnchor:r,spacerHeight:n},ud(n),Gs=!0,Ct.scrollTop=o,Qs=Ct.scrollTop,Gs=!1,Ql()},Cd=(e,t,r,o,n)=>{if(Ls.delete(r),"toggle"!==n&&xr()&&Ks.isFollowing())return void Ul(e,t,r,o);let a=Ct.getBoundingClientRect().top,s=e.getBoundingClientRect(),i=Zs;i&&(vl(),ud(i.spacerHeight+e.offsetHeight)),Ul(e,t,r,o);let l=e.getBoundingClientRect(),d=s.top-a,c="toggle"===n?l.top-a-("collapsed"===o.state&&d<0?Cr():d):d>=0?l.top-s.top:l.bottom-s.bottom,p=Math.max(0,Ct.scrollTop+c);i&&Zs===i&&(ud(p+Ct.clientHeight+24-gd(i.spacerHeight)),i.initialSpacerHeight=i.spacerHeight,i.contentHeightAtAnchor=Ct.scrollHeight-i.spacerHeight),Math.abs(p-Ct.scrollTop)>=1&&(Gs=!0,Ct.scrollTop=p,Qs=Ct.scrollTop,Gs=!1),Ql()},Ad=()=>{if(!Fl(l))return;let e=zl(l);for(let t of Array.from(St.querySelectorAll(`[${Dl}]`))){let r=t.closest("[data-message-id]"),o=r?.getAttribute("data-message-id");if(!r||!o)continue;let n=t.scrollHeight;n>0&&v.set(o,jl(n,e));let a=v.get(o)??!1,s=t.getAttribute(Dl);if("live"===s)continue;"settling"===s&&x.delete(o);let i=a?w.get(o)?"expanded":"collapsed":"fit";i!==s&&Cd(r,t,o,{state:i,maxHeight:e,...ql(l)},"measure")}},Td=(e,t)=>{let r="user"===t?"user":"assistant",o=l.layout?.messages?.[r],n=o?.width??"content",a="operator"===t?"content":n,s="operator"===t?"var(--persona-message-operator-max-width, var(--persona-message-assistant-max-width, 100%))":`var(--persona-message-${r}-max-width, 100%)`,i=o?.maxWidth??("full"===n?s: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-row-operator","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),i?e.style.setProperty("--persona-message-row-max-width",i):e.style.removeProperty("--persona-message-row-max-width")},Ed=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),Td(r,t),r},Ld=(e,t)=>Array.from(e.querySelectorAll("[data-wrapper-id]")).find(e=>e.getAttribute("data-wrapper-id")===t),Bd=(t,r,o)=>{let n=new Set;g(),i?.observeMessages(r,n);let a=document.createElement("div"),d=!l.features?.toolCallDisplay?.grouped,c=new Set;if(d)for(let e of Array.from(t.children)){let t=e.getAttribute("data-wrapper-id");t&&c.add(t)}let p,u=new Map,h=T.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator??l.loadingIndicator?.render,v=new Set,w=new Map,x=new Set,S=T.some(e=>e.renderAskUserQuestion),k=[],A=[],M=!1!==l.enableComponentStreaming,I=!1!==l.approval,E=[],L=l.messageActions;if(l.future?.v5Defaults&&void 0===L?.visibility)for(let e=r.length-1;e>=0;e--)if("assistant"===r[e].role&&!r[e].variant){p=r[e].id;break}let R=!0!==L?.showRegenerate&&"block"!==l.errorDisplay||!1===L?.enabled||!0===Vn.current?.isStreaming()?null:function(e){for(let t=e.length-1;t>=0;--t){let r=e[t];if("user"===r.role||"operator"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return Ln(e,r.id)?r.id:null}return null}(r),$=!0===L?.showEdit&&!1!==L.enabled,W=-1;r.forEach((e,t)=>{"operator"===e.role&&(W=t)});let H=!0===L?.showQuote&&!1!==L.enabled,D=null,F=l.features?.reasoningDisplay?.completedVisibility,z=e=>"removed"===F||"removed-when-short"===F&&((e,t)=>{let r=t?.durationMs??15e3,o=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<o})(e,l.features?.reasoningDisplay?.shortThinkThreshold),q="removed"===l.features?.toolCallDisplay?.completedVisibility,j=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?z(e.reasoning):q&&"tool"===e.variant&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;r.forEach((n,s)=>{if(j(n))return;if(v.add(n.id),w.set(n.id,n.role),("tool"===n.variant&&n.toolCall&&Re||"reasoning"===n.variant&&n.reasoning&&Be)&&!g())return void a.appendChild(Ed(n.id,n.role));if(zs===n.id&&qs){let e=Ed(n.id,n.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void(D={messageId:n.id,element:qs.element})}let i=S&&yo(n),B=I&&"approval"===n.variant&&!!n.approval,F=!i&&"assistant"===n.role&&!n.variant&&M&&$n(n);!B&&Hs.has(n.id)&&(Ld(t,n.id)?.removeAttribute("data-preserve-runtime"),Os(n.id)),!F&&Ns.has(n.id)&&(Ld(t,n.id)?.removeAttribute("data-preserve-runtime"),Ws(n.id));let z=yo(n)?`:${n.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${n.agentMetadata?.askUserQuestionAnswers?Object.keys(n.agentMetadata.askUserQuestionAnswers).length:0}`:"",q={isLastAssistant:n.id===p,canRegenerate:R===n.id&&(!0===L?.showRegenerate||!0===n.dispatchError),canEdit:$&&s>W&&Bn(n),canQuote:H&&!n.variant&&(n.content?.trim().length??0)>0},U=`${q.canRegenerate?"r":""}${q.canEdit?"e":""}${q.canQuote?"q":""}${q.isLastAssistant?"l":""}`,V=n.approval?.toolCallId?r.filter(e=>!("tool"!==e.variant||e.toolCall?.id!==n.approval?.toolCallId||e.agentMetadata?.executionId&&n.approval?.executionId&&e.agentMetadata.executionId!==n.approval.executionId)):[],K=1===V.length?V[0].toolCall:void 0,Q=K&&"pending"!==K.status?{toolCallId:K.id,status:"running"===K.status?"running":!1===K.success||K.error?"failed":"completed"}:void 0,J=C(n),G=Bi(n,Vs)+z+`:${U}`+(J?`:uc-${J.state}`:"")+(B?`:${n.approval?.toolCallId??""}:${JSON.stringify(Q)}`:""),Y=i||B||F||n.dispatchError&&"block"===l.errorDisplay&&!P?null:function(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}(Ls,n.id,G);if(Y){if(c.has(n.id)&&Rs.get(n.id)===G){let e=document.createElement("div");e.id=`wrapper-${n.id}`,e.setAttribute("data-wrapper-id",n.id),e.setAttribute("data-persona-reuse","true"),a.appendChild(e)}else a.appendChild(Y.cloneNode(!0));return d&&u.set(n.id,G),void(yo(n)&&n.toolCall?.id&&!0===n.agentMetadata?.awaitingLocalTool&&!n.agentMetadata?.askUserQuestionAnswered&&(x.add(n.toolCall.id),Jn(n)))}let X=null,Z=()=>{if(n.dispatchError&&"block"===l.errorDisplay){let e=O();if(e)return e.createErrorBlock(n,o,!0===q.canRegenerate)}let e=od(n,o,l.layout?.messages,l.messageActions,0,{loadingIndicatorRenderer:h,widgetConfig:l,actionEligibility:q,userCollapse:J});return e.dataset.personaDefaultMessage="true",e},ee=T.find(e=>!!("reasoning"===n.variant&&e.renderReasoning||"tool"===n.variant&&e.renderToolCall||!n.variant&&e.renderMessage));if(yo(n)&&!0===n.agentMetadata?.askUserQuestionAnswered)return Ps.delete(n.id),void Ld(t,n.id)?.removeAttribute("data-preserve-runtime");if(Ho(n)&&zo(l).enabled)return;if(yo(n)&&!1!==l.features?.askUserQuestion?.enabled){let e=T.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&Vn.current){let t=Ps.get(n.id),r=t!==G,o=null;if(r){let{payload:t,complete:r}=wo(n),a=n.id,s=()=>Vn.current?.getMessages().find(e=>e.id===a);o=e.renderAskUserQuestion({message:n,payload:t,complete:r,resolve:e=>{let t=s();t&&Vn.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Vn.current?.markAskUserQuestionResolved(e),Vn.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:l})}if(r&&null===o&&null==t)return void(!0===n.agentMetadata?.awaitingLocalTool&&!n.agentMetadata?.askUserQuestionAnswered&&(x.add(n.toolCall.id),Jn(n)));let s=Ed(n.id,n.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),a.appendChild(s),void k.push({messageId:n.id,fingerprint:G,bubble:o})}return void(!0===n.agentMetadata?.awaitingLocalTool&&!n.agentMetadata?.askUserQuestionAnswered&&(x.add(n.toolCall.id),Jn(n)))}if(B){let t=O();if(!t)return void a.appendChild(Ed(n.id,n.role));let r=T.find(e=>"function"==typeof e.renderApproval)??N,o=Hs.get(n.id),s=null,i=!1;if(o!==G&&r?.renderApproval){let a=n.id,d=!1,c=(e,t)=>{let r=Vn.current?.getMessages().find(e=>e.id===a);d||"pending"!==r?.approval?.status||(d=!0,dr(r.approval)?Vn.current?.resolveWebMcpApproval(r.id,e):Vn.current?.resolveApproval(r.approval,e,t))};Os(n.id);let p=new AbortController;Ds.set(n.id,p);let u={message:n,execution:Q,signal:p.signal,defaultRenderer:()=>g(),config:l,approve:e=>{p.signal.aborted||c("approved",e)},deny:e=>{p.signal.aborted||c("denied",e)}},h=null,m=new AbortController;p.signal.addEventListener("abort",()=>m.abort(),{once:!0});let g=()=>(h??=N?.renderApproval?.({...u,signal:m.signal})??t.createApprovalBubble(n,l,y),h);s=r===N?g():r.renderApproval(u)??g();let f=null!==h&&(s===h||s.contains(h));f||m.abort();let b=e.getRootNode();i=f&&void 0===o&&"pending"===n.approval?.status&&!1!==l.approval&&"focused"===l.approval?.keyboardShortcuts&&e.contains(b.activeElement)}let d=Ed(n.id,n.role);return d.setAttribute("data-approval-plugin-stub","true"),d.setAttribute("data-preserve-runtime","true"),a.appendChild(d),void E.push({messageId:n.id,fingerprint:G,bubble:s,focusDefault:i})}if(ee)if("reasoning"===n.variant&&n.reasoning&&ee.renderReasoning){if(!Be)return;X=ee.renderReasoning({message:n,defaultRenderer:()=>m.createReasoningBubble(n,l,b),config:l})}else if("tool"===n.variant&&n.toolCall&&ee.renderToolCall){if(!Re)return;X=ee.renderToolCall({message:n,defaultRenderer:()=>m.createToolBubble(n,l,f),config:l})}else ee.renderMessage&&(X=ee.renderMessage({message:n,defaultRenderer:()=>{let e=Z();return"user"!==n.role&&_(e,n,l,ls),e},config:l}));if(X&&$s.has(n.id)&&Ws(n.id),!X&&F){let e=Wn(n);if(e){let r=Ns.get(n.id),s=!1!==l.wrapComponentDirectiveInBubble&&!1!==yt(l,e.component)?.bubbleChrome,i=`${Bi(n,Vs)}:${s}:${e.raw}`,d=$s.get(n.id),c=bt(l,e.component),p=d?.renderer!==c||d?.component!==e.component,u=r!==i||p;d&&(d.context.message=n,d.context.config=l);let h=null;if(u){let r=null;if(d&&!p&&d.handle.update){d.context.message=n,d.context.config=l;try{d.handle.update(e.props,d.context),r=d.handle.element}catch(e){console.error("[AgentWidget] Component update failed:",e),Ws(n.id)}}else{Ws(n.id);let t=new AbortController,a={config:l,message:n,signal:t.signal,updateProps:e=>{queueMicrotask(()=>{t.signal.aborted||Vn.current?.updateComponentProps(n.id,e)})}},s=Pn(e,{config:l,message:n,transform:o,signal:t.signal,onPropsUpdate:a.updateProps,context:a});if(s){let o="element"in s?s:{element:s};r=o.element,$s.set(n.id,{renderer:c,component:e.component,controller:t,handle:o,context:a})}else t.abort()}if(r&&"PersonaArtifactInline"===e.component){let e=r.hasAttribute("data-artifact-inline")?r:r.querySelector("[data-artifact-inline]"),o=e?.getAttribute("data-artifact-inline")??"",a=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(o):o,s=o?t.querySelector(`#wrapper-${n.id}`)?.querySelector(`[data-artifact-inline="${a}"]`)??null:null;e&&s&&s!==e&&Et()?.hasLiveInlineArtifactBlock(s)&&(e===r?r=s:e.replaceWith(s))}if(r)if(s){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",e.id=`bubble-${n.id}`,e.setAttribute("data-message-id",n.id),n.content&&n.content.trim()){let t=document.createElement("div");t.className="persona-mb-3 persona-text-sm persona-leading-relaxed",t.innerHTML=o({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),e.appendChild(t)}e.appendChild(r),h=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-${n.id}`,e.setAttribute("data-message-id",n.id),e.setAttribute("data-persona-component-directive","true"),n.content&&n.content.trim()){let t=document.createElement("div");t.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",t.innerHTML=o({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),e.appendChild(t)}e.appendChild(r),h=e}}if(h||$s.has(n.id)){let e=Ed(n.id,n.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void A.push({messageId:n.id,fingerprint:i,bubble:h})}}}if(!X)if("reasoning"===n.variant&&n.reasoning){if(!Be)return;X=m.createReasoningBubble(n,l,b)}else if("tool"===n.variant&&n.toolCall){if(!Re)return;X=m.createToolBubble(n,l,f)}else if("approval"===n.variant&&n.approval){if(!1===l.approval)return;let e=O();if(!e)return;X=e.createApprovalBubble(n,l,y)}else{let e=l.layout?.messages;X=e?.renderUserMessage&&"user"===n.role?e.renderUserMessage({message:n,config:l,streaming:!!n.streaming}):e?.renderAssistantMessage&&"assistant"===n.role?e.renderAssistantMessage({message:n,config:l,streaming:!!n.streaming}):Z(),"user"!==n.role&&X&&_(X,n,l,ls)}let te=Ed(n.id,n.role);te.appendChild(X),function(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}(Ls,n.id,G,te),a.appendChild(te),d&&u.set(n.id,G)}),wt.composerOverlay&&wt.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!x.has(t)&&Po(wt.composerOverlay,t)});let U=g()?.groupToolRows({root:e,config:l,messages:r,tempContainer:a,streaming:!!B&&ls.isStreaming(),runActivity:ls?.getRunActivity(),showToolCalls:Re,showReasoning:Be,dropCompletedToolCalls:q,dropReasoningRow:z,createMessageRow:Ed,activityIds:n,activityLifecycle:i,toolExpansionState:f});i?.prune(n);for(let e of $s.keys())v.has(e)||Ws(e);for(let e of Ds.keys())v.has(e)||Os(e);!function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(Ls,v);let V=e=>yo(e)&&!0!==e.agentMetadata?.askUserQuestionAnswered&&!1!==l.features?.askUserQuestion?.enabled?(e=>!(e.toolCall?.id&&x.has(e.toolCall.id)||k.some(t=>t.messageId===e.id)))(e):"tool"===e.variant&&!Re||"reasoning"===e.variant&&!Be||j(e),K=r.some(e=>"assistant"===e.role&&e.streaming&&!V(e)),Q=r.length-1;for(;Q>=0&&V(r[Q]);)Q--;let J=Q>=0?r[Q]:void 0,G=Q<r.length-1,Y="assistant"===J?.role&&!J.streaming&&"approval"!==J.variant&&!G;if(!U&&Es&&r.some(e=>"user"===e.role)&&!K&&!Y){let e={config:l,streaming:!0,location:"standalone",defaultRenderer:()=>Kl(l)},t=T.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator?.(e)??l.loadingIndicator?.render?.(e)??Kl(l);if(t){let e=document.createElement("div"),r=!1!==l.loadingIndicator?.showBubble,o=l.layout?.messages?.layout??"bubble";e.className=r?Yl("assistant",o).join(" "):"persona-text-sm persona-leading-relaxed persona-text-persona-text",e.setAttribute("data-typing-indicator","true"),r&&(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(t);let n=Ed("typing-indicator","assistant");n.appendChild(e),a.appendChild(n)}}if(!Es&&r.length>0){let e=r[r.length-1],t={config:l,lastMessage:e,messageCount:r.length},o=T.find(e=>e.renderIdleIndicator)?.renderIdleIndicator?.(t)??l.loadingIndicator?.renderIdle?.(t);if(o){let e=document.createElement("div");e.className=!1===l.loadingIndicator?.showBubble?"persona-text-sm persona-leading-relaxed persona-text-persona-primary":"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",e.setAttribute("data-idle-indicator","true"),e.appendChild(o);let t=Ed("idle-indicator","assistant");t.appendChild(e),a.appendChild(t)}}(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)})})(a),s?.prepare(a),i?.prepare(a),Ii(t,a),Rs=u;for(let e of Array.from(t.querySelectorAll(":scope > [data-persona-reuse]"))){let t=Ls.get(e.getAttribute("data-wrapper-id")??"");t?e.replaceWith(t.wrapper.cloneNode(!0)):e.remove()}if(Wr(t),D){let{messageId:e,element:r}=D,o=Ld(t,e);o&&r.parentElement!==o&&(Td(o,w.get(e)??"user"),o.replaceChildren(r))}if(k.length>0)for(let{messageId:e,fingerprint:r,bubble:o}of k){let n=Ld(t,e);n&&(Td(n,w.get(e)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Ps.set(e,r)))}if(Ps.size>0)for(let e of Ps.keys())v.has(e)||Ps.delete(e);if(A.length>0)for(let{messageId:e,fingerprint:r,bubble:o}of A){let n=Ld(t,e);n&&(Td(n,w.get(e)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Ns.set(e,r)))}if(Ns.size>0)for(let e of Ns.keys())v.has(e)||Ns.delete(e);if(E.length>0)for(let{messageId:e,fingerprint:r,bubble:o,focusDefault:n}of E){let a=Ld(t,e);if(!a||(Td(a,w.get(e)??"assistant"),null===o))continue;a.replaceChildren(o),a.setAttribute("data-bubble-fp",r),Hs.set(e,r);let s=xr()&&Ks.isFollowing();n&&(s||!Ll(a))&&o.querySelector('[data-action="allow"]')?.focus()}if(Hs.size>0)for(let e of Hs.keys())v.has(e)||Hs.delete(e);g(),s?.sync(),i?.sync()},Rd=()=>{qr().catch(()=>{})},$d=(e,t,r)=>{if(t.length>0&&Rd(),Bd(e,t,r),(e=>{if(0===v.size&&0===w.size&&0===x.size)return;let t=new Set(e.map(e=>e.id));for(let e of[v,w,x])for(let r of e.keys())t.has(r)||e.delete(r)})(t),Ad(),kn(),gn.size>0){for(let[e,r]of gn)t.some(t=>t.id===e)||(window.clearTimeout(r),gn.delete(e));vn()}},Hd=null,Dd=()=>{if(Hd)return;let t=e=>{let t=e.composedPath();t.includes(gt)||vt&&t.includes(vt)||rc(!1,"user")};Hd=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},Od=()=>{Hd&&=((e.ownerDocument??document).removeEventListener("pointerdown",Hd,!0),null)};Ua.push(()=>Od());let Fd=null,zd=()=>{if(Fd)return;let t=e=>{"Escape"===e.key&&(e.isComposing||rc(!1,"user"))};Fd=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},_d=()=>{Fd&&=((e.ownerDocument??document).removeEventListener("keydown",Fd,!0),null)};Ua.push(()=>_d());let Ud=!1,Vd=new Set,Gd=()=>l.launcher?.composerBar?.peek?.streamAnimation||l.features?.streamAnimation,Yd=()=>{if(!ye())return;let t=wt.peekBanner,r=wt.peekTextNode;if(!t||!r)return;if(we)return void t.classList.remove("persona-pill-peek--visible");let o,n=ls?.getMessages()??[];for(let e=n.length-1;e>=0;e--){let t=n[e];if("assistant"===t.role&&t.content){o=t;break}}if(!o)return void t.classList.remove("persona-pill-peek--visible");let a=o.content,s=!!o.streaming,i=Gd(),l=Pi(i),d="none"===l.type?null:Xa(l.type,i?.plugins),c=!0===d?.isAnimating?.(o),p=null!==d&&(s||c);p&&d&&!Vd.has(d.name)&&(Xi(d,e),Vd.add(d.name));let u=p&&d?.containerClass?d.containerClass:null,h=r.dataset.personaPeekStreamClass??null;h&&h!==u&&(r.classList.remove(h),delete r.dataset.personaPeekStreamClass),u&&h!==u&&(r.classList.add(u),r.dataset.personaPeekStreamClass=u),p?(r.style.setProperty("--persona-stream-step",`${l.speed}ms`),r.style.setProperty("--persona-stream-duration",`${l.duration}ms`)):(r.style.removeProperty("--persona-stream-step"),r.style.removeProperty("--persona-stream-duration"));let m=p?Oi(a,l.buffer,d,o,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),n=m.length>100?m.slice(-100):m,a=Ar(n);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Vi(a,d.wrap,`peek-${o.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&n.length>0){let e=Ki(),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)}Ii(r,i),d.onAfterRender?.({container:r,bubble:t,messageId:o.id,message:o,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${n}`:n;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=Qi();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),Ii(r,e)}let g=Es||Ud;t.classList.toggle("persona-pill-peek--visible",g)};if(ye()){let e=wt.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),rc(!0,"user")};e.addEventListener("pointerdown",t),Ua.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Ud||(Ud=!0,Yd())},r=()=>{Ud&&(Ud=!1,Yd())};ft.addEventListener("pointerenter",t),ft.addEventListener("pointerleave",r),Ua.push(()=>{ft.removeEventListener("pointerenter",t),ft.removeEventListener("pointerleave",r)}),vt&&(vt.addEventListener("pointerenter",t),vt.addEventListener("pointerleave",r),Ua.push(()=>{vt.removeEventListener("pointerenter",t),vt.removeEventListener("pointerleave",r)}))}let Xd=()=>{if(we&&Rd(),!ve())return;if(ye()){let e=(l.launcher?.composerBar??{}).expandedSize??"anchored",t=we?"expanded":"collapsed";return gt.dataset.state=t,gt.dataset.expandedSize=e,vt&&(vt.dataset.state=t,vt.dataset.expandedSize=e),gt.style.removeProperty("display"),gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=l.launcher?.composerBar??{},r=t.expandedSize??"anchored",o=t.bottomOffset??"16px",n=t.collapsedMaxWidth,a=t.expandedMaxWidth??"880px",s=t.expandedTopOffset??"5vh",i=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)";Kr();let p=gt.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",vt){let e=vt.style;e.bottom=o,e.width=n??""}e&&"fullscreen"!==r&&("modal"===r?(p.top="50%",p.left="50%",p.transform="translate(-50%, -50%)",p.bottom="auto",p.right="auto",p.width=i,p.maxWidth=c,p.maxHeight=d,p.height=d):(p.left="50%",p.transform="translateX(-50%)",p.bottom=`calc(${o} + var(--persona-pill-area-height, var(--persona-measured-pill-area-height, 80px)))`,p.top=s,p.width=a,p.maxWidth=c))})(we),xt.style.display=we?"flex":"none",Nn(),we?(Dd(),zd()):(Od(),_d()),void Yd()}let t=il(l),r=e.ownerDocument.defaultView??window,o=l.launcher?.mobileBreakpoint??640,n=l.launcher?.mobileFullscreen??!0,a=r.innerWidth<=o,s=n&&a&&le,i=dl(l).reveal;we?(gt.style.removeProperty("display"),gt.style.display=t?"flex":"",gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-95","persona-opacity-0"),ft.classList.add("persona-scale-100","persona-opacity-100"),mh?(mh.setPanelOpen(!0),mh.element.style.display="none"):gh&&(gh.style.display="none")):(t?!t||"overlay"!==i&&"push"!==i||s?(gt.style.setProperty("display","none","important"),gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(gt.style.removeProperty("display"),gt.style.display="flex",gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(gt.style.display="",gt.classList.add("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-100","persona-opacity-100"),ft.classList.add("persona-scale-95","persona-opacity-0")),mh?(mh.setPanelOpen(!1),mh.element.style.display=t?"none":""):gh&&(gh.style.display=t?"none":""))},rc=(t,r="user")=>{if(!ve()||we===t)return;let o=we;we=t,Xd();let n=(()=>{let t=l.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,o=l.launcher?.mobileFullscreen??!0,n=l.launcher?.mobileBreakpoint??640,a=r.innerWidth<=n,s=il(l)&&o&&a,i=ye()&&"fullscreen"===(l.launcher?.composerBar?.expandedSize??"fullscreen");return t||o&&a&&le||s||i})();if(we&&n){if(!Va){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(Va=ol(r,l.launcher?.zIndex??1e5))}Ka||=sl(e.ownerDocument)}else we||(Va?.(),Va=null,Ka?.(),Ka=null);we&&(vh(),ld()||("follow"===wr()?Xl(!0):sd()));let a={open:we,source:r,timestamp:Date.now()};we&&!o?U.emit("widget:opened",a):!we&&o&&U.emit("widget:closed",a),U.emit("widget:state",{open:we,launcherEnabled:le,voiceActive:Li.active,streaming:ls.isStreaming()})},oc={inputDisabled:!1,sendDisabled:!1},nc=()=>oc.inputDisabled,ac=()=>_t(l.voiceRecognition?.provider)&&!!ls&&(ls.isBargeInActive()||["listening","processing","speaking"].includes(ls.getVoiceStatus())),sc=()=>oc.inputDisabled||oc.sendDisabled;function ic(){if(!Bt)return;if("streaming"===Xr.getState().phase)return void(Bt.disabled=!1);let e=!!Gr&&!Gr.isReady();Bt.disabled=sc()||e}function lc(){if(!cr)return;let e=Xr.getState(),t="when-text"===l.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;cr.toggleAttribute("data-persona-send-hidden",t)}function dc(){let e=Aa(l.composer?.inputDisabled),t=Aa(l.composer?.sendDisabled);oc={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Xr.setInputDisabled(e.disabled),Xr.setSendDisabled(t.disabled);let r="streaming"===Xr.getState().phase,o=e.disabled,n=r||o;It&&(It instanceof HTMLTextAreaElement?It.disabled=o:It.setAttribute("contenteditable",o?"false":"true"),It.setAttribute("aria-disabled",o?"true":"false")),fr&&(fr.disabled=o),yr&&(yr.disabled=o);for(let e of Yr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=o});mr&&(mr.disabled=o||r&&!ac()),is.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",n),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",n?"true":"false")}),e.buttons.forEach(e=>{e.disabled=n})}),Tc.forEach(e=>{e.toggleAttribute("data-disabled",n),e instanceof HTMLButtonElement?e.disabled=n:e.setAttribute("aria-disabled",n?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=n})}),ar.dataset.personaComposerStreaming=r?"true":"false",ar.dataset.personaComposerInputDisabled=o?"true":"false",ar.dataset.personaComposerSendDisabled=sc()?"true":"false",ar.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=r)}),ic(),function(){let e=(oc.inputDisabled?oc.inputReason:void 0)??(oc.sendDisabled?oc.sendReason:void 0);if(ye()){let t=Rt??ar;e?t.setAttribute("title",e):t.removeAttribute("title"),ar.toggleAttribute(xp,!!e)}else if(e)Pt.setAttribute("role","status"),Pt.setAttribute("aria-live","polite"),Pt.setAttribute(xp,""),Pt.removeAttribute(Cp),Pt.textContent=e,pr(Pt,l.statusIndicator??{},"idle");else if(Pt.hasAttribute(xp)&&(Pt.removeAttribute("role"),Pt.removeAttribute("aria-live"),Pt.removeAttribute(xp),B)){let e=ls.getStatus();ht(Pt,ut(e),l.statusIndicator??{},e)}}()}let cc=e=>{Xr.setStreaming(e),hr(e?"stop":"send"),dc()},pc=()=>{e.hasAttribute("data-persona-preparing")?u.ready.then(pc,()=>{}):Li.active||It&&It.focus()};U.on("widget:opened",()=>{l.autoFocusInput&&setTimeout(()=>pc(),200)});let uc=null,hc=!1,mc=!Nt.hidden,gc=null,fc=!J,bc=null;Ua.push(()=>{bc?.cancel(),bc=null});let yc,vc,wc=t=>{let r=wd(t);if(r===zr)return;zr=r,e.setAttribute("data-persona-conversation-state",r);let o=_r();Jr(),fc&&(bc?.cancel(),bc=md(ar,"active"===r?o:_r(),"active"===r?"drop":"rise","centered"===Fr().layout?320:260)),vd()},xc=null,Cc=null,Sc=null,Ac=!1,Mc=e=>{let t=Fr(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==xc||t.icon!==yc)&&(xc=r,yc=t.icon,ad({host:Nt,iconHolder:$t,kicker:Ot,title:Ft,subtitle:zt,starterSuggestions:kt},t));let o=void 0===t.message?null:`${l.layout?.messages?.layout??"bubble"}|${t.message}`;o!==Cc&&(Cc=o,pd(Dt,t.message,l));let n=e??(ls?ls.getMessages():l.initialMessages);wc(n);let a=hc,s=!a&&xd(t,n),i=s!==mc;if(mc=s,Sc)return gc?.cancel(),gc=null,a!==Ac&&(Ac=a,a?cd(Ct,Nt,null):dd(Ct,Nt,Sc)),void nd(Ct,Nt,!a);if(i&&!s&&!a&&"on-first-message"===t.dismiss&&fc)return void(gc=hd(Nt,e=>{gc===e&&(gc=null),!mc&&!Sc&&(nd(Ct,Nt,!1),vd()),e?.cancel()}));if(gc){if(!s&&!a)return;gc.cancel(),gc=null}let d=!Nt.hidden;nd(Ct,Nt,s),!s&&d&&vd()},Ic=[],Tc=[],Ec=!1,Pc=null,Nc=()=>{Tc.length=0;let e=Ic.splice(0,Ic.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};Ua.push(Nc);let $c=(e,t)=>{let r=ul(e,t);if(!r)return!0===l.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),st("span");let o=l.suggestions?.starters,n=ml({item:{...r,behavior:r.behavior??o?.behavior??"send"},index:t,surface:"starter",source:"config",variant:o?.variant??"card",streaming:!!B&&ls.isStreaming(),config:l,plugins:T,chipsConfig:l.suggestionChipsConfig,session:ls,getTextarea:()=>It,eventTarget:Nt,submitPrompt:gu});return Tc.push(n),n},Hc=()=>{if(Ec)return;Ec=!0;let e=Fr();Pc=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,vc=e.icon;try{Nc(),cd(Ct,Nt,Sc),Sc=null,Ac=!1;let t=ls?ls.getMessages():l.initialMessages,r=xd(e,t),o=0,n=null;for(let t of T)if(t.renderWelcome&&(n=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>Nt,sendMessage:e=>{if(!ls||ls.isStreaming())return;let t=e.trim();t&&ls.sendMessage(t)},requestRender:()=>Hc(),renderStarter:e=>$c(e,o++),storage:R(t.id),onCleanup:e=>{Ic.push(e)}}),n))break;n&&n!==Nt&&(Sc=n,dd(Ct,Nt,n))}finally{Ec=!1}Mc()},Dc=()=>{Mc(),Eo||(It.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Xr.getState().activeModeIds,l.composer?.modes)??l.copy?.inputPlaceholder??"How can I help...",!l.sendButton?.useIcon&&!ls?.isStreaming()&&(Bt.textContent=l.copy?.sendButtonLabel??"Send")),It.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',It.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Oc=!!l.setStoredConversationId,Fc=e=>oe(t=>{let r={...t};return delete r[e],r}),zc=e=>{let t=Q[e];return"string"==typeof t?t:null},qc=()=>{let e=Q.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};l.clientToken&&(l={...l,getStoredSessionId:()=>zc("sessionId"),setStoredSessionId:e=>{oe(t=>({...t,sessionId:e}))},clearStoredSessionId:l.clearStoredSessionId??(()=>Fc("sessionId")),getStoredConversationId:l.getStoredConversationId??(()=>zc("conversationId")),setStoredConversationId:l.setStoredConversationId??(e=>{oe(t=>({...t,conversationId:e}))}),clearStoredConversationId:l.clearStoredConversationId??(()=>Fc("conversationId"))});let jc=()=>l.clientToken??null,_c=e=>((e,t,r)=>{let o="",n="",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(o)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let o={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(o)},g=e=>{i||(null===e.key||e.key===o)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await op(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await op(`${e}\0${t}`)}`}})(e,t);o=s.storageKey,n=s.leaseKey,a=s.lockName,d=h(),!r&&typeof window<"u"&&window.addEventListener("storage",g)})(),b=e=>new Promise(t=>setTimeout(t,e)),y=()=>{let e=u();if(!e)return null;try{let t=e.getItem(n);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{y()?.ownerNonce===e&&t.removeItem(n)}catch{}},w=new Set,x=e=>i?Promise.reject(Error("Visitor store destroyed before its first init could start")):e(),C=e=>new Promise(t=>{let r=setTimeout(o,e);function o(){clearTimeout(r),w.delete(o),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===n)&&o()}w.add(o),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(o,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(o)}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 o=Date.now(),a=y();if(a&&a.expiresAt>o&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-o,500));else{try{r.setItem(n,JSON.stringify({ownerNonce:t,expiresAt:o+1e4}))}catch{s=!0;break}if(await b(20+40*Math.random()),y()?.ownerNonce!==t)await C(500);else{c=t;try{return await x(e)}finally{c=null,v(t)}}}}return x(e)})(e):x(e)},matches:(o,n,a)=>o===e&&n===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,He(),!1===l.persistState),Uc=jc(),Jc=Uc?_c(Uc):null,Yc={...Jc?{visitorStore:Jc}:{},historyBootstrapReady:!0!==l.features?.history?.enabled||mp()?G:Promise.all([G,Z]).then(()=>{}),getStoredMessageCursor:()=>zc("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?Fc("historyMessageCursor"):oe(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:()=>{let e=Q.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?oe(t=>({...t,pendingDisplayProjections:e})):Fc("pendingDisplayProjections")},getStoredResumableHandle:qc,setStoredResumableHandle:e=>{e?oe(t=>({...t,durableResume:e})):Fc("durableResume")},shouldResumeDurableConversation:()=>K&&null!==qc(),...Oc?{}:{getStoredConversationRevision:()=>zc("conversationRevision"),setStoredConversationRevision:e=>{null===e?Fc("conversationRevision"):oe(t=>({...t,conversationRevision:e}))}}};if(K){let t=l.onExecutionState,r=e.ownerDocument.defaultView,o=!1,n=()=>o=!0,a=()=>o=!1;r?.addEventListener("pagehide",n),r?.addEventListener("pageshow",a),Ua.push(()=>{r?.removeEventListener("pagehide",n),r?.removeEventListener("pageshow",a)}),l={...l,reconnectStream:l.reconnectStream??(e=>ls.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!o)&&Yc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Zc=null,ep=e=>"user"===e.role||"approval"===e.variant||!0===e.agentMetadata?.awaitingLocalTool||yo(e),np=null,ap=null,sp=null,lp=null,dp=e=>{let t,r;!e.length&&l.future?.v5Defaults&&(cs=null),np=e;for(let o=e.length-1;o>=0;--o){let n=e[o];if(!t&&"user"===n.role&&(t=n),!r&&"assistant"===n.role&&(r=n),t&&r)break}$d(St,e,Le),Et()?.updateInlineArtifactBlocks(St,On.artifacts,{suppressTransition:Es}),Zc??=setInterval(()=>{let e=St.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Zc),void(Zc=null);let t=Date.now();e.forEach(e=>{m?.updateActivityElapsed(e,t)})},100),Mc(e),As(e),Xl(!Es),(e=>{let t=new Map;e.forEach(e=>{let r=ki.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(U.emit("assistant:message",e),!ri&&("anchor-top"!==wr()||kr())&&_l()&&(Xs+=1,Ml(),Ql(),Dr(1===Xs?"1 new message below.":`${Xs} new messages below.`))),"assistant"===e.role&&(r?.streaming||Bs.has(e.id))&&!1===e.streaming&&U.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&U.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):U.emit("approval:requested",{approval:e.approval,message:e}))}),ki.clear(),t.forEach((e,t)=>{ki.set(t,e)}),Bs.clear()})(e),Ql(),Ve?.update(),0===e.length&&(fd(),ni=!0,ai=!1,si=null,ii=!1),!ti||ri?(ti=!0,oi=t?.id??null,pi=r?.id??null):t&&t.id!==oi?(oi=t.id,(e=>{let t=wr();"follow"===t?(Gl(),Xl(!0)):"anchor-top"===t&&(ni=!1,ai=!0,ii=!1,si=e,(e=>{null!==ei&&cancelAnimationFrame(ei),ei=requestAnimationFrame(()=>{ei=null;let t=yd(e);if(!t)return;let r=Ur(t),o=gd(Zs?.spacerHeight??0),{targetScrollTop:n,spacerHeight:a}=Jt({anchorOffsetTop:r,topOffset:Cr(),viewportHeight:Ct.clientHeight,contentHeight:o,slack:24});Zs={pending:0,initialSpacerHeight:a,contentHeightAtAnchor:o,spacerHeight:a},ud(a),ed(Ct,()=>t.isConnected?Math.max(0,Ur(t)-Cr()):n,220)})})(e))})(t.id)):r&&r.id!==pi&&"anchor-top"===wr()&&(ai?ni=!1:(ni=!0,fd(),Gl(),Xl(!0))),r&&(pi=r.id);let o=Li.lastUserMessageId;t&&t.id!==o&&(Li.lastUserMessageId=t.id,U.emit("user:message",t)),Li.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!K)return Gi(e);lp=e,queueMicrotask(()=>{lp===e&&(lp=null,Gi(ap??e))})})(e),Yd(),U.emit("messages:changed",e)},cp=()=>{null!==sp&&(cancelAnimationFrame(sp),sp=null);let e=ap;ap=null,e&&dp(e)},pp=()=>{null!==sp&&cancelAnimationFrame(sp),sp=null,ap=null};ls=new c(l,{onRunStarted:e=>U.emit("run:started",e),onRunFinished(e){cp(),l.turnActivity?.enabled&&$d(St,ls.getMessages(),Le),U.emit("run:finished",e)},onMessagesChanged(e){(e=>{if(0===e.length)return pp(),void dp(e);let t=ap??np;Es&&t&&((e,t)=>{if(t.length<e.length)return!1;for(let r=0;r<t.length;r+=1){let o=t[r];if(o!==e[r]){if(ep(o))return!1;"assistant"===o.role&&o.streaming&&Bs.add(o.id)}}return!0})(t,e)?(ap=e,null===sp&&(sp=requestAnimationFrame(()=>{sp=null;let e=ap;ap=null,e&&dp(e)}))):(cp(),dp(e))})(e)},onStatusChanged(e){let t=l.statusIndicator??{};ht(Pt,(e=>"idle"===e?t.idleText??dt.idle:"connecting"===e?t.connectingText??dt.connecting:"connected"===e?t.connectedText??dt.connected:"error"===e?t.errorText??dt.error:"paused"===e?t.pausedText??dt.paused:"resuming"===e?t.resumingText??dt.resuming:dt[e])(e),t,e),Ql(),Ve?.update(),lt()},onStreamingChanged(e){e||(0===ls?.getMessages().length?pp():cp()),Es=e,e?Is():l.future?.v5Defaults&&As(),cc(e),lt(),ls&&$d(St,ls.getMessages(),Le),e||(Xl(!0),(()=>{if(!Zs||Zs.spacerHeight<=0||Zs.pending)return;let e=gd(Zs.spacerHeight),t=Math.max(0,Math.round(Ct.scrollTop)+Ct.clientHeight-e+24);t<Zs.spacerHeight&&(ud(t),Ql())})(),Ss=!0,ls&&ks(ls.getMessages(),zo(l))),Ql(),Ve?.update(),Dr(e?"Responding…":"Response complete."),Yd()},onVoiceStatusChanged(e){if(U.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!_t(l.voiceRecognition?.provider))return;let t=ls.getVoiceNotice();switch(t&&pu(t,1e4),e){case"listening":if(!Ai){let e=ls.getVoiceDisclosure();e&&(Ai=!0,ye()?(Ei=It.placeholder,It.placeholder=e,Dr(e)):pu(e,1e4))}Gu(),Ku();break;case"processing":Gu(),Qu();break;case"speaking":Gu(),Ju();break;default:"idle"===e&&ls.isBargeInActive()?(Gu(),Ku(),mr?.setAttribute("aria-label","End voice session")):(Li.active=!1,Ai=!1,null!==Ei&&(It.placeholder=Ei,Ei=null),Gu(),Fi("system"),$i||zi())}},onArtifactsState(e){On=e,0===e.artifacts.length&&(jn=!1),Et()?.updateInlineArtifactBlocks(St,e.artifacts,{suppressTransition:Es}),$a(),Gi()},onHistoryStateChanged(e){at(e)},onHistoryNotice(e){it(e)},onHistoryScopeInvalidated(){Up(),fp?.clearConversationOpenPending()},onConversationExecutionState(e){U.emit("conversation:executionState",e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?U.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?U.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):U.emit("stream:resumed",{executionId:t,after:r})}},Yc),Vn.current=ls,Ua.push(()=>ls.cancel()),Ua.push(()=>{ls.destroy(),Jc?.destroy(),Jc=null});let up=null;if(ls.onReadAloudChange((e,t)=>{xn=e,Cn=t,kn();let r=e??up;e&&(up=e);let o=r?ls.getMessages().find(e=>e.id===r)??null:null;U.emit("message:read-aloud",{messageId:r,message:o,state:t,timestamp:Date.now()}),"idle"===t&&(up=null)}),B=!0,ti=!0,!0===l.voiceRecognition?.enabled&&Ut(l))try{ls.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let fp=null,bp=null,Lp=!1,Bp=ls.getHistoryState(),Rp=()=>!0===l.features?.history?.enabled,Pp=e=>{e&&(Nr.textContent="",Nr.textContent=e)},Np=()=>{L.forEach(e=>e()),L=[];let t=fp,r=t?.railCollapseShortcut();t&&r&&L.push(E.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===l.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>tt&&"rail"===rt&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of l.layout?.header?.trailingActions??[])t.shortcut&&L.push(E.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():l.layout?.header?.onAction?.(t.id)}}));for(let e of T)for(let t of e.shortcuts??[])L.push(E.register({...t,id:`${e.id}:${t.id}`}))};Np();let $p=null,Wp=!1,Hp=()=>{if(!tr)return;let e="conversation"===l.layout?.header?.titleSource,t=e&&$p?.trim()||null;tr.textContent=t??l.launcher?.title??"Chat Assistant";let r=tr.closest(".persona-combo-btn");if(!r)return;let o=!e||null!==ls.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 n=r.querySelector("svg");n&&(n.style.display=o?"":"none")};Hp(),xt.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=ls.getActiveConversationId();r&&("delete"===t?Jp(e=>e.requestDeleteConversation(r)):"star"===t&&ls.canUpdateConversations()&&Jp(e=>e.updateHistoryConversation(r,{starred:!Wp})).catch(()=>{}))});let Dp=new Map,Op=(e=ls.getActiveConversationId(),t=fp?.historyOperationScope()??l.features?.history?.scope??(l.getIdentityProof?"verified-user":"browser"))=>JSON.stringify([t,e]),Fp=null,zp=0,qp=()=>{let e=Ct.getBoundingClientRect().top,t=Ct.clientHeight>0?Array.from(St.querySelectorAll("[data-message-id]")).find(t=>t.getBoundingClientRect().bottom>e):void 0;return{top:Ct.scrollTop,anchorId:t?.dataset.messageId,anchorOffset:t?t.getBoundingClientRect().top-e:0,following:Ks.isFollowing(),followFallback:ni,anchored:ai,anchoredId:si,readerEngaged:ii,anchor:Zs?{...Zs}:null,unread:Xs}},jp=e=>{ni=e.followFallback,ai=e.anchored,si=e.anchoredId,ii=e.readerEngaged,Zs=e.anchor?{...e.anchor,pending:0}:null,ud(e.anchor?.spacerHeight??0),e.following?Ks.resume():Ks.pause(),Xs=e.unread;let t=Array.from(St.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e.anchorId);Gs=!0,e.following&&xr()?Ct.scrollTop=Kt(Ct):t?Ct.scrollTop+=t.getBoundingClientRect().top-Ct.getBoundingClientRect().top-e.anchorOffset:Ct.scrollTop=e.top,Gs=!1,Qs=Ct.scrollTop,xh=Kt(Ct),Ml(),Fa(),Ql()},_p=(e=!1,t=!0)=>{let r=e?void 0:Dp.get(Op());Yr?.clear(),Gr?.setPreviewsContainer(null),Gr=r?.attachments??(l.attachments?.enabled?no():null),Gr?.updateConfig(ro()),Gr?.remountPreviews(vr),ao(Gr?.getAttachments()??[]);let o=r?.draft,n=Yr?.getInlineInput();r?.document&&n?.setDocument?n.setDocument(r.document):n?n.setValueWithCaret(o?.text??"",(o?.text??"").length):It.value=o?.text??"",Yr?.restoreDraft(r?.mentions??[]),Zr(),eo(),Xr.setSelectedModelId(o?l.composer?.models?.some(e=>e.id===o.selectedModelId)?o.selectedModelId:void 0:l.composer?.selectedModelId),uo?.repaint(),co(fa(o?.activeModeIds??l.composer?.defaultActiveModeIds??[],so())),go(o?.quote),xo(r?.pending),wu(),fd(),Cl(),fp?.cancelConversationOpenTakeover(),uc&&(uc.hidden=!0),hc=!1,St.style.removeProperty("display"),r?jp(r.reading):(Gl(),ld()||sd()),t&&(Zi=tl()?ma({...Xr.getState(),contentSegments:au()}):void 0),nl.cancel(),t&&Gi(),Fp={key:Op(),reading:r?.reading??qp()}},Up=(e,t=!0,r=!0)=>{for(let[t,r]of Dp)(void 0===e||JSON.parse(t)[1]===e)&&(r.attachments?.destroy({release:!0}),Gr===r.attachments&&(Gr=null),Dp.delete(t));(void 0===e||e===ls.getActiveConversationId())&&(++zp,el=null,lu?.abort(),lu=null,Bu(),Gr?.destroy({release:!0}),Gr=null,t&&_p(!0,r),Fp=null)};at=e=>{Bp=e,fp?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),cc(e.sendBlocked||Es),fp?.syncEarlierMessagesPill()},it=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(Up(),fp?.clearConversationOpenPending(),Ls.clear(),fd(),Gl()),Pp(e.message),fp?.historySurface?.view.refresh()};let Vp={getBubbleClasses:Yl,parseCombo:wi,formatCombo:Ci,ariaCombo:Si,usesSessionVoiceForConfig:Ut,applyBubbleGeometry:Zl,resolveThemeDefaults:_s,composerStore:Xr,get attachmentManager(){return Gr},set attachmentManager(e){Gr=e},get composerConversationGeneration(){return zp},set composerConversationGeneration(e){zp=e},get submissionAbort(){return lu},set submissionAbort(e){lu=e},persistState:Gi,applyMessageRowLayout:Td,SessionHistoryError:d,instanceId:n,discardConversationContinuity:Up,clearPersistedDraft:hl,saveConversationContinuity:()=>{Bu(),_u("system"),Ut(l)&&ls.cleanupVoice(),++zp,lu?.abort(),lu=null,Xr.setPreparing(!1),js(),cl();let e=Xr.getState(),t=Op();Dp.set(t,{draft:{text:e.text,mentionRefs:[...e.mentionRefs],contentSegments:au(),quote:e.quote,selectedModelId:e.selectedModelId,activeModeIds:[...e.activeModeIds]},document:Yr?.getInlineInput()?.getDocument?.(),mentions:Yr?.captureDraft()??[],attachments:Gr,pending:e.pendingSubmission,reading:Fp?.key===t?Fp.reading:qp()}),nl.cancel()},restoreConversationContinuity:_p,get pendingConversationReading(){return Fp},set pendingConversationReading(e){Fp=e},conversationStateKey:Op,captureConversationReading:qp,restoreConversationReading:jp,get conversationPersistenceOwner(){return el},set conversationPersistenceOwner(e){el=e},setComposerDisabled:cc,get actionManager(){return ie},get activeConversationTitle(){return $p},announceHistory:Pp,get applyRailChrome(){return nt},set applyRailChrome(e){nt=e},get artifactSplitRoot(){return ra},get body(){return Ct},get config(){return l},get container(){return xt},get conversationOpenPendingEl(){return uc},set conversationOpenPendingEl(e){uc=e},get conversationOpenTakeover(){return hc},set conversationOpenTakeover(e){hc=e},currentKeyPrefix:He,destroyCallbacks:Ua,eventBus:U,get footer(){return ar},get header(){return nr},get historyChromeSync(){return lt},set historyChromeSync(e){lt=e},historyFeatureEnabled:Rp,get historyInternals(){return Yc},set historyInternals(e){Yc=e},get historyPresentation(){return rt},set historyPresentation(e){rt=e},get historySessionState(){return Bp},get historyVisible(){return tt},set historyVisible(e){tt=e},get isStreaming(){return Es},jumpToBottomInstant:sd,get lastAppliedMessages(){return np},set lastAppliedMessages(e){np=e},get launcherEnabled(){return le},get launcherSurfaceInstance(){return mh},maybeFocusInput:pc,messageCache:Ls,get messagesWrapper(){return St},mount:e,get open(){return we},panel:ft,panelElements:wt,panelSuggestions:Br,panelSuggestionsFade:Rr,get persistentMetadata(){return Q},set persistentMetadata(e){Q=e},plugins:T,get reapplyHistoryHostChrome(){return ot},set reapplyHistoryHostChrome(e){ot=e},repinAnchoredMessage:vd,resetAnchorState:fd,restoreScrollPosition:ld,resumeAutoScroll:Gl,runStorageMutation:Ji,get session(){return ls},setActiveConversationSummary:e=>{Wp=!0===e?.starred,(e=>{e!==$p&&($p=e,Hp())})(e&&e.title.trim()||null),Hp()},storageAdapter:V,get suppressScrollSend(){return ri},set suppressScrollSend(e){ri=e},syncScrollToBottomButton:Ql,scrollToBottomButton:Er,updateWelcome:Mc,getHistoryProviderFactory:gp,historyErrors:{HistoryClientError:o,HistoryProviderError:a},isDockedMountMode:il,renderLucideIcon:Ee,loadHistoryView:ip,createHeaderIconButton:wl,attachTooltip:Qa},Kp=e=>(!fp&&!Lp&&(fp=e.createHistoryShell(Vp),fp.railCollapseShortcut()&&Np()),fp),Qp=()=>{if(fp)return Promise.resolve(fp);let e=mp();return e?Promise.resolve(Kp(e)):(bp??=hp().then(Kp,e=>{throw bp=null,e}),bp)},Jp=e=>{let t=mp(),r=fp??(t?Kp(t):null);return r?e(r):Qp().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},Gp=()=>{fp?.syncHistoryPresentation()};Ua.push(()=>{Lp=!0}),Rp()&&Qp().catch(()=>{}).finally(X),l.clientToken&&(!0===l.features?.history?.enabled||"mount"===l.sessionInit)&&ls.initClientSession().then(()=>{let e=fp;if(e?.historyAvailable())return ls.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{fp?.syncEarlierMessagesPill()}).catch(e=>{l.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let Yp=()=>ls.warmClientSession(),Xp=e=>{let t=l.sessionInit??"input",r=No?.input??It,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:(No?.form??Rt)?.contains(o)))&&Yp()},Zp=["input","pointerdown","keyup"];Zp.forEach(t=>e.addEventListener(t,Xp));let eu,tu,ru=()=>{let e=tu;tu=void 0;try{"function"==typeof e&&e()}catch{}},ou=()=>{let t=l.clientToken&&"function"==typeof l.sessionInit?l.sessionInit:void 0;if(t!==eu){ru(),eu=t;try{tu=t?.({warm:Yp,mount:e})}catch{}}};ou(),Ua.push(()=>{Zp.forEach(t=>e.removeEventListener(t,Xp)),ru()}),(Pe||l.onSSEEvent)&&ls.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ze(e,t)});let nu=()=>{let e=l.resume??(K?Yc.getStoredResumableHandle?.():null);e&&"function"==typeof l.reconnectStream&&ls.resumeFromHandle(e)};J?J.then(e=>{if(e){if(e.metadata&&(Q=Ap(e.metadata),ie.syncFromMetadata()),e.messages?.length){ri=!0;try{ls.hydrateMessages(e.messages)}finally{ri=!1}Rd()}e.artifacts?.length&&ls.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),pl(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{fc=!0,M(),nu()}):(pl(I),nu());let au=()=>{let e=It.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},su=!1,iu=0,lu=null,du=()=>{It.value="",It.style.height="auto",Zr(),wu()},cu=null;function pu(e,t=4e3){Dr(e),!ye()&&Pt&&(Pt.hasAttribute(xp)||(Pt.setAttribute(Cp,""),Pt.setAttribute("role","status"),Pt.setAttribute("aria-live","polite"),Pt.textContent=e,pr(Pt,l.statusIndicator??{},"idle"),cu&&clearTimeout(cu),cu=setTimeout(()=>{if(cu=null,Pt?.hasAttribute(Cp)&&(Pt.removeAttribute(Cp),Pt.removeAttribute("role"),Pt.removeAttribute("aria-live"),B)){let e=ls.getStatus();ht(Pt,ut(e),l.statusIndicator??{},e)}},t)))}let uu=(e={})=>{if(Lu()||uc)return;let t=zp,r=(e.overrideText??It?.value??"").trim();return e.resolveInlineCommand&&r?(Yr?.takeInlineCommand(r)??Promise.resolve(null)).then(o=>{if(t===zp)return hu(e,r,o)}):hu(e,r,null)},hu=(e,t,r)=>{if("action"===r?.kind)return du(),Yr?.clear(),void eo();let o="server"===r?.kind?r.mentions:null,n="prompt"===r?.kind?r.sendText:t,a=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:n,hasAttachments:(Gr?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:Gr?.isReady()??!0,hasMentions:Yr?.hasMentions()??!1,hasServerMentions:!!o,inputDisabled:nc(),sendDisabled:sc()}))return;let s=ls.isStreaming()?bo():"block";if("defer-one"===s&&!e.pending)return Xr.getState().pendingSubmission?void pu("One message is already queued. Edit or remove it first."):void function(e){let t=Xr.getState(),r=Gr?.hasAttachments()??!1,o=r?[...Gr.getContentParts()]:[];r&&e.sendText&&o.push(fn(e.sendText)),xo(Ma({text:e.sendText,contentParts:o.length?o:void 0,mentionRefs:[...Yr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:au(),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&&du(),r&&Gr.clearAttachments(),Yr?.clear(),eo(),t.quote&&go(void 0),hl(),Yo.release(),en(),Dr("Message queued. It sends when the response finishes.")}({intent:e,sendText:n,serverMentions:o});let i={text:n,mentionRefs:[...Yr?.getMentionRefs()??[],...o?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:au(),options:{...Xr.getState().selectedModelId&&{selectedModelId:Xr.getState().selectedModelId},...Xr.getState().activeModeIds.length>0&&{activeModeIds:[...Xr.getState().activeModeIds]},...Xr.getState().quote&&{quote:{...Xr.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(i.options={...e.pending.options},i.contentSegments=e.pending.contentSegments,i.mentionRefs=[...e.pending.mentionRefs],i.viaVoice=e.pending.viaVoice);let d=()=>{if(a?.length)return[...a];if(!Gr?.hasAttachments())return;let e=[...Gr.getContentParts()];return i.text&&e.push(fn(i.text)),e};i.contentParts=d();let c=()=>{js(),ye()&&(we||(l.launcher?.composerBar?.expandOnSubmit??1)&&rc(!0,"auto"));let t=Yr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,o]=await Promise.allSettled([e.finalize(),t.finalize()]),n=[];return"fulfilled"===r.status?n.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===o.status?n.push(o.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",o.reason),(e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Ep(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}))(n)}}:e:t)(t,o),n=d();!1!==e.consumeDraft&&du();let a={selectedModelId:i.options.selectedModelId,activeModeIds:i.options.activeModeIds},c="interrupt"===s;c&&ls.cancel(),ls.sendMessage(i.text,{contentParts:n,mentions:r??void 0,contentSegments:i.contentSegments,viaVoice:i.viaVoice,composerOptions:a,...i.options.quote&&{quote:i.options.quote},...c&&{interrupt:!0}}),Gr?.hasAttachments()&&Gr.clearAttachments(),t&&Yr?.clear(),eo();let p=Xr.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,l.composer?.modes);u.length!==p.length&&co(u),Xr.getState().quote&&go(void 0),hl(),Yo.release(),en()},p=l.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;lu=u;let h=zp,m=e=>{u.signal.aborted||h!==zp||(lu===u&&(lu=null),"error"===e.status?(e=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",e)})(e.error):"proceed"===e.status&&c())},g=Ta(p,i,u.signal);if(g instanceof Promise)return Xr.setPreparing(!0),g.then(m).finally(()=>{h===zp&&Xr.setPreparing(!1)});m(g)};An={regenerate:function(e){if(ls.isStreaming())return;let t=Ln(ls.getMessages(),e);t&&(js(),ls.resubmitFrom(t,{reason:"retry"})&&vd())},edit:function(e){if(!0!==l.messageActions?.showEdit)return;let t=ls.getMessages().find(t=>t.id===e);t&&Bn(t)&&En(ls.getMessages(),e)&&zs!==e&&(js(),zs=e,qs=ha({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=qs;zs=null,qs=null,r?.destroy(),Ls.delete(e),ls.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?vd():$d(St,ls.getMessages(),Le)}(e,t),onCancel:()=>js()}),Ls.delete(e),$d(St,ls.getMessages(),Le),qs.focus())},quote:e=>{let t=ls.getMessages().find(t=>t.id===e)?.content?.trim();t&&(go({text:t,messageId:e}),It?.focus())}};let mu=async e=>{if(Lu())return void(l.voiceRecognition?.dictation?.showSend&&!sc()&&Ru(!0));if(su)return;su=!0;let t=++iu;try{await uu({resolveInlineCommand:!0,...e})}finally{t===iu&&(su=!1)}};function gu(e){sc()||(du(),fu(e,{consumeDraft:!1}))}let fu=(e,t)=>{if(su)return;su=!0;let r=++iu,o=()=>{r===iu&&(su=!1)};try{let r=uu({...t,overrideText:e});r instanceof Promise?r.finally(o):o()}catch(e){throw o(),e}},bu=e=>{e.preventDefault(),ls.isStreaming()?(ls.cancel(),qe?.reset(),Ve?.update()):su||mu()},yu={...Ti},vu=!1,wu=()=>{yu={...Ti}},xu=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(xt)&&(lu?(lu.abort(),lu=null,e.preventDefault(),e.stopImmediatePropagation()):ls.isStreaming()&&(ls.cancel(),qe?.reset(),Ve?.update(),wu(),e.preventDefault(),e.stopImmediatePropagation()))},Cu=null,Su=null,ku=!1,Au=null,Mu=null,Iu=0,Tu=Object.freeze({phase:"idle",recordingId:0,transcript:"",interimTranscript:"",error:null,audioLevel:null}),Eu=()=>!!l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&Hu(),Lu=()=>ku||["recording","processing"].includes(Cu?.getState().phase??"idle"),Bu=()=>{if(++Iu,ku=!1,Mu=null,Au){Au=null,Su?.element.remove(),Su=null;let{audioLevel:e,...t}=Tu;return U.emit("dictation:state",{...t,instanceId:n,timestamp:Date.now()}),!0}return Cu?.cancel()??!1},Ru=(e=!1)=>ku?(Mu=e||!0===Mu,!0):Cu?.finish(e)||e&&Cu?.send()||!1,Pu=()=>{if(nc()||ls.isStreaming()||Lu()||ac())return!1;let e=l.voiceRecognition;if(!1===e?.enabled)return!1;let t=e?.dictation?.provider??("custom"===e?.provider?.type?{type:"custom",custom:e.provider.custom}:{type:"browser",browser:e?.provider?.browser});if("browser"===t.type&&!qu()||"custom"===t.type&&!t.custom)return!1;!we&&ve()&&rc(!0,"system"),Au&&Bu();let r={text:It.value,logicalEnd:Yr?.getInlineInput()?.getLogicalText().length??null,readOnly:It.readOnly,contentEditable:It.getAttribute("contenteditable")};ku=!0,Mu=null;let o=++Iu;return Je().then(a=>{o===Iu&&(ku=!1,Cu??=a.createDictationSession({instanceId:n,getTextarea:()=>It,getFooter:()=>ar,getConfig:()=>l,plugins:T,getInlineInput:()=>Yr?.getInlineInput(),isInputDisabled:nc,isSendBlocked:sc,syncText:Zr,onSend:()=>{mu({viaVoice:!0})},rendererDeps:{renderLucideIcon:Ee,attachTooltip:Qa},onState:(e,t)=>{let{audioLevel:r,...o}=e;U.emit("dictation:state",{...o,instanceId:n,timestamp:Date.now()}),Li.active="recording"===e.phase,Du(t?"recording"===e.phase?"recording":"processing":"idle"),Fi("system")}}),ls.stopSpeaking(),Cu.start(t,{autoSend:!Hu(),pauseDuration:e?.pauseDuration},r),null!==Mu&&(Cu.finish(Mu),Mu=null))}).catch(e=>{if(o!==Iu)return;ku=!1;let t=e instanceof Error?e.message:"Unable to load dictation.";Au=Object.freeze({...Tu,recordingId:o,phase:"error",error:t});let r=st("div","persona-dictation");r.setAttribute("role","alert"),r.textContent=t;let a=document.createElement("button");a.type="button",a.textContent="Dismiss dictation",a.addEventListener("click",()=>{Bu()}),r.append(a),Su={element:r},ar.append(r);let{audioLevel:s,...i}=Au;U.emit("dictation:state",{...i,instanceId:n,timestamp:Date.now()})}),!0};Ua.push(()=>{++Iu,Cu?.destroy(),Su?.destroy?.(),Su?.element.remove()}),l.voiceRecognition?.dictation&&Je().catch(()=>{});let Nu,$u=null,Wu=!1,Hu=()=>"review"===l.voiceRecognition?.completionBehavior;function Du(e){mr&&xs(mr,l,e,ls.getVoiceInterruptionMode()),ar?.setAttribute("data-persona-voice-state",e),"recording"===e?function(){Fu=!0;let e=e=>{Fu&&(Ou??=e.createVoiceLevelIndicator({targets:()=>[gr??mr?.parentElement,ar].filter(e=>!!e),sample:()=>{let e=Cu?.getState();return"recording"===e?.phase?{level:e.audioLevel,fallback:!1}:{level:B?ls.getVoiceLevel():null,fallback:!0}}}),Ou.start())},t=Ge();t?e(t):Je().then(e,()=>{})}():zu()}let Ou,Fu=!1;function zu(){Fu=!1,Ou?.stop()}let qu=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ju=(e="user")=>{if(Wu||ls.isStreaming())return;let t=qu();if(!t)return;$u=new t;let r=$u,o=l.voiceRecognition??{},n=o.pauseDuration??2e3;$u.continuous=o.provider?.browser?.continuous??!0,$u.interimResults=!0,$u.lang=o.provider?.browser?.language??"en-US";let a,s=It.value,i=(e,t)=>{let o=o=>{$u===r&&Wu&&(a??=o.createBrowserRecognitionHandlers({textarea:It,initialText:s,pauseDuration:n,isActive:()=>$u===r&&Wu,syncText:Zr,stop:_u,review:Hu,submit:()=>{mu({viaVoice:!0})}}),Nu=()=>a?.dispose(),a[e](t))},i=Ge();i?o(i):Je().then(o,()=>{$u===r&&_u("system")})};r.onresult=e=>i("result",e),r.onerror=e=>i("error",e),r.onend=e=>i("end",e);try{$u.start(),Wu=!0,Li.active=!0,"system"!==e&&(Li.manuallyDeactivated=!1),Fi(e),zi(),en(),mr&&(mr.classList.add("persona-voice-recording"),Du("recording"),mr.setAttribute("aria-label","Stop voice recognition"))}catch{_u("system")}},_u=(e="user")=>{if(Wu){if(Wu=!1,Nu?.(),Nu=void 0,$u){try{$u.stop()}catch{}$u=null}Li.active=!1,Fi(e),$i||zi(),en(),mr&&(mr.classList.remove("persona-voice-recording"),Du("idle"),mr.setAttribute("aria-label",l.voiceRecognition?.tooltipText??"Start voice recognition"))}},Uu=null,Vu=e=>{let t=t=>{Uu??=t.createMicStateStyles({mic:()=>mr,config:()=>l,session:()=>ls,setMicState:Du}),e(Uu)},r=jt();r?t(r):qt().then(t,()=>{})},Ku=()=>Vu(e=>e.recording()),Qu=()=>Vu(e=>e.processing()),Ju=()=>Vu(e=>e.speaking()),Gu=()=>Vu(e=>e.reset()),Yu=()=>{if(!nc())if(Eu())"recording"===Cu?.getState().phase?Cu.finish():Lu()||Pu();else if(_t(l.voiceRecognition?.provider)){let e=ls.getVoiceStatus(),t=ls.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;if("cancel"===t&&("processing"===e||"speaking"===e))return void ls.stopVoicePlayback();if(ls.isBargeInActive())return ls.stopVoicePlayback(),void ls.deactivateBargeIn().then(()=>{Li.active=!1,Li.manuallyDeactivated=!0,zi(),Fi("user"),Gu()});ls.toggleVoice().then(()=>{Li.active=Ni(),Li.manuallyDeactivated=!Li.active,zi(),Fi("user"),Li.active?Ku():Gu()})}else if(Wu){let e=It.value.trim();Li.manuallyDeactivated=!0,zi(),_u("user"),e&&!Hu()&&mu()}else Li.manuallyDeactivated=!1,zi(),ju("user")};Co=Yu;let Xu=()=>ls.prewarmVoice(),Zu=()=>{let e=l.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!l.clientToken&&"hover"))},eh=e=>{"hover"===Zu()&&mr?.contains(e.target)&&Xu()},th=["pointerover","pointerdown","focusin"];th.forEach(t=>e.addEventListener(t,eh));let rh,oh,nh=null,ah=()=>{let e=oh;oh=void 0;try{"function"==typeof e&&e()}catch{}},sh=()=>{let t=Zu(),r="function"==typeof t&&mr?t:void 0,o=r?mr:null;if((r!==rh||o!==nh)&&(ah(),rh=r,nh=o,r&&o))try{oh=r({warm:Xu,micButton:o,mount:e})}catch{}};sh(),Ua.push(()=>{th.forEach(t=>e.removeEventListener(t,eh)),ah()}),mr&&Ua.push(()=>{_t(l.voiceRecognition?.provider)?(ls.isVoiceActive()&&ls.toggleVoice(),Gu()):_u("system")});let ih=U.on("assistant:complete",()=>{let e=Xr.getState().pendingSubmission,t=zp,r=xe;e&&setTimeout(()=>{Se(r)&&!ls.isStreaming()&&t===zp&&Xr.getState().pendingSubmission===e&&function(){let e=Xr.getState().pendingSubmission;e&&(xo(void 0),fu(e.text,{consumeDraft:!1,pending:e}))}()},0)});Ua.push(ih);let lh=U.on("assistant:complete",()=>{if(!Ri||Li.active||Li.manuallyDeactivated||"assistant"===Ri&&!Li.lastUserMessageWasVoice)return;let e=zp,t=xe;setTimeout(()=>{Se(t)&&e===zp&&!Li.active&&!Li.manuallyDeactivated&&(_t(l.voiceRecognition?.provider)?ls.toggleVoice().then(()=>{Se(t)&&e===zp&&(Li.active=ls.isVoiceActive(),Fi("auto"),ls.isVoiceActive()&&Ku())}):ju("auto"))},600)});Ua.push(lh);let dh=!1,ch=e=>{e.persisted&&!dh&&(dh=!0,$i=!0,ke(),zp++,iu++,su=!1,lu?.abort(),lu=null,Xr.setPreparing(!1),Bu(),_u("system"),ls.cancel(),ls.stopSpeaking(),ls.cleanupVoice(),qe?.reset(),Ve?.update())},ph=e=>{e.persisted&&dh&&(dh=!1,$i=!1,!0===l.voiceRecognition?.enabled&&Ut(l)&&ls.setupVoice())};window.addEventListener("pagehide",ch),window.addEventListener("pageshow",ph),Ua.push(()=>{window.removeEventListener("pagehide",ch),window.removeEventListener("pageshow",ph)});let uh=U.on("action:resubmit",()=>{Ae()});Ua.push(uh);let hh=()=>{rc(!we,"user")},mh=null,gh=null;if(le&&!ye()){let{instance:e,element:t}=Nd({config:l,plugins:T,onToggle:hh});mh=e,e||(gh=t)}mh?e.appendChild(mh.element):gh&&e.appendChild(gh),Xd(),As(),Dc(),Hc(),cc(ls.isStreaming()),ld()||("follow"===wr()?Xl(!0):sd()),(()=>{if(!1===l.voiceRecognition?.enabled||l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&"review"===l.voiceRecognition.completionBehavior)return;let e=Ap(Q.voiceState),t=!!e.active,r=Number(e.timestamp??0);if(Li.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4){let e=xe;setTimeout(()=>{Se(e)&&(Li.active||(Li.manuallyDeactivated=!1,_t(l.voiceRecognition?.provider)?ls.toggleVoice().then(()=>{Se(e)&&(Li.active=Ni(),Fi("restore"),Li.active?Ku():(zi(),pu("Tap the mic to resume your voice call",1e4)))}):ju("restore")))},_t(l.voiceRecognition?.provider)?0:1e3)}})(),ue&&(!le||ye()?setTimeout(()=>pc(),0):we&&setTimeout(()=>pc(),200));let fh=null,bh=()=>{fh&&(fh.disconnect(),fh.observe(ar),fh.observe(xt),fh.observe(Nt),fh.observe(Br))},yh=Or(),vh=()=>{if(ye())return Vr(),void Xd();let t=il(l),r=l.launcher?.sidebarMode??!1,o=e.ownerDocument.defaultView??window,n=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640,s=o.innerWidth<=a,i=n&&s&≤try{if(i)return Nn(),void(Hn=Na());let e=!1;be&&(be=!1,Nn(),e=!0);let o=Na();if(!e&&o!==Hn&&(Nn(),e=!0),Hn=o,e&&ia(),!le&&!t)return ft.style.height="",void(r||(gt.style.width=kd(l),ft.style.width="100%",ft.style.maxWidth="100%"));if(!r&&!t){let e=Sd(l);ft.style.width=e.width,ft.style.maxWidth=e.maxWidth}Ba(),_a()}finally{Vr(),Jr();let t=Or();if(t!==yh&&(yh=t,Mc(),As()),Xd(),we&&le){let t=(e.ownerDocument.defaultView??window).innerWidth<=(l.launcher?.mobileBreakpoint??640),r=l.launcher?.sidebarMode??!1,o=l.launcher?.mobileFullscreen??!0,n=il(l)&&o&&t,a=r||o&&t&&le||n;if(a&&!Ka){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!Va&&(Va=ol(r,l.launcher?.zIndex??1e5)),Ka=sl(e.ownerDocument)}else a||(Va?.(),Va=null,Ka?.(),Ka=null)}}};vh();let wh=e.ownerDocument.defaultView??window;if(wh.addEventListener("resize",vh),Ua.push(()=>wh.removeEventListener("resize",vh)),typeof ResizeObserver<"u"){fh=new ResizeObserver(()=>{Jr(),Ql()}),bh(),Ua.push(()=>{fh?.disconnect(),fh=null});let e=new ResizeObserver(()=>{Gp()});e.observe(xt),Ua.push(()=>e.disconnect())}wh.addEventListener("resize",Gp),Ua.push(()=>wh.removeEventListener("resize",Gp)),Qs=Ct.scrollTop;let xh=Kt(Ct),Ch=()=>{Fa();let e=Ct.scrollTop,t=Kt(Ct),r=t<xh;if(xh=t,td.interrupted||!xr())return Qs=e,void Ql();let{action:o,nextLastScrollTop:n}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-o;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&n&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!n?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Ks.isFollowing(),currentScrollTop:e,lastScrollTop:Qs,nearBottom:Qt(Ct,24),userScrollThreshold:4,isAutoScrolling:td.active||Gs||Ys||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Qs=n,"resume"!==o||id()?"pause"===o?Jl():Ql():Gl()};if(Ct.addEventListener("scroll",Ch,{passive:!0}),Ua.push(()=>Ct.removeEventListener("scroll",Ch)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{Ad(),(()=>{if(xr()){if(Ql(),!Ks.isFollowing()||Qt(Ct,1))return;Xl(!Es)}else{if(Zs&&Zs.initialSpacerHeight>0&&!Zs.pending){let e=Ct.scrollHeight-Zs.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:Zs.initialSpacerHeight,contentHeightAtAnchor:Zs.contentHeightAtAnchor,currentContentHeight:e});t!==Zs.spacerHeight&&ud(t)}Ql()}})(),Fa(),Wr(St)});e.observe(St),e.observe(Ct),Ua.push(()=>e.disconnect())}let Sh=()=>{xr()&&Ks.isFollowing()&&id()&&Jl()},kh=Ct.ownerDocument;kh.addEventListener("selectionchange",Sh),Ua.push(()=>{kh.removeEventListener("selectionchange",Sh)});let Ah=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Mh=e=>{Ah.has(e.key)&&(ci(),Sr()&&xr()&&Ks.isFollowing()&&Jl())},Ih=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(ci(),Sr()&&xr()&&Ks.isFollowing()&&Jl())};Ct.addEventListener("keydown",Mh),Ct.addEventListener("focusin",Ih),Ua.push(()=>{Ct.removeEventListener("keydown",Mh),Ct.removeEventListener("focusin",Ih)});let Th=e=>{if(td.interruptedBy(e))return void ci();if(0!==e.deltaY&&ci(),!xr())return;let t=function(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}({following:Ks.isFollowing(),deltaY:e.deltaY,nearBottom:Qt(Ct,24),resumeWhenNearBottom:!0});"pause"===t?Jl():"resume"===t&&!id()&&Gl()};Ct.addEventListener("wheel",Th,{passive:!0}),Ct.addEventListener("touchmove",ci,{passive:!0}),Ct.addEventListener("pointerdown",ci,{passive:!0}),Ua.push(()=>{Ct.removeEventListener("touchmove",ci),Ct.removeEventListener("pointerdown",ci)}),Ua.push(()=>Ct.removeEventListener("wheel",Th)),Er.addEventListener("click",()=>{let e=Bl().filter(Ll).map(e=>e.getAttribute("data-message-id"));fd(),Hl=e,Cl(),Ks.pause(),td.start(l),Ql()}),Ua.push(()=>td.destroy()),Ua.push(()=>Tr.destroy()),Ua.push(()=>{Cl(),fd()});let Eh=()=>{Zt&&(ds&&=(Zt.removeEventListener("click",ds),null),ve()?(Zt.style.display="",ds=()=>{rc(!1,"user")},Zt.addEventListener("click",ds)):Zt.style.display="none")};Eh(),(()=>{let{clearChatButton:e}=wt;e&&e.addEventListener("click",()=>{let e=fp;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{l.debug&&console.warn("[AgentWidget] New conversation failed:",e)});ls.clearMessages(),l.layout?.topFade&&(Ct.scrollTop=0),Ct.removeAttribute("data-persona-top-fade"),Ls.clear(),Gl(),Po(wt.composerOverlay);try{localStorage.removeItem(wp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${wp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==wp)try{localStorage.removeItem(l.clearChatHistoryStorageKey),l.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${l.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let t=new CustomEvent("persona:clear-chat",{detail:{instanceId:n,timestamp:(new Date).toISOString()}});window.dispatchEvent(t),hl(),V?.clear&&Ji(()=>V.clear(),"[AgentWidget] Failed to clear storage adapter:"),Q={},ie.syncFromMetadata(),Up(ls.getActiveConversationId(),!0,!1),du(),hl(),xo(void 0),go(void 0),js(),ze?.clear(),qe?.reset(),Ve?.update()})})();let Lh=[["keydown",e=>{if(It&&!nc()&&(e.isComposing||!Yr?.handleKeydown(e))){if(!(!1===l.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===It.selectionStart&&0===It.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!n)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:o}}}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:ls.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:It.value,atStart:t,state:yu});if(yu=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!It)return;vu=!0,It.value=e,It.dispatchEvent(new Event("input",{bubbles:!0})),vu=!1;let t=It.value.length;It.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,o=t.submitKey??"enter";return"none"!==o&&("mod-enter"===o?r:r||!Ca(t))}(e,{submitKey:l.composer?.submitKey,insertNewlineOnTouchEnter:l.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(It)}))if(ls.isStreaming()){if(e.preventDefault(),"block"===bo()||su||sc())return;wu(),mu()}else su||sc()?e.preventDefault():(wu(),e.preventDefault(),Bt.click())}}],["input",e=>{vu||(Is(),e.isComposing||Yr?.handleInput(e.inputType??void 0),wu())}],["input",Zr],["input",eo],["keyup",eo],["paste",async e=>{if(!0!==l.attachments?.enabled||!Gr||nc())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 o=Sp[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${o}`,{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 Gr.handleFiles(t))}],["focus",()=>Yr?.prefetch()]],Bh=e=>{if(e)for(let[t,r]of Lh)No?.addListener(e,t,r)},Rh=()=>{No&&(No.addListener(No.form,"submit",bu),No.addListener(No.footer,"click",eo),Bh(It),mr&&No.addListener(mr,"click",Yu),sh())};Rh();let Ph=()=>{Yr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of Lh)No?.removeListener(e,t,r)})(t),It=e,No&&(No.input=e),Bh(e),$o(),dc(),Zr(),Cu?.refresh()})};Ph();let Nh=!1;function $h(){if(!Nh){Nh=!0;try{ln.detach(["footer-top","footer-bottom","composer-start","composer-end","composer-before-send"]);let e=It?.value??"",t=ar.ownerDocument??document,r=!!It&&t.activeElement===It;zu(),No?.destroy(),No=null,Yr?.destroy(),Yr=null;let o=null,n=()=>(o=ye()?Wl({config:l}):$l({config:l}),o.footer),a=Lo(n)??n();mt.replaceComposer(a),ar=mt.composer.footer,!1===l.layout?.showFooter&&(ar.style.display="none");let s=null!==o&&a===o.footer;Eo=!s,hr=s?o.setSendButtonMode:()=>{},To(ar),Wo(ar),Fo(),qo(),jo(),Ph(),Qo(),Jo(),Go(),Rh();let i=is.indexOf(es);if(es.destroy(),es=gl(Mt),i>=0&&(is[i]=es),ln.remount(),It&&(It.value=e),Zr(),eo(),Dc(),As(),cc(ls.isStreaming()),"transient"===l.statusIndicator?.mode&&!ye()){let e=ls.getStatus();ht(Pt,ut(e),l.statusIndicator,e)}Li.active&&Du("recording"),Cu?.refresh(),Nn(),bh(),Vr(),en(),lc(),r&&It?.focus()}finally{Nh=!1}}}let Wh=e.ownerDocument??document;Wh.addEventListener("keydown",xu,!0);let Hh=()=>{cl()},Dh=()=>{"hidden"===Wh.visibilityState&&cl()};typeof window<"u"&&(window.addEventListener("pagehide",Hh),Wh.addEventListener("visibilitychange",Dh),Ua.push(()=>{window.removeEventListener("pagehide",Hh),Wh.removeEventListener("visibilitychange",Dh)}));let Oh="persona-attachment-drop-active",Fh=0,zh=()=>{Fh=0,xt.classList.remove(Oh)},qh=()=>!0===l.attachments?.enabled&&null!==Gr&&!nc(),jh=e=>{kp(e.dataTransfer)&&qh()&&(Fh++,1===Fh&&xt.classList.add(Oh))},_h=e=>{kp(e.dataTransfer)&&qh()&&(Fh--,Fh<=0&&zh())},Uh=e=>{kp(e.dataTransfer)&&qh()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},Vh=e=>{if(!kp(e.dataTransfer)||!qh())return;e.preventDefault(),e.stopPropagation(),zh();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&Gr.handleFiles(t)};xt.addEventListener("dragenter",jh,!0),xt.addEventListener("dragleave",_h,!0),e.addEventListener("dragover",Uh,!0),e.addEventListener("drop",Vh,!0);let Kh=e.ownerDocument,Qh=e=>{qh()&&e.preventDefault()},Jh=e=>{qh()&&e.preventDefault()};Kh.addEventListener("dragover",Qh),Kh.addEventListener("drop",Jh),Ua.push(()=>{No?.destroy(),No=null,zu(),Ko=!0,_o?.destroy(),_o=null,ho?.destroy(),ho=null,mo?.destroy(),mo=null,vo?.destroy(),vo=null,uo=null,cl(),nl.destroy(),cu&&clearTimeout(cu),js(),lu?.abort(),lu=null,fp?.clearConversationOpenPending(),Up(void 0,!1),Gr?.destroy(),Gr=null,Xr.destroy(),Wh.removeEventListener("keydown",xu,!0),Yr?.destroy()}),Ua.push(()=>{xt.removeEventListener("dragenter",jh,!0),xt.removeEventListener("dragleave",_h,!0),e.removeEventListener("dragover",Uh,!0),e.removeEventListener("drop",Vh,!0),Kh.removeEventListener("dragover",Qh),Kh.removeEventListener("drop",Jh),zh()}),Ua.push(()=>{ls.cancel()}),mh?Ua.push(()=>{mh?.destroy()}):gh&&Ua.push(()=>{gh?.remove()}),r?.registerHostMove?.(t=>{let r=Ct.scrollTop,o=xr()&&Ks.isFollowing(),n=Ct.getBoundingClientRect().top,a=!o&&Ct.clientHeight>0?Array.from(St.querySelectorAll("[data-message-id]")).find(e=>e.getBoundingClientRect().bottom>n):void 0,s=a?a.getBoundingClientRect().top-n:0;Cl(),t(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),vh(),nt(),o?Ct.scrollTop=Kt(Ct):a?Ct.scrollTop+=a.getBoundingClientRect().top-Ct.getBoundingClientRect().top-s:Ct.scrollTop=r,!o&&!ii&&vd(),Qs=Ct.scrollTop,xh=Kt(Ct),Fa(),Ql(),e.dispatchEvent(new Event("persona:internal:host-moved"))});let Gh=e=>{!we&&ve()&&rc(!0,"system"),St.querySelector(".persona-feedback-container")?.remove();let t=e();St.appendChild(t),t.scrollIntoView({behavior:"smooth",block:"end"})},Yh=!1,Xh=[],Zh=!1,em=()=>{let e=Xh;Xh=[],Zh=!0;try{for(let t of e)tm.update(t)}finally{Zh=!1}},tm={get ready(){return u.ready},get instanceId(){return n},update(t){if(!Zh){Xh.push(t);let e=Xh.reduce(Wc,{...l,features:A}),r=Vt(kc(e));if(r.length)return void u.prepare(r,em,Yh);if(Xh.length>1)return void u.prepare([],em,Yh);Xh=[]}r?.diagnostics||Kc(h,t);let o=t.voiceRecognition;o&&(!1===o.enabled||o.dictation?.provider&&o.dictation.provider!==l.voiceRecognition?.dictation?.provider||o.provider?.custom&&o.provider.custom!==l.voiceRecognition?.provider?.custom)&&Bu();let n=!0===l.future?.v5Defaults,a=l.messageActions,s=l.layout?.messages,i=l.colorScheme,d=l.iterationDisplay,c=l.features?.showReasoning,p=l.features?.showToolCalls,m=l.features?.toolCallDisplay,g=l.features?.reasoningDisplay,f=()=>JSON.stringify([l.features?.userMessageCollapse,l.copy?.showMoreLabel,l.copy?.showLessLabel]),b=f(),y=l.features?.streamAnimation?.type,v=!0===l.features?.history?.enabled,w=l.features?.history?.provider,x=l.getIdentityProof,C=l.clientToken,k=l.contextMentions;l=Wc({...l,features:A},t),A=l.features,l=kc(l),S(),Nn(),$a(),l.colorScheme!==i&&Ga();let M=Rc.getForInstance(l.plugins);T.length=0,T.push(...M),Np(),le=l.launcher?.enabled??!0,ce=l.launcher?.autoExpand??!1,Be=l.features?.showReasoning??!0,Re=l.features?.showToolCalls??!0,td.cancel();let I=wr();Ne=l.features?.scrollBehavior??{},I!==wr()&&(fd(),Gl()),vi(),Ql();let E=Pe;if(Pe=l.features?.showEventStreamToggle??!1,Pe&&!E){if(ze||(et(),ls.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ze(e,t)})),!Io&&nr){let e=l.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:"");Io=st("button",t),Io.style.width="28px",Io.style.height="28px",Io.style.color=kl.actionIconColor,Io.type="button",Io.setAttribute("aria-label","Event Stream"),Io.title="Event Stream";let r=ne(de,"18px","currentColor",1.5);r&&Io.appendChild(r);let o=wt.clearChatButtonWrapper,n=wt.closeButtonWrapper,a=o||n;a&&a.parentNode===nr?nr.insertBefore(Io,a):nr.appendChild(Io),Io.addEventListener("click",()=>{Ke?Mo():Ao()})}}else!Pe&&E&&(Mo(),Ve?.destroy(),Ve=null,Io&&=(Io.remove(),null),ze?.clear(),Oe?.destroy(),ze=null,Oe=null,qe?.reset(),qe=null,_e=null);if(!1===l.launcher?.enabled&&mh&&(mh.destroy(),mh=null),!1===l.launcher?.enabled&&gh&&(gh.remove(),gh=null),!1!==l.launcher?.enabled&&!mh&&!gh){let{instance:t,element:r}=Nd({config:l,plugins:T,onToggle:hh});mh=t,t||(gh=r),e.appendChild(r)}mh&&mh.update(l),Hp(),or&&void 0!==l.launcher?.subtitle&&(or.textContent=l.launcher.subtitle);let L=l.layout?.header;if(L?.layout!==fe&&nr){let e=L?Pl(l,L,{showClose:ve(),onClose:()=>rc(!1,"user")}):Il({config:l,showClose:ve(),onClose:()=>rc(!1,"user")});mt.replaceHeader(e),nr=mt.header.element,er=mt.header.iconHolder,tr=mt.header.headerTitle,or=mt.header.headerSubtitle,Zt=mt.header.closeButton,fe=L?.layout,Hp()}else if(L){if(er&&(er.style.display=!1===L.showIcon?"none":""),tr&&(tr.style.display=!1===L.showTitle?"none":""),or&&(or.style.display=!1===L.showSubtitle?"none":""),Zt){let e=ve()&&!1!==L.showCloseButton;Zt.style.display=e?"":"none"}if(wt.clearChatButtonWrapper){let e=L.showClearChat;if(void 0!==e){wt.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=wt;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let B=ss(l);nr&&(nr.style.display=B?"":"none");let R=!1!==l.layout?.showFooter;ar&&(ar.style.display=R?"":"none"),Vr(),Ql(),le===ge?ce!==me&&rc(ce,"auto"):le?rc(ce,"auto"):(we=!0,Xd()),me=ce,ge=le,vh(),Eh();let P=JSON.stringify(l.messageActions)!==JSON.stringify(a),N=JSON.stringify(l.layout?.messages)!==JSON.stringify(s)||l.layout?.messages?.renderAssistantMessage!==s?.renderAssistantMessage||l.layout?.messages?.renderUserMessage!==s?.renderUserMessage,$=l.iterationDisplay!==d,W=(l.features?.showReasoning??!0)!==(c??!0)||(l.features?.showToolCalls??!0)!==(p??!0)||JSON.stringify(l.features?.toolCallDisplay)!==JSON.stringify(m)||JSON.stringify(l.features?.reasoningDisplay)!==JSON.stringify(g)||f()!==b;(!0===l.future?.v5Defaults!==n||"toolCall"in t||P||N||"loadingIndicator"in t||$||W||"turnActivity"in t||"loadingLabel"in t||"expansion"in t||"errorDisplay"in t||"theme"in t||"darkTheme"in t||"approval"in t||l.colorScheme!==i||"askUserQuestion"in(t.features??{})||"features"in t&&void 0===t.features)&&ls&&(Vs++,$d(St,ls.getMessages(),Le));let H=l.features?.streamAnimation?.type;if(H!==y&&H&&"none"!==H){let t=Xa(H,l.features?.streamAnimation?.plugins);t&&Xi(t,e)}let D=l.launcher??{},O=D.headerIconHidden??!1,F=l.layout?.header?.showIcon,z=O||!1===F,q=D.headerIconName,j=D.headerIconSize??"40px";if(er){let e=nr,t=e?.querySelector(".persona-flex-col");if(z)er.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(er.style.display="",er.style.height=j,er.style.width=j,e&&t&&(e.contains(er)?er.nextSibling!==t&&(er.remove(),e.insertBefore(er,t)):e.insertBefore(er,t)),q){let e=parseFloat(j)||24,t=Ee(q,.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))`,er.replaceChildren(t)):er.textContent=D.agentIconText??"💬"}else if(D.iconUrl){let e=er.querySelector("img");if(e)e.src=D.iconUrl,e.style.height=j,e.style.width=j;else{let e=document.createElement("img");e.src=D.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=j,e.style.width=j,er.replaceChildren(e)}}else{let e=er.querySelector("svg"),t=er.querySelector("img");(e||t)&&er.replaceChildren(),er.textContent=D.agentIconText??"💬"}let r=er.querySelector("img");r&&(r.style.height=j,r.style.width=j)}}let _=l.layout?.header?.showTitle,V=l.layout?.header?.showSubtitle;if(tr&&(tr.style.display=!1===_?"none":""),or&&(or.style.display=!1===V?"none":""),Zt){let e=ve()&&!1!==l.layout?.header?.showCloseButton;Zt.style.display=e?"":"none";let t=D.closeButtonPlacement??"inline",{closeButtonWrapper:r}=wt,o="top-right"===t,n=r?.classList.contains("persona-absolute");if(r&&o!==n)if(r.remove(),o){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=fp?.railColumn??xt;e.style.position="relative",e.appendChild(r)}else{let e=D.clearChat?.placement??"inline";r.className=(D.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",nr&&nr.appendChild(r)}xl(Zt,l,"close",{buttonSize:ye()?Zt.style.width:void 0,iconSize:ye()?Md:void 0});let a=D.closeButtonTooltipText??"Close chat",s=D.closeButtonShowTooltip??!0;Zt.setAttribute("aria-label",a),r&&Qa({anchor:Zt,trigger:r,text:()=>Zt?.getAttribute("aria-label")??a,enabled:s})}let{clearChatButton:K,clearChatButtonWrapper:Q}=wt;if(K){let e=D.clearChat??{},t=e.enabled??!0,r=l.layout?.header?.showClearChat,o=void 0===r?t:r,n=e.placement??"inline";if(Q){Q.style.display=o?"":"none";let{closeButtonWrapper:e}=wt;!ye()&&e&&!e.classList.contains("persona-absolute")&&(o?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===n,r=Q.classList.contains("persona-absolute");if(!ye()&&t!==r&&o){if(Q.remove(),t){Q.className="persona-absolute persona-top-4 persona-z-50",Q.style.right="48px";let e=fp?.railColumn??xt;e.style.position="relative",e.appendChild(Q)}else{Q.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Q.style.right="";let e=wt.closeButtonWrapper;nr&&e&&e.parentElement===nr?nr.insertBefore(Q,e):nr&&nr.appendChild(Q)}let e=wt.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(o){xl(K,l,"clear",{buttonSize:ye()?K.style.width:void 0,iconSize:ye()?Id:void 0});let t=e.tooltipText??"Clear chat",r=e.showTooltip??!0;K.setAttribute("aria-label",t),Q&&Qa({anchor:K,trigger:Q,text:()=>K?.getAttribute("aria-label")??t,enabled:r})}}let J=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Qc],G=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[Gc.message,Gc.messageAndClick];ie=Xc({parsers:J,handlers:G,getSessionMetadata:re,updateSessionMetadata:oe,emit:U.emit,captureResubmitGuard:()=>{let e=xe;return()=>Se(e)},documentRef:typeof document<"u"?document:null}),Le=Ip(l,ie,Te),(()=>{let e=jc();if(e&&Jc?.matches(e,He(),!1===l.persistState)||!e&&!Jc)return;Jc?.destroy(),Jc=e?_c(e):null;let t={...Yc};Jc?t.visitorStore=Jc:delete t.visitorStore,Yc=t,ls.setHistoryInternals(Yc)})(),ls.updateConfig(l),ou(),(!0===l.features?.history?.enabled!==v||l.features?.history?.provider!==w||l.getIdentityProof!==x||l.clientToken!==C)&&(fp?.closeHistory({restoreFocus:!1}),(l.getIdentityProof!==x||l.clientToken!==C)&&fp?.discardConversationContinuity(),fp?.installHistoryProvider()),fp?.syncHistoryChromeImpl(),Gp(),Rp()&&!fp&&Qp().catch(()=>{}),$d(St,ls.getMessages(),Le),As(),Dc(),(()=>{let e=Fr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==Pc||e.icon!==vc)&&Hc()})(),cc(ls.isStreaming()),k!==l.contextMentions&&$h();let Y=!0===l.voiceRecognition?.enabled&&!1!==l.voiceRecognition.showButton,X=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),Z=_t(l.voiceRecognition?.provider),ee=X||Z||"custom"===l.voiceRecognition?.dictation?.provider?.type;if(Y&&ee)if(mr&&gr){let e=l.voiceRecognition??{},t=mr.getAttribute("data-state");xs(mr,l,"recording"===t||"processing"===t||"speaking"===t?t:"idle",ls.getVoiceInterruptionMode());let r=e.tooltipText??"Start voice recognition",o=e.showTooltip??!1;"idle"===t&&mr.setAttribute("aria-label",r),gr&&Qa({anchor:mr,trigger:gr,text:()=>mr?.getAttribute("aria-label")??r,enabled:o}),gr.style.display="",mr.disabled=nc()||ls.isStreaming()&&!ac()}else{let e=Cs(l);if(e){mr=e.button,gr=e.wrapper;let t=cr&&cr.parentElement===lr?cr:null;lr?lr.insertBefore(gr,t):Rt?.appendChild(gr),No&&(No.micButton=mr),No?.addListener(mr,"click",Yu),mr.disabled=nc()||ls.isStreaming()&&!ac()}}else mr&&gr&&(gr.style.display="none",!0===l.voiceRecognition?.enabled&&ee||(_t(l.voiceRecognition?.provider)?ls.isVoiceActive()&&ls.toggleVoice():Wu&&_u()));if(sh(),!0===l.attachments?.enabled){if(br&&fr){br.style.display="";let e=l.attachments??{};yr&&(yr.accept=(e.allowedTypes??yn).join(","),yr.multiple=(e.maxFiles??4)>1)}else{let e=l.attachments??{};vr||(vr=st("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),vr.style.display="none",(It.parentElement??Rt).insertBefore(vr,It)),yr||(yr=document.createElement("input"),yr.type="file",yr.accept=(e.allowedTypes??yn).join(","),yr.multiple=(e.maxFiles??4)>1,yr.style.display="none",yr.setAttribute("aria-label","Attach files"),(It.parentElement??Rt).insertBefore(yr,It)),br=st("div","persona-send-button-wrapper"),fr=st("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${na} ${aa}`),fr.type="button",fr.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";fr.style.fontSize="18px",fr.style.lineHeight="1";let r=Ee(t,24,"currentColor",1.5);r?fr.appendChild(r):fr.textContent="📎",fr.addEventListener("click",e=>{e.preventDefault(),yr?.click()}),br.appendChild(fr);let o=e.buttonTooltipText??"Attach file";Qa({anchor:fr,trigger:br,text:()=>fr?.getAttribute("aria-label")??o}),ir?ir.append(br):Rt.appendChild(br),No&&(No.attachmentButton=fr,No.attachmentInput=yr??void 0,No.attachmentPreviews=vr??void 0),!Gr&&yr&&vr&&(Gr=no(),Gr.setPreviewsContainer(vr),No?.addListener(yr,"change",async()=>{Gr&&yr?.files&&(await Gr.handleFileSelect(yr.files),yr.value="")}))}if(xt.querySelector(".persona-attachment-drop-overlay")?.remove(),xt.appendChild(Tp(l.attachments?.dropOverlay)),fr){let e=l.attachments??{},t=e.buttonTooltipText??"Attach file";fr.setAttribute("aria-label",t),fr.textContent="";let r=Ee(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?fr.appendChild(r):fr.textContent="📎",br&&Qa({anchor:fr,trigger:br,text:()=>fr?.getAttribute("aria-label")??t})}}else br&&(br.style.display="none"),Gr&&Gr.clearAttachments(),xt.querySelector(".persona-attachment-drop-overlay")?.remove();let te=l.sendButton?.tooltipText??"Send message",ae=l.sendButton?.showTooltip??!1;vs(Bt,l),ls.isStreaming()||Bt.setAttribute("aria-label",te),lc(),cr&&Qa({anchor:Bt,trigger:cr,text:()=>Bt.getAttribute("aria-label")??te,enabled:ae});let se=new Set([Gr,...Array.from(Dp.values(),e=>e.attachments)]);for(let e of se)e?.updateConfig(ro());"plugins"in t&&Gr?.remountPreviews(vr),tn(),qa();let pe=fa(Xr.getState().activeModeIds,l.composer?.modes);Xr.setActiveModeIds(pe),io().length>0!=!!ho&&Jo(),ho?.render(pe,io()),uo?.repaint(),_o?_o.resolve():Qo();let ue=gi(l,ye());if(Da(),ue){St.style.maxWidth=ue,St.style.marginLeft="auto",St.style.marginRight="auto",St.style.width="100%",Dt.style.maxWidth=ue,Dt.style.marginLeft="auto",Dt.style.marginRight="auto",Dt.style.width="100%";for(let e of[Rt,Mt,vr,Pt])e&&(e.style.maxWidth=ue,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{St.style.maxWidth="",St.style.marginLeft="",St.style.marginRight="",St.style.width="",Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight="",Dt.style.width="";for(let e of[Rt,Mt,vr,Pt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let he=l.statusIndicator??{};if(ur(Pt,Rt,he),pr(Pt,he,ls?.getStatus()??"idle"),ls){let e=ls.getStatus();ht(Pt,(e=>"idle"===e?he.idleText??dt.idle:"connecting"===e?he.connectingText??dt.connecting:"connected"===e?he.connectedText??dt.connected:"error"===e?he.errorText??dt.error:"paused"===e?he.pausedText??dt.paused:"resuming"===e?he.resumingText??dt.resuming:dt[e])(e),he,e)}Pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let be="left"===he.align?"persona-text-left":"center"===he.align?"persona-text-center":"persona-text-right";Pt.classList.add(be),$o(),dc(),en(),ot(),on(l.layout?.slots??{}),Lu()&&nc()&&Bu(),Cu?.refresh(),ln.update(),nm()},open(){ve()&&rc(!0,"api")},close(){ve()&&rc(!1,"api")},toggle(){ve()&&rc(!we,"api")},reconnect(){ls.reconnectNow()},clearChat(){Bu(),Fs(),Fn=!1,i?.clear(),wn(),f.clear(),b.clear(),y.clear(),ls.clearMessages(),l.layout?.topFade&&(Ct.scrollTop=0),Ct.removeAttribute("data-persona-top-fade"),Ls.clear(),Gl();try{localStorage.removeItem(wp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${wp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==wp)try{localStorage.removeItem(l.clearChatHistoryStorageKey),l.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${l.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let e=new CustomEvent("persona:clear-chat",{detail:{instanceId:n,timestamp:(new Date).toISOString()}});window.dispatchEvent(e),hl(),V?.clear&&Ji(()=>V.clear(),"[AgentWidget] Failed to clear storage adapter:"),Q={},ie.syncFromMetadata(),Up(ls.getActiveConversationId(),!0,!1),du(),hl(),xo(void 0),go(void 0),js(),ze?.clear(),qe?.reset(),Ve?.update()},setMessage:e=>!(!It||Lu()||ls.isStreaming()||nc()||(!we&&ve()&&rc(!0,"system"),It.value=e,It.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(ls.isStreaming()||Lu()||sc())return!1;let t=e?.trim()||It.value.trim();return!!t&&(!we&&ve()&&rc(!0,"system"),It.value="",It.style.height="auto",Zr(),fu(t,{consumeDraft:!1}),!0)},getComposerState:()=>Xr.getState(),setComposerModes(e){co(function(e,t,r){let o=[];for(let n of e)o.includes(n)||(o=ga(o,n,t,r));return o}(e,so(),l.composer?.modeGroups))},setQuote(e){let t=e?.text?.trim();t&&go({...e,text:t})},clearQuote(){go(void 0)},startDictation:Pu,finishDictation:()=>Ru(),cancelDictation:()=>{let e=ku;return Bu()||e},sendDictation:()=>!(!l.voiceRecognition?.dictation?.showSend||sc())&&Ru(!0),getDictationState:()=>Au??Cu?.getState()??Tu,startVoiceRecognition:()=>!ls.isStreaming()&&!Lu()&&(Eu()&&!l.voiceRecognition?.dictation?.provider&&"runtype"!==l.voiceRecognition?.provider?.type?Pu():_t(l.voiceRecognition?.provider)?(ls.isVoiceActive()||ls.isBargeInActive()||(!we&&ve()&&rc(!0,"system"),Li.manuallyDeactivated=!1,zi(),ls.toggleVoice().then(()=>{Li.active=Ni(),zi(),Fi("user"),Li.active&&Ku()})),!0):!!Wu||!!qu()&&(!we&&ve()&&rc(!0,"system"),Li.manuallyDeactivated=!1,zi(),ju("user"),!0)),stopVoiceRecognition:()=>Lu()?Ru():_t(l.voiceRecognition?.provider)?!(!ls.isVoiceActive()&&!ls.isBargeInActive()||((ls.isBargeInActive()?ls.deactivateBargeIn():ls.toggleVoice()).then(()=>{Li.active=!1,Li.manuallyDeactivated=!0,zi(),Fi("user"),Gu()}),0)):!!Wu&&(Li.manuallyDeactivated=!0,zi(),_u("user"),!0),injectMessage:e=>(!we&&ve()&&rc(!0,"system"),ls.injectMessage(e)),injectAssistantMessage(e){!we&&ve()&&rc(!0,"system");let t=ls.injectAssistantMessage(e);return Me&&(Me=!1,Ie&&=(clearTimeout(Ie),null),Ae()),t},injectUserMessage:e=>(!we&&ve()&&rc(!0,"system"),ls.injectUserMessage(e)),injectSystemMessage:e=>(!we&&ve()&&rc(!0,"system"),ls.injectSystemMessage(e)),injectMessageBatch:e=>(!we&&ve()&&rc(!0,"system"),ls.injectMessageBatch(e)),injectComponentDirective:e=>(!we&&ve()&&rc(!0,"system"),ls.injectComponentDirective(e)),updateComponentProps:(e,t)=>ls.updateComponentProps(e,t),removeComponentMessage:e=>ls.removeComponentMessage(e),injectTestMessage(e){!we&&ve()&&rc(!0,"system"),ls.injectTestEvent(e)},connectStream:async(e,t)=>ls.connectStream(e,t),__pushEventStreamEvent(e){Pe&&(et(),Ze(e.type,e.payload))},showEventStream(){Pe&&Ao()},hideEventStream(){Ke&&Mo()},isEventStreamVisible:()=>Ke,listConversations:e=>ls.listConversations(e),getActiveConversationId:()=>ls.getActiveConversationId(),openConversation:(e,t)=>Jp(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus,busy:t?.busy})),startNewConversation:e=>Jp(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){Yp()},deleteConversation:e=>Jp(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Jp(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Jp(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Jp(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Jp(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Jc;if(!e)return null;let t=await e.get();return e===Jc?t:null},getHistoryIdentityStatus(){let e=fp?.historyProvider;return e?e.getIdentityStatus():Rp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>Rp()?Jp(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){fp?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>tt,showArtifacts(){Jd(l)&&(Fn=!1,jn=!0,$a(),In?.setMobileOpen(!0))},hideArtifacts(){Jd(l)&&(Fn=!0,$a())},upsertArtifact:e=>Jd(l)?("panel"===Mn(l.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Fn=!1,jn=!0),ls.upsertArtifact(e)):null,selectArtifact(e){Jd(l)&&ls.selectArtifact(e)},clearArtifacts(){Jd(l)&&ls.clearArtifacts()},getArtifacts:()=>ls?.getArtifacts()??[],getSelectedArtifactId:()=>ls?.getSelectedArtifactId()??null,focusInput:()=>!(le&&!we&&!ye()||!It||(It.focus(),0)),revealToolCall(e,t={}){let r=Array.from(Ct.querySelectorAll(".persona-tool-bubble[data-tool-call-id]")).find(t=>t.dataset.toolCallId===e);if(!r)return!1;let o=e=>Array.from(e.querySelectorAll('button[data-expand-header="true"]')).find(t=>t.closest(".persona-tool-bubble")===e),n=e=>{"false"===e?.getAttribute("aria-expanded")&&un(e)},a=[];for(let e=r.parentElement?.closest(".persona-tool-bubble");e;e=e.parentElement?.closest(".persona-tool-bubble"))a.unshift(e);a.forEach(e=>n(o(e)));let s=o(r);!1!==t.expand&&n(s),ci(),td.cancel(),Jl();let i=bn,l=s??r,d=()=>!Ce&&i===bn&&Ct.contains(l),c="function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,p=()=>{let e=Ur(l)-(Ct.clientHeight-l.offsetHeight)/2;return Math.max(0,Math.min(e,Kt(Ct)))},u=()=>{d()&&(c?(vl(),Gs=!0,Ct.scrollTop=p(),Qs=Ct.scrollTop,Gs=!1):ed(Ct,p,200,d))};window.clearTimeout(hn),u(),hn=window.setTimeout(()=>{hn=void 0,u()},200);let h=t.highlightMs??2e3;if(h>0){let e=r.dataset.messageId;window.clearTimeout(gn.get(e)),gn.set(e,window.setTimeout(()=>{gn.delete(e),vn()},h)),r.setAttribute("data-persona-revealed","")}return!0},async resolveApproval(e,t,r){let o=ls.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!o?.approval)throw Error(`Approval not found: ${e}`);if(!dr(o.approval))return ls.resolveApproval(o.approval,t,r);ls.resolveWebMcpApproval(o.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Ts();let r=ls?ls.getMessages():[];cs=t,ps=!0,us=fs(r),hs=bs(r),As(r)})(e)},clearFollowUpSuggestions(){Ts()},getMessages:()=>ls.getMessages(),getStatus:()=>ls.getStatus(),getPersistentMetadata:()=>({...Q}),updatePersistentMetadata(e){oe(e)},on:(e,t)=>U.on(e,t),off(e,t){U.off(e,t)},isOpen:()=>ve()&&we,isVoiceActive:()=>Li.active,toggleReadAloud(e){ls.toggleReadAloud(e)},stopReadAloud(){ls.stopSpeaking()},getReadAloudState:e=>ls.getReadAloudState(e),onReadAloudChange:e=>ls.onReadAloudChange(e),getState:()=>({open:ve()&&we,launcherEnabled:le,voiceActive:Li.active,streaming:ls.isStreaming()}),showCSATFeedback(e){Gh(()=>yp({onSubmit:async(t,r)=>{ls.isClientTokenMode()&&await ls.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},showNPSFeedback(e){Gh(()=>vp({onSubmit:async(t,r)=>{ls.isClientTokenMode()&&await ls.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},submitCSATFeedback:async(e,t)=>ls.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>ls.submitNPSFeedback(e,t),destroy(){Ce=!0,ke(),u.destroy(),ln.destroy(),e.removeEventListener("click",dn),cp(),Ua.forEach(e=>e()),null!=Zc&&(clearInterval(Zc),Zc=null),i?.destroy(),s?.destroy(),wn(),f.clear(),b.clear(),y.clear(),U.dispose(),gt.remove(),vt?.remove(),mh?.destroy(),gh?.remove(),ds&&Zt.removeEventListener("click",ds)}};if((r?.debugTools||l.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:tm,getMessages:tm.getMessages,getStatus:tm.getStatus,getMetadata:tm.getPersistentMetadata,updateMetadata:tm.updatePersistentMetadata,clearHistory:()=>tm.clearChat(),setVoiceActive:e=>e?tm.startVoiceRecognition():tm.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Ua.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<"u"){let e=(e,t)=>{let r=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==n||t(r)};window.addEventListener(e,r),Ua.push(()=>window.removeEventListener(e,r))};e("persona:focusInput",()=>tm.focusInput()),Pe&&(e("persona:showEventStream",()=>tm.showEventStream()),e("persona:hideEventStream",()=>tm.hideEventStream())),e("persona:showHistory",()=>tm.showHistory()),e("persona:hideHistory",()=>tm.hideHistory()),e("persona:showArtifacts",()=>tm.showArtifacts()),e("persona:hideArtifacts",()=>tm.hideArtifacts()),e("persona:upsertArtifact",e=>{e?.artifact&&tm.upsertArtifact(e.artifact)}),e("persona:selectArtifact",e=>{"string"==typeof e?.id&&tm.selectArtifact(e.id)}),e("persona:clearArtifacts",()=>tm.clearArtifacts())}let rm=function(e){if(!e)return null;let t=!0===e?{}:e;return{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}}(l.persistState);if(rm&&ve()){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}}(rm.storage),r=`${rm.keyPrefix}widget-open`,o=`${rm.keyPrefix}widget-voice`,a=`${rm.keyPrefix}widget-voice-mode`;if(t){let s=rm.persist?.openState&&"true"===t.getItem(r),i=rm.persist?.voiceState&&"true"===t.getItem(o),l=rm.persist?.voiceState&&"true"===t.getItem(a);if(s&&(mh?.setPanelOpen(!0,"auto"),setTimeout(()=>{tm.open(),setTimeout(()=>{if(i||l)tm.startVoiceRecognition();else if(rm.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),rm.persist?.openState&&(U.on("widget:opened",()=>{t.setItem(r,"true")}),U.on("widget:closed",()=>{t.setItem(r,"false")})),rm.persist?.voiceState&&(U.on("voice:state",e=>{t.setItem(o,e.active?"true":"false")}),U.on("user:message",e=>{t.setItem(a,e.viaVoice?"true":"false")})),rm.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(o),t.removeItem(a)},s=t=>{t.detail?.instanceId===n&&e()};window.addEventListener("persona:clear-chat",s),Ua.push(()=>{window.removeEventListener("persona:clear-chat",s)})}}}ee&&ve()&&(mh?.setPanelOpen(!0,"auto"),setTimeout(()=>{tm.open()},0)),Yd(),H=()=>{ls&&(Vs++,Ls.clear(),$d(St,ls.getMessages(),Le))},ls.getMessages().length>0&&Rd(),q=H;let om=Lt(()=>{H?.(),Et()?.updateInlineArtifactBlocks(St,On.artifacts,{suppressTransition:!0}),$a()});Ua.push(om);let nm=()=>{let t=Vt(l);Yh||t.push(...r?.preparation??[]),Rp()&&!fp&&t.push(Qp()),t.length||e.hasAttribute("data-persona-preparing")?u.prepare(t,()=>{_o||Qo(),ho||Jo(),g(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),H?.(),Yh=!0}):Yh=!0};return nm(),tm},Bp=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},Rp=(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"},Pp=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=""},Np=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Pp(e)},$p=e=>{e.style.transition=""},Wp=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=""},Hp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Dp=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Op=(e,t,r,o)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=o):(e.style.padding="",e.style.background="",e.style.boxSizing="")},Fp=(e,t)=>il(t)?((e,t)=>{let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if("BODY"===n||"HTML"===n)throw 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),o.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=di(e),r=t.components?.panel,o=(e,r)=>null==e||""===e?r:Us(t,e)??e;return{inset:o(r?.inset,Es),canvasBackground:o(r?.canvasBackground,Ls)}})(t):null};g();let f=()=>{((e,t,r,o,n,a,s,i)=>{let l=dl(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))})(e,t,r,o,d),((e,t,r,o,n,a)=>{let s=a?t:e;"left"===n?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)})(e,t,r,o,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",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.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)e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Wp(t),$p(o),Np(o),Hp(r),Dp(n,o),Op(o,!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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(a?.launcher?.zIndex??1e5),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");else if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Np(o),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(o,l.maxHeight),Op(o,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",Wp(t),$p(o),Hp(r),Dp(n,o);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=l.width,o.style.maxWidth=l.width,o.style.minWidth=l.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=a,o.style.transform=d,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2","right"===l.side?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",$p(o),Pp(o),Dp(n,o);let a=Bp(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`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=l.width,o.style.minWidth=l.width,o.style.maxWidth=l.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Wp(t),Pp(o),Hp(r),Dp(n,o);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(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${i}`,o.style.width=i,o.style.maxWidth=i,o.style.minWidth=i,o.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(o,l.maxHeight),o.style.overflow=a||u?"hidden":"visible",o.style.transition=d,a){o.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Bp(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;n.style.width=t,n.style.minWidth=t,n.style.maxWidth=t,n.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},b=null,y=()=>{b?.(),b=null,!0===t?.launcher?.detachedPanel&&"auto"===t?.colorScheme&&(b=mi(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===dl(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 o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),n&&!a&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(!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,dl(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===dl(t).reveal?(i.appendChild(l),i.appendChild(d),s.appendChild(i)):(s.appendChild(l),s.appendChild(d)),w(),y(),{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(),y()},destroy(){x?.removeEventListener("resize",C),b?.(),b=null,h(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Rp(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Rp(r,e)},destroy(){r.remove()}}})(e,t),zp=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let o=r.cloneNode(!0),n=new Promise((e,t)=>{o.onload=()=>e(),o.onerror=()=>t(Error("Unable to load the widget stylesheet"))});return e.insertBefore(o,e.firstChild),n},qp=[],jp=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),_p=new Set(["button","a","input","select","textarea","details","summary"]),Up=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Vp=/\b(product|card|item|listing|result)\b/i,Kp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function Qp(e){let t="string"==typeof e.className?e.className:"";if(Vp.test(t)||e.id&&Vp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Vp.test(r.value))return!0}return!1}function Jp(e){return Kp.test((e.textContent??"").trim())}function Gp(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 Yp(e){let t=e.match(Kp);return t?t[0]:null}function Xp(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 Zp(e){return Qp(e)&&Jp(e)&&(Gp(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function eu(e){return!Qp(e)||Jp(e)||!Gp(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let tu=[{id:"commerce-card",scoreElement:e=>Zp(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||Kp.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===Zp(e))return null;let{title:r,href:o}=Xp(e),n=Yp((e.textContent??"").trim())??Yp(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[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>eu(e),formatSummary(e,t){if(0===eu(e))return null;let{title:r,href:o}=Xp(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function ru(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let ou=["data-testid","data-product","data-action","data-id","data-name","data-type"];function nu(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||_p.has(t)||r&&Up.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function au(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 su(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let 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 o=e.attributes[r];o.name.startsWith("data-")&&(t[o.name]=o.value)}return t}function iu(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${ru(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of ou){let o=e.getAttribute(r);if(o){let n=`${t}[${r}="${ru(o)}"]`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${t}.${r.map(e=>ru(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${o}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function lu(e,t){let r=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:iu(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:nu(e),attributes:su(e)}}function du(e,t,r,o){let n=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,o);r>0&&(n+=r,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function cu(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}let pu={components:{panel:{borderRadius:"0",shadow:"none"}}},uu={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:is},welcome:{title:"Welcome to our shop!",subtitle:"I can help you find products and answer questions"},copy:{inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestions:{starters:{items:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],variant:"chip",placement:"composer",overflow:"wrap",maxItems:4}}}},hu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:pu}},mu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:pu}},gu={shop:uu,minimal:hu,fullscreen:mu},fu=typeof document<"u"&&(document.currentScript?.src??"").replace(/^https:\/\/cdn\.runtype\.com\/persona\/latest\//,"https://cdn.runtype.com/persona/4.34.0/")||null,bu=(e,t=`host ${e} alongside it`)=>{let r=0;return()=>{let o=fu?.replace(/index\.global\.js($|\?)/,`${e}$1`);return o&&o!==fu?import(`${o}${r?`#retry-${r}`:""}`).catch(e=>{throw r++,e}):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${fu??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))}};return(e=>{or=e})(bu("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),rt(bu("markdown-parsers.js")),zr(bu("client-stream.js")),en(bu("client-history.js")),$t(bu("ui-extras.js")),un(bu("session-actions.js")),up(bu("history-shell.js")),(e=>{zn=e})(bu("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),Ba(bu("context-mentions.js")),$a(bu("context-mentions-inline.js")),sp(bu("history-view.js")),tl(bu("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),zd(bu("approval-ui.js")),zt(bu("voice-runtime.js")),oo(bu("voice-client-tools.js")),It(bu("artifacts-ui.js")),Ec(bu("forms-ui.js")),ie(bu("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),Zr(bu("webmcp-runtime.js")),Un(bu("session-reconnect.js")),Vd(bu("event-stream-view.js")),Ne(bu("composer-actions-runtime.js")),Qe(bu("dictation-runtime.js")),an(bu("background-runtime.js")),zc(bu("config-diagnostics.js")),J(bu("activity-ui.js")),ze(bu("loading-label-runtime.js")),Qr(bu("client-dispatch.js")),te(bu("turn-activity-ui.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=jo,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=qo,e.ASK_USER_QUESTION_TOOL_NAME=lo,e.AgentWidgetClient=n,e.AgentWidgetSession=c,e.AttachmentManager=p,e.BrowserSpeechEngine=s,e.DEFAULT_COMPONENTS=js,e.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH="440px",e.DEFAULT_FLOATING_LAUNCHER_WIDTH=is,e.DEFAULT_PALETTE=Hs,e.DEFAULT_SEMANTIC=Fs,e.DEFAULT_WIDGET_CONFIG=hs,e.HistoryProviderError=a,e.PRESETS=gu,e.PRESET_FULLSCREEN=mu,e.PRESET_MINIMAL=hu,e.PRESET_SHOP=uu,e.ReadAloudController=i,e.SUGGEST_REPLIES_CLIENT_TOOL=Wo,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=$o,e.SUGGEST_REPLIES_TOOL_NAME=No,e.THEME_ZONES={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble","operator-message":"Operator 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"},e.VERSION=Go,e.WEBMCP_TOOL_PREFIX=Zt,e.applyFeaturePreferences=Sc,e.applyThemeVariables=ui,e.attachHeaderToContainer=Tl,e.buildComposer=$l,e.buildDefaultHeader=El,e.buildHeader=Il,e.buildHeaderWithLayout=Pl,e.buildMinimalHeader=Ll,e.builtInClientToolsForDispatch=_o,e.canonicalArtifactDisplayMode=Sn,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",n=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??tu;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:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(jp.has(s)){a=n.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!au(t)){a=n.nextNode();continue}let i=lu(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=n.nextNode();continue}o.has(i.selector)||(o.add(i.selector),r.push(i))}a=n.nextNode()}let s=[],i=[];for(let e of r)"static"===e.interactivity?i.push(e):s.push(e);return[...s,...i].slice(0,e.maxElements)}(t,r):function(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(jp.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!au(t)){i=s.nextNode();continue}let d=lu(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||o.has(d.selector)){i=s.nextNode();continue}o.add(d.selector);let{score:u,formattingRule:h}=du(t,d,e.rules,r);n.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}n.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-o});let l=[];for(let t of n){if(l.length>=e.maxElements)break;cu(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-o}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let o=e.formattingRule.formatSummary(e.el,e.enriched,r);o&&(t=o)}let o={...e.enriched};return t&&(o.formattedSummary=t),o})}(t,r):[]},e.componentRegistry=ft,e.createActionManager=Xc,e.createAgentExperience=Lp,e.createAskUserQuestionBubble=(e,t)=>{let r=st("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"),So(r,t);let o=st("span","persona-ask-stub-label"),{complete:n}=wo(e);return o.textContent=n?"Awaiting your response…":"Preparing options…",r.appendChild(o),r},e.createBubbleWithLayout=(e,t,r,o,n,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}):od(e,t,r,o,0,a)},e.createCSATFeedback=yp,e.createComboButton=gt,e.createComponentMiddleware=function(){let e=Rn();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=Rn,e.createDefaultSanitizer=Br,e.createDirectivePostprocessor=e=>{let t=Cr(e);return e=>{let r=[],o=Tr(e,r),n=t(o);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Mr(t)}"></div>`;n=n.replace(r,o)}),n}},e.createDropdownMenu=ct,e.createFlexibleJsonStreamParser=e=>{let t=null,o=0,n=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?Uo(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?Uo(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 a=e.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(e.length<=o)return null===t?null:{text:t,raw:e};try{let o=(0,r.parse)(e,r.STR|r.OBJ),a=n(o);null!==a&&(t=a)}catch{}return o=e.length,{text:t||"",raw:e}},close:()=>{}}},e.createIconButton=pt,e.createImagePart=function(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}},e.createJsonStreamParser=Qo,e.createLabelButton=ut,e.createLocalStorageAdapter=rp,e.createMarkdownProcessor=xr,e.createMarkdownProcessorFromConfig=Cr,e.createMessageActions=rd,e.createNPSFeedback=vp,e.createPlainTextParser=Vo,e.createRegexJsonParser=Ko,e.createSplitButton=mt,e.createStandardBubble=od,e.createTextPart=fn,e.createTheme=Js,e.createThemeObserver=mi,e.createToggleGroup=ht,e.createTypingIndicator=Kl,e.createWidgetHostLayout=Fp,e.createXmlParser=Jo,e.defaultActionHandlers=Gc,e.defaultJsonActionParser=Qc,e.defaultParseRules=tu,e.detectColorScheme=ii,e.directivePostprocessor=e=>{let t=[],r=Tr(e,t),o=kr(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Mr(t)}"></div>`;o=o.replace(r,n)}),o},e.ensureAskUserQuestionSheet=Ro,e.escapeHtml=Ar,e.extractComponentDirectiveFromMessage=Wn,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",o=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&o.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||n[t.interactivity].push(t);if(n.clickable.length>0){let e=n.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);o.push(`Interactive elements:\n${e.join("\n")}`)}if(n.navigable.length>0){let e=n.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);o.push(`Navigation links:\n${e.join("\n")}`)}if(n.input.length>0){let e=n.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);o.push(`Form inputs:\n${e.join("\n")}`)}if(n.static.length>0){let e=n.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);o.push(`Content:\n${e.join("\n")}`)}return o.join("\n\n")},e.generateAssistantMessageId=io,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=iu,e.generateUserMessageId=so,e.getActiveTheme=di,e.getAgentWidgetHandles=()=>[...qp],e.getColorScheme=li,e.getDisplayText=function(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")},e.getHeaderLayout=Rl,e.getImageParts=function(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)},e.getPreset=function(e){return gu[e]},e.hasComponentDirective=$n,e.hasImages=gn,e.headerLayouts=Bl,e.initAgentWidget=e=>{let t,r=(e=>{if(typeof window>"u"||typeof document>"u")throw Error("Chat widget can only be mounted in a browser environment");if("string"==typeof e){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e})(e.target),o=!0===e.useShadowDom,n=r.ownerDocument,a=r.id||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,s=e.config,i=Vc(s),l=Fp(r,s),d=[],c=!1,p=!1,u=()=>{let r=t;r.ready.then(()=>{c||p||r!==t||(p=!0,e.onChatReady?.())},()=>{})},h=e=>e(),m=new Set,g=(e,t)=>{let r,s=!(t?.launcher?.enabled??1)||il(t),i=n.createElement("div");if(i.setAttribute("data-persona-root","true"),s&&(i.style.height="100%",i.style.display="flex",i.style.flexDirection="column",i.style.flex="1",i.style.minHeight="0",i.style.minWidth="0"),o){let t=e.attachShadow({mode:"open"});t.appendChild(i),r=zp(t,n)}else e.appendChild(i),zp(e,n);return i.setAttribute("data-persona-instance",a),{mount:i,stylesReady:r}},f=()=>{l.syncWidgetState(t.getState())},b=()=>{let{mount:r,stylesReady:o}=g(l.host,s);t=Lp(r,s,{debugTools:e.debugTools,registerHostMove:e=>{h=e},diagnostics:i,preparation:o?[o]:[]}),m.forEach(e=>e.bind()),d.forEach(e=>e()),d=[t.on("widget:opened",f),t.on("widget:closed",f)],f(),u()},y=()=>{d.forEach(e=>e()),d=[],t.destroy()};b();let v=e=>{y(),l.destroy(),l=Fp(r,e),s=e,b()},w=new Proxy({moveTo(e,t){if(c)throw Error("Cannot move a destroyed widget");if("direct"!==l.mode)throw Error("Docked widgets cannot be moved");let o="string"==typeof e?n.querySelector(e):e;if(!(o instanceof HTMLElement)||o.ownerDocument!==n||o.getRootNode()!==n||l.host.getRootNode()!==n||l.host.contains(o))throw Error("Invalid widget move target: expected a connected light-DOM container in the same document");o!==r&&(h(()=>function(e,t,r){let o=e.ownerDocument,n=o.activeElement;for(;n?.shadowRoot?.activeElement;)n=n.shadowRoot.activeElement;let a=t=>{for(;t;){if(e.contains(t))return!0;let r=t.getRootNode();t=r instanceof ShadowRoot?r.host:null}return!1},s=r&&a(n)?n:null,i=s,l=i?.selectionStart,d=i?.selectionEnd,c=i?.selectionDirection,p=(s?.getRootNode())?.getSelection?.()??o.getSelection(),u=p?.anchorNode,h=p?.focusNode,m=r&&a(u??null)&&a(h??null)?[p.anchorOffset,p.focusOffset]:null,g=t;"function"==typeof g.moveBefore?g.moveBefore(e,null):t.appendChild(e),s?.focus({preventScroll:!0}),i&&null!=l&&null!=d&&i.setSelectionRange(l,d,c??void 0),m&&u&&h&&p.setBaseAndExtent(u,m[0],h,m[1])}(l.host,o,!1!==t?.preserveFocus)),r=o)},on(e,r){if(c)return()=>{};let o=[...m].find(t=>t.event===e&&t.handler===r);if(o)return o.unsubscribe;let n=()=>{},a={event:e,handler:r,bind:()=>{n=t.on(e,r)},unsubscribe:()=>{n(),m.delete(a)}};return m.add(a),a.bind(),a.unsubscribe},off(e,t){for(let r of m)r.event===e&&r.handler===t&&r.unsubscribe()},update(e){Kc(i,e);let r=Wc(s??{},e),o=il(s),n=il(r),a=ll(s),d=ll(r);o!==n||a!==d?v(r):(s=r,l.updateConfig(s),t.update(e),u(),f())},destroy(){if(c)return;c=!0,y(),m.forEach(e=>e.unsubscribe()),l.destroy();let t=qp.indexOf(w);-1!==t&&qp.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,o){if("host"===r)return l.host;if(r in e)return Reflect.get(e,r,o);let n=t[r];return"function"==typeof n?n.bind(t):n}});return qp.push(w),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w},e.isAskUserQuestionMessage=yo,e.isComponentDirectiveType=function(e){return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component&&"props"in e&&"object"==typeof e.props},e.isDockedMountMode=il,e.isHistoryProviderError=function(e){return e instanceof a},e.isSuggestRepliesMessage=Ho,e.isWebMcpToolName=ir,e.isWelcomeVisible=xd,e.latestAgentSuggestions=Oo,e.listRegisteredStreamAnimations=()=>Array.from($i.keys()),e.loadMarkdownParsers=ot,e.markdownPostprocessor=kr,e.mergeWithDefaults=gs,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=kn,e.onMarkdownParsersReady=nt,e.parseAskUserQuestionPayload=wo,e.parseSuggestRepliesPayload=Do,e.parseWidgetPreferenceSlice=vc,e.pickBestVoice=On,e.pluginRegistry=Rc,e.preprocessStreamingMarkdown=wr,e.registerIcons=e=>{for(let[t,r]of Object.entries(e))Ce.set(t,r);Ie()>0&&!ke&&Me(!1)},e.registerStreamAnimationPlugin=Hi,e.removeAskUserQuestionSheet=Po,e.renderComponentDirective=Pn,e.renderLoadingIndicatorWithFallback=Ql,e.renderLucideIcon=Ee,e.resolveArtifactDisplay=An,e.resolveArtifactDisplayMode=Mn,e.resolveConfigPreferences=kc,e.resolveDockConfig=dl,e.resolveSanitizer=Rr,e.resolveTokens=Vs,e.resolveWelcomeConfig=bd,e.stripWebMcpPrefix=sr,e.themeToCssVariables=ei,e.unregisterStreamAnimationPlugin=e=>{Ni.some(t=>t.name===e)||$i.delete(e)},e.validateImageFile=function(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(", ")}`}},e.validateTheme=Ks,e}({});
|
|
7
|
+
var AgentWidget=function(e){var t,r,o,n,a,s,i,l,d,c,p,u,h=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);let m=Symbol.for("persona.defaultsProvenance"),g=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function f(e,t=""){return Object.entries(e).flatMap(([e,r])=>{let o=t?`${t}.${e}`:e;return g(r)?f(r,o):[o]})}function b(e,t){let r=t.split(".");for(let t=0;t<r.length;t++){let o=r[t];if(!g(e)||!Object.prototype.hasOwnProperty.call(e,o))return"absent";if(void 0===(e=e[o])||t<r.length-1&&!g(e))return"clear"}return"explicit"}function y(e,t){return e?.[m]??t.filter(t=>"explicit"===b(e,t))}function v(e,t){return Object.defineProperty(e,m,{value:t,enumerable:!0,configurable:!0}),e}function w(e,t,r){return v(e,y(t,f(r)))}function x(e,t,r){let o=t[m];if(o)return o;let n=new Set(y(e,r));for(let e of r){let r=b(t,e);"clear"===r&&n.delete(e),"explicit"===r&&n.add(e)}return[...n]}function C(e,t,r){let o={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),n=o;for(let e of t.slice(0,-1)){let t=n[e];if(!g(t)){n=void 0;break}n[e]={...t},n=n[e]}n&&delete n[t[t.length-1]]}return o}let S=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function k(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=S(t)&&S(o)?k(t,o):o}return r}let A=e=>{if("string"!=typeof e)return;let t=e.trim(),r=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(t)?.[1];if(r){let e=3===r.length?[...r].map(e=>e+e).join(""):r;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let o=/^rgba?\(\s*([^)]*)\)$/i.exec(t);if(!o)return;let n=o[1].trim().split(/\s*[,/]\s*|\s+/);if(4===n.length&&/^(?:1(?:\.0+)?|100%)$/.test(n[3])&&n.pop(),3!==n.length)return;let a=n.map(e=>/^\d+(?:\.\d+)?%?$/.test(e)?Number.parseFloat(e)*(e.endsWith("%")?2.55:1):NaN);return a.some(e=>!Number.isFinite(e)||e<0||e>255)?void 0:a},M=e=>e.reduce((e,t,r)=>{let o=t/255;return e+(o<=.04045?o/12.92:((o+.055)/1.055)**2.4)*[.2126,.7152,.0722][r]},0),I=e=>"#"+e.map(e=>Math.round(e).toString(16).padStart(2,"0")).join(""),T=(e,t,r)=>I(e.map(e=>e+(t-e)*r)),E=e=>M(e)>.179?"#000000":"#ffffff",L=e=>{let t=A(e?.neutral);return t?M(t)<.18?"dark":"light":void 0},B=(e,t)=>t.split(" ").map(t=>`${e}.${t}`),R=[...B("launcher","closeButtonSize closeButtonColor closeButtonBackgroundColor closeButtonBorderWidth closeButtonBorderColor closeButtonBorderRadius closeButtonPaddingX closeButtonPaddingY"),...B("launcher.clearChat","size iconColor backgroundColor borderWidth borderColor borderRadius paddingX paddingY"),...B("sendButton","size iconSize iconStrokeWidth backgroundColor textColor borderWidth borderColor paddingX paddingY"),...B("voiceRecognition","iconSize iconColor backgroundColor borderColor borderWidth paddingX paddingY recordingIconColor recordingBackgroundColor recordingBorderColor processingIconColor processingBackgroundColor processingBorderColor speakingIconColor speakingBackgroundColor speakingBorderColor"),...B("toolCall","shadow backgroundColor borderColor borderWidth borderRadius headerBackgroundColor headerTextColor headerPaddingX headerPaddingY contentBackgroundColor contentTextColor contentPaddingX contentPaddingY codeBlockBackgroundColor codeBlockBorderColor codeBlockTextColor toggleTextColor labelTextColor loadingAnimationColor loadingAnimationSecondaryColor loadingAnimationDuration"),...B("approval","backgroundColor borderColor shadow titleColor descriptionColor reasonColor approveButtonColor approveButtonTextColor denyButtonColor denyButtonTextColor parameterBackgroundColor parameterTextColor"),...B("features.askUserQuestion.styles","sheetBackground sheetBorder sheetShadow pillBackground pillBackgroundSelected pillTextColor pillTextColorSelected pillBorderRadius customInputBackground"),...B("features.artifacts.layout","paneBackground panePadding paneBorderRadius paneShadow chatShadow paneBorder paneBorderLeft unifiedSplitOuterRadius documentToolbarIconColor documentToolbarToggleActiveBackground documentToolbarToggleActiveBorderColor documentToolbarToggleActiveColor tabFadeSize"),...B("suggestionChipsConfig","fontWeight paddingX paddingY")],P=["voice.recording.border","voice.processing.icon","voice.processing.background","voice.speaking.icon","approval.requested.text","approval.approve.foreground","approval.deny.foreground","approval.deny.background","reasoningBubble.shadow","toolBubble.shadow"],N=[...R,"suggestionChips","copy.welcomeTitle","copy.welcomeSubtitle","copy.showWelcomeCard","features.suggestReplies.enabled","features.suggestReplies.expose",...["theme","darkTheme"].flatMap(e=>P.map(t=>`${e}.components.${t}`))],$=Symbol.for("persona.styleProvenance"),W=(e,t)=>{for(let r of t.split(".")){if("object"!=typeof e||!e)return;e=e[r]}return e},H=e=>{let t=e?.[$];if(!t)return N.filter(t=>"explicit"===b(e,t));let r=new Set(t.explicit);return N.forEach(o=>{W(e,o)!==t.values[o]&&("explicit"===b(e,o)?r.add(o):r.delete(o))}),[...r]},D=(e,t)=>(Object.defineProperty(e,$,{value:{explicit:t,values:Object.fromEntries(N.map(t=>[t,W(e,t)]))},enumerable:!0,configurable:!0}),e),F=(e,t)=>D(e,H(t)),O=(e,t)=>{let r=e?.[$];return r&&Object.prototype.hasOwnProperty.call(r.values,t)&&W(e,t)===r.values[t]?r.explicit.includes(t):"explicit"===b(e,t)},z=(e,t)=>O(e,t)?W(e,t):void 0,q=(e,t,r)=>{let o=e,n=r??o?.colorScheme??L(o?.brand)??"light",a="dark"===n||"auto"===n&&(typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches);return O(e,`theme.components.${t}`)||a&&O(e,`darkTheme.components.${t}`)},j={defaultProvenance:y,suppliedPath:b,hasExplicitThemeStyle:q,getExplicitLegacyStyle:z},_=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,o=null,n=null,a=null;return{setLoader:e=>{o=e,r&&(n=null,a=null)},load:()=>{if(n)return Promise.resolve(n);if(a)return a;let e=o??t;try{return a=e().then(e=>(n=e,e)).catch(e=>{throw a=null,e}),a}catch(e){return Promise.reject(e)}},provide:e=>{n=e},getSync:()=>n}},{setLoader:U,load:V,provide:K,getSync:Q}=_({fallbackImport:()=>import("@runtypelabs/persona/activity-ui")}),J=U,G=V,Y=Q,{setLoader:X,load:Z,provide:ee}=_({fallbackImport:()=>import("@runtypelabs/persona/turn-activity-ui")}),te=X,re=null,oe=()=>Promise.all([Z(),G()]).then(([e,t])=>(Object.assign(t.turnUi,e),re=e)),ne=(e,t=24,r="currentColor",o=2)=>{if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");for(let[e,a]of Object.entries({width:String(t),height:String(t),viewBox:"0 0 24 24",fill:"none",stroke:r,"stroke-width":String(o),"stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"}))n.setAttribute(e,a);for(let t of e){if(!Array.isArray(t)||t.length<2)continue;let e=t[0],r=t[1];if(!r)continue;let o=document.createElementNS("http://www.w3.org/2000/svg",e);for(let[e,t]of Object.entries(r))"stroke"!==e&&o.setAttribute(e,String(t));n.appendChild(o)}return n},{setLoader:ae,load:se}=_({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),ie=ae,le=se,de=[["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"}]],ce=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]],pe=[["path",{d:"M20 6 9 17l-5-5"}]],ue=[["path",{d:"m18 15-6-6-6 6"}]],he=[["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"}]],me=[["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"}]],ge=[["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"}]],fe=[["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"}]],be=[["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"}]],ye=[["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"}]],ve=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]],we={activity:de,"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":[["path",{d:"m6 9 6 6 6-6"}]],"chevron-up":ue,"chevron-right":[["path",{d:"m9 18 6-6-6-6"}]],"chevron-left":[["path",{d:"m15 18-6-6 6-6"}]],check:pe,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:he,file:be,"file-code":me,"file-spreadsheet":ge,"file-text":fe,"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"}]],"square-text":[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 8h10M7 12h10M7 16h6"}]],"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"}]],"voice-bars":[["path",{d:"M4 10v4"}],["path",{d:"M8 6v12"}],["path",{d:"M12 3v18"}],["path",{d:"M16 7v10"}],["path",{d:"M20 10v4"}]],x:ve,"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":ce,"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"}]],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":ye,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"}]]},xe="brain.toolbox.wrench.circle.database.terminal.user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.ellipsis-vertical.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".split("."),Ce=new Map(Object.entries(we)),Se=new Map,ke=!1,Ae=new Set,Me=e=>{let t=[...Ae];e&&Ae.clear();for(let e of t)try{e()}catch{}},Ie=()=>{let e=0;for(let[t,r]of Se){let o=Ce.get(r);if(!o)continue;Se.delete(t),e++;let n=ne(o);if(n)for(t.removeAttribute("data-persona-icon-pending");n.firstChild;)t.appendChild(n.firstChild)}return e},Te=()=>ke?null:le().then(e=>(e=>{if(!ke){for(let[t,r]of Object.entries(e))Ce.has(t)||Ce.set(t,r);ke=!0,Ie(),Me(!0)}})(e.EXTRA_LUCIDE_ICONS)),Ee=(e,t=24,r="currentColor",o=2)=>{let n=Ce.get(e);if(n)return ne(n,t,r,o);if(xe.includes(e)){let n=((e,t,r)=>{let o=ne([],e,t,r);return o.setAttribute("data-persona-icon-pending","true"),o})(t,r,o);return Se.size>=500&&Se.delete(Se.keys().next().value),Se.set(n,e),Te()?.catch(e=>{console.warn("[Persona] Failed to load the icons-extra chunk",e)}),n}return console.warn(`Unknown Persona icon "${e}". Use registerIcons().`),null},{setLoader:Le,load:Be,provide:Re,getSync:Pe}=_({fallbackImport:()=>import("@runtypelabs/persona/composer-actions-runtime")}),Ne=Le,$e=Be,We=Pe,{setLoader:He,load:De,provide:Fe,getSync:Oe}=_({fallbackImport:()=>import("@runtypelabs/persona/loading-label-runtime")}),ze=He,qe=De,je=Oe,{setLoader:_e,load:Ue,getSync:Ve,provide:Ke}=_({fallbackImport:()=>import("@runtypelabs/persona/dictation-runtime")}),Qe=_e,Je=Ue,Ge=Ve,{setLoader:Ye,load:Xe,provide:Ze,getSync:et}=_({fallbackImport:()=>import("./markdown-parsers-entry")}),tt=new Set,rt=Ye,ot=()=>{let e=et();return e?Promise.resolve(e):Xe().then(e=>((()=>{let e=[...tt];tt.clear();for(let t of e)try{t()}catch{}})(),e))},nt=e=>et()?()=>{}:(tt.add(e),()=>{tt.delete(e)}),at=et,st=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},it=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),void 0!==t.text&&(o.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))o.setAttribute(e,r);if(t.style){let e=o.style,r=t.style;for(let t of Object.keys(r)){let o=r[t];null!=o&&(e[t]=o)}}let n=r.filter(e=>null!=e);return n.length>0&&o.append(...n),o},lt=(...e)=>e.filter(Boolean).join(" "),dt={idle:"Online",connecting:"Connecting…",connected:"Streaming…",error:"Offline",paused:"Connection lost…",resuming:"Reconnecting…"};function ct(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a,onOpenChange:s}=e,i=st("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="100001"):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px","bottom-right"===n?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=Ee(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let o=document.createElement("span");o.textContent=e.label,t.appendChild(o),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=o.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===n?(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)&&!o.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 pt(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,chromeless:s,onClick:i,aria:l}=e,d=st("button",lt(!s&&"persona-icon-btn",a));d.type="button",d.setAttribute("aria-label",r),d.title=r;let c=Ee(t,o??16,"currentColor",n??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 ut(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==o&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let c=st("button",d);if(c.type="button",c.setAttribute("aria-label",r),t){let e=Ee(t,a??14,"currentColor",2);e&&c.appendChild(e)}let p=st("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 ht(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=st("div","persona-toggle-group"+(n?" "+n:""));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=pt({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),o(e.id)}}):(t=st("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(),o(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 mt(e){let{label:t,icon:r,iconSize:o,iconOnly:n,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=st("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},b=n&&r?pt({...f,icon:r,size:o??14}):ut({...f,icon:r,iconSize:o??14}),y=pt({icon:"chevron-down",label:c,size:p??14,className:"persona-split-btn-chevron"+(m?" "+m:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});g.append(b,y);let v=null,w=()=>{if(v)return v;let e=("function"==typeof d?d():d)??void 0;return v=ct({items:a,onSelect:s,anchor:g,position:l,portal:e,onOpenChange:e=>{y.setAttribute("aria-expanded",e?"true":"false")}}),e||g.appendChild(v.element),v};return g.isConnected?w():requestAnimationFrame(()=>{v||w()}),y.addEventListener("click",e=>{e.stopPropagation(),w().toggle()}),{element:g,primaryButton:b,chevronButton:y,openMenu:()=>w().show(),closeMenu:()=>v?.hide(),toggleMenu:()=>w().toggle(),destroy:()=>{v?.destroy(),g.remove()}}}function gt(e){let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:l}=e,d=st("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=st("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let p=Ee(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=ct({items:o,onSelect:e=>{d.setAttribute("aria-expanded","false"),n(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()}}}let ft=new class{#e=new Map;#t=new Map;register(e,t,r){this.#e.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.#e.set(e,t),r?this.#t.set(e,r):this.#t.delete(e)}unregister(e){this.#e.delete(e),this.#t.delete(e)}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}getOptions(e){return this.#t.get(e)}getAllNames(){return Array.from(this.#e.keys())}clear(){this.#e.clear(),this.#t.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}};function bt(e,t){return e.components&&Object.prototype.hasOwnProperty.call(e.components,t)?e.components[t]:ft.get(t)}function yt(e,t){return e.components&&Object.prototype.hasOwnProperty.call(e.components,t)?void 0:ft.getOptions(t)}let vt=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:wt,load:xt,provide:Ct,getSync:St}=_({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),kt=null,At=new Set,Mt=e=>{if(kt)return kt;kt=e,e.initArtifactsUi({componentRegistry:ft,loadingLabels:je(),buttons:{createIconButton:pt,createLabelButton:ut,createSplitButton:mt,createToggleGroup:ht}});for(let t of vt)ft.has(t)||ft.register(t,"PersonaArtifactCard"===t?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=at();t?e.__provideMarkdownParsers(t):nt(()=>{let t=at();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader!==ie&&e.__setIconsExtraLoader(le);let r=[...At];At.clear();for(let e of r)try{e()}catch{}return e},It=wt,Tt=()=>Promise.all([xt(),qe()]).then(([e])=>Mt(e)),Et=()=>{if(kt)return kt;if(!je())return null;let e=St();return e?Mt(e):null},Lt=e=>kt?()=>{}:(At.add(e),()=>{At.delete(e)}),{setLoader:Bt,load:Rt,provide:Pt,getSync:Nt}=_({fallbackImport:()=>import("./ui-extras-entry")}),$t=Bt,Wt=Rt,Ht=Nt,{setLoader:Dt,load:Ft,getSync:Ot}=_({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),zt=Dt,qt=Ft,jt=Ot;function _t(e){return"runtype"===e?.type||"custom"===e?.type}function Ut(e){let t=e.voiceRecognition;return _t(t?.provider)&&("custom"!==t?.provider?.type||!!t.dictation?.provider||!t.dictation&&"review"!==t.completionBehavior)}let Vt=e=>{let t=[],r=(e,r,o)=>{e&&!r&&t.push(o())};r(!0,We(),$e),r(!0,at(),ot);let o=!0===e.turnActivity?.enabled;r(o,re,oe);let n=o||!1!==e.features?.showToolCalls||!1!==e.features?.showReasoning;r(n,Y(),G),r(n||"none"!==e.loadingLabel?.animation&&(!!e.loadingLabel?.animate||"label"===(e.loadingIndicator?.variant??(e.future?.v5Defaults?"label":"dots"))),je(),qe),r(!1!==e.voiceRecognition?.enabled,Ge(),Je),r(!1!==e.voiceRecognition?.enabled&&Ut(e),jt(),qt),r(!0===e.features?.artifacts?.enabled,Et(),Tt),r(!0===e.contextMentions?.enabled,Ht(),Wt);let a=Te();return a&&t.push(a),t};function Kt(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Qt(e,t){return Kt(e)-e.scrollTop<=t}function Jt(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))}}function Gt(){let e=null,t=()=>{null!==e&&cancelAnimationFrame(e),e=null};return{get active(){return null!==e},cancel:t,start(r,o,n,a,s,i=()=>!0){t();let l=r.scrollTop,d=performance.now();if(Math.abs(o()-l)<1)return r.scrollTop=o(),a(),void s();let c=p=>{if(!i())return t(),void s();let u=Math.min(Math.max(0,(p-d)/n),1);r.scrollTop=l+(o()-l)*(1-(1-u)**3),a(),u<1?e=requestAnimationFrame(c):(e=null,s())};e=requestAnimationFrame(c)}}}function Yt(e,t,r,o,n){let a,s=Gt(),i=!1,l=!1,d=e=>{e&&(l=!1),s.active&&(s.cancel(),a=e,l=!!e,n())},c=e=>{["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"," "].includes(e.key)&&d(e)},p=e=>{0!==e.deltaY&&d(e)};return e.addEventListener("wheel",p,{passive:!0}),e.addEventListener("touchstart",d,{passive:!0}),e.addEventListener("pointerdown",d,{passive:!0}),t.addEventListener("keydown",c),{get active(){return s.active},cancel:d,get interrupted(){return l},interruptedBy:e=>a===e,start(t){if(i)return;s.cancel(),l=!1,a=void 0;let n="smooth"===(t.features?.scrollToBottom?.scrollBehavior??(t.future?.v5Defaults?"smooth":"instant")),d=t.features?.scrollToBottom?.scrollDurationMs??220,c=Number.isFinite(d)&&d>=0?d:220,p="function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches;!n||p||0===c?(e.scrollTop=Kt(e),r(),o()):s.start(e,()=>Kt(e),c,r,o)},destroy(){i=!0,s.cancel(),e.removeEventListener("wheel",p),e.removeEventListener("touchstart",d),e.removeEventListener("pointerdown",d),t.removeEventListener("keydown",c)}}}function Xt(e,t,r){let o=st("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");o.type="button",o.setAttribute("data-persona-scroll-to-bottom-visible","false"),o.disabled=!0,o.tabIndex=-1,o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-scroll-to-bottom","true");let n=st("span","persona-flex persona-items-center persona-justify-center");n.setAttribute("aria-hidden","true");let a=st("span",""),s=st("span","");s.setAttribute("data-persona-scroll-to-bottom-count",""),o.append(n,a,s);let i,l,d,c={},p={activity:"idle",visible:!1,hovered:!1,focused:!1,reducedMotion:!1},u="",h="function"==typeof matchMedia?matchMedia("(prefers-reduced-motion: reduce)"):void 0,m=[],g=()=>{let e=getComputedStyle(o);return{width:`${o.offsetWidth}px`,backgroundColor:e.backgroundColor,borderColor:e.borderColor,color:e.color}};p.reducedMotion=h?.matches??!1;let f=e=>console.warn("Persona scroll icon failed",e),b=()=>({config:c,state:{...p},view:t,signal:d.signal}),y=()=>{d?.abort();try{l?.destroy?.()}catch(e){f(e)}l=void 0,d=void 0,n.innerHTML="",u=""},v=()=>{if(l?.element)return;let t=c.features?.scrollToBottom,r="generating-below"===p.activity&&"dots"===(t?.streamingIndicator??(c.future?.v5Defaults?"dots":"arrow")),o="approval-below"===p.activity?"shield-check":t?.iconName??"arrow-down",a=r?"dots":`arrow:${o}`;if(u!==a)if(u=a,n.innerHTML="",r){let e=st("span","persona-scroll-to-bottom-dots");for(let t=0;t<3;t++){let r=st("span","");r.style.animationDelay=150*t+"ms",e.appendChild(r)}n.appendChild(e)}else{let t=e(o,"14px","currentColor",2);t&&n.appendChild(t)}},w=e=>{let t=!1===c.features?.scrollToBottom?.enabled?void 0:c.features?.scrollToBottom?.renderIcon;if(t!==i){if(y(),i=t,i){d=new AbortController;try{let e=i(b());l=e&&"element"in e?e:e?{element:e}:void 0,l?.element&&n.appendChild(l.element)}catch(e){f(e),y()}}}else if(e&&l?.update)try{l.update(b())}catch(e){f(e),y()}v()},x=e=>Object.keys(e).some(t=>e[t]!==p[t]),C=e=>{let t=x(e);p=e,w(t)},S=()=>C({...p,hovered:!0}),k=()=>C({...p,hovered:!1}),A=()=>C({...p,focused:!0}),M=()=>C({...p,focused:!1}),I=()=>C({...p,reducedMotion:h?.matches??!1}),T=new AbortController;for(let[e,t]of[["mouseenter",S],["mouseleave",k],["focus",A],["blur",M]])o.addEventListener(e,t,{signal:T.signal});return h?.addEventListener?.("change",I),{element:o,update(e,t,n=!1,i=0,l=!1){let d=c.features?.scrollToBottom,u=e.features?.scrollToBottom,h=c.future?.v5Defaults!==e.future?.v5Defaults||["enabled","iconName","label","approvalLabel","streamingIndicator","transition","scrollBehavior","scrollDurationMs"].some(e=>d?.[e]!==u?.[e]);c=e;let f=c.features?.scrollToBottom;t&&=!1!==f?.enabled;let b=o.getRootNode().activeElement===o;o.setAttribute("data-persona-scroll-to-bottom-visible",String(t));let y=!1===f?.enabled?"none":f?.transition??(c.future?.v5Defaults?"fade":"none");o.setAttribute("data-persona-scroll-to-bottom-transition",y),n&&t?o.setAttribute("data-persona-scroll-to-bottom-streaming",""):o.removeAttribute("data-persona-scroll-to-bottom-streaming"),o.style.display=t||"none"!==y?"":"none",o.disabled=!t,o.tabIndex=t?0:-1,o.setAttribute("aria-hidden",String(!t)),!t&&b&&(o.blur(),r&&(r.hasAttribute("tabindex")||(r.tabIndex=-1),r.focus({preventScroll:!0})));let v=l&&t,C=p.visible&&t&&"approval-below"===p.activity!==v;(C||!t)&&m.forEach(e=>e.cancel());let S=C&&!p.reducedMotion&&"function"==typeof o.animate?g():null,k=f?.approvalLabel??"Approval needed",A=v&&k?k:f?.label??"",M=f?.label||"Jump to latest";o.setAttribute("aria-label",v?`${k||"Approval needed"} below. ${M}`:`${M}${i>0?` (${i} new)`:""}${n&&t?" (response streaming below)":""}`),o.title=A,o.setAttribute("data-persona-scroll-to-bottom-has-label",String(!!A)),v?o.setAttribute("data-persona-scroll-to-bottom-approval",""):o.removeAttribute("data-persona-scroll-to-bottom-approval"),a.textContent=A,a.style.display=A?"":"none";let I=v?0:i;s.textContent=I>0?String(I):"",s.style.display=I>0?"":"none";let T=v?"approval-below":n&&t?"generating-below":"idle",E={...p,visible:t,hovered:t&&p.hovered,focused:t&&p.focused,activity:T},L=h||x(E);p=E,w(L),S&&(e=>{let t=getComputedStyle(o),r=t.getPropertyValue("--persona-motion-duration-base"),n=parseFloat(r)*(r.includes("ms")?1:1e3);if(0===n)return;let s={duration:n>0?n:200,easing:t.getPropertyValue("--persona-motion-easing").trim()||"ease-out"},i="none"===a.style.display?null:{overflow:"hidden"};m=[o.animate([{...e,...i},{...g(),...i}],s)],i&&m.push(a.animate([{opacity:0},{opacity:1}],s))})(S)},destroy(){m.forEach(e=>e.cancel()),y(),T.abort(),h?.removeEventListener?.("change",I),o.remove()}}}let Zt="webmcp:",er=new Map,tr=e=>{er.clear();for(let t of e){let e=t.title?.trim();e&&er.set(t.name,e)}},rr=e=>er.get(sr(e)),or=null;function nr(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`${ar(e,0).toString(36)}.${ar(e,2654435761).toString(36)}`}(t.join(""))}`}function ar(e,t){let r=3735928559^t,o=1103547991^t;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);r=Math.imul(r^n,2654435761),o=Math.imul(o^n,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&o)+(r>>>0)}let sr=e=>e.startsWith("webmcp:")?e.slice(7):e,ir=e=>e.startsWith(Zt),lr=()=>or?or():import("@mcp-b/webmcp-polyfill");function dr(e){return"webmcp"===e.toolType&&!e.executionId}function cr(e){let t=e.approval,r="pending"===t?.status&&dr(t),o=!1,n=t=>t.name&&ir(t.name)&&(o=!0,"complete"!==t.status||!0===e.agentMetadata?.awaitingLocalTool&&void 0===t.result&&void 0===t.success)?{...t,status:"complete",interrupted:!0,success:!1,error:"The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.",approvalStatus:"pending"===t.approvalStatus?"timeout":t.approvalStatus,startedAt:void 0===t.completedAt?void 0:t.startedAt}:t,a=e.toolCall?n(e.toolCall):void 0,s=e.tools?.map(n);return{...e,streaming:!o&&!r&&e.streaming,...r?{approval:{...t,status:"timeout",interrupted:!0}}:{},...a?{toolCall:a}:{},...s?{tools:s}:{},...o&&e.agentMetadata?.awaitingLocalTool?{agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}}:{}}}let pr=(e,t,r)=>{let o="transient"===t.mode,n=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)||o&&n&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},ur=(e,t,r)=>{t.parentElement&&e.parentElement===t.parentElement&&("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))},hr=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mr=e=>e.includes("|"),gr=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())},fr=e=>`| ${e.join(" | ")} |`,br=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,yr=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),vr=e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let o=t[e],n=t[e+1];if(!mr(o)||hr.test(o)||!hr.test(n))continue;let a=gr(o).length;if(a<1)continue;let s=br(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()||!mr(e))break;let o=fr(yr(gr(e),a));t[i]!==o&&(t[i]=o,r=!0)}e=i-1}return r?t.join("\n"):e},wr=(e,t)=>t?(at()?.stabilizeStreamingMarkdown??vr)(e):e,xr=e=>{let t=null;return r=>{let o=at();if(!o)return Ar(r);if(!t){let{Marked:r}=o,n=e?.markedOptions;t=new r({gfm:n?.gfm??!0,breaks:n?.breaks??!0,pedantic:n?.pedantic,silent:n?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,o)=>e({type:"heading",raw:o,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,o)=>e({type:"code",raw:"",text:t,lang:r,escaped:o})}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,o)=>e({type:"link",raw:"",href:t,title:r??null,text:o,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,o)=>e({type:"image",raw:"",href:t,title:r??null,text:o})}if(r.list){let e=r.list;t.list=(t,r,o)=>e({type:"list",raw:"",ordered:r,start:o,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,o)=>e({type:"list_item",raw:"",task:r,checked:o,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)}},Cr=e=>e?xr({markedOptions:e.options,renderer:e.renderer}):xr(),Sr=xr(),kr=e=>Sr(e),Ar=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Mr=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Ir=e=>`%%FORM_PLACEHOLDER_${e}%%`,Tr=(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=Ir(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 o=Ir(t.length);return t.push({token:o,type:r}),o}),r},Er={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".split("."),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".split(".")},Lr=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Br=()=>{let e=null;return t=>{let r=at();if(!r)return Ar(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:")&&!Lr.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,Er)}},Rr=e=>!1===e?null:"function"==typeof e?e:Br(),Pr="var(--persona-md-table-scroll-fade, 24px)",Nr=new WeakSet;function $r(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,o=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":Pr),e.style.setProperty("--persona-fade-r",o<=1?"0px":Pr)}function Wr(e){Nr.has(e)||(Nr.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&$r(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach($r)}let{setLoader:Hr,load:Dr,provide:Fr,getSync:Or}=_({fallbackImport:()=>import("./client-stream")}),zr=Hr,qr=Dr,jr=Or,{setLoader:_r,load:Ur,provide:Vr,getSync:Kr}=_({fallbackImport:()=>import("./client-dispatch")}),Qr=_r,Jr=Ur,Gr=Kr,{setLoader:Yr,load:Xr}=_({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Zr=Yr,eo=Xr,{setLoader:to,load:ro}=_({fallbackImport:()=>import("@runtypelabs/persona/voice-client-tools")}),oo=to,no=ro;function ao(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function so(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function io(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}t=h(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}),r=h((e,r,o)=>{var n,a,s=o&&o.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=o&&o.__exportStar||function(e,t){for(var r in e)"default"!==r&&!Object.prototype.hasOwnProperty.call(t,r)&&s(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let l=t();function d(e,t=l.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return c(e.trim(),t)}Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return l.Allow}}),i(t(),e),n=class extends Error{},e.PartialJSON=n,a=class extends Error{},e.MalformedJSON=a,e.parseJSON=d;let c=(e,t)=>{let r=e.length,o=0,s=e=>{throw new n(`${e} at position ${o}`)},i=e=>{throw new a(`${e} at position ${o}`)},d=()=>(m(),o>=r&&s("Unexpected end of input"),'"'===e[o]?c():"{"===e[o]?p():"["===e[o]?u():"null"===e.substring(o,o+4)||l.Allow.NULL&t&&r-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):"true"===e.substring(o,o+4)||l.Allow.BOOL&t&&r-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):"false"===e.substring(o,o+5)||l.Allow.BOOL&t&&r-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):"Infinity"===e.substring(o,o+8)||l.Allow.INFINITY&t&&r-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):"-Infinity"===e.substring(o,o+9)||l.Allow._INFINITY&t&&1<r-o&&r-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):"NaN"===e.substring(o,o+3)||l.Allow.NAN&t&&r-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):h()),c=()=>{let n=o,a=!1;for(o++;o<r&&('"'!==e[o]||a&&"\\"===e[o-1]);)a="\\"===e[o]&&!a,o++;if('"'==e.charAt(o))try{return JSON.parse(e.substring(n,++o-Number(a)))}catch(e){i(String(e))}else if(l.Allow.STR&t)try{return JSON.parse(e.substring(n,o-Number(a))+'"')}catch{return JSON.parse(e.substring(n,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},p=()=>{o++,m();let n={};try{for(;"}"!==e[o];){if(m(),o>=r&&l.Allow.OBJ&t)return n;let a=c();m(),o++;try{n[a]=d()}catch(e){if(l.Allow.OBJ&t)return n;throw e}m(),","===e[o]&&o++}}catch{if(l.Allow.OBJ&t)return n;s("Expected '}' at end of object")}return o++,n},u=()=>{o++;let r=[];try{for(;"]"!==e[o];)r.push(d()),m(),","===e[o]&&o++}catch{if(l.Allow.ARR&t)return r;s("Expected ']' at end of array")}return o++,r},h=()=>{if(0===o){"-"===e&&i("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(l.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}i(String(r))}}let n=o;for("-"===e[o]&&o++;e[o]&&-1===",]}".indexOf(e[o]);)o++;o==r&&!(l.Allow.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(n,o))}catch{"-"===e.substring(n,o)&&s("Not sure what '-' is");try{return JSON.parse(e.substring(n,e.lastIndexOf("e")))}catch(e){i(String(e))}}},m=()=>{for(;o<r&&" \n\r\t".includes(e[o]);)o++};return d()};e.parse=d})();let lo="ask_user_question",co="data-persona-ask-sheet-for",po="Type your own answer here",uo="Send",ho="data-ask-question-count",mo="data-ask-answers",go="data-ask-grouped",fo=!1,bo=e=>e.replace(/["\\]/g,"\\$&"),yo=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,vo=e=>e?.features?.askUserQuestion??{},wo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:o};let n=t.chunks;if(!n||0===n.length)return{payload:null,complete:o};try{let e=n.join(""),t=(0,r.parse)(e,r.STR|r.OBJ|r.ARR);if(t&&"object"==typeof t)return{payload:t,complete:o}}catch{}return{payload:null,complete:o}},xo=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!fo&&(fo=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Co={sheetBackground:"--persona-ask-sheet-bg",sheetBorder:"--persona-ask-sheet-border",sheetShadow:"--persona-ask-sheet-shadow",pillBackground:"--persona-ask-pill-bg",pillBackgroundSelected:"--persona-ask-pill-bg-selected",pillTextColor:"--persona-ask-pill-fg",pillTextColorSelected:"--persona-ask-pill-fg-selected",pillBorderRadius:"--persona-ask-pill-radius",customInputBackground:"--persona-ask-input-bg"},So=(e,t)=>{Object.entries(Co).forEach(([r,o])=>{let n=z(t,`features.askUserQuestion.styles.${r}`);"string"==typeof n&&n?e.style.setProperty(o,n):e.style.removeProperty(o)})},ko=(e,t,r)=>{if("rows"!==e)return null;let o=st("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let e=st("span","persona-ask-row-check");o.appendChild(e)}else{let e=st("span","persona-ask-row-badge");e.textContent=String(r+1),o.appendChild(e)}return o},Ao=e=>{let t=st("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},Mo=(e,t)=>{let r=st("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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=e.freeTextPlaceholder??po,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),"rows"!==t){let t=st("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??uo,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Io=e=>{let t=e.getAttribute(mo);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},To=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Eo=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Lo=e=>"true"===e.getAttribute(go),Bo=(e,t,r)=>{let o=vo(r),n=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=wo(t),i=Lo(e),l=To(e),d=Eo(e),c=i?((e,t)=>xo(e)[t]??null)(a,l):(e=>xo(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,o)=>{let n=st("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");n.setAttribute("role","group"),n.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++)n.appendChild(Ao(o));return n}if(s.forEach((e,t)=>{n.appendChild(((e,t,r,o)=>{let n=st("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(n.type="button",n.setAttribute("role",o?"checkbox":"button"),n.setAttribute("aria-pressed","false"),n.setAttribute("data-ask-user-action","pick"),n.setAttribute("data-option-index",String(t)),n.setAttribute("data-option-label",e.label),"rows"===r){let a=st("span","persona-ask-row-content"),s=st("span","persona-ask-row-label");if(s.textContent=e.label,a.appendChild(s),e.description){let t=st("span","persona-ask-row-description");t.textContent=e.description,a.appendChild(t)}n.appendChild(a);let i=ko(r,o,t);i&&n.appendChild(i)}else n.textContent=e.label,e.description&&(n.title=e.description);return n})(e,t,o,a))}),!1!==e?.allowFreeText){let e="rows"===o?"Other":"Other…";if("rows"===o){let r=st("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=st("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??po,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=ko(o,a,s.length);d&&r.appendChild(d),n.appendChild(r)}else{let r=st("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,n.appendChild(r)}}return n})(c,o,s,n);g.replaceWith(e)}if("rows"!==n){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(Mo(o,n))}let f=e.querySelector('[data-ask-multi-actions="true"]');i||!p||f?(!p||i)&&f&&f.remove():e.appendChild((e=>{let t=st("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=st("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=e.submitLabel??uo,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(o)),e.setAttribute("data-multi-select",p?"true":"false");let b=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let o=st("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=st("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=r.backLabel??"Back",n.setAttribute("data-ask-user-action","back"),n.disabled=0===e,o.appendChild(n);let a=st("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=st("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=st("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),o.appendChild(a),o})(l,d,o);b?b.replaceWith(t):e.appendChild(t)}else b&&b.remove();(e=>{let t=Io(e)[To(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(e=>{let t=e.getAttribute("data-option-label")??"",o=r.has(t);e.setAttribute("aria-pressed",o?"true":"false"),e.classList.toggle("persona-ask-pill-selected",o)});let n=new Set(Array.from(o).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!n.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Lo(e))return;let t=Io(e)[To(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!r);let n=e.querySelector('[data-ask-user-action="submit-multi"]');n&&(n.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},Ro=(e,t,r)=>{if(!r||!yo(e)||!1===vo(t).enabled)return;let o=e.toolCall.id;r.querySelectorAll(`[${co}]`).forEach(e=>{e.getAttribute(co)!==o&&e.remove()});let n=r.querySelector(`[${co}="${bo(o)}"]`);if(n)return void((e,t,r)=>{So(e,r);let{payload:o}=wo(t),n=Math.max(1,xo(o).length);n>Eo(e)&&(e.setAttribute(ho,String(n)),n>1&&!Lo(e)&&e.setAttribute(go,"true")),Bo(e,t,r)})(n,e,t);let{payload:a}=wo(e),s=((e,t,r)=>{let o=vo(t),n=(e=>"pills"===e.layout?"pills":"rows")(o),a=e.toolCall.id,s=xo(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 o={};return t.forEach((e,t)=>{let n="string"==typeof e?.question?e.question:"";if(n&&Object.prototype.hasOwnProperty.call(r,n)){let e=r[n];("string"==typeof e||Array.isArray(e))&&(o[t]=e)}}),o})(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=st("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(co,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(ho,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(go,l?"true":"false"),p.setAttribute("data-ask-layout",n),((e,t)=>{e.setAttribute(mo,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==o.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),So(p,t);let u=st("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=st("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",u.appendChild(h);let m=st("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",u.appendChild(m),p.appendChild(u);let g=st("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");return g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==n&&p.appendChild(Mo(o,n)),Bo(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},Po=(e,t)=>{if(!e)return;let r=t?`[${co}="${bo(t)}"]`:`[${co}]`;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)})},No="suggest_replies",$o={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},Wo={name:No,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:$o,origin:"sdk",annotations:{readOnlyHint:!0}},Ho=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,Do=(e,t=4)=>{let r=e;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}let o=r?.suggestions;if(!Array.isArray(o))return[];let n=o.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>t?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of ${t}; extra suggestions dropped.`),n.slice(0,t)):n},Fo=(e,t=4)=>{for(let r=e.length-1;r>=0;r--){let o=e[r];if("user"===o.role)return null;if(!Ho(o))continue;let n=Do(o.toolCall?.args,t);return n.length>0?n:null}return null},Oo=new Set,zo=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,o=e=>{let o=t?.[e],n=r?.[e];void 0!==o&&void 0!==n&&o!==n&&((e,t,r)=>{let o=`${e}:${t}:${r}`;Oo.has(o)||(Oo.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,n,o)};e&&(o("enabled"),o("expose"));let n=t?.enabled??r?.enabled??!0;return{enabled:n,expose:!!n&&(t?.expose??r?.expose??!1)}},qo={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},jo={name:lo,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:qo,origin:"sdk",annotations:{readOnlyHint:!0}},_o=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(jo),zo(e).expose&&t.push((e=>{let t=e?.suggestions?.followUps?.maxItems,r="number"==typeof t&&Number.isFinite(t)?Math.max(1,Math.floor(t)):e?.future?.v5Defaults?5:4;return 4===r?Wo:{...Wo,parametersSchema:{...$o,properties:{suggestions:{...$o.properties.suggestions,maxItems:r,description:`1-${r} short, distinct follow-up replies, phrased in the user's voice.`}}}}})(e)),t},Uo=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Vo=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),Ko=()=>(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return null===e?null:{text:e,raw:r};let n=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/)?.[1]||e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/)?.[1];if(!t)return null;try{return Uo(t)}catch{return t}})(r);return null!==n&&(e=n),t=r.length,null===e?null:{text:e,raw:r}},close:async()=>{}}})(),Qo=()=>{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 null!==e||""===e?{text:e||"",raw:o}:null;try{let t=(0,r.parse)(o,r.STR|r.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?Uo(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=Uo(t.text)))}catch{}return t=o.length,null===e?null:{text:e,raw:o}},close:()=>{}}},Jo=()=>{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}},Go="4.35.1",{setLoader:Yo,load:Xo,provide:Zo}=_({fallbackImport:()=>import("./client-history")}),en=Yo,tn=Xo;o=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let rn=e=>"reason"in e?e.reason:void 0;n=class{#e;#t;#r;#o;#n;#a;#s;#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;get clientSession(){return this.#g}set clientSession(e){this.#g=e,e&&(this.#f=e.config?.webmcp?.requireConfirmFor??[])}#b;#y;#v;#w;#x;#C;#S;#k;#A;#M;#I;constructor(e={},t={}){if(this.#u=0,this.#h=new Set,this.#m=null,this.#g=null,this.#f=null,this.#b=null,this.#y=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#v=null,this.#w=!1,this.#x=!1,this.#C=!1,this.#S=null,this.#k=new Set,this.#A=new Set,this.webMcpBridge=null,this.#M=null,this.#T=null,this.#E=null,this.#n=e,this.#o=t,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??"https://api.runtype.com/v1/dispatch",this.#t={"Content-Type":"application/json","X-Persona-Version":Go,...e.headers},this.#r=!!e.debug,this.#a=e.streamParser??function(e){switch(e){case"json":return Qo;case"regex-json":return Ko;case"xml":return Jo;default:return Vo}}(e.parserType),this.#s=e.contextProviders??[],this.#i=e.requestMiddleware,this.#l=e.customFetch,this.#d=e.parseSSEEvent,this.#c=e.getHeaders,!0===e.webmcp?.enabled&&(this.#M=this.#L(e.webmcp))}#L(e){return eo().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:tr,getToolDisplayTitle:rr,loadPolyfill:lr,getRequireConfirmFor:()=>this.#B()});return void 0!==this.#I&&r.setConfirmHandler(this.#I),this.webMcpBridge=r,r}).catch(e=>(this.#M=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",e),null))}#R(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):!0===this.#n.webmcp?.enabled?(this.#M||=this.#L(this.#n.webmcp),this.#M):Promise.resolve(null)}updateConfig(e){this.#n=e}setHistoryInternals(e){this.#o=e}cancelStreams(){if(this.#u+=1,this.#n.backgroundConversations)for(let e of this.#h)e.cancel().catch(()=>{})}setSSEEventCallback(e){this.#p=e}setWebMcpConfirmHandler(e){this.#I=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return!0===this.webMcpBridge?.isOperational()}getVoiceClientTools(){if(!0!==this.#n.webmcp?.enabled)return null;let e=()=>this.#R(),t={open:async e=>(await no()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await((await e())?.snapshotForDispatch())??[];return{tools:t,fingerprint:nr(t)}},onChange:t=>{let r=null,o=!1;return e().then(e=>{e&&!o&&(r=e.watchToolChanges(t))}),()=>{o=!0,r?.()}},execute:async(t,r,o)=>{let n=await e();return n?n.executeVoiceToolCall(t,r,await this.#P(o)):{status:"failed",error:{message:"WebMCP runtime failed to load."}}}};return t}#B(){return this.isClientTokenMode()?this.#f:void 0}async#P(e){return e.autoConfirmReadOnly&&this.isClientTokenMode()&&!this.clientSession&&await this.initSession().catch(()=>{}),e}executeWebMcpToolCall(e,t,r,o){return!0===this.#n.webmcp?.enabled?this.#R().then(n=>n?n.executeToolCall(e,t,r,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]}):null}getSSEEventCallback(){return this.#p}isClientTokenMode(){return!!this.#n.clientToken}#N(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.#n;if(!r)return{agentId:e,flowId:t};let n=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let e=r.slice(0,o),n=r.slice(o+1);if("runtype"===e){let e=ao(n);if(e)return e;throw Error(`[Persona] target "runtype:${n}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw 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(n).payload}}let n=ao(r);if(n)return n;let a=t?.default;if(a)return{kind:"payload",payload:a(r).payload};throw 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,o);return"agentId"===n.kind?{agentId:n.agentId}:"flowId"===n.kind?{flowId:n.flowId}:{targetPayload:n.payload}}isAgentMode(){return!(!this.#n.agent&&!this.#N().agentId)}#$(){return this.#n.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||"https://api.runtype.com"}#W(e){return`${this.#$()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),r=!1;for(;;){let n=t.conversationId,a=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!n||!a)throw new o("visitor_token_missing","Durable recovery is not enabled for this client session");let s=`${this.#$()}/v1/client/conversations/${encodeURIComponent(n)}/executions/${encodeURIComponent(e.executionId)}/events`,i=new URLSearchParams({sessionId:t.sessionId,after:e.after}),l=await fetch(`${s}?${i}`,{method:"GET",headers:{"X-Persona-Version":Go,"X-Visitor-Token":a},signal:e.signal});if(401!==l.status||r){if(!l.ok)throw await(await tn()).historyErrorFor(this.#H(),l,!0);return l}{r=!0;let e=await tn();t=await e.recoverFromUnauthorized(this.#H(),await e.readErrorCode(this.#H(),l),null,!0)}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#b||e&&new Date<e.expiresAt||this.#y===e?null:(this.#y=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#b)return this.#b;let e=this.#b=this.#D().then(t=>this.#b===e?(this.clientSession=t,this.#y=!1,this.resetClientToolsFingerprint(),this.#n.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#b===e&&(this.#b=null)});return e}#F(){return!0===this.#n.features?.history?.enabled&&this.isClientTokenMode()&&!this.#w}async readVisitorToken(){let e=this.#o.visitorStore;return e?(await e.ready,await e.get()??null):null}#O(){if(!this.#w){this.#z({state:"unavailable",reason:"history_disabled"}),this.#w=!0,!this.#x&&typeof console<"u"&&(this.#x=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.#o.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#A])e(!1)}}getHistoryIdentityStatus(){return this.#S??this.#q()}subscribeHistoryIdentityStatus(e){return this.#k.add(e),()=>{this.#k.delete(e)}}subscribeHistoryAvailability(e){return this.#A.add(e),this.#w&&e(!1),()=>{this.#A.delete(e)}}#q(){return this.isClientTokenMode()?!0!==this.#n.features?.history?.enabled||this.#w?{state:"unavailable",reason:"history_disabled"}:this.#j():{state:"unavailable",reason:"ineligible_mode"}}#j(){let e=this.#S;return"browser_only"===e?.state?e:this.#_()}#_(){return"browser"===this.#n.features?.history?.scope?{state:"browser_only",reason:"configured_browser_scope"}:this.#n.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#z(e){let t=this.getHistoryIdentityStatus(),r=t.state===e.state&&rn(t)===rn(e);if(this.#S=e,!r){this.#o.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#k])t(e)}}async#U(e){return new((Gr()??await Jr()).ClientDispatch)(this.#V()).createClientSession(e)}async#D(){return new((Gr()??await Jr()).ClientDispatch)(this.#V()).initializeSession()}async#K(e){let t=this.#n.getStoredSessionId?.()||null,r=this.#n.getStoredConversationId?.()||null,o=await this.#U({storedSessionId:t,identityProof:e}),n=this.#Q(o,r,!1);return this.clientSession=n,this.#b=null,this.#y=!1,this.resetClientToolsFingerprint(),n}#Q(e,t,r){let o=e.conversationId;return o&&t&&(r||o!==t)&&this.#o.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:o}),this.#n.setStoredSessionId?.(e.sessionId),o&&(this.#n.setStoredConversationId?.(o),this.#o.setStoredConversationRevision?.(e.conversationRevision??null)),e}#J(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#y=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error("prepareConversationSession() only available in client token mode");if(!this.#F())throw new o("history_disabled","Visitor history is disabled for this surface");await this.#o.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new o("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let n=await this.#U({conversationId:e,identityProof:r});return this.#J(n)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.#o.historyBootstrapReady;let e=await this.#U({});return this.#J(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#F()&&this.#z(this.#_())}clearClientSession(){this.clientSession=null,this.#b=null,this.#y=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#v=null}async sendFeedback(e){if(!this.isClientTokenMode())throw Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw Error("No active session. Please initialize session first.");return new((Gr()??await Jr()).ClientDispatch)(this.#V()).sendFeedback(e)}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#G(e){e?.throwIfAborted();let t=this.#n.identityProvider;if(void 0===t)return;let r,o,n=this.#n.getIdentityProof;if(!t.trim()||!n)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,r)=>{o=()=>r(e.reason),e.addEventListener("abort",o,{once:!0}),e.aborted&&o()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{o&&e?.removeEventListener("abort",o)}if("string"!=typeof r||!r.trim())throw Error("A fresh identity proof is required to send this message.");return{provider:t,token:r}}#T;#Y(){let e=this;return this.#T??={get config(){return e.#n},headers:this.#t,getHeaders:this.#c,debug:this.#r,clientApiBase:()=>e.#$(),getClientApiUrl:t=>e.#W(t),getWebMcpBridge:()=>e.#R(),sendWithClientToolsDiff:(t,r,o,n)=>e.#X(t,r,o,n),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#E;#H(){let e=this;return this.#E??={HistoryClientError:o,get config(){return e.#n},get historyInternals(){return e.#o},get clientSession(){return e.clientSession},clientApiBase:()=>e.#$(),setHistoryIdentityStatus:t=>e.#z(t),browserOnlyStatus:()=>e.#j(),derivedBrowserOnly:()=>e.#_(),reinitWithProof:t=>e.#K(t),isHistoryCapable:()=>e.#F(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await tn()).listConversations(this.#H(),e)}async getConversation(e,t){return(await tn()).getConversation(this.#H(),e,t)}async finalizeDisplayProjections(e,t){return(await tn()).finalizeDisplayProjections(this.#H(),e,t)}async deleteConversation(e,t){return(await tn()).deleteConversation(this.#H(),e,t)}async deleteAllConversations(e){return(await tn()).deleteAllConversations(this.#H(),e)}async resetVisitor(){return(await tn()).resetVisitor(this.#H())}async dispatch(e,t){e.signal?.throwIfAborted(),qr().catch(()=>{});let r=this.isClientTokenMode(),o=this.isAgentMode(),n=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;r&&(this.#m=n),t({type:"status",status:"connecting"});let a=Gr()??await Jr().catch(e=>{let o=e instanceof Error?e:Error(String(e));throw r&&this.#m!==n||t({type:"error",error:o}),o});if(e.signal?.throwIfAborted(),r&&this.#m!==n)throw new DOMException("Turn superseded","AbortError");let s=new a.ClientDispatch(this.#V());return r?s.dispatchClientToken(e,t,n):o?s.dispatchAgent(e,t):s.dispatchProxy(e,t)}#V(){let e=this;return Object.setPrototypeOf({HistoryClientError:o,get claimInFlight(){return e.#C},set claimInFlight(t){e.#C=t},get clientToolsFingerprintSessionId(){return e.clientToolsFingerprintSessionId},set clientToolsFingerprintSessionId(t){e.clientToolsFingerprintSessionId=t},get lastSentClientToolsFingerprint(){return e.lastSentClientToolsFingerprint},set lastSentClientToolsFingerprint(t){e.lastSentClientToolsFingerprint=t},get sentNonEmptyClientToolsSessionId(){return e.#v},set sentNonEmptyClientToolsSessionId(t){e.#v=t},get historyInternals(){return e.#o},markHistoryUnavailable:()=>e.#O(),apiUrl:this.#e,contextProviders:this.#s,requestMiddleware:this.#i,customFetch:this.#l,get clientSession(){return e.clientSession},set clientSession(t){e.clientSession=t},isCurrentTurn:t=>e.#m===t,isHistoryCapable:()=>e.#F(),createClientSession:t=>e.#U(t),finishInit:(t,r,o)=>e.#Q(t,r,o),resetSessionWarmLatch:()=>{e.#y=!1},resetClientToolsFingerprint:()=>e.resetClientToolsFingerprint(),clearClientSession:()=>e.clearClientSession(),resolveChatIdentityProof:t=>e.#G(t),routing:()=>e.#N(),builtInClientTools:_o,streamResponse:(...t)=>e.#Z(...t)},this.#Y())}async processStream(e,t,r,o,n,a,s){t({type:"status",status:"connected"});try{await this.#Z(e,t,r,o,n,a,s)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t,r){return(await qr()).resolveApproval(this.#Y(),e,t,r)}async#X(e,t,r,o){return new((Gr()??await Jr()).ClientDispatch)(this.#V()).sendWithClientToolsDiff(e,t,r,o)}async resumeFlow(e,t,r){return(await qr()).resumeFlow(this.#Y(),e,t,r)}async#Z(e,t,r,o,n,a,s){let{streamResponse:i}=jr()??await qr();return i({config:()=>this.#n,streamGeneration:()=>this.#u,streamReaders:this.#h,createStreamParser:this.#a,parseSSEEvent:this.#d,onSSEEvent:(e,t)=>this.#p?.(e,t)},e,t,r,o,n,a,s)}},a=class extends Error{constructor(e,t,r){super(t),this.name="HistoryProviderError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let{setLoader:on,load:nn}=_({fallbackImport:()=>import("@runtypelabs/persona/background-runtime")}),an=on,sn=nn,{setLoader:ln,load:dn,provide:cn,getSync:pn}=_({fallbackImport:()=>import("./session-actions")}),un=ln,hn=dn,mn=pn;function gn(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function fn(e){return{type:"text",text:e}}let bn=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yn=[...bn,"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 vn(e){return function(e){return bn.includes(e)||e.startsWith("image/")}(e.type)}function wn(e,t=yn,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 xn(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"}let Cn=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function Sn(e){return"card"===e?"collapsed":e}function kn(e){return e.split(";",1)[0].trim().toLowerCase()}function An(e,t){let r=e?.display,o="string"==typeof r?{default:r}:r??{};if(t.file&&o.files){if("string"==typeof o.files)return{mode:Sn(o.files),matchedBy:{type:"files"}};let e=t.file.mimeType?kn(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,o]of r)if(kn(e)===t)return{mode:Sn(o),selector:kn(e)};let o=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(kn(e)===o)return{mode:Sn(t),selector:o}}(o.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(o.files.default)return{mode:Sn(o.files.default),matchedBy:{type:"files"}}}let n=o.byKind?.[t.artifactType];if(n)return{mode:Sn(n),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:Sn(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:Sn(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:Sn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Mn(e,t){return An(e,t).mode}function In(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 Tn(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function En(e,t){let r=e.findIndex(e=>e.id===t);return r>=0&&"user"===e[r].role&&!e.slice(r+1).some(e=>"operator"===e.role)}function Ln(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;--t){if("operator"===e[t].role)return null;if("user"===e[t].role)return e[t].id}return null}function Bn(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 Rn(){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 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,r.parse)(o,r.STR|r.OBJ),o);t&&(e=t)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function Pn(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=bt(r,e.component);if(!a){if(vt.includes(e.component)){Tt().catch(()=>{});let e=st("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=t.context??{message:o,config:r,signal:t.signal??(new AbortController).signal,updateProps:e=>{n&&n(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Nn(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 $n(e){let t=Nn(e);if(!t)return!1;try{let e=JSON.parse(t);return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component}catch{return!1}}function Wn(e){let t=Nn(e);if(!t)return null;try{let e=JSON.parse(t);if("object"==typeof e&&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}function Hn(e,t=e.contentParts??e.llmContent??e.rawContent??e.content){let r=e.content;if("string"!=typeof r)return;let o=e.contentParts??e.llmContent??e.rawContent??r;return""===r&&(t===o||JSON.stringify(t)===JSON.stringify(o))||"string"==typeof t&&t===r?void 0:r}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(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a})}function Fn(e){for(let t of["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)"]){let r=e.find(e=>e.name===t);if(r)return r}return e.find(e=>e.lang.startsWith("en"))??e[0]}function On(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?e:t)}s=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?.(Error("Web Speech API is unavailable"));let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(n.voice=e)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Fn(a));void 0!==t.rate&&(n.rate=t.rate),void 0!==t.pitch&&(n.pitch=t.pitch),n.onend=()=>r.onEnd?.(),n.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{o.speak(n),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},i=class{#e=null;#t=null;#r="idle";#o=new Set;#n=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#r:"idle"}activeMessageId(){return this.#t}onChange(e){return this.#o.add(e),()=>this.#o.delete(e)}toggle(e,t){if(this.#t===e){if("playing"===this.#r)return void(this.#e?.supportsPause?(this.#e.pause(),this.#s(e,"paused")):this.stop());if("paused"===this.#r)return this.#e?.resume(),void this.#s(e,"playing");if("loading"===this.#r)return void this.stop()}this.play(e,t)}async play(e,t){let r=++this.#n;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#n)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#n&&this.#s(e,"playing")},onEnd:()=>{r===this.#n&&this.#s(null,"idle")},onError:()=>{r===this.#n&&this.#s(null,"idle")}})}catch{r===this.#n&&this.#s(null,"idle")}}stop(){this.#n++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#o)e(this.#t,this.#r)}},l=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!(this.#t||e&&this.#e&&e!==this.#e)}};let zn=null,qn=()=>zn?zn():import("./voice/runtype-tts-entry"),{setLoader:jn,load:_n}=_({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Un=jn,Vn=_n,Kn="apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.modelMessageTransform.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId".split(".");function Qn(e,t){let r=e instanceof Error?e:Error(String(e));if("string"==typeof t)return t;if("function"==typeof t)return t(r);let o=r.message.trim(),n=/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.?)$/i.test(o),a=/^(Chat backend|Agent execution) request failed: \d{3}\b/.test(o),s=n?"Sorry: I couldn't reach the assistant. Please check your connection and try again.":a?"Sorry: the chat service couldn't complete the request. Please try again.":"Sorry: the chat encountered an unexpected error. Please reload the page and try again.";return o?`${s}\n\n_Details: ${o}_`:s}d=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};let Jn=e=>ir(e)||"suggest_replies"===e;c=class e{#e;#t;#r;#o;#n(e){if(this.#a("cancel"),this.#r=!1,this.#e={runId:`run-${io()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:new Set},e)for(let t of this.messages)"assistant"===t.role&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;null!==this.#o&&clearTimeout(this.#o),this.#o=null;let r=this.#e;if(this.#e=null,r){let t=r;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#s(){if(!this.#e||null!==this.#o)return;let e=this.#e;this.#o=setTimeout(()=>{this.#o=null,this.#e===e&&(!this.#r&&(this.streaming||this.#u||this.#ee()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#r?"error":"success"))},0)}#i;#l;#d;#c;#p;#u;#h;#m;#g;#f;#b;#y;#v;#w;#x;#C;#S;#k;#A;#M;#I;#L;#R;#B;#P;#N;#$;#W;#F;#O;#q;#j;#_;#z;#U;#D;#K;#Q;#J;#G;#T;#Y;#E;constructor(e={},t,r={}){this.config=e,this.callbacks=t,this.historyInternals=r,this.status="idle",this.#e=null,this.#r=!1,this.#o=null,this.streaming=!1,this.#i=new Map,this.abortController=null,this.#d=Date.now(),this.clientSession=null,this.agentExecution=null,this.#c=null,this.#p=null,this.#u=!1,this.#m=null,this.#g=null,this.#f=null,this.#b=null,this.#y=null,this.#v=null,this.artifacts=new Map,this.#w=null,this.webMcpInflightKeys=new Set,this.webMcpResolvedKeys=new Set,this.webMcpResolveControllers=new Set,this.#x=0,this.webMcpApprovalResolvers=new Map,this.#C=0,this.approvalTokens=new Map,this.webMcpAwaitBatches=new Map,this.#S=null,this.#k=null,this.#A=0,this.#M=0,this.#I=!1,this.#L="disconnected",this.#R=null,this.#B=null,this.#P=null,this.#N=0,this.#$=0,this.#W=null,this.#F=Promise.resolve(),this.#O=!1,this.#q=null,this.#j=!1,this.#_=null,this.#z=new Map,this.#U=null,this.#D=new Map,this.#K=null,this.#Q=null,this.#J=!1,this.#G=null,this.#T=null,this.#Y=!1,this.#E=null,this.#X=null,this.#Z=null,this.#te=new l,this.#re=Promise.resolve(),this.#oe=null,this.#ne=null,this.ttsSpokenMessageIds=new Set,this.readAloud=new i(()=>this.#ae()),this.#se=null,this.#ie=0,this.handleEvent=(e,t=!1)=>{if(this.#m)return void this.#m.push({event:e,readOnlyReplay:t});let r=this.#ne,o=!1;if(r&&("error"===e.type||"status"===e.type&&"error"===e.status?r.failed=!0:"message"===e.type&&"assistant"===e.message.role&&(r.dropped||this.ttsSpokenMessageIds.add(e.message.id),r.ids.includes(e.message.id)||r.ids.push(e.message.id),o=!0)),"message"===e.type){this.#e&&!t&&"assistant"===e.message.role&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||"approval"===e.message.variant&&"pending"===e.message.approval?.status)&&this.#le("needs-attention"),o&&r.onUpdate?.(),"approval"===e.message.variant&&e.message.approval&&"pending"!==e.message.approval.status&&this.#i.set(e.message.id,this.#l),"assistant"===e.message.role&&!e.message.variant&&e.message.streaming&&(this.#p=e.message.id),("approval"===e.message.variant||!0===e.message.agentMetadata?.awaitingLocalTool)&&hn().catch(()=>{});let n=e.message.toolCall,a=!!n?.name&&(ir(n.name)||"suggest_replies"===n.name&&zo(this.config).enabled);!0===e.message.agentMetadata?.awaitingLocalTool&&a&&!t&&!0===this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool&&this.#de(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution&&this.agentExecution.executionId===e.message.agentMetadata.executionId?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.#h=e.checkpoint,this.#ce(e.id);else if("status"===e.type){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0},this.#le("running")),"idle"===e.status&&!e.terminal&&this.#pe())return void this.#ue();if("error"===e.status?this.#le("failed"):e.terminal&&"idle"===e.status&&this.#le("completed"),this.#he(e.status),"connecting"===e.status)this.#me(!0);else if("idle"===e.status||"error"===e.status){this.#ee()||this.#ge(),0===this.webMcpResolveControllers.size&&(this.#me(!1),this.abortController=null,this.#fe(),this.#be());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.#ye()}}else"error"===e.type?(this.#le("failed"),this.#he("error"),this.#ge(),0===this.webMcpResolveControllers.size&&(this.#me(!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.#ve(e)},this.historyInternals=this.#we(r),this.messages=[...e.initialMessages??[]].map(e=>({...cr(e),sequence:e.sequence??this.#xe()})),this.messages=this.#Ce(this.messages),this.client=new n(e,this.historyInternals),this.#Se(),this.#ke();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:"complete"});null!=e.initialSelectedArtifactId&&(this.#w=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ae(),this.callbacks.onStatusChanged(this.status),this.#V(),this.#H()}#H(){this.config.voiceRecognition?.provider&&qt().catch(()=>{})}#V(){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&&qn().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}getVoiceNotice(){return this.#S?.takeNotice?.()??null}getVoiceDisclosure(){return this.#S?.getDisclosure?.()??null}getVoiceLevel(){return this.#S?.onLevel?this.#M:null}getVoiceInterruptionMode(){return this.#S?.getInterruptionMode?this.#S.getInterruptionMode():"none"}stopVoicePlayback(){this.#S?.stopPlayback&&(this.#te.cancel(),this.#oe?.cancel(),this.#S.stopPlayback())}isBargeInActive(){return this.#S?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#S?.deactivateBargeIn&&await this.#S.deactivateBargeIn()}#X;#Z;#te;#re;#oe;#ne;#ae(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=s.isSupported()?new s({pickVoice:e?.pickVoice}):null;if("runtype"===e?.provider){let r=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,n=this.config.clientToken,a=!1!==e.browserFallback;if(r&&o&&n)return qn().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:o,clientToken:n,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 n&&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 Error("Voice configuration not provided");this.cleanupVoice();let r=this.#re,o=++this.#A;this.#k=qt().then(async e=>{await r,o===this.#A&&this.#Me(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{o===this.#A&&(this.#k=null)})}catch(e){console.error("Failed to setup voice:",e)}}#Me(e,t){this.#S=t;let r=this;e.wireSessionVoice({session:this,provider:()=>r.#S,generation:()=>r.#A,get keyed(){return r.#oe},set keyed(e){r.#oe=e},get pendingUser(){return r.#X},set pendingUser(e){r.#X=e},get pendingAssistant(){return r.#Z},set pendingAssistant(e){r.#Z=e},turns:()=>r.#te,busy:()=>r.#Ie(),setStreaming:e=>r.#me(e),setDelegation:e=>{r.#ne=e},setLevel:e=>{r.#M=e},setStatus:e=>{r.#L=e,r.#I="listening"===e},settlePending:e=>r.#Te(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#A;if(!this.#S&&this.#k&&await this.#k,e===this.#A)if(this.#S)if(this.#I)await this.#S.stopListening();else{this.stopSpeaking();try{await this.#S.startListening()}catch(e){console.error("Failed to start voice:",e)}}else console.error("Voice not configured")}prewarmVoice(){if(!_t(this.config.voiceRecognition?.provider))return void this.warmClientSession();let e=this.#A,t=()=>{let t=this.#S;t?.prewarm&&e===this.#A&&(this.#I||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#S&&this.#k?this.#k.then(t,()=>{}):t()}#Ie(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#u||"resuming"===this.status}cleanupVoice(){let e=null!==this.#S;if(this.#A++,this.#k=null,this.#S){let e=this.#S;this.#S=null,this.#re=this.#Ee(e)}this.#I=!1,this.#L="disconnected",this.#Te(!0),this.#oe?.settle(),this.#oe=null,this.#te=new l,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#Ee(e){try{await e.disconnect()}catch(e){console.error("Failed to disconnect voice:",e)}}#Te(e){let t=e?this.#X:null,r=this.#Z;(t||r)&&(r&&this.#te.cancel(),e&&(this.#X=null),this.#Z=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.#me(!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.#Q=this.historyInternals.getStoredConversationRevision?.()??null,this.#J=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e: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.#Le(e,t)}#Le(e,t=!this.messages.length){if(this.#O||!e.config.welcomeMessage||!t)return;let r=this.messages[0],o={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:r?.createdAt??(new Date).toISOString(),sequence:r?(r.sequence??0)-1:this.#xe()};this.#Be(o)}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){e.historyProvider!==this.historyInternals.historyProvider&&(this.#N+=1,this.#$+=1,this.config.backgroundConversations&&this.cancel(),this.#Re()),this.historyInternals=this.#we(e),this.client.setHistoryInternals(this.historyInternals),this.#Se()}destroy(){this.#Re(),this.#N+=1,this.#$+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#G?.(),this.#G=null,this.#T=null}#we(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#Pe(e),t?.(e)}}}get#Ne(){return this.historyInternals.historyProvider??null}#$e(){let e=this.#Ne;if(!e)throw new d("history_unavailable","No conversation history provider is installed");return e}#We(e){let t=this.#$e(),r=e??this.config.features?.history?.scope,o=this.config.getIdentityProof?"verified-user":"browser",n=r??(t.capabilities.scopes.includes(o)?o:t.capabilities.scopes[0]??o);if(!t.capabilities.scopes.includes(n))throw new a("unsupported_scope","This history scope is not supported.");return{scope:n}}getHistoryState(){return{activeConversationId:this.#R,conversationRevision:this.#B,nextMessageCursor:this.#P,recovery:this.#q,sendBlocked:this.#j}}getActiveConversationId(){return this.#R}#He(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#De(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#_;e&&await e.catch(()=>{});let t=this.#U;t&&await t.catch(()=>{})}#Fe(){if(this.streaming||"paused"===this.status||"resuming"===this.status)throw new d("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#$e().list({...e?.cursor?{cursor:e.cursor}:{},...void 0===e?.limit?{}:{limit:e.limit},...void 0===e?.targetId?{}:{targetId:e.targetId},context:this.#We(e?.scope)})}async openConversation(e,t){let r=this.#$e();"background"===t?.busy&&this.assertBackgroundSwitchable(),"stop"===t?.busy&&this.cancel(),"background"!==t?.busy&&this.#Fe();let o=this.#We(t?.scope),n=++this.#N,a=this.#$;if("background"===t?.busy&&await this.#Oe(),await this.awaitHistorySettled(),n!==this.#N)throw new d("superseded","A later selection won");let s=await r.getPage(e,{context:o});if(n!==this.#N)throw new d("superseded","A later selection won");let i=await r.prepareOpen(e,{context:o}),l=this.#F.then(async()=>{if(n!==this.#N)throw i.discard(),new d("superseded","A later selection won");"stop"===t?.busy&&this.cancel();try{"background"===t?.busy?this.assertBackgroundSwitchable():this.#Fe()}catch(e){throw i.discard(),e}let o=this.#R,l=this.#e;t?.onBeforeCommit?.(),"background"===t?.busy&&(this.#m=[]),this.#O=!0,this.#W=a;try{if(await this.#ze(i),a!==this.#$||r!==this.#Ne)throw new d("superseded","The history identity changed");if("background"===t?.busy&&o&&this.#c){let e={conversationId:o,handle:this.#c,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#w,streamCheckpoint:this.#h};this.#g?.save(e)}this.#R=i.conversationId||e,this.#B=i.conversationRevision||s.conversationRevision||null,this.#P=s.nextCursor,this.#q=null,this.#j=!1,this.#qe();for(let e of s.messages)this.#D.set(e.id,e.content);this.#je();let n=this.#g?.take(this.#R);return this.hydrateMessages(n?.messages??s.messages),n&&(this.hydrateArtifacts(n.artifacts,n.selectedArtifactId,!0),this.#_e(n)),t?.onCommitted?.(),this.#He(),{summary:s.summary,nextMessageCursor:s.nextCursor}}finally{this.#O=!1,this.#W=null;let e=this.#m;if(this.#m=null,e&&this.#e===l&&this.#R===o)for(let{event:t,readOnlyReplay:r}of e)this.handleEvent(t,r)}}),c=l.then(()=>{},()=>{});this.#F=c,this.#_=c;try{return await l}finally{this.#_===c&&(this.#_=null)}}loadOlderMessages(e,t,r){let o=this.#$e(),n=this.#We(r?.scope),a=t??this.#P;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let s=`${e} ${a}`,i=this.#z.get(s);if(i)return i;let l=this.#Ue(o,e,a,n).finally(()=>{this.#z.delete(s)});return this.#z.set(s,l),l}async#Ue(e,t,r,o){let n=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...n?{beforeCreatedAt:n}:{},context:o});if(this.#R&&this.#R!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=this.#Ve(a.messages),i=Dn(this.messages,s);this.messages=this.#Ce(i.map(e=>this.#Ke(e))),this.#P=a.nextCursor;for(let e of a.messages)this.#D.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#He(),{messages:s,nextMessageCursor:a.nextCursor}}#Ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let r=t.get(e.id);if(r){if(this.webMcpApprovalResolvers.has(r.id)||r.approval&&dr(r.approval)&&r.approval.id===e.approval?.id&&"pending"!==r.approval.status&&"pending"===e.approval?.status)return r;let t=r.agentMetadata?.executionId,o=[...r.toolCall?[r.toolCall]:[],...r.tools??[]];if(t&&o.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return r}return cr(e)})}async startNewConversation(e){let t=this.#$e(),r=this.#We(e?.scope),o=++this.#N,n=this.#$;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:r}),s=this.#F.then(async()=>{if(o!==this.#N)throw a.discard(),new d("superseded","A later action won");e?.onBeforeCommit?.(),this.#O=!0,this.#W=n;try{await this.#ze(a)}finally{this.#O=!1,this.#W=null}if(n!==this.#$||t!==this.#Ne)throw new d("superseded","The history identity changed");this.#Qe(!1,!0),this.#R=a.conversationId||null,this.#B=a.conversationRevision||null,this.#P=null,this.#q=null,this.#j=!1,this.#je(),this.clientSession&&this.#Le(this.clientSession),e?.onCommitted?.(),this.#He()}),i=s.then(()=>{},()=>{});this.#F=i,this.#_=i;try{await s}finally{this.#_===i&&(this.#_=null)}}async#Je(e,t=!1){this.#Qe(t),await this.#ze(e),this.#R=e.conversationId||null,this.#B=e.conversationRevision||null,this.#P=null,this.#q=null,this.#j=!1,this.#je(),this.#He()}async deleteConversation(e,t){let r=this.#$e(),o=this.#We(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:o}),this.#g?.clear(e),e===this.#R&&await this.#Ge(o)}async updateConversation(e,t,r){let o=this.#$e();if(!o.update)throw new d("history_unavailable","This history provider cannot update conversations");let n=this.#We(r?.scope);return await this.awaitHistorySettled(),o.update(e,t,{context:n})}canUpdateConversations(){return"function"==typeof this.#Ne?.update}async clearConversationHistory(e){let t=this.#$e(),r=this.#We(e?.scope);await this.awaitHistorySettled();let o=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return this.#Re(),await this.#Ge(r),o}async resetHistoryDevice(){let e=this.#$e();if(!e.resetDevice)throw new d("history_unavailable","This history provider cannot reset the device");this.#Re(),this.#N+=1,this.#$+=1,this.#U=null;try{return await e.resetDevice()}finally{this.#Qe(),this.#R=null,this.#B=null,this.#P=null,this.#q=null,this.#j=!1,this.#He()}}async#Ge(e){this.#N+=1,this.#$+=1,this.#U=null,this.#Qe(),this.#R=null,this.#B=null,this.#P=null,this.#j=!0,this.#q=null,this.#He(),await this.#Ye(e)}async#Ye(e){let t=this.#Ne;if(t)try{let r=await t.prepareStartNew({context:e});await this.#Je(r)}catch{this.#j=!0,this.#q="new_conversation_required",this.#He(),this.#De("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}else this.#j=!1,this.#He()}async#Xe(){if("new_conversation_required"===this.#q&&this.#Ne&&(this.#q=null,await this.#Ye(this.#We()),"new_conversation_required"===this.#q))throw new d("new_conversation_required","A new conversation is required before sending")}async#ze(e){if(await e.commit(),null!==this.#W&&this.#W!==this.#$)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(null===this.#W||this.#W===this.#$)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#R=e.conversationId,this.#B=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#O||this.#Le(e))}#je(){this.#R?this.config.setStoredConversationId?.(this.#R):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#B),this.historyInternals.setStoredMessageCursor?.(this.#P)}#qe(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ze(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#D.clear(),this.#et(null)}#Qe(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ie++,this.messages=[],this.#qe(),this.#z.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#me(!1),this.#he("idle"),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a("cancel")}#Pe(e){this.#Re(),this.#N+=1,this.#$+=1,this.#U=null,this.#j=!0,this.#Qe(),this.#R=e.conversationId,this.#B=null,this.#P=null,this.#q=null,this.#He(),this.#De("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#_=Promise.resolve().then(()=>{this.#j=!1,this.#_=null,this.#He()})}#Se(){let e=this.historyInternals.visitorStore??null;e!==this.#T&&(this.#G?.(),this.#G=null,this.#T=e,e&&(this.#G=e.subscribe(e=>this.#ot(e))))}#ot(e){if("external"!==e.source||null===e.previousToken)return;this.#Re(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#N+=1,this.#$+=1,this.#U=null,this.#Y=!0,this.#E=null;let t=this.messages.length>0;t||null!==this.#R||null!==(this.config.getStoredConversationId?.()??null)?this.#Qe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#z.clear(),this.#et(null)),this.#R=null,this.#B=null,this.#P=null,this.#q=null,this.#He(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#De("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#nt(){return this.#Y?(this.#E||=this.#at().finally(()=>{this.#E=null}),this.#E):Promise.resolve()}async#at(){if(this.isClientTokenMode())try{this.bindActivatedSession(await this.client.initSession()),this.#Y=!1}catch{}else this.#Y=!1}reconcileBootConversation(e){let t=this.#Ne,r=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#R;if(!t||!r)return Promise.resolve();let o=this.#We(e?.scope);this.#j=!0,this.#He();let n=this.#st(t,r,o).finally(()=>{this.#j=null!==this.#q,this.#_===n&&(this.#_=null),this.#He()});return this.#_=n,n}async#st(e,t,r){this.#R=t;let o=this.clientSession?.conversationRevision??this.#B??null,n=this.#J?this.#Q:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#J=!1,this.#P=this.historyInternals.getStoredMessageCursor?.()??this.#P,await this.replayPendingProjections(),o&&n&&o===n)return void(this.#B=o);let a,s=await e.getPage(t,{context:r}),i=this.#Ve(s.messages),l=new Set(s.messages.map(e=>e.id)),d=this.messages.some(e=>l.has(e.id)),c=s.messages[0]?.createdAt;if(d){let e=this.#c?this.#p:null;a=Dn(this.messages.filter(t=>!(!l.has(t.id)&&t.id!==e)||void 0!==c&&t.createdAt<c),i).map(e=>this.#Ke(e))}else a=i.map(e=>this.#Ke(e));this.#P=s.nextCursor,this.#B=s.conversationRevision||o||null,this.#D.clear();for(let e of s.messages)this.#D.set(e.id,e.content);this.#je(),this.#t=void 0,this.messages=this.#Ce(a),this.callbacks.onMessagesChanged([...this.messages])}#it(){return!0===this.config.features?.history?.enabled&&this.isClientTokenMode()}#et(e){this.#K=e,this.historyInternals.setPendingDisplayProjections?.(e)}#lt(){return this.historyInternals.getPendingDisplayProjections?.()??this.#K}#dt(e){if(this.#it())for(let t of e){let e=Hn(t);void 0!==e&&this.#D.set(t.id,e)}}#be(){if(!this.#it())return;let e=this.#R;if(!e)return;let t=[];for(let e of this.messages){if("assistant"!==e.role||e.streaming)continue;let r=Hn(e);void 0!==r&&this.#D.get(e.id)!==r&&t.push({id:e.id,displayContent:r})}0!==t.length&&(this.#et({conversationId:e,messageIds:t.map(e=>e.id)}),this.#ct(e,t))}#ct(e,t){let r=(this.#U??Promise.resolve()).catch(()=>{}).then(()=>this.#pt(e,t,!1)).finally(()=>{this.#U===r&&(this.#U=null)});this.#U=r}async#pt(e,t,r){if(this.#R!==e)return;let n=t.filter(e=>this.#D.get(e.id)!==e.displayContent);if(0===n.length)this.#ut(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,n);for(let e of n)this.#D.set(e.id,e.displayContent);this.#R===e&&r&&(this.#B=r),this.#ut(e,t)}catch(a){if(!r&&this.#ht(a))return void await this.#pt(e,n,!0);if(a instanceof o&&("not_found"===a.code||"conversation_deleted"===a.code))return void this.#ut(e,t);this.#De("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ht(e){return e instanceof o?"request_failed"===e.code:e instanceof Error}#ut(e,t){let r=this.#lt();if(!r||r.conversationId!==e)return;let o=new Set(t.map(e=>e.id)),n=r.messageIds.filter(e=>!o.has(e));this.#et(n.length?{conversationId:e,messageIds:n}:null)}async replayPendingProjections(){if(!this.#it())return;let e=this.#lt();if(!e)return;if(this.#R&&e.conversationId!==this.#R)return void this.#et(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.#et(null):(this.#ct(e.conversationId,t),await(this.#U?.catch(()=>{})))}#fe(){this.#R&&(this.#B=null,this.historyInternals.setStoredConversationRevision?.(null))}async#mt(){await this.awaitHistorySettled(),await this.#nt(),"new_conversation_required"===this.#q&&await this.#Xe()}static#gt(e){return e instanceof o&&"conversation_deleted"===e.code}async#ft(t,r,o,n,a){let s=this.#e,i=e=>{this.#e===s&&this.handleEvent(e)};this.#dt(t);try{return void await this.client.dispatch({messages:t,signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},i)}catch(t){if(r.signal.aborted||this.#e!==s||!e.#gt(t))throw t;let l=await this.#bt(n);if(!l)throw t;this.#dt([l]),await this.client.dispatch({messages:[l],signal:r.signal,assistantMessageId:o,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},i)}}async#bt(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let r={...t};this.#N+=1,this.#$+=1,this.#U=null,this.#Qe(!0),this.#R=null,this.#B=null,this.#P=null,this.#O=!0;try{let e=this.#Ne;if(e){let t=await e.prepareStartNew({context:this.#We()});await this.#Je(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#j=!0,this.#q="new_conversation_required",this.#He(),this.#De("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#O=!1}return this.#Be(r),this.#me(!0),this.#De("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},o=function(e,t){let r=e.voiceRecognition,o=t.voiceRecognition;return!0===r?.enabled!=(!0===o?.enabled)||r?.provider?.type!==o?.provider?.type||r?.provider?.custom!==o?.provider?.custom||Ut(e)!==Ut(t)||r?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),a=function(e,t){return Kn.some(r=>e[r]!==t[r])}(this.config,r);a&&(this.cancel(),this.#Re()),this.config=r,o&&(this.cleanupVoice(),!0===r.voiceRecognition?.enabled&&Ut(r)&&this.setupVoice());let s=JSON.stringify(t)!==JSON.stringify(r.features?.artifacts?.display);if(!a)return this.client.updateConfig(r),void(s&&this.#yt());this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let i=this.client.getSSEEventCallback();this.#N+=1,this.#$+=1,this.client=new n(this.config,this.historyInternals),s&&this.#yt(),this.#ke(),i&&this.client.setSSEEventCallback(i)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#vt(e);return this.upsertMessage(t),t}#vt(e){let{role:t,content:r,llmContent:o,contentParts:n,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e;return{id:a??("user"===t?so():"assistant"===t?io():`${"operator"===t?"operator":"system"}-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:r,createdAt:s??(new Date).toISOString(),sequence:i??this.#xe(),streaming:l,...void 0!==o&&{llmContent:o},...void 0!==n&&{contentParts:n},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p},...void 0!==e.dispatchError&&{dispatchError:e.dispatchError},...void 0!==e.author&&{author:{...e.author}}}}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=e.map(e=>this.#vt(e));return this.messages=this.#Ce([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:n,id:a,createdAt:s,sequence:i}=e,l={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...void 0!==n&&{llmContent:n},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}updateComponentProps(e,t){let r=this.messages.find(t=>t.id===e),o=r&&Wn(r);return!(!r||"assistant"!==r.role||r.variant||!o||(this.upsertMessage({...r,rawContent:JSON.stringify({text:r.content,component:o.component,props:t})}),0))}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!(!t||"assistant"!==t.role||t.variant||!Wn(t)||(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),0))}async#wt(e,t,r){let o;try{o=await r()}catch{return}let n=o.blocks.join("\n\n"),a=[n,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=o.contentParts.length>0;if(s){let t=[];n&&t.push(fn(n)),t.push(...o.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(fn(a)),t.push(...o.contentParts),e.contentParts=t}else n&&(e.llmContent=a);Object.keys(o.context).length>0&&(e.mentionContext=o.context)}async sendMessage(e,t){let r=e.trim(),o=!!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||o))return;this.#ne&&!t?.voiceTurn&&(this.#ne.failed=!0,this.#ne=null),(this.#_||this.#U||this.#j||this.#Y)&&await this.#mt(),this.stopSpeaking(),this.client.cancelStreams(),this.abortController?.abort(),this.#n(),this.#rt(),this.#ie++,this.#tt();let n=t?.voiceTurn?.userMessageId,a=n?this.messages.find(e=>e.id===n&&"user"===e.role):void 0,s=a?.id??so(),i=io();this.#p=null;let l=t?.contentParts&&gn(t.contentParts)?"[Image]":"",d={id:s,role:"user",content:r||l,createdAt:(new Date).toISOString(),sequence:this.#xe(),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.#Be(d),this.#me(!0);let c=new AbortController;this.abortController=c;let p=this.#e;if(t?.mentions){let e=this.messages.find(e=>e.id===s)??d;if(await this.#wt(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:[fn(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 u=(new Date).toISOString(),h=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:u}]:[...this.messages],m=(a??this.messages.find(e=>e.id===s))?.createdAt??u,g=((e,t)=>{let r=new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!Cn(e))return[];let{toolCallId:o,name:n}=e;if("string"!=typeof o||!o||"string"!=typeof n||!n||r.has(o))return[];r.add(o);let a=Cn(e.arguments)?e.arguments:{},s=e.result??null;return[{id:`voice-tool-${o}`,role:"assistant",variant:"tool",content:"",createdAt:t,streaming:!1,toolCall:{id:o,name:n,status:"complete",args:a,result:s},agentMetadata:{clientToolAnswer:{toolCallId:o,toolName:n,args:a,result:s}}}]})})(t?.voiceTurn?.priorToolResults,m);for(let e of g)this.messages.some(t=>t.id===e.id)||(this.#Be(e),h.push({...e,createdAt:u}));let f=g.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:r,args:o,result:n}=e.clientToolAnswer;return{toolCallId:t,name:r,arguments:o,result:n}});try{await this.#ft(h,c,i,s,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...f.length>0&&{voicePriorToolResults:f}})}catch(e){if(this.#e!==p||"resuming"===this.status||this.#u)return;this.#ne&&(this.#ne.failed=!0);let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));t||this.#xt(e),this.#he("idle"),this.#me(!1),this.abortController=null,this.#a(t?"cancel":"error",p),t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(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 o=r+1;for(;o<e.length&&"user"!==e[o].role;)o+=1;return{start:r,end:o}}(this.messages,e);if(!r||!En(this.messages,e))return!1;let o=this.messages[r.start],n=t.replacement,a=n?n.text:o.content,s=n?n.contentParts:o.contentParts;if(!(a?.trim()||(s?.length??0)>0||!n&&(o.llmContent?.trim()?.length??0)>0))return!1;let i=n?void 0:{...void 0!==o.llmContent&&{llmContent:o.llmContent},...void 0!==o.rawContent&&{rawContent:o.rawContent},...o.mentionContext&&{mentionContext:o.mentionContext},...o.contextMentions&&{contextMentions:o.contextMentions},...o.quote&&{quote:o.quote}},l=n?this.#Ct(n.options):o.composerOptions,d=n?n.contentSegments:o.contentSegments,c=n?n.options?.quote:void 0,p=n?n.viaVoice:o.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}#Ct(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.#_||this.#U||this.#j||this.#Y)&&await this.#mt(),this.abortController?.abort(),this.#tt(),this.#n();let e=io();this.#p=null,this.#me(!0);let t=new AbortController;this.abortController=t;let r=this.#e,o=[...this.messages];try{await this.client.dispatch({messages:o,signal:t.signal,assistantMessageId:e},e=>{this.#e===r&&this.handleEvent(e)})}catch(e){if(this.#e!==r||"resuming"===this.status||this.#u)return;let t=e instanceof Error&&("AbortError"===e.name||e.message.includes("aborted")||e.message.includes("abort"));t||this.#xt(e),this.#a(t?"cancel":"error",r),this.#he("idle"),this.#me(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;this.#e||this.#n(),t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#p=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.#me(!0);let n=this.#e,a={};try{await this.client.processStream(e,e=>{if(this.#e!==n)return;let r=this.#l;this.#l=a;try{this.handleEvent(e,t?.readOnlyReplay)}finally{this.#l=r}},t?.assistantMessageId,t?.seedContent,this.abortController?.signal,t?.readOnlyReplay?this.messages:void 0,t?.readOnlyReplay?this.#h:void 0),this.#St(a)}catch(e){if(this.#e!==n)return;if("resuming"===this.status||this.#u)return void this.#kt(a);this.#St(a),this.#he("error"),0===this.webMcpResolveControllers.size&&(this.#me(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#ke(){let e=this.config.webmcp;!0===e?.enabled&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(!0!==e.confirmRequired&&!0===this.config.webmcp?.autoApprove?.(e))return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do{t="webmcp-"+ ++this.#C}while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let r={id:t,status:"pending",agentId:"",executionId:"",toolName:e.toolName,...e.toolCallId?{toolCallId:e.toolCallId}:{},toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(t=>{this.webMcpApprovalResolvers.set(o,t),e.signal?.addEventListener("abort",()=>this.resolveWebMcpApproval(o,"timeout"),{once:!0})})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(t=>t.id===e);o?.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#se;#ie;#At(e){let t=this.#se??={s:this,setStreaming:e=>this.#me(e),appendMessage:e=>this.#Be(e),nextSequence:()=>this.#xe(),settleApprovalPausedToolCall:e=>this.#Mt(e),resumeAfter:e=>this.#c?.executionId===e?this.#c.lastEventId:void 0},r=mn();if(r)return e(r,t);let o=this.#ie;return hn().then(r=>o===this.#ie?e(r,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,r){return this.#At((o,n)=>o.resolveApproval(n,e,t,r))}resolveAskUserQuestion(e,t){return this.#At((r,o)=>r.resolveAskUserQuestion(o,e,t))}resolveWebMcpToolCall(e){return this.#At((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}:{}}})}#de(e){let t=e.agentMetadata?.executionId,r=e.toolCall?.id;if(!t||!r){let t=this.#x;return void queueMicrotask(()=>{t===this.#x&&this.resolveWebMcpToolCall(e)})}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}#ye(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#x;queueMicrotask(()=>{if(e===this.#x)for(let e of[...this.webMcpAwaitBatches.keys()])this.#It(e)})}#It(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.#At((t,o)=>t.resolveWebMcpToolCallBatch(o,e,r))}#rt(){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.#x++}cancel(){this.client.cancelStreams(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ie++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#me(!1),this.#he("idle"),this.#a("cancel")}clearMessages(){this.client.cancelStreams(),this.#Re(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ie++,this.#t=void 0,this.messages=[],this.agentExecution=null,this.#Ze(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#me(!1),this.#he("idle"),this.callbacks.onMessagesChanged([...this.messages]),this.#a("cancel")}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#w}selectArtifact(e){this.#w=e,this.#Ae()}clearArtifacts(){this.#Ze()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,r="markdown"===e.artifactType?{id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,r),this.#w=t,this.#Ae(),!1!==e.transcript&&this.#Tt(r),r}#Tt(e){let t=`artifact-ref-${e.id}`,r=In(Mn(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}}),o=this.messages.find(e=>e.id===t);o?(o.rawContent=r,o.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:"",rawContent:r})}#yt(){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 o=In(Mn(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!==o&&(r.rawContent=o,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ze(){(0!==this.artifacts.size||null!==this.#w)&&(this.artifacts.clear(),this.#w=null,this.#Ae())}#Ae(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#w})}#ve(e){switch(e.type){case"artifact_start":"markdown"===e.artifactType?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.#w=e.id;break;case"artifact_delta":{let t=this.artifacts.get(e.id);"markdown"===t?.artifactType&&(t.markdown=(t.markdown??"")+e.artDelta);break}case"artifact_update":{let t=this.artifacts.get(e.id);"component"===t?.artifactType&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case"artifact_complete":{let t=this.artifacts.get(e.id);t&&(t.status="complete");break}default:return}this.#Ae()}hydrateMessages(e){this.client.cancelStreams(),this.abortController?.abort(),this.abortController=null,this.#tt(),this.#rt(),this.#ie++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.#t=void 0,this.messages=this.#Ce(e.map(e=>({...cr(e),streaming:!1,sequence:e.sequence??this.#xe()}))),this.#me(!1),this.#he("idle"),this.callbacks.onMessagesChanged([...this.messages]),this.#a("cancel")}hydrateArtifacts(e,t=null,r=!1){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:r?t.status:"complete"});this.#w=t,this.#Ae()}assertBackgroundSwitchable(){let e=this.config.backgroundConversations;if(!0!==e?.capabilities?.durableExecution||!0!==e.capabilities?.readOnlyReplay||"function"!=typeof e.reconnectStream)throw new d("background_unavailable","This backend does not support background conversations");if(this.config.parseSSEEvent)throw new d("background_unavailable","Background replay requires the native event parser");if(this.#ee()||this.webMcpResolveControllers.size||this.webMcpAwaitBatches.size||(this.streaming||this.#u)&&(!this.#c||!this.#R))throw new d("conversation_busy","This turn cannot safely continue in the background")}async#Oe(){if(this.#g)return;let e=this.config.backgroundConversations,t=this.#$,{BackgroundConversationController:r}=await sn();if(t!==this.#$||e!==this.config.backgroundConversations)throw new d("superseded","The history identity changed");if(this.#g)return;this.#g=new r(e,e=>{this.#Et(e)});let o=!0;this.#f=this.#Ne?.subscribeIdentityStatus(()=>{o||(this.#g?.clear(),this.cancel())})??null,o=!1}#Re(){this.#g?.clear(),this.#g=null,this.#f?.(),this.#f=null}#le(e){let t=this.#c?.executionId??this.agentExecution?.executionId,r=this.#R;if(!this.config.backgroundConversations||!t||!r)return;let o={conversationId:r,executionId:t,status:e,detached:!1};this.#Et(o)}#Et(e){try{this.config.onConversationExecutionState?.(e)}catch{}try{this.callbacks.onConversationExecutionState?.(e)}catch{}}#Lt(){let e=this.config.backgroundConversations,t=this.#R;return e&&t?r=>e.reconnectStream({...r,conversationId:t}):this.config.reconnectStream}#_e(e){this.#n(e.handle.executionId),this.#p=e.handle.assistantMessageId;let t=this.messages.find(e=>e.id===this.#p);t&&(t.streaming=e.streamCheckpoint?.openAssistant??!0),this.#h=e.streamCheckpoint,this.agentExecution={executionId:e.handle.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0},this.#c=e.handle,this.#Bt(!0),this.#le(e.observedStatus??"running"),this.#ue()}#ce(e){let t=this.agentExecution?.executionId;if(!t||!this.#p||"running"!==this.agentExecution?.status)return;let r=null===this.#c;this.#c={executionId:t,lastEventId:e,assistantMessageId:this.#p,status:"running"},this.#Bt(r),r&&this.#le("running")}#pe(){return null!==this.#c&&"function"==typeof this.#Lt()&&!0!==this.abortController?.signal.aborted&&0===this.webMcpResolveControllers.size&&0===this.webMcpAwaitBatches.size&&!this.#ee()}#ee(){return this.messages.some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata?.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)}#ue(){this.#u||this.#c&&"function"==typeof this.#Lt()&&(this.#u=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#c}),this.#me(!0),this.#he("resuming"),this.#Rt().then(e=>{this.#u&&this.#c&&e.begin()}))}#Rt(){return this.#b?Promise.resolve(this.#b):(this.#y||(this.#y=Vn().then(({createReconnectController:e})=>{let t=e(this.#Pt());return this.#b=t,t}),this.#y.catch(()=>{this.#y=null})),this.#y)}#Pt(){let e=this;return{get config(){return{...e.config,reconnectStream:e.#Lt()}},getResumable:()=>e.#c,clearResumable:()=>e.#ge(),getStatus:()=>e.status,setStatus:t=>e.#he(t),setStreaming:t=>e.#me(t),setReconnecting:t=>{e.#u=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,isAwaitPending:()=>e.#ee(),notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o,readOnlyReplay:!!e.config.backgroundConversations}),appendMessage:t=>e.#Be(t),settleParked:t=>e.#Nt(t),nextSequence:()=>e.#xe(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Qn(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#u?this.#b?.wake():this.#ue()}resumeFromHandle(e){if("function"!=typeof this.config.reconnectStream||this.#u)return;if(this.#n(e.executionId),this.#ee())return this.#$t(e.executionId),void(this.#c={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#p??"",status:"running"});let t=this.#Wt(e.executionId)?io():this.#Ht();t||(t=io(),this.#Be({id:t,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:this.#xe()})),this.#p=t,this.#$t(e.executionId),this.#c={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.#ue()}#Nt(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#ee()){if(!this.#Wt(e))return!1;this.#ge()}if(this.#u=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#me(!1),this.abortController=null}return this.#he("idle"),!0}#$t(e){this.agentExecution||={executionId:e,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}}#Wt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>!0===e?.interrupted))}#Ht(){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}#tt(){this.#u=!1,this.#b?.teardown(),this.#ge()}#ge(){this.#v&&=(clearTimeout(this.#v),null);let e=null!==this.#c;this.#c=null,this.#h=void 0,e&&this.config.onExecutionState?.(null)}#Bt(e){let t=this.config.onExecutionState;t&&(e?(this.#v&&=(clearTimeout(this.#v),null),t(this.#c)):this.#v||=setTimeout(()=>{this.#v=null,this.config.onExecutionState?.(this.#c)},500))}getResumableHandle(){return this.#c}#he(e){"error"===e&&(this.#r=!0,this.#s()),this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#me(e){if(e||this.#s(),this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#St(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 o=On(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Fn(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=On(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o?.voice,rate:o?.rate,pitch:o?.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()}#xt(e){for(let e of this.messages)e.streaming=!1;let t=Qn(e,this.config.errorMessage);t?this.#Be({id:io(),role:"assistant",content:t,dispatchError:!0,localOnly:!0,createdAt:(new Date).toISOString(),sequence:this.#xe()}):this.callbacks.onMessagesChanged([...this.messages])}#St(e){for(let[t,r]of[...this.#i])r===e&&(this.#i.delete(t),this.#Mt(t))}#kt(e){for(let[t,r]of this.#i)r===e&&this.#i.set(t,void 0)}#Mt(e){let t=this.messages.find(t=>t.id===e)?.approval,r=t?.toolCallId,o=r&&this.messages.find(e=>e.toolCall?.id===r),n=o&&o.toolCall;if(!n||"complete"===n.status||"pending"===t.status)return;let a={...n,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({...o,streaming:!1,toolCall:a})}#Be(e){let t=this.#Ke(e),r=this.messages[this.messages.length-1];this.messages=!r||this.#Dt(r,t)<=0?[...this.messages,t]:this.#Ce([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Ke(e),r=this.messages.findIndex(e=>e.id===t.id);if(-1===r)return void this.#Be(t);this.messages=this.messages.map((e,o)=>{if(o!==r||e.toolCall?.name&&ir(e.toolCall.name)&&"complete"===e.toolCall.status&&t.toolCall?.id===e.toolCall.id&&"complete"!==t.toolCall.status&&("pending"===t.toolCall.status&&!t.toolCall.name||!e.toolCall.interrupted&&(void 0!==e.toolCall.result||void 0!==e.toolCall.success)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let n={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(n.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(n.agentMetadata={...n.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&n.agentMetadata&&!n.agentMetadata.clientToolAnswer&&(n.agentMetadata={...n.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,o=t.approval;n.approval={...r,...o,executionId:o.executionId||r.executionId,toolCallId:o.toolCallId||r.toolCallId,toolName:o.toolName||r.toolName,description:o.description||r.description,toolType:o.toolType??r.toolType,reason:o.reason??r.reason,parameters:o.parameters??r.parameters}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&Jn(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),o=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&Jn(a)&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;(r||o||s)&&(n.agentMetadata={...n.agentMetadata??{},awaitingLocalTool:!1},n.toolCall=e.toolCall,n.streaming=e.streaming)}return n});let o=this.messages[r],n=this.messages[r-1],a=this.messages[r+1];(n&&this.#Dt(n,o)>0||a&&this.#Dt(o,a)>0)&&(this.messages=this.#Ce(this.messages)),this.callbacks.onMessagesChanged([...this.messages])}#Ke(e){return void 0===e.sequence?{...e,sequence:this.#xe()}:{...e}}#xe(){return this.#d++}#Dt(e,t){let r=new Date(e.createdAt).getTime(),o=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(o)&&r!==o)return r-o;let n=e.sequence??0,a=t.sequence??0;return n===a?e.id.localeCompare(t.id):n-a}#Ce(e){return[...e].sort((e,t)=>this.#Dt(e,t))}};let Gn={add:e=>async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;vn(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})}(e)},Yn={allowedTypes:yn,maxFileSize:10485760,maxFiles:4};function Xn(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}p=class e{#e=[];#t;#r=new Set;#o=new Map;#n=null;#a=new Map;#s=new WeakMap;#i=!1;#l=!1;constructor(e={}){this.#t={allowedTypes:e.allowedTypes??Yn.allowedTypes,maxFileSize:e.maxFileSize??Yn.maxFileSize,maxFiles:e.maxFiles??Yn.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,preview:e.preview,widgetConfig:e.widgetConfig,instanceId:e.instanceId,renderAttachmentPreview:e.renderAttachmentPreview,adapter:e.adapter}}#d(){return"function"==typeof this.#t.adapter?.add}#c(){return this.#d()?this.#t.adapter:Gn}setPreviewsContainer(e){this.#n!==e&&this.#v(),this.#n=e}remountPreviews(e){if(this.#v(),this.#n=e,e){e.innerHTML="";for(let e of this.#e)this.#f(e)}this.#x()}updateConfig(e){if("allowedTypes"in e&&(this.#t.allowedTypes=e.allowedTypes?.length?e.allowedTypes:Yn.allowedTypes),"maxFileSize"in e&&(this.#t.maxFileSize=e.maxFileSize??Yn.maxFileSize),"maxFiles"in e&&(this.#t.maxFiles=e.maxFiles??Yn.maxFiles),"onFileRejected"in e&&(this.#t.onFileRejected=e.onFileRejected),void 0!==e.onAttachmentsChange&&(this.#t.onAttachmentsChange=e.onAttachmentsChange),"adapter"in e&&(this.#t.adapter=e.adapter),"preview"in e&&(this.#t.preview=e.preview),"widgetConfig"in e&&(this.#t.widgetConfig=e.widgetConfig),"instanceId"in e&&(this.#t.instanceId=e.instanceId),"renderAttachmentPreview"in e&&e.renderAttachmentPreview!==this.#t.renderAttachmentPreview)this.#t.renderAttachmentPreview=e.renderAttachmentPreview,this.remountPreviews(this.#n);else for(let e of this.#e)this.#b(e),this.#w(e)}isReady(){return this.#e.every(e=>"ready"===e.status)}getAttachments(){return[...this.#e]}getContentParts(){return this.#e.map(e=>e.contentPart).filter(e=>null!==e)}hasAttachments(){return this.#e.length>0}count(){return this.#e.length}async handleFileSelect(e){e&&0!==e.length&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#i)return;let t=[];for(let r of e){if(this.#e.length>=this.#t.maxFiles){this.#t.onFileRejected?.(r,"count");continue}let e=wn(r,this.#t.allowedTypes,this.#t.maxFileSize);if(!e.valid){let t=e.error?.includes("type")?"type":"size";this.#t.onFileRejected?.(r,t);continue}let o={id:Xn(),file:r,previewUrl:vn(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#d()?"uploading":"processing",progress:this.#d()?0:void 0};this.#e.push(o),this.#f(o),t.push(o),this.#w(o)}this.#x(),this.#m(),await Promise.all(t.map(e=>this.#p(e)))}async#p(e){let t=new AbortController;this.#a.set(e.id,t);let r=this.#c(),o=()=>this.#i||t.signal.aborted||this.#a.get(e.id)!==t||!this.#e.includes(e);try{let n=await r.add(e.file,{signal:t.signal,onProgress:t=>{o()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#b(e),this.#m())}});if(o())return void(this.#i&&this.#l&&this.#h(n,r));this.#s.set(e,r),e.contentPart=n,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(o())return;e.status="error",e.progress=void 0,e.error=t instanceof Error?t.message:String(t??"Upload failed")}finally{this.#a.get(e.id)===t&&this.#a.delete(e.id)}this.#b(e),this.#m()}retryAttachment(e){let t=this.#e.find(t=>t.id===e);!t||"error"!==t.status||this.#i||(t.status=this.#d()?"uploading":"processing",t.progress=this.#d()?0:void 0,t.error=void 0,this.#b(t),this.#m(),this.#p(t))}#u(e){let t=this.#a.get(e);t&&(this.#a.delete(e),t.abort())}removeAttachment(e){let t=this.#e.findIndex(t=>t.id===e);if(-1===t)return;let r=this.#e[t];this.#u(e),r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.#e.splice(t,1),this.#y(e),this.#r.delete(e);let o=this.#n?.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),"ready"===r.status&&r.contentPart&&this.#h(r.contentPart,this.#s.get(r)),this.#x(),this.#m()}async#h(e,t){try{await(t?.remove?.(e,{signal:(new AbortController).signal}))}catch(e){console.error("[AttachmentManager] adapter.remove failed:",e)}}clearAttachments(){this.#v(),this.#r.clear();for(let e of this.#e)this.#u(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.#e=[],this.#a.clear(),this.#n&&(this.#n.innerHTML=""),this.#x(),this.#m()}destroy(e){if(!this.#i){this.#i=!0,this.#v(),this.#l=!0===e?.release;for(let e of this.#a.values())e.abort();this.#a.clear();for(let e of this.#e)e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.#l&&"ready"===e.status&&e.contentPart&&this.#h(e.contentPart,this.#s.get(e));this.#e=[],this.#n=null}}#m(){this.#i||this.#t.onAttachmentsChange?.(this.getAttachments())}#g(e){let t={instanceId:this.#t.instanceId??"",state:Object.freeze({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error,lineCount:e.lineCount,kind:vn(e.file)?"image":"file",previewUrl:e.previewUrl}),config:{...this.#t.widgetConfig,attachments:{...this.#t.widgetConfig?.attachments,preview:this.#t.preview}},actions:{remove:()=>this.removeAttachment(e.id),retry:()=>this.retryAttachment(e.id)},defaultRenderer:()=>function(e){let t=st("div","persona-attachment-preview persona-relative persona-inline-block"),r=e,o="",n=e=>{r=e;let{state:n}=r,a=JSON.stringify([r.config.attachments?.preview,n.lineCount,n.previewUrl]);o!==a&&(o=a,(()=>{let{state:e}=r,o=r.config.attachments?.preview,n="image"===e.kind,a=n?o?.image:o?.file,s=n?o?.image?.layout??"thumbnail":o?.file?.layout??"tile";if(t.dataset.kind=e.kind,t.dataset.layout=s,t.dataset.fileIcon=String(!1!==o?.file?.icon),t.dataset.iconPlacement=o?.file?.iconPlacement??"start",t.dataset.removeVisibility=a?.remove?.visibility??"always",t.dataset.removePlacement=a?.remove?.placement??"overlap",t.replaceChildren(),n&&e.previewUrl){let r=it("img",{className:"persona-attachment-image",attrs:{src:e.previewUrl,alt:e.name},style:{objectFit:o?.image?.fit??"cover"}}),n=o?.image?.name??"hidden";if("chip"===s||"hidden"!==n){let o=st("div","persona-attachment-image-card");o.append(r),"hidden"!==n&&o.append(it("span",{className:"persona-attachment-file-name",text:"basename"===n?e.name.replace(/\.[^.]+$/,""):e.name})),t.append(o)}else t.append(r)}else{let r=st("div","persona-attachment-file"),n=e.mimeType,a=n.includes("spreadsheet")||n.includes("excel")?ge:"application/json"===n?me:"application/pdf"===n||n.startsWith("text/")||n.includes("word")?fe:be,s=(o?.file?.iconName?Ee(o.file.iconName,20,"currentColor",1.5):null)??ne(a,20,"currentColor",1.5);s&&!1!==o?.file?.icon&&(s.classList.add("persona-attachment-file-icon"),r.append(s));let i=st("div","persona-attachment-file-copy"),l=o?.file?.name??"hidden";"hidden"!==l&&i.append(it("span",{className:"persona-attachment-file-name",text:"basename"===l?e.name.replace(/\.[^.]+$/,""):e.name}));let d=o?.file?.metadata,c="size"===d?e.size<1024?`${e.size} B`:e.size<1048576?`${Math.round(e.size/1024)} KB`:`${(e.size/1048576).toFixed(1)} MB`:"line-count"===d&&void 0!==e.lineCount?`${e.lineCount} ${1===e.lineCount?"line":"lines"}`:"";c&&i.append(it("span",{className:"persona-attachment-file-metadata",text:c})),i.childNodes.length&&r.append(i);let p=o?.file?.badge??"type";"none"!==p&&r.append(it("span",{className:"persona-attachment-file-badge",text:"extension"===p?e.name.match(/\.([^.]+)$/)?.[1].toUpperCase()??xn(n,e.name):xn(n,e.name)})),t.append(r)}let i=it("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),l=st("div","persona-attachment-progress");l.append(st("div","persona-attachment-progress__bar"));let d=it("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=Ee("rotate-cw",12,"#ffffff",2);c?d.append(c):d.textContent="↻",d.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r.actions.retry()}),i.append(l,d);let p=it("button",{className:"persona-attachment-remove",attrs:{type:"button","aria-label":"Remove attachment"}}),u=ne(ve,10,"currentColor",2);u?p.append(u):p.textContent="×",p.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r.actions.remove()}),t.append(i),(("inline"===a?.remove?.placement?t.querySelector(".persona-attachment-file, .persona-attachment-image-card"):null)??t).append(p)})()),t.dataset.status=n.status,t.setAttribute("aria-busy",String("uploading"===n.status||"processing"===n.status)),t.title="error"===n.status?`${n.name}: ${n.error??"Upload failed"}`:n.name;let s=t.querySelector(".persona-attachment-progress__bar");s&&(s.style.width="number"==typeof n.progress?`${Math.round(100*n.progress)}%`:"")};return n(e),{element:t,update:n}}(t)};return t}#f(e){if(!this.#n)return;let t=this.#g(e),r=null;try{r=this.#t.renderAttachmentPreview?.(t)??null}catch(e){console.error("[AttachmentManager] preview renderer failed:",e)}r??=t.defaultRenderer();let o=r instanceof HTMLElement?{element:r}:r;o.element.dataset.attachmentId=e.id,this.#o.set(e.id,o),this.#n.appendChild(o.element)}#b(e){try{this.#o.get(e.id)?.update?.(this.#g(e))}catch(e){console.error("[AttachmentManager] preview update failed:",e)}}#y(e){let t=this.#o.get(e);if(t){this.#o.delete(e);try{t.destroy?.()}catch(e){console.error("[AttachmentManager] preview cleanup failed:",e)}finally{t.element.remove()}}}#v(){for(let e of this.#o.keys())this.#y(e)}async#w(e){let t=e.file;if(!this.#r.has(e.id)&&!("line-count"!==this.#t.preview?.file?.metadata||t.size>1048576)&&["text/plain","text/markdown","text/csv","application/json"].includes(t.type)){this.#r.add(e.id);try{let r=await new Promise((e,r)=>{let o=new FileReader;o.onload=()=>e(String(o.result??"")),o.onerror=()=>r(o.error),o.readAsText(t)});if(this.#i||!this.#e.includes(e)||r.includes("\0"))return;e.lineCount=""===r?0:r.split(/\r\n|\r|\n/).length-+!!/\r?\n$|\r$/.test(r),this.#b(e)}catch{}}}#x(){this.#n&&(this.#n.style.display=this.#e.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,preview:t?.preview,adapter:t?.adapter})}};let Zn=(e,t)=>e.length===t.length&&e.every((e,r)=>e===t[r]);function ea(){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,o=!1,n=!1,a=()=>(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(o=!1,n||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,!n&&!o&&(o=!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 o=t[r];return e.id===o.id&&e.name===o.name&&e.mimeType===o.mimeType&&e.size===o.size&&e.status===o.status&&e.progress===o.progress&&e.error===o.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Zn(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Zn(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:()=>{o&&s()},destroy:()=>{n=!0,o=!1,t.clear()}}}let ta=(e,...t)=>{for(let r of t){let t=e.querySelector(r);if(t)return t}return null},ra=(e,t)=>{let r=st("div",e);return r.setAttribute(t,""),r.setAttribute("data-persona-composer-synthesized",""),r.style.display="contents",r};function oa(e,t={}){let r=ta(e,"[data-persona-composer-form]"),o=ta(e,"[data-persona-composer-input]");if(!r||!o){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||o))throw Error(e);return typeof console<"u"&&console.warn(e),null}let n={header:ta(e,"[data-persona-composer-header]"),body:ta(e,"[data-persona-composer-body]"),actionsStart:ta(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:ta(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:ta(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:ta(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:ta(e,"[data-persona-composer-status]")},a=new Set,s=n.header;s||(a.add("header"),s=ra("persona-widget-composer__header","data-persona-composer-header"),r.parentNode?r.parentNode.insertBefore(s,r):e.appendChild(s));let i=n.body??o.parentElement??r,l=(e,t,r,o,n)=>{if(t)return t;a.add(e);let s=ra(r,o);return n.appendChild(s),s},d=l("actionsStart",n.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",n.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",n.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",n.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:o,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput:ta(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0,attachmentPreviews:ta(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:ta(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:ta(e,"[data-persona-composer-submit]")??void 0,micButton:ta(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:n,addListener:(e,t,r,o)=>{e.addEventListener(t,r,o),h.push({target:e,type:t,handler:r,options:o})},removeListener:(e,t,r,o)=>{e.removeEventListener(t,r,o),h=h.filter(o=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(o,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let na="persona-composer-control",aa="persona-composer-control--glyph",sa=e=>Number.parseFloat(e)||0;function ia(e,t){let r=t.getComputedStyle(e);if("none"===r.display)return 0;let o=Array.from(e.children).filter(e=>{if(!(e instanceof t.HTMLElement))return!1;let r=t.getComputedStyle(e);return"none"!==r.display&&!["absolute","fixed"].includes(r.position)});return o.reduce((e,r)=>{let o=t.getComputedStyle(r);return e+("contents"===o.display?ia(r,t):Math.max(r.getBoundingClientRect().width,r.scrollWidth))+sa(o.marginLeft)+sa(o.marginRight)},0)+Math.max(0,o.length-1)*sa(r.columnGap)+sa(r.paddingLeft)+sa(r.paddingRight)}function la(e){let t=null,r=null,o=null,n=null,a=0,s=!0,i=!1,l=!1,d=()=>{null!==n&&t?.form.ownerDocument.defaultView?.cancelAnimationFrame(n),n=null,r?.disconnect(),o?.disconnect(),r=null,o=null,t?.form.ownerDocument.defaultView?.removeEventListener("resize",c)},c=()=>{if(l||null!==n)return;let r=t?.form.ownerDocument.defaultView;r&&(n=r.requestAnimationFrame(()=>{n=null,l||e.onMeasure()}))};return{measure:()=>{if(l)return s;let n=e.getSurface();if(n?.form!==t?.form||n?.input!==t?.input||n?.start!==t?.start||n?.end!==t?.end){d(),t=n,s=!0,i=!1,a=0;let e=t?.form.ownerDocument.defaultView;if(t&&e){if(e.addEventListener("resize",c),void 0!==e.ResizeObserver){r=new e.ResizeObserver(c);let o=[t.form,t.start,t.end,t.input];for(let e of o)r.observe(e)}void 0!==e.MutationObserver&&(o=new e.MutationObserver(e=>{e.some(e=>e.target!==t?.input||"attributes"!==e.type)&&c()}),o.observe(t.form,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["class","style","hidden"]}))}}t&&n&&(t.resizeInput=n.resizeInput);let p=t?.form.ownerDocument.defaultView;if(!t||!p)return!0;if(!t.form.clientWidth)return s;let u=p.getComputedStyle(t.form),h=Math.max(1,t.form.clientWidth-sa(u.paddingLeft)-sa(u.paddingRight)),m=ia(t.start,p)+ia(t.end,p),g=sa(u.columnGap);i=m+g+(i?16:0)>h,s=function(e,t,r,o){return e<=0?o:e>=t+2*r+120+(o?0:16)}(h,m,g,s);let f=t.input.getBoundingClientRect().width;if(!1!==t.resizeInput&&f>0&&f!==a&&"TEXTAREA"===t.input.tagName){a=f,t.input.style.height="auto";let e=sa(p.getComputedStyle(t.input).maxHeight)||1/0,r=Math.min(t.input.scrollHeight,e);t.input.style.height=`${r}px`}return s},toolbarCrowded:()=>i,refresh:c,destroy:()=>{l=!0,d(),t=null}}}let da="[data-persona-composer-chip-row]";function ca(e){let t=e.querySelector(da);if(t)return t;let r=it("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(r,o):e.appendChild(r),r}function pa(e){let t=it("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",o=!1,n=r=>{let o=st("span","persona-composer-quote-bar"),n=st("div","persona-composer-quote-content");if(r.sourceLabel){let e=st("div","persona-composer-quote-source");e.textContent=r.sourceLabel,n.appendChild(e)}let a=it("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=Tn(r.text),n.appendChild(a);let s=it("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),i=Ee("x",12,"currentColor",2);i?s.appendChild(i):s.textContent="×",s.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(o,n,s)};return{element:t,render:e=>{if(o)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(n(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function ua(e){let t=it("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,o=!1,n=(e,t,r,o)=>{let n=it("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=Ee(e,12,"currentColor",2);return a?n.appendChild(a):n.textContent=t,n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n};return{element:t,render:a=>{if(o||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=st("span","persona-composer-pending-badge");s.textContent=e.label??"Sends next";let i=it("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});i.textContent=(e=>{let t=Tn(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,n("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),n("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function ha(e){let t=it("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),r=it("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 o=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",o);let n=st("div","persona-message-edit-actions"),a=(e,t,r,o)=>{let n=it("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return n.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),o()}),n},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return n.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=>{"Escape"===t.key?(t.preventDefault(),t.stopPropagation(),e.onCancel()):"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,n),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function ma(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 ga(e,t,r,o){let n=r.find(e=>e.id===t);if(!n)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)(n,o)){let e=r.filter(e=>e.groupId===n.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)}function fa(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function ba(e){return!e.wrapped&&!e.text.includes("\n")&&!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function ya(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 o=parseFloat(r);return Number.isFinite(o)&&o>0?o:20}function va(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function wa(e,t){e.style.maxHeight=t*ya(e)+"px",e.style.overflowY="auto"}function xa(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 Ca(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function Sa(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?Ca(e)?"enter":"send":"enter"}(t))}function ka(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let o=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};o("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),o("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),o("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),o("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function Aa(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}}function Ma(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 Ia(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"})}function Ta(e,t,r){let o;try{o=e(Ma(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(o)?Promise.resolve(o).then(e=>r.aborted?{status:"aborted"}:Ia(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Ia(t,o)}let{setLoader:Ea,load:La}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ba=Ea,Ra=La,{setLoader:Pa,load:Na}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),$a=Pa,Wa=Na,Ha=400,Da=300,Fa=0,Oa=e=>Math.max(0,e);function za(e){void 0!==e.delayMs&&(Ha=Oa(e.delayMs)),void 0!==e.skipDelayMs&&(Da=Oa(e.skipDelayMs))}let qa=new WeakMap;function ja(e){qa.get(e)?.hide()}let _a=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Ua=e=>{let t=e.getRootNode?.();return _a(t)?t:e.closest("dialog[open]")??e.ownerDocument.body},Va=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Ka=[...["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 Qa(e){qa.get(e.anchor)?.destroy();let t,{anchor:r,trigger:o=r,text:n,hint:a,enabled:s=!0,gap:i=8,viewportPadding:l=8}=e,d=()=>r.ownerDocument,c=()=>d().defaultView??window,p=null,u=null,h=null,m=null,g=!1,f=!1,b=!1,y=()=>("function"==typeof n?n():n).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>Oa(e.delayMs??Ha),x=()=>Oa(e.skipDelayMs??Da),C=()=>{void 0!==t&&(c().clearTimeout(t),t=void 0)},S=()=>{C();let e=null!==p;m?.(),m=null,p?.remove(),p=null,u=null,h=null,e&&(e=>{Fa=e>0?Date.now()+e:0})(x())},k=()=>{if(!p)return;let e=d(),t=c(),o=r.getBoundingClientRect(),n=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-n.width,h=o.left+o.width/2-n.width/2,m=Va(h,l,u),g=o.top-l,f=s-l-o.bottom,b=g>=n.height+i||g>=f?"top":"bottom",y="top"===b?o.top-i-n.height:o.bottom+i,v=s-l-n.height,w=Va(y,l,v),x=o.left+o.width/2,C=Math.max(10,n.width-10),S=Va(x-m,10,C);p.dataset.placement=b,p.style.left=`${m}px`,p.style.top=`${w}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${S}px`)},A=()=>{if(b||!s||p||!r.isConnected||(e=>"function"==typeof e.closest&&null!==e.closest("[data-persona-tooltip-suppressed]"))(r))return;let e=y(),t=Ua(r);if(!e||!t)return;let o=d(),n=c();p=o.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=n.getComputedStyle?.(r);if(a){for(let e of Ka){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=o.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=o.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=o.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),k(),p.dataset.state="open";let g=()=>{if(!r.isConnected)return void S();u&&(u.textContent=y()),h&&(h.textContent=v());let e=Ua(r);p&&e&&p.parentNode!==e&&e.appendChild(p),k()};n.addEventListener("scroll",g,!0),n.addEventListener("resize",g);let f=r.closest("[data-persona-root]");f?.addEventListener("persona:internal:host-moved",g);let w=r.getRootNode(),x=_a(w)?w:o.documentElement,C=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});C?.observe(x,{childList:!0,subtree:!0}),m=()=>{n.removeEventListener("scroll",g,!0),n.removeEventListener("resize",g),f?.removeEventListener("persona:internal:host-moved",g),C?.disconnect()}},M=()=>{g||f?(e=>{b||p||(C(),e||w()<=0||Date.now()<Fa?A():t=c().setTimeout(()=>{t=void 0,A()},w()))})(f):S()},I=()=>{let e=c();e.matchMedia&&e.matchMedia("(hover: none)").matches||(g=!0,M())},T=()=>{g=!1,M()},E=()=>{try{f=r.matches(":focus-visible")}catch{f=!0}M()},L=()=>{f=!1,M()},B=()=>{g=!1,f=!1,S()},R=e=>{"Escape"===e.key&&B()};o.addEventListener("mouseenter",I),o.addEventListener("mouseleave",T),r.addEventListener("focus",E),r.addEventListener("blur",L),r.addEventListener("keydown",R),r.addEventListener("click",B);let P={get isOpen(){return null!==p},show:A,hide:S,reposition:k,destroy:()=>{b||(b=!0,S(),o.removeEventListener("mouseenter",I),o.removeEventListener("mouseleave",T),r.removeEventListener("focus",E),r.removeEventListener("blur",L),r.removeEventListener("keydown",R),r.removeEventListener("click",B),qa.delete(r))}};return qa.set(r,P),P}let Ja=(e,t,r,o)=>{let[n,a]=t.split(".");return[e?.theme,e?.darkTheme].some(e=>void 0!==e?.components?.[n]?.[a]?.[r])?`var(--persona-components-${t.replace(".","-")}-${r}, ${o})`:o},Ga=(e,t)=>{let r=e&&z(e,t);return"string"==typeof r&&r?r:void 0},Ya=(e,t,r,o)=>{let n=t.startsWith("var(");e.classList.toggle("persona-theme-padding",n),e.style.padding=n?"":t,n?e.style.setProperty("--persona-theme-padding",t):e.style.removeProperty("--persona-theme-padding"),r&&(e.style.paddingLeft=e.style.paddingRight=r),o&&(e.style.paddingTop=e.style.paddingBottom=o)},Xa=(e,t,r)=>{let o=t.startsWith("var(")&&t.includes("--persona-components-");e.classList.toggle("persona-control-size",o),o?e.style.setProperty("--persona-control-size",t):e.style.removeProperty("--persona-control-size"),e.style.width=e.style.height=t,e.style.minWidth=e.style.minHeight=r??""},Za=Symbol("persona.panelAliasProvenance"),es=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),ts=(e,t)=>es(e,t)&&void 0!==e[t],rs=e=>{let t=e?.[Za];return t?{...t}:(e=>({launcherWidth:ts(e?.launcher,"width"),legacyLauncherWidth:ts(e,"launcherWidth"),sidebarWidth:ts(e?.launcher,"sidebarWidth"),dockWidth:ts(e?.launcher?.dock,"width")}))(e)},os=(e,t)=>(Object.defineProperty(e,Za,{value:t,enumerable:!0,configurable:!0}),e),ns=(e,t)=>os(e,rs(t)),as=e=>!0===e?.layout?.embedded&&!1===e.launcher?.enabled&&!e.launcher.sidebarMode&&"floating"===(e.launcher.mountMode??"floating"),ss=e=>e?.layout?.showHeader??!as(e),is="min(440px, calc(100vw - 24px))",ls={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:400,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:is,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{inputPlaceholder:"How can I help...",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:"",streamingIndicator:"arrow",scrollBehavior:"instant",scrollDurationMs:220,transition:"none"},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",groupBoundary:"adjacent",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other…",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},ds={},cs={colorScheme:"light",errorDisplay:"block",messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:{resolvedDisplay:"row",primaryAction:"allow-once",keyboardShortcuts:"focused"},loadingIndicator:{variant:"label"},launcher:{variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:"dots",transition:"fade",scrollBehavior:"smooth"},userMessageCollapse:{enabled:!0},toolCallDisplay:{layout:"row",variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",groupAppearance:"inset",loadingAnimation:"shimmer"},reasoningDisplay:{appearance:"inset",layout:"row",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 ps(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function us(e){let t="v5"===ps(e)?cs:ds;return k(ls,t)}let hs=us();function ms(e,t){if(e||t)return e?t?k(e,t):e:t}function gs(e){let t=us(e);return e?F(w(ns({...t,...e,colorScheme:y(e,["colorScheme"]).includes("colorScheme")?e.colorScheme:e.brand?void 0:t.colorScheme,...t.approval||void 0!==e.approval?{approval:!1!==e.approval&&{...t.approval||{},...e.approval}}:{},theme:ms(t.theme,e.theme),darkTheme:ms(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,o=e.features?.artifacts,n=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?.userMessageCollapse,h=e.features?.userMessageCollapse,m=t.features?.history,g=e.features?.history,f=void 0===r&&void 0===o?void 0:{...r,...o,layout:{...r?.layout,...o?.layout}},b=void 0===n&&void 0===a?void 0:{...n,...a},y=void 0===s&&void 0===i?void 0:{...s,...i},v=void 0===l&&void 0===d?void 0:{...l,...d},w=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},x=void 0===m&&void 0===g?void 0:{...m,...g,copy:{...m?.copy,...g?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay,...void 0===e.features?.toolCallDisplay?.layout&&void 0!==e.features?.toolCallDisplay?.variant?{layout:e.features.toolCallDisplay.variant}:{}},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay,...void 0===e.features?.reasoningDisplay?.layout&&void 0!==e.features?.reasoningDisplay?.variant?{layout:e.features.reasoningDisplay.variant}:{}},...void 0===b?{}:{scrollToBottom:b},...void 0===y?{}:{scrollBehavior:y},...void 0===f?{}:{artifacts:f},...void 0===v?{}:{streamAnimation:v},...void 0===w?{}:{askUserQuestion:w},...void 0===x?{}:{history:x},...void 0!==u||void 0!==h?{userMessageCollapse:{...u,...h}}:{}}})(),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,cs),e):F(w(ns(t),void 0,cs))}let fs=(e,t)=>{let r=st("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??"How can I help...",r.dir="auto",Sa(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(r)}),ka(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 o=va(e?.composer?.maxLines,t?.defaultMaxLines??3),n=20*o+"px";return r.style.maxHeight=n,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!==n){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=o*ya(r);return n=`${t}px`,r.style.maxHeight=n,t})());r.style.height=`${e}px`})}}},bs="[data-persona-glyph-stack]",ys=new WeakMap,vs=(e,t,r=!0)=>{ys.set(e,t);let o=t?.sendButton??{},n=o.useIcon??!1,a="stop"===e.getAttribute("data-persona-send-mode")?"stop":"send",s=e=>Ga(t,`sendButton.${e}`),i=(e,r)=>Ja(t,"composer.send",e,r),l=s("size")||o.size;e.style.fontSize=n?"18px":"",e.style.lineHeight=n?"1":"",e.className=lt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${na}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!s("backgroundColor")&&"persona-bg-persona-primary",!n&&!s("textColor")&&"persona-text-white"),Xa(e,n?l||(i("size","")?i("size","var(--persona-composer-control-size, 40px)"):""):"",n?l:void 0);let d=i("foreground",n?"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":"#ffffff"),c=i("background",n?"var(--persona-button-primary-bg, var(--persona-primary, #111827))":"var(--persona-accent, #0f0f0f)");e.style.color=s("textColor")||("stop"===a&&i("foreground","")?`var(--persona-button-stop-fg, ${d})`:i("foreground","")||(n?d:"")),e.style.backgroundColor=(n?s("backgroundColor"):void 0)||(i("background","")?"stop"===a?`var(--persona-button-stop-bg, ${c})`:c:"");let p=s("borderWidth")||(i("borderWidth","")?i("borderWidth",o.borderWidth||"0px"):o.borderWidth||"");e.style.borderWidth=p,e.style.borderStyle=p?"solid":"",e.style.borderColor=s("borderColor")||(i("borderColor","")?i("borderColor",o.borderColor||"transparent"):o.borderColor||""),e.style.borderRadius=i("borderRadius","")?i("borderRadius","var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))"):"",Ya(e,i("padding",n?"0":"8px 16px"),n?void 0:s("paddingX")||(i("padding","")?void 0:o.paddingX),n?void 0:s("paddingY")||(i("padding","")?void 0:o.paddingY));let u=parseFloat(o.iconSize??"")||Math.round(.5*(parseFloat(o.size??"")||40));if(r)if(e.replaceChildren(),n){let t=o.iconStrokeWidth??2,r=o.iconName?Ee(o.iconName,u,"currentColor",t):null,n=Ee(o.stopIconName??"square",u,"currentColor",t);r&&n?e.appendChild(((e,t,r="send")=>{let o=it("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"),o.append(e,t),o})(r,n,a)):r?e.appendChild(r):e.textContent=o.iconText??"↑"}else e.textContent="stop"===a?t?.copy?.stopButtonLabel??"Stop":t?.copy?.sendButtonLabel??"Send";for(let r of Array.from(e.querySelectorAll("svg"))){r.style.width=r.style.height=s("iconSize")?"":i("iconSize",`var(--persona-components-composer-sendIconSize, ${u}px)`);let e=t?.sendButton?.iconStrokeWidth;r.style.strokeWidth=void 0===e?i("iconStrokeWidth",""):String(e)}},ws=e=>{let t=e?.sendButton,r=st("div","persona-send-button-wrapper"),o=it("button",{attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"}});return vs(o,e),o.setAttribute("aria-label",t?.tooltipText??"Send message"),r.appendChild(o),Qa({anchor:o,trigger:r,text:()=>o.getAttribute("aria-label")??"",enabled:t?.showTooltip??!1}),{button:o,wrapper:r,setMode:e=>{if(o.getAttribute("data-persona-send-mode")===e)return;o.setAttribute("data-persona-send-mode",e),o.setAttribute("aria-label","stop"===e?t?.stopTooltipText??"Stop generating":t?.tooltipText??"Send message");let r=ys.get(o);vs(o,r,!1),o.querySelector(bs)?.setAttribute("data-mode",e),r?.sendButton?.useIcon||(o.textContent="stop"===e?r?.copy?.stopButtonLabel??"Stop":r?.copy?.sendButtonLabel??"Send")},glyphStack:o.querySelector(bs)}},xs=(e,t,r="idle",o="none")=>{let n=t?.voiceRecognition??{},a=e=>Ga(t,`voiceRecognition.${e}`),s=(e,r)=>Ja(t,"voice.control",e,r),i=a("iconSize")||n.iconSize;Xa(e,i||(s("size","")?s("size","var(--persona-composer-control-size, 40px)"):""),i),e.classList.add(na),e.classList.toggle(aa,!i&&!s("size","")),e.style.fontSize="18px",e.style.lineHeight="1";let l=a("iconColor")||Ga(t,"sendButton.textColor")||s("foreground","var(--persona-text, #111827)"),d=a("backgroundColor")||Ga(t,"sendButton.backgroundColor")||s("background",n.backgroundColor||"transparent"),c=a("borderColor")||s("borderColor",n.borderColor||"transparent"),p=a("borderWidth")||s("borderWidth",n.borderWidth||"");e.style.borderWidth=p,e.style.borderStyle=p?"solid":"",e.style.borderRadius=s("borderRadius","")?s("borderRadius","var(--persona-button-radius)"):"",Ya(e,s("padding","")?s("padding","0px"):"",a("paddingX")||(s("padding","")?void 0:n.paddingX),a("paddingY")||(s("padding","")?void 0:n.paddingY));let u=a("recordingBackgroundColor")||"var(--persona-voice-recording-bg, #ef4444)",h=a("recordingIconColor")||"var(--persona-voice-recording-indicator, #ffffff)",m=a("recordingBorderColor")||`var(--persona-consumer-voice-recording-border, ${n.recordingBorderColor||c})`,g=l,f=d,b=c,y=n.iconName??"mic";if("recording"===r)g=h,f=u,b=m;else if("processing"===r)g=a("processingIconColor")||`var(--persona-consumer-voice-processing-icon, ${l})`,f=a("processingBackgroundColor")||`var(--persona-consumer-voice-processing-background, ${d})`,b=a("processingBorderColor")||`var(--persona-components-voice-processing-border, ${c})`,y=n.processingIconName??"loader";else if("speaking"===r){let e="barge-in"===o;g=a("speakingIconColor")||`var(--persona-consumer-voice-speaking-icon, ${e&&a("recordingIconColor")||l})`,f=a("speakingBackgroundColor")||`var(--persona-components-voice-speaking-background, ${e?u:d})`,b=a("speakingBorderColor")||`var(--persona-components-voice-speaking-border, ${e?m:c})`,y=n.speakingIconName??("cancel"===o?"square":e?"mic":"volume-2")}e.style.color=g,e.style.backgroundColor=f,e.style.borderColor=b,e.setAttribute("data-state",r);let v=parseFloat(n.iconSize??"")||24,w=Ee(y,v,"currentColor",1.5);if(e.replaceChildren(),w){let t=i||(s("iconSize","")?s("iconSize","var(--persona-composer-control-icon-size, 24px)"):"");w.style.width=w.style.height=t,!i&&s("iconSize","")&&(w.style.flexBasis=t),w.style.strokeWidth=s("iconStrokeWidth","1.5"),e.appendChild(w)}else e.textContent="🎤"},Cs=e=>{let t=e?.voiceRecognition??{};if(!0!==t.enabled||!1===t.showButton)return null;let r=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),o="runtype"===t.provider?.type,n="custom"===t.provider?.type||"custom"===t.dictation?.provider?.type;if(!(r||o||n))return null;let a=st("div","persona-send-button-wrapper"),s=it("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-control",attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"}});xs(s,e),a.appendChild(s);let i=t.tooltipText??"Start voice recognition";return Qa({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??i,enabled:t.showTooltip??!1}),{button:s,wrapper:a}},Ss=e=>{let t=e?.attachments??{};if(!0!==t.enabled)return null;let r=st("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 o=st("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??yn).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let n=t.buttonIconName??"paperclip",a=st("div","persona-send-button-wrapper"),s=it("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${na} ${aa}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(n,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),o.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Qa({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:o,previewsContainer:r}},ks=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",o=st("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),pr(o,t,"idle");let n=t.idleText??"Online";if(t.idleLink){let e=st("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=n,e.style.color="inherit",e.style.textDecoration="none",o.appendChild(e)}else o.textContent=n;return o},As=()=>it("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Ms(e){let{config:t,onOpen:r}=e,o=t.buttonIconName??"plus",n=t.buttonTooltipText??"Add context",a=st("div","persona-send-button-wrapper"),s=it("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${na} ${aa}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":n,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(o,24,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Qa({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??n}),{button:s,wrapper:a}}let Is=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),Ts={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"},Es="16px",Ls="transparent",Bs={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:(()=>{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})(),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"}},Rs={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"}},Ps={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:is,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Es,canvasBackground:Ls,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"},operator:{background:"color-mix(in srgb, var(--persona-primary) 6%, var(--persona-container))",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"color-mix(in srgb, var(--persona-primary) 20%, var(--persona-container))",borderWidth:"1px",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"}}},Ns=Bs.colors.gray,$s={...Bs,colors:{...Bs.colors,gray:Ns}},Ws={...Bs,colors:{...Bs.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"}},Hs=$s,Ds=Rs,Fs={...Rs,colors:{...Rs.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Rs.typography,fontSize:"14px",lineHeight:"1.5"}},Os=Ds,zs=Ps,qs={...Ps,scrollToBottom:{...Ps.scrollToBottom,background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",size:"32px"},messageActions:{background:"transparent",border:"none",hoverBackground:"components.button.ghost.hoverBackground",hoverForeground:"semantic.colors.text",borderRadius:"palette.radius.md"},launcher:Ts,activity:{labelSize:"13px",iconSize:"16px",indent:"0px",transcriptGap:"0px",responseGap:"12px",groupIndent:"16px",groupGap:"2px",groupPadding:"2px 0",bodyPadding:"4px 0",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...Ps.input,borderRadius:"palette.radius.full"},introCard:{...Ps.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Ps.suggestion.chip,fontWeight:"400"},card:{...Ps.suggestion.card,fontWeight:"400"},list:{...Ps.suggestion.list,fontWeight:"400"}},panel:{...Ps.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Ps.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",iconPadding:"auto",controlSize:"28px",controlIconSize:"16px",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:{...Ps.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Ps.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:{...Ps.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"},operator:{...Ps.message.operator,background:"transparent",border:"semantic.colors.border",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"}},artifact:{...Ps.artifact,card:{background:"semantic.colors.surface",border:"1px solid var(--persona-border)",borderRadius:"palette.radius.lg",hoverBackground:"components.button.ghost.hoverBackground",hoverBorderColor:"semantic.colors.border"},inline:{background:"semantic.colors.surface",border:"1px solid var(--persona-border)",borderRadius:"palette.radius.lg",chromeBackground:"semantic.colors.surface",chromeBorder:"semantic.colors.border",titleColor:"semantic.colors.text",mutedColor:"semantic.colors.textMuted"}},composer:{...Ps.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",expandedPadding:"12px 16px",expandedBorderRadius:"24px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overflowMenu:{borderRadius:"12px"},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)"}},js=zs,_s=e=>"v5"===(e=>ps({future:e}))(e)?{palette:Ws,semantic:Fs,components:qs}:{palette:$s,semantic:Ds,components:zs};function Us(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let e of r){if(null==o)return;o=o[e]}return"string"==typeof o&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Us(e,o):o}function Vs(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let o=`${n}.${a}`;if("string"==typeof s){let r=Us(e,s);void 0!==r&&(t[o]={path:o,value:r,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,o)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Ks(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 Qs(e,t){let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&o&&"object"==typeof o&&!Array.isArray(o)?Qs(t,o):o}return r}function Js(e,t={}){let r=_s(t.future),o=e?.components,n={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:o?Qs(r.components,o):r.components},a=o?.activity;for(let e of["toolBubble","reasoningBubble"]){let t=n.components[e]={...n.components[e]};for(let r of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[r]&&("bodySurface"!==r||void 0===o?.[e]?.bodySurface)&&(t[r]=a[r])}let s=o?.collapsibleWidget?.surface;"v4"===ps(t)&&void 0!==s&&void 0===a?.bodySurface&&(n.components.activity={...n.components.activity,bodySurface:s});let i=o?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(n.components.header.minimalPadding=n.components.header.padding);let l=o?.composer;n.components.composer={...n.components.composer},void 0!==l?.padding&&void 0===l.expandedPadding&&(n.components.composer.expandedPadding=l.padding),void 0!==o?.input?.borderRadius&&void 0===l?.expandedBorderRadius&&(n.components.composer.expandedBorderRadius=o.input.borderRadius);let d=o?.message;if(void 0!==d?.gap&&void 0===d.fullscreenGap&&(n.components.message.fullscreenGap=n.components.message.gap),!1!==t.validate){let e=Ks(n);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)n=e.transform(n);return n}let Gs=e=>"0"===e.trim()?"0px":e,Ys="--persona-",Xs=(e,t)=>{for(let[r,...o]of t){let t;for(let r of o)if(t=61===r.charCodeAt(0)?r.slice(1):e[Ys+r],void 0!==t)break;void 0!==t&&(e[Ys+r]=t)}},Zs=[["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-textMuted","palette-colors-gray-500"],["text-inverse","semantic-colors-textInverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["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"]];function ei(e){let t=(e=>{let t=Vs(e),r={};for(let[e,o]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=o.value;return r})(e);Xs(t,Zs),Xs(t,[["ask-sheet-bg","components-askUserQuestion-sheet-background"],["ask-sheet-border","components-askUserQuestion-sheet-border"],["ask-sheet-shadow","components-askUserQuestion-sheet-shadow"],["ask-pill-bg","components-askUserQuestion-pill-background"],["ask-pill-fg","components-askUserQuestion-pill-foreground"],["ask-pill-radius","components-askUserQuestion-pill-borderRadius"],["ask-pill-bg-selected","components-askUserQuestion-pill-selectedBackground"],["ask-pill-fg-selected","components-askUserQuestion-pill-selectedForeground"],["ask-input-bg","components-askUserQuestion-customInput-background"],["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"]]),(e=>{let t=e["--persona-components-launcher-foreground"];e["--persona-launcher-fg-muted"]=t&&t!==e["--persona-primary"]?`color-mix(in srgb, ${t} 70%, transparent)`:e["--persona-muted"]})(t),Xs(t,[["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"]]),Xs(t,[["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"]]),t["--persona-panel-border"]=t["--persona-components-panel-border"]??`1px solid ${t["--persona-border"]}`,Xs(t,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),t["--persona-panel-inset"]=t["--persona-components-panel-inset"]??"16px",t["--persona-panel-canvas-bg"]=t["--persona-components-panel-canvasBackground"]??"transparent",Xs(t,[["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"]]);let r=(r,o,n,a="")=>{if(r)for(let[s,i,l]of n){let n=r[a+s];n&&(t[`--persona-${o}${i}`]=l?Us(e,n)??n:n)}};Xs(t,[["header-bg","components-header-background","surface"]]);let o=t["--persona-header-bg"],n=t["--persona-components-header-foreground"],a=n?`color-mix(in srgb, ${n} 72%, ${o})`:void 0;t["--persona-header-border"]=t["--persona-components-header-border"]??(n?`color-mix(in srgb, ${n} 14%, ${o})`:void 0)??t["--persona-divider"],Xs(t,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),(e=>{if("auto"===e["--persona-components-header-iconPadding"]){let t=(e["--persona-components-header-iconBackground"]??e["--persona-primary"]).trim().toLowerCase(),r=t.match(/^(?:rgba?|hsla?)\(([^)]+)\)$/)?.[1].split(/[,\s/]+/).filter(Boolean);e["--persona-components-header-iconPadding"]="transparent"===t||/^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(t)||4===r?.length&&0===parseFloat(r[3])?"0px":"6px"}})(t),t["--persona-header-title-fg"]=t["--persona-components-header-title-color"]??t["--persona-components-header-titleForeground"]??n??t["--persona-primary"],t["--persona-header-subtitle-fg"]=t["--persona-components-header-subtitle-color"]??t["--persona-components-header-subtitleForeground"]??a??t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=t["--persona-components-header-actionIconForeground"]??a??t["--persona-muted"],Xs(t,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=16px"]]),r(e.components?.header,"header-",[["shadow","shadow"],["borderBottom","border-bottom"],["minHeight","min-height"]]),r(t,"history-rail-header-",[["background","bg"],["border","border"],["minHeight","min-height"]],"--persona-components-history-railHeader-"),r(t,"history-overlay-",[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]],"--persona-components-history-overlay-"),r(t,"history-menu-",[["background","bg"],["borderRadius","radius"]],"--persona-components-history-menu-");let s=e.components?.history?.motion;if(s){let e=e=>{if(void 0===e)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},r=e(s.enterDurationMs);void 0!==r&&(t["--persona-history-enter-ms"]=r);let o=e(s.exitDurationMs);void 0!==o&&(t["--persona-history-exit-ms"]=o),s.enterEasing&&(t["--persona-history-enter-easing"]=s.enterEasing),s.exitEasing&&(t["--persona-history-exit-easing"]=s.exitEasing)}let i=t["--persona-components-history-dangerForeground"];i&&(t["--persona-history-danger-fg"]=i),t["--persona-danger"]=t["--persona-components-history-confirm-dangerBackground"]??t["--persona-palette-colors-error-700"]??"#b42318",t["--persona-danger-fg"]=t["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let e of["scrim","shadow"]){let r=t[`--persona-components-history-confirm-${e}`];r&&(t[`--persona-history-confirm-${e}`]=r)}r(t,"tooltip-",[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]],"--persona-components-tooltip-"),!1===e.components?.tooltip?.arrow&&(t["--persona-tooltip-arrow-display"]="none"),r(t,"scroll-to-bottom-count-",[["background","bg"],["foreground","fg"],["border","border"],["borderRadius","radius"],["size","size"],["padding","padding"],["fontSize","font-size"],["fontWeight","font-weight"]],"--persona-components-scrollToBottom-countBadge-"),r(t,"scroll-to-bottom-approval-",[["background","bg"],["foreground","fg"],["border","border"],["fontWeight","font-weight"]],"--persona-components-scrollToBottom-approval-"),r(t,"message-action-",[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]],"--persona-components-messageActions-"),r(t,"user-collapse-",[["fadeHeight","fade-height"],["toggleForeground","toggle-fg"],["toggleFontSize","toggle-font-size"],["toggleFontWeight","toggle-font-weight"]],"--persona-components-userMessageCollapse-"),Xs(t,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let l=t["--persona-components-introCard-background"],d=t["--persona-components-introCard-shadow"],c=!(l&&"transparent"!==l&&"none"!==l||d&&"none"!==d),p=t["--persona-components-introCard-padding"]??"1.5rem";t["--persona-intro-card-padding"]=c&&"1.5rem"===p?"1.5rem 0":p,Xs(t,[["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"]]),Xs(t,[["panel-background","components-panel-background","surface"],["transcript-background","components-message-background","container"],["transcript-top-fade-background","components-message-topFadeBackground","transcript-background"],["composer-footer-background","components-composer-footerBackground","surface"],["composer-footer-padding","components-composer-footerPadding","=1rem 1.5rem"],["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"]]),r(t,"md-",[["h1-fontSize","h1-size"],["h1-fontWeight","h1-weight"],["h2-fontSize","h2-size"],["h2-fontWeight","h2-weight"]],"--persona-components-markdown-heading-");let u=t["--persona-components-markdown-prose-fontFamily"];u&&"inherit"!==u&&(t["--persona-md-prose-font-family"]=u),Xs(t,[["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"]]),Xs(t,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Xs(t,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Xs(t,[["md-hr-color","components-markdown-hr-color","divider"]]),Xs(t,[["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"]]);for(let[e,r]of[["container","surface"],["surface","surface"],["border","border"]]){let o=t[`--persona-components-collapsibleWidget-${e}`]??t[`--persona-${r}`];void 0!==o&&(t[`--persona-cw-${e}`]=o,t[`--cw-${e}`]=o)}Xs(t,[["message-border","components-message-border","border"]]),Xs(t,[["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"],["message-operator-padding","components-message-operator-padding"],["message-operator-max-width","components-message-operator-maxWidth"],["message-operator-font-size","components-message-operator-fontSize"],["message-operator-font-family","components-message-operator-fontFamily"],["message-operator-line-height","components-message-operator-lineHeight"]]);let h=e.components;r(h?.iconButton,"icon-btn-",[["background","bg"],["border","border"],["color","color"],["padding","padding"],["borderRadius","radius"],["hoverBackground","hover-bg"],["hoverColor","hover-color"],["activeBackground","active-bg"],["activeBorder","active-border"]]),r(h?.labelButton,"label-btn-",[["background","bg"],["border","border"],["color","color"],["padding","padding"],["borderRadius","radius"],["hoverBackground","hover-bg"],["fontSize","font-size"],["gap","gap"]]),r(h?.toggleGroup,"toggle-group-",[["gap","gap"],["borderRadius","radius"]]);let m=h?.artifact;if(m?.toolbar){let o=m.toolbar;r(o,"artifact-toolbar-icon-",[["iconHoverColor","hover-color"],["iconHoverBackground","hover-bg"],["iconPadding","padding"],["iconBorderRadius","radius"],["iconBorder","border"]]),o.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Gs(o.toggleGroupGap)),o.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=o.toggleBorderRadius),o.toggleGroupPadding&&(t["--persona-artifact-toolbar-toggle-group-padding"]=Gs(o.toggleGroupPadding)),r(o,"artifact-toolbar-toggle-group-",[["toggleGroupBorder","border"],["toggleGroupBorderRadius","radius"]]),o.toggleGroupBackground&&(t["--persona-artifact-toolbar-toggle-group-bg"]=Us(e,o.toggleGroupBackground)??o.toggleGroupBackground),r(o,"artifact-toolbar-copy-",[["copyBackground","bg"],["copyBorder","border"],["copyColor","color"]]),o.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Gs(o.copyBorderRadius)),o.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=o.copyPadding),o.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=o.copyMenuBackground,t["--persona-dropdown-bg"]=t["--persona-dropdown-bg"]??o.copyMenuBackground),o.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=o.copyMenuBorder,t["--persona-dropdown-border"]=t["--persona-dropdown-border"]??o.copyMenuBorder),o.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=o.copyMenuShadow,t["--persona-dropdown-shadow"]=t["--persona-dropdown-shadow"]??o.copyMenuShadow),o.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=o.copyMenuBorderRadius,t["--persona-dropdown-radius"]=t["--persona-dropdown-radius"]??o.copyMenuBorderRadius),o.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=o.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=t["--persona-dropdown-item-hover-bg"]??o.copyMenuItemHoverBackground),r(o,"artifact-toolbar-",[["iconBackground","icon-bg"],["toolbarBorder","border"]])}if(m?.tab&&r(m.tab,"artifact-tab-",[["background","bg"],["activeBackground","active-bg"],["activeBorder","active-border"],["borderRadius","radius"],["textColor","color"],["hoverBackground","hover-bg"],["listBackground","list-bg"],["listBorderColor","list-border-color"],["listPadding","list-padding"]]),m?.pane){let r=m.pane;r.toolbarBackground&&(t["--persona-artifact-toolbar-bg"]=Us(e,r.toolbarBackground)??r.toolbarBackground)}r(m?.card,"artifact-card-",[["background","bg",!0],["border","border"],["borderRadius","radius",!0],["hoverBackground","hover-bg",!0],["hoverBorderColor","hover-border",!0]]),r(m?.inline,"artifact-inline-",[["background","bg",!0],["border","border"],["borderRadius","radius",!0],["chromeBackground","chrome-bg",!0],["chromeBorder","chrome-border",!0],["titleColor","title-color",!0],["mutedColor","muted-color",!0],["frameHeight","frame-height"]]);let g=h?.code;g&&(r(g,"code-",[["keywordColor","keyword-color"],["stringColor","string-color"],["commentColor","comment-color"],["numberColor","number-color"],["tagColor","tag-color"],["attrColor","attr-color"],["propertyColor","property-color"],["lineNumberColor","line-number-color"],["gutterBorderColor","gutter-border-color"]]),g.background&&(t["--persona-code-bg"]=Us(e,g.background)??g.background));let f=t["--persona-surface"],b=t["--persona-container"],y=t["--persona-palette-colors-gray-100"]??"#f3f4f6",v=t["--persona-palette-colors-gray-200"]??"#e5e7eb",w=t["--persona-palette-colors-gray-300"]??"#d1d5db",x=!b||b===f,C=(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[o,n,a]=t.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return.2126*o+.7152*n+.0722*a})(f??t["--persona-background"]),S=x&&void 0!==C&&C<.179,k=S?"rgba(255, 255, 255, 0.16)":w,A=x?S?"rgba(255, 255, 255, 0.08)":y:b,M=x?S?"rgba(255, 255, 255, 0.12)":v:b;return t["--persona-icon-btn-hover-bg"]=t["--persona-icon-btn-hover-bg"]??A,t["--persona-icon-btn-active-bg"]=t["--persona-icon-btn-active-bg"]??M,x&&(t["--persona-icon-btn-active-border"]=t["--persona-icon-btn-active-border"]??k),t["--persona-label-btn-hover-bg"]=t["--persona-label-btn-hover-bg"]??A,t["--persona-artifact-tab-hover-bg"]=t["--persona-artifact-tab-hover-bg"]??A,t["--persona-artifact-card-hover-bg"]=t["--persona-artifact-card-hover-bg"]??A,t}let ti={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)"}}}},ri={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"}}},oi={...ri,colors:{...ri.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"}}},ni=ti,ai={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:{...ti.components,button:{...ti.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:{...ti.components?.eventStream,badge:{...ti.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"}}}}},si=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},ii=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",li=e=>(e=>{let t=e?.colorScheme??L(e?.brand)??"light";return"light"===t?"light":"dark"===t?"dark":ii()})(e),di=e=>{let t=li(e),r=k(((e,t="light",r,o=!1)=>{let n={};if(!e)return n;let a=A(e.accent);if(a){let e={};for(let[t,r]of[[50,.96],[100,.9],[200,.75],[300,.55],[400,.25]])e[t]=T(a,255,r);e[500]=I(a);for(let[t,r]of[[600,.15],[700,.3],[800,.45],[900,.6],[950,.75]])e[t]=T(a,0,r);let t=E(a);n.palette={colors:{primary:e,accent:e}},n.semantic={colors:{primary:e[500],accent:e[500],interactive:{default:e[500],hover:e[600],focus:e[500],active:e[700]}}},n.components={button:{primary:{background:e[500],foreground:t}},launcher:{background:e[500],foreground:t},header:o?{background:"semantic.colors.container",foreground:"semantic.colors.text",iconBackground:"transparent",iconForeground:"semantic.colors.text"}:{background:e[500],foreground:t,iconBackground:e[500],iconForeground:t},approval:{approve:{foreground:t}},message:o?{user:{background:"color-mix(in srgb, var(--persona-primary) 12%, var(--persona-container))",text:"semantic.colors.text"},operator:{border:"color-mix(in srgb, var(--persona-primary) 35%, var(--persona-border))"}}:{user:{background:e[500],text:t}}}}let s=A(e.neutral);if(s){let e="dark"===t,r=e===M(s)<.18?s:A(T(s,e?0:255,.9)),o=I(r),a=T(r,e?255:0,e?.06:.025),i=T(r,e?255:0,e?.2:.16),l=E(r),d={};for(let[e,t]of[[50,0],[100,.06],[200,.16],[300,.28],[400,.45],[500,.65],[600,.72],[700,.8],[800,.9],[900,.97],[950,1]])d[e]=T(r,"#ffffff"===l?255:0,t);n.palette={...n.palette,colors:{...n.palette?.colors,gray:d}},n.semantic={...n.semantic,colors:{...n.semantic?.colors,surface:o,background:o,container:a,border:i,divider:i,text:l,textMuted:T(r,"#ffffff"===l?255:0,.65)}},n.components={...n.components,panel:{background:o},header:{...n.components?.header,background:o,foreground:l},composer:{footerBackground:o}}}if(a){let e=A(n.semantic?.colors?.surface)??("dark"===t?[15,15,16]:[255,255,255]),r=I(a),o="#ffffff"===E(e)?255:0;for(let t=0;t<=1;t+=.1){r=T(a,o,t);let n=M(A(r)),s=M(e);if((Math.max(n,s)+.05)/(Math.min(n,s)+.05)>=4.5)break}n.components={...n.components,markdown:{link:{foreground:r}},input:{focus:{border:r,ring:r}}}}e.font?.trim()&&(n.semantic={...n.semantic,typography:{fontFamily:e.font}});let i={none:"0px",sm:"4px",md:"8px",lg:"16px"}[e.radius??"none"];e.radius&&i&&(n.palette={...n.palette,radius:{none:"0px",sm:i,md:i,lg:i,xl:i,"2xl":i}},n.components={...n.components,input:{...n.components?.input,borderRadius:i},header:{...n.components?.header,controlBorderRadius:i}});let l={compact:[13,44,8],comfortable:[14,48,12],spacious:[15,52,16]}[e.density??"comfortable"];if(e.density&&l){let[e,t,r]=l;n.semantic={...n.semantic,typography:{...n.semantic?.typography,fontSize:`${e}px`}},n.components={...n.components,header:{...n.components?.header,minHeight:`${t}px`,padding:`${r}px 16px`,minimalPadding:`${r}px 16px`},history:{railHeader:{minHeight:`${t}px`}},composer:{...n.components?.composer,fontSize:`${e}px`,padding:`${r}px`,gap:r/2+"px"},message:{...n.components?.message,gap:`${r}px`,user:{...n.components?.message?.user,fontSize:`${e}px`},assistant:{fontSize:`${e}px`},operator:{...n.components?.message?.operator,fontSize:`${e}px`}}}}if(e.elevation&&["flat","subtle","raised"].includes(e.elevation)){let t="flat"===e.elevation,a=t?"none":"subtle"===e.elevation?"0 2px 8px rgba(0, 0, 0, 0.08)":"0 12px 32px rgba(0, 0, 0, 0.18)",s=t?"1px solid var(--persona-border)":"1px solid color-mix(in srgb, var(--persona-border) 65%, transparent)";n.palette={...n.palette,shadows:{sm:a,md:a,lg:a,xl:a,"2xl":a}};let i=(e,r="")=>{let n={};if(o&&"message.assistant"===r)return n;for(let[o,l]of Object.entries(e))if(o.toLowerCase().endsWith("shadow")){n[o]=a;let r="shadow"===o?"border":o.replace(/Shadow$/,"Border");r in e&&(n[r]="string"==typeof e[r]&&e[r].includes("solid")?s:t?"semantic.colors.border":"color-mix(in srgb, var(--persona-border) 65%, transparent)")}else if(l&&"object"==typeof l){let e=i(l,r?`${r}.${o}`:o);Object.keys(e).length&&(n[o]=e)}return n},l=r?i(r):{};n.components=k(n.components,l),n.components={...n.components,panel:{...n.components?.panel,shadow:a,modes:{floating:{shadow:a,border:s},inline:{shadow:a,border:s},docked:{shadow:a,border:s},sidebar:{shadow:a,border:s},mobile:{shadow:a,border:s}}},launcher:{...n.components?.launcher,shadow:a,border:"semantic.colors.border"},composer:{...n.components?.composer,shadow:a,borderColor:"semantic.colors.border"},toolBubble:{shadow:a},reasoningBubble:{shadow:a}}}return n})(e?.brand,t,_s(e?.future).components,e?.future?.v5Defaults),si(e?.theme)),o=k({components:{launcher:"circle"===Is(e)?Ts:{...zs.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},...as(e)?{panel:{background:"transparent",modes:{inline:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"transparent"},message:{background:"transparent"},composer:{footerBackground:"transparent",footerBorder:"none",overlayBand:"transparent"}}:{}}},r),n=si(e?.darkTheme),a=((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,o=t.darkTheme?.components?.panel?.width;return null==("dark"===li(t)?o??r:r)?{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===ps(t)?"400px":"420px"}}}:e})("dark"===t?((e,t={})=>{let r=(e=>"v5"===ps({future:e})?{palette:oi,components:ai}:{palette:ri,components:ni})(t.future),o=k(r.components,e??{})??{};return Js({...o,palette:{...o.palette,colors:"v5"===ps(t)?k(r.palette.colors,o.palette?.colors):{...r.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})})(k(o??{},n??{}),{future:e?.future}):((e,t={})=>Js(e,t))(o,{future:e?.future}),e);return Object.defineProperty(a,ci,{value:[...P,"suggestion.chip.padding","suggestion.chip.fontWeight"].filter(r=>q(e,r,t))}),a},ci=Symbol("persona.themeConsumerPaths"),pi=new WeakMap,ui=(e,t)=>{hi(e,(e=>{let t=ei(e);t["--persona-suggestion-compat-padding"]="6px 12px",t["--persona-suggestion-compat-weight"]="500";for(let r of e[ci]??[]){let e=r.split(".").join("-"),o=t[`--persona-components-${e}`];void 0!==o&&(t["suggestion.chip.padding"===r?"--persona-suggestion-compat-padding":"suggestion.chip.fontWeight"===r?"--persona-suggestion-compat-weight":`--persona-consumer-${e}`]=o)}return t})(di(t)),t)},hi=(e,t,r)=>{for(let r of pi.get(e)??[])r in t||e.style.removeProperty(r);pi.set(e,Object.keys(t));for(let[r,o]of Object.entries(t))e.style.setProperty(r,o);e.setAttribute("data-persona-color-scheme",li(r)),e.setAttribute("data-persona-defaults",ps(r))},mi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(ii())});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)"),o=()=>e(ii());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(e=>e())}},gi=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),fi=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",bi=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},yi=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},vi=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},wi=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),o={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)o.mod=!0;else if("shift"===r)o.shift=!0;else{if("alt"!==r&&"option"!==r)return vi("unknown modifier in",e),null;o.alt=!0}return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(vi("unsupported",e),null):("space"===r&&(o.key=" "),o)},xi=(e,t)=>{let r=wi(e);if(!r)return"";let o=yi(),n=(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&&o)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${n}`;let a=[t?o?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(n),a.join("+")},Ci=e=>xi(e,!1),Si=e=>xi(e,!0),ki=(e,t)=>t.key?.toLowerCase()===e.key&&(yi()?t.metaKey:t.ctrlKey)===e.mod&&!(yi()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Ai=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},Mi=e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),o=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let o=r.composedPath?.();return o?.length?o.includes(e):e.contains(r.target)},n=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let n of t.values())if(ki(n.parsed,e)&&!1!==n.when?.()&&o(n,e)&&(n.allowInInput||!Ai(r))){e.preventDefault();try{n.run(e)}catch(e){vi(`${n.id} threw on`,n.combo),console.warn(e)}return}};return r?.addEventListener("keydown",n),{register(e){let r=wi(e.combo);if(!r)return()=>{};let o=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,n=t.get(o);return n?(vi(`${n.id} already owns`,e.combo),()=>{}):(t.set(o,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",Si(e.combo)),()=>{t.get(o)?.id===e.id&&t.delete(o),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",n)}}};u=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: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,n){if(!1===n.callbacks.beforeNodeAdded(t))return null;if(n.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),o(a,t,n),n.callbacks.afterNodeAdded(a),a}{let o=document.importNode(t,!0);return e.insertBefore(o,r),n.callbacks.afterNodeAdded(o),o}}let t=function(){function e(e,t,r){let o=e.idMap.get(t),n=e.idMap.get(r);if(!n||!o)return!1;for(let e of o)if(n.has(e))return!0;return!1}function t(e,t){let r=e,o=t;return r.nodeType===o.nodeType&&r.tagName===o.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===o.getAttribute?.("id"))}return function(r,o,n,a){let s=null,i=o.nextSibling,l=0,d=n;for(;d&&d!=a;){if(t(d,o)){if(e(r,d,o))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 n(e,t,o){let n=t;for(;n&&n!==o;){let t=n;n=n.nextSibling,r(e,t)}return n}function a(e,t,r,o){let n=o.target.getAttribute?.("id")===t&&o.target||o.target.querySelector(`[id="${t}"]`)||o.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let o=t.idMap.get(e);o&&(o.delete(r),o.size||t.idMap.delete(e))}}(n,o),s(e,n,r),n}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&&n(s,d,e),o(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);o(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)}}}(),o=function(){function e(e,r,o){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)n(e.name,a,"update",o)||a.getAttribute(e.name)!==e.value&&a.setAttribute(e.name,e.value);for(let e=l.length-1;0<=e;e--){let t=l[e];if(t&&!i.hasAttribute(t.name)){if(n(t.name,a,"remove",o))continue;a.removeAttribute(t.name)}}s(a,o)||t(a,i,o)}(8===a||3===a)&&e.nodeValue!==r.nodeValue&&(e.nodeValue=r.nodeValue)}function t(e,t,r){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==t.type){let a=t.value,s=e.value;o(e,t,"checked",r),o(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(n("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):n("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)o(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let o=t.value,a=e.value;if(n("value",e,"update",r))return;o!==a&&(e.value=o),e.firstChild&&e.firstChild.nodeValue!==o&&(e.firstChild.nodeValue=o)}}function o(e,t,r,o){let a=t[r];if(a!==e[r]){let s=n(r,e,"update",o);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):n(r,e,"remove",o)||e.removeAttribute(r)}}function n(e,t,r,o){return!("value"!==e||!o.ignoreActiveValue||t!==document.activeElement)||!1===o.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,o,n){return n.ignoreActive&&t===document.activeElement?null:(!1===n.callbacks.beforeNodeMorphed(t,o)||(t instanceof HTMLHeadElement&&n.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==n.head.style?a(t,o,n):(e(t,o,n),s(t,n)||r(n,t,o))),n.callbacks.afterNodeMorphed(t,o)),t)}}();function n(e,t,r,o){if(e.head.block){let n=t.querySelector("head"),s=r.querySelector("head");if(n&&s){let t=a(n,s,e);return Promise.all(t).then(()=>o(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return o(e)}function a(e,t,r){let o=[],n=[],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),o=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?o?n.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?o&&(n.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&n.push(t)}s.push(...i.values());let l=[];for(let t of s){let n=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(n)){if("href"in n&&n.href||"src"in n&&n.src){let e,t=new Promise(function(t){e=t});n.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(n),r.callbacks.afterNodeAdded(n),o.push(n)}}for(let t of n)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:o,kept:a,removed:n}),l}let s=function(){function e(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}function r(){let e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function o(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 a(e,t,r,o){for(let n of o){let o=n.getAttribute("id");if(t.has(o)){let t=n;for(;t;){let n=e.get(t);if(n??(n=new Set,e.set(t,n)),n.add(o),t===r)break;t=t.parentElement}}}}function s(e,t){let r=n(e),o=n(t),s=function(e,t){let r=new Set,o=new Map;for(let{id:t,tagName:n}of e)o.has(t)?r.add(t):o.set(t,n);let n=new Set;for(let{id:e,tagName:a}of t)n.has(e)?r.add(e):o.get(e)===a&&n.add(e);for(let e of r)n.delete(e);return n}(r,o),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,o),{persistentIds:s,idMap:i}}return function(t,n,a){let{persistentIds:i,idMap:l}=s(t,n),d=e(a),c=d.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(c))throw`Do not understand how to morph style ${c}`;return{target:t,newContent:n,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:o(t),callbacks:d.callbacks,head:d.head}}}(),{normalizeElement:i,normalizeParent:l}=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 o=r.querySelectorAll(e);for(let e=0;e<o.length;e++)t.push(o[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(o){if(null==o)return document.createElement("div");if("string"==typeof o)return r(function(t){let r=new DOMParser,o=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(o.match(/<\/html>/)||o.match(/<\/head>/)||o.match(/<\/body>/)){let n=r.parseFromString(t,"text/html");if(o.match(/<\/html>/))return e.add(n),n;{let t=n.firstChild;return t&&e.add(t),t}}{let o=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(o),o}}(o));if(e.has(o))return o;if(o instanceof Node){if(o.parentNode)return new t(o);{let e=document.createElement("div");return e.append(o),e}}{let e=document.createElement("div");for(let t of[...o])e.append(t);return e}}}}();return{morph:function(e,t,o={}){e=i(e);let a=l(t),d=s(e,a,o),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:o,selectionStart:n,selectionEnd:a}=r,s=t();return o&&o!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${o}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(n,a),s}(d,()=>n(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,o){let n=l(t);return r(e,n,o,t,t.nextSibling),Array.from(n.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let Ii=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;u.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement){if(t instanceof HTMLElement&&t.hasAttribute("data-persona-reuse")&&e.id===t.id)return!1;if(o){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"))return t instanceof HTMLElement&&(!t.hasAttribute("data-preserve-animation")||(e.dataset.personaLoadingLabel?e.dataset.personaLoadingAnimation!==t.dataset.personaLoadingAnimation:e.textContent!==t.textContent))&&void 0}}}}})},Ti={index:-1,draft:""},Ei=new WeakMap;function Li(e){if("string"==typeof e)return e.length;if(!e)return 0;if("object"!=typeof e)return JSON.stringify(e)?.length??0;let t=Ei.get(e);return void 0===t&&(t=JSON.stringify(e)?.length??0,Ei.set(e,t)),t}function Bi(e,t){return[e.id,e.role,e.author?.id??"",e.author?.displayName??"",e.author?.kind??"",e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.dispatchError?"1":"0",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)??"",Li(e.toolCall?.args),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??"",e.toolCall?.actionTitle??"",t].join("\0")}let Ri=["pre","code","a","script","style"],Pi=e=>({type:e?.type??"none",placeholder:e?.placeholder??"none",speed:e?.speed??120,duration:e?.duration??1800,buffer:e?.buffer??"none"}),Ni=[{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"}],$i=new Map;for(let e of Ni)$i.set(e.name,e);let Wi=["wipe","glyph-cycle"],Hi=e=>{$i.set(e.name,e)},Di=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:$i.get(e)??null,Fi=(e,t,r,o,n)=>{if(!n)return e;if(r?.bufferContent)return r.bufferContent(e,o);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},Oi=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},zi=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},qi=/\s/,ji=(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},_i=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(qi.test(a[i])){let e=i;for(;e<a.length&&qi.test(a[e]);)e+=1;s.appendChild(o.createTextNode(a.slice(i,e))),i=e}else{let e=o.createElement("span");e.className="persona-stream-word-group";let n=i;for(;n<a.length&&!qi.test(a[n]);)e.appendChild(Oi(o,a[n],t,r.value)),r.value+=1,n+=1;s.appendChild(e),i=n}n.replaceChild(s,e)},Ui=(e,t,r)=>{let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(o.createTextNode(e)):(s.appendChild(zi(o,e,t,r.value)),r.value+=1));n.replaceChild(s,e)},Vi=(e,t,r,o)=>{if(!e||typeof document>"u")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set((o?.skipTags??Ri).map(e=>e.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)ji(l,a)||i.push(l),l=s.nextNode();let d={value:o?.startIndex??0},c="char"===t?_i:Ui;for(let e of i)c(e,r,d);return n.innerHTML},Ki=(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},Qi=(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},Ji=new WeakMap,Gi=new WeakMap,Yi=e=>{let t=Gi.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}},Xi=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=Ji.get(t);if(r||(r=new Set,Ji.set(t,r)),r.has(e.name)){let o=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${o}"]`))return;r.delete(e.name)}r.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Gi.get(t);if(r||(r=new Map,Gi.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)})(e,t)},{setLoader:Zi,load:el}=_({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),tl=Zi,rl=el;function ol(e,t=1e5){let r=e.style.position,o=e.style.zIndex,n=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=o,e.style.isolation=n}}let nl=0,al=null;function sl(e=document){if(nl++,1===nl){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;al={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,nl=Math.max(0,nl-1),0===nl&&al)){let t=e.body,r=e.defaultView??window;t.style.overflow=al.originalOverflow,t.style.position=al.originalPosition,t.style.top=al.originalTop,t.style.width=al.originalWidth,r.scrollTo(0,al.scrollY),al=null}}}let il=e=>"docked"===(e?.launcher?.mountMode??"floating"),ll=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),dl=e=>{let t=e?.launcher?.dock,r=rs(e).dockWidth?t?.width:Us(di(e),"components.panel.width");return{side:t?.side??"right",width:r??"420px",animate:t?.animate??!0,reveal:t?.reveal??"resize",maxHeight:t?.maxHeight??"100dvh"}},cl=e=>e.closest("[data-persona-instance]")?.dataset.personaInstance,pl=e=>"followUp"===e?"follow-up":e,ul=(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 o=e.prompt?.trim()||r;return{id:e.id?.trim()||o||`suggestion-${t}`,label:r,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},hl=new WeakSet,ml=e=>{let{item:t,index:r,surface:o,source:n,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,m="followUp"===o,g=t.behavior,f=()=>{if(c.isStreaming()||u.closest("[inert]"))return;let e={instanceId:cl(u),suggestion:{...t},surface:o,source:n,behavior:g},r=u.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(m&&u.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{instanceId:cl(u),suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of l)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:o,source:n,variant:a,config:i}))return;let s=p();"fill"===g?(s.value=t.prompt,s.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),s.focus()):h?h(t.prompt):(s.value="",c.sendMessage(t.prompt))},b=()=>{let e=st("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=g,"chip"===a){let t=i.suggestionChipsConfig===d?i:{suggestionChipsConfig:d},r=e=>O(t,`suggestionChipsConfig.${e}`),o=e=>q(i,`suggestion.chip.${e}`,"light")||q(i,`suggestion.chip.${e}`,"dark");d?.fontWeight&&(e.style.fontWeight=!r("fontWeight")&&o("fontWeight")?"var(--persona-suggestion-compat-weight, 500)":d.fontWeight);let n=o("padding");n&&(e.classList.add("persona-theme-padding"),e.style.setProperty("--persona-theme-padding","var(--persona-suggestion-compat-padding, 6px 12px)")),d?.paddingX&&(r("paddingX")||!n)&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(r("paddingY")||!n)&&(e.style.paddingTop=d.paddingY,e.style.paddingBottom=d.paddingY)}if(t.icon){let r=Ee(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=st("span","persona-suggestion__copy");if(r.appendChild(it("span",{className:"persona-suggestion__label",text:t.label})),t.description&&"chip"!==a&&r.appendChild(it("span",{className:"persona-suggestion__description",text:t.description})),e.appendChild(r),"chip"!==a){let t=ne(ce,16,"currentColor",1.8);t&&(t.classList.add("persona-suggestion__arrow"),e.appendChild(t))}return e.addEventListener("click",f),e},y=null;for(let e of l)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:r,surface:o,source:n,variant:a,streaming:s,config:i,defaultRenderer:b,select:f}),y))break;return y??=b(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute("aria-disabled",s?"true":"false"),y},gl=e=>{let t=[],r=[],o=null,n=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(n=null,e.toggleAttribute("data-edge-to-edge",e.hasAttribute("data-hide-scrollbar")&&(e.hasAttribute("data-persona-composer-suggestions")||"follow-up"===e.dataset.personaSuggestions)&&"chip"===e.dataset.variant&&"scroll"===e.dataset.overflow),e.hasAttribute("data-edge-to-edge")&&e.parentElement){let t=e.parentElement,r=getComputedStyle(t),o=parseFloat(r.paddingLeft)||0,n=parseFloat(r.paddingRight)||0;e.style.setProperty("--persona-suggestion-bleed-left",`${o}px`),e.style.setProperty("--persona-suggestion-bleed-right",`${n}px`);let a=t.closest(".persona-widget-container")?.querySelector("form"),s=t.getBoundingClientRect(),i=a?.getBoundingClientRect();e.style.setProperty("--persona-suggestion-inset-left",`${i?.width?i.left-s.left:o}px`),e.style.setProperty("--persona-suggestion-inset-right",`${i?.width?s.right-i.right:n}px`)}if(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,o=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=o<=4,i=o>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==n||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():n=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!==n&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n),n=null},render:(n,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",b=u?.behavior??"send",y=u?.overflow??"wrap",v=u?.config??{},w=u?.plugins??[];e.toggleAttribute("data-hide-scrollbar",!0===v.future?.v5Defaults),e.dataset.edgeStyle=v.suggestions?.[g?"followUps":"starters"]?.edgeStyle??"fade";let x="number"==typeof u?.maxItems?Math.max(0,Math.floor(u.maxItems)):void 0,C=g?"followUps":"starters";!hl.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(hl.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(ul).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??b})),k=S(n??[]);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,o=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(o=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=pl(m),e.dataset.variant=f,e.dataset.overflow=y;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((o,n)=>{let a=ml({item:o,index:n,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!==o&&(o=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:{instanceId:cl(e),suggestions:A.map(e=>({...e})),surface:m,source:h,variant:f},bubbles:!0,composed:!0})),g&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{instanceId:cl(e),suggestions:A.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},fl={"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"},bl={x:[1.4,1.05]},yl="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",vl=(e,t,r={})=>{let{iconSize:o,iconText:n}=r,[a,s]=bl[t]??[1,1.5],i=!o;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=Ee(t,`${Math.round((parseFloat(o??"")||16)*a)}px`,"currentColor",s);l?(l.style.display="block",i||(l.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((s/1.5).toFixed(4))})`),e.replaceChildren(l)):n&&(e.textContent=n)},wl=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:o,iconName:n,iconText:a,wrapperClassName:s=yl,size:i,iconSize:l,color:d,backgroundColor:c,borderWidth:p,borderColor:u,borderRadius:h,paddingX:m,paddingY:g,hidden:f,extraClassName:b,attrs:y}=e,v=st("div",s),w=!(!p&&!u),x=it("button",{className:lt("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",b),attrs:{type:"button","aria-label":t,...y},style:{width:i,height:i,minWidth:i,minHeight:i,display:f?"none":void 0,color:d||kl.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return n?vl(x,n,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Qa({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:o,enabled:r}),{button:x,wrapper:v}},xl=(e,t,r,o={})=>{let n=t?.launcher,a=n?.clearChat,s=e=>Ga(t,(e=>"close"===r?`launcher.closeButton${e[0].toUpperCase()}${e.slice(1)}`:`launcher.clearChat.${"color"===e?"iconColor":e}`)(e)),i=(e,o)=>Ja(t,`header.${r}`,e,o),l=(e,t,r)=>s(e)||i(t,r),d=o.buttonSize||s("size");Xa(e,d||i("size","var(--persona-header-control-size, 32px)"),d),!d&&""===i("size","")&&(e.style.width=e.style.height="");let c="close"===r?n?.closeButtonBackgroundColor:a?.backgroundColor;e.style.color=l("color","foreground",kl.actionIconColor),e.style.backgroundColor=s("backgroundColor")||(i("background","")?i("background",c||"transparent"):c||""),e.classList.toggle("hover:persona-bg-gray-100",!c&&!s("backgroundColor")&&""===i("background",""));let p="close"===r?n?.closeButtonBorderWidth:a?.borderWidth,u="close"===r?n?.closeButtonBorderColor:a?.borderColor,h=!!(p||u||i("borderWidth","")||i("borderColor",""));e.style.border=h?`${l("borderWidth","borderWidth",p||"0px")} solid ${l("borderColor","borderColor",u||"transparent")}`:"",e.classList.toggle("persona-border-none",!h);let m="close"===r?n?.closeButtonBorderRadius:a?.borderRadius;e.style.borderRadius=s("borderRadius")||(i("borderRadius","")?i("borderRadius","var(--persona-components-header-controlBorderRadius, 9999px)"):m||""),e.classList.toggle("persona-rounded-full",!e.style.borderRadius);let g="close"===r?n?.closeButtonPaddingX:a?.paddingX,f="close"===r?n?.closeButtonPaddingY:a?.paddingY,b=i("padding","0px");Ya(e,b,s("paddingX")||("0px"===b?g:void 0),s("paddingY")||("0px"===b?f:void 0));let y="close"===r?n?.closeButtonIconName??"x":a?.iconName??"refresh-cw";vl(e,y,{iconSize:o.iconSize,iconText:"close"===r?n?.closeButtonIconText??"×":void 0});let v=e.querySelector("svg");if(v){let e=bl[y]?.[0]??1,t=i("iconSize","");!o.iconSize&&t&&(v.style.width=v.style.height=`calc(${i("iconSize","var(--persona-header-control-icon-size, 16px)")} * ${e})`),i("iconStrokeWidth","")&&(v.style.strokeWidth=`calc(${i("iconStrokeWidth","var(--persona-components-header-controlStrokeWidth, 1.5)")} * ${1===e?1:.7})`)}},Cl=(e,t={})=>{let{showClose:r=!0,wrapperClassName:o=yl,buttonSize:n,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=wl({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:o,size:n??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 xl(d,e,"close",{buttonSize:n,iconSize:a}),{button:d,wrapper:c}},Sl=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:o,iconSize:n}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=wl({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:o??a.size,iconSize:n,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return xl(l,e,"clear",{buttonSize:o,iconSize:n}),{button:l,wrapper:d}},kl={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)"},Al={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)"},Ml={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)"},Il=e=>{let{config:t,showClose:r=!0}=e,o=it("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:kl.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)))"}}),n=t?.launcher??{},a=n.headerIconSize??"40px",s=n.closeButtonPlacement??"inline",i=n.headerIconHidden??!1,l=n.headerIconName,d=it("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,boxSizing:"content-box",padding:"var(--persona-components-header-iconPadding, 0px)",flexShrink:"0",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=Ee(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=st("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=st("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=it("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:kl.titleColor,...Al}}),u=it("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:kl.subtitleColor,...Ml}});c.append(p,u),i?o.append(c):o.append(d,c);let h=n.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,b=null;if(m){let e=Sl(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,b=e.wrapper,"top-right"===g&&(b.style.right="48px"),"inline"===g&&o.appendChild(b)}let{button:y,wrapper:v}=Cl(t,{showClose:r,wrapperClassName:"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"});return"top-right"!==s&&o.appendChild(v),{header:o,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:y,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:b}},Tl=(e,t,r)=>{let o=r?.launcher??{},n=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===n&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))},El=e=>{let t=Il({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},Ll=e=>{let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=t?.launcher??{},i=st("div","persona-flex persona-items-center persona-justify-between");i.setAttribute("data-persona-theme-zone","header"),i.style.minHeight=kl.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=n?.titleMenu;if(c){let e=gt({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,instanceId:e.element.closest("[data-persona-instance]")?.dataset.personaInstance}}))},o=c.onSelect(t);o instanceof Promise?o.then(r,()=>{}):r(o)},hover:c.hover,className:""});l=e.element,l.style.color=kl.titleColor,d=l.querySelector(".persona-combo-btn-label")??l}else{if(l=st("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=st("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=kl.titleColor,Object.assign(d.style,Al),d.textContent=s.title??"Chat Assistant",l.appendChild(d),n?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=n.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=n?.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}=Cl(t,{showClose:r,wrapperClassName:p});o&&u.addEventListener("click",o);let m=st("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let o of t){let{button:t,wrapper:n}=wl({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Ci(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",o.id),o.shortcut){let e=Si(o.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(o.menuItems?.length){let e=ct({items:o.menuItems,onSelect:e=>r?.(e),anchor:n,position:"bottom-right"});n.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(o.id));e.appendChild(n)}}(m,n?.trailingActions,n?.onAction??a);let g=s.clearChat??{},f=null,b=null;if(g.enabled??1){let e=g.placement??"inline",r=Sl(t,{wrapperClassName:"top-right"===e?"persona-absolute persona-top-4 persona-z-50":p});f=r.button,b=r.wrapper,"top-right"===e?b.style.right="48px":m.appendChild(b)}m.appendChild(h),i.appendChild(m);let y=st("div");y.style.display="none";let v=st("span");return v.style.display="none",{header:i,iconHolder:y,headerTitle:d,headerSubtitle:v,closeButton:u,closeButtonWrapper:h,clearChatButton:f,clearChatButtonWrapper:b}},Bl={default:El,minimal:Ll},Rl=e=>Bl[e]??Bl.default,Pl=(e,t,r)=>{if(t?.render){let o=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),n=st("div");n.style.display="none";let a=st("span"),s=st("span"),i=st("button");i.style.display="none";let l=st("div");return l.style.display="none",{header:o,iconHolder:n,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let o=Rl(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&&(o.iconHolder.style.display="none"),!1===t.showTitle&&(o.headerTitle.style.display="none"),!1===t.showSubtitle&&(o.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(o.closeButton.style.display="none"),!1===t.showClearChat&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};function Nl(e,t){if(!t.defaultPrevented){for(let r of t.composedPath()){if(r===e)break;if(r instanceof Element&&r.matches('button, input, textarea, select, a[href], label, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="combobox"], [tabindex]'))return}(e.querySelector('[data-persona-composer-input][contenteditable="true"]')??e.querySelector("textarea[data-persona-composer-input]"))?.focus()}}let $l=e=>{let{config:t}=e,r=it("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=As(),n=it("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}=fs(t);s();let i=ws(t),l=Cs(t),d=Ss(t),c=ks(t),p=it("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(p),d&&(p.append(d.previewsContainer),n.append(d.input)),n.append(a);let u=it("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=it("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),m=it("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),n.append(u),n.addEventListener("click",e=>{Nl(n,e)}),"transient"===t?.statusIndicator?.mode?r.append(o,c,n):r.append(o,n,c),{footer:r,suggestions:o,composerForm:n,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}},Wl=e=>{let{config:t}=e,r=it("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=As(),n=ks(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=fs(t,{defaultMaxLines:5});s();let i=ws(t),l=Cs(t),d=Ss(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=it("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),p=it("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&p.append(d.wrapper);let u=it("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=>{Nl(c,e)}),d&&c.append(d.input),c.append(p,a,u);let h=it("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(h),d&&h.append(d.previewsContainer),r.append(o,c,n);let m=c;return{footer:r,suggestions:o,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:n,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 Hl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let r=it("span",{className:lt("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 o=Ee(e.iconName??"at-sign",13,"currentColor",2);if(o){let e=st("span","persona-mention-token-icon");e.appendChild(o),r.appendChild(e)}return r.appendChild(it("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let Dl="data-persona-user-collapse",Fl="data-persona-user-collapse-toggle",Ol=e=>!0===e.features?.userMessageCollapse?.enabled,zl=e=>{let t=e.features?.userMessageCollapse?.maxHeight;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:240},ql=e=>({showMoreLabel:e.copy?.showMoreLabel?.trim()||"Show more",showLessLabel:e.copy?.showLessLabel?.trim()||"Show less"}),jl=(e,t)=>e>t+48,_l=e=>`persona-user-collapse-${e}`,Ul=(e,t,r,o)=>{let{state:n}=o;t.setAttribute(Dl,n),t.style.setProperty("--persona-user-collapse-max-height",`${o.maxHeight}px`);let a=e.querySelector(`button[${Fl}]`);if("collapsed"!==n&&"expanded"!==n)return void a?.remove();a||(a=it("button",{className:"persona-user-collapse-toggle",attrs:{type:"button",id:`persona-user-collapse-toggle-${r}`,[Fl]:"","aria-controls":_l(r)}}),t.after(a));let s="expanded"===n;a.setAttribute("aria-expanded",s?"true":"false"),a.textContent=s?o.showLessLabel:o.showMoreLabel},Vl=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(":"))},Kl=(e={})=>{let t=e.loadingIndicator,r=e.future?.v5Defaults;if("label"===(t?.variant??(r?"label":"dots"))){let o=it("div",{className:"persona-loading-label",attrs:{role:"status"}});r&&!0!==t?.showBubble&&o.classList.add("persona-activity-row","persona-activity-header");let n=e.features?.toolCallDisplay,a=t?.iconVisibility??(!1!==n?.grouped&&"collapsible"===(n?.groupedMode??"collapsible")?n?.groupIconVisibility:void 0)??n?.iconVisibility,s=t?.iconName??"loader-circle";if("never"!==a&&(r||t?.iconName||t?.iconVisibility)){let e=Ee(s,16);e&&(e.classList.add("persona-activity-icon"),e.dataset.loadingIconAnimation=t?.iconAnimation??("loader-circle"===s?"spin":"none"),o.appendChild(e))}let i=it("span",{text:t?.label??"Thinking…"});return o.appendChild(i),je()?.applyLoadingLabel(i,e,"waiting"),o}let o=st("div","persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2");for(let e=0;e<3;e++){let t=st("div","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=250*e+"ms",o.appendChild(t)}let n=st("span","persona-sr-only");return n.textContent="Loading",o.appendChild(n),o},Ql=(e,t,r)=>t?.({config:r??{},streaming:!0,location:e,defaultRenderer:()=>Kl(r)})??Kl(r),Jl=(e,t,r="div")=>{let o=st(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return o.textContent=t.format?t.format(n):n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Gl=new Set(["persona-bg-persona-container","persona-text-persona-text","persona-border-persona-message-border"]),Yl=(e,t="bubble")=>{if("operator"===e){let e=Yl("assistant",t).flatMap(e=>"persona-message-assistant-bubble"===e?["persona-message-operator-bubble"]:Gl.has(e)?[]:[e]);return"flat"===t?[...e,"persona-px-3"]:e}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},Xl={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"}},Zl=(e,t,r="bubble",o)=>{if(!o)return;let n="user"===t||"operator"===t?t:"assistant",a=Xl[r??"bubble"]??Xl.bubble;o.padding&&(e.style.padding=`var(--persona-message-${n}-padding, ${a.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${n}-font-size, ${a.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${n}-line-height, ${a.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${n}-font-family, inherit)`)},ed=e=>`custom:${e}`,td=(e,t)=>"user"!==t&&"assistant"!==t&&"operator"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),rd=(e,t,r,o,n=!1)=>{let a=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&!0===o?.canRegenerate,c=(t.showEdit??!1)&&!0===o?.canEdit,p=(t.showQuote??!1)&&!1!==o?.canQuote,u=td(t,e.role);if(!(a||s||i||l||d||c||p||0!==u.length)){let t=st("div");return t.style.display="none",t.id=`actions-${e.id}`,t.setAttribute("data-actions-for",e.id),t}let h=t.visibility??(n&&o?.isLastAssistant?"always":"hover"),m=t.align??"right",g=t.layout??"pill-inside",f=st("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"}[m]} ${{"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[g]} ${"hover"===h?"persona-message-actions-hover":""} ${n?"persona-message-actions-adaptive":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let b=(e,t,r)=>{let o=pt({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return o.setAttribute("data-action",r),o};a&&f.appendChild(b("copy","Copy message","copy")),l&&f.appendChild(b("volume-2","Read aloud","read-aloud")),s&&f.appendChild(b("thumbs-up","Upvote","upvote")),i&&f.appendChild(b("thumbs-down","Downvote","downvote")),d&&f.appendChild(b("refresh-cw","Regenerate response","regenerate")),c&&f.appendChild(b("pencil","Edit message","edit")),p&&f.appendChild(b("quote","Quote message","quote"));for(let e of u)f.appendChild(b(e.iconName??"ellipsis",e.label,ed(e.id)));return f},od=(e,t,r,o,n,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=Yl(e.role,i),g=st("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id);let f="operator"===e.role;f&&!0===a?.widgetConfig?.future?.v5Defaults&&g.classList.add("persona-border"),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":f?"operator-message":"assistant-message");let b=_s(a?.widgetConfig?.future).components.message,y=a?.widgetConfig?.theme?.components?.message,v=a?.widgetConfig?.darkTheme?.components?.message;if(Zl(g,e.role,i,"user"===e.role?{...b.user,...y?.user,...v?.user}:f?{...b.operator,...y?.operator,...v?.operator}:{...b.assistant,...y?.assistant,...v?.assistant}),"flat"!==i||f?"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))"):f&&(g.style.backgroundColor="var(--persona-components-message-operator-background, var(--persona-container))",g.style.color="var(--persona-components-message-operator-text, var(--persona-text))"):(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"),f){let t=st("div","persona-message-author persona-text-xs persona-font-medium persona-mb-1"),r=a?.widgetConfig?.copy?.operatorLabel,o="string"==typeof r&&r.trim()?r.trim():"Human operator",n="string"==typeof e.author?.displayName?e.author.displayName.trim():"";t.textContent=n?`${n} · ${o}`:o,g.setAttribute("role","group"),g.setAttribute("aria-label",t.textContent),g.appendChild(t)}let w=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),x=e.content?.trim()??"",C=w.length>0&&"[Image]"===x,S=Pi(a?.widgetConfig?.features?.streamAnimation),k=a?.widgetConfig?.features?.streamAnimation?.plugins,A="assistant"===e.role&&"none"!==S.type?Di(S.type,k):null,M="assistant"===e.role&&!0===A?.isAnimating?.(e),I="assistant"===e.role&&null!==A&&(!!e.streaming||M);I&&A?.bubbleClass&&g.classList.add(A.bubbleClass);let T=document.createElement("div");T.classList.add("persona-message-content"),e.streaming&&T.classList.add("persona-content-streaming"),I&&A&&(A.containerClass&&T.classList.add(A.containerClass),T.style.setProperty("--persona-stream-step",`${S.speed}ms`),T.style.setProperty("--persona-stream-duration",`${S.duration}ms`));let E=I?Fi(e.content??"",S.buffer,A,e,!!e.streaming):e.content??"",L=()=>{let r=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return I&&"char"===A?.wrap?Vi(r,"char",e.id,{skipTags:A.skipTags}):I&&"word"===A?.wrap?Vi(r,"word",e.id,{skipTags:A.skipTags}):r},B=null;if(C?(B=document.createElement("div"),B.innerHTML=L(),B.style.display="none",T.appendChild(B)):e.contentSegments?.length?((e,t,r,o)=>{let n=Math.random().toString(36).slice(2,8),a=e=>`${n}:${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 o of e)"text"===o.kind?r.appendChild(document.createTextNode(o.text)):r.appendChild(Hl(o.ref,{readonly:!0,render:t}));return r})(t,o));e.innerHTML=s;let i=RegExp(`${n}:(\\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 n=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===n?.kind&&a.parentNode?.insertBefore(Hl(n.ref,{readonly:!0,render:o}),a),r=a}}})(T,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):T.innerHTML=L(),I&&A?.useCaret&&!C&&x){let e=Ki(),t=T.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=T.lastElementChild;t?t.appendChild(e):T.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=Jl(e,d,"span");t.classList.add("persona-timestamp-inline");let r=T.lastElementChild;r?r.appendChild(t):T.appendChild(t)}let R="user"===e.role?a?.userCollapse:void 0,P=R?((e,t)=>{let r=it("div",{className:"persona-user-collapse-region",attrs:{id:_l(e),[Dl]:"fit"}});return r.style.setProperty("--persona-user-collapse-max-height",`${t}px`),r})(e.id,R.maxHeight):null,N=P??g;if(w.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let o=st("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r?.())};return e.forEach((e,t)=>{let r=st("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;n+=1,r.addEventListener("error",()=>{a||(a=!0,n=Math.max(0,n-1),r.remove(),0===n&&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,o.appendChild(r)):(a=!0,n=Math.max(0,n-1),r.remove())}),0===n?(s(),null):o}catch{return r?.(),null}})(w,!C&&!!x,()=>{C&&B&&(B.style.display="")});e?N.appendChild(e):C&&B&&(B.style.display="")}let $=(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($.length>0){let e=(e=>{if(0===e.length)return null;try{let t=st("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!Vl(e.audio))return;let o=st("audio");o.controls=!0,o.preload="metadata",o.src=e.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})($);e&&N.appendChild(e)}let W=(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(W.length>0){let e=(e=>{if(0===e.length)return null;try{let t=st("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(e=>{if(!Vl(e.video))return;let o=st("video");o.controls=!0,o.preload="metadata",o.src=e.video,o.style.display="block",o.style.width="100%",o.style.maxWidth="320px",o.style.maxHeight="320px",o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(W);e&&N.appendChild(e)}let H=(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(H.length>0){let e=(e=>{if(0===e.length)return null;try{let t=st("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(e=>{if(!Vl(e.data))return;let o=st("a");o.href=e.data,o.download=e.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=e.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(H);e&&N.appendChild(e)}let D=e.contentSegments?.length?null:(e=>{if(!e||0===e.length)return null;let t=it("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let r of e){let e=it("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:r.label}}),o=st("span","persona-mention-chip-icon"),n=Ee(r.iconName??"at-sign",13,"currentColor",2);n&&o.appendChild(n),e.appendChild(o),e.appendChild(it("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(D&&N.appendChild(D),N.appendChild(T),P&&R&&(g.appendChild(P),Ul(g,P,e.id,R)),p&&"below"===h&&e.createdAt){let t=Jl(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let F="assistant"===e.role?((e,t)=>{if(!e)return null;let r=(e=>{switch(e){case"max_tool_calls":return"Tool limit reached.";case"length":return"Output token limit reached.";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 o=t?.[e];return(void 0===o?r:o)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!E||!E.trim()),t="skeleton"===S.placeholder,r=t&&"line"===S.buffer&&e;if(e)r&&g.appendChild(Qi());else if(t)g.appendChild(Qi());else{let e=Ql("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}F&&e.stopReason&&!e.streaming&&(x||(T.style.display="none"),g.appendChild(((e,t)=>it("div",{className:"persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic",attrs:{"data-stop-reason":e,role:"note"},style:{opacity:"0.75"},text:t}))(e.stopReason,F)));let O=("assistant"===e.role||f)&&!e.streaming&&!e.voiceCaption&&(x.length>0||f&&td(o,"operator").length>0)&&!1!==o?.enabled,z=a?.actionEligibility,q="user"===e.role&&!e.streaming&&!1!==o?.enabled&&(!0===o?.showEdit&&!0===z?.canEdit||!0===o?.showQuote&&!0===z?.canQuote||td(o,"user").length>0);if((O||q)&&o){let t=rd(e,q?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:f?{...o,showCopy:x.length>0&&!1!==o.showCopy,showUpvote:!1,showDownvote:!1,showReadAloud:!1,showRegenerate:!1,showEdit:!1,showQuote:!1}:o,0,z,!0===a?.widgetConfig?.future?.v5Defaults&&void 0===o.visibility);g.appendChild(t)}if(!c||"system"===e.role)return g;let j=st("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),_=((e,t)=>{let r=st("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o="operator"===t,n="user"===t?e.userAvatar:o?e.operatorAvatar:e.assistantAvatar,a=()=>{r.classList.add(...o?["persona-bg-persona-container","persona-text-persona-text","persona-border"]:["user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white"])};if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=st("img");e.src=n,e.alt="user"===t?"User":o?"Operator":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,a();else r.textContent="user"===t?"U":o?"O":"A",a();return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?j.append(g,_):j.append(_,g),j},nd=(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)},ad=(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)}if(!r)return void(e.hidden=!0);e.appendChild(r),e.hidden=!1}else{if("lucide"===t.type){let r=Ee(t.name,40);if(!r)return void(e.hidden=!0);e.appendChild(r)}else"image"===t.type?e.appendChild(it("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(it("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")},sd="data-persona-welcome-overlay",id="persona-welcome-overlay-active",ld=new WeakMap,dd=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(sd,""),e.classList.contains(id)||(ld.set(e,e.scrollTop),e.classList.add(id),e.scrollTop=0)},cd=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(sd),e.classList.contains(id)&&(e.classList.remove(id),e.scrollTop=ld.get(e)??e.scrollTop,ld.delete(e))},pd=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let o=r?.layout?.messages?.layout??"bubble",n=it("div",{className:Yl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===o?{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(it("div",{className:"persona-flex"},n)),e.hidden=!1},ud=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,hd=(e,t)=>{if(ud()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),o=e.parentElement,n=0,a=0,s=0;if(o){let t=getComputedStyle(o);n=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=o.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-o.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-n:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-n: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:-n+"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},md=(e,t,r,o=260)=>{if(t<=1||ud()||"function"!=typeof e.animate||!e.isConnected)return null;let n="drop"===r?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})},gd=new WeakSet,fd=(e,t)=>!!e&&void 0!==e[t],bd=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,o=e?.copy,n=!0===e?.future?.v5Defaults,a=r?.layout??(n?"centered":"top"),s=fd(r,"variant")?r.variant:!1===o?.showWelcomeCard?"none":"card",i="hero"!==s||n||void 0!==r?.layout?fd(r,"dismiss")?r.dismiss:n||"hero"===s?"on-first-message":"never":"on-first-message",l=[];for(let[e,t]of[["title","welcomeTitle"],["subtitle","welcomeSubtitle"],["variant","showWelcomeCard"]])fd(r,e)&&fd(o,t)&&l.push(`welcome.${e} and copy.${t} are both set; welcome.${e} wins. copy.${t} is deprecated.`);"hero"===s&&fd(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!n&&void 0===r?.layout&&"hero"===s&&fd(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??("none"!==s&&"centered"===a&&t?"center":"bottom"),c=null!==bi(r?.anchorComposerTop);return fd(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(fd(r,"anchorComposerTop")||fd(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{e&&!0===e.debug&&t.length&&!gd.has(e)&&(gd.add(e),t.forEach(e=>console.warn(`[persona] ${e}`)))})(e,l),{title:fd(r,"title")?r.title:o?.welcomeTitle??(n?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:fd(r,"subtitle")?r.subtitle:o?.welcomeSubtitle??(n?"":"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()||"24px"}},yd=e=>!(!e.content.trim()&&!e.contentParts?.some(e=>"text"!==e.type||e.text.trim())),vd=(e=[])=>e.some(e=>"user"===e.role||"operator"===e.role&&yd(e)||"assistant"===e.role&&(yd(e)||e.toolCall||e.tools?.length||e.reasoning||e.approval)),wd=e=>vd(e)?"active":"empty",xd=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!vd(t)),Cd="var(--persona-components-panel-height)",Sd=e=>{let t=rs(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===o?`max(200px, ${Cd})`:`max(200px, calc(${Cd} - ${o}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},kd=e=>{let t=rs(e);return t.launcherWidth||t.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?Sd(e).width:"100%"},Ad="16px",Md="10px",Id="14px",Td=e=>{let t=it("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":pl(e)}});return t.hidden=!0,t},Ed=(e,t)=>{let r=((e,t,r={})=>{let o=it("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let n=st("p","persona-welcome-kicker");n.hidden=!0;let a=st("h2","persona-welcome-title"),s=st("p","persona-welcome-subtitle"),i=it("div",{className:"persona-welcome-head-text"},n,a),l=it("div",{className:"persona-welcome-title-row"},o,i);return{host:it("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:o,kicker:n,title:a,subtitle:s,starterSuggestions:t}})(0,Td("starter"),{flatShadow:il(e)}),o=bd(e);ad(r,o),nd(t,r.host,xd(o,e?.initialMessages));let n=(()=>{let e=it("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return pd(n,o.message,e),{welcome:r,greetingHost:n}},Ld=(e,t)=>{let r=st("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 o=e=>{let t=e.launcher??{},o=il(e),n="circle"===Is(e);n?(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||o||n?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,o=Ee(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);o?(l.appendChild(o),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||n)c.style.display="none";else if(c.style.display=o?"none":"",c.innerHTML="",t.callToActionIconName){let o=Math.max((parseFloat(e)||24)-r,8),n=Ee(t.callToActionIconName,o,"currentColor",1.5);n?c.appendChild(n):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&fl[t.position]?fl[t.position]:fl["bottom-right"];r.className=o?"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}`,o||(r.style.zIndex=String(t.zIndex??1e5)),r.style.border=t.border??"1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",r.style.boxShadow=void 0===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))":""===t.shadow.trim()?"none":t.shadow,o?(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&&o(e),{element:r,update:o,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},Bd=new Set,Rd=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},Pd=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=(e=>{let t=e?.launcher?.enabled??!0,r=il(e);if(ll(e)){let t=e?.launcher?.composerBar??{},r=st("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??1e5);let o=st("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");o.style.width="100%",r.appendChild(o);let n=st("div","persona-widget-pill-root");return n.setAttribute("data-persona-composer-bar",""),n.dataset.state="collapsed",n.dataset.expandedSize=t.expandedSize??"anchored",n.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:o,pillRoot:n}}if(r){let e=st("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),t=st("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=st("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),r=st("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0");return t.style.width=kd(e),r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let o=e?.launcher??{},n=o.position&&fl[o.position]?fl[o.position]:fl["bottom-right"],a=st("div",`persona-widget-wrapper persona-fixed ${n} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=st("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=Sd(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(ll(e))return((e,t)=>{let r=st("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Cl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Ad,iconSize:Md});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=Sl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Ad,iconSize:Id});a=t.button,s=t.wrapper,s.style.position="absolute",s.style.top="8px",s.style.right="32px",s.style.zIndex="10"}let i=it("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=it("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}=Ed(e,l),{host:p,title:u,subtitle:h}=d,m=d.starterSuggestions,g=st("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let f=Td("followUp"),b=gi(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 y=it("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"}}),v=Wl({config:e}),{root:w,textNode:x}=(()=>{let e=it("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=st("span","persona-pill-peek__icon"),r=ne(ye,16,"currentColor",1.5);r&&t.appendChild(r);let o=st("span","persona-pill-peek__text"),n=st("span","persona-pill-peek__caret"),a=ne(ue,16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}})();return r.append(i,n,l,y),s&&r.appendChild(s),{container:r,body:l,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:f,composerOverlay:y,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,welcomeHost:p,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:u,introSubtitle:h,closeButton:o,closeButtonWrapper:n,clearChatButton:a,clearChatButtonWrapper:s,iconHolder:st("span"),headerTitle:st("span"),headerSubtitle:st("span"),header:i,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions,setSendButtonMode:v.setSendButtonMode,peekBanner:w,peekTextNode:x}})(e,t);let r=it("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,n=ss(e),a=o?Pl(e,o,{showClose:t}):Il({config:e,showClose:t}),s=it("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}=Ed(e,s),{host:d,title:c,subtitle:p}=i,u=i.starterSuggestions,h=st("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let m=Td("followUp"),g=gi(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=$l({config:e}),b=!1!==e?.layout?.showFooter;n||(a.header.style.display="none"),Tl(r,a,e),r.append(s);let y=it("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(y),{container:r,body:s,messagesWrapper:h,starterSuggestions:u,transcriptSuggestions:m,composerOverlay:y,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:o,pillRoot:n},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}}},Nd=({config:e,plugins:t,onToggle:r})=>{let o=t.find(e=>e.renderLauncher);if(o?.renderLauncher){let t=o.renderLauncher({config:e,defaultRenderer:()=>Ld(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let n=((e,t)=>{let r=st("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let o=e??{},n=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(n?.frequency??"once")&&!1!==o.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(Bd.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(Rd(o),e&&h())},f=e=>{n&&!p&&g("user"===e&&d)},b=()=>{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"}))},y=()=>{g(h()),t()},v=e=>{e.stopPropagation(),g(h())},w=Ld(e,()=>{f("user"),t()}),x=()=>{m(),i?.removeEventListener("click",y),s?.removeEventListener("click",v),a?.remove(),a=null,i=null,s=null,d=!1},C=()=>{let e=o.launcher?.position??"bottom-right",t=fl[e]??fl["bottom-right"];a?(r.className=lt("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(o.launcher?.zIndex??1e5),w.element.style.position="static"):(r.className="persona-launcher-surface",r.removeAttribute("data-teaser"),r.style.zIndex="",w.element.style.position="")},S=e=>{let t=(e=>{let t=e?.launcher?.teaser;return t&&t.text&&!1!==e?.launcher?.enabled&&!il(e??{})?t:null})(e);n=t,t?(a||(i=it("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",y),s=it("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"×"}),s.addEventListener("click",v),a=it("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"),n&&a&&(p||c||u||((e,t)=>{if(Bd.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(Rd(o),h())||(m(),l=setTimeout(b,Math.max(0,n.delayMs??0))))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:b,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{o=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}})(e,r);return{instance:n,element:n.element}},$d=new WeakMap;async function Wd(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout($d.get(e));try{await navigator.clipboard.writeText(r.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let t=null;t&&e.replaceChildren(t)}catch{e.setAttribute("aria-label","Copy failed — try again"),e.title="Copy failed — try again"}$d.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o,$d.delete(e)},1800))}let{setLoader:Hd,load:Dd,provide:Fd,getSync:Od}=_({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),zd=Hd,qd=Dd,jd=Od,{setLoader:_d,load:Ud}=_({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),Vd=_d,Kd=Ud;function Qd(e,t,r){return t?.trim()||(q(e,`artifact.${r}`)?`var(--persona-components-artifact-${r.split(".").join("-")})`:void 0)}function Jd(e){return!0===e?.features?.artifacts?.enabled}function Gd(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"),!Jd(t))return;let r=t.features?.artifacts?.layout,o=Qd(t,r?.paneBorder,"pane.border"),n=Qd(t,r?.paneBorderLeft,"pane.borderLeft");o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}let Yd=["panel","seamless","detached"];function Xd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Yd.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Zd(e){return!(!e||!Jd(e))&&"detached"===Xd(e)}function ec(e,t){if(!Jd(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.style.removeProperty("--persona-artifact-doc-toggle-active-color")}(e),void Gd(e,t);let r=t.features?.artifacts?.layout,o="detached"===Xd(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??o),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 n=Qd(t,r?.paneBackground,"pane.background");n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let a=Qd(t,r?.panePadding,"pane.padding");a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[Qd(t,r?.documentToolbarIconColor,"toolbar.iconColor"),"--persona-artifact-doc-toolbar-icon-color"],[Qd(t,r?.documentToolbarToggleActiveBackground,"toolbar.toggleActiveBackground"),"--persona-artifact-doc-toggle-active-bg"],[Qd(t,r?.documentToolbarToggleActiveBorderColor,"toolbar.toggleActiveBorderColor"),"--persona-artifact-doc-toggle-active-border"],[Qd(t,r?.documentToolbarToggleActiveColor,"toolbar.toggleActiveColor"),"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let o=t?.trim();o?e.style.setProperty(r,o):e.style.removeProperty(r)}Gd(e,t)}function tc(e,t){for(let t of Yd)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"),!Jd(t))return;let r=t.features?.artifacts?.layout,o=Xd(t);e.classList.add(`persona-artifact-appearance-${o}`);let n=Qd(t,r?.paneBorderRadius,"pane.borderRadius");n&&e.style.setProperty("--persona-artifact-pane-radius",n);let a=Qd(t,r?.paneShadow,"pane.shadow");a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=Qd(t,r?.chatShadow,"chat.shadow");s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}let rc=["__proto__","prototype","constructor"],oc=["collapsed","card","panel","inline"],nc=["markdown","component"],ac=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,sc=e=>"object"==typeof e&&!!e&&!Array.isArray(e),ic=e=>!rc.includes(e),lc=e=>oc.includes(e),dc=e=>Object.keys(e).length>0;function cc(e,t,r,o){e.push({path:t,code:r,message:o})}let pc="Ignored an unsupported value.",uc={kind:"mode"},hc={kind:"string",message:"Expected a CSS length string."},mc={kind:"boolean"},gc=(...e)=>({kind:"value",accepts:t=>e.includes(t)}),fc={paneWidth:hc,paneMaxWidth:hc,paneMinWidth:hc,expandedPanelWidth:hc,resizableMinWidth:hc,resizableMaxWidth:hc,expandLauncherPanelWhenOpen:mc,resizable:mc},bc={kind:"object",message:"Expected a preference object.",children:{showToolCalls:mc,showReasoning:mc,toolCallDisplay:{kind:"object",children:{layout:gc("row","card"),collapsedMode:gc("tool-call","tool-name","tool-preview"),groupedMode:gc("stack","summary","collapsible"),groupAppearance:gc("plain","inset"),groupSummary:gc("current-action","aggregate"),groupBoundary:gc("adjacent","iteration"),groupSummaryMaxItems:{kind:"value",accepts:e=>Number.isInteger(e)&&e>=0},loadingAnimation:gc("none","pulse","shimmer","shimmer-color","rainbow"),expandable:mc,grouped:mc}},reasoningDisplay:{kind:"object",children:{layout:gc("row","card"),appearance:gc("plain","inset","panel"),expandable:mc,activePreview:mc}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:uc,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:uc,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:nc,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:nc}}},filePreview:{kind:"object",children:{enabled:mc}},layout:{kind:"object",children:fc}}}}};function yc(e,t,r,o){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:cc(o,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:cc(o,r,"invalid_type",t.message);case"value":return t.accepts(e)?e:cc(o,r,"invalid_value",pc);case"mode":return lc(e)?Sn(e):cc(o,r,"invalid_value",pc);case"modeMap":{if(!sc(e))return cc(o,r,"invalid_type","Expected an object.");let n="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=n?t:kn(t);ic(t)&&(n?n.includes(t):ac.test(e))?lc(s)?a[e]=Sn(s):cc(o,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):cc(o,`${r}.${t}`,n?"unknown_key":"invalid_value",n?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return dc(a)?a:void 0}case"object":{if(t.bareMode&&lc(e))return Sn(e);if(!sc(e))return cc(o,r,"invalid_type",t.message??"Expected an object.");let n=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))ic(t)&&n.includes(t)||cc(o,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of n){let n=t.children[r],i=yc(e[r],n,a(r),o);if(n.deprecated&&void 0!==e[r]&&cc(o,a(r),"deprecated_key",n.deprecated),void 0===i)continue;let l=n.alias??r,d=s[l];s[l]=sc(d)&&sc(i)?{...d,...i}:i}return dc(s)?s:void 0}}}function vc(e){let t=[];return{preferences:(null===e?void 0:yc(e,bc,"",t))??{},issues:t}}function wc(e){if(Array.isArray(e))return e.map(wc);if(!sc(e))return e;let t={};for(let[r,o]of Object.entries(e))ic(r)&&void 0!==o&&(t[r]=wc(o));return t}function xc(e,t){let r=wc(e);for(let[e,o]of Object.entries(t)){if(!ic(e)||void 0===o)continue;let t=r[e];r[e]=sc(t)&&sc(o)?xc(t,o):wc(o)}return r}function Cc(e,t){if(void 0===t)return wc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return wc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},o=t.default??r.default,n={...r.byMediaType,...t.byMediaType},a={...o?{default:o}:{},...dc(n)?{byMediaType:n}:{}};return dc(a)?a:void 0}(r.files,t.files),s={...o?{default:o}:{},...dc(n)?{byKind:n}:{},...void 0===a?{}:{files:a}};return dc(s)?s:void 0}function Sc(e={},t){let r=function(e){let t,r={};for(let o of e){let e=vc(o).preferences;t=Cc(t,e.artifacts?.display),r=xc(r,e)}let o=r;return o.artifacts&&(void 0===t?delete o.artifacts.display:o.artifacts.display=t),o}(t),o={...e};for(let e of["showToolCalls","showReasoning"])void 0!==r[e]&&(o[e]=r[e]);for(let t of["toolCallDisplay","reasoningDisplay"])r[t]&&Object.assign(o,{[t]:{...e[t],...r[t]}});if(r.artifacts){let t=e.artifacts??{},n={...t};if(void 0!==r.artifacts.display){let e=Cc(t.display,r.artifacts.display);void 0!==e&&(n.display=e)}for(let e of["filePreview","layout"])r.artifacts[e]&&(n[e]={...t[e],...r.artifacts[e]});o.artifacts=n}return o}function kc(e){let t=e.preferences;return t&&dc(t)?{...e,features:Sc(e.features??{},[t])}:e}let{setLoader:Ac,load:Mc,provide:Ic,getSync:Tc}=_({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),Ec=Ac,Lc=Mc,Bc=Tc,Rc=new class{#e=new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.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.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Pc=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Nc=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),$c=(e,t,r)=>{if(!Pc(e)||!Pc(t)||Nc.has(r))return t;let o={...e};for(let n of Object.keys(t)){if(void 0===t[n]){delete o[n];continue}let a=r?`${r}.${n}`:n;o[n]=$c(e[n],t[n],a)}return o};function Wc(e,t){let r=f(cs),o=x(e,t,r),n=v(C($c(e,t,""),r,o),o);return D(n,((e,t)=>{if(t[$])return H(t);let r=new Set(H(e));for(let e of N){let o=b(t,e);"clear"===o&&r.delete(e),"explicit"===o&&r.add(e)}return[...r]})(e,t)),os(gs(n),((e,t)=>{let r=t[Za];if(r)return{...r};let o=rs(e);return es(t,"launcherWidth")&&(o.legacyLauncherWidth=void 0!==t.launcherWidth),es(t,"launcher")&&void 0===t.launcher?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(es(t.launcher,"width")&&(o.launcherWidth=void 0!==t.launcher?.width),es(t.launcher,"sidebarWidth")&&(o.sidebarWidth=void 0!==t.launcher?.sidebarWidth),es(t.launcher,"dock")&&void 0===t.launcher?.dock?o.dockWidth=!1:es(t.launcher?.dock,"width")&&(o.dockWidth=void 0!==t.launcher?.dock?.width),o)})(e,t))}let{setLoader:Hc,load:Dc,provide:Fc,getSync:Oc}=_({fallbackImport:()=>import("@runtypelabs/persona/config-diagnostics")}),zc=Hc,qc=Dc,jc=Oc,_c=[...R,"launcherWidth","suggestionChips","copy.welcomeTitle","copy.welcomeSubtitle","copy.showWelcomeCard","features.suggestReplies.enabled","features.suggestReplies.expose"],Uc=e=>{if(!e.debug)return;let t=jc();if(t)for(let r of e.current)r in t.LEGACY_MIGRATIONS&&(e.warned.has(r)||(console.warn(`[persona] ${r} is a supported legacy alias. Prefer ${t.LEGACY_MIGRATIONS[r]}. Compatibility behavior remains supported; clear the old field with an own undefined update when migrating.`),e.warned.add(r)));else qc().then(()=>Uc(e),()=>{})},Vc=e=>{let t={warned:new Set,current:new Set(_c.filter(t=>O(e,t))),debug:!0===e?.debug};return Uc(t),t},Kc=(e,t)=>{if((e=>void 0!==e[$])(t))e.current=new Set(_c.filter(e=>O(t,e)));else for(let r of _c){let o=b(t,r);"clear"===o&&e.current.delete(r),"explicit"===o&&e.current.add(r)}Object.prototype.hasOwnProperty.call(t,"debug")&&(e.debug=!0===t.debug),Uc(e)},Qc=({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 o=0;for(let e=r;e<t.length;e+=1){let n=t[e];if("{"===n&&(o+=1),"}"===n&&(--o,0===o))return t.slice(r,e+1)}return null})(t);if(!r)return null;let o=JSON.parse(r);if(!o||"object"!=typeof o||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Jc=e=>"string"==typeof e?e:null==e?"":String(e),Gc={message:e=>{if("message"===e.type)return{handled:!0,displayText:Jc(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,o=Jc(r.element);if(o&&t.document?.querySelector){let e=t.document.querySelector(o);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Jc(r.text)}}},Yc=e=>Array.isArray(e)?e.map(e=>String(e)):[],Xc=e=>{let t=new Set(Yc(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let o="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!o&&"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 n=o?e.parsers.reduce((e,t)=>e||t?.({text:o,message:r.message})||null,null):null;if(!n)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:n,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let o=e.captureResubmitGuard?.(),s=t(n,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{(!o||o())&&e.emit("action:resubmit",a)}});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(Yc(e.getSessionMetadata().processedActionMessageIds))}}},Zc=e=>e.map(e=>({...e,streaming:!1})),ep=e=>e.map(e=>({...e,status:"complete"})),tp=e=>`${e??"persona-"}state`,rp=(e=tp())=>{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 o=t();if(o)try{let t={...r,messages:r.messages?Zc(r.messages):void 0,artifacts:r.artifacts?ep(r.artifacts):void 0};o.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)}}}},op=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:np,load:ap}=_({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),sp=np,ip=ap,{setLoader:lp,load:dp,provide:cp,getSync:pp}=_({fallbackImport:()=>import("@runtypelabs/persona/history-shell")}),up=lp,hp=dp,mp=pp;function gp(){return null}let fp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function bp(e,t,r){let{onSubmit:o,onDismiss:n,title:a=("csat"===t?"How satisfied are you?":"How likely are you to recommend us?"),subtitle:s=("csat"===t?"Please rate your experience":"On a scale of 0 to 10"),commentPlaceholder:i=("csat"===t?"Share your thoughts (optional)...":"What could we do better? (optional)..."),submitText:l="Submit",skipText:d="Skip",showComment:c=!0}=e,p=document.createElement("div");p.className=`persona-feedback-container persona-feedback-${t}`,p.setAttribute("role","dialog"),p.setAttribute("aria-label","csat"===t?"Customer satisfaction feedback":"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=a,m.appendChild(g);let f=document.createElement("p");f.className="persona-feedback-subtitle",f.textContent=s,m.appendChild(f),h.appendChild(m);let{element:b,attentionTarget:y}=r(e=>{u=e});h.appendChild(b);let v=null;if(c){let e=document.createElement("div");e.className="persona-feedback-comment-container",v=document.createElement("textarea"),v.className="persona-feedback-comment",v.placeholder=i,v.rows=3,v.setAttribute("aria-label","Additional comments"),e.appendChild(v),h.appendChild(e)}let w=document.createElement("div");w.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",()=>{n?.(),p.remove()});let C=document.createElement("button");return C.type="button",C.className="persona-feedback-btn persona-feedback-btn-submit",C.textContent=l,C.addEventListener("click",async()=>{if(null===u)y.classList.add("persona-feedback-shake"),setTimeout(()=>y.classList.remove("persona-feedback-shake"),500);else{C.disabled=!0,C.textContent="Submitting...";try{let e=v?.value.trim()||void 0;await o(u,e),p.remove()}catch(e){C.disabled=!1,C.textContent=l,console.error(`[${t.toUpperCase()} Feedback] Failed to submit:`,e)}}}),w.appendChild(x),w.appendChild(C),h.appendChild(w),p.appendChild(h),p}function yp(e){return bp(e,"csat",t=>{let{ratingLabels:r=fp}=e,o=document.createElement("div");o.className="persona-feedback-rating persona-feedback-rating-csat",o.setAttribute("role","radiogroup"),o.setAttribute("aria-label","Satisfaction rating from 1 to 5");let n=[];for(let e=1;e<=5;e++){let a=document.createElement("button");a.type="button",a.className="persona-feedback-rating-btn persona-feedback-star-btn",a.setAttribute("role","radio"),a.setAttribute("aria-checked","false"),a.setAttribute("aria-label",`${e} star${e>1?"s":""}: ${r[e-1]}`),a.title=r[e-1],a.dataset.rating=String(e),a.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 ',a.addEventListener("click",()=>{t(e),n.forEach((t,r)=>{let o=r<e;t.classList.toggle("selected",o),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),n.push(a),o.appendChild(a)}return{element:o,attentionTarget:o}})}function vp(e){return bp(e,"nps",t=>{let{lowLabel:r="Not likely",highLabel:o="Very likely"}=e,n=document.createElement("div");n.className="persona-feedback-rating persona-feedback-rating-nps",n.setAttribute("role","radiogroup"),n.setAttribute("aria-label","Likelihood rating from 0 to 10");let a=document.createElement("div");a.className="persona-feedback-labels";let s=document.createElement("span");s.className="persona-feedback-label-low",s.textContent=r;let i=document.createElement("span");i.className="persona-feedback-label-high",i.textContent=o,a.appendChild(s),a.appendChild(i);let l=document.createElement("div");l.className="persona-feedback-numbers";let d=[];for(let e=0;e<=10;e++){let r=document.createElement("button");r.type="button",r.className="persona-feedback-rating-btn persona-feedback-number-btn",r.setAttribute("role","radio"),r.setAttribute("aria-checked","false"),r.setAttribute("aria-label",`Rating ${e} out of 10`),r.textContent=String(e),r.dataset.rating=String(e),e<=6?r.classList.add("persona-feedback-detractor"):e<=8?r.classList.add("persona-feedback-passive"):r.classList.add("persona-feedback-promoter"),r.addEventListener("click",()=>{t(e),d.forEach((t,r)=>{t.classList.toggle("selected",r===e),t.setAttribute("aria-checked",r===e?"true":"false")})}),d.push(r),l.appendChild(r)}return n.appendChild(a),n.appendChild(l),{element:n,attentionTarget:l}})}let wp="persona-chat-history",xp="data-persona-composer-reason",Cp="data-persona-composer-notice",Sp={"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 kp(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let Ap=e=>e&&"object"==typeof e?{...e}:{},Mp=e=>e.filter(e=>!(e=>!0===e.localOnly||"assistant"===e.role&&"string"==typeof e.id&&e.id.startsWith("reconnect-failed-"))(e)).map(e=>({...e,streaming:!1})),Ip=(e,t,r)=>{let o=e?.markdown?Cr(e.markdown):null,n=Rr(e?.sanitize);e?.postprocessMessage&&n&&void 0===e?.sanitize&&console.warn("[Persona] postprocessMessage HTML is sanitized: unsupported tags/attributes are stripped. Provide a custom sanitize function to allow them, or sanitize: false only for trusted HTML.");let a=!1,s=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!==at();if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:s,raw:i??a.text??""});l=n?n(t):t}else if(o){let e=wr(s,a.streaming),t=o(e);l=n&&d?n(t):t}else l=Ar(s);return l};return e=>{try{return s(e)}catch(t){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",t)),Ar(e.text??"")}}};function Tp(e){let t=st("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=Ee(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=st("span","persona-drop-overlay-label");r.textContent=e.label,t.appendChild(r)}return t}let Ep=(e,t)=>{let r={...e};for(let[e,o]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...o}:o}return r},Lp=(e,t,r)=>{if(null==e)throw 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);let n=e.getAttribute("data-persona-instance")||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;e.setAttribute("data-persona-instance",n),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let s,i,l=gs(t),u=(e=>{let t,r=0,o=!1,n=Promise.resolve(),a=()=>{},s=!0===e.inert,i=()=>{t?.remove(),t=void 0,e.removeAttribute("data-persona-preparing"),e.inert=s};return{get ready(){return n},prepare(s,l,d=!1){let c=++r;if(a(),!s.length){if(l(),c!==r)return;return i(),void(n=Promise.resolve())}!d&&!t&&(t=e.ownerDocument.createElement("style"),t.textContent="[data-persona-preparing],[data-persona-preparing] *{visibility:hidden!important}",e.append(t)),d||(e.setAttribute("data-persona-preparing",""),e.inert=!0);let p=new Promise((e,t)=>{a=()=>t(Error("Widget destroyed before ready"))});n=Promise.race([Promise.all(s),p]).then(()=>{if(o)throw Error("Widget destroyed before ready");if(c!==r||(l(),c!==r))return n;i()},e=>{if(!o&&c!==r)return n;throw e}),n.catch(()=>{})},destroy(){o=!0,++r,a(),i()}}})(e),h=r?.diagnostics??Vc(t),m=null,g=()=>{let t=je();if(s??=t?.createLoadingLabelLifecycle(e,()=>l),m)return m;let r=Y();return r&&t?(r.initActivityUi(Ee,t,j),i=r.createActivityLifecycle(e,()=>l,f,b,Ls,yd),m=r):null},f=new Set,b=new Set,y=new Map,v=new Map,w=new Map,x=new Set,C=e=>{if("user"===e.role&&Ol(l))return e.voiceProcessing&&x.add(e.id),{state:e.voiceProcessing?"live":x.has(e.id)?"settling":v.get(e.id)?w.get(e.id)?"expanded":"collapsed":"fit",maxHeight:zl(l),...ql(l)}},S=()=>{za({delayMs:l.tooltip?.delayMs??400,skipDelayMs:l.tooltip?.skipDelayMs??300})};S();let A=l.features;l=kc(l);let M,I,T=Rc.getForInstance(l.plugins),E=Mi(e),L=[],B=!1,R=(e=>{let t=new Map,r=!1,o=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return n=>{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(),n,t);return{get:e=>{let n=a(e),s=o();if(s)try{return s.getItem(n)}catch{r=!0}return t.get(n)??null},set:(e,n)=>{let s=a(e),i=o();if(i)try{return void i.setItem(s,n)}catch{r=!0}t.set(s,n)},remove:e=>{let n=a(e);t.delete(n);let s=o();if(s)try{s.removeItem(n)}catch{r=!0}}}}})(()=>l),P=null,N=null,$=null,W=!1,H=null,D=(e,t)=>{P=e,e.initApprovalUi({webMcpToolTitle:rr,popover:t,icons:{render:Ee,node:ne}});let r=e.createBuiltInApprovalPlugin(y);N=r.plugin,$=r.teardown},F=()=>{if(P)return P;let e=jd(),t=We();return e&&t?(D(e,t),e):(Promise.all([qd(),$e()]).then(([e,t])=>{W||P||(D(e,t),H?.())}).catch(()=>{}),null)},O=!1,z=!1,q=null,_=(e,t,r,o)=>{if(!e.querySelector("[data-tv-form]"))return;let n=Bc();n?n.enhanceWithForms(e,t,r,o):Lc().then(()=>{O||z||!q||(z=!0,q())}).catch(()=>{})},U=((e={instanceId:""})=>{let t=!1,r=new Map,o=(e,t)=>{r.get(e)?.delete(t)};return{on:(e,n)=>t?()=>{}:(r.has(e)||r.set(e,new Set),r.get(e).add(n),()=>o(e,n)),off:o,emit:(t,o)=>{r.get(t)?.forEach(t=>{try{t(o,e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})},dispose:()=>{t=!0,r.clear()}}})(Object.freeze({instanceId:n})),V=!1===l.persistState?null:l.storageAdapter??rp(tp("object"==typeof l.persistState?l.persistState.keyPrefix:void 0)),K=!!l.clientToken&&"function"!=typeof l.reconnectStream,Q={},J=null,G=new Promise(e=>{M=e}),X=()=>{},Z=new Promise(e=>{X=e}),ee=!1,te=e=>{if(l.onStateLoaded)try{let t=l.onStateLoaded(e);if(t&&"object"==typeof t&&"state"in t){let{state:e,open:r}=t;return r&&(ee=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(V?.load)try{let e=V.load();if(e&&"function"==typeof e.then)J=e.then(e=>te(e??{messages:[],metadata:{}}));else{let t=te(e??{messages:[],metadata:{}});t.metadata&&(Q=Ap(t.metadata)),t.messages?.length&&(l={...l,initialMessages:t.messages}),t.artifacts?.length&&(l={...l,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),I=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(l.onStateLoaded)try{let e=te({messages:[],metadata:{}});e.messages?.length&&(l={...l,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}J||M();let re=()=>Q,oe=e=>{Q=e({...Q})??{},Gi()},ae=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Qc],se=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[Gc.message,Gc.messageAndClick],ie=Xc({parsers:ae,handlers:se,getSessionMetadata:re,updateSessionMetadata:oe,emit:U.emit,captureResubmitGuard:()=>{let e=xe;return()=>Se(e)},documentRef:typeof document<"u"?document:null});ie.syncFromMetadata();let le=l.launcher?.enabled??!0,ce=l.launcher?.autoExpand??!1,ue=l.autoFocusInput??!1,me=ce,ge=le,fe=l.layout?.header?.layout,be=!1,ye=()=>ll(l),ve=()=>le||ye(),we=!ye()&&(!le||ce),xe=0,Ce=!1,Se=e=>!Ce&&!$i&&e===xe,ke=()=>{xe++,Me=!1,null!==Ie&&clearTimeout(Ie),Ie=null},Ae=()=>{let e=xe;Se(e)&&setTimeout(()=>{Se(e)&&!ls.isStreaming()&&ls.continueConversation()},100)},Me=!1,Ie=null,Te=()=>{Se(xe)&&(Me=!0,Ie&&clearTimeout(Ie),Ie=setTimeout(()=>{Me&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4))},Le=Ip(l,ie,Te),Be=l.features?.showReasoning??!0,Re=l.features?.showToolCalls??!0,Pe=l.features?.showEventStreamToggle??!1,Ne=l.features?.scrollBehavior??{},He=()=>("object"==typeof l.persistState?l.persistState?.keyPrefix:void 0)??"persona-",De=`${He()}event-stream`,Fe=null,Oe=l.features?.eventStream?.maxEvents??2e3,ze=null,qe=null,_e=null,Ue=!1,Ve=null,Ke=!1,Qe=null,Ye=0,Xe=(e,t)=>{ze?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Ze=(e,t)=>{qe?.processEvent(e,t),ze?Xe(e,t):_e&&(_e.length>=Oe&&_e.shift(),_e.push({type:e,payload:t}))},et=()=>{!ze&&Pe&&(_e??=[],Kd().then(e=>{if(Ue||ze||!Pe)return;Fe=new e.EventStreamStore(De),ze=new e.EventStreamBuffer(Oe,Fe),qe??=new e.ThroughputTracker,Fe.open().then(()=>ze?.restore()).catch(e=>{l.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=_e??[];_e=null;for(let e of t)qe?.processEvent(e.type,e.payload),Xe(e.type,e.payload)}).catch(()=>{}))};Pe&&et();let tt=!1,rt=null,ot=()=>{},nt=()=>{},at=()=>{},it=()=>{},lt=()=>{},ct=e=>{U.emit("message:copy",e),ls?.isClientTokenMode()&&"operator"!==e.role&&ls.submitMessageFeedback(e.id,"copy").catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),l.messageActions?.onCopy?.(e)},pt=e=>{U.emit("message:feedback",e),ls?.isClientTokenMode()&&ls.submitMessageFeedback(e.messageId,e.type).catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),l.messageActions?.onFeedback?.(e)};l.statusIndicator;let ut=(e,t=l.statusIndicator??{})=>"idle"===e?t.idleText??dt.idle:"connecting"===e?t.connectingText??dt.connecting:"connected"===e?t.connectedText??dt.connected:"error"===e?t.errorText??dt.error:"paused"===e?t.pausedText??dt.paused:"resuming"===e?t.resumingText??dt.resuming:dt[e];function ht(e,t,r,o){if(!ye()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(ur(e,Rt,r),pr(e,r,o)),!e.hasAttribute(xp)&&!e.hasAttribute(Cp))if("idle"===o&&r.idleLink){e.textContent="";let o=document.createElement("a");o.href=r.idleLink,o.target="_blank",o.rel="noopener noreferrer",o.textContent=t,o.style.color="inherit",o.style.textDecoration="none",e.appendChild(o)}else e.textContent=t}let mt=Pd({config:l,showClose:ve()}),{wrapper:gt,panel:ft,pillRoot:vt}=mt.shell,wt=mt.panelElements,{container:xt,body:Ct,messagesWrapper:St,starterSuggestions:kt,transcriptSuggestions:At,suggestions:Mt,textarea:It,sendButton:Bt,composerForm:Rt,statusText:Pt,welcomeHost:Nt,welcomeIconHolder:$t,greetingHost:Dt,introKicker:Ft,introTitle:Ot,introSubtitle:zt,closeButton:Zt,iconHolder:er,headerTitle:tr,headerSubtitle:or,header:nr,footer:ar,actionsRow:sr}=wt,ir=wt.leftActions,lr=wt.rightActions,cr=wt.sendButtonWrapper,hr=wt.setSendButtonMode,mr=wt.micButton,gr=wt.micButtonWrapper,fr=wt.attachmentButton,br=wt.attachmentButtonWrapper,yr=wt.attachmentInput,vr=wt.attachmentPreviewsContainer;xt.classList.add("persona-relative"),Ct.classList.add("persona-relative");let wr=()=>Ne.mode??"anchor-top",xr=()=>"follow"===wr()||"anchor-top"===wr()&&ni,Cr=()=>Ne.anchorTopOffset??16,Sr=()=>!0===Ne.pauseOnInteraction,kr=()=>!1!==Ne.showActivityWhilePinned,Mr=()=>!0===Ne.announce,Ir=()=>Ne.scrollbar??"on-scroll",Tr=Xt(Ee,"transcript",Ct),Er=Tr.element;xt.appendChild(Er);let Lr=()=>Ct.parentElement??xt,Br=st("div","persona-panel-suggestions");Br.setAttribute("data-persona-panel-suggestions",""),Br.hidden=!0,xt.appendChild(Br);let Rr=st("div","persona-panel-suggestions-fade");Rr.setAttribute("aria-hidden","true"),Rr.hidden=!0,xt.appendChild(Rr);let Pr=st("div","persona-stream-anchor-spacer");Pr.setAttribute("aria-hidden","true"),Pr.setAttribute("data-persona-anchor-spacer",""),Pr.style.flexShrink="0",Pr.style.pointerEvents="none",Pr.style.height="0px",Pr.style.display="none",Ct.appendChild(Pr);let Nr=st("div","persona-sr-only");Nr.setAttribute("aria-live","polite"),Nr.setAttribute("aria-atomic","true"),Nr.setAttribute("role","status"),Nr.setAttribute("data-persona-live-region",""),Object.assign(Nr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),xt.appendChild(Nr);let $r=null,Hr=null,Dr=e=>{Mr()&&e&&(Hr=e,null===$r&&($r=setTimeout(()=>{$r=null,Hr&&Mr()&&(Nr.textContent=Hr),Hr=null},400)))},Fr=()=>{let t=e.ownerDocument.defaultView??window;return(l.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(l.launcher?.mobileBreakpoint??640)&&(le||il(l))||!0===l.launcher?.fullHeight&&!l.launcher.sidebarMode&&!il(l)},Or=()=>bd(l,Fr()),zr="empty",jr=0,_r=()=>jr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Ur=(e,t=Ct)=>{let r=0,o=e;for(;o&&o!==t;)r+=o.offsetTop,o=o.offsetParent;return r},Vr=()=>{let e="none"===ar.style.display,t=Lr();if(ye()){let r=e||!ar.offsetHeight?0:Math.max(0,t.getBoundingClientRect().bottom-ar.getBoundingClientRect().top),o=Br.hidden?0:Math.max(0,t.getBoundingClientRect().bottom-Br.getBoundingClientRect().top);return void(Er.style.bottom=`${Math.max(r,o)+16}px`)}let r=e?0:ar.offsetHeight;if(r>0&&"overlay"===fi(l,ye())){let e=1/0;for(let r of ar.querySelectorAll(":scope > *, [data-persona-composer-header] > *"))!r.hidden&&r.offsetHeight&&"hidden"!==getComputedStyle(r).visibility&&(e=Math.min(e,Ur(r,t)));e<1/0&&(r-=e-Ur(ar,t))}Er.style.bottom=`${r+(e?0:_r())+16}px`};Vr();let Kr=()=>{if(!ye())return;let e="none"===ar.style.display?0:ar.offsetHeight;e>0?gt.style.setProperty("--persona-measured-pill-area-height",`${e+8}px`):gt.style.removeProperty("--persona-measured-pill-area-height"),gt.style.setProperty("--persona-pill-bottom",l.launcher?.composerBar?.bottomOffset??"16px")},Qr=()=>{Eo||(ar.style.marginBottom=jr>0?`${jr}px`:"")},Jr=()=>{let t=fi(l,ye()),r=Or();e.setAttribute("data-persona-welcome-fullscreen",String(Fr())),e.setAttribute("data-persona-welcome-layout",r.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",l.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom");let o="none"===ar.style.display?0:ar.offsetHeight,n="center"===r.anchor&&"empty"===zr?bi(r.anchorComposerTop)??bi("44%"):null,a=null!==n&&"centered"===r.layout&&void 0===l.welcome?.anchor&&void 0===l.welcome?.anchorComposerTop,s=a?getComputedStyle(Ct):null,i=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,d=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,c=Math.max(0,(parseFloat(s?.paddingBottom??"")||0)-("overlay"===t?i+d:0)),p=a?Ct.getBoundingClientRect().top-xt.getBoundingClientRect().top:0,u=!a||Nt.hidden?0:(Nt.querySelector("[data-persona-welcome-plugin]")??Nt).offsetHeight,h=null===n||ye()?0:a?Math.max(0,Math.round((xt.clientHeight-p-u-c-o)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:xt.clientHeight,footerHeight:o,fraction:n});e.style.setProperty("--persona-composer-overlay-height",`${o}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),jr="block"===t?h:0,Qr(),Kr(),Vr(),Oa()};Tr.update(l,!1);let Gr=null,Yr=null,Xr=ea();Xr.subscribe(e=>{try{xt.dispatchEvent(new CustomEvent("persona:composer:state",{detail:{...e,instanceId:n},bubbles:!0,composed:!0}))}catch{}});let Zr=()=>{Xr.setText(It?.value??"")},eo=()=>{Xr.setMentionRefs(Yr?.getMentionRefs()??[])},to=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}),ro=()=>({allowedTypes:l.attachments?.allowedTypes,maxFileSize:l.attachments?.maxFileSize,maxFiles:l.attachments?.maxFiles,adapter:l.attachments?.adapter,onFileRejected:l.attachments?.onFileRejected,instanceId:n,widgetConfig:l,preview:l.attachments?.preview,renderAttachmentPreview:oo}),oo=e=>{for(let t of Rc.getForInstance(l.plugins))try{let r=t.renderAttachmentPreview?.(e);if(r)return r}catch(e){console.error(`[AgentWidget] plugin ${t.id} attachment preview failed:`,e)}return null},no=()=>{let e=p.fromConfig(l.attachments,t=>{Gr===e&&ao(t)});return e.updateConfig(ro()),e},ao=e=>{let t=Object.freeze(e.map(to));Xr.setAttachments(t);try{l.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}ic()};Xr.setSelectedModelId(l.composer?.selectedModelId);let so=()=>l.composer?.modes??[],io=()=>function(e,t,r=!1){return e?.length?e.filter(e=>!(function(e,t){return!!e&&"segmented"===t?.find(t=>t.id===e)?.presentation}(e.groupId,t)||function(e,t){return!!e&&"hidden"===t?.find(t=>t.id===e)?.chipVisibility}(e.groupId,t)||r&&"overflow"!==e.presentation&&"auto"!==t?.find(t=>t.id===e.groupId)?.chipVisibility)):[]}(so(),l.composer?.modeGroups,!!l.future?.v5Defaults);{let e=fa(l.composer?.defaultActiveModeIds??[],so());e.length&&Xr.setActiveModeIds(e)}function lo(e){if(Xr.getState().selectedModelId!==e){Xr.setSelectedModelId(e),uo?.repaint();try{l.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function co(e){Xr.setActiveModeIds(e),ho?.render(e,io()),uo?.repaint(),_o?.resolve(),Dc(),en()}function po(t){let r=e.getRootNode(),o=r instanceof ShadowRoot?r.activeElement:e.ownerDocument.activeElement,n=(e=>`core:mode:${e}`)(t),a=_o?.getOverflowMenu(),s=o&&(o.closest("[data-persona-composer-action]")?.getAttribute("data-persona-composer-action")===n||a?.trigger.contains(o));if(co(ga(Xr.getState().activeModeIds,t,so(),l.composer?.modeGroups)),s&&!o.isConnected){let t=Array.from(e.querySelectorAll("[data-persona-composer-action]")).find(e=>e.getAttribute("data-persona-composer-action")===n)?.querySelector("button")??_o?.getOverflowMenu()?.triggerButton;t?.isConnected&&t.focus()}}let uo=null,ho=null,mo=null;function go(e){Xr.setQuote(e),mo?.render(Xr.getState().quote),en(),al()}let fo=!1;function bo(){let e=l.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?l.clientToken?"interrupt":(!fo&&!0===l.debug&&(fo=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let vo=null;function xo(e){Xr.setPendingSubmission(e),vo?.render(Xr.getState().pendingSubmission),en()}let Co=null,So=T.find(e=>e.renderHeader);if(So?.renderHeader){let e=So.renderHeader({config:l,defaultRenderer:()=>{let e=Il({config:l,showClose:ve()});return Tl(xt,e,l),e.header},onClose:()=>rc(!1,"user")});e&&nr&&(nr.replaceWith(e),nr=e,mt.header.element=e)}let ko=()=>{Ve&&(Ct.style.display="none",ar.parentNode?.insertBefore(Ve.element,ar),Ve.update())},Ao=()=>{if(!ze)return void et();if(td.cancel(),Ke=!0,Ve?ko():Kd().then(e=>{!Ve&&Ke&&ze&&(Ve=e.createEventStreamView({scroll:{createScrollToLatest:Yt,createScrollToBottomControl:Xt},buffer:ze,getFullHistory:()=>ze.getAllFromStore(),onClose:()=>Mo(),config:l,plugins:T,getThroughput:()=>qe?.getMetric()??{status:"idle"},renderIconByName:Ee,getResponseActive:Sl,getConfig:()=>l,getViewVisible:()=>Ke}),ko())}).catch(()=>{Mo()}),Io){Io.style.boxShadow=`inset 0 0 0 1.5px ${kl.actionIconColor}`;let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Io.classList.add(e))}let e=()=>{if(!Ke)return;let t=Date.now();t-Ye>=200&&(Ve?.update(),Ye=t),Qe=requestAnimationFrame(e)};Ye=0,Qe=requestAnimationFrame(e),Ql(),U.emit("eventStream:opened",{timestamp:Date.now()})},Mo=()=>{if(Ke){if(Ke=!1,Ve&&(Ve.update(),Ve.element.remove()),Ct.style.display="",Io){Io.style.boxShadow="";let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Io.classList.remove(e))}null!==Qe&&(cancelAnimationFrame(Qe),Qe=null),Ql(),U.emit("eventStream:closed",{timestamp:Date.now()})}},Io=null;if(Pe){let e=l.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:"");Io=st("button",t),Io.style.width="28px",Io.style.height="28px",Io.style.color=kl.actionIconColor,Io.type="button",Io.setAttribute("aria-label","Event Stream"),Io.title="Event Stream";let r=ne(de,"18px","currentColor",1.5);r&&Io.appendChild(r);let o=wt.clearChatButtonWrapper,n=wt.closeButtonWrapper,a=o||n;a&&a.parentNode===nr?nr.insertBefore(Io,a):nr.appendChild(Io),Io.addEventListener("click",()=>{Ke?Mo():Ao()})}let To=e=>{let t=l.attachments;if(!t?.enabled)return;let r=e.querySelector("[data-persona-composer-attachment-previews]")??e.querySelector(".persona-attachment-previews");if(!r){r=st("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=st("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??yn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},Eo=!1,Lo=e=>{let t=T.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=l.composer,o=!!B&&ls.isStreaming();return t.renderComposer({config:l,defaultRenderer:e,requestRender:()=>$h(),storage:R(t.id),onSubmit:e=>{ls&&!ls.isStreaming()&&fu(e.trim(),{consumeDraft:!1})},streaming:o,disabled:o,openAttachmentPicker:()=>{nc()||yr?.click()},models:r?.models,selectedModelId:Xr.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>lo(e),onVoiceToggle:!0===l.voiceRecognition?.enabled?()=>{Co?.()}:void 0})},Bo=Lo(()=>$l({config:l}).footer);Bo&&(mt.replaceComposer(Bo),ar=mt.composer.footer,Eo=!0);let No=null;function $o(){let e=It;if(!e)return;let t=l.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");ka(e,t),r&&e.setAttribute("aria-label",r),Sa(e,{submitKey:l.composer?.submitKey,insertNewlineOnTouchEnter:l.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(e)}),wa(e,va(l.composer?.maxLines,ye()?5:3))}let Wo=e=>{No=oa(e,{debug:!0===l.debug}),No&&(e=>{Rt=e.form,It=e.input,cr=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(Bt=e.sendButton),e.micButton&&(mr=e.micButton,gr=e.micButton.parentElement),e.found.status&&(Pt=e.found.status),e.found.suggestions&&(Mt=e.found.suggestions),e.attachmentButton&&(fr=e.attachmentButton,br=e.attachmentButton.parentElement),yr=e.attachmentInput??null,vr=e.attachmentPreviews??null,e.found.actionsRow&&(sr=e.found.actionsRow),ir=e.found.actionsStart,lr=e.found.actionsEnd})(No),$o()};To(ar),Wo(ar),Zr();let Do=gi(l,ye());Do&&(St.style.maxWidth=Do,St.style.marginLeft="auto",St.style.marginRight="auto",St.style.width="100%",Dt.style.maxWidth=Do,Dt.style.marginLeft="auto",Dt.style.marginRight="auto",Dt.style.width="100%",kt.style.maxWidth=Do,At.style.maxWidth=Do,At.style.marginLeft="auto",At.style.marginRight="auto",At.style.width="100%");let Oo=()=>{let e=gi(l,ye());if(e&&!ye())for(let t of[Rt,Mt,vr,Pt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};Oo();let qo=()=>{l.attachments?.enabled&&yr&&vr&&(Gr?Gr.remountPreviews(vr):(Gr=no(),Gr.setPreviewsContainer(vr)),No?.addListener(yr,"change",e=>{let t=e.target;Gr?.handleFileSelect(t.files),t.value=""}),xt.querySelector(".persona-attachment-drop-overlay")||xt.appendChild(Tp(l.attachments.dropOverlay)))};qo();let jo=()=>{if(!l.contextMentions?.enabled||!It)return;let e=Ht();if(!e){let e=It;return void Wt().then(()=>{!Yr&&It===e&&e.isConnected&&(jo(),_o?.resolve())},()=>{})}let t=No?.header??null,r=t?ca(t):void 0;if(Yr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Ra,loadContextMentionsInline:Wa,renderLucideIcon:Ee,createMentionButton:Ms},config:l,textarea:It,anchor:Rt??It,getMessages:()=>ls.getMessages(),liveRegionHost:xt,chipRow:r}),Yr&&!r){let e=It;e.parentElement?.insertBefore(Yr.contextRow,e)}};jo();let _o=null,Uo={getState:()=>Xr.getState(),getValue:()=>It?.value??"",setValue:e=>{It&&(It.value=e,It.dispatchEvent(new Event("input",{bubbles:!0})),Zr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(No?.form??null)},openAttachmentPicker:()=>{nc()||yr?.click()},toggleVoice:()=>{Co?.()},requestRender:()=>_o?.resolve()},Vo=()=>{let e=[];return(Yr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),br&&e.push({id:"core:attachment",placement:"start",order:200,element:br}),gr&&e.push({id:"core:mic",placement:"end",order:800,element:gr}),cr&&e.push({id:"core:send",placement:"end",order:1e3,element:cr}),e},Ko=!1,Qo=()=>{if(Ko)return;let e=We();e&&(_o?.destroy(),_o=e.createComposerActionRenderer({deps:{renderLucideIcon:Ee,attachTooltip:Qa,hideTooltipFor:ja},getBindings:()=>No,collect:()=>({builtIns:Vo(),configActions:[...(uo??=We().createComposerCoreControls({getConfig:()=>l,getState:()=>Xr.getState(),getModes:so,getChipModes:io,hasComposerPlugin:()=>T.some(e=>e.renderComposer),renderIcon:Ee,onModelChange:lo,onModeChange:po}),uo.collect()),...l.composer?.actions??[]],plugins:T,contributionContext:{config:l,getState:()=>Xr.getState(),requestRender:()=>_o?.resolve()},debug:!0===l.debug}),actionContext:Uo,getState:()=>Xr.getState(),getOverflow:()=>l.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),_o.resolve())};Qo();let Jo=()=>{if(ho?.destroy(),ho=null,!io().length)return;let e=No?.header;if(!e)return;let t=We();t&&(ho=t.createComposerModeChipRow({renderIcon:Ee,row:ca(e),onRemove:e=>po(e),initialIds:Xr.getState().activeModeIds}),ho.render(Xr.getState().activeModeIds,io()))};Jo();let Go=()=>{mo?.destroy(),mo=null,vo?.destroy(),vo=null;let e=No?.header;e&&(mo=pa({onDismiss:()=>go(void 0)}),e.appendChild(mo.element),mo.render(Xr.getState().quote),"defer-one"===bo()&&(vo=ua({onEdit:()=>function(){let e=Xr.getState().pendingSubmission;e&&(xo(void 0),It&&(It.value=e.text,It.dispatchEvent(new Event("input",{bubbles:!0})),Zr()),e.options.selectedModelId&&(Xr.setSelectedModelId(e.options.selectedModelId),uo?.repaint()),e.options.activeModeIds?.length&&co(e.options.activeModeIds),e.options.quote&&go(e.options.quote),It?.focus())}(),onRemove:()=>xo(void 0)}),e.appendChild(vo.element),vo.render(Xr.getState().pendingSubmission)))};Go();let Yo=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),Xo=la({getSurface:()=>ye()||!No?null:{form:No.form,input:No.input,start:No.actionsStart,end:No.actionsEnd,resizeInput:"single-row"===l.composer?.layout},onMeasure:()=>en()}),Zo=()=>{let e=No?.header?.querySelector(da);if(e)return e.childElementCount>0;let t=Xr.getState();return t.mentionRefs.length>0||fa(t.activeModeIds,io()).length>0};function en(){let e=Xr.getState(),t=Xo.measure(),r="single-row"!==l.composer?.layout&&"single-row"!==l.composer?.attachmentLayout||t,o=Xo.toolbarCrowded();ar.hasAttribute("data-persona-composer-crowded")!==o&&ar.toggleAttribute("data-persona-composer-crowded",o),ar.hasAttribute("data-persona-composer-fit")!==r&&ar.toggleAttribute("data-persona-composer-fit",r);let n=Yo.observe(r&&function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),o=Number.parseFloat(r.lineHeight),n=Number.parseFloat(r.fontSize),a=Number.isFinite(o)&&o>0?o:Number.isFinite(n)&&n>0?1.4*n:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0),i=e.style.height,l=e.style.getPropertyPriority("height"),d="TEXTAREA"===e.tagName;d&&(e.style.height="auto");let c=e.scrollHeight-s;return d&&e.style.setProperty("height",i,l),c>1.5*a}(It),e.text);ar.toggleAttribute("data-persona-has-attachments",e.attachments.length>0),ar.toggleAttribute("data-persona-attachment-row-compact",ba({text:e.text,wrapped:n,hasAttachments:!1,hasChips:Zo(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}));let a=ba({text:e.text,wrapped:n,hasAttachments:e.attachments.length>0,hasChips:Zo(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission});ar.hasAttribute("data-persona-composer-compact")!==a&&ar.toggleAttribute("data-persona-composer-compact",a);let s=!a||!r||"single-row"!==l.composer?.layout;ar.hasAttribute("data-persona-composer-expanded")!==s&&ar.toggleAttribute("data-persona-composer-expanded",s)}function tn(){"single-row"!==l.composer?.layout||ye()?ar.removeAttribute("data-persona-composer-layout"):ar.setAttribute("data-persona-composer-layout","single-row"),l.composer?.attachmentLayout?ar.setAttribute("data-persona-attachment-layout",l.composer.attachmentLayout):ar.removeAttribute("data-persona-attachment-layout"),en()}tn(),Xr.subscribe(()=>{_o?.sync(),ic(),lc(),en(),al()}),lc();let rn=!1,on=e=>{if(rn||!0!==l.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(rn=!0,console.warn(`[persona] Ignoring deprecated layout.slots.${t.join(" / layout.slots.")}. Use message render hooks or the renderComposer plugin hook.`))},nn=new Map,an=new Map,sn=e=>{let t=nn.get(e);if(t)return t.element;let r=null;if("body-top"===e&&(r=Ct.querySelector("[data-persona-intro-card]")),"messages"===e)return St;if("composer"===e)return Rt;if("footer-top"===e&&(r=Mt),"footer-bottom"===e&&(r=Pt),r?.parentNode){let t=document.createComment(`persona:${e}`);r.before(t),nn.set(e,{anchor:t,element:r})}return r},ln=function(e){let t=new Map,r=(t,r)=>({slot:t,signal:r.abort.signal,config:e.config(),defaultContent:()=>e.defaultContent(t)}),o=(r,o)=>{t.delete(r),o.abort.abort();try{o.result.destroy?.()}catch(e){console.error(`[AgentWidget] Error destroying slot "${r}":`,e)}e.remove(r,o.result.element)};return{update(){let n=e.config().layout?.slots??{};for(let[e,r]of t)n[e]!==r.renderer&&o(e,r);for(let[a,s]of Object.entries(n)){if(!s)continue;let n=t.get(a);try{if(n){if(n.result.update){let t=n.result.update(r(a,n));void 0!==t&&t!==n.result.element&&(e.remove(a,n.result.element),n.result.element=t)}}else{n={renderer:s,abort:new AbortController,result:{element:null}},t.set(a,n);let e=s(r(a,n));n.result=null===e||"nodeType"in e?{element:e}:e}n.result.element&&e.mount(a,n.result.element)}catch(e){n&&o(a,n),console.error(`[AgentWidget] Error rendering slot "${a}":`,e)}}},remount(){for(let[r,o]of t)o.result.element&&e.mount(r,o.result.element)},detach(r){for(let o of r){let r=t.get(o);r&&e.remove(o,r.result.element)}},destroy(){for(let[e,r]of t)o(e,r)}}}({config:()=>l,defaultContent:sn,remove(e,t){if("messages"===e||"composer"===e)return;t?.remove(),an.get(e)?.remove(),an.delete(e);let r=nn.get(e);r&&(r.anchor.replaceWith(r.element),nn.delete(e))},mount(e,t){if(!("messages"===e||"composer"===e||t.parentNode&>.contains(t))){if("body-top"===e||"footer-top"===e||"footer-bottom"===e){let r=sn(e),o=nn.get(e);if(r&&o?.anchor.parentNode)return o.anchor.after(t),void(r!==t&&!t.contains(r)&&r.remove())}switch(e){case"header-left":nr.prepend(t);break;case"header-right":nr.append(t);break;case"header-center":{let e=nr.querySelector(".persona-flex-col");e?e.after(t):nr.append(t);break}case"body-top":Ct.prepend(t);break;case"body-bottom":Ct.append(t);break;case"footer-top":ar.prepend(t);break;case"footer-bottom":ar.append(t);break;case"transcript-top":{let r=document.createElement("div");r.setAttribute("data-persona-layout-slot",e),r.style.cssText="width:100%;min-width:0;max-width:var(--persona-content-max-width, 100%);margin-inline:auto;flex-shrink:0",r.append(t),St.before(r),an.set(e,r);break}case"composer-start":case"composer-end":case"composer-before-send":{let r="composer-start"===e?ir:"composer-end"===e?lr:cr?.parentElement;if(!r)break;let o=document.createElement("div");o.setAttribute("data-persona-layout-slot",e),o.style.cssText="display:flex;align-items:center;min-width:0;max-width:100%",o.append(t),"composer-start"===e?r.prepend(o):"composer-before-send"===e?cr?.before(o):r.append(o),an.set(e,o);break}}}}});on(l.layout?.slots??{}),ln.update();let dn=t=>{if(!l.onLinkClick||t.defaultPrevented||0!==t.button||t.ctrlKey||t.metaKey||t.shiftKey||t.altKey)return;let r=t.target;if(!(r instanceof Element))return;let o=r.closest("a[href]");if(!o||!e.contains(o)||o.hasAttribute("download")||o.closest("[data-persona-root]")!==e)return;let n=o.getAttribute("target")??o.ownerDocument.querySelector("base[target]")?.getAttribute("target");if((!n||"_self"===n.toLowerCase())&&/^(https?:|mailto:|tel:)/i.test(o.href))try{l.onLinkClick({url:o.href,anchor:o,originalEvent:t,preventDefault:()=>t.preventDefault()})}catch(e){console.error("[AgentWidget] onLinkClick failed:",e)}};e.addEventListener("click",dn),St.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(),Wd(r))}),St.addEventListener("click",e=>{let t=e.target;t instanceof Element&&t.closest('.persona-approval-head[data-action="toggle-params"]')&&(ci(),Jl())},{capture:!0});let cn=(e,t)=>{let r=e.querySelector(`[${Dl}]`),o=e.getAttribute("data-message-id");r&&o&&(ci(),Jl(),w.set(o,t),Cd(e,r,o,{state:t?"expanded":"collapsed",maxHeight:zl(l),...ql(l)},"toggle"))};St.addEventListener("click",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest(`button[${Fl}]`),o=r?.closest("[data-message-id]");r&&o&&(e.preventDefault(),cn(o,"true"!==r.getAttribute("aria-expanded")))}),St.addEventListener("focusin",e=>{let t=e.target;if(!(t instanceof Element))return;let r=t.closest(`[${Dl}="collapsed"]`)?.closest("[data-message-id]");r&&cn(r,!0)});let pn=e=>{let t=e.target.closest('button[data-expand-header="true"]');t&&un(t)},un=e=>{let t=e.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!t)return;let r=t.getAttribute("data-message-id");if(!r)return;ci(),Jl();let o=Zs;o&&vl();let n=o&&m?.holdScroll(t,Ct,o,gd,ud,hi,()=>Zs===o),a=e.getAttribute("data-bubble-type");if(t.classList.contains("persona-activity-row")){i?.manual(r);let e=t.parentElement?.closest("[data-persona-tool-group]");e?.dataset.messageId&&i?.manual(e.dataset.messageId)}if("reasoning"===a||"tool"===a){let e="reasoning"===a,o=e?b:f;o.has(r)?o.delete(r):o.add(r),m&&(e?m.updateReasoningBubbleUI:m.updateToolBubbleUI)(r,t,o,l)}else if("approval"===a&&P){let e="expanded"===((!1===l.approval?void 0:l.approval)?.detailsDisplay??"collapsed"),o=y.get(r)??e;y.set(r,!o),P.updateApprovalDetailsUI(r,t,l,y)}n?.(),Ls.delete(r)};St.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),pn(e))}),St.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&pn(e)}),St.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),pn(e))}),St.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=St.getRootNode(),o="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!o||o.isCollapsed)return;let n=o.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(n);a&&a!==n&&(t.setData("text/plain",a),e.preventDefault())});let hn,mn=new Map,gn=new Map,bn=0,vn=()=>{St.querySelectorAll(".persona-tool-bubble[data-tool-call-id]").forEach(e=>{e.toggleAttribute("data-persona-revealed",gn.has(e.dataset.messageId))})},wn=()=>{window.clearTimeout(hn),hn=void 0,gn.forEach(e=>window.clearTimeout(e)),gn.clear(),vn()},xn=null,Cn="idle",Sn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},kn=()=>{St.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:o}=Sn[t];e.setAttribute("aria-label",o),e.title=o,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 n=Ee(r,14,"currentColor",2);n&&(e.innerHTML="",e.appendChild(n))})(e,t&&t===xn?Cn:"idle")})};St.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 n=t.getAttribute("data-action");if("copy"===n){let e=ls.getMessages().find(e=>e.id===o);if(e&&ct){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=ne(pe,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=ne(he,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),ct(e)}}else if("read-aloud"===n)ls.toggleReadAloud(o);else if("upvote"===n||"downvote"===n){let e="upvote"===n?"thumbs-up":"thumbs-down";if((mn.get(o)??null)===n){mn.delete(o),t.classList.remove("persona-message-action-active");let r=Ee(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let a="upvote"===n?"downvote":"upvote",s=r.querySelector(`[data-action="${a}"]`);if(s){s.classList.remove("persona-message-action-active");let e=Ee("upvote"===a?"thumbs-up":"thumbs-down",14,"currentColor",2);e&&(s.innerHTML="",s.appendChild(e))}mn.set(o,n),t.classList.add("persona-message-action-active");let i=Ee(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=ls.getMessages().find(e=>e.id===o);l&&pt&&pt({type:n,messageId:l.id,message:l})}}else if("regenerate"===n)An?.regenerate(o);else if("edit"===n)An?.edit(o);else if("quote"===n)An?.quote(o);else if(n?.startsWith("custom:")){let e=n.slice(7),r=l.messageActions?.custom?.find(t=>t.id===e),a=ls.getMessages().find(e=>e.id===o);if(!r||!a)return;try{r.onSelect(a)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let An=null;St.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 o=r.getAttribute("data-message-id");if(!o)return;let n=t.getAttribute("data-approval-action");if(!n)return;let a="approve"===n?"approved":"denied",s=ls.getMessages().find(e=>e.id===o);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"}),dr(s.approval)?ls.resolveWebMcpApproval(o,a):ls.resolveApproval(s.approval,a)});let In=null,Tn=!1,Rn=null,Nn=()=>{},Hn="none",Dn=null,Fn={artifacts:[],selectedId:null},On=!1,zn=!1,qn=!1,jn=!1,_n=()=>jn||Fn.artifacts.some(e=>"panel"===Mn(l.features?.artifacts,e)),Un=()=>Fn.artifacts.length>0&&!On&&_n(),Vn={current:null},Kn=(e,t)=>{let r=ls.getArtifactById(t),o=r?.markdown,n=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!o){let t=(e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]"))?.getAttribute("data-message-id");if(t){let e=ls.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);o=t?.props?.markdown,n=t?.props?.title||n,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:o,title:n,file:a,artifactType:s}};St.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===l.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:r}))return;let{markdown:o,title:n,file:a}=Kn(t,r);if(!o)return;let s=Et();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:n,markdown:o,file:a}))}),St.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]"),n=o?null:t.closest("[data-open-artifact]"),a=o?o.getAttribute("data-artifact-inline"):n?.getAttribute("data-open-artifact")??null,s=(o?l.features?.artifacts?.inlineActions:l.features?.artifacts?.cardActions)?.find(e=>e.id===r);if(!s)return;let{markdown:i,title:d,file:c,artifactType:p}=Kn(t,a??""),u={artifactId:a,title:d,artifactType:p,markdown:i,file:c};try{Promise.resolve(s.onClick(u)).catch(()=>{})}catch{}}),St.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 o=ls.getArtifactById(r),n=Et();if(!n)return;let a="";if(o)a=n.artifactCopyText(o);else{let{markdown:e,file:o,artifactType:s}=Kn(t,r);"markdown"===s&&(a=n.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...o?{file:o}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=ne(pe,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=ne(he,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),St.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!==l.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:r})&&(On=!1,jn=!0,zn=!0,qn=!0,ls.selectArtifact(r),$a())}),St.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!==l.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:o})&&(e.preventDefault(),e.stopPropagation(),On=!1,jn=!0,ls.selectArtifact(o),$a())}),St.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 Qn=wt.composerOverlay,Jn=e=>{Wt().catch(()=>{}),Ro(e,l,Qn)},Gn=null,Yn={instanceId:n,mount:e,overlay:Qn,sessionRef:Vn,config:()=>l},Xn=!1,Zn=e=>t=>{let r=t.target,o=r?.closest?.("[data-persona-ask-sheet-for]");if(!o||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let n=r=>{Gn??=r.createAskUserSheetHandlers(Yn),Gn[e](t)},a=Ht();a?n(a):Xn||(Xn=!0,Wt().then(e=>{Xn=!1,o.isConnected&&n(e)},()=>{Xn=!1}))};Qn.addEventListener("click",Zn("click")),Qn.addEventListener("keydown",Zn("keydown"));let ta=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=Qn.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let o=Number(e.key),n=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[o-1];n&&(e.preventDefault(),n.click())};document.addEventListener("keydown",ta);let ra=null,sa=null,ia=()=>{},ya=!1,Ia="",Ea="",La=()=>{let e=fp?.railShell?fp.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360},Ba=()=>{},Pa=()=>{let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,o=l.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>o)&&(le||il(l))},Na=()=>!Jd(l)||!Un()||e.classList.contains("persona-artifact-narrow-host")||Pa()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":Zd(l)?"detached":"welded",$a=()=>{if(!In||!Jd(l))return;ec(e,l),tc(e,l),Ba();let t=l.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=ft.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let o=Un();In.setVisible(o),In.update(Fn),On?(In.setMobileOpen(!1),In.element.classList.add("persona-hidden"),In.backdrop?.classList.add("persona-hidden"),zn=!1,qn=!1):Fn.artifacts.length>0&&_n()?(In.element.classList.remove("persona-hidden"),In.setMobileOpen(!0)):(In.setMobileOpen(!1),In.element.classList.add("persona-hidden"),In.backdrop?.classList.add("persona-hidden"),zn=!1,qn=!1);let n=!0===l.features?.artifacts?.layout?.showExpandToggle;if(In.setExpandToggleVisible(n),In.setCopyButtonVisible(!0===l.features?.artifacts?.layout?.showCopyButton),In.setRefreshButtonVisible("function"==typeof l.features?.artifacts?.layout?.onDocumentToolbarRefresh),In.setCustomActions(l.features?.artifacts?.toolbarActions??[]),In.setStyleConfig(l),In.setTabFade(l.features?.artifacts?.layout?.tabFade),In.setRenderTabBar(l.features?.artifacts?.renderTabBar),!n&&!qn&&(zn=!1),zn!==ya){let e=In.element;zn?(Ia=e.style.width,Ea=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(Ia&&(e.style.width=Ia),Ea&&(e.style.maxWidth=Ea),Ia="",Ea=""),ya=zn}e.classList.toggle("persona-artifact-expanded",zn),In.setExpanded(zn);let a=Na();a!==Hn&&(Hn=a,Nn()),ia()};if(Jd(l)){ft.style.position="relative";let t=st("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),r=st("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");t.appendChild(xt),ra=r,r.appendChild(t),ft.appendChild(r);let o=t=>{Tn||In||(In=t.createArtifactPane(l,{onSelect:e=>Vn.current?.selectArtifact(e),onDismiss:()=>{On=!0,$a()},onToggleExpand:()=>{let e=!zn,t=Fn.selectedId??Fn.artifacts[Fn.artifacts.length-1]?.id??null;!0!==l.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(zn=e,e||(qn=!1),$a())}}),sa=t.createArtifactResizer({mount:e,splitRoot:r,pane:In,getConfig:()=>l,chatMinWidth:La,isVisible:Un}),In.element.classList.add("persona-hidden"),r.appendChild(In.element),In.backdrop&&ft.appendChild(In.backdrop),ia(),$a())},n=Et();n?o(n):(Lt(()=>{let e=Et();e&&o(e)}),Tt().catch(()=>{})),ia=()=>sa?.update(),Ba=()=>{if(!le||!In||l.launcher?.sidebarMode||il(l)&&"emerge"===dl(l).reveal)return;let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,o=l.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=o||!function(e,t){return!(!t||!Jd(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(l,le))return;let n=Sd(l).width,a=l.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Un()?(ft.style.width=a,ft.style.maxWidth=a):(ft.style.width=n,ft.style.maxWidth=n)},typeof ResizeObserver<"u"&&(Rn=new ResizeObserver(()=>{$a()}),Rn.observe(ft))}else ft.appendChild(xt);ye()&&vt&&(wt.peekBanner&&vt.appendChild(wt.peekBanner),vt.appendChild(ar)),e.appendChild(gt),vt&&e.appendChild(vt);let Ha=()=>{let t=Pa()||ye()&&"fullscreen"===l.launcher?.composerBar?.expandedSize||!0===l.launcher?.fullHeight&&!l.launcher?.sidebarMode&&!il(l);if(St.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",St.style.setProperty("--persona-transcript-gap",St.style.gap),ye()){ft.style.width="100%",ft.style.maxWidth="100%";let e=l.launcher?.composerBar??{},t="expanded"===gt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return xt.style.background="",xt.style.border="",xt.style.borderRadius="",xt.style.overflow="",void(xt.style.boxShadow="");let o=l.theme?.components?.panel,n=di(l),a=(e,t)=>null==e||""===e?t:Us(n,e)??e;return xt.style.background="var(--persona-surface, #ffffff)",xt.style.border=a(o?.border,"1px solid var(--persona-border)"),xt.style.borderRadius=a(o?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),xt.style.boxShadow=a(o?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(xt.style.overflow="hidden")}let r=il(l),o=l.launcher?.sidebarMode??!1,n=as(l)||r||o||(l.launcher?.fullHeight??!1),a=!1===l.launcher?.enabled,s=!0===l.launcher?.detachedPanel,i=l.theme?.components?.panel,d=l.darkTheme?.components?.panel,c="dark"===li(l)?k(i??{},d??{}):i,p=di(l),u=(e,t)=>null==e||""===e?t:Us(p,e)??e,h=e.ownerDocument.defaultView??window,m=l.launcher?.mobileFullscreen??!0,g=l.launcher?.mobileBreakpoint??640,f=h.innerWidth<=g,b=m&&f&&le,y=r&&m&&f,v=l.launcher?.position??"bottom-left",w="bottom-left"===v||"top-left"===v,x=l.launcher?.zIndex??1e5,C=(e,t,r)=>`var(--persona-components-panel-modes-${e}-${t}, ${r})`,S=c?.modes?.floating,A=u(S?.border??c?.border,C("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),M=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)))")),I=u(S?.borderRadius??c?.borderRadius,C("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),T=s&&!b&&!y,E=b||y?"mobile":T?"floating":r?"docked":o?"sidebar":a?"inline":"floating",L=c?.modes?.[E];T?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let B=T?A:o||b?"none":A,R=T?M:b?"none":o?w?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":a?"none":M;r&&!b&&!T&&(R="none",B="none");let P=T?I:o||b?"0":I,N=u(L?.border??c?.border,C(E,"border",B)),$=u(L?.shadow??c?.shadow,C(E,"shadow",R)),W=u(L?.borderRadius??c?.borderRadius,C(E,"borderRadius",P)),H=Na(),D="detached"===H,F="welded"===H;e.classList.toggle("persona-artifact-detached-split",D),e.classList.toggle("persona-artifact-welded-split",F);let O="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)))))",z="flush"==("flush"===l.features?.artifacts?.layout?.chatSurface?"flush":"card")&&Jd(l)&&Zd(l)&&a&&!r;e.classList.toggle("persona-artifact-chat-flush",z);let q=D||z?"none":$,j=D?A:F?"none":N,_=D?I:W;z&&(j="none",_="0");let U=null!=L?.borderRadius&&""!==L.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,V=z&&!U?"0":W,K=Ct.scrollTop;e.style.cssText="",gt.style.cssText="",ft.style.cssText="",xt.style.cssText="",Ct.style.cssText="",Eo||(ar.style.cssText="",!1===l.layout?.showFooter&&(ar.style.display="none")),Ke&&(Ct.style.display="none"),(n||a)&&(e.style.minWidth="0");let Q=()=>{K<=0||(Ct.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(Ct.scrollTop===K)return;let e=Ct.scrollHeight-Ct.clientHeight;e<=0||(Ct.scrollTop=Math.min(K,e))})};if(b)return gt.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"),gt.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 `,ft.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 ",xt.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 ",Ct.style.flex="1 1 0%",Ct.style.minHeight="0",Ct.style.overflowY="auto",ar.style.flexShrink="0",Qr(),be=!0,void Q();let J=Sd(l);if(o||r){if(r)if("emerge"!==dl(l).reveal||s)ft.style.width="100%",ft.style.maxWidth="100%";else{let e=dl(l).width;ft.style.width=e,ft.style.maxWidth=e}}else a?(gt.style.width=kd(l),ft.style.width="100%",ft.style.maxWidth="100%"):(ft.style.width=J.width,ft.style.maxWidth=J.maxWidth);if(Ba(),ft.style.boxShadow=q,ft.style.borderRadius=V,D?ft.style.border="none":F&&(ft.style.border=N),xt.style.border=j,xt.style.borderRadius=_,xt.style.boxShadow=D&&!z?O:"",z&&(xt.style.background="transparent",Ct.style.background="transparent",ar.style.background="transparent",ar.style.borderTop="none"),F){let e=l.features?.artifacts?.layout;Dn=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||Qd(l,void 0,"split.outerRadius")||Qd(l,void 0,"pane.borderRadius")||W}else Dn=null;let G=null!=L?.border||null!=c?.border;if(!r||b||T||D||F||G||(xt.style.border="none","right"===dl(l).side?xt.style.borderLeft="1px solid var(--persona-border)":xt.style.borderRight="1px solid var(--persona-border)"),r&&!b&&F&&!G&&("right"===dl(l).side?ft.style.borderLeft="1px solid var(--persona-border)":ft.style.borderRight="1px solid var(--persona-border)"),n&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",as(l)&&(e.style.flex="1 1 0%"),a&&(e.style.width="100%"),gt.style.display="flex",gt.style.flexDirection="column",gt.style.flex="1 1 0%",gt.style.minHeight="0",gt.style.maxHeight="100%",gt.style.height="100%",a&&(gt.style.overflow="hidden"),ft.style.display="flex",ft.style.flexDirection="column",ft.style.flex="1 1 0%",ft.style.minHeight="0",ft.style.maxHeight="100%",ft.style.height="100%",D||(ft.style.overflow="hidden"),xt.style.display="flex",xt.style.flexDirection="column",xt.style.flex="1 1 0%",xt.style.minHeight="0",xt.style.maxHeight="100%",xt.style.overflow="hidden",Ct.style.flex="1 1 0%",Ct.style.minHeight="0",Ct.style.overflowY="auto",ar.style.flexShrink="0"),a&&(T||D||z)&&!r&&(z||(gt.style.padding="var(--persona-panel-inset)"),gt.style.background="var(--persona-panel-canvas-bg)"),gt.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||a||r||(fl[v]??fl["bottom-right"]).split(" ").forEach(e=>gt.classList.add(e)),o){let e=rs(l).sidebarWidth?l.launcher?.sidebarWidth??"420px":Us(di(l),"components.panel.width")??"420px";gt.style.cssText=s?`\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 `,ft.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: ${q} !important;\n border-radius: ${V} !important;\n ${D?"border: none !important;":F?`border: ${N} !important;`:""}\n `,ft.style.setProperty("width","100%","important"),ft.style.setProperty("max-width","100%","important"),xt.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: ${_} !important;\n border: ${j} !important;\n ${D&&!z?`box-shadow: ${O} !important;`:""}\n ${z?"background: transparent !important;":""}\n `,Eo||(ar.style.cssText=`\n flex-shrink: 0 !important;\n border-top: none !important;\n padding: 8px 16px 12px 16px !important;\n ${z?"background: transparent !important;":""}\n ${!1===l.layout?.showFooter?"display: none !important;":""}\n `)}if(!a&&!r){let e=o?"":"padding-top: 1.25em !important;",t=o?"":`z-index: ${l.launcher?.zIndex??1e5} !important;`;gt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}Qr(),Q()},Da=()=>{e.style.setProperty("--persona-content-max-width",gi(l,ye()))},Fa=!1;function Oa(){l.layout?.topFade&&Ct.scrollTop>1?Ct.setAttribute("data-persona-top-fade","true"):Ct.removeAttribute("data-persona-top-fade"),Rr.hidden=!ye()||Br.hidden||Ct.scrollHeight-Ct.clientHeight-Ct.scrollTop<=1,Rr.hidden||(Rr.style.bottom=xt.getBoundingClientRect().bottom-Br.getBoundingClientRect().top-xt.clientTop+"px")}let qa=()=>{Oa();let t=fi(l,ye());ye()&&l.composer?.placement&&!0===l.debug&&!Fa&&(Fa=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=Or();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",zr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),Jr()},_a=()=>{if(ye())return;let t=il(l),r=l.launcher?.sidebarMode??!1;if(as(l)||t||r||l.launcher?.fullHeight||!le)return;let o=e.ownerDocument.defaultView??window,n=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640;if(n&&o.innerWidth<=a)return;let s=Sd(l);ft.style.height=s.height,ft.style.maxHeight=s.maxHeight};Ha(),ui(e,l),ec(e,l),tc(e,l),Da(),qa(),Nn=()=>{Ha(),_a(),ui(e,l),ec(e,l),tc(e,l),Da(),qa(),Dn?e.style.setProperty("--persona-artifact-welded-outer-radius",Dn):e.style.removeProperty("--persona-artifact-welded-outer-radius"),nt(),ot()};let Ua=[];Ua.push(()=>Xo.destroy()),Ua.push(()=>{Tn=!0}),Ua.push(()=>{L.forEach(e=>e()),E.destroy()}),Ua.push(()=>{document.removeEventListener("keydown",ta)}),Ua.push(()=>{null!==$r&&clearTimeout($r)});let Va=null,Ka=null;Ua.push(()=>{Va?.(),Va=null,Ka?.(),Ka=null}),Rn&&Ua.push(()=>{Rn?.disconnect(),Rn=null}),Ua.push(()=>{sa?.destroy(),sa=null,In?.element.style.removeProperty("width"),In?.element.style.removeProperty("maxWidth"),In?.destroy()}),Pe&&Ua.push(()=>{Ue=!0,_e=null,null!==Qe&&(cancelAnimationFrame(Qe),Qe=null),Ve?.destroy(),Ve=null,ze?.destroy(),ze=null,Fe=null});let Ja=null,Ga=()=>{if(Ja&&=(Ja(),null),"auto"===l.colorScheme){let e=li(l);Ja=mi(t=>{t!==e&&(e=t,Nn(),$a(),ls&&(Vs++,$d(St,ls.getMessages(),Le)))})}};Ga(),Ua.push(()=>{Ja&&=(Ja(),null)}),Ua.push(()=>{W=!0,$?.()}),Ua.push(()=>{O=!0});let Ya=!1;Ua.push(()=>{Ya=!0});let Xa=(t,r)=>{let o=Di(t,r);return o||!Wi.includes(t)?o:(rl().then(o=>{if(Ya)return;Hi(o.wipe),Hi(o.glyphCycle);let n=Di(t,r);n&&Xi(n,e)}).catch(()=>{}),null)},Za=l.features?.streamAnimation;if(Za?.type&&"none"!==Za.type){let t=Xa(Za.type,Za.plugins);t&&Xi(t,e),Ua.push(()=>Yi(e))}let es=gl(Mt),ts=gl(kt),os=gl(At),ns=gl(Br),is=[es,ts,os,ns];Ua.push(()=>{is.forEach(e=>e.destroy())});let ls,ds=null,cs=null,ps=!1,us=0,hs=null,ms=new Set;Ua.push(()=>ms.clear());let fs=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),bs=e=>{for(let t=e.length-1;t>=0;t--)if(Ho(e[t]))return e[t].id??null;return null},ys=!1,ws=!1,Ss=!1,ks=(e,t)=>{ws||!0!==l.debug||t.enabled&&!t.expose&&(ps||Ss&&(ls.isStreaming()||e.some(Ho)||(ws=!0,console.info("[persona] No suggest_replies call received. Declare the tool server-side or set suggestions.followUps.expose: true, and instruct the model when to use it. See UI-COMPONENTS.md."))))},As=e=>{if(!ls)return;let t=e??ls.getMessages();if(Mt.removeAttribute("data-persona-suggestions-below"),Mt.parentElement===ar&&ar.insertBefore(Mt,ar.firstChild),ms.size){let e=new Set(t.map(e=>e.id));for(let t of ms)e.has(t)||ms.delete(t)}let r=e=>{e.render([],ls,It,t)},o=e=>{is.forEach(t=>{t!==e&&r(t)})};cs&&(fs(t)>us||bs(t)!==hs)&&(cs=null);let n=zo(l);ks(t,n);let a=bs(t),s=!n.enabled||l.future?.v5Defaults&&a&&ms.has(a)?null:Fo(t,l.suggestions?.followUps?.maxItems??(l.future?.v5Defaults?5:4));if(l.future?.v5Defaults&&ls.isStreaming())return void is.forEach(r);let i=cs??s,d=cs?"host":"agent";if(i){let e=l.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),n="after-message"===("auto"===r?ye()?"composer":"after-message":r)?os:ye()?ns:es;return o(n),void n.render(i,ls,It,t,l.suggestionChipsConfig,{source:d,surface:"followUp",variant:e?.variant??"chip",behavior:e?.behavior??"send",overflow:e?.overflow??(l.future?.v5Defaults?"scroll":"wrap"),maxItems:e?.maxItems??(l.future?.v5Defaults?Fr()?5:3:4),config:l,plugins:T,submitPrompt:gu})}if(t.some(e=>"user"===e.role))return void is.forEach(r);let c=!0===l.future?.v5Defaults,p=Fr(),u=l.suggestions?.starters??(c?{}:void 0);if(u){let e=xd(Or(),t),n=u.placement??"auto",a="auto"===n?e?"welcome":"composer":n;if("welcome"===a&&!e)return ys||!0!==l.debug||(ys=!0,console.warn('[persona] Starters are hidden: suggestions.starters.placement is "welcome", but welcome is disabled. Use "auto" or "composer".')),void is.forEach(r);Mt.toggleAttribute("data-persona-suggestions-below","below-composer"===a),"below-composer"===a?Rt.after(Mt):ar.insertBefore(Mt,ar.firstChild);let s="welcome"===a?ts:es;o(s),s.render(u.items??l.suggestionChips,ls,It,t,l.suggestionChipsConfig,{surface:"starter",variant:u.variant??(c&&!p?"chip":"card"),behavior:u.behavior??"send",overflow:u.overflow??"wrap",maxItems:u.maxItems??(c&&!p?3:4),config:l,plugins:T,submitPrompt:gu})}else o(es),es.render(l.suggestionChips,ls,It,t,l.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:l,plugins:T,submitPrompt:gu})},Is=()=>{if(!l.future?.v5Defaults||!ls)return;cs=null;let e=bs(ls.getMessages());e&&ms.add(e),As()},Ts=()=>{cs&&(cs=null,As())},Es=!1,Ls=new Map,Bs=new Set,Rs=new Map,Ps=new Map,Ns=new Map,$s=new Map,Ws=e=>{let t=$s.get(e);if($s.delete(e),Ns.delete(e),Ld(St,e)?.removeAttribute("data-preserve-runtime"),t){t.controller.abort();try{t.handle.destroy?.()}catch(e){console.error("[AgentWidget] Component cleanup failed:",e)}}};Ua.push(()=>{for(let e of $s.keys())Ws(e)});let Hs=new Map,Ds=new Map,Fs=e=>{Ds.get(e)?.abort(),Ds.delete(e),Hs.delete(e)},Os=()=>{for(let e of Ds.keys())Fs(e)};Ua.push(Os);let zs=null,qs=null;function js(){if(!zs)return;let e=zs;zs=null,qs?.destroy(),qs=null,Ls.delete(e),xt.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),ls&&$d(St,ls.getMessages(),Le)}let Vs=0,Ks=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),Qs=0,Js=null,Gs=!1,Ys=!1,Xs=0,Zs=null,ei=null,ti=!1,ri=!1,oi=null,ni=!0,ai=!1,si=null,ii=!1,ci=()=>{bn++,ii=!0,xi()},pi=null,hi=24,yi=null,vi=()=>{e.setAttribute("data-persona-scrollbar",Ir()),"on-scroll"!==Ir()&&(null!==yi&&clearTimeout(yi),yi=null,Ct.removeAttribute("data-persona-scrollbar-visible"))},xi=()=>{"on-scroll"===Ir()&&(Ct.setAttribute("data-persona-scrollbar-visible",""),null!==yi&&clearTimeout(yi),yi=setTimeout(()=>{yi=null,Qt(Ct,24)&&Ct.removeAttribute("data-persona-scrollbar-visible")},1e3))};vi(),Ua.push(()=>{null!==yi&&clearTimeout(yi)});let ki=new Map,Ai=!1,Ei=null,Li={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};en();let Ri=l.voiceRecognition?.autoResume??!1,Ni=()=>ls.isVoiceActive()||ls.isBargeInActive(),$i=!1,Oi=e=>{U.emit("voice:state",{active:Li.active,source:e,timestamp:Date.now()})},zi=()=>{oe(e=>({...e,voiceState:{active:Li.active,timestamp:Date.now(),manuallyDeactivated:Li.manuallyDeactivated}}))},qi=()=>{$i=!0,Li.active&&zi()};typeof window<"u"&&(window.addEventListener("pagehide",qi),Ua.push(()=>window.removeEventListener("pagehide",qi)));let ji=()=>ls?Mp(ls.getMessages()).filter(e=>!e.__skipPersist):[],_i=null,Ui=(e,t)=>{typeof console<"u"&&console.error(e,t)},Ji=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{Ui(t,e)}):null}catch(e){return Ui(t,e),null}},o=_i?_i.then(()=>r()??void 0):r();if(!o)return;let n=o.finally(()=>{_i===n&&(_i=null)});_i=n};function Gi(e){if(null!==el||!V?.save)return;let t=e?Mp(e):ls?ji():[],r=K&&ls?.getResumableHandle();r&&(Q={...Q,durableResume:{executionId:r.executionId,after:r.lastEventId}});let o={messages:t,metadata:Q,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId,...Zi?{draft:Zi}:{}};Ji(()=>V.save(o),"[AgentWidget] Failed to persist state:")}let Zi,el=null,tl=()=>!(!V?.save||!1===l.persistState||"object"==typeof l.persistState&&!1===l.persistState.persist?.draft),nl=function(e){let t=e.delay??500,r=null,o=!1,n=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{o||(n(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{o||null===r||(n(),e.write())},cancel:n,destroy:()=>{o=!0,n()}}}({write:()=>{if(!tl())return;let e=Xr.getState(),t=ma({text:e.text,mentionRefs:e.mentionRefs,contentSegments:au(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(Zi)&&(Zi=t,Gi())}});function al(){tl()&&nl.schedule()}function cl(){nl.flush()}function pl(e){if(!tl())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),n=o.length===(e.mentionRefs?.length??0)&&o.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,...n?{mentionRefs:o}:{},...n&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(l.contextMentions?.sources??[]).map(e=>e.id),modelIds:(l.composer?.models??[]).map(e=>e.id),modes:l.composer?.modes??[]});t&&(Zi=e,It&&!It.value&&(It.value=t.text,It.dispatchEvent(new Event("input",{bubbles:!0})),Zr()),t.selectedModelId&&(Xr.setSelectedModelId(t.selectedModelId),uo?.repaint()),co(t.activeModeIds??[]),t.quote&&go(t.quote),nl.cancel())}function hl(){nl.cancel(),Zi&&(Zi=void 0,tl()&&Gi())}let bl=Gt(),yl=()=>gt.querySelector("#persona-scroll-container")||Ct,vl=()=>{bl.cancel(),Gs=!1},Cl=()=>{null!==Js&&(cancelAnimationFrame(Js),Js=null),Ys=!1,vl()},Sl=()=>{let e=ls?.getStatus();return Es&&"paused"!==e&&"resuming"!==e&&"error"!==e&&!ls?.getMessages().some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)},Al=()=>Sl()&&_l()&&("anchor-top"!==wr()||kr()),Ml=()=>{let e="true"===Er.getAttribute("data-persona-scroll-to-bottom-visible");Tr.update(l,e,Al(),Xs,e&&Rl())},El=()=>{let e=Ct.getBoundingClientRect(),t=ar.getBoundingClientRect();return t.height>0&&t.bottom>e.top?Math.min(Ct.clientHeight,Math.max(0,t.top-e.top-Ct.clientTop)):Ct.clientHeight},Ll=e=>Ur(e)>Ct.scrollTop+El()-24,Bl=()=>(ls?.getMessages()??[]).filter(e=>"approval"===e.variant&&"pending"===e.approval?.status).map(e=>yd(e.id)).filter(e=>!!e?.isConnected),Rl=()=>Bl().some(Ll),Nl=e=>{let t=Ur(e);return t>=Ct.scrollTop&&t+e.offsetHeight<=Ct.scrollTop+El()},Hl=[],_l=()=>!(xr()&&Ks.isFollowing()||gd(Zs?.spacerHeight??0,!1)-Ct.scrollTop-El()<=24),Vl=()=>!!ls&&ls.getMessages().length>0,Ql=()=>{if(!1===l.features?.scrollToBottom?.enabled||Ke||tt&&"panel"===rt)return Tr.update(l,!1),void(Er.parentNode&&Er.remove());let e=Lr();Er.parentNode!==e&&e.insertBefore(Er,e===xt?Br:null),Vr();let t=Kt(Ct)>0,r=!td.active&&t&&_l()&&Vl();r||(Xs=0),Tr.update(l,r,Al(),Xs,r&&Rl())},Jl=()=>{Ks.pause()&&(Cl(),Ql())},Gl=()=>{Ks.resume(),0!==Xs&&(Xs=0,Ml()),Ql()},Xl=(e=!1)=>{!td.active&&xr()&&Vl()&&Ks.isFollowing()&&(e||Es)&&(null!==Js&&(cancelAnimationFrame(Js),Js=null),Ys=!0,Js=requestAnimationFrame(()=>{Js=null,Ys=!1,Ks.isFollowing()&&rd(yl(),e?220:140)}))},ed=(e,t,r,o=()=>!0)=>{vl(),Gs=!0,bl.start(e,t,r,()=>{Qs=e.scrollTop},()=>{Gs=!1},o)},td=Yt(Ct,xt,()=>{Qs=Ct.scrollTop},()=>{Gl(),Xl(!0),Ql(),(()=>{let e=Hl;Hl=[];for(let t of e){let e=yd(t)?.querySelector('[data-action="allow"]');if(e&&Nl(e))return void e.focus({preventScroll:!0})}})()},()=>{Hl=[],Ks.pause(),Ql()}),rd=(e,t=500)=>{let r=Kt(e)-e.scrollTop;Math.abs(r)<1?Qs=e.scrollTop:Math.abs(r)>=80?(vl(),Gs=!0,e.scrollTop=Kt(e),Qs=e.scrollTop,Gs=!1):ed(e,()=>Kt(e),t,()=>Ks.isFollowing())},sd=()=>{if(!Vl())return void Ql();let e=yl();Gs=!0,e.scrollTop=Kt(e),Qs=e.scrollTop,Gs=!1,Ql()},id=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=Ct.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??Ct.ownerDocument.getSelection()})(),Ct),ld=()=>{if("last-user-turn"!==(Ne.restorePosition??"bottom"))return!1;let e=ls?.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,'\\"'),o=Ct.querySelector(`[data-message-id="${r}"]`);if(!o)return!1;let n=Math.min(Math.max(0,Ur(o)-Cr()),Kt(Ct));return Gs=!0,Ct.scrollTop=n,Qs=Ct.scrollTop,Gs=!1,"follow"===wr()&&!Qt(Ct,24)&&Ks.pause(),Ql(),!0},ud=e=>{let t=Math.max(0,Math.round(e));Pr.style.height=`${t}px`,Pr.style.display=t>0?"":"none",Zs&&(Zs.spacerHeight=Math.max(0,e))},gd=(e,t=!0)=>{let r=parseFloat(getComputedStyle(Ct).paddingBottom)||0,o=0;for(let e of Ct.children){let t=e;t!==Pr&&0!==t.offsetHeight&&(o=Math.max(o,Ur(t)+t.offsetHeight))}let n=Ct.scrollHeight-e,a=o>0?Math.min(o+r,n):n;return t?a:a-r},fd=()=>{null!==ei&&(cancelAnimationFrame(ei),ei=null),td.cancel(),vl(),Zs=null,Pr.style.height="0px",Pr.style.display="none"},yd=e=>Ct.querySelector(`[data-message-id="${(e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'))(e)}"]`),vd=()=>{if("anchor-top"!==wr()||!Zs||!si)return;let e=yd(si);if(!e)return;vl();let t=Zs.spacerHeight,r=gd(t),{targetScrollTop:o,spacerHeight:n}=Jt({anchorOffsetTop:Ur(e),topOffset:Cr(),viewportHeight:Ct.clientHeight,contentHeight:r,slack:24});Zs={pending:0,initialSpacerHeight:n,contentHeightAtAnchor:r,spacerHeight:n},ud(n),Gs=!0,Ct.scrollTop=o,Qs=Ct.scrollTop,Gs=!1,Ql()},Cd=(e,t,r,o,n)=>{if(Ls.delete(r),"toggle"!==n&&xr()&&Ks.isFollowing())return void Ul(e,t,r,o);let a=Ct.getBoundingClientRect().top,s=e.getBoundingClientRect(),i=Zs;i&&(vl(),ud(i.spacerHeight+e.offsetHeight)),Ul(e,t,r,o);let l=e.getBoundingClientRect(),d=s.top-a,c="toggle"===n?l.top-a-("collapsed"===o.state&&d<0?Cr():d):d>=0?l.top-s.top:l.bottom-s.bottom,p=Math.max(0,Ct.scrollTop+c);i&&Zs===i&&(ud(p+Ct.clientHeight+24-gd(i.spacerHeight)),i.initialSpacerHeight=i.spacerHeight,i.contentHeightAtAnchor=Ct.scrollHeight-i.spacerHeight),Math.abs(p-Ct.scrollTop)>=1&&(Gs=!0,Ct.scrollTop=p,Qs=Ct.scrollTop,Gs=!1),Ql()},Ad=()=>{if(!Ol(l))return;let e=zl(l);for(let t of Array.from(St.querySelectorAll(`[${Dl}]`))){let r=t.closest("[data-message-id]"),o=r?.getAttribute("data-message-id");if(!r||!o)continue;let n=t.scrollHeight;n>0&&v.set(o,jl(n,e));let a=v.get(o)??!1,s=t.getAttribute(Dl);if("live"===s)continue;"settling"===s&&x.delete(o);let i=a?w.get(o)?"expanded":"collapsed":"fit";i!==s&&Cd(r,t,o,{state:i,maxHeight:e,...ql(l)},"measure")}},Td=(e,t)=>{let r="user"===t?"user":"assistant",o=l.layout?.messages?.[r],n=o?.width??"content",a="operator"===t?"content":n,s="operator"===t?"var(--persona-message-operator-max-width, var(--persona-message-assistant-max-width, 100%))":`var(--persona-message-${r}-max-width, 100%)`,i=o?.maxWidth??("full"===n?s: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-row-operator","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),i?e.style.setProperty("--persona-message-row-max-width",i):e.style.removeProperty("--persona-message-row-max-width")},Ed=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),Td(r,t),r},Ld=(e,t)=>Array.from(e.querySelectorAll("[data-wrapper-id]")).find(e=>e.getAttribute("data-wrapper-id")===t),Bd=(t,r,o)=>{let n=new Set;g(),i?.observeMessages(r,n);let a=document.createElement("div"),d=!l.features?.toolCallDisplay?.grouped,c=new Set;if(d)for(let e of Array.from(t.children)){let t=e.getAttribute("data-wrapper-id");t&&c.add(t)}let p,u=new Map,h=T.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator??l.loadingIndicator?.render,v=new Set,w=new Map,x=new Set,S=T.some(e=>e.renderAskUserQuestion),k=[],A=[],M=!1!==l.enableComponentStreaming,I=!1!==l.approval,E=[],L=l.messageActions;if(l.future?.v5Defaults&&void 0===L?.visibility)for(let e=r.length-1;e>=0;e--)if("assistant"===r[e].role&&!r[e].variant){p=r[e].id;break}let R=!0!==L?.showRegenerate&&"block"!==l.errorDisplay||!1===L?.enabled||!0===Vn.current?.isStreaming()?null:function(e){for(let t=e.length-1;t>=0;--t){let r=e[t];if("user"===r.role||"operator"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return Ln(e,r.id)?r.id:null}return null}(r),$=!0===L?.showEdit&&!1!==L.enabled,W=-1;r.forEach((e,t)=>{"operator"===e.role&&(W=t)});let H=!0===L?.showQuote&&!1!==L.enabled,D=null,O=l.features?.reasoningDisplay?.completedVisibility,z=e=>"removed"===O||"removed-when-short"===O&&((e,t)=>{let r=t?.durationMs??15e3,o=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<o})(e,l.features?.reasoningDisplay?.shortThinkThreshold),q="removed"===l.features?.toolCallDisplay?.completedVisibility,j=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?z(e.reasoning):q&&"tool"===e.variant&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;r.forEach((n,s)=>{if(j(n))return;if(v.add(n.id),w.set(n.id,n.role),("tool"===n.variant&&n.toolCall&&Re||"reasoning"===n.variant&&n.reasoning&&Be)&&!g())return void a.appendChild(Ed(n.id,n.role));if(zs===n.id&&qs){let e=Ed(n.id,n.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void(D={messageId:n.id,element:qs.element})}let i=S&&yo(n),B=I&&"approval"===n.variant&&!!n.approval,O=!i&&"assistant"===n.role&&!n.variant&&M&&$n(n);!B&&Hs.has(n.id)&&(Ld(t,n.id)?.removeAttribute("data-preserve-runtime"),Fs(n.id)),!O&&Ns.has(n.id)&&(Ld(t,n.id)?.removeAttribute("data-preserve-runtime"),Ws(n.id));let z=yo(n)?`:${n.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${n.agentMetadata?.askUserQuestionAnswers?Object.keys(n.agentMetadata.askUserQuestionAnswers).length:0}`:"",q={isLastAssistant:n.id===p,canRegenerate:R===n.id&&(!0===L?.showRegenerate||!0===n.dispatchError),canEdit:$&&s>W&&Bn(n),canQuote:H&&!n.variant&&(n.content?.trim().length??0)>0},U=`${q.canRegenerate?"r":""}${q.canEdit?"e":""}${q.canQuote?"q":""}${q.isLastAssistant?"l":""}`,V=n.approval?.toolCallId?r.filter(e=>!("tool"!==e.variant||e.toolCall?.id!==n.approval?.toolCallId||e.agentMetadata?.executionId&&n.approval?.executionId&&e.agentMetadata.executionId!==n.approval.executionId)):[],K=1===V.length?V[0].toolCall:void 0,Q=K&&"pending"!==K.status?{toolCallId:K.id,status:"running"===K.status?"running":!1===K.success||K.error?"failed":"completed"}:void 0,J=C(n),G=Bi(n,Vs)+z+`:${U}`+(J?`:uc-${J.state}`:"")+(B?`:${n.approval?.toolCallId??""}:${JSON.stringify(Q)}`:""),Y=i||B||O||n.dispatchError&&"block"===l.errorDisplay&&!P?null:function(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}(Ls,n.id,G);if(Y){if(c.has(n.id)&&Rs.get(n.id)===G){let e=document.createElement("div");e.id=`wrapper-${n.id}`,e.setAttribute("data-wrapper-id",n.id),e.setAttribute("data-persona-reuse","true"),a.appendChild(e)}else a.appendChild(Y.cloneNode(!0));return d&&u.set(n.id,G),void(yo(n)&&n.toolCall?.id&&!0===n.agentMetadata?.awaitingLocalTool&&!n.agentMetadata?.askUserQuestionAnswered&&(x.add(n.toolCall.id),Jn(n)))}let X=null,Z=()=>{if(n.dispatchError&&"block"===l.errorDisplay){let e=F();if(e)return e.createErrorBlock(n,o,!0===q.canRegenerate)}let e=od(n,o,l.layout?.messages,l.messageActions,0,{loadingIndicatorRenderer:h,widgetConfig:l,actionEligibility:q,userCollapse:J});return e.dataset.personaDefaultMessage="true",e},ee=T.find(e=>!!("reasoning"===n.variant&&e.renderReasoning||"tool"===n.variant&&e.renderToolCall||!n.variant&&e.renderMessage));if(yo(n)&&!0===n.agentMetadata?.askUserQuestionAnswered)return Ps.delete(n.id),void Ld(t,n.id)?.removeAttribute("data-preserve-runtime");if(Ho(n)&&zo(l).enabled)return;if(yo(n)&&!1!==l.features?.askUserQuestion?.enabled){let e=T.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&Vn.current){let t=Ps.get(n.id),r=t!==G,o=null;if(r){let{payload:t,complete:r}=wo(n),a=n.id,s=()=>Vn.current?.getMessages().find(e=>e.id===a);o=e.renderAskUserQuestion({message:n,payload:t,complete:r,resolve:e=>{let t=s();t&&Vn.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Vn.current?.markAskUserQuestionResolved(e),Vn.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:l})}if(r&&null===o&&null==t)return void(!0===n.agentMetadata?.awaitingLocalTool&&!n.agentMetadata?.askUserQuestionAnswered&&(x.add(n.toolCall.id),Jn(n)));let s=Ed(n.id,n.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),a.appendChild(s),void k.push({messageId:n.id,fingerprint:G,bubble:o})}return void(!0===n.agentMetadata?.awaitingLocalTool&&!n.agentMetadata?.askUserQuestionAnswered&&(x.add(n.toolCall.id),Jn(n)))}if(B){let t=F();if(!t)return void a.appendChild(Ed(n.id,n.role));let r=T.find(e=>"function"==typeof e.renderApproval)??N,o=Hs.get(n.id),s=null,i=!1;if(o!==G&&r?.renderApproval){let a=n.id,d=!1,c=(e,t)=>{let r=Vn.current?.getMessages().find(e=>e.id===a);d||"pending"!==r?.approval?.status||(d=!0,dr(r.approval)?Vn.current?.resolveWebMcpApproval(r.id,e):Vn.current?.resolveApproval(r.approval,e,t))};Fs(n.id);let p=new AbortController;Ds.set(n.id,p);let u={message:n,execution:Q,signal:p.signal,defaultRenderer:()=>g(),config:l,approve:e=>{p.signal.aborted||c("approved",e)},deny:e=>{p.signal.aborted||c("denied",e)}},h=null,m=new AbortController;p.signal.addEventListener("abort",()=>m.abort(),{once:!0});let g=()=>(h??=N?.renderApproval?.({...u,signal:m.signal})??t.createApprovalBubble(n,l,y),h);s=r===N?g():r.renderApproval(u)??g();let f=null!==h&&(s===h||s.contains(h));f||m.abort();let b=e.getRootNode();i=f&&void 0===o&&"pending"===n.approval?.status&&!1!==l.approval&&"focused"===l.approval?.keyboardShortcuts&&e.contains(b.activeElement)}let d=Ed(n.id,n.role);return d.setAttribute("data-approval-plugin-stub","true"),d.setAttribute("data-preserve-runtime","true"),a.appendChild(d),void E.push({messageId:n.id,fingerprint:G,bubble:s,focusDefault:i})}if(ee)if("reasoning"===n.variant&&n.reasoning&&ee.renderReasoning){if(!Be)return;X=ee.renderReasoning({message:n,defaultRenderer:()=>m.createReasoningBubble(n,l,b),config:l})}else if("tool"===n.variant&&n.toolCall&&ee.renderToolCall){if(!Re)return;X=ee.renderToolCall({message:n,defaultRenderer:()=>m.createToolBubble(n,l,f),config:l})}else ee.renderMessage&&(X=ee.renderMessage({message:n,defaultRenderer:()=>{let e=Z();return"user"!==n.role&&_(e,n,l,ls),e},config:l}));if(X&&$s.has(n.id)&&Ws(n.id),!X&&O){let e=Wn(n);if(e){let r=Ns.get(n.id),s=!1!==l.wrapComponentDirectiveInBubble&&!1!==yt(l,e.component)?.bubbleChrome,i=`${Bi(n,Vs)}:${s}:${e.raw}`,d=$s.get(n.id),c=bt(l,e.component),p=d?.renderer!==c||d?.component!==e.component,u=r!==i||p;d&&(d.context.message=n,d.context.config=l);let h=null;if(u){let r=null;if(d&&!p&&d.handle.update){d.context.message=n,d.context.config=l;try{d.handle.update(e.props,d.context),r=d.handle.element}catch(e){console.error("[AgentWidget] Component update failed:",e),Ws(n.id)}}else{Ws(n.id);let t=new AbortController,a={config:l,message:n,signal:t.signal,updateProps:e=>{queueMicrotask(()=>{t.signal.aborted||Vn.current?.updateComponentProps(n.id,e)})}},s=Pn(e,{config:l,message:n,transform:o,signal:t.signal,onPropsUpdate:a.updateProps,context:a});if(s){let o="element"in s?s:{element:s};r=o.element,$s.set(n.id,{renderer:c,component:e.component,controller:t,handle:o,context:a})}else t.abort()}if(r&&"PersonaArtifactInline"===e.component){let e=r.hasAttribute("data-artifact-inline")?r:r.querySelector("[data-artifact-inline]"),o=e?.getAttribute("data-artifact-inline")??"",a=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(o):o,s=o?t.querySelector(`#wrapper-${n.id}`)?.querySelector(`[data-artifact-inline="${a}"]`)??null:null;e&&s&&s!==e&&Et()?.hasLiveInlineArtifactBlock(s)&&(e===r?r=s:e.replaceWith(s))}if(r)if(s){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",e.id=`bubble-${n.id}`,e.setAttribute("data-message-id",n.id),n.content&&n.content.trim()){let t=document.createElement("div");t.className="persona-mb-3 persona-text-sm persona-leading-relaxed",t.innerHTML=o({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),e.appendChild(t)}e.appendChild(r),h=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-${n.id}`,e.setAttribute("data-message-id",n.id),e.setAttribute("data-persona-component-directive","true"),n.content&&n.content.trim()){let t=document.createElement("div");t.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",t.innerHTML=o({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),e.appendChild(t)}e.appendChild(r),h=e}}if(h||$s.has(n.id)){let e=Ed(n.id,n.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void A.push({messageId:n.id,fingerprint:i,bubble:h})}}}if(!X)if("reasoning"===n.variant&&n.reasoning){if(!Be)return;X=m.createReasoningBubble(n,l,b)}else if("tool"===n.variant&&n.toolCall){if(!Re)return;X=m.createToolBubble(n,l,f)}else if("approval"===n.variant&&n.approval){if(!1===l.approval)return;let e=F();if(!e)return;X=e.createApprovalBubble(n,l,y)}else{let e=l.layout?.messages;X=e?.renderUserMessage&&"user"===n.role?e.renderUserMessage({message:n,config:l,streaming:!!n.streaming}):e?.renderAssistantMessage&&"assistant"===n.role?e.renderAssistantMessage({message:n,config:l,streaming:!!n.streaming}):Z(),"user"!==n.role&&X&&_(X,n,l,ls)}let te=Ed(n.id,n.role);te.appendChild(X),function(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}(Ls,n.id,G,te),a.appendChild(te),d&&u.set(n.id,G)}),wt.composerOverlay&&wt.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!x.has(t)&&Po(wt.composerOverlay,t)});let U=g()?.groupToolRows({root:e,config:l,messages:r,tempContainer:a,streaming:!!B&&ls.isStreaming(),runActivity:ls?.getRunActivity(),showToolCalls:Re,showReasoning:Be,dropCompletedToolCalls:q,dropReasoningRow:z,createMessageRow:Ed,activityIds:n,activityLifecycle:i,toolExpansionState:f});i?.prune(n);for(let e of $s.keys())v.has(e)||Ws(e);for(let e of Ds.keys())v.has(e)||Fs(e);!function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(Ls,v);let V=e=>yo(e)&&!0!==e.agentMetadata?.askUserQuestionAnswered&&!1!==l.features?.askUserQuestion?.enabled?(e=>!(e.toolCall?.id&&x.has(e.toolCall.id)||k.some(t=>t.messageId===e.id)))(e):"tool"===e.variant&&!Re||"reasoning"===e.variant&&!Be||j(e),K=r.some(e=>"assistant"===e.role&&e.streaming&&!V(e)),Q=r.length-1;for(;Q>=0&&V(r[Q]);)Q--;let J=Q>=0?r[Q]:void 0,G=Q<r.length-1,Y="assistant"===J?.role&&!J.streaming&&"approval"!==J.variant&&!G;if(!U&&Es&&r.some(e=>"user"===e.role)&&!K&&!Y){let e={config:l,streaming:!0,location:"standalone",defaultRenderer:()=>Kl(l)},t=T.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator?.(e)??l.loadingIndicator?.render?.(e)??Kl(l);if(t){let e=document.createElement("div"),r=!1!==l.loadingIndicator?.showBubble,o=l.layout?.messages?.layout??"bubble";e.className=r?Yl("assistant",o).join(" "):"persona-text-sm persona-leading-relaxed persona-text-persona-text",e.setAttribute("data-typing-indicator","true"),r&&(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(t);let n=Ed("typing-indicator","assistant");n.appendChild(e),a.appendChild(n)}}if(!Es&&r.length>0){let e=r[r.length-1],t={config:l,lastMessage:e,messageCount:r.length},o=T.find(e=>e.renderIdleIndicator)?.renderIdleIndicator?.(t)??l.loadingIndicator?.renderIdle?.(t);if(o){let e=document.createElement("div");e.className=!1===l.loadingIndicator?.showBubble?"persona-text-sm persona-leading-relaxed persona-text-persona-primary":"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",e.setAttribute("data-idle-indicator","true"),e.appendChild(o);let t=Ed("idle-indicator","assistant");t.appendChild(e),a.appendChild(t)}}(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)})})(a),s?.prepare(a),i?.prepare(a),Ii(t,a),Rs=u;for(let e of Array.from(t.querySelectorAll(":scope > [data-persona-reuse]"))){let t=Ls.get(e.getAttribute("data-wrapper-id")??"");t?e.replaceWith(t.wrapper.cloneNode(!0)):e.remove()}if(Wr(t),D){let{messageId:e,element:r}=D,o=Ld(t,e);o&&r.parentElement!==o&&(Td(o,w.get(e)??"user"),o.replaceChildren(r))}if(k.length>0)for(let{messageId:e,fingerprint:r,bubble:o}of k){let n=Ld(t,e);n&&(Td(n,w.get(e)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Ps.set(e,r)))}if(Ps.size>0)for(let e of Ps.keys())v.has(e)||Ps.delete(e);if(A.length>0)for(let{messageId:e,fingerprint:r,bubble:o}of A){let n=Ld(t,e);n&&(Td(n,w.get(e)??"assistant"),null!==o&&(n.replaceChildren(o),n.setAttribute("data-bubble-fp",r),Ns.set(e,r)))}if(Ns.size>0)for(let e of Ns.keys())v.has(e)||Ns.delete(e);if(E.length>0)for(let{messageId:e,fingerprint:r,bubble:o,focusDefault:n}of E){let a=Ld(t,e);if(!a||(Td(a,w.get(e)??"assistant"),null===o))continue;a.replaceChildren(o),a.setAttribute("data-bubble-fp",r),Hs.set(e,r);let s=xr()&&Ks.isFollowing();n&&(s||!Ll(a))&&o.querySelector('[data-action="allow"]')?.focus()}if(Hs.size>0)for(let e of Hs.keys())v.has(e)||Hs.delete(e);g(),s?.sync(),i?.sync()},Rd=()=>{qr().catch(()=>{})},$d=(e,t,r)=>{if(t.length>0&&Rd(),Bd(e,t,r),(e=>{if(0===v.size&&0===w.size&&0===x.size)return;let t=new Set(e.map(e=>e.id));for(let e of[v,w,x])for(let r of e.keys())t.has(r)||e.delete(r)})(t),Ad(),kn(),gn.size>0){for(let[e,r]of gn)t.some(t=>t.id===e)||(window.clearTimeout(r),gn.delete(e));vn()}},Hd=null,Dd=()=>{if(Hd)return;let t=e=>{let t=e.composedPath();t.includes(gt)||vt&&t.includes(vt)||rc(!1,"user")};Hd=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},Fd=()=>{Hd&&=((e.ownerDocument??document).removeEventListener("pointerdown",Hd,!0),null)};Ua.push(()=>Fd());let Od=null,zd=()=>{if(Od)return;let t=e=>{"Escape"===e.key&&(e.isComposing||rc(!1,"user"))};Od=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},_d=()=>{Od&&=((e.ownerDocument??document).removeEventListener("keydown",Od,!0),null)};Ua.push(()=>_d());let Ud=!1,Vd=new Set,Gd=()=>l.launcher?.composerBar?.peek?.streamAnimation||l.features?.streamAnimation,Yd=()=>{if(!ye())return;let t=wt.peekBanner,r=wt.peekTextNode;if(!t||!r)return;if(we)return void t.classList.remove("persona-pill-peek--visible");let o,n=ls?.getMessages()??[];for(let e=n.length-1;e>=0;e--){let t=n[e];if("assistant"===t.role&&t.content){o=t;break}}if(!o)return void t.classList.remove("persona-pill-peek--visible");let a=o.content,s=!!o.streaming,i=Gd(),l=Pi(i),d="none"===l.type?null:Xa(l.type,i?.plugins),c=!0===d?.isAnimating?.(o),p=null!==d&&(s||c);p&&d&&!Vd.has(d.name)&&(Xi(d,e),Vd.add(d.name));let u=p&&d?.containerClass?d.containerClass:null,h=r.dataset.personaPeekStreamClass??null;h&&h!==u&&(r.classList.remove(h),delete r.dataset.personaPeekStreamClass),u&&h!==u&&(r.classList.add(u),r.dataset.personaPeekStreamClass=u),p?(r.style.setProperty("--persona-stream-step",`${l.speed}ms`),r.style.setProperty("--persona-stream-duration",`${l.duration}ms`)):(r.style.removeProperty("--persona-stream-step"),r.style.removeProperty("--persona-stream-duration"));let m=p?Fi(a,l.buffer,d,o,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),n=m.length>100?m.slice(-100):m,a=Ar(n);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Vi(a,d.wrap,`peek-${o.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&n.length>0){let e=Ki(),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)}Ii(r,i),d.onAfterRender?.({container:r,bubble:t,messageId:o.id,message:o,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${n}`:n;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=Qi();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),Ii(r,e)}let g=Es||Ud;t.classList.toggle("persona-pill-peek--visible",g)};if(ye()){let e=wt.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),rc(!0,"user")};e.addEventListener("pointerdown",t),Ua.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Ud||(Ud=!0,Yd())},r=()=>{Ud&&(Ud=!1,Yd())};ft.addEventListener("pointerenter",t),ft.addEventListener("pointerleave",r),Ua.push(()=>{ft.removeEventListener("pointerenter",t),ft.removeEventListener("pointerleave",r)}),vt&&(vt.addEventListener("pointerenter",t),vt.addEventListener("pointerleave",r),Ua.push(()=>{vt.removeEventListener("pointerenter",t),vt.removeEventListener("pointerleave",r)}))}let Xd=()=>{if(we&&Rd(),!ve())return;if(ye()){let e=(l.launcher?.composerBar??{}).expandedSize??"anchored",t=we?"expanded":"collapsed";return gt.dataset.state=t,gt.dataset.expandedSize=e,vt&&(vt.dataset.state=t,vt.dataset.expandedSize=e),gt.style.removeProperty("display"),gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=l.launcher?.composerBar??{},r=t.expandedSize??"anchored",o=t.bottomOffset??"16px",n=t.collapsedMaxWidth,a=t.expandedMaxWidth??"880px",s=t.expandedTopOffset??"5vh",i=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)";Kr();let p=gt.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",vt){let e=vt.style;e.bottom=o,e.width=n??""}e&&"fullscreen"!==r&&("modal"===r?(p.top="50%",p.left="50%",p.transform="translate(-50%, -50%)",p.bottom="auto",p.right="auto",p.width=i,p.maxWidth=c,p.maxHeight=d,p.height=d):(p.left="50%",p.transform="translateX(-50%)",p.bottom=`calc(${o} + var(--persona-pill-area-height, var(--persona-measured-pill-area-height, 80px)))`,p.top=s,p.width=a,p.maxWidth=c))})(we),xt.style.display=we?"flex":"none",Nn(),we?(Dd(),zd()):(Fd(),_d()),void Yd()}let t=il(l),r=e.ownerDocument.defaultView??window,o=l.launcher?.mobileBreakpoint??640,n=l.launcher?.mobileFullscreen??!0,a=r.innerWidth<=o,s=n&&a&&le,i=dl(l).reveal;we?(gt.style.removeProperty("display"),gt.style.display=t?"flex":"",gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-95","persona-opacity-0"),ft.classList.add("persona-scale-100","persona-opacity-100"),mh?(mh.setPanelOpen(!0),mh.element.style.display="none"):gh&&(gh.style.display="none")):(t?!t||"overlay"!==i&&"push"!==i||s?(gt.style.setProperty("display","none","important"),gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(gt.style.removeProperty("display"),gt.style.display="flex",gt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(gt.style.display="",gt.classList.add("persona-pointer-events-none","persona-opacity-0"),ft.classList.remove("persona-scale-100","persona-opacity-100"),ft.classList.add("persona-scale-95","persona-opacity-0")),mh?(mh.setPanelOpen(!1),mh.element.style.display=t?"none":""):gh&&(gh.style.display=t?"none":""))},rc=(t,r="user")=>{if(!ve()||we===t)return;let o=we;we=t,Xd();let n=(()=>{let t=l.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,o=l.launcher?.mobileFullscreen??!0,n=l.launcher?.mobileBreakpoint??640,a=r.innerWidth<=n,s=il(l)&&o&&a,i=ye()&&"fullscreen"===(l.launcher?.composerBar?.expandedSize??"fullscreen");return t||o&&a&&le||s||i})();if(we&&n){if(!Va){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(Va=ol(r,l.launcher?.zIndex??1e5))}Ka||=sl(e.ownerDocument)}else we||(Va?.(),Va=null,Ka?.(),Ka=null);we&&(vh(),ld()||("follow"===wr()?Xl(!0):sd()));let a={open:we,source:r,timestamp:Date.now()};we&&!o?U.emit("widget:opened",a):!we&&o&&U.emit("widget:closed",a),U.emit("widget:state",{open:we,launcherEnabled:le,voiceActive:Li.active,streaming:ls.isStreaming()})},oc={inputDisabled:!1,sendDisabled:!1},nc=()=>oc.inputDisabled,ac=()=>_t(l.voiceRecognition?.provider)&&!!ls&&(ls.isBargeInActive()||["listening","processing","speaking"].includes(ls.getVoiceStatus())),sc=()=>oc.inputDisabled||oc.sendDisabled;function ic(){if(!Bt)return;if("streaming"===Xr.getState().phase)return void(Bt.disabled=!1);let e=!!Gr&&!Gr.isReady();Bt.disabled=sc()||e}function lc(){if(!cr)return;let e=Xr.getState(),t="when-text"===l.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;cr.toggleAttribute("data-persona-send-hidden",t)}function dc(){let e=Aa(l.composer?.inputDisabled),t=Aa(l.composer?.sendDisabled);oc={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Xr.setInputDisabled(e.disabled),Xr.setSendDisabled(t.disabled);let r="streaming"===Xr.getState().phase,o=e.disabled,n=r||o;It&&(It instanceof HTMLTextAreaElement?It.disabled=o:It.setAttribute("contenteditable",o?"false":"true"),It.setAttribute("aria-disabled",o?"true":"false")),fr&&(fr.disabled=o),yr&&(yr.disabled=o);for(let e of Yr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=o});mr&&(mr.disabled=o||r&&!ac()),is.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",n),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",n?"true":"false")}),e.buttons.forEach(e=>{e.disabled=n})}),Tc.forEach(e=>{e.toggleAttribute("data-disabled",n),e instanceof HTMLButtonElement?e.disabled=n:e.setAttribute("aria-disabled",n?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=n})}),ar.dataset.personaComposerStreaming=r?"true":"false",ar.dataset.personaComposerInputDisabled=o?"true":"false",ar.dataset.personaComposerSendDisabled=sc()?"true":"false",ar.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=r)}),ic(),function(){let e=(oc.inputDisabled?oc.inputReason:void 0)??(oc.sendDisabled?oc.sendReason:void 0);if(ye()){let t=Rt??ar;e?t.setAttribute("title",e):t.removeAttribute("title"),ar.toggleAttribute(xp,!!e)}else if(e)Pt.setAttribute("role","status"),Pt.setAttribute("aria-live","polite"),Pt.setAttribute(xp,""),Pt.removeAttribute(Cp),Pt.textContent=e,pr(Pt,l.statusIndicator??{},"idle");else if(Pt.hasAttribute(xp)&&(Pt.removeAttribute("role"),Pt.removeAttribute("aria-live"),Pt.removeAttribute(xp),B)){let e=ls.getStatus();ht(Pt,ut(e),l.statusIndicator??{},e)}}()}let cc=e=>{Xr.setStreaming(e),hr(e?"stop":"send"),dc()},pc=()=>{e.hasAttribute("data-persona-preparing")?u.ready.then(pc,()=>{}):Li.active||It&&It.focus()};U.on("widget:opened",()=>{l.autoFocusInput&&setTimeout(()=>pc(),200)});let uc=null,hc=!1,mc=!Nt.hidden,gc=null,fc=!J,bc=null;Ua.push(()=>{bc?.cancel(),bc=null});let yc,vc,wc=t=>{let r=wd(t);if(r===zr)return;zr=r,e.setAttribute("data-persona-conversation-state",r);let o=_r();Jr(),fc&&(bc?.cancel(),bc=md(ar,"active"===r?o:_r(),"active"===r?"drop":"rise","centered"===Or().layout?320:260)),vd()},xc=null,Cc=null,Sc=null,Ac=!1,Mc=e=>{let t=Or(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==xc||t.icon!==yc)&&(xc=r,yc=t.icon,ad({host:Nt,iconHolder:$t,kicker:Ft,title:Ot,subtitle:zt,starterSuggestions:kt},t));let o=void 0===t.message?null:`${l.layout?.messages?.layout??"bubble"}|${t.message}`;o!==Cc&&(Cc=o,pd(Dt,t.message,l));let n=e??(ls?ls.getMessages():l.initialMessages);wc(n);let a=hc,s=!a&&xd(t,n),i=s!==mc;if(mc=s,Sc)return gc?.cancel(),gc=null,a!==Ac&&(Ac=a,a?cd(Ct,Nt,null):dd(Ct,Nt,Sc)),void nd(Ct,Nt,!a);if(i&&!s&&!a&&"on-first-message"===t.dismiss&&fc)return void(gc=hd(Nt,e=>{gc===e&&(gc=null),!mc&&!Sc&&(nd(Ct,Nt,!1),vd()),e?.cancel()}));if(gc){if(!s&&!a)return;gc.cancel(),gc=null}let d=!Nt.hidden;nd(Ct,Nt,s),!s&&d&&vd()},Ic=[],Tc=[],Ec=!1,Pc=null,Nc=()=>{Tc.length=0;let e=Ic.splice(0,Ic.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};Ua.push(Nc);let $c=(e,t)=>{let r=ul(e,t);if(!r)return!0===l.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),st("span");let o=l.suggestions?.starters,n=ml({item:{...r,behavior:r.behavior??o?.behavior??"send"},index:t,surface:"starter",source:"config",variant:o?.variant??"card",streaming:!!B&&ls.isStreaming(),config:l,plugins:T,chipsConfig:l.suggestionChipsConfig,session:ls,getTextarea:()=>It,eventTarget:Nt,submitPrompt:gu});return Tc.push(n),n},Hc=()=>{if(Ec)return;Ec=!0;let e=Or();Pc=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,vc=e.icon;try{Nc(),cd(Ct,Nt,Sc),Sc=null,Ac=!1;let t=ls?ls.getMessages():l.initialMessages,r=xd(e,t),o=0,n=null;for(let t of T)if(t.renderWelcome&&(n=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>Nt,sendMessage:e=>{if(!ls||ls.isStreaming())return;let t=e.trim();t&&ls.sendMessage(t)},requestRender:()=>Hc(),renderStarter:e=>$c(e,o++),storage:R(t.id),onCleanup:e=>{Ic.push(e)}}),n))break;n&&n!==Nt&&(Sc=n,dd(Ct,Nt,n))}finally{Ec=!1}Mc()},Dc=()=>{Mc(),Eo||(It.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Xr.getState().activeModeIds,l.composer?.modes)??l.copy?.inputPlaceholder??"How can I help...",!l.sendButton?.useIcon&&!ls?.isStreaming()&&(Bt.textContent=l.copy?.sendButtonLabel??"Send")),It.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',It.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Fc=!!l.setStoredConversationId,Oc=e=>oe(t=>{let r={...t};return delete r[e],r}),zc=e=>{let t=Q[e];return"string"==typeof t?t:null},qc=()=>{let e=Q.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};l.clientToken&&(l={...l,getStoredSessionId:()=>zc("sessionId"),setStoredSessionId:e=>{oe(t=>({...t,sessionId:e}))},clearStoredSessionId:l.clearStoredSessionId??(()=>Oc("sessionId")),getStoredConversationId:l.getStoredConversationId??(()=>zc("conversationId")),setStoredConversationId:l.setStoredConversationId??(e=>{oe(t=>({...t,conversationId:e}))}),clearStoredConversationId:l.clearStoredConversationId??(()=>Oc("conversationId"))});let jc=()=>l.clientToken??null,_c=e=>((e,t,r)=>{let o="",n="",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(o)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let o={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(o)},g=e=>{i||(null===e.key||e.key===o)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await op(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await op(`${e}\0${t}`)}`}})(e,t);o=s.storageKey,n=s.leaseKey,a=s.lockName,d=h(),!r&&typeof window<"u"&&window.addEventListener("storage",g)})(),b=e=>new Promise(t=>setTimeout(t,e)),y=()=>{let e=u();if(!e)return null;try{let t=e.getItem(n);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{y()?.ownerNonce===e&&t.removeItem(n)}catch{}},w=new Set,x=e=>i?Promise.reject(Error("Visitor store destroyed before its first init could start")):e(),C=e=>new Promise(t=>{let r=setTimeout(o,e);function o(){clearTimeout(r),w.delete(o),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===n)&&o()}w.add(o),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(o,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(o)}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 o=Date.now(),a=y();if(a&&a.expiresAt>o&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-o,500));else{try{r.setItem(n,JSON.stringify({ownerNonce:t,expiresAt:o+1e4}))}catch{s=!0;break}if(await b(20+40*Math.random()),y()?.ownerNonce!==t)await C(500);else{c=t;try{return await x(e)}finally{c=null,v(t)}}}}return x(e)})(e):x(e)},matches:(o,n,a)=>o===e&&n===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,He(),!1===l.persistState),Uc=jc(),Jc=Uc?_c(Uc):null,Yc={...Jc?{visitorStore:Jc}:{},historyBootstrapReady:!0!==l.features?.history?.enabled||mp()?G:Promise.all([G,Z]).then(()=>{}),getStoredMessageCursor:()=>zc("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?Oc("historyMessageCursor"):oe(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:()=>{let e=Q.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?oe(t=>({...t,pendingDisplayProjections:e})):Oc("pendingDisplayProjections")},getStoredResumableHandle:qc,setStoredResumableHandle:e=>{e?oe(t=>({...t,durableResume:e})):Oc("durableResume")},shouldResumeDurableConversation:()=>K&&null!==qc(),...Fc?{}:{getStoredConversationRevision:()=>zc("conversationRevision"),setStoredConversationRevision:e=>{null===e?Oc("conversationRevision"):oe(t=>({...t,conversationRevision:e}))}}};if(K){let t=l.onExecutionState,r=e.ownerDocument.defaultView,o=!1,n=()=>o=!0,a=()=>o=!1;r?.addEventListener("pagehide",n),r?.addEventListener("pageshow",a),Ua.push(()=>{r?.removeEventListener("pagehide",n),r?.removeEventListener("pageshow",a)}),l={...l,reconnectStream:l.reconnectStream??(e=>ls.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!o)&&Yc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Zc=null,ep=e=>"user"===e.role||"approval"===e.variant||!0===e.agentMetadata?.awaitingLocalTool||yo(e),np=null,ap=null,sp=null,lp=null,dp=e=>{let t,r;!e.length&&l.future?.v5Defaults&&(cs=null),np=e;for(let o=e.length-1;o>=0;--o){let n=e[o];if(!t&&"user"===n.role&&(t=n),!r&&"assistant"===n.role&&(r=n),t&&r)break}$d(St,e,Le),Et()?.updateInlineArtifactBlocks(St,Fn.artifacts,{suppressTransition:Es}),Zc??=setInterval(()=>{let e=St.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Zc),void(Zc=null);let t=Date.now();e.forEach(e=>{m?.updateActivityElapsed(e,t)})},100),Mc(e),As(e),Xl(!Es),(e=>{let t=new Map;e.forEach(e=>{let r=ki.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(U.emit("assistant:message",e),!ri&&("anchor-top"!==wr()||kr())&&_l()&&(Xs+=1,Ml(),Ql(),Dr(1===Xs?"1 new message below.":`${Xs} new messages below.`))),"assistant"===e.role&&(r?.streaming||Bs.has(e.id))&&!1===e.streaming&&U.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&U.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):U.emit("approval:requested",{approval:e.approval,message:e}))}),ki.clear(),t.forEach((e,t)=>{ki.set(t,e)}),Bs.clear()})(e),Ql(),Ve?.update(),0===e.length&&(fd(),ni=!0,ai=!1,si=null,ii=!1),!ti||ri?(ti=!0,oi=t?.id??null,pi=r?.id??null):t&&t.id!==oi?(oi=t.id,(e=>{let t=wr();"follow"===t?(Gl(),Xl(!0)):"anchor-top"===t&&(ni=!1,ai=!0,ii=!1,si=e,(e=>{null!==ei&&cancelAnimationFrame(ei),ei=requestAnimationFrame(()=>{ei=null;let t=yd(e);if(!t)return;let r=Ur(t),o=gd(Zs?.spacerHeight??0),{targetScrollTop:n,spacerHeight:a}=Jt({anchorOffsetTop:r,topOffset:Cr(),viewportHeight:Ct.clientHeight,contentHeight:o,slack:24});Zs={pending:0,initialSpacerHeight:a,contentHeightAtAnchor:o,spacerHeight:a},ud(a),ed(Ct,()=>t.isConnected?Math.max(0,Ur(t)-Cr()):n,220)})})(e))})(t.id)):r&&r.id!==pi&&"anchor-top"===wr()&&(ai?ni=!1:(ni=!0,fd(),Gl(),Xl(!0))),r&&(pi=r.id);let o=Li.lastUserMessageId;t&&t.id!==o&&(Li.lastUserMessageId=t.id,U.emit("user:message",t)),Li.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!K)return Gi(e);lp=e,queueMicrotask(()=>{lp===e&&(lp=null,Gi(ap??e))})})(e),Yd(),U.emit("messages:changed",e)},cp=()=>{null!==sp&&(cancelAnimationFrame(sp),sp=null);let e=ap;ap=null,e&&dp(e)},pp=()=>{null!==sp&&cancelAnimationFrame(sp),sp=null,ap=null};ls=new c(l,{onRunStarted:e=>U.emit("run:started",e),onRunFinished(e){cp(),l.turnActivity?.enabled&&$d(St,ls.getMessages(),Le),U.emit("run:finished",e)},onMessagesChanged(e){(e=>{if(0===e.length)return pp(),void dp(e);let t=ap??np;Es&&t&&((e,t)=>{if(t.length<e.length)return!1;for(let r=0;r<t.length;r+=1){let o=t[r];if(o!==e[r]){if(ep(o))return!1;"assistant"===o.role&&o.streaming&&Bs.add(o.id)}}return!0})(t,e)?(ap=e,null===sp&&(sp=requestAnimationFrame(()=>{sp=null;let e=ap;ap=null,e&&dp(e)}))):(cp(),dp(e))})(e)},onStatusChanged(e){let t=l.statusIndicator??{};ht(Pt,(e=>"idle"===e?t.idleText??dt.idle:"connecting"===e?t.connectingText??dt.connecting:"connected"===e?t.connectedText??dt.connected:"error"===e?t.errorText??dt.error:"paused"===e?t.pausedText??dt.paused:"resuming"===e?t.resumingText??dt.resuming:dt[e])(e),t,e),Ql(),Ve?.update(),lt()},onStreamingChanged(e){e||(0===ls?.getMessages().length?pp():cp()),Es=e,e?Is():l.future?.v5Defaults&&As(),cc(e),lt(),ls&&$d(St,ls.getMessages(),Le),e||(Xl(!0),(()=>{if(!Zs||Zs.spacerHeight<=0||Zs.pending)return;let e=gd(Zs.spacerHeight),t=Math.max(0,Math.round(Ct.scrollTop)+Ct.clientHeight-e+24);t<Zs.spacerHeight&&(ud(t),Ql())})(),Ss=!0,ls&&ks(ls.getMessages(),zo(l))),Ql(),Ve?.update(),Dr(e?"Responding…":"Response complete."),Yd()},onVoiceStatusChanged(e){if(U.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!_t(l.voiceRecognition?.provider))return;let t=ls.getVoiceNotice();switch(t&&pu(t,1e4),e){case"listening":if(!Ai){let e=ls.getVoiceDisclosure();e&&(Ai=!0,ye()?(Ei=It.placeholder,It.placeholder=e,Dr(e)):pu(e,1e4))}Gu(),Ku();break;case"processing":Gu(),Qu();break;case"speaking":Gu(),Ju();break;default:"idle"===e&&ls.isBargeInActive()?(Gu(),Ku(),mr?.setAttribute("aria-label","End voice session")):(Li.active=!1,Ai=!1,null!==Ei&&(It.placeholder=Ei,Ei=null),Gu(),Oi("system"),$i||zi())}},onArtifactsState(e){Fn=e,0===e.artifacts.length&&(jn=!1),Et()?.updateInlineArtifactBlocks(St,e.artifacts,{suppressTransition:Es}),$a(),Gi()},onHistoryStateChanged(e){at(e)},onHistoryNotice(e){it(e)},onHistoryScopeInvalidated(){Up(),fp?.clearConversationOpenPending()},onConversationExecutionState(e){U.emit("conversation:executionState",e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?U.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?U.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):U.emit("stream:resumed",{executionId:t,after:r})}},Yc),Vn.current=ls,Ua.push(()=>ls.cancel()),Ua.push(()=>{ls.destroy(),Jc?.destroy(),Jc=null});let up=null;if(ls.onReadAloudChange((e,t)=>{xn=e,Cn=t,kn();let r=e??up;e&&(up=e);let o=r?ls.getMessages().find(e=>e.id===r)??null:null;U.emit("message:read-aloud",{messageId:r,message:o,state:t,timestamp:Date.now()}),"idle"===t&&(up=null)}),B=!0,ti=!0,!0===l.voiceRecognition?.enabled&&Ut(l))try{ls.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let fp=null,bp=null,Lp=!1,Bp=ls.getHistoryState(),Rp=()=>!0===l.features?.history?.enabled,Pp=e=>{e&&(Nr.textContent="",Nr.textContent=e)},Np=()=>{L.forEach(e=>e()),L=[];let t=fp,r=t?.railCollapseShortcut();t&&r&&L.push(E.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===l.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>tt&&"rail"===rt&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of l.layout?.header?.trailingActions??[])t.shortcut&&L.push(E.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let r=e.querySelector(`[data-persona-header-action="${t.id}"]`);r?r.click():l.layout?.header?.onAction?.(t.id)}}));for(let e of T)for(let t of e.shortcuts??[])L.push(E.register({...t,id:`${e.id}:${t.id}`}))};Np();let $p=null,Wp=!1,Hp=()=>{if(!tr)return;let e="conversation"===l.layout?.header?.titleSource,t=e&&$p?.trim()||null;tr.textContent=t??l.launcher?.title??"Chat Assistant";let r=tr.closest(".persona-combo-btn");if(!r)return;let o=!e||null!==ls.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 n=r.querySelector("svg");n&&(n.style.display=o?"":"none")};Hp(),xt.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=ls.getActiveConversationId();r&&("delete"===t?Jp(e=>e.requestDeleteConversation(r)):"star"===t&&ls.canUpdateConversations()&&Jp(e=>e.updateHistoryConversation(r,{starred:!Wp})).catch(()=>{}))});let Dp=new Map,Fp=(e=ls.getActiveConversationId(),t=fp?.historyOperationScope()??l.features?.history?.scope??(l.getIdentityProof?"verified-user":"browser"))=>JSON.stringify([t,e]),Op=null,zp=0,qp=()=>{let e=Ct.getBoundingClientRect().top,t=Ct.clientHeight>0?Array.from(St.querySelectorAll("[data-message-id]")).find(t=>t.getBoundingClientRect().bottom>e):void 0;return{top:Ct.scrollTop,anchorId:t?.dataset.messageId,anchorOffset:t?t.getBoundingClientRect().top-e:0,following:Ks.isFollowing(),followFallback:ni,anchored:ai,anchoredId:si,readerEngaged:ii,anchor:Zs?{...Zs}:null,unread:Xs}},jp=e=>{ni=e.followFallback,ai=e.anchored,si=e.anchoredId,ii=e.readerEngaged,Zs=e.anchor?{...e.anchor,pending:0}:null,ud(e.anchor?.spacerHeight??0),e.following?Ks.resume():Ks.pause(),Xs=e.unread;let t=Array.from(St.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e.anchorId);Gs=!0,e.following&&xr()?Ct.scrollTop=Kt(Ct):t?Ct.scrollTop+=t.getBoundingClientRect().top-Ct.getBoundingClientRect().top-e.anchorOffset:Ct.scrollTop=e.top,Gs=!1,Qs=Ct.scrollTop,xh=Kt(Ct),Ml(),Oa(),Ql()},_p=(e=!1,t=!0)=>{let r=e?void 0:Dp.get(Fp());Yr?.clear(),Gr?.setPreviewsContainer(null),Gr=r?.attachments??(l.attachments?.enabled?no():null),Gr?.updateConfig(ro()),Gr?.remountPreviews(vr),ao(Gr?.getAttachments()??[]);let o=r?.draft,n=Yr?.getInlineInput();r?.document&&n?.setDocument?n.setDocument(r.document):n?n.setValueWithCaret(o?.text??"",(o?.text??"").length):It.value=o?.text??"",Yr?.restoreDraft(r?.mentions??[]),Zr(),eo(),Xr.setSelectedModelId(o?l.composer?.models?.some(e=>e.id===o.selectedModelId)?o.selectedModelId:void 0:l.composer?.selectedModelId),uo?.repaint(),co(fa(o?.activeModeIds??l.composer?.defaultActiveModeIds??[],so())),go(o?.quote),xo(r?.pending),wu(),fd(),Cl(),fp?.cancelConversationOpenTakeover(),uc&&(uc.hidden=!0),hc=!1,St.style.removeProperty("display"),r?jp(r.reading):(Gl(),ld()||sd()),t&&(Zi=tl()?ma({...Xr.getState(),contentSegments:au()}):void 0),nl.cancel(),t&&Gi(),Op={key:Fp(),reading:r?.reading??qp()}},Up=(e,t=!0,r=!0)=>{for(let[t,r]of Dp)(void 0===e||JSON.parse(t)[1]===e)&&(r.attachments?.destroy({release:!0}),Gr===r.attachments&&(Gr=null),Dp.delete(t));(void 0===e||e===ls.getActiveConversationId())&&(++zp,el=null,lu?.abort(),lu=null,Bu(),Gr?.destroy({release:!0}),Gr=null,t&&_p(!0,r),Op=null)};at=e=>{Bp=e,fp?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),cc(e.sendBlocked||Es),fp?.syncEarlierMessagesPill()},it=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(Up(),fp?.clearConversationOpenPending(),Ls.clear(),fd(),Gl()),Pp(e.message),fp?.historySurface?.view.refresh()};let Vp={getBubbleClasses:Yl,parseCombo:wi,formatCombo:Ci,ariaCombo:Si,usesSessionVoiceForConfig:Ut,applyBubbleGeometry:Zl,resolveThemeDefaults:_s,composerStore:Xr,get attachmentManager(){return Gr},set attachmentManager(e){Gr=e},get composerConversationGeneration(){return zp},set composerConversationGeneration(e){zp=e},get submissionAbort(){return lu},set submissionAbort(e){lu=e},persistState:Gi,applyMessageRowLayout:Td,SessionHistoryError:d,instanceId:n,discardConversationContinuity:Up,clearPersistedDraft:hl,saveConversationContinuity:()=>{Bu(),_u("system"),Ut(l)&&ls.cleanupVoice(),++zp,lu?.abort(),lu=null,Xr.setPreparing(!1),js(),cl();let e=Xr.getState(),t=Fp();Dp.set(t,{draft:{text:e.text,mentionRefs:[...e.mentionRefs],contentSegments:au(),quote:e.quote,selectedModelId:e.selectedModelId,activeModeIds:[...e.activeModeIds]},document:Yr?.getInlineInput()?.getDocument?.(),mentions:Yr?.captureDraft()??[],attachments:Gr,pending:e.pendingSubmission,reading:Op?.key===t?Op.reading:qp()}),nl.cancel()},restoreConversationContinuity:_p,get pendingConversationReading(){return Op},set pendingConversationReading(e){Op=e},conversationStateKey:Fp,captureConversationReading:qp,restoreConversationReading:jp,get conversationPersistenceOwner(){return el},set conversationPersistenceOwner(e){el=e},setComposerDisabled:cc,get actionManager(){return ie},get activeConversationTitle(){return $p},announceHistory:Pp,get applyRailChrome(){return nt},set applyRailChrome(e){nt=e},get artifactSplitRoot(){return ra},get body(){return Ct},get config(){return l},get container(){return xt},get conversationOpenPendingEl(){return uc},set conversationOpenPendingEl(e){uc=e},get conversationOpenTakeover(){return hc},set conversationOpenTakeover(e){hc=e},currentKeyPrefix:He,destroyCallbacks:Ua,eventBus:U,get footer(){return ar},get header(){return nr},get historyChromeSync(){return lt},set historyChromeSync(e){lt=e},historyFeatureEnabled:Rp,get historyInternals(){return Yc},set historyInternals(e){Yc=e},get historyPresentation(){return rt},set historyPresentation(e){rt=e},get historySessionState(){return Bp},get historyVisible(){return tt},set historyVisible(e){tt=e},get isStreaming(){return Es},jumpToBottomInstant:sd,get lastAppliedMessages(){return np},set lastAppliedMessages(e){np=e},get launcherEnabled(){return le},get launcherSurfaceInstance(){return mh},maybeFocusInput:pc,messageCache:Ls,get messagesWrapper(){return St},mount:e,get open(){return we},panel:ft,panelElements:wt,panelSuggestions:Br,panelSuggestionsFade:Rr,get persistentMetadata(){return Q},set persistentMetadata(e){Q=e},plugins:T,get reapplyHistoryHostChrome(){return ot},set reapplyHistoryHostChrome(e){ot=e},repinAnchoredMessage:vd,resetAnchorState:fd,restoreScrollPosition:ld,resumeAutoScroll:Gl,runStorageMutation:Ji,get session(){return ls},setActiveConversationSummary:e=>{Wp=!0===e?.starred,(e=>{e!==$p&&($p=e,Hp())})(e&&e.title.trim()||null),Hp()},storageAdapter:V,get suppressScrollSend(){return ri},set suppressScrollSend(e){ri=e},syncScrollToBottomButton:Ql,scrollToBottomButton:Er,updateWelcome:Mc,getHistoryProviderFactory:gp,historyErrors:{HistoryClientError:o,HistoryProviderError:a},isDockedMountMode:il,renderLucideIcon:Ee,loadHistoryView:ip,createHeaderIconButton:wl,attachTooltip:Qa},Kp=e=>(!fp&&!Lp&&(fp=e.createHistoryShell(Vp),fp.railCollapseShortcut()&&Np()),fp),Qp=()=>{if(fp)return Promise.resolve(fp);let e=mp();return e?Promise.resolve(Kp(e)):(bp??=hp().then(Kp,e=>{throw bp=null,e}),bp)},Jp=e=>{let t=mp(),r=fp??(t?Kp(t):null);return r?e(r):Qp().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},Gp=()=>{fp?.syncHistoryPresentation()};Ua.push(()=>{Lp=!0}),Rp()&&Qp().catch(()=>{}).finally(X),l.clientToken&&(!0===l.features?.history?.enabled||"mount"===l.sessionInit)&&ls.initClientSession().then(()=>{let e=fp;if(e?.historyAvailable())return ls.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{fp?.syncEarlierMessagesPill()}).catch(e=>{l.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let Yp=()=>ls.warmClientSession(),Xp=e=>{let t=l.sessionInit??"input",r=No?.input??It,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:(No?.form??Rt)?.contains(o)))&&Yp()},Zp=["input","pointerdown","keyup"];Zp.forEach(t=>e.addEventListener(t,Xp));let eu,tu,ru=()=>{let e=tu;tu=void 0;try{"function"==typeof e&&e()}catch{}},ou=()=>{let t=l.clientToken&&"function"==typeof l.sessionInit?l.sessionInit:void 0;if(t!==eu){ru(),eu=t;try{tu=t?.({warm:Yp,mount:e})}catch{}}};ou(),Ua.push(()=>{Zp.forEach(t=>e.removeEventListener(t,Xp)),ru()}),(Pe||l.onSSEEvent)&&ls.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ze(e,t)});let nu=()=>{let e=l.resume??(K?Yc.getStoredResumableHandle?.():null);e&&"function"==typeof l.reconnectStream&&ls.resumeFromHandle(e)};J?J.then(e=>{if(e){if(e.metadata&&(Q=Ap(e.metadata),ie.syncFromMetadata()),e.messages?.length){ri=!0;try{ls.hydrateMessages(e.messages)}finally{ri=!1}Rd()}e.artifacts?.length&&ls.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),pl(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{fc=!0,M(),nu()}):(pl(I),nu());let au=()=>{let e=It.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},su=!1,iu=0,lu=null,du=()=>{It.value="",It.style.height="auto",Zr(),wu()},cu=null;function pu(e,t=4e3){Dr(e),!ye()&&Pt&&(Pt.hasAttribute(xp)||(Pt.setAttribute(Cp,""),Pt.setAttribute("role","status"),Pt.setAttribute("aria-live","polite"),Pt.textContent=e,pr(Pt,l.statusIndicator??{},"idle"),cu&&clearTimeout(cu),cu=setTimeout(()=>{if(cu=null,Pt?.hasAttribute(Cp)&&(Pt.removeAttribute(Cp),Pt.removeAttribute("role"),Pt.removeAttribute("aria-live"),B)){let e=ls.getStatus();ht(Pt,ut(e),l.statusIndicator??{},e)}},t)))}let uu=(e={})=>{if(Lu()||uc)return;let t=zp,r=(e.overrideText??It?.value??"").trim();return e.resolveInlineCommand&&r?(Yr?.takeInlineCommand(r)??Promise.resolve(null)).then(o=>{if(t===zp)return hu(e,r,o)}):hu(e,r,null)},hu=(e,t,r)=>{if("action"===r?.kind)return du(),Yr?.clear(),void eo();let o="server"===r?.kind?r.mentions:null,n="prompt"===r?.kind?r.sendText:t,a=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:n,hasAttachments:(Gr?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:Gr?.isReady()??!0,hasMentions:Yr?.hasMentions()??!1,hasServerMentions:!!o,inputDisabled:nc(),sendDisabled:sc()}))return;let s=ls.isStreaming()?bo():"block";if("defer-one"===s&&!e.pending)return Xr.getState().pendingSubmission?void pu("One message is already queued. Edit or remove it first."):void function(e){let t=Xr.getState(),r=Gr?.hasAttachments()??!1,o=r?[...Gr.getContentParts()]:[];r&&e.sendText&&o.push(fn(e.sendText)),xo(Ma({text:e.sendText,contentParts:o.length?o:void 0,mentionRefs:[...Yr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:au(),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&&du(),r&&Gr.clearAttachments(),Yr?.clear(),eo(),t.quote&&go(void 0),hl(),Yo.release(),en(),Dr("Message queued. It sends when the response finishes.")}({intent:e,sendText:n,serverMentions:o});let i={text:n,mentionRefs:[...Yr?.getMentionRefs()??[],...o?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:au(),options:{...Xr.getState().selectedModelId&&{selectedModelId:Xr.getState().selectedModelId},...Xr.getState().activeModeIds.length>0&&{activeModeIds:[...Xr.getState().activeModeIds]},...Xr.getState().quote&&{quote:{...Xr.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(i.options={...e.pending.options},i.contentSegments=e.pending.contentSegments,i.mentionRefs=[...e.pending.mentionRefs],i.viaVoice=e.pending.viaVoice);let d=()=>{if(a?.length)return[...a];if(!Gr?.hasAttachments())return;let e=[...Gr.getContentParts()];return i.text&&e.push(fn(i.text)),e};i.contentParts=d();let c=()=>{js(),ye()&&(we||(l.launcher?.composerBar?.expandOnSubmit??1)&&rc(!0,"auto"));let t=Yr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,o]=await Promise.allSettled([e.finalize(),t.finalize()]),n=[];return"fulfilled"===r.status?n.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===o.status?n.push(o.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",o.reason),(e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Ep(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}))(n)}}:e:t)(t,o),n=d();!1!==e.consumeDraft&&du();let a={selectedModelId:i.options.selectedModelId,activeModeIds:i.options.activeModeIds},c="interrupt"===s;c&&ls.cancel(),ls.sendMessage(i.text,{contentParts:n,mentions:r??void 0,contentSegments:i.contentSegments,viaVoice:i.viaVoice,composerOptions:a,...i.options.quote&&{quote:i.options.quote},...c&&{interrupt:!0}}),Gr?.hasAttachments()&&Gr.clearAttachments(),t&&Yr?.clear(),eo();let p=Xr.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,l.composer?.modes);u.length!==p.length&&co(u),Xr.getState().quote&&go(void 0),hl(),Yo.release(),en()},p=l.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;lu=u;let h=zp,m=e=>{u.signal.aborted||h!==zp||(lu===u&&(lu=null),"error"===e.status?(e=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",e)})(e.error):"proceed"===e.status&&c())},g=Ta(p,i,u.signal);if(g instanceof Promise)return Xr.setPreparing(!0),g.then(m).finally(()=>{h===zp&&Xr.setPreparing(!1)});m(g)};An={regenerate:function(e){if(ls.isStreaming())return;let t=Ln(ls.getMessages(),e);t&&(js(),ls.resubmitFrom(t,{reason:"retry"})&&vd())},edit:function(e){if(!0!==l.messageActions?.showEdit)return;let t=ls.getMessages().find(t=>t.id===e);t&&Bn(t)&&En(ls.getMessages(),e)&&zs!==e&&(js(),zs=e,qs=ha({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=qs;zs=null,qs=null,r?.destroy(),Ls.delete(e),ls.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?vd():$d(St,ls.getMessages(),Le)}(e,t),onCancel:()=>js()}),Ls.delete(e),$d(St,ls.getMessages(),Le),qs.focus())},quote:e=>{let t=ls.getMessages().find(t=>t.id===e)?.content?.trim();t&&(go({text:t,messageId:e}),It?.focus())}};let mu=async e=>{if(Lu())return void(l.voiceRecognition?.dictation?.showSend&&!sc()&&Ru(!0));if(su)return;su=!0;let t=++iu;try{await uu({resolveInlineCommand:!0,...e})}finally{t===iu&&(su=!1)}};function gu(e){sc()||(du(),fu(e,{consumeDraft:!1}))}let fu=(e,t)=>{if(su)return;su=!0;let r=++iu,o=()=>{r===iu&&(su=!1)};try{let r=uu({...t,overrideText:e});r instanceof Promise?r.finally(o):o()}catch(e){throw o(),e}},bu=e=>{e.preventDefault(),ls.isStreaming()?(ls.cancel(),qe?.reset(),Ve?.update()):su||mu()},yu={...Ti},vu=!1,wu=()=>{yu={...Ti}},xu=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(xt)&&(lu?(lu.abort(),lu=null,e.preventDefault(),e.stopImmediatePropagation()):ls.isStreaming()&&(ls.cancel(),qe?.reset(),Ve?.update(),wu(),e.preventDefault(),e.stopImmediatePropagation()))},Cu=null,Su=null,ku=!1,Au=null,Mu=null,Iu=0,Tu=Object.freeze({phase:"idle",recordingId:0,transcript:"",interimTranscript:"",error:null,audioLevel:null}),Eu=()=>!!l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&Hu(),Lu=()=>ku||["recording","processing"].includes(Cu?.getState().phase??"idle"),Bu=()=>{if(++Iu,ku=!1,Mu=null,Au){Au=null,Su?.element.remove(),Su=null;let{audioLevel:e,...t}=Tu;return U.emit("dictation:state",{...t,instanceId:n,timestamp:Date.now()}),!0}return Cu?.cancel()??!1},Ru=(e=!1)=>ku?(Mu=e||!0===Mu,!0):Cu?.finish(e)||e&&Cu?.send()||!1,Pu=()=>{if(nc()||ls.isStreaming()||Lu()||ac())return!1;let e=l.voiceRecognition;if(!1===e?.enabled)return!1;let t=e?.dictation?.provider??("custom"===e?.provider?.type?{type:"custom",custom:e.provider.custom}:{type:"browser",browser:e?.provider?.browser});if("browser"===t.type&&!qu()||"custom"===t.type&&!t.custom)return!1;!we&&ve()&&rc(!0,"system"),Au&&Bu();let r={text:It.value,logicalEnd:Yr?.getInlineInput()?.getLogicalText().length??null,readOnly:It.readOnly,contentEditable:It.getAttribute("contenteditable")};ku=!0,Mu=null;let o=++Iu;return Je().then(a=>{o===Iu&&(ku=!1,Cu??=a.createDictationSession({instanceId:n,getTextarea:()=>It,getFooter:()=>ar,getConfig:()=>l,plugins:T,getInlineInput:()=>Yr?.getInlineInput(),isInputDisabled:nc,isSendBlocked:sc,syncText:Zr,onSend:()=>{mu({viaVoice:!0})},rendererDeps:{renderLucideIcon:Ee,attachTooltip:Qa},onState:(e,t)=>{let{audioLevel:r,...o}=e;U.emit("dictation:state",{...o,instanceId:n,timestamp:Date.now()}),Li.active="recording"===e.phase,Du(t?"recording"===e.phase?"recording":"processing":"idle"),Oi("system")}}),ls.stopSpeaking(),Cu.start(t,{autoSend:!Hu(),pauseDuration:e?.pauseDuration},r),null!==Mu&&(Cu.finish(Mu),Mu=null))}).catch(e=>{if(o!==Iu)return;ku=!1;let t=e instanceof Error?e.message:"Unable to load dictation.";Au=Object.freeze({...Tu,recordingId:o,phase:"error",error:t});let r=st("div","persona-dictation");r.setAttribute("role","alert"),r.textContent=t;let a=document.createElement("button");a.type="button",a.textContent="Dismiss dictation",a.addEventListener("click",()=>{Bu()}),r.append(a),Su={element:r},ar.append(r);let{audioLevel:s,...i}=Au;U.emit("dictation:state",{...i,instanceId:n,timestamp:Date.now()})}),!0};Ua.push(()=>{++Iu,Cu?.destroy(),Su?.destroy?.(),Su?.element.remove()}),l.voiceRecognition?.dictation&&Je().catch(()=>{});let Nu,$u=null,Wu=!1,Hu=()=>"review"===l.voiceRecognition?.completionBehavior;function Du(e){mr&&xs(mr,l,e,ls.getVoiceInterruptionMode()),ar?.setAttribute("data-persona-voice-state",e),"recording"===e?function(){Ou=!0;let e=e=>{Ou&&(Fu??=e.createVoiceLevelIndicator({targets:()=>[gr??mr?.parentElement,ar].filter(e=>!!e),sample:()=>{let e=Cu?.getState();return"recording"===e?.phase?{level:e.audioLevel,fallback:!1}:{level:B?ls.getVoiceLevel():null,fallback:!0}}}),Fu.start())},t=Ge();t?e(t):Je().then(e,()=>{})}():zu()}let Fu,Ou=!1;function zu(){Ou=!1,Fu?.stop()}let qu=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ju=(e="user")=>{if(Wu||ls.isStreaming())return;let t=qu();if(!t)return;$u=new t;let r=$u,o=l.voiceRecognition??{},n=o.pauseDuration??2e3;$u.continuous=o.provider?.browser?.continuous??!0,$u.interimResults=!0,$u.lang=o.provider?.browser?.language??"en-US";let a,s=It.value,i=(e,t)=>{let o=o=>{$u===r&&Wu&&(a??=o.createBrowserRecognitionHandlers({textarea:It,initialText:s,pauseDuration:n,isActive:()=>$u===r&&Wu,syncText:Zr,stop:_u,review:Hu,submit:()=>{mu({viaVoice:!0})}}),Nu=()=>a?.dispose(),a[e](t))},i=Ge();i?o(i):Je().then(o,()=>{$u===r&&_u("system")})};r.onresult=e=>i("result",e),r.onerror=e=>i("error",e),r.onend=e=>i("end",e);try{$u.start(),Wu=!0,Li.active=!0,"system"!==e&&(Li.manuallyDeactivated=!1),Oi(e),zi(),en(),mr&&(mr.classList.add("persona-voice-recording"),Du("recording"),mr.setAttribute("aria-label","Stop voice recognition"))}catch{_u("system")}},_u=(e="user")=>{if(Wu){if(Wu=!1,Nu?.(),Nu=void 0,$u){try{$u.stop()}catch{}$u=null}Li.active=!1,Oi(e),$i||zi(),en(),mr&&(mr.classList.remove("persona-voice-recording"),Du("idle"),mr.setAttribute("aria-label",l.voiceRecognition?.tooltipText??"Start voice recognition"))}},Uu=null,Vu=e=>{let t=t=>{Uu??=t.createMicStateStyles({mic:()=>mr,config:()=>l,session:()=>ls,setMicState:Du}),e(Uu)},r=jt();r?t(r):qt().then(t,()=>{})},Ku=()=>Vu(e=>e.recording()),Qu=()=>Vu(e=>e.processing()),Ju=()=>Vu(e=>e.speaking()),Gu=()=>Vu(e=>e.reset()),Yu=()=>{if(!nc())if(Eu())"recording"===Cu?.getState().phase?Cu.finish():Lu()||Pu();else if(_t(l.voiceRecognition?.provider)){let e=ls.getVoiceStatus(),t=ls.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;if("cancel"===t&&("processing"===e||"speaking"===e))return void ls.stopVoicePlayback();if(ls.isBargeInActive())return ls.stopVoicePlayback(),void ls.deactivateBargeIn().then(()=>{Li.active=!1,Li.manuallyDeactivated=!0,zi(),Oi("user"),Gu()});ls.toggleVoice().then(()=>{Li.active=Ni(),Li.manuallyDeactivated=!Li.active,zi(),Oi("user"),Li.active?Ku():Gu()})}else if(Wu){let e=It.value.trim();Li.manuallyDeactivated=!0,zi(),_u("user"),e&&!Hu()&&mu()}else Li.manuallyDeactivated=!1,zi(),ju("user")};Co=Yu;let Xu=()=>ls.prewarmVoice(),Zu=()=>{let e=l.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!l.clientToken&&"hover"))},eh=e=>{"hover"===Zu()&&mr?.contains(e.target)&&Xu()},th=["pointerover","pointerdown","focusin"];th.forEach(t=>e.addEventListener(t,eh));let rh,oh,nh=null,ah=()=>{let e=oh;oh=void 0;try{"function"==typeof e&&e()}catch{}},sh=()=>{let t=Zu(),r="function"==typeof t&&mr?t:void 0,o=r?mr:null;if((r!==rh||o!==nh)&&(ah(),rh=r,nh=o,r&&o))try{oh=r({warm:Xu,micButton:o,mount:e})}catch{}};sh(),Ua.push(()=>{th.forEach(t=>e.removeEventListener(t,eh)),ah()}),mr&&Ua.push(()=>{_t(l.voiceRecognition?.provider)?(ls.isVoiceActive()&&ls.toggleVoice(),Gu()):_u("system")});let ih=U.on("assistant:complete",()=>{let e=Xr.getState().pendingSubmission,t=zp,r=xe;e&&setTimeout(()=>{Se(r)&&!ls.isStreaming()&&t===zp&&Xr.getState().pendingSubmission===e&&function(){let e=Xr.getState().pendingSubmission;e&&(xo(void 0),fu(e.text,{consumeDraft:!1,pending:e}))}()},0)});Ua.push(ih);let lh=U.on("assistant:complete",()=>{if(!Ri||Li.active||Li.manuallyDeactivated||"assistant"===Ri&&!Li.lastUserMessageWasVoice)return;let e=zp,t=xe;setTimeout(()=>{Se(t)&&e===zp&&!Li.active&&!Li.manuallyDeactivated&&(_t(l.voiceRecognition?.provider)?ls.toggleVoice().then(()=>{Se(t)&&e===zp&&(Li.active=ls.isVoiceActive(),Oi("auto"),ls.isVoiceActive()&&Ku())}):ju("auto"))},600)});Ua.push(lh);let dh=!1,ch=e=>{e.persisted&&!dh&&(dh=!0,$i=!0,ke(),zp++,iu++,su=!1,lu?.abort(),lu=null,Xr.setPreparing(!1),Bu(),_u("system"),ls.cancel(),ls.stopSpeaking(),ls.cleanupVoice(),qe?.reset(),Ve?.update())},ph=e=>{e.persisted&&dh&&(dh=!1,$i=!1,!0===l.voiceRecognition?.enabled&&Ut(l)&&ls.setupVoice())};window.addEventListener("pagehide",ch),window.addEventListener("pageshow",ph),Ua.push(()=>{window.removeEventListener("pagehide",ch),window.removeEventListener("pageshow",ph)});let uh=U.on("action:resubmit",()=>{Ae()});Ua.push(uh);let hh=()=>{rc(!we,"user")},mh=null,gh=null;if(le&&!ye()){let{instance:e,element:t}=Nd({config:l,plugins:T,onToggle:hh});mh=e,e||(gh=t)}mh?e.appendChild(mh.element):gh&&e.appendChild(gh),Xd(),As(),Dc(),Hc(),cc(ls.isStreaming()),ld()||("follow"===wr()?Xl(!0):sd()),(()=>{if(!1===l.voiceRecognition?.enabled||l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&"review"===l.voiceRecognition.completionBehavior)return;let e=Ap(Q.voiceState),t=!!e.active,r=Number(e.timestamp??0);if(Li.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4){let e=xe;setTimeout(()=>{Se(e)&&(Li.active||(Li.manuallyDeactivated=!1,_t(l.voiceRecognition?.provider)?ls.toggleVoice().then(()=>{Se(e)&&(Li.active=Ni(),Oi("restore"),Li.active?Ku():(zi(),pu("Tap the mic to resume your voice call",1e4)))}):ju("restore")))},_t(l.voiceRecognition?.provider)?0:1e3)}})(),ue&&(!le||ye()?setTimeout(()=>pc(),0):we&&setTimeout(()=>pc(),200));let fh=null,bh=()=>{fh&&(fh.disconnect(),fh.observe(ar),fh.observe(xt),fh.observe(Nt),fh.observe(Br))},yh=Fr(),vh=()=>{if(ye())return Vr(),void Xd();let t=il(l),r=l.launcher?.sidebarMode??!1,o=e.ownerDocument.defaultView??window,n=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640,s=o.innerWidth<=a,i=n&&s&≤try{if(i)return Nn(),void(Hn=Na());let e=!1;be&&(be=!1,Nn(),e=!0);let o=Na();if(!e&&o!==Hn&&(Nn(),e=!0),Hn=o,e&&ia(),!le&&!t)return ft.style.height="",void(r||(gt.style.width=kd(l),ft.style.width="100%",ft.style.maxWidth="100%"));if(!r&&!t){let e=Sd(l);ft.style.width=e.width,ft.style.maxWidth=e.maxWidth}Ba(),_a()}finally{Vr(),Jr();let t=Fr();if(t!==yh&&(yh=t,Mc(),As()),Xd(),we&&le){let t=(e.ownerDocument.defaultView??window).innerWidth<=(l.launcher?.mobileBreakpoint??640),r=l.launcher?.sidebarMode??!1,o=l.launcher?.mobileFullscreen??!0,n=il(l)&&o&&t,a=r||o&&t&&le||n;if(a&&!Ka){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!Va&&(Va=ol(r,l.launcher?.zIndex??1e5)),Ka=sl(e.ownerDocument)}else a||(Va?.(),Va=null,Ka?.(),Ka=null)}}};vh();let wh=e.ownerDocument.defaultView??window;if(wh.addEventListener("resize",vh),Ua.push(()=>wh.removeEventListener("resize",vh)),typeof ResizeObserver<"u"){fh=new ResizeObserver(()=>{Jr(),Ql()}),bh(),Ua.push(()=>{fh?.disconnect(),fh=null});let e=new ResizeObserver(()=>{Gp()});e.observe(xt),Ua.push(()=>e.disconnect())}wh.addEventListener("resize",Gp),Ua.push(()=>wh.removeEventListener("resize",Gp)),Qs=Ct.scrollTop;let xh=Kt(Ct),Ch=()=>{Oa();let e=Ct.scrollTop,t=Kt(Ct),r=t<xh;if(xh=t,td.interrupted||!xr())return Qs=e,void Ql();let{action:o,nextLastScrollTop:n}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-o;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&n&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!n?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Ks.isFollowing(),currentScrollTop:e,lastScrollTop:Qs,nearBottom:Qt(Ct,24),userScrollThreshold:4,isAutoScrolling:td.active||Gs||Ys||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Qs=n,"resume"!==o||id()?"pause"===o?Jl():Ql():Gl()};if(Ct.addEventListener("scroll",Ch,{passive:!0}),Ua.push(()=>Ct.removeEventListener("scroll",Ch)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{Ad(),(()=>{if(xr()){if(Ql(),!Ks.isFollowing()||Qt(Ct,1))return;Xl(!Es)}else{if(Zs&&Zs.initialSpacerHeight>0&&!Zs.pending){let e=Ct.scrollHeight-Zs.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:Zs.initialSpacerHeight,contentHeightAtAnchor:Zs.contentHeightAtAnchor,currentContentHeight:e});t!==Zs.spacerHeight&&ud(t)}Ql()}})(),Oa(),Wr(St)});e.observe(St),e.observe(Ct),Ua.push(()=>e.disconnect())}let Sh=()=>{xr()&&Ks.isFollowing()&&id()&&Jl()},kh=Ct.ownerDocument;kh.addEventListener("selectionchange",Sh),Ua.push(()=>{kh.removeEventListener("selectionchange",Sh)});let Ah=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Mh=e=>{Ah.has(e.key)&&(ci(),Sr()&&xr()&&Ks.isFollowing()&&Jl())},Ih=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(ci(),Sr()&&xr()&&Ks.isFollowing()&&Jl())};Ct.addEventListener("keydown",Mh),Ct.addEventListener("focusin",Ih),Ua.push(()=>{Ct.removeEventListener("keydown",Mh),Ct.removeEventListener("focusin",Ih)});let Th=e=>{if(td.interruptedBy(e))return void ci();if(0!==e.deltaY&&ci(),!xr())return;let t=function(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}({following:Ks.isFollowing(),deltaY:e.deltaY,nearBottom:Qt(Ct,24),resumeWhenNearBottom:!0});"pause"===t?Jl():"resume"===t&&!id()&&Gl()};Ct.addEventListener("wheel",Th,{passive:!0}),Ct.addEventListener("touchmove",ci,{passive:!0}),Ct.addEventListener("pointerdown",ci,{passive:!0}),Ua.push(()=>{Ct.removeEventListener("touchmove",ci),Ct.removeEventListener("pointerdown",ci)}),Ua.push(()=>Ct.removeEventListener("wheel",Th)),Er.addEventListener("click",()=>{let e=Bl().filter(Ll).map(e=>e.getAttribute("data-message-id"));fd(),Hl=e,Cl(),Ks.pause(),td.start(l),Ql()}),Ua.push(()=>td.destroy()),Ua.push(()=>Tr.destroy()),Ua.push(()=>{Cl(),fd()});let Eh=()=>{Zt&&(ds&&=(Zt.removeEventListener("click",ds),null),ve()?(Zt.style.display="",ds=()=>{rc(!1,"user")},Zt.addEventListener("click",ds)):Zt.style.display="none")};Eh(),(()=>{let{clearChatButton:e}=wt;e&&e.addEventListener("click",()=>{let e=fp;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{l.debug&&console.warn("[AgentWidget] New conversation failed:",e)});ls.clearMessages(),l.layout?.topFade&&(Ct.scrollTop=0),Ct.removeAttribute("data-persona-top-fade"),Ls.clear(),Gl(),Po(wt.composerOverlay);try{localStorage.removeItem(wp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${wp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==wp)try{localStorage.removeItem(l.clearChatHistoryStorageKey),l.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${l.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let t=new CustomEvent("persona:clear-chat",{detail:{instanceId:n,timestamp:(new Date).toISOString()}});window.dispatchEvent(t),hl(),V?.clear&&Ji(()=>V.clear(),"[AgentWidget] Failed to clear storage adapter:"),Q={},ie.syncFromMetadata(),Up(ls.getActiveConversationId(),!0,!1),du(),hl(),xo(void 0),go(void 0),js(),ze?.clear(),qe?.reset(),Ve?.update()})})();let Lh=[["keydown",e=>{if(It&&!nc()&&(e.isComposing||!Yr?.handleKeydown(e))){if(!(!1===l.features?.composerHistory||"ArrowUp"!==e.key&&"ArrowDown"!==e.key||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey||e.isComposing)){let t=0===It.selectionStart&&0===It.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!n)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:o}}}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:ls.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:It.value,atStart:t,state:yu});if(yu=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!It)return;vu=!0,It.value=e,It.dispatchEvent(new Event("input",{bubbles:!0})),vu=!1;let t=It.value.length;It.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,o=t.submitKey??"enter";return"none"!==o&&("mod-enter"===o?r:r||!Ca(t))}(e,{submitKey:l.composer?.submitKey,insertNewlineOnTouchEnter:l.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(It)}))if(ls.isStreaming()){if(e.preventDefault(),"block"===bo()||su||sc())return;wu(),mu()}else su||sc()?e.preventDefault():(wu(),e.preventDefault(),Bt.click())}}],["input",e=>{vu||(Is(),e.isComposing||Yr?.handleInput(e.inputType??void 0),wu())}],["input",Zr],["input",eo],["keyup",eo],["paste",async e=>{if(!0!==l.attachments?.enabled||!Gr||nc())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 o=Sp[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${o}`,{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 Gr.handleFiles(t))}],["focus",()=>Yr?.prefetch()]],Bh=e=>{if(e)for(let[t,r]of Lh)No?.addListener(e,t,r)},Rh=()=>{No&&(No.addListener(No.form,"submit",bu),No.addListener(No.footer,"click",eo),Bh(It),mr&&No.addListener(mr,"click",Yu),sh())};Rh();let Ph=()=>{Yr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of Lh)No?.removeListener(e,t,r)})(t),It=e,No&&(No.input=e),Bh(e),$o(),dc(),Zr(),Cu?.refresh()})};Ph();let Nh=!1;function $h(){if(!Nh){Nh=!0;try{ln.detach(["footer-top","footer-bottom","composer-start","composer-end","composer-before-send"]);let e=It?.value??"",t=ar.ownerDocument??document,r=!!It&&t.activeElement===It;zu(),No?.destroy(),No=null,Yr?.destroy(),Yr=null;let o=null,n=()=>(o=ye()?Wl({config:l}):$l({config:l}),o.footer),a=Lo(n)??n();mt.replaceComposer(a),ar=mt.composer.footer,!1===l.layout?.showFooter&&(ar.style.display="none");let s=null!==o&&a===o.footer;Eo=!s,hr=s?o.setSendButtonMode:()=>{},To(ar),Wo(ar),Oo(),qo(),jo(),Ph(),Qo(),Jo(),Go(),Rh();let i=is.indexOf(es);if(es.destroy(),es=gl(Mt),i>=0&&(is[i]=es),ln.remount(),It&&(It.value=e),Zr(),eo(),Dc(),As(),cc(ls.isStreaming()),"transient"===l.statusIndicator?.mode&&!ye()){let e=ls.getStatus();ht(Pt,ut(e),l.statusIndicator,e)}Li.active&&Du("recording"),Cu?.refresh(),Nn(),bh(),Vr(),en(),lc(),r&&It?.focus()}finally{Nh=!1}}}let Wh=e.ownerDocument??document;Wh.addEventListener("keydown",xu,!0);let Hh=()=>{cl()},Dh=()=>{"hidden"===Wh.visibilityState&&cl()};typeof window<"u"&&(window.addEventListener("pagehide",Hh),Wh.addEventListener("visibilitychange",Dh),Ua.push(()=>{window.removeEventListener("pagehide",Hh),Wh.removeEventListener("visibilitychange",Dh)}));let Fh="persona-attachment-drop-active",Oh=0,zh=()=>{Oh=0,xt.classList.remove(Fh)},qh=()=>!0===l.attachments?.enabled&&null!==Gr&&!nc(),jh=e=>{kp(e.dataTransfer)&&qh()&&(Oh++,1===Oh&&xt.classList.add(Fh))},_h=e=>{kp(e.dataTransfer)&&qh()&&(Oh--,Oh<=0&&zh())},Uh=e=>{kp(e.dataTransfer)&&qh()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},Vh=e=>{if(!kp(e.dataTransfer)||!qh())return;e.preventDefault(),e.stopPropagation(),zh();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&Gr.handleFiles(t)};xt.addEventListener("dragenter",jh,!0),xt.addEventListener("dragleave",_h,!0),e.addEventListener("dragover",Uh,!0),e.addEventListener("drop",Vh,!0);let Kh=e.ownerDocument,Qh=e=>{qh()&&e.preventDefault()},Jh=e=>{qh()&&e.preventDefault()};Kh.addEventListener("dragover",Qh),Kh.addEventListener("drop",Jh),Ua.push(()=>{No?.destroy(),No=null,zu(),Ko=!0,_o?.destroy(),_o=null,ho?.destroy(),ho=null,mo?.destroy(),mo=null,vo?.destroy(),vo=null,uo=null,cl(),nl.destroy(),cu&&clearTimeout(cu),js(),lu?.abort(),lu=null,fp?.clearConversationOpenPending(),Up(void 0,!1),Gr?.destroy(),Gr=null,Xr.destroy(),Wh.removeEventListener("keydown",xu,!0),Yr?.destroy()}),Ua.push(()=>{xt.removeEventListener("dragenter",jh,!0),xt.removeEventListener("dragleave",_h,!0),e.removeEventListener("dragover",Uh,!0),e.removeEventListener("drop",Vh,!0),Kh.removeEventListener("dragover",Qh),Kh.removeEventListener("drop",Jh),zh()}),Ua.push(()=>{ls.cancel()}),mh?Ua.push(()=>{mh?.destroy()}):gh&&Ua.push(()=>{gh?.remove()}),r?.registerHostMove?.(t=>{let r=Ct.scrollTop,o=xr()&&Ks.isFollowing(),n=Ct.getBoundingClientRect().top,a=!o&&Ct.clientHeight>0?Array.from(St.querySelectorAll("[data-message-id]")).find(e=>e.getBoundingClientRect().bottom>n):void 0,s=a?a.getBoundingClientRect().top-n:0;Cl(),t(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),vh(),nt(),o?Ct.scrollTop=Kt(Ct):a?Ct.scrollTop+=a.getBoundingClientRect().top-Ct.getBoundingClientRect().top-s:Ct.scrollTop=r,!o&&!ii&&vd(),Qs=Ct.scrollTop,xh=Kt(Ct),Oa(),Ql(),e.dispatchEvent(new Event("persona:internal:host-moved"))});let Gh=e=>{!we&&ve()&&rc(!0,"system"),St.querySelector(".persona-feedback-container")?.remove();let t=e();St.appendChild(t),t.scrollIntoView({behavior:"smooth",block:"end"})},Yh=!1,Xh=[],Zh=!1,em=()=>{let e=Xh;Xh=[],Zh=!0;try{for(let t of e)tm.update(t)}finally{Zh=!1}},tm={get ready(){return u.ready},get instanceId(){return n},update(t){if(!Zh){Xh.push(t);let e=Xh.reduce(Wc,{...l,features:A}),r=Vt(kc(e));if(r.length)return void u.prepare(r,em,Yh);if(Xh.length>1)return void u.prepare([],em,Yh);Xh=[]}r?.diagnostics||Kc(h,t);let o=t.voiceRecognition;o&&(!1===o.enabled||o.dictation?.provider&&o.dictation.provider!==l.voiceRecognition?.dictation?.provider||o.provider?.custom&&o.provider.custom!==l.voiceRecognition?.provider?.custom)&&Bu();let n=!0===l.future?.v5Defaults,a=l.messageActions,s=l.layout?.messages,i=l.colorScheme,d=l.iterationDisplay,c=l.features?.showReasoning,p=l.features?.showToolCalls,m=l.features?.toolCallDisplay,g=l.features?.reasoningDisplay,f=()=>JSON.stringify([l.features?.userMessageCollapse,l.copy?.showMoreLabel,l.copy?.showLessLabel]),b=f(),y=l.features?.streamAnimation?.type,v=!0===l.features?.history?.enabled,w=l.features?.history?.provider,x=l.getIdentityProof,C=l.clientToken,k=l.contextMentions;l=Wc({...l,features:A},t),A=l.features,l=kc(l),S(),Nn(),$a(),l.colorScheme!==i&&Ga();let M=Rc.getForInstance(l.plugins);T.length=0,T.push(...M),Np(),le=l.launcher?.enabled??!0,ce=l.launcher?.autoExpand??!1,Be=l.features?.showReasoning??!0,Re=l.features?.showToolCalls??!0,td.cancel();let I=wr();Ne=l.features?.scrollBehavior??{},I!==wr()&&(fd(),Gl()),vi(),Ql();let E=Pe;if(Pe=l.features?.showEventStreamToggle??!1,Pe&&!E){if(ze||(et(),ls.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ze(e,t)})),!Io&&nr){let e=l.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:"");Io=st("button",t),Io.style.width="28px",Io.style.height="28px",Io.style.color=kl.actionIconColor,Io.type="button",Io.setAttribute("aria-label","Event Stream"),Io.title="Event Stream";let r=ne(de,"18px","currentColor",1.5);r&&Io.appendChild(r);let o=wt.clearChatButtonWrapper,n=wt.closeButtonWrapper,a=o||n;a&&a.parentNode===nr?nr.insertBefore(Io,a):nr.appendChild(Io),Io.addEventListener("click",()=>{Ke?Mo():Ao()})}}else!Pe&&E&&(Mo(),Ve?.destroy(),Ve=null,Io&&=(Io.remove(),null),ze?.clear(),Fe?.destroy(),ze=null,Fe=null,qe?.reset(),qe=null,_e=null);if(!1===l.launcher?.enabled&&mh&&(mh.destroy(),mh=null),!1===l.launcher?.enabled&&gh&&(gh.remove(),gh=null),!1!==l.launcher?.enabled&&!mh&&!gh){let{instance:t,element:r}=Nd({config:l,plugins:T,onToggle:hh});mh=t,t||(gh=r),e.appendChild(r)}mh&&mh.update(l),Hp(),or&&void 0!==l.launcher?.subtitle&&(or.textContent=l.launcher.subtitle);let L=l.layout?.header;if(L?.layout!==fe&&nr){let e=L?Pl(l,L,{showClose:ve(),onClose:()=>rc(!1,"user")}):Il({config:l,showClose:ve(),onClose:()=>rc(!1,"user")});mt.replaceHeader(e),nr=mt.header.element,er=mt.header.iconHolder,tr=mt.header.headerTitle,or=mt.header.headerSubtitle,Zt=mt.header.closeButton,fe=L?.layout,Hp()}else if(L){if(er&&(er.style.display=!1===L.showIcon?"none":""),tr&&(tr.style.display=!1===L.showTitle?"none":""),or&&(or.style.display=!1===L.showSubtitle?"none":""),Zt){let e=ve()&&!1!==L.showCloseButton;Zt.style.display=e?"":"none"}if(wt.clearChatButtonWrapper){let e=L.showClearChat;if(void 0!==e){wt.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=wt;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let B=ss(l);nr&&(nr.style.display=B?"":"none");let R=!1!==l.layout?.showFooter;ar&&(ar.style.display=R?"":"none"),Vr(),Ql(),le===ge?ce!==me&&rc(ce,"auto"):le?rc(ce,"auto"):(we=!0,Xd()),me=ce,ge=le,vh(),Eh();let P=JSON.stringify(l.messageActions)!==JSON.stringify(a),N=JSON.stringify(l.layout?.messages)!==JSON.stringify(s)||l.layout?.messages?.renderAssistantMessage!==s?.renderAssistantMessage||l.layout?.messages?.renderUserMessage!==s?.renderUserMessage,$=l.iterationDisplay!==d,W=(l.features?.showReasoning??!0)!==(c??!0)||(l.features?.showToolCalls??!0)!==(p??!0)||JSON.stringify(l.features?.toolCallDisplay)!==JSON.stringify(m)||JSON.stringify(l.features?.reasoningDisplay)!==JSON.stringify(g)||f()!==b;(!0===l.future?.v5Defaults!==n||"toolCall"in t||P||N||"loadingIndicator"in t||$||W||"turnActivity"in t||"loadingLabel"in t||"expansion"in t||"errorDisplay"in t||"theme"in t||"darkTheme"in t||"approval"in t||l.colorScheme!==i||"askUserQuestion"in(t.features??{})||"features"in t&&void 0===t.features)&&ls&&(Vs++,$d(St,ls.getMessages(),Le));let H=l.features?.streamAnimation?.type;if(H!==y&&H&&"none"!==H){let t=Xa(H,l.features?.streamAnimation?.plugins);t&&Xi(t,e)}let D=l.launcher??{},F=D.headerIconHidden??!1,O=l.layout?.header?.showIcon,z=F||!1===O,q=D.headerIconName,j=D.headerIconSize??"40px";if(er){let e=nr,t=e?.querySelector(".persona-flex-col");if(z)er.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(er.style.display="",er.style.height=j,er.style.width=j,e&&t&&(e.contains(er)?er.nextSibling!==t&&(er.remove(),e.insertBefore(er,t)):e.insertBefore(er,t)),q){let e=parseFloat(j)||24,t=Ee(q,.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))`,er.replaceChildren(t)):er.textContent=D.agentIconText??"💬"}else if(D.iconUrl){let e=er.querySelector("img");if(e)e.src=D.iconUrl,e.style.height=j,e.style.width=j;else{let e=document.createElement("img");e.src=D.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=j,e.style.width=j,er.replaceChildren(e)}}else{let e=er.querySelector("svg"),t=er.querySelector("img");(e||t)&&er.replaceChildren(),er.textContent=D.agentIconText??"💬"}let r=er.querySelector("img");r&&(r.style.height=j,r.style.width=j)}}let _=l.layout?.header?.showTitle,V=l.layout?.header?.showSubtitle;if(tr&&(tr.style.display=!1===_?"none":""),or&&(or.style.display=!1===V?"none":""),Zt){let e=ve()&&!1!==l.layout?.header?.showCloseButton;Zt.style.display=e?"":"none";let t=D.closeButtonPlacement??"inline",{closeButtonWrapper:r}=wt,o="top-right"===t,n=r?.classList.contains("persona-absolute");if(r&&o!==n)if(r.remove(),o){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=fp?.railColumn??xt;e.style.position="relative",e.appendChild(r)}else{let e=D.clearChat?.placement??"inline";r.className=(D.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",nr&&nr.appendChild(r)}xl(Zt,l,"close",{buttonSize:ye()?Zt.style.width:void 0,iconSize:ye()?Md:void 0});let a=D.closeButtonTooltipText??"Close chat",s=D.closeButtonShowTooltip??!0;Zt.setAttribute("aria-label",a),r&&Qa({anchor:Zt,trigger:r,text:()=>Zt?.getAttribute("aria-label")??a,enabled:s})}let{clearChatButton:K,clearChatButtonWrapper:Q}=wt;if(K){let e=D.clearChat??{},t=e.enabled??!0,r=l.layout?.header?.showClearChat,o=void 0===r?t:r,n=e.placement??"inline";if(Q){Q.style.display=o?"":"none";let{closeButtonWrapper:e}=wt;!ye()&&e&&!e.classList.contains("persona-absolute")&&(o?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===n,r=Q.classList.contains("persona-absolute");if(!ye()&&t!==r&&o){if(Q.remove(),t){Q.className="persona-absolute persona-top-4 persona-z-50",Q.style.right="48px";let e=fp?.railColumn??xt;e.style.position="relative",e.appendChild(Q)}else{Q.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Q.style.right="";let e=wt.closeButtonWrapper;nr&&e&&e.parentElement===nr?nr.insertBefore(Q,e):nr&&nr.appendChild(Q)}let e=wt.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(o){xl(K,l,"clear",{buttonSize:ye()?K.style.width:void 0,iconSize:ye()?Id:void 0});let t=e.tooltipText??"Clear chat",r=e.showTooltip??!0;K.setAttribute("aria-label",t),Q&&Qa({anchor:K,trigger:Q,text:()=>K?.getAttribute("aria-label")??t,enabled:r})}}let J=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Qc],G=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[Gc.message,Gc.messageAndClick];ie=Xc({parsers:J,handlers:G,getSessionMetadata:re,updateSessionMetadata:oe,emit:U.emit,captureResubmitGuard:()=>{let e=xe;return()=>Se(e)},documentRef:typeof document<"u"?document:null}),Le=Ip(l,ie,Te),(()=>{let e=jc();if(e&&Jc?.matches(e,He(),!1===l.persistState)||!e&&!Jc)return;Jc?.destroy(),Jc=e?_c(e):null;let t={...Yc};Jc?t.visitorStore=Jc:delete t.visitorStore,Yc=t,ls.setHistoryInternals(Yc)})(),ls.updateConfig(l),ou(),(!0===l.features?.history?.enabled!==v||l.features?.history?.provider!==w||l.getIdentityProof!==x||l.clientToken!==C)&&(fp?.closeHistory({restoreFocus:!1}),(l.getIdentityProof!==x||l.clientToken!==C)&&fp?.discardConversationContinuity(),fp?.installHistoryProvider()),fp?.syncHistoryChromeImpl(),Gp(),Rp()&&!fp&&Qp().catch(()=>{}),$d(St,ls.getMessages(),Le),As(),Dc(),(()=>{let e=Or();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==Pc||e.icon!==vc)&&Hc()})(),cc(ls.isStreaming()),k!==l.contextMentions&&$h();let Y=!0===l.voiceRecognition?.enabled&&!1!==l.voiceRecognition.showButton,X=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),Z=_t(l.voiceRecognition?.provider),ee=X||Z||"custom"===l.voiceRecognition?.dictation?.provider?.type;if(Y&&ee)if(mr&&gr){let e=l.voiceRecognition??{},t=mr.getAttribute("data-state");xs(mr,l,"recording"===t||"processing"===t||"speaking"===t?t:"idle",ls.getVoiceInterruptionMode());let r=e.tooltipText??"Start voice recognition",o=e.showTooltip??!1;"idle"===t&&mr.setAttribute("aria-label",r),gr&&Qa({anchor:mr,trigger:gr,text:()=>mr?.getAttribute("aria-label")??r,enabled:o}),gr.style.display="",mr.disabled=nc()||ls.isStreaming()&&!ac()}else{let e=Cs(l);if(e){mr=e.button,gr=e.wrapper;let t=cr&&cr.parentElement===lr?cr:null;lr?lr.insertBefore(gr,t):Rt?.appendChild(gr),No&&(No.micButton=mr),No?.addListener(mr,"click",Yu),mr.disabled=nc()||ls.isStreaming()&&!ac()}}else mr&&gr&&(gr.style.display="none",!0===l.voiceRecognition?.enabled&&ee||(_t(l.voiceRecognition?.provider)?ls.isVoiceActive()&&ls.toggleVoice():Wu&&_u()));if(sh(),!0===l.attachments?.enabled){if(br&&fr){br.style.display="";let e=l.attachments??{};yr&&(yr.accept=(e.allowedTypes??yn).join(","),yr.multiple=(e.maxFiles??4)>1)}else{let e=l.attachments??{};vr||(vr=st("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),vr.style.display="none",(It.parentElement??Rt).insertBefore(vr,It)),yr||(yr=document.createElement("input"),yr.type="file",yr.accept=(e.allowedTypes??yn).join(","),yr.multiple=(e.maxFiles??4)>1,yr.style.display="none",yr.setAttribute("aria-label","Attach files"),(It.parentElement??Rt).insertBefore(yr,It)),br=st("div","persona-send-button-wrapper"),fr=st("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${na} ${aa}`),fr.type="button",fr.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";fr.style.fontSize="18px",fr.style.lineHeight="1";let r=Ee(t,24,"currentColor",1.5);r?fr.appendChild(r):fr.textContent="📎",fr.addEventListener("click",e=>{e.preventDefault(),yr?.click()}),br.appendChild(fr);let o=e.buttonTooltipText??"Attach file";Qa({anchor:fr,trigger:br,text:()=>fr?.getAttribute("aria-label")??o}),ir?ir.append(br):Rt.appendChild(br),No&&(No.attachmentButton=fr,No.attachmentInput=yr??void 0,No.attachmentPreviews=vr??void 0),!Gr&&yr&&vr&&(Gr=no(),Gr.setPreviewsContainer(vr),No?.addListener(yr,"change",async()=>{Gr&&yr?.files&&(await Gr.handleFileSelect(yr.files),yr.value="")}))}if(xt.querySelector(".persona-attachment-drop-overlay")?.remove(),xt.appendChild(Tp(l.attachments?.dropOverlay)),fr){let e=l.attachments??{},t=e.buttonTooltipText??"Attach file";fr.setAttribute("aria-label",t),fr.textContent="";let r=Ee(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?fr.appendChild(r):fr.textContent="📎",br&&Qa({anchor:fr,trigger:br,text:()=>fr?.getAttribute("aria-label")??t})}}else br&&(br.style.display="none"),Gr&&Gr.clearAttachments(),xt.querySelector(".persona-attachment-drop-overlay")?.remove();let te=l.sendButton?.tooltipText??"Send message",ae=l.sendButton?.showTooltip??!1;vs(Bt,l),ls.isStreaming()||Bt.setAttribute("aria-label",te),lc(),cr&&Qa({anchor:Bt,trigger:cr,text:()=>Bt.getAttribute("aria-label")??te,enabled:ae});let se=new Set([Gr,...Array.from(Dp.values(),e=>e.attachments)]);for(let e of se)e?.updateConfig(ro());"plugins"in t&&Gr?.remountPreviews(vr),tn(),qa();let pe=fa(Xr.getState().activeModeIds,l.composer?.modes);Xr.setActiveModeIds(pe),io().length>0!=!!ho&&Jo(),ho?.render(pe,io()),uo?.repaint(),_o?_o.resolve():Qo();let ue=gi(l,ye());if(Da(),ue){St.style.maxWidth=ue,St.style.marginLeft="auto",St.style.marginRight="auto",St.style.width="100%",Dt.style.maxWidth=ue,Dt.style.marginLeft="auto",Dt.style.marginRight="auto",Dt.style.width="100%";for(let e of[Rt,Mt,vr,Pt])e&&(e.style.maxWidth=ue,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{St.style.maxWidth="",St.style.marginLeft="",St.style.marginRight="",St.style.width="",Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight="",Dt.style.width="";for(let e of[Rt,Mt,vr,Pt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let he=l.statusIndicator??{};if(ur(Pt,Rt,he),pr(Pt,he,ls?.getStatus()??"idle"),ls){let e=ls.getStatus();ht(Pt,(e=>"idle"===e?he.idleText??dt.idle:"connecting"===e?he.connectingText??dt.connecting:"connected"===e?he.connectedText??dt.connected:"error"===e?he.errorText??dt.error:"paused"===e?he.pausedText??dt.paused:"resuming"===e?he.resumingText??dt.resuming:dt[e])(e),he,e)}Pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let be="left"===he.align?"persona-text-left":"center"===he.align?"persona-text-center":"persona-text-right";Pt.classList.add(be),$o(),dc(),en(),ot(),on(l.layout?.slots??{}),Lu()&&nc()&&Bu(),Cu?.refresh(),ln.update(),nm()},open(){ve()&&rc(!0,"api")},close(){ve()&&rc(!1,"api")},toggle(){ve()&&rc(!we,"api")},reconnect(){ls.reconnectNow()},clearChat(){Bu(),Os(),On=!1,i?.clear(),wn(),f.clear(),b.clear(),y.clear(),ls.clearMessages(),l.layout?.topFade&&(Ct.scrollTop=0),Ct.removeAttribute("data-persona-top-fade"),Ls.clear(),Gl();try{localStorage.removeItem(wp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${wp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==wp)try{localStorage.removeItem(l.clearChatHistoryStorageKey),l.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${l.clearChatHistoryStorageKey}`)}catch(e){console.error("[AgentWidget] Failed to clear custom localStorage:",e)}let e=new CustomEvent("persona:clear-chat",{detail:{instanceId:n,timestamp:(new Date).toISOString()}});window.dispatchEvent(e),hl(),V?.clear&&Ji(()=>V.clear(),"[AgentWidget] Failed to clear storage adapter:"),Q={},ie.syncFromMetadata(),Up(ls.getActiveConversationId(),!0,!1),du(),hl(),xo(void 0),go(void 0),js(),ze?.clear(),qe?.reset(),Ve?.update()},setMessage:e=>!(!It||Lu()||ls.isStreaming()||nc()||(!we&&ve()&&rc(!0,"system"),It.value=e,It.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(ls.isStreaming()||Lu()||sc())return!1;let t=e?.trim()||It.value.trim();return!!t&&(!we&&ve()&&rc(!0,"system"),It.value="",It.style.height="auto",Zr(),fu(t,{consumeDraft:!1}),!0)},getComposerState:()=>Xr.getState(),setComposerModes(e){co(function(e,t,r){let o=[];for(let n of e)o.includes(n)||(o=ga(o,n,t,r));return o}(e,so(),l.composer?.modeGroups))},setQuote(e){let t=e?.text?.trim();t&&go({...e,text:t})},clearQuote(){go(void 0)},startDictation:Pu,finishDictation:()=>Ru(),cancelDictation:()=>{let e=ku;return Bu()||e},sendDictation:()=>!(!l.voiceRecognition?.dictation?.showSend||sc())&&Ru(!0),getDictationState:()=>Au??Cu?.getState()??Tu,startVoiceRecognition:()=>!ls.isStreaming()&&!Lu()&&(Eu()&&!l.voiceRecognition?.dictation?.provider&&"runtype"!==l.voiceRecognition?.provider?.type?Pu():_t(l.voiceRecognition?.provider)?(ls.isVoiceActive()||ls.isBargeInActive()||(!we&&ve()&&rc(!0,"system"),Li.manuallyDeactivated=!1,zi(),ls.toggleVoice().then(()=>{Li.active=Ni(),zi(),Oi("user"),Li.active&&Ku()})),!0):!!Wu||!!qu()&&(!we&&ve()&&rc(!0,"system"),Li.manuallyDeactivated=!1,zi(),ju("user"),!0)),stopVoiceRecognition:()=>Lu()?Ru():_t(l.voiceRecognition?.provider)?!(!ls.isVoiceActive()&&!ls.isBargeInActive()||((ls.isBargeInActive()?ls.deactivateBargeIn():ls.toggleVoice()).then(()=>{Li.active=!1,Li.manuallyDeactivated=!0,zi(),Oi("user"),Gu()}),0)):!!Wu&&(Li.manuallyDeactivated=!0,zi(),_u("user"),!0),injectMessage:e=>(!we&&ve()&&rc(!0,"system"),ls.injectMessage(e)),injectAssistantMessage(e){!we&&ve()&&rc(!0,"system");let t=ls.injectAssistantMessage(e);return Me&&(Me=!1,Ie&&=(clearTimeout(Ie),null),Ae()),t},injectUserMessage:e=>(!we&&ve()&&rc(!0,"system"),ls.injectUserMessage(e)),injectSystemMessage:e=>(!we&&ve()&&rc(!0,"system"),ls.injectSystemMessage(e)),injectMessageBatch:e=>(!we&&ve()&&rc(!0,"system"),ls.injectMessageBatch(e)),injectComponentDirective:e=>(!we&&ve()&&rc(!0,"system"),ls.injectComponentDirective(e)),updateComponentProps:(e,t)=>ls.updateComponentProps(e,t),removeComponentMessage:e=>ls.removeComponentMessage(e),injectTestMessage(e){!we&&ve()&&rc(!0,"system"),ls.injectTestEvent(e)},connectStream:async(e,t)=>ls.connectStream(e,t),__pushEventStreamEvent(e){Pe&&(et(),Ze(e.type,e.payload))},showEventStream(){Pe&&Ao()},hideEventStream(){Ke&&Mo()},isEventStreamVisible:()=>Ke,listConversations:e=>ls.listConversations(e),getActiveConversationId:()=>ls.getActiveConversationId(),openConversation:(e,t)=>Jp(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus,busy:t?.busy})),startNewConversation:e=>Jp(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){Yp()},deleteConversation:e=>Jp(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Jp(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Jp(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Jp(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Jp(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Jc;if(!e)return null;let t=await e.get();return e===Jc?t:null},getHistoryIdentityStatus(){let e=fp?.historyProvider;return e?e.getIdentityStatus():Rp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>Rp()?Jp(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){fp?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>tt,showArtifacts(){Jd(l)&&(On=!1,jn=!0,$a(),In?.setMobileOpen(!0))},hideArtifacts(){Jd(l)&&(On=!0,$a())},upsertArtifact:e=>Jd(l)?("panel"===Mn(l.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(On=!1,jn=!0),ls.upsertArtifact(e)):null,selectArtifact(e){Jd(l)&&ls.selectArtifact(e)},clearArtifacts(){Jd(l)&&ls.clearArtifacts()},getArtifacts:()=>ls?.getArtifacts()??[],getSelectedArtifactId:()=>ls?.getSelectedArtifactId()??null,focusInput:()=>!(le&&!we&&!ye()||!It||(It.focus(),0)),revealToolCall(e,t={}){let r=Array.from(Ct.querySelectorAll(".persona-tool-bubble[data-tool-call-id]")).find(t=>t.dataset.toolCallId===e);if(!r)return!1;let o=e=>Array.from(e.querySelectorAll('button[data-expand-header="true"]')).find(t=>t.closest(".persona-tool-bubble")===e),n=e=>{"false"===e?.getAttribute("aria-expanded")&&un(e)},a=[];for(let e=r.parentElement?.closest(".persona-tool-bubble");e;e=e.parentElement?.closest(".persona-tool-bubble"))a.unshift(e);a.forEach(e=>n(o(e)));let s=o(r);!1!==t.expand&&n(s),ci(),td.cancel(),Jl();let i=bn,l=s??r,d=()=>!Ce&&i===bn&&Ct.contains(l),c="function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,p=()=>{let e=Ur(l)-(Ct.clientHeight-l.offsetHeight)/2;return Math.max(0,Math.min(e,Kt(Ct)))},u=()=>{d()&&(c?(vl(),Gs=!0,Ct.scrollTop=p(),Qs=Ct.scrollTop,Gs=!1):ed(Ct,p,200,d))};window.clearTimeout(hn),u(),hn=window.setTimeout(()=>{hn=void 0,u()},200);let h=t.highlightMs??2e3;if(h>0){let e=r.dataset.messageId;window.clearTimeout(gn.get(e)),gn.set(e,window.setTimeout(()=>{gn.delete(e),vn()},h)),r.setAttribute("data-persona-revealed","")}return!0},async resolveApproval(e,t,r){let o=ls.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!o?.approval)throw Error(`Approval not found: ${e}`);if(!dr(o.approval))return ls.resolveApproval(o.approval,t,r);ls.resolveWebMcpApproval(o.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Ts();let r=ls?ls.getMessages():[];cs=t,ps=!0,us=fs(r),hs=bs(r),As(r)})(e)},clearFollowUpSuggestions(){Ts()},getMessages:()=>ls.getMessages(),getStatus:()=>ls.getStatus(),getPersistentMetadata:()=>({...Q}),updatePersistentMetadata(e){oe(e)},on:(e,t)=>U.on(e,t),off(e,t){U.off(e,t)},isOpen:()=>ve()&&we,isVoiceActive:()=>Li.active,toggleReadAloud(e){ls.toggleReadAloud(e)},stopReadAloud(){ls.stopSpeaking()},getReadAloudState:e=>ls.getReadAloudState(e),onReadAloudChange:e=>ls.onReadAloudChange(e),getState:()=>({open:ve()&&we,launcherEnabled:le,voiceActive:Li.active,streaming:ls.isStreaming()}),showCSATFeedback(e){Gh(()=>yp({onSubmit:async(t,r)=>{ls.isClientTokenMode()&&await ls.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},showNPSFeedback(e){Gh(()=>vp({onSubmit:async(t,r)=>{ls.isClientTokenMode()&&await ls.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},submitCSATFeedback:async(e,t)=>ls.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>ls.submitNPSFeedback(e,t),destroy(){Ce=!0,ke(),u.destroy(),ln.destroy(),e.removeEventListener("click",dn),cp(),Ua.forEach(e=>e()),null!=Zc&&(clearInterval(Zc),Zc=null),i?.destroy(),s?.destroy(),wn(),f.clear(),b.clear(),y.clear(),U.dispose(),gt.remove(),vt?.remove(),mh?.destroy(),gh?.remove(),ds&&Zt.removeEventListener("click",ds)}};if((r?.debugTools||l.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:tm,getMessages:tm.getMessages,getStatus:tm.getStatus,getMetadata:tm.getPersistentMetadata,updateMetadata:tm.updatePersistentMetadata,clearHistory:()=>tm.clearChat(),setVoiceActive:e=>e?tm.startVoiceRecognition():tm.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Ua.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<"u"){let e=(e,t)=>{let r=e=>{let r=e.detail;r?.instanceId&&r.instanceId!==n||t(r)};window.addEventListener(e,r),Ua.push(()=>window.removeEventListener(e,r))};e("persona:focusInput",()=>tm.focusInput()),Pe&&(e("persona:showEventStream",()=>tm.showEventStream()),e("persona:hideEventStream",()=>tm.hideEventStream())),e("persona:showHistory",()=>tm.showHistory()),e("persona:hideHistory",()=>tm.hideHistory()),e("persona:showArtifacts",()=>tm.showArtifacts()),e("persona:hideArtifacts",()=>tm.hideArtifacts()),e("persona:upsertArtifact",e=>{e?.artifact&&tm.upsertArtifact(e.artifact)}),e("persona:selectArtifact",e=>{"string"==typeof e?.id&&tm.selectArtifact(e.id)}),e("persona:clearArtifacts",()=>tm.clearArtifacts())}let rm=function(e){if(!e)return null;let t=!0===e?{}:e;return{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}}(l.persistState);if(rm&&ve()){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}}(rm.storage),r=`${rm.keyPrefix}widget-open`,o=`${rm.keyPrefix}widget-voice`,a=`${rm.keyPrefix}widget-voice-mode`;if(t){let s=rm.persist?.openState&&"true"===t.getItem(r),i=rm.persist?.voiceState&&"true"===t.getItem(o),l=rm.persist?.voiceState&&"true"===t.getItem(a);if(s&&(mh?.setPanelOpen(!0,"auto"),setTimeout(()=>{tm.open(),setTimeout(()=>{if(i||l)tm.startVoiceRecognition();else if(rm.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),rm.persist?.openState&&(U.on("widget:opened",()=>{t.setItem(r,"true")}),U.on("widget:closed",()=>{t.setItem(r,"false")})),rm.persist?.voiceState&&(U.on("voice:state",e=>{t.setItem(o,e.active?"true":"false")}),U.on("user:message",e=>{t.setItem(a,e.viaVoice?"true":"false")})),rm.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(o),t.removeItem(a)},s=t=>{t.detail?.instanceId===n&&e()};window.addEventListener("persona:clear-chat",s),Ua.push(()=>{window.removeEventListener("persona:clear-chat",s)})}}}ee&&ve()&&(mh?.setPanelOpen(!0,"auto"),setTimeout(()=>{tm.open()},0)),Yd(),H=()=>{ls&&(Vs++,Ls.clear(),$d(St,ls.getMessages(),Le))},ls.getMessages().length>0&&Rd(),q=H;let om=Lt(()=>{H?.(),Et()?.updateInlineArtifactBlocks(St,Fn.artifacts,{suppressTransition:!0}),$a()});Ua.push(om);let nm=()=>{let t=Vt(l);Yh||t.push(...r?.preparation??[]),Rp()&&!fp&&t.push(Qp()),t.length||e.hasAttribute("data-persona-preparing")?u.prepare(t,()=>{_o||Qo(),ho||Jo(),g(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),H?.(),Yh=!0}):Yh=!0};return nm(),tm},Bp=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},Rp=(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"},Pp=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=""},Np=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Pp(e)},$p=e=>{e.style.transition=""},Wp=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=""},Hp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Dp=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Fp=(e,t,r,o)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=o):(e.style.padding="",e.style.background="",e.style.boxSizing="")},Op=(e,t)=>il(t)?((e,t)=>{let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if("BODY"===n||"HTML"===n)throw 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),o.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=di(e),r=t.components?.panel,o=(e,r)=>null==e||""===e?r:Us(t,e)??e;return{inset:o(r?.inset,Es),canvasBackground:o(r?.canvasBackground,Ls)}})(t):null};g();let f=()=>{((e,t,r,o,n,a,s,i)=>{let l=dl(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))})(e,t,r,o,d),((e,t,r,o,n,a)=>{let s=a?t:e;"left"===n?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)})(e,t,r,o,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",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.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)e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Wp(t),$p(o),Np(o),Hp(r),Dp(n,o),Fp(o,!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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(a?.launcher?.zIndex??1e5),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");else if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Np(o),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(o,l.maxHeight),Fp(o,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",Wp(t),$p(o),Hp(r),Dp(n,o);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=l.width,o.style.maxWidth=l.width,o.style.minWidth=l.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=a,o.style.transform=d,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2","right"===l.side?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",$p(o),Pp(o),Dp(n,o);let a=Bp(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`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=l.width,o.style.minWidth=l.width,o.style.maxWidth=l.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Wp(t),Pp(o),Hp(r),Dp(n,o);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(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${i}`,o.style.width=i,o.style.maxWidth=i,o.style.minWidth=i,o.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(o,l.maxHeight),o.style.overflow=a||u?"hidden":"visible",o.style.transition=d,a){o.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Bp(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;n.style.width=t,n.style.minWidth=t,n.style.maxWidth=t,n.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},b=null,y=()=>{b?.(),b=null,!0===t?.launcher?.detachedPanel&&"auto"===t?.colorScheme&&(b=mi(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===dl(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 o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),n&&!a&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(!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,dl(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===dl(t).reveal?(i.appendChild(l),i.appendChild(d),s.appendChild(i)):(s.appendChild(l),s.appendChild(d)),w(),y(),{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(),y()},destroy(){x?.removeEventListener("resize",C),b?.(),b=null,h(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Rp(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Rp(r,e)},destroy(){r.remove()}}})(e,t),zp=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let o=r.cloneNode(!0),n=new Promise((e,t)=>{o.onload=()=>e(),o.onerror=()=>t(Error("Unable to load the widget stylesheet"))});return e.insertBefore(o,e.firstChild),n},qp=[],jp=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),_p=new Set(["button","a","input","select","textarea","details","summary"]),Up=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Vp=/\b(product|card|item|listing|result)\b/i,Kp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function Qp(e){let t="string"==typeof e.className?e.className:"";if(Vp.test(t)||e.id&&Vp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Vp.test(r.value))return!0}return!1}function Jp(e){return Kp.test((e.textContent??"").trim())}function Gp(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 Yp(e){let t=e.match(Kp);return t?t[0]:null}function Xp(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 Zp(e){return Qp(e)&&Jp(e)&&(Gp(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function eu(e){return!Qp(e)||Jp(e)||!Gp(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let tu=[{id:"commerce-card",scoreElement:e=>Zp(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||Kp.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===Zp(e))return null;let{title:r,href:o}=Xp(e),n=Yp((e.textContent??"").trim())??Yp(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[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>eu(e),formatSummary(e,t){if(0===eu(e))return null;let{title:r,href:o}=Xp(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function ru(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let ou=["data-testid","data-product","data-action","data-id","data-name","data-type"];function nu(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||_p.has(t)||r&&Up.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function au(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 su(e){let t={},r=e.id;r&&(t.id=r);let o=e.getAttribute("href");o&&(t.href=o);let n=e.getAttribute("aria-label");n&&(t["aria-label"]=n);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let 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 o=e.attributes[r];o.name.startsWith("data-")&&(t[o.name]=o.value)}return t}function iu(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${ru(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of ou){let o=e.getAttribute(r);if(o){let n=`${t}[${r}="${ru(o)}"]`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let o=`${t}.${r.map(e=>ru(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${o}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function lu(e,t){let r=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:iu(e),tagName:r,text:o,role:e.getAttribute("role"),interactivity:nu(e),attributes:su(e)}}function du(e,t,r,o){let n=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,o);r>0&&(n+=r,s.formatSummary&&!a&&(a=s))}return{score:n,formattingRule:a}}function cu(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}let pu={components:{panel:{borderRadius:"0",shadow:"none"}}},uu={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:is},welcome:{title:"Welcome to our shop!",subtitle:"I can help you find products and answer questions"},copy:{inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestions:{starters:{items:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],variant:"chip",placement:"composer",overflow:"wrap",maxItems:4}}}},hu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:pu}},mu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:pu}},gu={shop:uu,minimal:hu,fullscreen:mu},fu=typeof document<"u"&&(document.currentScript?.src??"").replace(/^https:\/\/cdn\.runtype\.com\/persona\/latest\//,"https://cdn.runtype.com/persona/4.35.1/")||null,bu=(e,t=`host ${e} alongside it`)=>{let r=0;return()=>{let o=fu?.replace(/index\.global\.js($|\?)/,`${e}$1`);return o&&o!==fu?import(`${o}${r?`#retry-${r}`:""}`).catch(e=>{throw r++,e}):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${fu??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))}};return(e=>{or=e})(bu("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),rt(bu("markdown-parsers.js")),zr(bu("client-stream.js")),en(bu("client-history.js")),$t(bu("ui-extras.js")),un(bu("session-actions.js")),up(bu("history-shell.js")),(e=>{zn=e})(bu("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),Ba(bu("context-mentions.js")),$a(bu("context-mentions-inline.js")),sp(bu("history-view.js")),tl(bu("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),zd(bu("approval-ui.js")),zt(bu("voice-runtime.js")),oo(bu("voice-client-tools.js")),It(bu("artifacts-ui.js")),Ec(bu("forms-ui.js")),ie(bu("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),Zr(bu("webmcp-runtime.js")),Un(bu("session-reconnect.js")),Vd(bu("event-stream-view.js")),Ne(bu("composer-actions-runtime.js")),Qe(bu("dictation-runtime.js")),an(bu("background-runtime.js")),zc(bu("config-diagnostics.js")),J(bu("activity-ui.js")),ze(bu("loading-label-runtime.js")),Qr(bu("client-dispatch.js")),te(bu("turn-activity-ui.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=jo,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=qo,e.ASK_USER_QUESTION_TOOL_NAME=lo,e.AgentWidgetClient=n,e.AgentWidgetSession=c,e.AttachmentManager=p,e.BrowserSpeechEngine=s,e.DEFAULT_COMPONENTS=js,e.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH="440px",e.DEFAULT_FLOATING_LAUNCHER_WIDTH=is,e.DEFAULT_PALETTE=Hs,e.DEFAULT_SEMANTIC=Os,e.DEFAULT_WIDGET_CONFIG=hs,e.HistoryProviderError=a,e.PRESETS=gu,e.PRESET_FULLSCREEN=mu,e.PRESET_MINIMAL=hu,e.PRESET_SHOP=uu,e.ReadAloudController=i,e.SUGGEST_REPLIES_CLIENT_TOOL=Wo,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=$o,e.SUGGEST_REPLIES_TOOL_NAME=No,e.THEME_ZONES={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble","operator-message":"Operator 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"},e.VERSION=Go,e.WEBMCP_TOOL_PREFIX=Zt,e.applyFeaturePreferences=Sc,e.applyThemeVariables=ui,e.attachHeaderToContainer=Tl,e.buildComposer=$l,e.buildDefaultHeader=El,e.buildHeader=Il,e.buildHeaderWithLayout=Pl,e.buildMinimalHeader=Ll,e.builtInClientToolsForDispatch=_o,e.canonicalArtifactDisplayMode=Sn,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",n=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??tu;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:o,maxTextLength:n,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],o=new Set,n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=n.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(jp.has(s)){a=n.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=n.nextNode();continue}}catch{}if(e.visibleOnly&&!au(t)){a=n.nextNode();continue}let i=lu(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=n.nextNode();continue}o.has(i.selector)||(o.add(i.selector),r.push(i))}a=n.nextNode()}let s=[],i=[];for(let e of r)"static"===e.interactivity?i.push(e):s.push(e);return[...s,...i].slice(0,e.maxElements)}(t,r):function(e,t){let r={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,n=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&n.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(jp.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!au(t)){i=s.nextNode();continue}let d=lu(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||o.has(d.selector)){i=s.nextNode();continue}o.add(d.selector);let{score:u,formattingRule:h}=du(t,d,e.rules,r);n.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}n.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-o});let l=[];for(let t of n){if(l.length>=e.maxElements)break;cu(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),o=+("static"===t.enriched.interactivity);return r===o?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-o}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let o=e.formattingRule.formatSummary(e.el,e.enriched,r);o&&(t=o)}let o={...e.enriched};return t&&(o.formattedSummary=t),o})}(t,r):[]},e.componentRegistry=ft,e.createActionManager=Xc,e.createAgentExperience=Lp,e.createAskUserQuestionBubble=(e,t)=>{let r=st("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"),So(r,t);let o=st("span","persona-ask-stub-label"),{complete:n}=wo(e);return o.textContent=n?"Awaiting your response…":"Preparing options…",r.appendChild(o),r},e.createBubbleWithLayout=(e,t,r,o,n,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}):od(e,t,r,o,0,a)},e.createCSATFeedback=yp,e.createComboButton=gt,e.createComponentMiddleware=function(){let e=Rn();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=Rn,e.createDefaultSanitizer=Br,e.createDirectivePostprocessor=e=>{let t=Cr(e);return e=>{let r=[],o=Tr(e,r),n=t(o);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Mr(t)}"></div>`;n=n.replace(r,o)}),n}},e.createDropdownMenu=ct,e.createFlexibleJsonStreamParser=e=>{let t=null,o=0,n=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?Uo(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?Uo(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 a=e.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(e.length<=o)return null===t?null:{text:t,raw:e};try{let o=(0,r.parse)(e,r.STR|r.OBJ),a=n(o);null!==a&&(t=a)}catch{}return o=e.length,{text:t||"",raw:e}},close:()=>{}}},e.createIconButton=pt,e.createImagePart=function(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}},e.createJsonStreamParser=Qo,e.createLabelButton=ut,e.createLocalStorageAdapter=rp,e.createMarkdownProcessor=xr,e.createMarkdownProcessorFromConfig=Cr,e.createMessageActions=rd,e.createNPSFeedback=vp,e.createPlainTextParser=Vo,e.createRegexJsonParser=Ko,e.createSplitButton=mt,e.createStandardBubble=od,e.createTextPart=fn,e.createTheme=Js,e.createThemeObserver=mi,e.createToggleGroup=ht,e.createTypingIndicator=Kl,e.createWidgetHostLayout=Op,e.createXmlParser=Jo,e.defaultActionHandlers=Gc,e.defaultJsonActionParser=Qc,e.defaultParseRules=tu,e.detectColorScheme=ii,e.directivePostprocessor=e=>{let t=[],r=Tr(e,t),o=kr(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Mr(t)}"></div>`;o=o.replace(r,n)}),o},e.ensureAskUserQuestionSheet=Ro,e.escapeHtml=Ar,e.extractComponentDirectiveFromMessage=Wn,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>r(Error("Failed to read file")),o.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",o=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&o.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let n={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||n[t.interactivity].push(t);if(n.clickable.length>0){let e=n.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);o.push(`Interactive elements:\n${e.join("\n")}`)}if(n.navigable.length>0){let e=n.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);o.push(`Navigation links:\n${e.join("\n")}`)}if(n.input.length>0){let e=n.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);o.push(`Form inputs:\n${e.join("\n")}`)}if(n.static.length>0){let e=n.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);o.push(`Content:\n${e.join("\n")}`)}return o.join("\n\n")},e.generateAssistantMessageId=io,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=iu,e.generateUserMessageId=so,e.getActiveTheme=di,e.getAgentWidgetHandles=()=>[...qp],e.getColorScheme=li,e.getDisplayText=function(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")},e.getHeaderLayout=Rl,e.getImageParts=function(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)},e.getPreset=function(e){return gu[e]},e.hasComponentDirective=$n,e.hasImages=gn,e.headerLayouts=Bl,e.initAgentWidget=e=>{let t,r=(e=>{if(typeof window>"u"||typeof document>"u")throw Error("Chat widget can only be mounted in a browser environment");if("string"==typeof e){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e})(e.target),o=!0===e.useShadowDom,n=r.ownerDocument,a=r.id||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,s=e.config,i=Vc(s),l=Op(r,s),d=[],c=!1,p=!1,u=()=>{let r=t;r.ready.then(()=>{c||p||r!==t||(p=!0,e.onChatReady?.())},()=>{})},h=e=>e(),m=new Set,g=(e,t)=>{let r,s=!(t?.launcher?.enabled??1)||il(t),i=n.createElement("div");if(i.setAttribute("data-persona-root","true"),s&&(i.style.height="100%",i.style.display="flex",i.style.flexDirection="column",i.style.flex="1",i.style.minHeight="0",i.style.minWidth="0"),o){let t=e.attachShadow({mode:"open"});t.appendChild(i),r=zp(t,n)}else e.appendChild(i),zp(e,n);return i.setAttribute("data-persona-instance",a),{mount:i,stylesReady:r}},f=()=>{l.syncWidgetState(t.getState())},b=()=>{let{mount:r,stylesReady:o}=g(l.host,s);t=Lp(r,s,{debugTools:e.debugTools,registerHostMove:e=>{h=e},diagnostics:i,preparation:o?[o]:[]}),m.forEach(e=>e.bind()),d.forEach(e=>e()),d=[t.on("widget:opened",f),t.on("widget:closed",f)],f(),u()},y=()=>{d.forEach(e=>e()),d=[],t.destroy()};b();let v=e=>{y(),l.destroy(),l=Op(r,e),s=e,b()},w=new Proxy({moveTo(e,t){if(c)throw Error("Cannot move a destroyed widget");if("direct"!==l.mode)throw Error("Docked widgets cannot be moved");let o="string"==typeof e?n.querySelector(e):e;if(!(o instanceof HTMLElement)||o.ownerDocument!==n||o.getRootNode()!==n||l.host.getRootNode()!==n||l.host.contains(o))throw Error("Invalid widget move target: expected a connected light-DOM container in the same document");o!==r&&(h(()=>function(e,t,r){let o=e.ownerDocument,n=o.activeElement;for(;n?.shadowRoot?.activeElement;)n=n.shadowRoot.activeElement;let a=t=>{for(;t;){if(e.contains(t))return!0;let r=t.getRootNode();t=r instanceof ShadowRoot?r.host:null}return!1},s=r&&a(n)?n:null,i=s,l=i?.selectionStart,d=i?.selectionEnd,c=i?.selectionDirection,p=(s?.getRootNode())?.getSelection?.()??o.getSelection(),u=p?.anchorNode,h=p?.focusNode,m=r&&a(u??null)&&a(h??null)?[p.anchorOffset,p.focusOffset]:null,g=t;"function"==typeof g.moveBefore?g.moveBefore(e,null):t.appendChild(e),s?.focus({preventScroll:!0}),i&&null!=l&&null!=d&&i.setSelectionRange(l,d,c??void 0),m&&u&&h&&p.setBaseAndExtent(u,m[0],h,m[1])}(l.host,o,!1!==t?.preserveFocus)),r=o)},on(e,r){if(c)return()=>{};let o=[...m].find(t=>t.event===e&&t.handler===r);if(o)return o.unsubscribe;let n=()=>{},a={event:e,handler:r,bind:()=>{n=t.on(e,r)},unsubscribe:()=>{n(),m.delete(a)}};return m.add(a),a.bind(),a.unsubscribe},off(e,t){for(let r of m)r.event===e&&r.handler===t&&r.unsubscribe()},update(e){Kc(i,e);let r=Wc(s??{},e),o=il(s),n=il(r),a=ll(s),d=ll(r);o!==n||a!==d?v(r):(s=r,l.updateConfig(s),t.update(e),u(),f())},destroy(){if(c)return;c=!0,y(),m.forEach(e=>e.unsubscribe()),l.destroy();let t=qp.indexOf(w);-1!==t&&qp.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,o){if("host"===r)return l.host;if(r in e)return Reflect.get(e,r,o);let n=t[r];return"function"==typeof n?n.bind(t):n}});return qp.push(w),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w},e.isAskUserQuestionMessage=yo,e.isComponentDirectiveType=function(e){return"object"==typeof e&&!!e&&"component"in e&&"string"==typeof e.component&&"props"in e&&"object"==typeof e.props},e.isDockedMountMode=il,e.isHistoryProviderError=function(e){return e instanceof a},e.isSuggestRepliesMessage=Ho,e.isWebMcpToolName=ir,e.isWelcomeVisible=xd,e.latestAgentSuggestions=Fo,e.listRegisteredStreamAnimations=()=>Array.from($i.keys()),e.loadMarkdownParsers=ot,e.markdownPostprocessor=kr,e.mergeWithDefaults=gs,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=kn,e.onMarkdownParsersReady=nt,e.parseAskUserQuestionPayload=wo,e.parseSuggestRepliesPayload=Do,e.parseWidgetPreferenceSlice=vc,e.pickBestVoice=Fn,e.pluginRegistry=Rc,e.preprocessStreamingMarkdown=wr,e.registerIcons=e=>{for(let[t,r]of Object.entries(e))Ce.set(t,r);Ie()>0&&!ke&&Me(!1)},e.registerStreamAnimationPlugin=Hi,e.removeAskUserQuestionSheet=Po,e.renderComponentDirective=Pn,e.renderLoadingIndicatorWithFallback=Ql,e.renderLucideIcon=Ee,e.resolveArtifactDisplay=An,e.resolveArtifactDisplayMode=Mn,e.resolveConfigPreferences=kc,e.resolveDockConfig=dl,e.resolveSanitizer=Rr,e.resolveTokens=Vs,e.resolveWelcomeConfig=bd,e.stripWebMcpPrefix=sr,e.themeToCssVariables=ei,e.unregisterStreamAnimationPlugin=e=>{Ni.some(t=>t.name===e)||$i.delete(e)},e.validateImageFile=function(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(", ")}`}},e.validateTheme=Ks,e}({});
|
|
8
8
|
//# sourceMappingURL=index.global.js.map
|