@runtypelabs/persona 4.32.0 → 4.32.2
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.cjs +1 -1
- package/dist/activity-ui.js +1 -1
- package/dist/{chunk-BrptyKSq.js → chunk-B3l7TOOv.js} +1 -1
- package/dist/{chunk-CkE90FtA.js → chunk-B4ecQzeK.js} +1 -1
- package/dist/{chunk-CzZBmTLd.js → chunk-B9Zu-wrk.js} +1 -1
- package/dist/chunk-BNE40cEG.js +1 -0
- package/dist/{chunk-BWCo3rCm.js → chunk-B_H0l3u2.js} +1 -1
- package/dist/{chunk-MdlQetfC.js → chunk-BbXc58OA.js} +1 -1
- package/dist/{chunk-DE0cSmku.js → chunk-BpjtKnGI.js} +1 -1
- package/dist/{chunk-CHAwCqpk.js → chunk-CdpVP6LZ.js} +1 -1
- package/dist/{chunk-FEzOcZof.js → chunk-CjkechxR.js} +1 -1
- package/dist/{chunk-DZg9bFK6.js → chunk-D0tcIZJM.js} +1 -1
- package/dist/{chunk-Cb7qy0c7.js → chunk-DNdeIFJ6.js} +1 -1
- package/dist/{chunk-VaT6xry9.js → chunk-DTGvDx8o.js} +1 -1
- package/dist/{chunk-ezlpsYGk.js → chunk-DVZ8ri1z.js} +1 -1
- package/dist/{chunk-DhedQnek.js → chunk-DgZZqy14.js} +1 -1
- package/dist/{chunk-C2IbR39s.js → chunk-UWMfWW2a.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/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/theme-editor-preview.cjs +4 -4
- package/dist/theme-editor-preview.js +4 -4
- package/dist/theme-editor.cjs +1 -1
- package/dist/theme-editor.js +1 -1
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.js +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/index-global.ts +2 -1
- package/src/install.test.ts +6 -5
- package/src/install.ts +2 -2
- package/src/launcher-global.ts +2 -1
- package/src/session.test.ts +41 -0
- package/src/session.ts +14 -7
- package/src/styles/widget.css +12 -0
- package/src/utils/brand.test.ts +50 -0
- package/src/utils/brand.ts +6 -2
- package/src/utils/cdn-release.test.ts +20 -0
- package/src/utils/cdn-release.ts +14 -0
- package/src/utils/tokens.ts +2 -1
- package/src/utils/tool-activity-summary.test.ts +8 -0
- package/src/utils/tool-activity-summary.ts +2 -1
- package/dist/chunk-DDAwu89-.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,n,o,a,s,i,l,d,c,p,u,h=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),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 n=t?`${t}.${e}`:e;return g(r)?f(r,n):[n]})}function b(e,t){let r=t.split(".");for(let t=0;t<r.length;t++){let n=r[t];if(!g(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(void 0===(e=e[n])||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 n=t[m];if(n)return n;let o=new Set(y(e,r));for(let e of r){let r=b(t,e);"clear"===r&&o.delete(e),"explicit"===r&&o.add(e)}return[...o]}function C(e,t,r){let n={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),o=n;for(let e of t.slice(0,-1)){let t=o[e];if(!g(t)){o=void 0;break}o[e]={...t},o=o[e]}o&&delete o[t[t.length-1]]}return n}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,n]of Object.entries(t)){let t=r[e];r[e]=S(t)&&S(n)?k(t,n):n}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 n=/^rgba?\(\s*([^)]*)\)$/i.exec(t);if(!n)return;let o=n[1].trim().split(/\s*[,/]\s*|\s+/);if(4===o.length&&/^(?:1(?:\.0+)?|100%)$/.test(o[3])&&o.pop(),3!==o.length)return;let a=o.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 n=t/255;return e+(n<=.04045?n/12.92:((n+.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",B=e=>{let t=A(e?.neutral);return t?M(t)<.18?"dark":"light":void 0},L=(e,t)=>t.split(" ").map(t=>`${e}.${t}`),R=[...L("launcher","closeButtonSize closeButtonColor closeButtonBackgroundColor closeButtonBorderWidth closeButtonBorderColor closeButtonBorderRadius closeButtonPaddingX closeButtonPaddingY"),...L("launcher.clearChat","size iconColor backgroundColor borderWidth borderColor borderRadius paddingX paddingY"),...L("sendButton","size iconSize iconStrokeWidth backgroundColor textColor borderWidth borderColor paddingX paddingY"),...L("voiceRecognition","iconSize iconColor backgroundColor borderColor borderWidth paddingX paddingY recordingIconColor recordingBackgroundColor recordingBorderColor processingIconColor processingBackgroundColor processingBorderColor speakingIconColor speakingBackgroundColor speakingBorderColor"),...L("toolCall","shadow backgroundColor borderColor borderWidth borderRadius headerBackgroundColor headerTextColor headerPaddingX headerPaddingY contentBackgroundColor contentTextColor contentPaddingX contentPaddingY codeBlockBackgroundColor codeBlockBorderColor codeBlockTextColor toggleTextColor labelTextColor loadingAnimationColor loadingAnimationSecondaryColor loadingAnimationDuration"),...L("approval","backgroundColor borderColor shadow titleColor descriptionColor reasonColor approveButtonColor approveButtonTextColor denyButtonColor denyButtonTextColor parameterBackgroundColor parameterTextColor"),...L("features.askUserQuestion.styles","sheetBackground sheetBorder sheetShadow pillBackground pillBackgroundSelected pillTextColor pillTextColorSelected pillBorderRadius customInputBackground"),...L("features.artifacts.layout","paneBackground panePadding paneBorderRadius paneShadow chatShadow paneBorder paneBorderLeft unifiedSplitOuterRadius documentToolbarIconColor documentToolbarToggleActiveBackground documentToolbarToggleActiveBorderColor documentToolbarToggleActiveColor tabFadeSize"),...L("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(n=>{W(e,n)!==t.values[n]&&("explicit"===b(e,n)?r.add(n):r.delete(n))}),[...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)),z=(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)},O=(e,t)=>z(e,t)?W(e,t):void 0,q=(e,t,r)=>{let n=e,o=r??n?.colorScheme??B(n?.brand)??"light",a="dark"===o||"auto"===o&&(typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches);return z(e,`theme.components.${t}`)||a&&z(e,`darkTheme.components.${t}`)},j={defaultProvenance:y,suppliedPath:b,hasExplicitThemeStyle:q,getExplicitLegacyStyle:O},_=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,n=null,o=null,a=null;return{setLoader:e=>{n=e,r&&(o=null,a=null)},load:()=>{if(o)return Promise.resolve(o);if(a)return a;let e=n??t;try{return a=e().then(e=>(o=e,e)).catch(e=>{throw a=null,e}),a}catch(e){return Promise.reject(e)}},provide:e=>{o=e},getSync:()=>o}},{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,ne=()=>Promise.all([Z(),G()]).then(([e,t])=>(Object.assign(t.turnUi,e),re=e)),oe=(e,t=24,r="currentColor",n=2)=>{if(!Array.isArray(e))return null;let o=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(n),"stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"}))o.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 n=document.createElementNS("http://www.w3.org/2000/svg",e);for(let[e,t]of Object.entries(r))"stroke"!==e&&n.setAttribute(e,String(t));o.appendChild(n)}return o},{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 n=Ce.get(r);if(!n)continue;Se.delete(t),e++;let o=oe(n);if(o)for(t.removeAttribute("data-persona-icon-pending");o.firstChild;)t.appendChild(o.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",n=2)=>{let o=Ce.get(e);if(o)return oe(o,t,r,n);if(xe.includes(e)){let o=((e,t,r)=>{let n=oe([],e,t,r);return n.setAttribute("data-persona-icon-pending","true"),n})(t,r,n);return Se.size>=500&&Se.delete(Se.keys().next().value),Se.set(o,e),Te()?.catch(e=>{console.warn("[Persona] Failed to load the icons-extra chunk",e)}),o}return console.warn(`Unknown Persona icon "${e}". Use registerIcons().`),null},{setLoader:Be,load:Le,provide:Re,getSync:Pe}=_({fallbackImport:()=>import("@runtypelabs/persona/composer-actions-runtime")}),Ne=Be,$e=Le,We=Pe,{setLoader:He,load:De,provide:Fe,getSync:ze}=_({fallbackImport:()=>import("@runtypelabs/persona/loading-label-runtime")}),Oe=He,qe=De,je=ze,{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,nt=()=>{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))},ot=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 n=document.createElement(e);if(t.className&&(n.className=t.className),void 0!==t.text&&(n.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);if(t.style){let e=n.style,r=t.style;for(let t of Object.keys(r)){let n=r[t];null!=n&&(e[t]=n)}}let o=r.filter(e=>null!=e);return o.length>0&&n.append(...o),n},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:n,position:o="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"===o?i.style.right="0":i.style.left="0");for(let e of t){if(e.dividerBefore){let e=document.createElement("hr");i.appendChild(e)}let t=document.createElement("button");if(t.type="button",t.setAttribute("role","menuitem"),t.setAttribute("data-dropdown-item-id",e.id),e.destructive&&t.setAttribute("data-destructive",""),e.icon){let r=Ee(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let n=document.createElement("span");n.textContent=e.label,t.appendChild(n),t.addEventListener("click",t=>{t.stopPropagation(),c(),r(e.id)}),i.appendChild(t)}let l=null;function d(){let e=i.classList.contains("persona-hidden");(function(){if(!a)return;let e=n.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===o?(i.style.right=window.innerWidth-e.right+"px",i.style.left="auto"):(i.style.left=`${e.left}px`,i.style.right="auto")})(),i.classList.remove("persona-hidden"),e&&s?.(!0),requestAnimationFrame(()=>{let e=e=>{!i.contains(e.target)&&!n.contains(e.target)&&c()};document.addEventListener("click",e,!0),l=()=>document.removeEventListener("click",e,!0)})}function c(){let e=!i.classList.contains("persona-hidden");i.classList.add("persona-hidden"),l?.(),l=null,e&&s?.(!1)}return a&&a.appendChild(i),{element:i,show:d,hide:c,toggle:function(){i.classList.contains("persona-hidden")?d():c()},destroy:function(){c(),i.remove()}}}function pt(e){let{icon:t,label:r,size:n,strokeWidth:o,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,n??16,"currentColor",o??2);if(c&&d.appendChild(c),i&&d.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))d.setAttribute(e,t);return d}function ut(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==n&&(d+=" persona-label-btn--"+n),d+=" persona-label-btn--"+o,s&&(d+=" "+s);let c=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:n,className:o}=e,a=st("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=r,i=[];function l(){for(let e of i)e.btn.setAttribute("aria-pressed",e.id===s?"true":"false")}for(let e of t){let t;e.icon?t=pt({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),n(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(),n(e.id)})),t.setAttribute("aria-pressed",e.id===s?"true":"false"),i.push({id:e.id,btn:t}),a.appendChild(t)}return{element:a,setSelected:function(e){s=e,l()}}}function mt(e){let{label:t,icon:r,iconSize:n,iconOnly:o,menuItems:a,onSelect:s,onPrimary:i,position:l="bottom-left",portal:d,chevronLabel:c="More options",chevronIconSize:p,className:u,primaryClassName:h,chevronClassName:m}=e,g=st("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},b=o&&r?pt({...f,icon:r,size:n??14}):ut({...f,icon:r,iconSize:n??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:n,onSelect:o,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:n,onSelect:e=>{d.setAttribute("aria-expanded","false"),o(e)},anchor:d,position:a,portal:s});return s||d.appendChild(u.element),d.addEventListener("click",e=>{if(e.stopPropagation(),"true"===d.getAttribute("data-persona-menu-locked"))return;let t=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",t?"false":"true"),u.toggle()}),d.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),d.click())}),{element:d,setLabel:e=>{c.textContent=e,d.setAttribute("aria-label",e)},open:()=>{d.setAttribute("aria-expanded","true"),u.show()},close:()=>{d.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let e=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",e?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),d.remove()}}}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):ot(()=>{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},Bt=e=>kt?()=>{}:(At.add(e),()=>{At.delete(e)}),{setLoader:Lt,load:Rt,provide:Pt,getSync:Nt}=_({fallbackImport:()=>import("./ui-extras-entry")}),$t=Lt,Wt=Rt,Ht=Nt,{setLoader:Dt,load:Ft,getSync:zt}=_({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Ot=Dt,qt=Ft,jt=zt;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,n)=>{e&&!r&&t.push(n())};r(!0,We(),$e),r(!0,at(),nt);let n=!0===e.turnActivity?.enabled;r(n,re,ne);let o=n||!1!==e.features?.showToolCalls||!1!==e.features?.showReasoning;r(o,Y(),G),r(o||"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"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function Qt(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Jt(e,t){return Qt(e)-e.scrollTop<=t}function Gt(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 Yt(){let e=null,t=()=>{null!==e&&cancelAnimationFrame(e),e=null};return{get active(){return null!==e},cancel:t,start(r,n,o,a,s,i=()=>!0){t();let l=r.scrollTop,d=performance.now();if(Math.abs(n()-l)<1)return r.scrollTop=n(),a(),void s();let c=p=>{if(!i())return t(),void s();let u=Math.min(Math.max(0,(p-d)/o),1);r.scrollTop=l+(n()-l)*(1-(1-u)**3),a(),u<1?e=requestAnimationFrame(c):(e=null,s())};e=requestAnimationFrame(c)}}}function Xt(e,t,r,n,o){let a,s=Yt(),i=!1,l=!1,d=e=>{e&&(l=!1),s.active&&(s.cancel(),a=e,l=!!e,o())},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 o="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;!o||p||0===c?(e.scrollTop=Qt(e),r(),n()):s.start(e,()=>Qt(e),c,r,n)},destroy(){i=!0,s.cancel(),e.removeEventListener("wheel",p),e.removeEventListener("touchstart",d),e.removeEventListener("pointerdown",d),t.removeEventListener("keydown",c)}}}function Zt(e,t,r){let n=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");n.type="button",n.setAttribute("data-persona-scroll-to-bottom-visible","false"),n.disabled=!0,n.tabIndex=-1,n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-scroll-to-bottom","true");let o=st("span","persona-flex persona-items-center persona-justify-center");o.setAttribute("aria-hidden","true");let a=st("span",""),s=st("span","");s.setAttribute("data-persona-scroll-to-bottom-count",""),n.appendChild(o),n.appendChild(a),n.appendChild(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;p.reducedMotion=h?.matches??!1;let m=e=>console.warn("Persona scroll icon failed",e),g=()=>({config:c,state:{...p},view:t,signal:d.signal}),f=()=>{d?.abort();try{l?.destroy?.()}catch(e){m(e)}l=void 0,d=void 0,o.innerHTML="",u=""},b=()=>{if(l?.element)return;let t=c.features?.scrollToBottom,r="generating-below"===p.activity&&"dots"===(t?.streamingIndicator??(c.future?.v5Defaults?"dots":"arrow")),n=r?"dots":`arrow:${t?.iconName??"arrow-down"}`;if(u!==n)if(u=n,o.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)}o.appendChild(e)}else{let r=e(t?.iconName??"arrow-down","14px","currentColor",2);r&&o.appendChild(r)}},y=e=>{let t=!1===c.features?.scrollToBottom?.enabled?void 0:c.features?.scrollToBottom?.renderIcon;if(t!==i){if(f(),i=t,i){d=new AbortController;try{let e=i(g());l=e&&"element"in e?e:e?{element:e}:void 0,l?.element&&o.appendChild(l.element)}catch(e){m(e),f()}}}else if(e&&l?.update)try{l.update(g())}catch(e){m(e),f()}b()},v=e=>Object.keys(e).some(t=>e[t]!==p[t]),w=e=>{let t=v(e);p=e,y(t)},x=()=>w({...p,hovered:!0}),C=()=>w({...p,hovered:!1}),S=()=>w({...p,focused:!0}),k=()=>w({...p,focused:!1}),A=()=>w({...p,reducedMotion:h?.matches??!1}),M=new AbortController;for(let[e,t]of[["mouseenter",x],["mouseleave",C],["focus",S],["blur",k]])n.addEventListener(e,t,{signal:M.signal});return h?.addEventListener?.("change",A),{element:n,update(e,t,o=!1,i=0){let l=c.features?.scrollToBottom,d=e.features?.scrollToBottom,u=c.future?.v5Defaults!==e.future?.v5Defaults||["enabled","iconName","label","streamingIndicator","transition","scrollBehavior","scrollDurationMs"].some(e=>l?.[e]!==d?.[e]);c=e;let h=c.features?.scrollToBottom;t&&=!1!==h?.enabled;let m=n.getRootNode().activeElement===n;n.setAttribute("data-persona-scroll-to-bottom-visible",String(t));let g=!1===h?.enabled?"none":h?.transition??(c.future?.v5Defaults?"fade":"none");n.setAttribute("data-persona-scroll-to-bottom-transition",g),o&&t?n.setAttribute("data-persona-scroll-to-bottom-streaming",""):n.removeAttribute("data-persona-scroll-to-bottom-streaming"),n.style.display=t||"none"!==g?"":"none",n.disabled=!t,n.tabIndex=t?0:-1,n.setAttribute("aria-hidden",String(!t)),!t&&m&&(n.blur(),r&&(r.hasAttribute("tabindex")||(r.tabIndex=-1),r.focus({preventScroll:!0})));let f=h?.label??"",b=f||"Jump to latest";n.setAttribute("aria-label",`${b}${i>0?` (${i} new)`:""}${o&&t?" (response streaming below)":""}`),n.title=f,n.setAttribute("data-persona-scroll-to-bottom-has-label",String(!!f)),a.textContent=f,a.style.display=f?"":"none",s.textContent=i>0?String(i):"",s.style.display=i>0?"":"none";let w={...p,visible:t,hovered:t&&p.hovered,focused:t&&p.focused,activity:o&&t?"generating-below":"idle"},x=u||v(w);p=w,y(x)},destroy(){f(),M.abort(),h?.removeEventListener?.("change",A),n.remove()}}}let er="webmcp:",tr=new Map,rr=e=>{tr.clear();for(let t of e){let e=t.title?.trim();e&&tr.set(t.name,e)}},nr=e=>tr.get(ir(e)),or=null;function ar(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`${sr(e,0).toString(36)}.${sr(e,2654435761).toString(36)}`}(t.join(""))}`}function sr(e,t){let r=3735928559^t,n=1103547991^t;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);r=Math.imul(r^o,2654435761),n=Math.imul(n^o,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}let ir=e=>e.startsWith("webmcp:")?e.slice(7):e,lr=e=>e.startsWith(er),dr=()=>or?or():import("@mcp-b/webmcp-polyfill");function cr(e){return"webmcp"===e.toolType&&!e.executionId}function pr(e){let t=e.approval,r="pending"===t?.status&&cr(t),n=!1,o=t=>t.name&&lr(t.name)&&(n=!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?o(e.toolCall):void 0,s=e.tools?.map(o);return{...e,streaming:!n&&!r&&e.streaming,...r?{approval:{...t,status:"timeout",interrupted:!0}}:{},...a?{toolCall:a}:{},...s?{tools:s}:{},...n&&e.agentMetadata?.awaitingLocalTool?{agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}}:{}}}let ur=(e,t,r)=>{let n="transient"===t.mode,o=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=((e,t)=>!1!==e.visible&&("transient"!==e.mode||"connecting"===t||"paused"===t||"resuming"===t||"error"===t))(t,r)||n&&o&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!n),e.classList.toggle("persona-mb-2",n)},hr=(e,t,r)=>{t.parentElement&&e.parentElement===t.parentElement&&("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))},mr=/^\s*\|?[\s:|-]*-[\s:|-]*$/,gr=e=>e.includes("|"),fr=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())},br=e=>`| ${e.join(" | ")} |`,yr=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,vr=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),wr=e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1];if(!gr(n)||mr.test(n)||!mr.test(o))continue;let a=fr(n).length;if(a<1)continue;let s=yr(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()||!gr(e))break;let n=br(vr(fr(e),a));t[i]!==n&&(t[i]=n,r=!0)}e=i-1}return r?t.join("\n"):e},xr=(e,t)=>t?(at()?.stabilizeStreamingMarkdown??wr)(e):e,Cr=e=>{let t=null;return r=>{let n=at();if(!n)return Mr(r);if(!t){let{Marked:r}=n,o=e?.markedOptions;t=new r({gfm:o?.gfm??!0,breaks:o?.breaks??!0,pedantic:o?.pedantic,silent:o?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,n)=>e({type:"heading",raw:n,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,n)=>e({type:"code",raw:"",text:t,lang:r,escaped:n})}if(r.blockquote){let e=r.blockquote;t.blockquote=t=>e({type:"blockquote",raw:"",text:t,tokens:[]})}if(r.table){let e=r.table;t.table=(t,r)=>e({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:t,bodyHtml:r})}if(r.link){let e=r.link;t.link=(t,r,n)=>e({type:"link",raw:"",href:t,title:r??null,text:n,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,n)=>e({type:"image",raw:"",href:t,title:r??null,text:n})}if(r.list){let e=r.list;t.list=(t,r,n)=>e({type:"list",raw:"",ordered:r,start:n,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,n)=>e({type:"list_item",raw:"",task:r,checked:n,loose:!1,text:t,tokens:[]})}if(r.paragraph){let e=r.paragraph;t.paragraph=t=>e({type:"paragraph",raw:"",text:t,tokens:[]})}if(r.codespan){let e=r.codespan;t.codespan=t=>e({type:"codespan",raw:"",text:t})}if(r.strong){let e=r.strong;t.strong=t=>e({type:"strong",raw:"",text:t,tokens:[]})}if(r.em){let e=r.em;t.em=t=>e({type:"em",raw:"",text:t,tokens:[]})}if(r.del){let e=r.del;t.del=t=>e({type:"del",raw:"",text:t,tokens:[]})}if(r.html){let e=r.html;t.html=t=>e({type:"html",raw:t,text:t})}if(r.text){let e=r.text;t.text=t=>e({type:"text",raw:t,text:t})}if(r.checkbox){let e=r.checkbox;t.checkbox=t=>e({checked:t})}return r.hr&&(t.hr=r.hr),r.br&&(t.br=r.br),t})(e?.renderer);a&&t.use({renderer:a})}return t.parse(r)}},Sr=e=>e?Cr({markedOptions:e.options,renderer:e.renderer}):Cr(),kr=Cr(),Ar=e=>kr(e),Mr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Ir=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Tr=e=>`%%FORM_PLACEHOLDER_${e}%%`,Er=(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=Tr(t.length);return t.push({token:r,type:String(e.type)}),r}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let n=Tr(t.length);return t.push({token:n,type:r}),n}),r},Br={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,Rr=()=>{let e=null;return t=>{let r=at();if(!r)return Mr(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,Br)}},Pr=e=>!1===e?null:"function"==typeof e?e:Rr(),Nr="var(--persona-md-table-scroll-fade, 24px)",$r=new WeakSet;function Wr(e){let t=e.scrollWidth-e.clientWidth;if(t<=1)return void e.removeAttribute("data-persona-scroll-x");e.setAttribute("data-persona-scroll-x","");let r="rtl"===getComputedStyle(e).direction?t+e.scrollLeft:e.scrollLeft,n=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":Nr),e.style.setProperty("--persona-fade-r",n<=1?"0px":Nr)}function Hr(e){$r.has(e)||($r.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&Wr(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Wr)}let{setLoader:Dr,load:Fr,provide:zr,getSync:Or}=_({fallbackImport:()=>import("./client-stream")}),qr=Dr,jr=Fr,_r=Or,{setLoader:Ur,load:Vr,provide:Kr,getSync:Qr}=_({fallbackImport:()=>import("./client-dispatch")}),Jr=Ur,Gr=Vr,Yr=Qr,{setLoader:Xr,load:Zr}=_({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),en=Xr,tn=Zr,{setLoader:rn,load:nn}=_({fallbackImport:()=>import("@runtypelabs/persona/voice-client-tools")}),on=rn,an=nn;function sn(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function ln(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function dn(){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=>{var r,n,o=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),a=e&&e.__exportStar||function(e,t){for(var r in e)"default"!==r&&!Object.prototype.hasOwnProperty.call(t,r)&&o(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let s=t();function i(e,t=s.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return l(e.trim(),t)}Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return s.Allow}}),a(t(),e),r=class extends Error{},e.PartialJSON=r,n=class extends Error{},e.MalformedJSON=n,e.parseJSON=i;let l=(e,t)=>{let o=e.length,a=0,i=e=>{throw new r(`${e} at position ${a}`)},l=e=>{throw new n(`${e} at position ${a}`)},d=()=>(m(),a>=o&&i("Unexpected end of input"),'"'===e[a]?c():"{"===e[a]?p():"["===e[a]?u():"null"===e.substring(a,a+4)||s.Allow.NULL&t&&o-a<4&&"null".startsWith(e.substring(a))?(a+=4,null):"true"===e.substring(a,a+4)||s.Allow.BOOL&t&&o-a<4&&"true".startsWith(e.substring(a))?(a+=4,!0):"false"===e.substring(a,a+5)||s.Allow.BOOL&t&&o-a<5&&"false".startsWith(e.substring(a))?(a+=5,!1):"Infinity"===e.substring(a,a+8)||s.Allow.INFINITY&t&&o-a<8&&"Infinity".startsWith(e.substring(a))?(a+=8,1/0):"-Infinity"===e.substring(a,a+9)||s.Allow._INFINITY&t&&1<o-a&&o-a<9&&"-Infinity".startsWith(e.substring(a))?(a+=9,-1/0):"NaN"===e.substring(a,a+3)||s.Allow.NAN&t&&o-a<3&&"NaN".startsWith(e.substring(a))?(a+=3,NaN):h()),c=()=>{let r=a,n=!1;for(a++;a<o&&('"'!==e[a]||n&&"\\"===e[a-1]);)n="\\"===e[a]&&!n,a++;if('"'==e.charAt(a))try{return JSON.parse(e.substring(r,++a-Number(n)))}catch(e){l(String(e))}else if(s.Allow.STR&t)try{return JSON.parse(e.substring(r,a-Number(n))+'"')}catch{return JSON.parse(e.substring(r,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{a++,m();let r={};try{for(;"}"!==e[a];){if(m(),a>=o&&s.Allow.OBJ&t)return r;let n=c();m(),a++;try{r[n]=d()}catch(e){if(s.Allow.OBJ&t)return r;throw e}m(),","===e[a]&&a++}}catch{if(s.Allow.OBJ&t)return r;i("Expected '}' at end of object")}return a++,r},u=()=>{a++;let r=[];try{for(;"]"!==e[a];)r.push(d()),m(),","===e[a]&&a++}catch{if(s.Allow.ARR&t)return r;i("Expected ']' at end of array")}return a++,r},h=()=>{if(0===a){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(s.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let r=a;for("-"===e[a]&&a++;e[a]&&-1===",]}".indexOf(e[a]);)a++;a==o&&!(s.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(r,a))}catch{"-"===e.substring(r,a)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(r,e.lastIndexOf("e")))}catch(e){l(String(e))}}},m=()=>{for(;a<o&&" \n\r\t".includes(e[a]);)a++};return d()};e.parse=i})();let cn="ask_user_question",pn="data-persona-ask-sheet-for",un="Type your own answer here",hn="Send",mn="data-ask-question-count",gn="data-ask-answers",fn="data-ask-grouped",bn=!1,yn=e=>e.replace(/["\\]/g,"\\$&"),vn=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,wn=e=>e?.features?.askUserQuestion??{},xn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:n};let o=t.chunks;if(!o||0===o.length)return{payload:null,complete:n};try{let e=o.join(""),t=(0,r.parse)(e,r.STR|r.OBJ|r.ARR);if(t&&"object"==typeof t)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},Cn=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!bn&&(bn=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Sn={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"},kn=(e,t)=>{Object.entries(Sn).forEach(([r,n])=>{let o=O(t,`features.askUserQuestion.styles.${r}`);"string"==typeof o&&o?e.style.setProperty(n,o):e.style.removeProperty(n)})},An=(e,t,r)=>{if("rows"!==e)return null;let n=st("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let e=st("span","persona-ask-row-check");n.appendChild(e)}else{let e=st("span","persona-ask-row-badge");e.textContent=String(r+1),n.appendChild(e)}return n},Mn=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},In=(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 n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=e.freeTextPlaceholder??un,n.setAttribute("data-ask-free-text-input","true"),r.appendChild(n),"rows"!==t){let t=st("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??hn,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Tn=e=>{let t=e.getAttribute(gn);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},En=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Bn=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ln=e=>"true"===e.getAttribute(fn),Rn=(e,t,r)=>{let n=wn(r),o=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=xn(t),i=Ln(e),l=En(e),d=Bn(e),c=i?((e,t)=>Cn(e)[t]??null)(a,l):(e=>Cn(e)[0]??null)(a),p=!!c?.multiSelect,u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${l+1}/${d}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let m=e.querySelector('[data-ask-question="true"]');if(m){let e="string"==typeof c?.question?c.question:"";m.textContent=e,m.classList.toggle("persona-ask-question-skeleton",!e&&!s)}let g=e.querySelector('[data-ask-pill-list="true"]');if(g){let e=((e,t,r,n)=>{let o=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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&"string"==typeof e.label&&e.label.length>0);if(0===s.length&&!r){for(let e=0;e<3;e++)o.appendChild(Mn(n));return o}if(s.forEach((e,t)=>{o.appendChild(((e,t,r,n)=>{let o=st("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",n?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),"rows"===r){let a=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)}o.appendChild(a);let i=An(r,n,t);i&&o.appendChild(i)}else o.textContent=e.label,e.description&&(o.title=e.description);return o})(e,t,n,a))}),!1!==e?.allowFreeText){let e="rows"===n?"Other":"Other…";if("rows"===n){let r=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??un,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=An(n,a,s.length);d&&r.appendChild(d),o.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,o.appendChild(r)}}return o})(c,n,s,o);g.replaceWith(e)}if("rows"!==o){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(In(n,o))}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??hn,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(n)),e.setAttribute("data-multi-select",p?"true":"false");let b=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let n=st("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=st("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=r.backLabel??"Back",o.setAttribute("data-ask-user-action","back"),o.disabled=0===e,n.appendChild(o);let a=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),n.appendChild(a),n})(l,d,n);b?b.replaceWith(t):e.appendChild(t)}else b&&b.remove();(e=>{let t=Tn(e)[En(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let n=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');n.forEach(e=>{let t=e.getAttribute("data-option-label")??"",n=r.has(t);e.setAttribute("aria-pressed",n?"true":"false"),e.classList.toggle("persona-ask-pill-selected",n)});let o=new Set(Array.from(n).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!o.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Ln(e))return;let t=Tn(e)[En(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,n=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');n&&(n.disabled=!r);let o=e.querySelector('[data-ask-user-action="submit-multi"]');o&&(o.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},Pn=(e,t,r)=>{if(!r||!vn(e)||!1===wn(t).enabled)return;let n=e.toolCall.id;r.querySelectorAll(`[${pn}]`).forEach(e=>{e.getAttribute(pn)!==n&&e.remove()});let o=r.querySelector(`[${pn}="${yn(n)}"]`);if(o)return void((e,t,r)=>{kn(e,r);let{payload:n}=xn(t),o=Math.max(1,Cn(n).length);o>Bn(e)&&(e.setAttribute(mn,String(o)),o>1&&!Ln(e)&&e.setAttribute(fn,"true")),Rn(e,t,r)})(o,e,t);let{payload:a}=xn(e),s=((e,t,r)=>{let n=wn(t),o=(e=>"pills"===e.layout?"pills":"rows")(n),a=e.toolCall.id,s=Cn(r),i=Math.max(1,s.length),l=i>1,d=((e,t)=>{let r=e.agentMetadata?.askUserQuestionAnswers;if(!r||"object"!=typeof r)return{};let n={};return t.forEach((e,t)=>{let o="string"==typeof e?.question?e.question:"";if(o&&Object.prototype.hasOwnProperty.call(r,o)){let e=r[o];("string"==typeof e||Array.isArray(e))&&(n[t]=e)}}),n})(e,s),c=l?((e,t)=>{let r=e.agentMetadata?.askUserQuestionIndex;return"number"==typeof r&&Number.isFinite(r)?Math.max(0,Math.min(t-1,Math.floor(r))):0})(e,i):0,p=st("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(pn,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(mn,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(fn,l?"true":"false"),p.setAttribute("data-ask-layout",o),((e,t)=>{e.setAttribute(gn,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==n.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),kn(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"===o?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==o&&p.appendChild(In(n,o)),Rn(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},Nn=(e,t)=>{if(!e)return;let r=t?`[${pn}="${yn(t)}"]`:`[${pn}]`;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)})},$n="suggest_replies",Wn={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},Hn={name:$n,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:Wn,origin:"sdk",annotations:{readOnlyHint:!0}},Dn=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,Fn=(e,t=4)=>{let r=e;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}let n=r?.suggestions;if(!Array.isArray(n))return[];let o=n.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 o.length>t?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of ${t}; extra suggestions dropped.`),o.slice(0,t)):o},zn=(e,t=4)=>{for(let r=e.length-1;r>=0;r--){let n=e[r];if("user"===n.role)return null;if(!Dn(n))continue;let o=Fn(n.toolCall?.args,t);return o.length>0?o:null}return null},On=new Set,qn=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,n=e=>{let n=t?.[e],o=r?.[e];void 0!==n&&void 0!==o&&n!==o&&((e,t,r)=>{let n=`${e}:${t}:${r}`;On.has(n)||(On.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,o,n)};e&&(n("enabled"),n("expose"));let o=t?.enabled??r?.enabled??!0;return{enabled:o,expose:!!o&&(t?.expose??r?.expose??!1)}},jn={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},_n={name:cn,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:jn,origin:"sdk",annotations:{readOnlyHint:!0}},Un=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(_n),qn(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?Hn:{...Hn,parametersSchema:{...Wn,properties:{suggestions:{...Wn.properties.suggestions,maxItems:r,description:`1-${r} short, distinct follow-up replies, phrased in the user's voice.`}}}}})(e)),t},Vn=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Kn=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),Qn=()=>(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return null===e?null:{text:e,raw:r};let o=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/)?.[1]||e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/)?.[1];if(!t)return null;try{return Vn(t)}catch{return t}})(r);return null!==o&&(e=o),t=r.length,null===e?null:{text:e,raw:r}},close:async()=>{}}})(),Jn=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return null!==e||""===e?{text:e||"",raw:n}:null;try{let t=(0,r.parse)(n,r.STR|r.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?Vn(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=Vn(t.text)))}catch{}return t=n.length,null===e?null:{text:e,raw:n}},close:()=>{}}},Gn=()=>{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}},Yn="4.32.0",{setLoader:Xn,load:Zn,provide:eo}=_({fallbackImport:()=>import("./client-history")}),to=Xn,ro=Zn;n=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let no=e=>"reason"in e?e.reason:void 0;o=class{#e;#t;#r;#n;#o;#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.#o=e,this.#n=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":Yn,...e.headers},this.#r=!!e.debug,this.#a=e.streamParser??function(e){switch(e){case"json":return Jn;case"regex-json":return Qn;case"xml":return Gn;default:return Kn}}(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 tn().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:rr,getToolDisplayTitle:nr,loadPolyfill:dr});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.#o.webmcp?.enabled?(this.#k||=this.#T(this.#o.webmcp),this.#k):Promise.resolve(null)}updateConfig(e){this.#o=e}setHistoryInternals(e){this.#n=e}cancelStreams(){if(this.#u+=1,this.#o.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.#o.webmcp?.enabled)return null;let e=()=>this.#E(),t={open:async e=>(await an()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await((await e())?.snapshotForDispatch())??[];return{tools:t,fingerprint:ar(t)}},onChange:t=>{let r=null,n=!1;return e().then(e=>{e&&!n&&(r=e.watchToolChanges(t))}),()=>{n=!0,r?.()}},execute:async(t,r,n)=>{let o=await e();return o?o.executeVoiceToolCall(t,r,n):{status:"failed",error:{message:"WebMCP runtime failed to load."}}}};return t}executeWebMcpToolCall(e,t,r,n){return!0===this.#o.webmcp?.enabled?this.#E().then(o=>o?o.executeToolCall(e,t,r,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]}):null}getSSEEventCallback(){return this.#p}isClientTokenMode(){return!!this.#o.clientToken}#B(){let{agentId:e,flowId:t,target:r,targetProviders:n}=this.#o;if(!r)return{agentId:e,flowId:t};let o=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let n=r.indexOf(":");if(n>0){let e=r.slice(0,n),o=r.slice(n+1);if("runtype"===e){let e=sn(o);if(e)return e;throw Error(`[Persona] target "runtype:${o}" 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(o).payload}}let o=sn(r);if(o)return o;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,n);return"agentId"===o.kind?{agentId:o.agentId}:"flowId"===o.kind?{flowId:o.flowId}:{targetPayload:o.payload}}isAgentMode(){return!(!this.#o.agent&&!this.#B().agentId)}#L(){return this.#o.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||"https://api.runtype.com"}#R(e){return`${this.#L()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),r=!1;for(;;){let o=t.conversationId,a=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!o||!a)throw new n("visitor_token_missing","Durable recovery is not enabled for this client session");let s=`${this.#L()}/v1/client/conversations/${encodeURIComponent(o)}/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":Yn,"X-Visitor-Token":a},signal:e.signal});if(401!==l.status||r){if(!l.ok)throw await(await ro()).historyErrorFor(this.#P(),l,!0);return l}{r=!0;let e=await ro();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.#o.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#g===e&&(this.#g=null)});return e}#$(){return!0===this.#o.features?.history?.enabled&&this.isClientTokenMode()&&!this.#y}async readVisitorToken(){let e=this.#n.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.#n.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.#o.features?.history?.enabled||this.#y?{state:"unavailable",reason:"history_disabled"}:this.#F():{state:"unavailable",reason:"ineligible_mode"}}#F(){let e=this.#x;return"browser_only"===e?.state?e:this.#z()}#z(){return"browser"===this.#o.features?.history?.scope?{state:"browser_only",reason:"configured_browser_scope"}:this.#o.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&&no(t)===no(e);if(this.#x=e,!r){this.#n.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#C])t(e)}}async#O(e){return new((Yr()??await Gr()).ClientDispatch)(this.#q()).createClientSession(e)}async#N(){return new((Yr()??await Gr()).ClientDispatch)(this.#q()).initializeSession()}async#j(e){let t=this.#o.getStoredSessionId?.()||null,r=this.#o.getStoredConversationId?.()||null,n=await this.#O({storedSessionId:t,identityProof:e}),o=this.#_(n,r,!1);return this.clientSession=o,this.#g=null,this.#f=!1,this.resetClientToolsFingerprint(),o}#_(e,t,r){let n=e.conversationId;return n&&t&&(r||n!==t)&&this.#n.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:n}),this.#o.setStoredSessionId?.(e.sessionId),n&&(this.#o.setStoredConversationId?.(n),this.#n.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 n("history_disabled","Visitor history is disabled for this surface");await this.#n.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new n("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let o=await this.#O({conversationId:e,identityProof:r});return this.#U(o)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.#n.historyBootstrapReady;let e=await this.#O({});return this.#U(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#$()&&this.#H(this.#z())}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((Yr()??await Gr()).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.#o.identityProvider;if(void 0===t)return;let r,n,o=this.#o.getIdentityProof;if(!t.trim()||!o)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>o());r=e?await Promise.race([t,new Promise((t,r)=>{n=()=>r(e.reason),e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{n&&e?.removeEventListener("abort",n)}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.#o},headers:this.#t,getHeaders:this.#c,debug:this.#r,clientApiBase:()=>e.#L(),getClientApiUrl:t=>e.#R(t),getWebMcpBridge:()=>e.#E(),sendWithClientToolsDiff:(t,r,n,o)=>e.#Q(t,r,n,o),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#I;#P(){let e=this;return this.#I??={HistoryClientError:n,get config(){return e.#o},get historyInternals(){return e.#n},get clientSession(){return e.clientSession},clientApiBase:()=>e.#L(),setHistoryIdentityStatus:t=>e.#H(t),browserOnlyStatus:()=>e.#F(),derivedBrowserOnly:()=>e.#z(),reinitWithProof:t=>e.#j(t),isHistoryCapable:()=>e.#$(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await ro()).listConversations(this.#P(),e)}async getConversation(e,t){return(await ro()).getConversation(this.#P(),e,t)}async finalizeDisplayProjections(e,t){return(await ro()).finalizeDisplayProjections(this.#P(),e,t)}async deleteConversation(e,t){return(await ro()).deleteConversation(this.#P(),e,t)}async deleteAllConversations(e){return(await ro()).deleteAllConversations(this.#P(),e)}async resetVisitor(){return(await ro()).resetVisitor(this.#P())}async dispatch(e,t){e.signal?.throwIfAborted(),jr().catch(()=>{});let r=this.isClientTokenMode(),n=this.isAgentMode(),o=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;r&&(this.#m=o),t({type:"status",status:"connecting"});let a=Yr()??await Gr().catch(e=>{let n=e instanceof Error?e:Error(String(e));throw(!r||this.#m===o)&&t({type:"error",error:n}),n});if(e.signal?.throwIfAborted(),r&&this.#m!==o)throw new DOMException("Turn superseded","AbortError");let s=new a.ClientDispatch(this.#q());return r?s.dispatchClientToken(e,t,o):n?s.dispatchAgent(e,t):s.dispatchProxy(e,t)}#q(){let e=this;return Object.setPrototypeOf({HistoryClientError:n,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.#n},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.#O(t),finishInit:(t,r,n)=>e.#_(t,r,n),resetSessionWarmLatch:()=>{e.#f=!1},resetClientToolsFingerprint:()=>e.resetClientToolsFingerprint(),clearClientSession:()=>e.clearClientSession(),resolveChatIdentityProof:t=>e.#V(t),routing:()=>e.#B(),builtInClientTools:Un,streamResponse:(...t)=>e.#J(...t)},this.#K())}async processStream(e,t,r,n,o,a,s){t({type:"status",status:"connected"});try{await this.#J(e,t,r,n,o,a,s)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t,r){return(await jr()).resolveApproval(this.#K(),e,t,r)}async#Q(e,t,r,n){return new((Yr()??await Gr()).ClientDispatch)(this.#q()).sendWithClientToolsDiff(e,t,r,n)}async resumeFlow(e,t,r){return(await jr()).resumeFlow(this.#K(),e,t,r)}async#J(e,t,r,n,o,a,s){let{streamResponse:i}=_r()??await jr();return i({config:()=>this.#o,streamGeneration:()=>this.#u,streamReaders:this.#h,createStreamParser:this.#a,parseSSEEvent:this.#d,onSSEEvent:(e,t)=>this.#p?.(e,t)},e,t,r,n,o,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:oo,load:ao}=_({fallbackImport:()=>import("@runtypelabs/persona/background-runtime")}),so=oo,io=ao,{setLoader:lo,load:co,provide:po,getSync:uo}=_({fallbackImport:()=>import("./session-actions")}),ho=lo,mo=co,go=uo;function fo(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function bo(e){return{type:"text",text:e}}let yo=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vo=[...yo,"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 wo(e){return function(e){return yo.includes(e)||e.startsWith("image/")}(e.type)}function xo(e,t=vo,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 Co(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 So=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function ko(e){return"card"===e?"collapsed":e}function Ao(e){return e.split(";",1)[0].trim().toLowerCase()}function Mo(e,t){let r=e?.display,n="string"==typeof r?{default:r}:r??{};if(t.file&&n.files){if("string"==typeof n.files)return{mode:ko(n.files),matchedBy:{type:"files"}};let e=t.file.mimeType?Ao(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,n]of r)if(Ao(e)===t)return{mode:ko(n),selector:Ao(e)};let n=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(Ao(e)===n)return{mode:ko(t),selector:n}}(n.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(n.files.default)return{mode:ko(n.files.default),matchedBy:{type:"files"}}}let o=n.byKind?.[t.artifactType];if(o)return{mode:ko(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:ko(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:ko(s),matchedBy:{type:"preferredMode"}}:n.default?{mode:ko(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Io(e,t){return Mo(e,t).mode}function To(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 Eo(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function Bo(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;--t)if("user"===e[t].role)return e[t].id;return null}function Lo(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 Ro(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let 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)(n,r.STR|r.OBJ),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Po(e,t){let{config:r,message:n,onPropsUpdate:o}=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:n,config:r,signal:t.signal??(new AbortController).signal,updateProps:e=>{o&&o(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function No(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 $o(e){let t=No(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 Wo(e){let t=No(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 Ho(e){let t=e.content;if("string"!=typeof t||""===t)return;let r=e.contentParts??e.llmContent??e.rawContent??t;return"string"!=typeof r||r!==t?t:void 0}function Do(e,t){let r=new Map;for(let t of e)r.set(t.id,t);for(let e of t)r.set(e.id,e);return[...r.values()].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a})}function Fo(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 zo(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 n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(o.voice=e)}else a.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(a):Fo(a));void 0!==t.rate&&(o.rate=t.rate),void 0!==t.pitch&&(o.pitch=t.pitch),o.onend=()=>r.onEnd?.(),o.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{n.speak(o),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},i=class{#e=null;#t=null;#r="idle";#n=new Set;#o=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.#n.add(e),()=>this.#n.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.#o;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#o)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#o&&this.#s(e,"playing")},onEnd:()=>{r===this.#o&&this.#s(null,"idle")},onError:()=>{r===this.#o&&this.#s(null,"idle")}})}catch{r===this.#o&&this.#s(null,"idle")}}stop(){this.#o++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#n)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 Oo=null,qo=()=>Oo?Oo():import("./voice/runtype-tts-entry"),{setLoader:jo,load:_o}=_({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Uo=jo,Vo=_o,Ko="apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId".split(".");function Qo(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 n="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${n}\n\n_Details: ${r.message}_`:n}d=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};let Jo=e=>lr(e)||"suggest_replies"===e;c=class e{#e;#t;#r;#n;#o(e){if(this.#a("cancel"),this.#r=!1,this.#e={runId:`run-${dn()}`,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.#n&&clearTimeout(this.#n),this.#n=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.#n)return;let e=this.#e;this.#n=setTimeout(()=>{this.#n=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;#B;#L;#R;#$;#W;#D;#F;#z;#H;#O;#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.#n=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.#B="disconnected",this.#L=null,this.#R=null,this.#$=null,this.#W=0,this.#D=0,this.#F=null,this.#z=Promise.resolve(),this.#H=!1,this.#O=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.#ne()),this.#oe=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,n=!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),n=!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"),n&&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)&&mo().catch(()=>{});let o=e.message.toolCall,a=!!o?.name&&(lr(o.name)||"suggest_replies"===o.name&&qn(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=>({...pr(e),sequence:e.sequence??this.#ve()})),this.messages=this.#we(this.messages),this.client=new o(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&&qo().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.#B}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;#ne(){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,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,o=this.config.clientToken,a=!1!==e.browserFallback;if(r&&n&&o)return qo().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:n,clientToken:o,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new i(l,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):l});if(a&&t)return o&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error("Voice configuration not provided");this.cleanupVoice();let r=this.#ee,n=++this.#A;this.#k=qt().then(async e=>{await r,n===this.#A&&this.#Me(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{n===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.#B=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.#B="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.#Be(e,t)}#Be(e,t=!this.messages.length){if(this.#H||!e.config.welcomeMessage||!t)return;let r=this.messages[0],n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:r?.createdAt??(new Date).toISOString(),sequence:r?(r.sequence??0)-1:this.#ve()};this.#Le(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return!!e&&new Date<e.expiresAt}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){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,n=this.config.getIdentityProof?"verified-user":"browser",o=r??(t.capabilities.scopes.includes(n)?n:t.capabilities.scopes[0]??n);if(!t.capabilities.scopes.includes(o))throw new a("unsupported_scope","This history scope is not supported.");return{scope:o}}getHistoryState(){return{activeConversationId:this.#L,conversationRevision:this.#R,nextMessageCursor:this.#$,recovery:this.#O,sendBlocked:this.#N}}getActiveConversationId(){return this.#L}#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(()=>{})}#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 n=this.#We(t?.scope),o=++this.#W,a=this.#D;if("background"===t?.busy&&await this.#ze(),await this.awaitHistorySettled(),o!==this.#W)throw new d("superseded","A later selection won");let s=await r.getPage(e,{context:n});if(o!==this.#W)throw new d("superseded","A later selection won");let i=await r.prepareOpen(e,{context:n}),l=this.#z.then(async()=>{if(o!==this.#W)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 n=this.#L,l=this.#e;t?.onBeforeCommit?.(),"background"===t?.busy&&(this.#m=[]),this.#H=!0,this.#F=a;try{if(await this.#Oe(i),a!==this.#D||r!==this.#Ne)throw new d("superseded","The history identity changed");if("background"===t?.busy&&n&&this.#c){let e={conversationId:n,handle:this.#c,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#w,streamCheckpoint:this.#h};this.#g?.save(e)}this.#L=i.conversationId||e,this.#R=i.conversationRevision||s.conversationRevision||null,this.#$=s.nextCursor,this.#O=null,this.#N=!1,this.#qe();for(let e of s.messages)this.#V.set(e.id,e.content);this.#je();let o=this.#g?.take(this.#L);return this.hydrateMessages(o?.messages??s.messages),o&&(this.hydrateArtifacts(o.artifacts,o.selectedArtifactId,!0),this.#_e(o)),t?.onCommitted?.(),this.#He(),{summary:s.summary,nextMessageCursor:s.nextCursor}}finally{this.#H=!1,this.#F=null;let e=this.#m;if(this.#m=null,e&&this.#e===l&&this.#L===n)for(let{event:t,readOnlyReplay:r}of e)this.handleEvent(t,r)}}),c=l.then(()=>{},()=>{});this.#z=c,this.#j=c;try{return await l}finally{this.#j===c&&(this.#j=null)}}loadOlderMessages(e,t,r){let n=this.#$e(),o=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(n,e,a,o).finally(()=>{this.#_.delete(s)});return this.#_.set(s,l),l}async#Ue(e,t,r,n){let o=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...o?{beforeCreatedAt:o}:{},context:n});if(this.#L&&this.#L!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=this.#Ve(a.messages),i=Do(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&&cr(r.approval)&&r.approval.id===e.approval?.id&&"pending"!==r.approval.status&&"pending"===e.approval?.status)return r;let t=r.agentMetadata?.executionId,n=[...r.toolCall?[r.toolCall]:[],...r.tools??[]];if(t&&n.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return r}return pr(e)})}async startNewConversation(e){let t=this.#$e(),r=this.#We(e?.scope),n=++this.#W,o=this.#D;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:r}),s=this.#z.then(async()=>{if(n!==this.#W)throw a.discard(),new d("superseded","A later action won");e?.onBeforeCommit?.(),this.#H=!0,this.#F=o;try{await this.#Oe(a)}finally{this.#H=!1,this.#F=null}if(o!==this.#D||t!==this.#Ne)throw new d("superseded","The history identity changed");this.#Qe(!1,!0),this.#L=a.conversationId||null,this.#R=a.conversationRevision||null,this.#$=null,this.#O=null,this.#N=!1,this.#je(),this.clientSession&&this.#Be(this.clientSession),e?.onCommitted?.(),this.#He()}),i=s.then(()=>{},()=>{});this.#z=i,this.#j=i;try{await s}finally{this.#j===i&&(this.#j=null)}}async#Je(e,t=!1){this.#Qe(t),await this.#Oe(e),this.#L=e.conversationId||null,this.#R=e.conversationRevision||null,this.#$=null,this.#O=null,this.#N=!1,this.#je(),this.#He()}async deleteConversation(e,t){let r=this.#$e(),n=this.#We(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:n}),this.#g?.clear(e),e===this.#L&&await this.#Ge(n)}async updateConversation(e,t,r){let n=this.#$e();if(!n.update)throw new d("history_unavailable","This history provider cannot update conversations");let o=this.#We(r?.scope);return await this.awaitHistorySettled(),n.update(e,t,{context:o})}canUpdateConversations(){return"function"==typeof this.#Ne?.update}async clearConversationHistory(e){let t=this.#$e(),r=this.#We(e?.scope);await this.awaitHistorySettled();let n=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return this.#Re(),await this.#Ge(r),n}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.#L=null,this.#R=null,this.#$=null,this.#O=null,this.#N=!1,this.#He()}}async#Ge(e){this.#W+=1,this.#D+=1,this.#U=null,this.#Qe(),this.#L=null,this.#R=null,this.#$=null,this.#N=!0,this.#O=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.#O="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.#O&&this.#Ne&&(this.#O=null,await this.#Ye(this.#We()),"new_conversation_required"===this.#O))throw new d("new_conversation_required","A new conversation is required before sending")}async#Oe(e){if(await e.commit(),null!==this.#F&&this.#F!==this.#D)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(null===this.#F||this.#F===this.#D)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#L=e.conversationId,this.#R=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#H||this.#Be(e))}#je(){this.#L?this.config.setStoredConversationId?.(this.#L):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.#L=e.conversationId,this.#R=null,this.#$=null,this.#O=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.#nt(e))))}#nt(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.#L||null!==(this.config.getStoredConversationId?.()??null)?this.#Qe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#_.clear(),this.#et(null)),this.#L=null,this.#R=null,this.#$=null,this.#O=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.")}#ot(){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.#L;if(!t||!r)return Promise.resolve();let n=this.#We(e?.scope);this.#N=!0,this.#He();let o=this.#st(t,r,n).finally(()=>{this.#N=null!==this.#O,this.#j===o&&(this.#j=null),this.#He()});return this.#j=o,o}async#st(e,t,r){this.#L=t;let n=this.clientSession?.conversationRevision??this.#R??null,o=this.#I?this.#K:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#I=!1,this.#$=this.historyInternals.getStoredMessageCursor?.()??this.#$,await this.replayPendingProjections(),n&&o&&n===o)return void(this.#R=n);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=Do(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||n||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=Ho(t);void 0!==e&&this.#V.set(t.id,e)}}#ge(){if(!this.#it())return;let e=this.#L;if(!e)return;let t=[];for(let e of this.messages){if("assistant"!==e.role||e.streaming)continue;let r=Ho(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.#L!==e)return;let o=t.filter(e=>this.#V.get(e.id)!==e.displayContent);if(0===o.length)this.#ut(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,o);for(let e of o)this.#V.set(e.id,e.displayContent);this.#L===e&&r&&(this.#R=r),this.#ut(e,t)}catch(a){if(!r&&this.#ht(a))return void await this.#pt(e,o,!0);if(a instanceof n&&("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 n?"request_failed"===e.code:e instanceof Error}#ut(e,t){let r=this.#lt();if(!r||r.conversationId!==e)return;let n=new Set(t.map(e=>e.id)),o=r.messageIds.filter(e=>!n.has(e));this.#et(o.length?{conversationId:e,messageIds:o}:null)}async replayPendingProjections(){if(!this.#it())return;let e=this.#lt();if(!e)return;if(this.#L&&e.conversationId!==this.#L)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.#L&&(this.#R=null,this.historyInternals.setStoredConversationRevision?.(null))}async#mt(){await this.awaitHistorySettled(),await this.#ot(),"new_conversation_required"===this.#O&&await this.#Xe()}static#gt(e){return e instanceof n&&"conversation_deleted"===e.code}async#ft(t,r,n,o,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:n,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(o);if(!l)throw t;this.#dt([l]),await this.client.dispatch({messages:[l],signal:r.signal,assistantMessageId:n,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.#L=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.#O="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.#Le(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},n=function(e,t){let r=e.voiceRecognition,n=t.voiceRecognition;return!0===r?.enabled!=(!0===n?.enabled)||r?.provider?.type!==n?.provider?.type||r?.provider?.custom!==n?.provider?.custom||Ut(e)!==Ut(t)||r?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),a=function(e,t){return Ko.some(r=>e[r]!==t[r])}(this.config,r);a&&(this.cancel(),this.#Re()),this.config=r,n&&(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 o(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:n,contentParts:o,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e;return{id:a??("user"===t?ln():"assistant"===t?dn():`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!==n&&{llmContent:n},...void 0!==o&&{contentParts:o},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p},...void 0!==e.dispatchError&&{dispatchError:e.dispatchError}}}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:n="",llmContent:o,id:a,createdAt:s,sequence:i}=e,l={text:n,component:t,props:r};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...void 0!==o&&{llmContent:o},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}updateComponentProps(e,t){let r=this.messages.find(t=>t.id===e),n=r&&Wo(r);return!(!r||"assistant"!==r.role||r.variant||!n||(this.upsertMessage({...r,rawContent:JSON.stringify({text:r.content,component:n.component,props:t})}),0))}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!(!t||"assistant"!==t.role||t.variant||!Wo(t)||(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),0))}async#wt(e,t,r){let n;try{n=await r()}catch{return}let o=n.blocks.join("\n\n"),a=[o,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=n.contentParts.length>0;if(s){let t=[];o&&t.push(bo(o)),t.push(...n.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(bo(a)),t.push(...n.contentParts),e.contentParts=t}else o&&(e.llmContent=a);Object.keys(n.context).length>0&&(e.mentionContext=n.context)}async sendMessage(e,t){let r=e.trim(),n=!!t?.replayFields&&(void 0!==t.replayFields.llmContent||void 0!==t.replayFields.rawContent||(t.replayFields.contextMentions?.length??0)>0);if(!(r||t?.contentParts&&0!==t.contentParts.length||t?.mentions&&0!==t.mentions.refs.length||n))return;this.#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.#o(),this.#rt(),this.#ae++,this.#tt();let o=t?.voiceTurn?.userMessageId,a=o?this.messages.find(e=>e.id===o&&"user"===e.role):void 0,s=a?.id??ln(),i=dn();this.#p=null;let l=t?.contentParts&&fo(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.#Le(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:[bo(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(!So(e))return[];let{toolCallId:n,name:o}=e;if("string"!=typeof n||!n||"string"!=typeof o||!o||r.has(n))return[];r.add(n);let a=So(e.arguments)?e.arguments:{},s=e.result??null;return[{id:`voice-tool-${n}`,role:"assistant",variant:"tool",content:"",createdAt:t,streaming:!1,toolCall:{id:n,name:o,status:"complete",args:a,result:s},agentMetadata:{clientToolAnswer:{toolCallId:n,toolName:o,args:a,result:s}}}]})})(t?.voiceTurn?.priorToolResults,m);for(let e of g)this.messages.some(t=>t.id===e.id)||(this.#Le(e),h.push({...e,createdAt:u}));let f=g.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:r,args:n,result:o}=e.clientToolAnswer;return{toolCallId:t,name:r,arguments:n,result:o}});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 n=r+1;for(;n<e.length&&"user"!==e[n].role;)n+=1;return{start:r,end:n}}(this.messages,e);if(!r)return!1;let n=this.messages[r.start],o=t.replacement,a=o?o.text:n.content,s=o?o.contentParts:n.contentParts;if(!(a?.trim()||(s?.length??0)>0||!o&&(n.llmContent?.trim()?.length??0)>0))return!1;let i=o?void 0:{...void 0!==n.llmContent&&{llmContent:n.llmContent},...void 0!==n.rawContent&&{rawContent:n.rawContent},...n.mentionContext&&{mentionContext:n.mentionContext},...n.contextMentions&&{contextMentions:n.contextMentions},...n.quote&&{quote:n.quote}},l=o?this.#Ct(o.options):n.composerOptions,d=o?o.contentSegments:n.contentSegments,c=o?o.options?.quote:void 0,p=o?o.viaVoice:n.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,r.start),this.sendMessage(a??"",{...s?.length?{contentParts:[...s]}:{},...d?.length?{contentSegments:[...d]}:{},...l?{composerOptions:l}:{},...c?{quote:c}:{},...i&&Object.keys(i).length>0?{replayFields:i}:{},viaVoice:!0===p}),!0}#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.#o();let e=dn();this.#p=null,this.#ue(!0);let t=new AbortController;this.abortController=t;let r=this.#e,n=[...this.messages];try{await this.client.dispatch({messages:n,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.#o(),t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#p=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,n=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.#ue(!0);let o=this.#e,a={};try{await this.client.processStream(e,e=>{if(this.#e!==o)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!==o)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},n=`approval-${r.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(t=>{this.webMcpApprovalResolvers.set(n,t),e.signal?.addEventListener("abort",()=>this.resolveWebMcpApproval(n,"timeout"),{once:!0})})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let n=this.messages.find(t=>t.id===e);n?.approval&&this.upsertMessage({...n,approval:{...n.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#oe;#ae;#At(e){let t=this.#oe??={s:this,setStreaming:e=>this.#ue(e),appendMessage:e=>this.#Le(e),nextSequence:()=>this.#ve(),settleApprovalPausedToolCall:e=>this.#Mt(e),resumeAfter:e=>this.#c?.executionId===e?this.#c.lastEventId:void 0},r=go();if(r)return e(r,t);let n=this.#ae;return mo().then(r=>n===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((n,o)=>n.resolveApproval(o,e,t,r))}resolveAskUserQuestion(e,t){return this.#At((r,n)=>r.resolveAskUserQuestion(n,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 n=this.webMcpAwaitBatches.get(t);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,n)),!n.seen.has(r)&&(n.seen.add(r),n.snapshots.push(e))}#fe(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#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,n)=>t.resolveWebMcpToolCallBatch(n,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=To(Io(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...void 0===e.markdown?{}:{markdown:e.markdown}}),n=this.messages.find(e=>e.id===t);n?(n.rawContent=r,n.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 n=To(Io(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...void 0===t.markdown?{}:{markdown:t.markdown}});r.rawContent!==n&&(r.rawContent=n,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#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=>({...pr(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.#L))throw new d("conversation_busy","This turn cannot safely continue in the background")}async#ze(){if(this.#g)return;let e=this.config.backgroundConversations,t=this.#D,{BackgroundConversationController:r}=await io();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 n=!0;this.#f=this.#Ne?.subscribeIdentityStatus(()=>{n||(this.#g?.clear(),this.cancel())})??null,n=!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.#L;if(!this.config.backgroundConversations||!t||!r)return;let n={conversationId:r,executionId:t,status:e,detached:!1};this.#Et(n)}#Et(e){try{this.config.onConversationExecutionState?.(e)}catch{}try{this.callbacks.onConversationExecutionState?.(e)}catch{}}#Bt(){let e=this.config.backgroundConversations,t=this.#L;return e&&t?r=>e.reconnectStream({...r,conversationId:t}):this.config.reconnectStream}#_e(e){this.#o(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.#Lt(!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.#Lt(r),r&&this.#se("running")}#de(){return null!==this.#c&&"function"==typeof this.#Bt()&&!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.#Bt()&&(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=Vo().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.#Bt()}},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,n)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:n,readOnlyReplay:!!e.config.backgroundConversations}),appendMessage:t=>e.#Le(t),settleParked:t=>e.#Nt(t),nextSequence:()=>e.#ve(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>Qo(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.#o(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)?dn():this.#Ht();t||(t=dn(),this.#Le({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)}#Lt(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 n=zo(r.content);n.trim()&&this.readAloud.play(r.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Fo(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=zo(t.content||"");if(!r.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:n?.voice,rate:n?.rate,pitch:n?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#xt(e){for(let e of this.messages)e.streaming=!1;let t=Qo(e,this.config.errorMessage);t?this.#Le({id:dn(),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,n=r&&this.messages.find(e=>e.toolCall?.id===r),o=n&&n.toolCall;if(!o||"complete"===o.status||"pending"===t.status)return;let a={...o,status:"complete",approvalStatus:t.status,completedAt:Date.now(),..."approved"===t.status?{superseded:!0}:{success:!1,error:"denied"===t.status?"Denied":"Approval timed out"}};this.upsertMessage({...n,streaming:!1,toolCall:a})}#Le(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.#Le(t);this.messages=this.messages.map((e,n)=>{if(n!==r||e.toolCall?.name&&lr(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 o={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(o.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(o.agentMetadata={...o.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&o.agentMetadata&&!o.agentMetadata.clientToolAnswer&&(o.agentMetadata={...o.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,n=t.approval;o.approval={...r,...n,executionId:n.executionId||r.executionId,toolCallId:n.toolCallId||r.toolCallId,toolName:n.toolName||r.toolName,description:n.description||r.description,toolType:n.toolType??r.toolType,reason:n.reason??r.reason,parameters:n.parameters??r.parameters}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&Jo(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),n=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&Jo(a)&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;(r||n||s)&&(o.agentMetadata={...o.agentMetadata??{},awaitingLocalTool:!1},o.toolCall=e.toolCall,o.streaming=e.streaming)}return o});let n=this.messages[r],o=this.messages[r-1],a=this.messages[r+1];(o&&this.#Dt(o,n)>0||a&&this.#Dt(n,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(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a}#we(e){return[...e].sort((e,t)=>this.#Dt(e,t))}};let Go={add:e=>async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;wo(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})}(e)},Yo={allowedTypes:vo,maxFileSize:10485760,maxFiles:4};function Xo(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}p=class e{#e=[];#t;#r=new Set;#n=new Map;#o=null;#a=new Map;#s=new WeakMap;#i=!1;#l=!1;constructor(e={}){this.#t={allowedTypes:e.allowedTypes??Yo.allowedTypes,maxFileSize:e.maxFileSize??Yo.maxFileSize,maxFiles:e.maxFiles??Yo.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:Go}setPreviewsContainer(e){this.#o!==e&&this.#v(),this.#o=e}remountPreviews(e){if(this.#v(),this.#o=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:Yo.allowedTypes),"maxFileSize"in e&&(this.#t.maxFileSize=e.maxFileSize??Yo.maxFileSize),"maxFiles"in e&&(this.#t.maxFiles=e.maxFiles??Yo.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.#o);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=xo(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 n={id:Xo(),file:r,previewUrl:wo(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#d()?"uploading":"processing",progress:this.#d()?0:void 0};this.#e.push(n),this.#f(n),t.push(n),this.#w(n)}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(),n=()=>this.#i||t.signal.aborted||this.#a.get(e.id)!==t||!this.#e.includes(e);try{let o=await r.add(e.file,{signal:t.signal,onProgress:t=>{n()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#b(e),this.#m())}});if(n())return void(this.#i&&this.#l&&this.#h(o,r));this.#s.set(e,r),e.contentPart=o,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(n())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 n=this.#o?.querySelector(`[data-attachment-id="${e}"]`);n&&n.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.#o&&(this.#o.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.#o=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:wo(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,n="",o=e=>{r=e;let{state:o}=r,a=JSON.stringify([r.config.attachments?.preview,o.lineCount,o.previewUrl]);n!==a&&(n=a,(()=>{let{state:e}=r,n=r.config.attachments?.preview,o="image"===e.kind,a=o?n?.image:n?.file,s=o?n?.image?.layout??"thumbnail":n?.file?.layout??"tile";if(t.dataset.kind=e.kind,t.dataset.layout=s,t.dataset.fileIcon=String(!1!==n?.file?.icon),t.dataset.iconPlacement=n?.file?.iconPlacement??"start",t.dataset.removeVisibility=a?.remove?.visibility??"always",t.dataset.removePlacement=a?.remove?.placement??"overlap",t.replaceChildren(),o&&e.previewUrl){let r=it("img",{className:"persona-attachment-image",attrs:{src:e.previewUrl,alt:e.name},style:{objectFit:n?.image?.fit??"cover"}}),o=n?.image?.name??"hidden";if("chip"===s||"hidden"!==o){let n=st("div","persona-attachment-image-card");n.append(r),"hidden"!==o&&n.append(it("span",{className:"persona-attachment-file-name",text:"basename"===o?e.name.replace(/\.[^.]+$/,""):e.name})),t.append(n)}else t.append(r)}else{let r=st("div","persona-attachment-file"),o=e.mimeType,a=o.includes("spreadsheet")||o.includes("excel")?ge:"application/json"===o?me:"application/pdf"===o||o.startsWith("text/")||o.includes("word")?fe:be,s=(n?.file?.iconName?Ee(n.file.iconName,20,"currentColor",1.5):null)??oe(a,20,"currentColor",1.5);s&&!1!==n?.file?.icon&&(s.classList.add("persona-attachment-file-icon"),r.append(s));let i=st("div","persona-attachment-file-copy"),l=n?.file?.name??"hidden";"hidden"!==l&&i.append(it("span",{className:"persona-attachment-file-name",text:"basename"===l?e.name.replace(/\.[^.]+$/,""):e.name}));let d=n?.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=n?.file?.badge??"type";"none"!==p&&r.append(it("span",{className:"persona-attachment-file-badge",text:"extension"===p?e.name.match(/\.([^.]+)$/)?.[1].toUpperCase()??Co(o,e.name):Co(o,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=oe(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=o.status,t.setAttribute("aria-busy",String("uploading"===o.status||"processing"===o.status)),t.title="error"===o.status?`${o.name}: ${o.error??"Upload failed"}`:o.name;let s=t.querySelector(".persona-attachment-progress__bar");s&&(s.style.width="number"==typeof o.progress?`${Math.round(100*o.progress)}%`:"")};return o(e),{element:t,update:o}}(t)};return t}#f(e){if(!this.#o)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 n=r instanceof HTMLElement?{element:r}:r;n.element.dataset.attachmentId=e.id,this.#n.set(e.id,n),this.#o.appendChild(n.element)}#b(e){try{this.#n.get(e.id)?.update?.(this.#g(e))}catch(e){console.error("[AttachmentManager] preview update failed:",e)}}#y(e){let t=this.#n.get(e);if(t){this.#n.delete(e);try{t.destroy?.()}catch(e){console.error("[AttachmentManager] preview cleanup failed:",e)}finally{t.element.remove()}}}#v(){for(let e of this.#n.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 n=new FileReader;n.onload=()=>e(String(n.result??"")),n.onerror=()=>r(n.error),n.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.#o&&(this.#o.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 Zo=(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,n=!1,o=!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(n=!1,o||0===t.size)return;let e=a();for(let r of[...t])try{r(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",e)}},i=()=>{r=null,!o&&!n&&(n=!0,queueMicrotask(s))};return{getState:a,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,i())},setAttachments:t=>{((e,t)=>e.length===t.length&&e.every((e,r)=>{let n=t[r];return e.id===n.id&&e.name===n.name&&e.mimeType===n.mimeType&&e.size===n.size&&e.status===n.status&&e.progress===n.progress&&e.error===n.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Zo(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Zo(e.activeModeIds,t)||(e.activeModeIds=[...t],i())},setQuote:t=>{let r=e.quote;(r?.text!==t?.text||r?.messageId!==t?.messageId||r?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,i())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,i())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,i())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,i())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,i())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,i())},flush:()=>{n&&s()},destroy:()=>{o=!0,n=!1,t.clear()}}}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 na(e,t={}){let r=ta(e,"[data-persona-composer-form]"),n=ta(e,"[data-persona-composer-input]");if(!r||!n){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||n))throw Error(e);return typeof console<"u"&&console.warn(e),null}let o={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=o.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=o.body??n.parentElement??r,l=(e,t,r,n,o)=>{if(t)return t;a.add(e);let s=ra(r,n);return o.appendChild(s),s},d=l("actionsStart",o.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",o.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",o.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",o.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:n,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput: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:o,addListener:(e,t,r,n)=>{e.addEventListener(t,r,n),h.push({target:e,type:t,handler:r,options:n})},removeListener:(e,t,r,n)=>{e.removeEventListener(t,r,n),h=h.filter(n=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(n,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let oa="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 n=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 n.reduce((e,r)=>{let n=t.getComputedStyle(r);return e+("contents"===n.display?ia(r,t):Math.max(r.getBoundingClientRect().width,r.scrollWidth))+sa(n.marginLeft)+sa(n.marginRight)},0)+Math.max(0,n.length-1)*sa(r.columnGap)+sa(r.paddingLeft)+sa(r.paddingRight)}let la="[data-persona-composer-chip-row]";function da(e){let t=e.querySelector(la);if(t)return t;let r=it("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});r.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(r,n):e.appendChild(r),r}function ca(e){let t=it("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let r="",n=!1,o=r=>{let n=st("span","persona-composer-quote-bar"),o=st("div","persona-composer-quote-content");if(r.sourceLabel){let e=st("div","persona-composer-quote-source");e.textContent=r.sourceLabel,o.appendChild(e)}let a=it("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=Eo(r.text),o.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(n,o,s)};return{element:t,render:e=>{if(n)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(o(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function pa(e){let t=it("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let r,n=!1,o=(e,t,r,n)=>{let o=it("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=Ee(e,12,"currentColor",2);return a?o.appendChild(a):o.textContent=t,o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o};return{element:t,render:a=>{if(n||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=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=Eo(e.text??"",90);if(t)return t;let r=e.contentParts?.length??0;return r>0?1===r?"1 attachment":`${r} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(", "):"Queued message"})(a),t.replaceChildren(s,i,o("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),o("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function ua(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 n=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",n);let o=st("div","persona-message-edit-actions"),a=(e,t,r,n)=>{let o=it("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return o.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",s)),r.addEventListener("keydown",t=>{"Escape"===t.key?(t.preventDefault(),t.stopPropagation(),e.onCancel()):"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,o),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function ha(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 ma(e,t,r,n){let o=r.find(e=>e.id===t);if(!o)return[...e];let a=e.includes(t),s=new Set(e);if(a)s.delete(t);else{if("single"===((e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null)(o,n)){let e=r.filter(e=>e.groupId===o.groupId).map(e=>e.id);s=new Set([...s].filter(t=>!e.includes(t)))}s.add(t)}return r.filter(e=>s.has(e.id)).map(e=>e.id)}function ga(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function fa(e){return!e.wrapped&&!e.text.includes("\n")&&!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function ba(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let r=t.getComputedStyle(e).lineHeight;if(!r||!r.trim().endsWith("px"))return 20;let n=parseFloat(r);return Number.isFinite(n)&&n>0?n:20}function ya(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}function va(e,t){e.style.maxHeight=t*ba(e)+"px",e.style.overflowY="auto"}function wa(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 xa(e){return!0===e.insertNewlineOnTouchEnter&&!0===e.coarsePointer}function Ca(e,t){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,n=t.submitKey??"enter";return"none"!==n&&("mod-enter"===n?r:r||!xa(t))}function Sa(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?xa(e)?"enter":"send":"enter"}(t))}function ka(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let n=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};n("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),n("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),n("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),n("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function 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 n;try{n=e(Ma(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(n)?Promise.resolve(n).then(e=>r.aborted?{status:"aborted"}:Ia(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Ia(t,n)}let{setLoader:Ea,load:Ba}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),La=Ea,Ra=Ba,{setLoader:Pa,load:Na}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),$a=Pa,Wa=Na,Ha=400,Da=300,Fa=0,za=e=>Math.max(0,e);function Oa(e){void 0!==e.delayMs&&(Ha=za(e.delayMs)),void 0!==e.skipDelayMs&&(Da=za(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:n=r,text:o,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 o?o():o).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>za(e.delayMs??Ha),x=()=>za(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(),n=r.getBoundingClientRect(),o=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-o.width,h=n.left+n.width/2-o.width/2,m=Va(h,l,u),g=n.top-l,f=s-l-n.bottom,b=g>=o.height+i||g>=f?"top":"bottom",y="top"===b?n.top-i-o.height:n.bottom+i,v=s-l-o.height,w=Va(y,l,v),x=n.left+n.width/2,C=Math.max(10,o.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 n=d(),o=c();p=n.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=o.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=n.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=n.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=n.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),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()};o.addEventListener("scroll",g,!0),o.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:n.documentElement,C=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});C?.observe(x,{childList:!0,subtree:!0}),m=()=>{o.removeEventListener("scroll",g,!0),o.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()},B=()=>{f=!1,M()},L=()=>{g=!1,f=!1,S()},R=e=>{"Escape"===e.key&&L()};n.addEventListener("mouseenter",I),n.addEventListener("mouseleave",T),r.addEventListener("focus",E),r.addEventListener("blur",B),r.addEventListener("keydown",R),r.addEventListener("click",L);let P={get isOpen(){return null!==p},show:A,hide:S,reposition:k,destroy:()=>{b||(b=!0,S(),n.removeEventListener("mouseenter",I),n.removeEventListener("mouseleave",T),r.removeEventListener("focus",E),r.removeEventListener("blur",B),r.removeEventListener("keydown",R),r.removeEventListener("click",L),qa.delete(r))}};return qa.set(r,P),P}let Ja=(e,t,r,n)=>{let[o,a]=t.split(".");return[e?.theme,e?.darkTheme].some(e=>void 0!==e?.components?.[o]?.[a]?.[r])?`var(--persona-components-${t.replace(".","-")}-${r}, ${n})`:n},Ga=(e,t)=>{let r=e&&O(e,t);return"string"==typeof r&&r?r:void 0},Ya=(e,t,r,n)=>{let o=t.startsWith("var(");e.classList.toggle("persona-theme-padding",o),e.style.padding=o?"":t,o?e.style.setProperty("--persona-theme-padding",t):e.style.removeProperty("--persona-theme-padding"),r&&(e.style.paddingLeft=e.style.paddingRight=r),n&&(e.style.paddingTop=e.style.paddingBottom=n)},Xa=(e,t,r)=>{let n=t.startsWith("var(")&&t.includes("--persona-components-");e.classList.toggle("persona-control-size",n),n?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)},ns=(e,t)=>(Object.defineProperty(e,Za,{value:t,enumerable:!0,configurable:!0}),e),os=(e,t)=>ns(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"},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(os({...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,n=e.features?.artifacts,o=t.features?.scrollToBottom,a=e.features?.scrollToBottom,s=t.features?.scrollBehavior,i=e.features?.scrollBehavior,l=t.features?.streamAnimation,d=e.features?.streamAnimation,c=t.features?.askUserQuestion,p=e.features?.askUserQuestion,u=t.features?.history,h=e.features?.history,m=void 0===r&&void 0===n?void 0:{...r,...n,layout:{...r?.layout,...n?.layout}},g=void 0===o&&void 0===a?void 0:{...o,...a},f=void 0===s&&void 0===i?void 0:{...s,...i},b=void 0===l&&void 0===d?void 0:{...l,...d},y=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},v=void 0===u&&void 0===h?void 0:{...u,...h,copy:{...u?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay,...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===g?{}:{scrollToBottom:g},...void 0===f?{}:{scrollBehavior:f},...void 0===m?{}:{artifacts:m},...void 0===b?{}:{streamAnimation:b},...void 0===y?{}:{askUserQuestion:y},...void 0===v?{}:{history:v}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,cs),e):F(w(os(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:wa(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 n=ya(e?.composer?.maxLines,t?.defaultMaxLines??3),o=20*n+"px";return r.style.maxHeight=o,r.style.overflowY="auto",r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:()=>{r.addEventListener("input",()=>{r.style.height="auto";let e=Math.min(r.scrollHeight,(()=>{let e=r.style.maxHeight;if(e!==o){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=n*ba(r);return o=`${t}px`,r.style.maxHeight=o,t})());r.style.height=`${e}px`})}}},bs="[data-persona-glyph-stack]",ys=new WeakMap,vs=(e,t,r=!0)=>{ys.set(e,t);let n=t?.sendButton??{},o=n.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")||n.size;e.style.fontSize=o?"18px":"",e.style.lineHeight=o?"1":"",e.className=lt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${oa}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!s("backgroundColor")&&"persona-bg-persona-primary",!o&&!s("textColor")&&"persona-text-white"),Xa(e,o?l||(i("size","")?i("size","var(--persona-composer-control-size, 40px)"):""):"",o?l:void 0);let d=i("foreground",o?"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":"#ffffff"),c=i("background",o?"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","")||(o?d:"")),e.style.backgroundColor=(o?s("backgroundColor"):void 0)||(i("background","")?"stop"===a?`var(--persona-button-stop-bg, ${c})`:c:"");let p=s("borderWidth")||(i("borderWidth","")?i("borderWidth",n.borderWidth||"0px"):n.borderWidth||"");e.style.borderWidth=p,e.style.borderStyle=p?"solid":"",e.style.borderColor=s("borderColor")||(i("borderColor","")?i("borderColor",n.borderColor||"transparent"):n.borderColor||""),e.style.borderRadius=i("borderRadius","")?i("borderRadius","var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))"):"",Ya(e,i("padding",o?"0":"8px 16px"),o?void 0:s("paddingX")||(i("padding","")?void 0:n.paddingX),o?void 0:s("paddingY")||(i("padding","")?void 0:n.paddingY));let u=parseFloat(n.iconSize??"")||Math.round(.5*(parseFloat(n.size??"")||40));if(r)if(e.replaceChildren(),o){let t=n.iconStrokeWidth??2,r=n.iconName?Ee(n.iconName,u,"currentColor",t):null,o=Ee(n.stopIconName??"square",u,"currentColor",t);r&&o?e.appendChild(((e,t,r="send")=>{let n=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"),n.append(e,t),n})(r,o,a)):r?e.appendChild(r):e.textContent=n.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"),n=it("button",{attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"}});return vs(n,e),n.setAttribute("aria-label",t?.tooltipText??"Send message"),r.appendChild(n),Qa({anchor:n,trigger:r,text:()=>n.getAttribute("aria-label")??"",enabled:t?.showTooltip??!1}),{button:n,wrapper:r,setMode:e=>{if(n.getAttribute("data-persona-send-mode")===e)return;n.setAttribute("data-persona-send-mode",e),n.setAttribute("aria-label","stop"===e?t?.stopTooltipText??"Stop generating":t?.tooltipText??"Send message");let r=ys.get(n);vs(n,r,!1),n.querySelector(bs)?.setAttribute("data-mode",e),r?.sendButton?.useIcon||(n.textContent="stop"===e?r?.copy?.stopButtonLabel??"Stop":r?.copy?.sendButtonLabel??"Send")},glyphStack:n.querySelector(bs)}},xs=(e,t,r="idle",n="none")=>{let o=t?.voiceRecognition??{},a=e=>Ga(t,`voiceRecognition.${e}`),s=(e,r)=>Ja(t,"voice.control",e,r),i=a("iconSize")||o.iconSize;Xa(e,i||(s("size","")?s("size","var(--persona-composer-control-size, 40px)"):""),i),e.classList.add(oa),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",o.backgroundColor||"transparent"),c=a("borderColor")||s("borderColor",o.borderColor||"transparent"),p=a("borderWidth")||s("borderWidth",o.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:o.paddingX),a("paddingY")||(s("padding","")?void 0:o.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, ${o.recordingBorderColor||c})`,g=l,f=d,b=c,y=o.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=o.processingIconName??"loader";else if("speaking"===r){let e="barge-in"===n;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=o.speakingIconName??("cancel"===n?"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(o.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),n="runtype"===t.provider?.type,o="custom"===t.provider?.type||"custom"===t.dictation?.provider?.type;if(!(r||n||o))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 n=st("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??vo).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let o=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 ${oa} ${aa}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(o,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),n.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Qa({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:n,previewsContainer:r}},ks=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",n=st("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status",""),ur(n,t,"idle");let o=t.idleText??"Online";if(t.idleLink){let e=st("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=o,e.style.color="inherit",e.style.textDecoration="none",n.appendChild(e)}else n.textContent=o;return n},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,n=t.buttonIconName??"plus",o=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 ${oa} ${aa}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":o,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(n,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")??o}),{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",Bs="transparent",Ls={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:Bs,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},Ns=Ls.colors.gray,$s={...Ls,colors:{...Ls.colors,gray:Ns}},Ws={...Ls,colors:{...Ls.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"}},zs=Ds,Os=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:{rowHeight:"32px",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"}},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=Os,_s=e=>"v5"===(e=>ps({future:e}))(e)?{palette:Ws,semantic:Fs,components:qs}:{palette:$s,semantic:Ds,components:Os};function Us(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),n=e;for(let e of r){if(null==n)return;n=n[e]}return"string"==typeof n&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Us(e,n):n}function Vs(e){let t={};function r(n,o){for(let[a,s]of Object.entries(n)){let n=`${o}.${a}`;if("string"==typeof s){let r=Us(e,s);void 0!==r&&(t[n]={path:n,value:r,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,n)}}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,n]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&n&&"object"==typeof n&&!Array.isArray(n)?Qs(t,n):n}return r}function Js(e,t={}){let r=_s(t.future),n=e?.components,o={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:n?Qs(r.components,n):r.components},a=n?.activity;for(let e of["toolBubble","reasoningBubble"]){let t=o.components[e]={...o.components[e]};for(let r of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[r]&&("bodySurface"!==r||void 0===n?.[e]?.bodySurface)&&(t[r]=a[r])}let s=n?.collapsibleWidget?.surface;"v4"===ps(t)&&void 0!==s&&void 0===a?.bodySurface&&(o.components.activity={...o.components.activity,bodySurface:s});let i=n?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(o.components.header.minimalPadding=o.components.header.padding);let l=n?.composer;o.components.composer={...o.components.composer},void 0!==l?.padding&&void 0===l.expandedPadding&&(o.components.composer.expandedPadding=l.padding),void 0!==n?.input?.borderRadius&&void 0===l?.expandedBorderRadius&&(o.components.composer.expandedBorderRadius=n.input.borderRadius);let d=n?.message;if(void 0!==d?.gap&&void 0===d.fullscreenGap&&(o.components.message.fullscreenGap=o.components.message.gap),!1!==t.validate){let e=Ks(o);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)o=e.transform(o);return o}let Gs=e=>"0"===e.trim()?"0px":e,Ys="--persona-",Xs=(e,t)=>{for(let[r,...n]of t){let t;for(let r of n)if(t=61===r.charCodeAt(0)?r.slice(1):e[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,n]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=n.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,n,o,a="")=>{if(r)for(let[s,i,l]of o){let o=r[a+s];o&&(t[`--persona-${n}${i}`]=l?Us(e,o)??o:o)}};Xs(t,[["header-bg","components-header-background","surface"]]);let n=t["--persona-header-bg"],o=t["--persona-components-header-foreground"],a=o?`color-mix(in srgb, ${o} 72%, ${n})`:void 0;t["--persona-header-border"]=t["--persona-components-header-border"]??(o?`color-mix(in srgb, ${o} 14%, ${n})`: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"]??o??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 n=e(s.exitDurationMs);void 0!==n&&(t["--persona-history-exit-ms"]=n),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,"message-action-",[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]],"--persona-components-messageActions-"),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 n=t[`--persona-components-collapsibleWidget-${e}`]??t[`--persona-${r}`];void 0!==n&&(t[`--persona-cw-${e}`]=n,t[`--cw-${e}`]=n)}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"]]);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 n=m.toolbar;r(n,"artifact-toolbar-icon-",[["iconHoverColor","hover-color"],["iconHoverBackground","hover-bg"],["iconPadding","padding"],["iconBorderRadius","radius"],["iconBorder","border"]]),n.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Gs(n.toggleGroupGap)),n.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=n.toggleBorderRadius),n.toggleGroupPadding&&(t["--persona-artifact-toolbar-toggle-group-padding"]=Gs(n.toggleGroupPadding)),r(n,"artifact-toolbar-toggle-group-",[["toggleGroupBorder","border"],["toggleGroupBorderRadius","radius"]]),n.toggleGroupBackground&&(t["--persona-artifact-toolbar-toggle-group-bg"]=Us(e,n.toggleGroupBackground)??n.toggleGroupBackground),r(n,"artifact-toolbar-copy-",[["copyBackground","bg"],["copyBorder","border"],["copyColor","color"]]),n.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Gs(n.copyBorderRadius)),n.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=n.copyPadding),n.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=n.copyMenuBackground,t["--persona-dropdown-bg"]=t["--persona-dropdown-bg"]??n.copyMenuBackground),n.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=n.copyMenuBorder,t["--persona-dropdown-border"]=t["--persona-dropdown-border"]??n.copyMenuBorder),n.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=n.copyMenuShadow,t["--persona-dropdown-shadow"]=t["--persona-dropdown-shadow"]??n.copyMenuShadow),n.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=n.copyMenuBorderRadius,t["--persona-dropdown-radius"]=t["--persona-dropdown-radius"]??n.copyMenuBorderRadius),n.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=n.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=t["--persona-dropdown-item-hover-bg"]??n.copyMenuItemHoverBackground),r(n,"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[n,o,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*n+.7152*o+.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"}}},ni={...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"}}},oi=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??B(e?.brand)??"light";return"light"===t?"light":"dark"===t?"dark":ii()})(e),di=e=>{let t=li(e),r=k(((e,t="light",r,n=!1)=>{let o={};if(!e)return o;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);o.palette={colors:{primary:e,accent:e}},o.semantic={colors:{primary:e[500],accent:e[500],interactive:{default:e[500],hover:e[600],focus:e[500],active:e[700]}}},o.components={button:{primary:{background:e[500],foreground:t}},launcher:{background:e[500],foreground:t},header:n?{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:{user:n?{background:"color-mix(in srgb, var(--persona-primary) 12%, var(--persona-container))",text:"semantic.colors.text"}:{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)),n=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);o.palette={...o.palette,colors:{...o.palette?.colors,gray:d}},o.semantic={...o.semantic,colors:{...o.semantic?.colors,surface:n,background:n,container:a,border:i,divider:i,text:l,textMuted:T(r,"#ffffff"===l?255:0,.65)}},o.components={...o.components,panel:{background:n},header:{...o.components?.header,background:n,foreground:l},composer:{footerBackground:n}}}if(a){let e=A(o.semantic?.colors?.surface)??("dark"===t?[15,15,16]:[255,255,255]),r=I(a),n="#ffffff"===E(e)?255:0;for(let t=0;t<=1;t+=.1){r=T(a,n,t);let o=M(A(r)),s=M(e);if((Math.max(o,s)+.05)/(Math.min(o,s)+.05)>=4.5)break}o.components={...o.components,markdown:{link:{foreground:r}},input:{focus:{border:r,ring:r}}}}e.font?.trim()&&(o.semantic={...o.semantic,typography:{fontFamily:e.font}});let i={none:"0px",sm:"4px",md:"8px",lg:"16px"}[e.radius??"none"];e.radius&&i&&(o.palette={...o.palette,radius:{none:"0px",sm:i,md:i,lg:i,xl:i,"2xl":i}},o.components={...o.components,input:{...o.components?.input,borderRadius:i},header:{...o.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;o.semantic={...o.semantic,typography:{...o.semantic?.typography,fontSize:`${e}px`}},o.components={...o.components,header:{...o.components?.header,minHeight:`${t}px`,padding:`${r}px 16px`,minimalPadding:`${r}px 16px`},history:{railHeader:{minHeight:`${t}px`}},composer:{...o.components?.composer,fontSize:`${e}px`,padding:`${r}px`,gap:r/2+"px"},message:{...o.components?.message,gap:`${r}px`,user:{...o.components?.message?.user,fontSize:`${e}px`},assistant:{fontSize:`${e}px`}}}}if(e.elevation&&["flat","subtle","raised"].includes(e.elevation)){let t="flat"===e.elevation,n=t?"none":"subtle"===e.elevation?"0 2px 8px rgba(0, 0, 0, 0.08)":"0 12px 32px rgba(0, 0, 0, 0.18)",a=t?"1px solid var(--persona-border)":"1px solid color-mix(in srgb, var(--persona-border) 65%, transparent)";o.palette={...o.palette,shadows:{sm:n,md:n,lg:n,xl:n,"2xl":n}};let s=e=>{let r={};for(let[o,i]of Object.entries(e))if(o.toLowerCase().endsWith("shadow")){r[o]=n;let s="shadow"===o?"border":o.replace(/Shadow$/,"Border");s in e&&(r[s]="string"==typeof e[s]&&e[s].includes("solid")?a:t?"semantic.colors.border":"color-mix(in srgb, var(--persona-border) 65%, transparent)")}else if(i&&"object"==typeof i){let e=s(i);Object.keys(e).length&&(r[o]=e)}return r},i=r?s(r):{};o.components=k(o.components,i),o.components={...o.components,panel:{...o.components?.panel,shadow:n,modes:{floating:{shadow:n,border:a},inline:{shadow:n,border:a},docked:{shadow:n,border:a},sidebar:{shadow:n,border:a},mobile:{shadow:n,border:a}}},launcher:{...o.components?.launcher,shadow:n,border:"semantic.colors.border"},composer:{...o.components?.composer,shadow:n,borderColor:"semantic.colors.border"},toolBubble:{shadow:n},reasoningBubble:{shadow:n}}}return o})(e?.brand,t,_s(e?.future).components,e?.future?.v5Defaults),si(e?.theme)),n=k({components:{launcher:"circle"===Is(e)?Ts:{...Os.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),o=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,n=t.darkTheme?.components?.panel?.width;return null==("dark"===li(t)?n??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:ni,components:ai}:{palette:ri,components:oi})(t.future),n=k(r.components,e??{})??{};return Js({...n,palette:{...n.palette,colors:"v5"===ps(t)?k(r.palette.colors,n.palette?.colors):{...r.palette.colors,...n.palette?.colors}}},{validate:!1,future:t.future})})(k(n??{},o??{}),{future:e?.future}):((e,t={})=>Js(e,t))(n,{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("-"),n=t[`--persona-components-${e}`];void 0!==n&&(t["suggestion.chip.padding"===r?"--persona-suggestion-compat-padding":"suggestion.chip.fontWeight"===r?"--persona-suggestion-compat-weight":`--persona-consumer-${e}`]=n)}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,n]of Object.entries(t))e.style.setProperty(r,n);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)"),n=()=>e(ii());r.addEventListener?(r.addEventListener("change",n),t.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),t.push(()=>r.removeListener(n)))}return()=>{t.forEach(e=>e())}},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(),n={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)n.mod=!0;else if("shift"===r)n.shift=!0;else{if("alt"!==r&&"option"!==r)return vi("unknown modifier in",e),null;n.alt=!0}return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(vi("unsupported",e),null):("space"===r&&(n.key=" "),n)},xi=(e,t)=>{let r=wi(e);if(!r)return"";let n=yi(),o=(e=>"ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space".split(" ").find(t=>t.toLowerCase()===e)??(" "===e?"Space":1===e.length?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))(r.key);if(!t&&n)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${o}`;let a=[t?n?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(o),a.join("+")},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),n=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let n=r.composedPath?.();return n?.length?n.includes(e):e.contains(r.target)},o=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let o of t.values())if(ki(o.parsed,e)&&!1!==o.when?.()&&n(o,e)&&(o.allowInInput||!Ai(r))){e.preventDefault();try{o.run(e)}catch(e){vi(`${o.id} threw on`,o.combo),console.warn(e)}return}};return r?.addEventListener("keydown",o),{register(e){let r=wi(e.combo);if(!r)return()=>{};let n=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,o=t.get(n);return o?(vi(`${o.id} already owns`,e.combo),()=>{}):(t.set(n,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",Si(e.combo)),()=>{t.get(n)?.id===e.id&&t.delete(n),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",o)}}};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,o){if(!1===o.callbacks.beforeNodeAdded(t))return null;if(o.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),n(a,t,o),o.callbacks.afterNodeAdded(a),a}{let n=document.importNode(t,!0);return e.insertBefore(n,r),o.callbacks.afterNodeAdded(n),n}}let t=function(){function e(e,t,r){let n=e.idMap.get(t),o=e.idMap.get(r);if(!o||!n)return!1;for(let e of n)if(o.has(e))return!0;return!1}function t(e,t){let r=e,n=t;return r.nodeType===n.nodeType&&r.tagName===n.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===n.getAttribute?.("id"))}return function(r,n,o,a){let s=null,i=n.nextSibling,l=0,d=o;for(;d&&d!=a;){if(t(d,n)){if(e(r,d,n))return d;null===s&&(r.idMap.has(d)||(s=d))}if(null===s&&i&&t(d,i)&&(l++,i=i.nextSibling,l>=2&&(s=void 0)),r.activeElementAndParents.includes(d))break;d=d.nextSibling}return s||null}}();function r(e,t){if(e.idMap.has(t))s(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;t.parentNode?.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function o(e,t,n){let o=t;for(;o&&o!==n;){let t=o;o=o.nextSibling,r(e,t)}return o}function a(e,t,r,n){let o=n.target.getAttribute?.("id")===t&&n.target||n.target.querySelector(`[id="${t}"]`)||n.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let n=t.idMap.get(e);n&&(n.delete(r),n.size||t.idMap.delete(e))}}(o,n),s(e,o,r),o}function s(e,t,r){if(e.moveBefore)try{e.moveBefore(t,r)}catch{e.insertBefore(t,r)}else e.insertBefore(t,r)}return function(s,i,l,d=null,c=null){i instanceof HTMLTemplateElement&&l instanceof HTMLTemplateElement&&(i=i.content,l=l.content),d||=i.firstChild;for(let r of l.childNodes){if(d&&d!=c){let e=t(s,r,d,c);if(e){e!==d&&o(s,d,e),n(e,r,s),d=e.nextSibling;continue}}if(r instanceof Element){let e=r.getAttribute("id");if(s.persistentIds.has(e)){let t=a(i,e,d,s);n(t,r,s),d=t.nextSibling;continue}}let l=e(i,r,d,s);l&&(d=l.nextSibling)}for(;d&&d!=c;){let e=d;d=d.nextSibling,r(s,e)}}}(),n=function(){function e(e,r,n){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)o(e.name,a,"update",n)||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(o(t.name,a,"remove",n))continue;a.removeAttribute(t.name)}}s(a,n)||t(a,i,n)}(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;n(e,t,"checked",r),n(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(o("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):o("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)n(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let n=t.value,a=e.value;if(o("value",e,"update",r))return;n!==a&&(e.value=n),e.firstChild&&e.firstChild.nodeValue!==n&&(e.firstChild.nodeValue=n)}}function n(e,t,r,n){let a=t[r];if(a!==e[r]){let s=o(r,e,"update",n);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):o(r,e,"remove",n)||e.removeAttribute(r)}}function o(e,t,r,n){return!("value"!==e||!n.ignoreActiveValue||t!==document.activeElement)||!1===n.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,n,o){return o.ignoreActive&&t===document.activeElement?null:(!1===o.callbacks.beforeNodeMorphed(t,n)||(t instanceof HTMLHeadElement&&o.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==o.head.style?a(t,n,o):(e(t,n,o),s(t,o)||r(o,t,n))),o.callbacks.afterNodeMorphed(t,n)),t)}}();function o(e,t,r,n){if(e.head.block){let o=t.querySelector("head"),s=r.querySelector("head");if(o&&s){let t=a(o,s,e);return Promise.all(t).then(()=>n(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return n(e)}function a(e,t,r){let n=[],o=[],a=[],s=[],i=new Map;for(let e of t.children)i.set(e.outerHTML,e);for(let t of e.children){let e=i.has(t.outerHTML),n=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?n?o.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?n&&(o.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&o.push(t)}s.push(...i.values());let l=[];for(let t of s){let o=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(o)){if("href"in o&&o.href||"src"in o&&o.src){let e,t=new Promise(function(t){e=t});o.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(o),r.callbacks.afterNodeAdded(o),n.push(o)}}for(let t of o)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:n,kept:a,removed:o}),l}let 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 n(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 o(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function a(e,t,r,n){for(let o of n){let n=o.getAttribute("id");if(t.has(n)){let t=o;for(;t;){let o=e.get(t);if(o??(o=new Set,e.set(t,o)),o.add(n),t===r)break;t=t.parentElement}}}}function s(e,t){let r=o(e),n=o(t),s=function(e,t){let r=new Set,n=new Map;for(let{id:t,tagName:o}of e)n.has(t)?r.add(t):n.set(t,o);let o=new Set;for(let{id:e,tagName:a}of t)o.has(e)?r.add(e):n.get(e)===a&&o.add(e);for(let e of r)o.delete(e);return o}(r,n),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,n),{persistentIds:s,idMap:i}}return function(t,o,a){let{persistentIds:i,idMap:l}=s(t,o),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:o,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:n(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 n=r.querySelectorAll(e);for(let e=0;e<n.length;e++)t.push(n[e])}return t},[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function r(n){if(null==n)return document.createElement("div");if("string"==typeof n)return r(function(t){let r=new DOMParser,n=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let o=r.parseFromString(t,"text/html");if(n.match(/<\/html>/))return e.add(o),o;{let t=o.firstChild;return t&&e.add(t),t}}{let n=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(n),n}}(n));if(e.has(n))return n;if(n instanceof Node){if(n.parentNode)return new t(n);{let e=document.createElement("div");return e.append(n),e}}{let e=document.createElement("div");for(let t of[...n])e.append(t);return e}}}}();return{morph:function(e,t,n={}){e=i(e);let a=l(t),d=s(e,a,n),c=function(e,t){if(!e.config.restoreFocus)return t();let r=document.activeElement;if(!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return t();let{id:n,selectionStart:o,selectionEnd:a}=r,s=t();return n&&n!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${n}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(o,a),s}(d,()=>o(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,n){let o=l(t);return r(e,o,n,t,t.nextSibling),Array.from(o.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let Ii=(e,t,r={})=>{let{preserveTypingAnimation:n=!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(n){if(e.classList.contains("persona-animate-typing")||e.hasAttribute("data-preserve-runtime"))return!1;if(e.hasAttribute("data-tool-elapsed"))return!(t instanceof HTMLElement&&t.getAttribute("data-tool-elapsed")===e.getAttribute("data-tool-elapsed"))&&void 0;if(e.hasAttribute("data-preserve-animation"))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 Bi(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 Li(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.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)??"",Bi(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,n,o)=>{if(!o)return e;if(r?.bufferContent)return r.bufferContent(e,n);if(!e)return e;if("word"===t){let t=e.search(/\s(?=\S*$)/);return t<0?"":e.slice(0,t)}if("line"===t){let t=e.lastIndexOf("\n");return t<0?"":e.slice(0,t)}return e},zi=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=t,o},Oi=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=t,o},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 n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(qi.test(a[i])){let e=i;for(;e<a.length&&qi.test(a[e]);)e+=1;s.appendChild(n.createTextNode(a.slice(i,e))),i=e}else{let e=n.createElement("span");e.className="persona-stream-word-group";let o=i;for(;o<a.length&&!qi.test(a[o]);)e.appendChild(zi(n,a[o],t,r.value)),r.value+=1,o+=1;s.appendChild(e),i=o}o.replaceChild(s,e)},Ui=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(n.createTextNode(e)):(s.appendChild(Oi(n,e,t,r.value)),r.value+=1));o.replaceChild(s,e)},Vi=(e,t,r,n)=>{if(!e||typeof document>"u")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set((n?.skipTags??Ri).map(e=>e.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)ji(l,a)||i.push(l),l=s.nextNode();let d={value:n?.startIndex??0},c="char"===t?_i:Ui;for(let e of i)c(e,r,d);return o.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 n=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${n}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Gi.get(t);if(r||(r=new Map,Gi.set(t,r)),r.has(e.name))return;let n=e.onAttach(t);r.set(e.name,n)})(e,t)},{setLoader:Zi,load:el}=_({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),tl=Zi,rl=el;function nl(e,t=1e5){let r=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s="static"===a.position||""===a.position;return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=n,e.style.isolation=o}}let ol=0,al=null;function sl(e=document){if(ol++,1===ol){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,ol=Math.max(0,ol-1),0===ol&&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??true,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 n=e.prompt?.trim()||r;return{id:e.id?.trim()||n||`suggestion-${t}`,label:r,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},hl=new WeakSet,ml=e=>{let{item:t,index:r,surface:n,source:o,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,m="followUp"===n,g=t.behavior,f=()=>{if(c.isStreaming()||u.closest("[inert]"))return;let e={instanceId:cl(u),suggestion:{...t},surface:n,source:o,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:n,source:o,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=>z(t,`suggestionChipsConfig.${e}`),n=e=>q(i,`suggestion.chip.${e}`,"light")||q(i,`suggestion.chip.${e}`,"dark");d?.fontWeight&&(e.style.fontWeight=!r("fontWeight")&&n("fontWeight")?"var(--persona-suggestion-compat-weight, 500)":d.fontWeight);let o=n("padding");o&&(e.classList.add("persona-theme-padding"),e.style.setProperty("--persona-theme-padding","var(--persona-suggestion-compat-padding, 6px 12px)")),d?.paddingX&&(r("paddingX")||!o)&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(r("paddingY")||!o)&&(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=oe(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:n,source:o,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=[],n=null,o=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(o=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),n=parseFloat(r.paddingLeft)||0,o=parseFloat(r.paddingRight)||0;e.style.setProperty("--persona-suggestion-bleed-left",`${n}px`),e.style.setProperty("--persona-suggestion-bleed-right",`${o}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:n}px`),e.style.setProperty("--persona-suggestion-inset-right",`${i?.width?s.right-i.right:o}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,n=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=n<=4,i=n>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==o||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():o=requestAnimationFrame(s)};e.addEventListener("scroll",i,{passive:!0});let l="function"==typeof ResizeObserver?new ResizeObserver(i):null;return l?.observe(e),{buttons:t,elements:r,destroy:()=>{e.removeEventListener("scroll",i),l?.disconnect(),null!==o&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o),o=null},render:(o,l,d,c,p,u)=>{e.replaceChildren(),t.length=0,r.length=0;let h=u?.source??"config",m=u?.surface??("config"===h?"starter":"followUp"),g="followUp"===m,f=u?.variant??"chip",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(o??[]);w.forEach(e=>{e.transformSuggestions&&(k=S(e.transformSuggestions({suggestions:k.map(e=>({...e})),surface:m,source:h,config:v})))});let A=void 0===x?k:k.slice(0,x);if(!A.length)return e.hidden=!0,n=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(n=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=pl(m),e.dataset.variant=f,e.dataset.overflow=y;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((n,o)=>{let a=ml({item:n,index:o,surface:m,source:h,variant:f,streaming:I,config:v,plugins:w,chipsConfig:p,session:l,getTextarea:()=>d,eventTarget:e,submitPrompt:u?.submitPrompt});M.appendChild(a),r.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll("button"))].forEach(e=>{t.includes(e)||(e.disabled=I,t.push(e))})}),e.appendChild(M),s(),i();let T=JSON.stringify({normalized:A,surface:m,variant:f,source:h});T!==n&&(n=T,(e=>{typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||e.forEach((e,t)=>{"function"==typeof e.animate&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:60*t,easing:"ease-out",fill:"backwards"})})})(r),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{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:n,iconText:o}=r,[a,s]=bl[t]??[1,1.5],i=!n;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=Ee(t,`${Math.round((parseFloat(n??"")||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)):o&&(e.textContent=o)},wl=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:n,iconName:o,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 o?vl(x,o,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Qa({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:n,enabled:r}),{button:x,wrapper:v}},xl=(e,t,r,n={})=>{let o=t?.launcher,a=o?.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,n)=>Ja(t,`header.${r}`,e,n),l=(e,t,r)=>s(e)||i(t,r),d=n.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?o?.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?o?.closeButtonBorderWidth:a?.borderWidth,u="close"===r?o?.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?o?.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?o?.closeButtonPaddingX:a?.paddingX,f="close"===r?o?.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?o?.closeButtonIconName??"x":a?.iconName??"refresh-cw";vl(e,y,{iconSize:n.iconSize,iconText:"close"===r?o?.closeButtonIconText??"×":void 0});let v=e.querySelector("svg");if(v){let e=bl[y]?.[0]??1,t=i("iconSize","");!n.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:n=yl,buttonSize:o,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:n,size:o??s.closeButtonSize,iconSize:a,color:s.closeButtonColor,backgroundColor:s.closeButtonBackgroundColor,borderWidth:s.closeButtonBorderWidth,borderColor:s.closeButtonBorderColor,borderRadius:s.closeButtonBorderRadius,paddingX:s.closeButtonPaddingX,paddingY:s.closeButtonPaddingY,hidden:!r});return xl(d,e,"close",{buttonSize:o,iconSize:a}),{button:d,wrapper:c}},Sl=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:n,iconSize:o}=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:n??a.size,iconSize:o,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return xl(l,e,"clear",{buttonSize:n,iconSize:o}),{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,n=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)))"}}),o=t?.launcher??{},a=o.headerIconSize??"40px",s=o.closeButtonPlacement??"inline",i=o.headerIconHidden??!1,l=o.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?n.append(c):n.append(d,c);let h=o.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&&n.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&&n.appendChild(v),{header:n,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:y,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:b}},Tl=(e,t,r)=>{let n=r?.launcher??{},o=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===o&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))},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},Bl=e=>{let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,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=o?.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}}))},n=c.onSelect(t);n instanceof Promise?n.then(r,()=>{}):r(n)},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),o?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=o.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=o?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??"10px",l.style.padding=e.padding??"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{l.style.backgroundColor=e.background??"",l.style.borderColor=e.border??""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:u,wrapper:h}=Cl(t,{showClose:r,wrapperClassName:p});n&&u.addEventListener("click",n);let m=st("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let n of t){let{button:t,wrapper:o}=wl({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?Ci(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",n.id),n.shortcut){let e=Si(n.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(n.menuItems?.length){let e=ct({items:n.menuItems,onSelect:e=>r?.(e),anchor:o,position:"bottom-right"});o.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(n.id));e.appendChild(o)}}(m,o?.trailingActions,o?.onAction??a);let g=s.clearChat??{},f=null,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}},Ll={default:El,minimal:Bl},Rl=e=>Ll[e]??Ll.default,Pl=(e,t,r)=>{if(t?.render){let n=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),o=st("div");o.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:n,iconHolder:o,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let n=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&&(n.iconHolder.style.display="none"),!1===t.showTitle&&(n.headerTitle.style.display="none"),!1===t.showSubtitle&&(n.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(n.closeButton.style.display="none"),!1===t.showClearChat&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n};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"}}),n=As(),o=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"}});o.append(p),d&&(p.append(d.previewsContainer),o.append(d.input)),o.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),o.append(u),o.addEventListener("click",e=>{Nl(o,e)}),"transient"===t?.statusIndicator?.mode?r.append(n,c,o):r.append(n,o,c),{footer:r,suggestions:n,composerForm:o,header:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}},Wl=e=>{let{config:t}=e,r=it("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=As(),o=ks(t);o.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(n,c,o);let m=c;return{footer:r,suggestions:n,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:o,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:p,rightActions:u,setSendButtonMode:i.setMode}};function 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 n=Ee(e.iconName??"at-sign",13,"currentColor",2);if(n){let e=st("span","persona-mention-token-icon");e.appendChild(n),r.appendChild(e)}return r.appendChild(it("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let Dl=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(":"))},Fl=(e={})=>{let t=e.loadingIndicator,r=e.future?.v5Defaults;if("label"===(t?.variant??(r?"label":"dots"))){let n=it("div",{className:"persona-loading-label",attrs:{role:"status"}});r&&!0!==t?.showBubble&&n.classList.add("persona-activity-row","persona-activity-header");let o=e.features?.toolCallDisplay,a=t?.iconVisibility??(!1!==o?.grouped&&"collapsible"===(o?.groupedMode??"collapsible")?o?.groupIconVisibility:void 0)??o?.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"),n.appendChild(e))}let i=it("span",{text:t?.label??"Thinking…"});return n.appendChild(i),je()?.applyLoadingLabel(i,e,"waiting"),n}let n=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",n.appendChild(t)}let o=st("span","persona-sr-only");return o.textContent="Loading",n.appendChild(o),n},zl=(e,t,r)=>t?.({config:r??{},streaming:!0,location:e,defaultRenderer:()=>Fl(r)})??Fl(r),Ol=(e,t,r="div")=>{let n=st(r,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return n.textContent=t.format?t.format(o):o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ql=(e,t="bubble")=>{let r=["persona-message-bubble"];switch(t){case"flat":"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3")}return r},jl={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"}},_l=(e,t,r="bubble",n)=>{if(!n)return;let o="user"===t?"user":"assistant",a=jl[r??"bubble"]??jl.bubble;n.padding&&(e.style.padding=`var(--persona-message-${o}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${o}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${o}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${o}-font-family, inherit)`)},Ul=e=>`custom:${e}`,Vl=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),Kl=(e,t,r,n,o=!1)=>{let a=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&!0===n?.canRegenerate,c=(t.showEdit??!1)&&!0===n?.canEdit,p=(t.showQuote??!1)&&!1!==n?.canQuote,u=Vl(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??(o&&n?.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":""} ${o?"persona-message-actions-adaptive":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let b=(e,t,r)=>{let n=pt({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return n.setAttribute("data-action",r),n};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,Ul(e.id)));return f},Ql=(e,t,r,n,o,a)=>{let s=r??{},i=s.layout??"bubble",l=s.avatar,d=s.timestamp,c=l?.show??!1,p=d?.show??!1,u=l?.position??"left",h=d?.position??"below",m=ql(e.role,i),g=st("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":"assistant-message");let f=_s(a?.widgetConfig?.future).components.message,b=a?.widgetConfig?.theme?.components?.message;_l(g,e.role,i,"user"===e.role?{...f.user,...b?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...f.assistant,...b?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),"flat"===i?(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):"user"===e.role?(g.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",g.style.color="var(--persona-message-user-text, white)"):"assistant"===e.role&&(g.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",g.style.color="var(--persona-message-assistant-text, var(--persona-text))");let y=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),v=e.content?.trim()??"",w=y.length>0&&"[Image]"===v,x=Pi(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?Di(x.type,C):null,k="assistant"===e.role&&!0===S?.isAnimating?.(e),A="assistant"===e.role&&null!==S&&(!!e.streaming||k);A&&S?.bubbleClass&&g.classList.add(S.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),A&&S&&(S.containerClass&&M.classList.add(S.containerClass),M.style.setProperty("--persona-stream-step",`${x.speed}ms`),M.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let I=A?Fi(e.content??"",x.buffer,S,e,!!e.streaming):e.content??"",T=()=>{let r=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent});return A&&"char"===S?.wrap?Vi(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?Vi(r,"word",e.id,{skipTags:S.skipTags}):r},E=null;if(w?(E=document.createElement("div"),E.innerHTML=T(),E.style.display="none",M.appendChild(E)):e.contentSegments?.length?((e,t,r,n)=>{let o=Math.random().toString(36).slice(2,8),a=e=>`${o}:${e}`,s=r(t.map((e,t)=>"text"===e.kind?e.text:a(t)).join(""));if(!t.every((e,t)=>"text"===e.kind||s.includes(a(t))))return void e.replaceChildren(((e,t)=>{let r=document.createDocumentFragment();for(let n of e)"text"===n.kind?r.appendChild(document.createTextNode(n.text)):r.appendChild(Hl(n.ref,{readonly:!0,render:t}));return r})(t,n));e.innerHTML=s;let i=RegExp(`${o}:(\\d+)`),l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),d=[];for(let e=l.nextNode();e;e=l.nextNode())d.push(e);for(let e of d){let r=e;for(let e=i.exec(r.data);e;e=i.exec(r.data)){let o=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===o?.kind&&a.parentNode?.insertBefore(Hl(o.ref,{readonly:!0,render:n}),a),r=a}}})(M,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=T(),A&&S?.useCaret&&!w&&v){let e=Ki(),t=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=M.lastElementChild;t?t.appendChild(e):M.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=Ol(e,d,"span");t.classList.add("persona-timestamp-inline");let r=M.lastElementChild;r?r.appendChild(t):M.appendChild(t)}if(y.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let n=st("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),r?.())};return e.forEach((e,t)=>{let r=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;o+=1,r.addEventListener("error",()=>{a||(a=!0,o=Math.max(0,o-1),r.remove(),0===o&&s())}),r.addEventListener("load",()=>{a=!0}),(e=>{let t=e.toLowerCase();return!(t.startsWith("data:image/svg+xml")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:image/")&&e.includes(":"))})(e.image)?(r.src=e.image,n.appendChild(r)):(a=!0,o=Math.max(0,o-1),r.remove())}),0===o?(s(),null):n}catch{return r?.(),null}})(y,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let B=(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(B.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(!Dl(e.audio))return;let n=st("audio");n.controls=!0,n.preload="metadata",n.src=e.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let L=(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(L.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(!Dl(e.video))return;let n=st("video");n.controls=!0,n.preload="metadata",n.src=e.video,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",n.style.maxHeight="320px",n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(L);e&&g.appendChild(e)}let R=(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(R.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(!Dl(e.data))return;let n=st("a");n.href=e.data,n.download=e.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(R);e&&g.appendChild(e)}let P=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}}),n=st("span","persona-mention-chip-icon"),o=Ee(r.iconName??"at-sign",13,"currentColor",2);o&&n.appendChild(o),e.appendChild(n),e.appendChild(it("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(P&&g.appendChild(P),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=Ol(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let N="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 n=t?.[e];return(void 0===n?r:n)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!I||!I.trim()),t="skeleton"===x.placeholder,r=t&&"line"===x.buffer&&e;if(e)r&&g.appendChild(Qi());else if(t)g.appendChild(Qi());else{let e=zl("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}N&&e.stopReason&&!e.streaming&&(v||(M.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,N)));let $="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==n?.enabled,W=a?.actionEligibility,H="user"===e.role&&!e.streaming&&!1!==n?.enabled&&(!0===n?.showEdit&&!0===W?.canEdit||!0===n?.showQuote&&!0===W?.canQuote||Vl(n,"user").length>0);if(($||H)&&n){let t=Kl(e,H?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,0,W,!0===a?.widgetConfig?.future?.v5Defaults&&void 0===n.visibility);g.appendChild(t)}if(!c||"system"===e.role)return g;let D=st("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),F=((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"),n="user"===t?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=st("img");e.src=n,e.alt="user"===t?"User":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent="user"===t?"U":"A",r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?D.append(g,F):D.append(F,g),D},Jl=(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)},Gl=(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")},Yl="data-persona-welcome-overlay",Xl="persona-welcome-overlay-active",Zl=new WeakMap,ed=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Yl,""),e.classList.contains(Xl)||(Zl.set(e,e.scrollTop),e.classList.add(Xl),e.scrollTop=0)},td=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Yl),e.classList.contains(Xl)&&(e.classList.remove(Xl),e.scrollTop=Zl.get(e)??e.scrollTop,Zl.delete(e))},rd=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let n=r?.layout?.messages?.layout??"bubble",o=it("div",{className:ql("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===n?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(it("div",{className:"persona-flex"},o)),e.hidden=!1},nd=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,od=(e,t)=>{if(nd()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),n=e.parentElement,o=0,a=0,s=0;if(n){let t=getComputedStyle(n);o=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=n.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-n.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-o:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-o:0)}let i=e.style.overflow;e.style.overflow="hidden";let l=getComputedStyle(e),d=parseFloat(l.paddingTop)||0,c=parseFloat(l.paddingBottom)||0,p=e.animate([{opacity:"1",transform:"none",height:`${r.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${c}px`,marginTop:`${a}px`,marginBottom:`${s}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:-o+"px"}],{duration:180,easing:"ease-out",fill:"forwards"}),u=!1,h=()=>{u||(u=!0,e.style.overflow=i,t(p))};return p.finished.then(h).catch(h),p},ad=(e,t,r,n=260)=>{if(t<=1||nd()||"function"!=typeof e.animate||!e.isConnected)return null;let o="drop"===r?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:n,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})},sd=new WeakSet,id=(e,t)=>!!e&&void 0!==e[t],ld=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,n=e?.copy,o=!0===e?.future?.v5Defaults,a=r?.layout??(o?"centered":"top"),s=id(r,"variant")?r.variant:!1===n?.showWelcomeCard?"none":"card",i="hero"!==s||o||void 0!==r?.layout?id(r,"dismiss")?r.dismiss:o||"hero"===s?"on-first-message":"never":"on-first-message",l=[];for(let[e,t]of[["title","welcomeTitle"],["subtitle","welcomeSubtitle"],["variant","showWelcomeCard"]])id(r,e)&&id(n,t)&&l.push(`welcome.${e} and copy.${t} are both set; welcome.${e} wins. copy.${t} is deprecated.`);"hero"===s&&id(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!o&&void 0===r?.layout&&"hero"===s&&id(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 id(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(id(r,"anchorComposerTop")||id(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{e&&!0===e.debug&&t.length&&!sd.has(e)&&(sd.add(e),t.forEach(e=>console.warn(`[persona] ${e}`)))})(e,l),{title:id(r,"title")?r.title:n?.welcomeTitle??(o?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:id(r,"subtitle")?r.subtitle:n?.welcomeSubtitle??(o?"":"I can answer questions and help you get things done here."),icon:r?.icon,align:"start"===r?.align||"center"===r?.align?r.align:"centered"===a?"center":void 0,iconPlacement:r?.icon&&"function"!=typeof r.icon&&"inline"===r.icon.placement?"inline":"above",variant:s,dismiss:i,message:"hero"===s?void 0:r?.message,layout:a,anchor:d,anchorComposerTop:c?r.anchorComposerTop:"44%",composerGap:r?.composerGap?.trim()||"24px"}},dd=(e=[])=>e.some(e=>"user"===e.role||"assistant"===e.role&&(e.content.trim()||e.contentParts?.some(e=>"text"!==e.type||e.text.trim())||e.toolCall||e.tools?.length||e.reasoning||e.approval)),cd=e=>dd(e)?"active":"empty",pd=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!dd(t)),ud="var(--persona-components-panel-height)",hd=e=>{let t=rs(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,n=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===n?`max(200px, ${ud})`:`max(200px, calc(${ud} - ${n}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},md=e=>{let t=rs(e);return t.launcherWidth||t.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?hd(e).width:"100%"},gd="16px",fd="10px",bd="14px",yd=e=>{let t=it("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":pl(e)}});return t.hidden=!0,t},vd=(e,t)=>{let r=((e,t,r={})=>{let n=it("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let o=st("p","persona-welcome-kicker");o.hidden=!0;let a=st("h2","persona-welcome-title"),s=st("p","persona-welcome-subtitle"),i=it("div",{className:"persona-welcome-head-text"},o,a),l=it("div",{className:"persona-welcome-title-row"},n,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:n,kicker:o,title:a,subtitle:s,starterSuggestions:t}})(0,yd("starter"),{flatShadow:il(e)}),n=ld(e);Gl(r,n),Jl(t,r.host,pd(n,e?.initialMessages));let o=(()=>{let e=it("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return rd(o,n.message,e),{welcome:r,greetingHost:o}},wd=(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 n=e=>{let t=e.launcher??{},n=il(e),o="circle"===Is(e);o?(r.dataset.personaLauncherVariant="circle",r.setAttribute("aria-label",t.title??"Open chat")):(r.removeAttribute("data-persona-launcher-variant"),r.removeAttribute("aria-label"));let a=r.querySelector("[data-role='launcher-title']");if(a){let e=t.title??"Chat Assistant";a.textContent=e,a.setAttribute("title",e)}let s=r.querySelector("[data-role='launcher-subtitle']");if(s){let e=t.subtitle??"Here to help you get answers fast";s.textContent=e,s.setAttribute("title",e)}let i=r.querySelector(".persona-flex-col");i&&(t.textHidden||n||o?i.style.display="none":i.style.display="");let l=r.querySelector("[data-role='launcher-icon']");if(l)if(t.agentIconHidden)l.style.display="none";else{let e=t.agentIconSize??"40px";if(l.style.height=e,l.style.width=e,t.agentIconBackgroundColor?(l.style.backgroundColor=t.agentIconBackgroundColor,l.classList.remove("persona-bg-persona-primary")):(l.style.backgroundColor="",l.classList.add("persona-bg-persona-primary")),l.innerHTML="",t.agentIconName){let r=parseFloat(e)||24,n=Ee(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);n?(l.appendChild(n),l.style.display=""):(l.textContent=t.agentIconText??"💬",l.style.display="")}else t.iconUrl?l.style.display="none":(l.textContent=t.agentIconText??"💬",l.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let e=t.agentIconSize??"40px";d.style.height=e,d.style.width=e,!t.iconUrl||t.agentIconName||t.agentIconHidden?d.style.display="none":(d.src=t.iconUrl,d.style.display="block")}let c=r.querySelector("[data-role='launcher-call-to-action-icon']");if(c){let e=t.callToActionIconSize??"32px";c.style.height=e,c.style.width=e,t.callToActionIconBackgroundColor?(c.style.backgroundColor=t.callToActionIconBackgroundColor,c.classList.remove("persona-bg-persona-primary")):(c.style.backgroundColor="",c.classList.add("persona-bg-persona-primary")),t.callToActionIconColor?(c.style.color=t.callToActionIconColor,c.classList.remove("persona-text-persona-call-to-action")):(c.style.color="",c.classList.add("persona-text-persona-call-to-action"));let r=0;if(t.callToActionIconPadding?(c.style.boxSizing="border-box",c.style.padding=t.callToActionIconPadding,r=2*(parseFloat(t.callToActionIconPadding)||0)):(c.style.boxSizing="",c.style.padding=""),t.callToActionIconHidden||o)c.style.display="none";else if(c.style.display=n?"none":"",c.innerHTML="",t.callToActionIconName){let n=Math.max((parseFloat(e)||24)-r,8),o=Ee(t.callToActionIconName,n,"currentColor",1.5);o?c.appendChild(o):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&fl[t.position]?fl[t.position]:fl["bottom-right"];r.className=n?"persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer":`persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer ${p}`,n||(r.style.zIndex=String(t.zIndex??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,n?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=t.collapsedMaxWidth??"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")};return e&&n(e),{element:r,update:n,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},xd=new Set,Cd=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},Sd=({config:e,showClose:t})=>{let{wrapper:r,panel:n,pillRoot:o}=(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 n=st("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");n.style.width="100%",r.appendChild(n);let o=st("div","persona-widget-pill-root");return o.setAttribute("data-persona-composer-bar",""),o.dataset.state="collapsed",o.dataset.expandedSize=t.expandedSize??"anchored",o.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:n,pillRoot:o}}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=md(e),r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let n=e?.launcher??{},o=n.position&&fl[n.position]?fl[n.position]:fl["bottom-right"],a=st("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=st("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=hd(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:n,wrapper:o}=Cl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:gd,iconSize:fd});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=Sl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:gd,iconSize:bd});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}=vd(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=yd("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=oe(ye,16,"currentColor",1.5);r&&t.appendChild(r);let n=st("span","persona-pill-peek__text"),o=st("span","persona-pill-peek__caret"),a=oe(ue,16,"currentColor",1.5);return a&&o.appendChild(a),e.append(t,n,o),{root:e,textNode:n}})();return r.append(i,o,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:n,closeButtonWrapper:o,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"}}),n=e?.layout?.header,o=ss(e),a=n?Pl(e,n,{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}=vd(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=yd("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;o||(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:n,pillRoot:o},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},l={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:l,composer:d,replaceHeader:e=>(l.element.replaceWith(e.header),l.element=e.header,l.iconHolder=e.iconHolder,l.headerTitle=e.headerTitle,l.headerSubtitle=e.headerSubtitle,l.closeButton=e.closeButton,l.closeButtonWrapper=e.closeButtonWrapper,l.clearChatButton=e.clearChatButton,l.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{d.footer.replaceWith(e),d.footer=e}}},kd=({config:e,plugins:t,onToggle:r})=>{let n=t.find(e=>e.renderLauncher);if(n?.renderLauncher){let t=n.renderLauncher({config:e,defaultRenderer:()=>wd(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let o=((e,t)=>{let r=st("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let n=e??{},o=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(o?.frequency??"once")&&!1!==n.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(xd.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(Cd(n),e&&h())},f=e=>{o&&!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=wd(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=n.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(n.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);o=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"),o&&a&&(p||c||u||((e,t)=>{if(xd.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(Cd(n),h())||(m(),l=setTimeout(b,Math.max(0,o.delayMs??0))))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:b,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{n=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}})(e,r);return{instance:o,element:o.element}},Ad=new WeakMap;async function Md(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let n=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(Ad.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"}Ad.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",n),e.title=n,Ad.delete(e)},1800))}let{setLoader:Id,load:Td,provide:Ed,getSync:Bd}=_({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),Ld=Id,Rd=Td,Pd=Bd,{setLoader:Nd,load:$d}=_({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),Wd=Nd,Hd=$d;function Dd(e,t,r){return t?.trim()||(q(e,`artifact.${r}`)?`var(--persona-components-artifact-${r.split(".").join("-")})`:void 0)}function Fd(e){return!0===e?.features?.artifacts?.enabled}function zd(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"),!Fd(t))return;let r=t.features?.artifacts?.layout,n=Dd(t,r?.paneBorder,"pane.border"),o=Dd(t,r?.paneBorderLeft,"pane.borderLeft");n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}let Od=["panel","seamless","detached"];function qd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Od.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function jd(e){return!(!e||!Fd(e))&&"detached"===qd(e)}function _d(e,t){if(!Fd(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 zd(e,t);let r=t.features?.artifacts?.layout,n="detached"===qd(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",r?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",r?.paneMaxWidth??"28rem"),r?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",r.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),r?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=Dd(t,r?.paneBackground,"pane.background");o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let a=Dd(t,r?.panePadding,"pane.padding");a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[Dd(t,r?.documentToolbarIconColor,"toolbar.iconColor"),"--persona-artifact-doc-toolbar-icon-color"],[Dd(t,r?.documentToolbarToggleActiveBackground,"toolbar.toggleActiveBackground"),"--persona-artifact-doc-toggle-active-bg"],[Dd(t,r?.documentToolbarToggleActiveBorderColor,"toolbar.toggleActiveBorderColor"),"--persona-artifact-doc-toggle-active-border"],[Dd(t,r?.documentToolbarToggleActiveColor,"toolbar.toggleActiveColor"),"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let n=t?.trim();n?e.style.setProperty(r,n):e.style.removeProperty(r)}zd(e,t)}function Ud(e,t){for(let t of Od)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"),!Fd(t))return;let r=t.features?.artifacts?.layout,n=qd(t);e.classList.add(`persona-artifact-appearance-${n}`);let o=Dd(t,r?.paneBorderRadius,"pane.borderRadius");o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=Dd(t,r?.paneShadow,"pane.shadow");a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=Dd(t,r?.chatShadow,"chat.shadow");s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}let Vd=["__proto__","prototype","constructor"],Kd=["collapsed","card","panel","inline"],Qd=["markdown","component"],Jd=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Gd=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Yd=e=>!Vd.includes(e),Xd=e=>Kd.includes(e),Zd=e=>Object.keys(e).length>0;function ec(e,t,r,n){e.push({path:t,code:r,message:n})}let tc="Ignored an unsupported value.",rc={kind:"mode"},nc={kind:"string",message:"Expected a CSS length string."},oc={kind:"boolean"},ac=(...e)=>({kind:"value",accepts:t=>e.includes(t)}),sc={paneWidth:nc,paneMaxWidth:nc,paneMinWidth:nc,expandedPanelWidth:nc,resizableMinWidth:nc,resizableMaxWidth:nc,expandLauncherPanelWhenOpen:oc,resizable:oc},ic={kind:"object",message:"Expected a preference object.",children:{showToolCalls:oc,showReasoning:oc,toolCallDisplay:{kind:"object",children:{layout:ac("row","card"),collapsedMode:ac("tool-call","tool-name","tool-preview"),groupedMode:ac("stack","summary","collapsible"),groupAppearance:ac("plain","inset"),groupSummary:ac("current-action","aggregate"),groupBoundary:ac("adjacent","iteration"),groupSummaryMaxItems:{kind:"value",accepts:e=>Number.isInteger(e)&&e>=0},loadingAnimation:ac("none","pulse","shimmer","shimmer-color","rainbow"),expandable:oc,grouped:oc}},reasoningDisplay:{kind:"object",children:{layout:ac("row","card"),appearance:ac("plain","inset","panel"),expandable:oc,activePreview:oc}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:rc,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:rc,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Qd,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Qd}}},filePreview:{kind:"object",children:{enabled:oc}},layout:{kind:"object",children:sc}}}}};function lc(e,t,r,n){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:ec(n,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:ec(n,r,"invalid_type",t.message);case"value":return t.accepts(e)?e:ec(n,r,"invalid_value",tc);case"mode":return Xd(e)?ko(e):ec(n,r,"invalid_value",tc);case"modeMap":{if(!Gd(e))return ec(n,r,"invalid_type","Expected an object.");let o="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=o?t:Ao(t);Yd(t)&&(o?o.includes(t):Jd.test(e))?Xd(s)?a[e]=ko(s):ec(n,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):ec(n,`${r}.${t}`,o?"unknown_key":"invalid_value",o?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return Zd(a)?a:void 0}case"object":{if(t.bareMode&&Xd(e))return ko(e);if(!Gd(e))return ec(n,r,"invalid_type",t.message??"Expected an object.");let o=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!Yd(t)||!o.includes(t))&&ec(n,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of o){let o=t.children[r],i=lc(e[r],o,a(r),n);if(o.deprecated&&void 0!==e[r]&&ec(n,a(r),"deprecated_key",o.deprecated),void 0===i)continue;let l=o.alias??r,d=s[l];s[l]=Gd(d)&&Gd(i)?{...d,...i}:i}return Zd(s)?s:void 0}}}function dc(e){let t=[];return{preferences:(null===e?void 0:lc(e,ic,"",t))??{},issues:t}}function cc(e){if(Array.isArray(e))return e.map(cc);if(!Gd(e))return e;let t={};for(let[r,n]of Object.entries(e))Yd(r)&&void 0!==n&&(t[r]=cc(n));return t}function pc(e,t){let r=cc(e);for(let[e,n]of Object.entries(t)){if(!Yd(e)||void 0===n)continue;let t=r[e];r[e]=Gd(t)&&Gd(n)?pc(t,n):cc(n)}return r}function uc(e,t){if(void 0===t)return cc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return cc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Zd(o)?{byMediaType:o}:{}};return Zd(a)?a:void 0}(r.files,t.files),s={...n?{default:n}:{},...Zd(o)?{byKind:o}:{},...void 0===a?{}:{files:a}};return Zd(s)?s:void 0}function hc(e={},t){let r=function(e){let t,r={};for(let n of e){let e=dc(n).preferences;t=uc(t,e.artifacts?.display),r=pc(r,e)}let n=r;return n.artifacts&&(void 0===t?delete n.artifacts.display:n.artifacts.display=t),n}(t),n={...e};for(let e of["showToolCalls","showReasoning"])void 0!==r[e]&&(n[e]=r[e]);for(let t of["toolCallDisplay","reasoningDisplay"])r[t]&&Object.assign(n,{[t]:{...e[t],...r[t]}});if(r.artifacts){let t=e.artifacts??{},o={...t};if(void 0!==r.artifacts.display){let e=uc(t.display,r.artifacts.display);void 0!==e&&(o.display=e)}for(let e of["filePreview","layout"])r.artifacts[e]&&(o[e]={...t[e],...r.artifacts[e]});n.artifacts=o}return n}function mc(e){let t=e.preferences;return t&&Zd(t)?{...e,features:hc(e.features??{},[t])}:e}let{setLoader:gc,load:fc,provide:bc,getSync:yc}=_({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),vc=gc,wc=fc,xc=yc,Cc=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()}},Sc=e=>"object"==typeof e&&!!e&&!Array.isArray(e),kc=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Ac=(e,t,r)=>{if(!Sc(e)||!Sc(t)||kc.has(r))return t;let n={...e};for(let o of Object.keys(t)){if(void 0===t[o]){delete n[o];continue}let a=r?`${r}.${o}`:o;n[o]=Ac(e[o],t[o],a)}return n};function Mc(e,t){let r=f(cs),n=x(e,t,r),o=v(C(Ac(e,t,""),r,n),n);return D(o,((e,t)=>{if(t[$])return H(t);let r=new Set(H(e));for(let e of N){let n=b(t,e);"clear"===n&&r.delete(e),"explicit"===n&&r.add(e)}return[...r]})(e,t)),ns(gs(o),((e,t)=>{let r=t[Za];if(r)return{...r};let n=rs(e);return es(t,"launcherWidth")&&(n.legacyLauncherWidth=void 0!==t.launcherWidth),es(t,"launcher")&&void 0===t.launcher?(n.launcherWidth=!1,n.sidebarWidth=!1,n.dockWidth=!1,n):(es(t.launcher,"width")&&(n.launcherWidth=void 0!==t.launcher?.width),es(t.launcher,"sidebarWidth")&&(n.sidebarWidth=void 0!==t.launcher?.sidebarWidth),es(t.launcher,"dock")&&void 0===t.launcher?.dock?n.dockWidth=!1:es(t.launcher?.dock,"width")&&(n.dockWidth=void 0!==t.launcher?.dock?.width),n)})(e,t))}let{setLoader:Ic,load:Tc,provide:Ec,getSync:Bc}=_({fallbackImport:()=>import("@runtypelabs/persona/config-diagnostics")}),Lc=Ic,Rc=Tc,Pc=Bc,Nc=[...R,"launcherWidth","suggestionChips","copy.welcomeTitle","copy.welcomeSubtitle","copy.showWelcomeCard","features.suggestReplies.enabled","features.suggestReplies.expose"],$c=e=>{if(!e.debug)return;let t=Pc();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 Rc().then(()=>$c(e),()=>{})},Wc=e=>{let t={warned:new Set,current:new Set(Nc.filter(t=>z(e,t))),debug:!0===e?.debug};return $c(t),t},Hc=(e,t)=>{if((e=>void 0!==e[$])(t))e.current=new Set(Nc.filter(e=>z(t,e)));else for(let r of Nc){let n=b(t,r);"clear"===n&&e.current.delete(r),"explicit"===n&&e.current.add(r)}Object.prototype.hasOwnProperty.call(t,"debug")&&(e.debug=!0===t.debug),$c(e)},Dc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=(e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e})(e),r=(e=>{let t=e.trim(),r=t.indexOf("{");if(-1===r)return null;let n=0;for(let e=r;e<t.length;e+=1){let o=t[e];if("{"===o&&(n+=1),"}"===o&&(--n,0===n))return t.slice(r,e+1)}return null})(t);if(!r)return null;let n=JSON.parse(r);if(!n||"object"!=typeof n||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},Fc=e=>"string"==typeof e?e:null==e?"":String(e),zc={message:e=>{if("message"===e.type)return{handled:!0,displayText:Fc(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,n=Fc(r.element);if(n&&t.document?.querySelector){let e=t.document.querySelector(n);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Fc(r.text)}}},Oc=e=>Array.isArray(e)?e.map(e=>String(e)):[],qc=e=>{let t=new Set(Oc(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let n="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!n&&"string"==typeof r.text&&r.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let o=n?e.parsers.reduce((e,t)=>e||t?.({text:n,message:r.message})||null,null):null;if(!o)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:o,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let n=e.captureResubmitGuard?.(),s=t(o,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{(!n||n())&&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(Oc(e.getSessionMetadata().processedActionMessageIds))}}},jc=e=>e.map(e=>({...e,streaming:!1})),_c=e=>e.map(e=>({...e,status:"complete"})),Uc=e=>`${e??"persona-"}state`,Vc=(e=Uc())=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?(e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}})(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let t={...r,messages:r.messages?jc(r.messages):void 0,artifacts:r.artifacts?_c(r.artifacts):void 0};n.setItem(e,JSON.stringify(t))}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",e)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}},Kc=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:Qc,load:Jc}=_({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),Gc=Qc,Yc=Jc,{setLoader:Xc,load:Zc,provide:ep,getSync:tp}=_({fallbackImport:()=>import("@runtypelabs/persona/history-shell")}),rp=Xc,np=Zc,op=tp;function ap(){return null}let sp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ip(e,t,r){let{onSubmit:n,onDismiss:o,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",()=>{o?.(),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 n(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 lp(e){return ip(e,"csat",t=>{let{ratingLabels:r=sp}=e,n=document.createElement("div");n.className="persona-feedback-rating persona-feedback-rating-csat",n.setAttribute("role","radiogroup"),n.setAttribute("aria-label","Satisfaction rating from 1 to 5");let o=[];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),o.forEach((t,r)=>{let n=r<e;t.classList.toggle("selected",n),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),o.push(a),n.appendChild(a)}return{element:n,attentionTarget:n}})}function dp(e){return ip(e,"nps",t=>{let{lowLabel:r="Not likely",highLabel:n="Very likely"}=e,o=document.createElement("div");o.className="persona-feedback-rating persona-feedback-rating-nps",o.setAttribute("role","radiogroup"),o.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=n,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 o.appendChild(a),o.appendChild(l),{element:o,attentionTarget:l}})}let cp="persona-chat-history",pp="data-persona-composer-reason",up="data-persona-composer-notice",hp={"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 mp(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let gp=e=>e&&"object"==typeof e?{...e}:{},fp=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})),bp=(e,t,r)=>{let n=e?.markdown?Sr(e.markdown):null,o=Pr(e?.sanitize);e?.postprocessMessage&&o&&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=o?o(t):t}else if(n){let e=xr(s,a.streaming),t=n(e);l=o&&d?o(t):t}else l=Mr(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)),Mr(e.text??"")}}};function yp(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 vp=(e,t)=>{let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...n}:n}return r},wp=(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 o=e.getAttribute("data-persona-instance")||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;e.setAttribute("data-persona-instance",o),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let s,i,l=gs(t),u=(e=>{let t,r=0,n=!1,o=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 o},prepare(s,l,d=!1){let c=++r;if(a(),!s.length){if(l(),c!==r)return;return i(),void(o=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"))});o=Promise.race([Promise.all(s),p]).then(()=>{if(n)throw Error("Widget destroyed before ready");if(c!==r||(l(),c!==r))return o;i()},e=>{if(!n&&c!==r)return o;throw e}),o.catch(()=>{})},destroy(){n=!0,++r,a(),i()}}})(e),h=r?.diagnostics??Wc(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,As,Vl),m=r):null},f=new Set,b=new Set,y=new Map,v=()=>{Oa({delayMs:l.tooltip?.delayMs??400,skipDelayMs:l.tooltip?.skipDelayMs??300})};v();let w=l.features;l=mc(l);let x,C,S=Cc.getForInstance(l.plugins),A=Mi(e),M=[],I=!1,T=(e=>{let t=new Map,r=!1,n=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return o=>{let a=t=>((e,t,r)=>`${(e=>{let t=e?.persistState;return("object"==typeof t?t?.keyPrefix:void 0)??"persona-"})(e)}plugin:${t}:${r}`)(e(),o,t);return{get:e=>{let o=a(e),s=n();if(s)try{return s.getItem(o)}catch{r=!0}return t.get(o)??null},set:(e,o)=>{let s=a(e),i=n();if(i)try{return void i.setItem(s,o)}catch{r=!0}t.set(s,o)},remove:e=>{let o=a(e);t.delete(o);let s=n();if(s)try{s.removeItem(o)}catch{r=!0}}}}})(()=>l),E=null,B=null,L=null,R=!1,P=null,N=(e,t)=>{E=e,e.initApprovalUi({webMcpToolTitle:nr,popover:t,icons:{render:Ee,node:oe}});let r=e.createBuiltInApprovalPlugin(y);B=r.plugin,L=r.teardown},$=()=>{if(E)return E;let e=Pd(),t=We();return e&&t?(N(e,t),e):(Promise.all([Rd(),$e()]).then(([e,t])=>{R||E||(N(e,t),P?.())}).catch(()=>{}),null)},W=!1,H=!1,D=null,F=(e,t,r,n)=>{if(!e.querySelector("[data-tv-form]"))return;let o=xc();o?o.enhanceWithForms(e,t,r,n):wc().then(()=>{W||H||!D||(H=!0,D())}).catch(()=>{})},z=((e={instanceId:""})=>{let t=!1,r=new Map,n=(e,t)=>{r.get(e)?.delete(t)};return{on:(e,o)=>t?()=>{}:(r.has(e)||r.set(e,new Set),r.get(e).add(o),()=>n(e,o)),off:n,emit:(t,n)=>{r.get(t)?.forEach(t=>{try{t(n,e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})},dispose:()=>{t=!0,r.clear()}}})(Object.freeze({instanceId:o})),O=!1===l.persistState?null:l.storageAdapter??Vc(Uc("object"==typeof l.persistState?l.persistState.keyPrefix:void 0)),q=!!l.clientToken&&"function"!=typeof l.reconnectStream,_={},U=null,V=new Promise(e=>{x=e}),K=()=>{},Q=new Promise(e=>{K=e}),J=!1,G=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&&(J=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(O?.load)try{let e=O.load();if(e&&"function"==typeof e.then)U=e.then(e=>G(e??{messages:[],metadata:{}}));else{let t=G(e??{messages:[],metadata:{}});t.metadata&&(_=gp(t.metadata)),t.messages?.length&&(l={...l,initialMessages:t.messages}),t.artifacts?.length&&(l={...l,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),C=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(l.onStateLoaded)try{let e=G({messages:[],metadata:{}});e.messages?.length&&(l={...l,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}U||x();let X=()=>_,Z=e=>{_=e({..._})??{},ji()},ee=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Dc],te=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[zc.message,zc.messageAndClick],re=qc({parsers:ee,handlers:te,getSessionMetadata:X,updateSessionMetadata:Z,emit:z.emit,captureResubmitGuard:()=>{let e=be;return()=>ve(e)},documentRef:typeof document<"u"?document:null});re.syncFromMetadata();let ne=l.launcher?.enabled??!0,ae=l.launcher?.autoExpand??!1,se=l.autoFocusInput??!1,ie=ae,le=ne,ce=l.layout?.header?.layout,ue=!1,me=()=>ll(l),ge=()=>ne||me(),fe=!me()&&(!ne||ae),be=0,ye=!1,ve=e=>!ye&&!Ei&&e===be,we=()=>{be++,Ce=!1,null!==Se&&clearTimeout(Se),Se=null},xe=()=>{let e=be;ve(e)&&setTimeout(()=>{ve(e)&&!ts.isStreaming()&&ts.continueConversation()},100)},Ce=!1,Se=null,ke=()=>{ve(be)&&(Ce=!0,Se&&clearTimeout(Se),Se=setTimeout(()=>{Ce&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4))},Ae=bp(l,re,ke),Me=l.features?.showReasoning??!0,Ie=l.features?.showToolCalls??!0,Te=l.features?.showEventStreamToggle??!1,Be=l.features?.scrollBehavior??{},Le=()=>("object"==typeof l.persistState?l.persistState?.keyPrefix:void 0)??"persona-",Re=`${Le()}event-stream`,Pe=null,Ne=l.features?.eventStream?.maxEvents??2e3,He=null,De=null,Fe=null,ze=!1,Oe=null,qe=!1,_e=null,Ue=0,Ve=(e,t)=>{He?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Ke=(e,t)=>{De?.processEvent(e,t),He?Ve(e,t):Fe&&(Fe.length>=Ne&&Fe.shift(),Fe.push({type:e,payload:t}))},Qe=()=>{!He&&Te&&(Fe??=[],Hd().then(e=>{if(ze||He||!Te)return;Pe=new e.EventStreamStore(Re),He=new e.EventStreamBuffer(Ne,Pe),De??=new e.ThroughputTracker,Pe.open().then(()=>He?.restore()).catch(e=>{l.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Fe??[];Fe=null;for(let e of t)De?.processEvent(e.type,e.payload),Ve(e.type,e.payload)}).catch(()=>{}))};Te&&Qe();let Ye=!1,Xe=null,Ze=()=>{},et=()=>{},tt=()=>{},rt=()=>{},nt=()=>{},ot=e=>{z.emit("message:copy",e),ts?.isClientTokenMode()&&ts.submitMessageFeedback(e.id,"copy").catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),l.messageActions?.onCopy?.(e)},at=e=>{z.emit("message:feedback",e),ts?.isClientTokenMode()&&ts.submitMessageFeedback(e.messageId,e.type).catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),l.messageActions?.onFeedback?.(e)};l.statusIndicator;let it=(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 lt(e,t,r,n){if(!me()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(hr(e,At,r),ur(e,r,n)),!e.hasAttribute(pp)&&!e.hasAttribute(up))if("idle"===n&&r.idleLink){e.textContent="";let n=document.createElement("a");n.href=r.idleLink,n.target="_blank",n.rel="noopener noreferrer",n.textContent=t,n.style.color="inherit",n.style.textDecoration="none",e.appendChild(n)}else e.textContent=t}let ct=Sd({config:l,showClose:ge()}),{wrapper:pt,panel:ut,pillRoot:ht}=ct.shell,mt=ct.panelElements,{container:gt,body:ft,messagesWrapper:vt,starterSuggestions:wt,transcriptSuggestions:xt,suggestions:Ct,textarea:St,sendButton:kt,composerForm:At,statusText:Mt,welcomeHost:It,welcomeIconHolder:Lt,greetingHost:Rt,introKicker:Pt,introTitle:Nt,introSubtitle:$t,closeButton:Dt,iconHolder:Ft,headerTitle:zt,headerSubtitle:Ot,header:er,footer:tr,actionsRow:rr}=mt,or=mt.leftActions,ar=mt.rightActions,sr=mt.sendButtonWrapper,ir=mt.setSendButtonMode,lr=mt.micButton,dr=mt.micButtonWrapper,pr=mt.attachmentButton,mr=mt.attachmentButtonWrapper,gr=mt.attachmentInput,fr=mt.attachmentPreviewsContainer;gt.classList.add("persona-relative"),ft.classList.add("persona-relative");let br=()=>Be.mode??"anchor-top",yr=()=>"follow"===br()||"anchor-top"===br()&&ei,vr=()=>Be.anchorTopOffset??16,wr=()=>!0===Be.pauseOnInteraction,xr=()=>!1!==Be.showActivityWhilePinned,Cr=()=>!0===Be.announce,Sr=()=>Be.scrollbar??"on-scroll",kr=Zt(Ee,"transcript",ft),Ar=kr.element;gt.appendChild(Ar);let Ir=()=>ft.parentElement??gt,Tr=st("div","persona-panel-suggestions");Tr.setAttribute("data-persona-panel-suggestions",""),Tr.hidden=!0,gt.appendChild(Tr);let Er=st("div","persona-panel-suggestions-fade");Er.setAttribute("aria-hidden","true"),Er.hidden=!0,gt.appendChild(Er);let Br=st("div","persona-stream-anchor-spacer");Br.setAttribute("aria-hidden","true"),Br.setAttribute("data-persona-anchor-spacer",""),Br.style.flexShrink="0",Br.style.pointerEvents="none",Br.style.height="0px",Br.style.display="none",ft.appendChild(Br);let Lr=st("div","persona-sr-only");Lr.setAttribute("aria-live","polite"),Lr.setAttribute("aria-atomic","true"),Lr.setAttribute("role","status"),Lr.setAttribute("data-persona-live-region",""),Object.assign(Lr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),gt.appendChild(Lr);let Rr=null,Pr=null,Nr=e=>{Cr()&&e&&(Pr=e,null===Rr&&(Rr=setTimeout(()=>{Rr=null,Pr&&Cr()&&(Lr.textContent=Pr),Pr=null},400)))},$r=()=>{let t=e.ownerDocument.defaultView??window;return(l.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(l.launcher?.mobileBreakpoint??640)&&(ne||il(l))||!0===l.launcher?.fullHeight&&!l.launcher.sidebarMode&&!il(l)},Wr=()=>ld(l,$r()),Dr="empty",Fr=0,zr=()=>Fr||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Or=(e,t=ft)=>{let r=0,n=e;for(;n&&n!==t;)r+=n.offsetTop,n=n.offsetParent;return r},qr=()=>{let e="none"===tr.style.display,t=Ir();if(me()){let r=e||!tr.offsetHeight?0:Math.max(0,t.getBoundingClientRect().bottom-tr.getBoundingClientRect().top),n=Tr.hidden?0:Math.max(0,t.getBoundingClientRect().bottom-Tr.getBoundingClientRect().top);return void(Ar.style.bottom=`${Math.max(r,n)+16}px`)}let r=e?0:tr.offsetHeight;if(r>0&&"overlay"===fi(l,me())){let e=1/0;for(let r of tr.querySelectorAll(":scope > *, [data-persona-composer-header] > *"))!r.hidden&&r.offsetHeight&&"hidden"!==getComputedStyle(r).visibility&&(e=Math.min(e,Or(r,t)));e<1/0&&(r-=e-Or(tr,t))}Ar.style.bottom=`${r+(e?0:zr())+16}px`};qr();let _r=()=>{if(!me())return;let e="none"===tr.style.display?0:tr.offsetHeight;e>0?pt.style.setProperty("--persona-measured-pill-area-height",`${e+8}px`):pt.style.removeProperty("--persona-measured-pill-area-height"),pt.style.setProperty("--persona-pill-bottom",l.launcher?.composerBar?.bottomOffset??"16px")},Ur=()=>{Mn||(tr.style.marginBottom=Fr>0?`${Fr}px`:"")},Vr=()=>{let t=fi(l,me()),r=Wr();e.setAttribute("data-persona-welcome-fullscreen",String($r())),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 n="none"===tr.style.display?0:tr.offsetHeight,o="center"===r.anchor&&"empty"===Dr?bi(r.anchorComposerTop)??bi("44%"):null,a=null!==o&&"centered"===r.layout&&void 0===l.welcome?.anchor&&void 0===l.welcome?.anchorComposerTop,s=a?getComputedStyle(ft):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?ft.getBoundingClientRect().top-gt.getBoundingClientRect().top:0,u=!a||It.hidden?0:(It.querySelector("[data-persona-welcome-plugin]")??It).offsetHeight,h=null===o||me()?0:a?Math.max(0,Math.round((gt.clientHeight-p-u-c-n)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:gt.clientHeight,footerHeight:n,fraction:o});e.style.setProperty("--persona-composer-overlay-height",`${n}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),Fr="block"===t?h:0,Ur(),_r(),qr(),$a()};kr.update(l,!1);let Kr=null,Qr=null,Jr=ea();Jr.subscribe(e=>{try{gt.dispatchEvent(new CustomEvent("persona:composer:state",{detail:{...e,instanceId:o},bubbles:!0,composed:!0}))}catch{}});let Gr=()=>{Jr.setText(St?.value??"")},Yr=()=>{Jr.setMentionRefs(Qr?.getMentionRefs()??[])},Xr=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}),Zr=()=>({allowedTypes:l.attachments?.allowedTypes,maxFileSize:l.attachments?.maxFileSize,maxFiles:l.attachments?.maxFiles,adapter:l.attachments?.adapter,onFileRejected:l.attachments?.onFileRejected,instanceId:o,widgetConfig:l,preview:l.attachments?.preview,renderAttachmentPreview:en}),en=e=>{for(let t of Cc.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},tn=()=>{let e=p.fromConfig(l.attachments,t=>{Kr===e&&rn(t)});return e.updateConfig(Zr()),e},rn=e=>{let t=Object.freeze(e.map(Xr));Jr.setAttachments(t);try{l.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}qd()};Jr.setSelectedModelId(l.composer?.selectedModelId);let nn=()=>l.composer?.modes??[],on=()=>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)):[]}(nn(),l.composer?.modeGroups,!!l.future?.v5Defaults);{let e=ga(l.composer?.defaultActiveModeIds??[],nn());e.length&&Jr.setActiveModeIds(e)}function an(e){if(Jr.getState().selectedModelId!==e){Jr.setSelectedModelId(e),dn?.repaint();try{l.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function sn(e){Jr.setActiveModeIds(e),cn?.render(e,on()),dn?.repaint(),Fn?.resolve(),yc(),Yn()}function ln(t){let r=e.getRootNode(),n=r instanceof ShadowRoot?r.activeElement:e.ownerDocument.activeElement,o=(e=>`core:mode:${e}`)(t),a=Fn?.getOverflowMenu(),s=n&&(n.closest("[data-persona-composer-action]")?.getAttribute("data-persona-composer-action")===o||a?.trigger.contains(n));if(sn(ma(Jr.getState().activeModeIds,t,nn(),l.composer?.modeGroups)),s&&!n.isConnected){let t=Array.from(e.querySelectorAll("[data-persona-composer-action]")).find(e=>e.getAttribute("data-persona-composer-action")===o)?.querySelector("button")??Fn?.getOverflowMenu()?.triggerButton;t?.isConnected&&t.focus()}}let dn=null,cn=null,pn=null;function un(e){Jr.setQuote(e),pn?.render(Jr.getState().quote),Yn(),Zi()}let hn=!1;function mn(){let e=l.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?l.clientToken?"interrupt":(!hn&&!0===l.debug&&(hn=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let gn=null;function fn(e){Jr.setPendingSubmission(e),gn?.render(Jr.getState().pendingSubmission),Yn()}let bn=null,yn=S.find(e=>e.renderHeader);if(yn?.renderHeader){let e=yn.renderHeader({config:l,defaultRenderer:()=>{let e=Il({config:l,showClose:ge()});return Tl(gt,e,l),e.header},onClose:()=>Nd(!1,"user")});e&&er&&(er.replaceWith(e),er=e,ct.header.element=e)}let wn=()=>{Oe&&(ft.style.display="none",tr.parentNode?.insertBefore(Oe.element,tr),Oe.update())},Cn=()=>{if(!He)return void Qe();if(Rl.cancel(),qe=!0,Oe?wn():Hd().then(e=>{!Oe&&qe&&He&&(Oe=e.createEventStreamView({scroll:{createScrollToLatest:Xt,createScrollToBottomControl:Zt},buffer:He,getFullHistory:()=>He.getAllFromStore(),onClose:()=>Sn(),config:l,plugins:S,getThroughput:()=>De?.getMetric()??{status:"idle"},renderIconByName:Ee,getResponseActive:bl,getConfig:()=>l,getViewVisible:()=>qe}),wn())}).catch(()=>{Sn()}),kn){kn.style.boxShadow=`inset 0 0 0 1.5px ${kl.actionIconColor}`;let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&kn.classList.add(e))}let e=()=>{if(!qe)return;let t=Date.now();t-Ue>=200&&(Oe?.update(),Ue=t),_e=requestAnimationFrame(e)};Ue=0,_e=requestAnimationFrame(e),Al(),z.emit("eventStream:opened",{timestamp:Date.now()})},Sn=()=>{if(qe){if(qe=!1,Oe&&(Oe.update(),Oe.element.remove()),ft.style.display="",kn){kn.style.boxShadow="";let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&kn.classList.remove(e))}null!==_e&&(cancelAnimationFrame(_e),_e=null),Al(),z.emit("eventStream:closed",{timestamp:Date.now()})}},kn=null;if(Te){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:"");kn=st("button",t),kn.style.width="28px",kn.style.height="28px",kn.style.color=kl.actionIconColor,kn.type="button",kn.setAttribute("aria-label","Event Stream"),kn.title="Event Stream";let r=oe(de,"18px","currentColor",1.5);r&&kn.appendChild(r);let n=mt.clearChatButtonWrapper,o=mt.closeButtonWrapper,a=n||o;a&&a.parentNode===er?er.insertBefore(kn,a):er.appendChild(kn),kn.addEventListener("click",()=>{qe?Sn():Cn()})}let An=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??vo).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},Mn=!1,In=e=>{let t=S.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=l.composer,n=!!I&&ts.isStreaming();return t.renderComposer({config:l,defaultRenderer:e,requestRender:()=>vh(),storage:T(t.id),onSubmit:e=>{ts&&!ts.isStreaming()&&eu(e.trim(),{consumeDraft:!1})},streaming:n,disabled:n,openAttachmentPicker:()=>{Wd()||gr?.click()},models:r?.models,selectedModelId:Jr.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>an(e),onVoiceToggle:!0===l.voiceRecognition?.enabled?()=>{bn?.()}:void 0})},Tn=In(()=>$l({config:l}).footer);Tn&&(ct.replaceComposer(Tn),tr=ct.composer.footer,Mn=!0);let En=null;function Bn(){let e=St;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:wa(e)}),va(e,ya(l.composer?.maxLines,me()?5:3))}let Ln=e=>{En=na(e,{debug:!0===l.debug}),En&&(e=>{At=e.form,St=e.input,sr=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(kt=e.sendButton),e.micButton&&(lr=e.micButton,dr=e.micButton.parentElement),e.found.status&&(Mt=e.found.status),e.found.suggestions&&(Ct=e.found.suggestions),e.attachmentButton&&(pr=e.attachmentButton,mr=e.attachmentButton.parentElement),gr=e.attachmentInput??null,fr=e.attachmentPreviews??null,e.found.actionsRow&&(rr=e.found.actionsRow),or=e.found.actionsStart,ar=e.found.actionsEnd})(En),Bn()};An(tr),Ln(tr),Gr();let Rn=gi(l,me());Rn&&(vt.style.maxWidth=Rn,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%",Rt.style.maxWidth=Rn,Rt.style.marginLeft="auto",Rt.style.marginRight="auto",Rt.style.width="100%",wt.style.maxWidth=Rn,xt.style.maxWidth=Rn,xt.style.marginLeft="auto",xt.style.marginRight="auto",xt.style.width="100%");let $n=()=>{let e=gi(l,me());if(e&&!me())for(let t of[At,Ct,fr,Mt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};$n();let Wn=()=>{l.attachments?.enabled&&gr&&fr&&(Kr?Kr.remountPreviews(fr):(Kr=tn(),Kr.setPreviewsContainer(fr)),En?.addListener(gr,"change",e=>{let t=e.target;Kr?.handleFileSelect(t.files),t.value=""}),gt.querySelector(".persona-attachment-drop-overlay")||gt.appendChild(yp(l.attachments.dropOverlay)))};Wn();let Hn=()=>{if(!l.contextMentions?.enabled||!St)return;let e=Ht();if(!e){let e=St;return void Wt().then(()=>{!Qr&&St===e&&e.isConnected&&(Hn(),Fn?.resolve())},()=>{})}let t=En?.header??null,r=t?da(t):void 0;if(Qr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Ra,loadContextMentionsInline:Wa,renderLucideIcon:Ee,createMentionButton:Ms},config:l,textarea:St,anchor:At??St,getMessages:()=>ts.getMessages(),liveRegionHost:gt,chipRow:r}),Qr&&!r){let e=St;e.parentElement?.insertBefore(Qr.contextRow,e)}};Hn();let Fn=null,On={getState:()=>Jr.getState(),getValue:()=>St?.value??"",setValue:e=>{St&&(St.value=e,St.dispatchEvent(new Event("input",{bubbles:!0})),Gr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(En?.form??null)},openAttachmentPicker:()=>{Wd()||gr?.click()},toggleVoice:()=>{bn?.()},requestRender:()=>Fn?.resolve()},jn=()=>{let e=[];return(Qr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),mr&&e.push({id:"core:attachment",placement:"start",order:200,element:mr}),dr&&e.push({id:"core:mic",placement:"end",order:800,element:dr}),sr&&e.push({id:"core:send",placement:"end",order:1e3,element:sr}),e},_n=!1,Un=()=>{if(_n)return;let e=We();e&&(Fn?.destroy(),Fn=e.createComposerActionRenderer({deps:{renderLucideIcon:Ee,attachTooltip:Qa,hideTooltipFor:ja},getBindings:()=>En,collect:()=>({builtIns:jn(),configActions:[...(dn??=We().createComposerCoreControls({getConfig:()=>l,getState:()=>Jr.getState(),getModes:nn,getChipModes:on,hasComposerPlugin:()=>S.some(e=>e.renderComposer),renderIcon:Ee,onModelChange:an,onModeChange:ln}),dn.collect()),...l.composer?.actions??[]],plugins:S,contributionContext:{config:l,getState:()=>Jr.getState(),requestRender:()=>Fn?.resolve()},debug:!0===l.debug}),actionContext:On,getState:()=>Jr.getState(),getOverflow:()=>l.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),Fn.resolve())};Un();let Vn=()=>{if(cn?.destroy(),cn=null,!on().length)return;let e=En?.header;if(!e)return;let t=We();t&&(cn=t.createComposerModeChipRow({renderIcon:Ee,row:da(e),onRemove:e=>ln(e),initialIds:Jr.getState().activeModeIds}),cn.render(Jr.getState().activeModeIds,on()))};Vn();let Kn=()=>{pn?.destroy(),pn=null,gn?.destroy(),gn=null;let e=En?.header;e&&(pn=ca({onDismiss:()=>un(void 0)}),e.appendChild(pn.element),pn.render(Jr.getState().quote),"defer-one"===mn()&&(gn=pa({onEdit:()=>function(){let e=Jr.getState().pendingSubmission;e&&(fn(void 0),St&&(St.value=e.text,St.dispatchEvent(new Event("input",{bubbles:!0})),Gr()),e.options.selectedModelId&&(Jr.setSelectedModelId(e.options.selectedModelId),dn?.repaint()),e.options.activeModeIds?.length&&sn(e.options.activeModeIds),e.options.quote&&un(e.options.quote),St?.focus())}(),onRemove:()=>fn(void 0)}),e.appendChild(gn.element),gn.render(Jr.getState().pendingSubmission)))};Kn();let Qn=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),Jn=function(e){let t=null,r=null,n=null,o=null,a=0,s=!0,i=!1,l=!1,d=()=>{null!==o&&t?.form.ownerDocument.defaultView?.cancelAnimationFrame(o),o=null,r?.disconnect(),n?.disconnect(),r=null,n=null,t?.form.ownerDocument.defaultView?.removeEventListener("resize",c)},c=()=>{if(l||null!==o)return;let r=t?.form.ownerDocument.defaultView;r&&(o=r.requestAnimationFrame(()=>{o=null,l||e.onMeasure()}))};return{measure:()=>{if(l)return s;let o=e.getSurface();if(o?.form!==t?.form||o?.input!==t?.input||o?.start!==t?.start||o?.end!==t?.end){d(),t=o,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 n=[t.form,t.start,t.end,t.input];for(let e of n)r.observe(e)}void 0!==e.MutationObserver&&(n=new e.MutationObserver(e=>{e.some(e=>e.target!==t?.input||"attributes"!==e.type)&&c()}),n.observe(t.form,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["class","style","hidden"]}))}}t&&o&&(t.resizeInput=o.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,n){return e<=0?n:e>=t+2*r+120+(n?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}}}({getSurface:()=>me()||!En?null:{form:En.form,input:En.input,start:En.actionsStart,end:En.actionsEnd,resizeInput:"single-row"===l.composer?.layout},onMeasure:()=>Yn()}),Gn=()=>{let e=En?.header?.querySelector(la);if(e)return e.childElementCount>0;let t=Jr.getState();return t.mentionRefs.length>0||ga(t.activeModeIds,on()).length>0};function Yn(){let e=Jr.getState(),t=Jn.measure(),r="single-row"!==l.composer?.layout&&"single-row"!==l.composer?.attachmentLayout||t,n=Jn.toolbarCrowded();tr.hasAttribute("data-persona-composer-crowded")!==n&&tr.toggleAttribute("data-persona-composer-crowded",n),tr.hasAttribute("data-persona-composer-fit")!==r&&tr.toggleAttribute("data-persona-composer-fit",r);let o=Qn.observe(r&&function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),n=Number.parseFloat(r.lineHeight),o=Number.parseFloat(r.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(o)&&o>0?1.4*o:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0),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}(St),e.text);tr.toggleAttribute("data-persona-has-attachments",e.attachments.length>0),tr.toggleAttribute("data-persona-attachment-row-compact",fa({text:e.text,wrapped:o,hasAttachments:!1,hasChips:Gn(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}));let a=fa({text:e.text,wrapped:o,hasAttachments:e.attachments.length>0,hasChips:Gn(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission});tr.hasAttribute("data-persona-composer-compact")!==a&&tr.toggleAttribute("data-persona-composer-compact",a);let s=!a||!r||"single-row"!==l.composer?.layout;tr.hasAttribute("data-persona-composer-expanded")!==s&&tr.toggleAttribute("data-persona-composer-expanded",s)}function Xn(){"single-row"!==l.composer?.layout||me()?tr.removeAttribute("data-persona-composer-layout"):tr.setAttribute("data-persona-composer-layout","single-row"),l.composer?.attachmentLayout?tr.setAttribute("data-persona-attachment-layout",l.composer.attachmentLayout):tr.removeAttribute("data-persona-attachment-layout"),Yn()}Xn(),Jr.subscribe(()=>{Fn?.sync(),qd(),Vd(),Yn(),Zi()}),Vd();let Zn=!1,eo=e=>{if(Zn||!0!==l.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(Zn=!0,console.warn(`[persona] Ignoring deprecated layout.slots.${t.join(" / layout.slots.")}. Use message render hooks or the renderComposer plugin hook.`))},to=new Map,ro=new Map,no=e=>{let t=to.get(e);if(t)return t.element;let r=null;if("body-top"===e&&(r=ft.querySelector("[data-persona-intro-card]")),"messages"===e)return vt;if("composer"===e)return At;if("footer-top"===e&&(r=Ct),"footer-bottom"===e&&(r=Mt),r?.parentNode){let t=document.createComment(`persona:${e}`);r.before(t),to.set(e,{anchor:t,element:r})}return r},oo=function(e){let t=new Map,r=(t,r)=>({slot:t,signal:r.abort.signal,config:e.config(),defaultContent:()=>e.defaultContent(t)}),n=(r,n)=>{t.delete(r),n.abort.abort();try{n.result.destroy?.()}catch(e){console.error(`[AgentWidget] Error destroying slot "${r}":`,e)}e.remove(r,n.result.element)};return{update(){let o=e.config().layout?.slots??{};for(let[e,r]of t)o[e]!==r.renderer&&n(e,r);for(let[a,s]of Object.entries(o)){if(!s)continue;let o=t.get(a);try{if(o){if(o.result.update){let t=o.result.update(r(a,o));void 0!==t&&t!==o.result.element&&(e.remove(a,o.result.element),o.result.element=t)}}else{o={renderer:s,abort:new AbortController,result:{element:null}},t.set(a,o);let e=s(r(a,o));o.result=null===e||"nodeType"in e?{element:e}:e}o.result.element&&e.mount(a,o.result.element)}catch(e){o&&n(a,o),console.error(`[AgentWidget] Error rendering slot "${a}":`,e)}}},remount(){for(let[r,n]of t)n.result.element&&e.mount(r,n.result.element)},detach(r){for(let n of r){let r=t.get(n);r&&e.remove(n,r.result.element)}},destroy(){for(let[e,r]of t)n(e,r)}}}({config:()=>l,defaultContent:no,remove(e,t){if("messages"===e||"composer"===e)return;t?.remove(),ro.get(e)?.remove(),ro.delete(e);let r=to.get(e);r&&(r.anchor.replaceWith(r.element),to.delete(e))},mount(e,t){if(!("messages"===e||"composer"===e||t.parentNode&&pt.contains(t))){if("body-top"===e||"footer-top"===e||"footer-bottom"===e){let r=no(e),n=to.get(e);if(r&&n?.anchor.parentNode)return n.anchor.after(t),void(r!==t&&!t.contains(r)&&r.remove())}switch(e){case"header-left":er.prepend(t);break;case"header-right":er.append(t);break;case"header-center":{let e=er.querySelector(".persona-flex-col");e?e.after(t):er.append(t);break}case"body-top":ft.prepend(t);break;case"body-bottom":ft.append(t);break;case"footer-top":tr.prepend(t);break;case"footer-bottom":tr.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),vt.before(r),ro.set(e,r);break}case"composer-start":case"composer-end":case"composer-before-send":{let r="composer-start"===e?or:"composer-end"===e?ar:sr?.parentElement;if(!r)break;let n=document.createElement("div");n.setAttribute("data-persona-layout-slot",e),n.style.cssText="display:flex;align-items:center;min-width:0;max-width:100%",n.append(t),"composer-start"===e?r.prepend(n):"composer-before-send"===e?sr?.before(n):r.append(n),ro.set(e,n);break}}}}});eo(l.layout?.slots??{}),oo.update();let ao=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 n=r.closest("a[href]");if(!n||!e.contains(n)||n.hasAttribute("download")||n.closest("[data-persona-root]")!==e)return;let o=n.getAttribute("target")??n.ownerDocument.querySelector("base[target]")?.getAttribute("target");if((!o||"_self"===o.toLowerCase())&&/^(https?:|mailto:|tel:)/i.test(n.href))try{l.onLinkClick({url:n.href,anchor:n,originalEvent:t,preventDefault:()=>t.preventDefault()})}catch(e){console.error("[AgentWidget] onLinkClick failed:",e)}};e.addEventListener("click",ao),vt.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(),Md(r))}),vt.addEventListener("click",e=>{let t=e.target;t instanceof Element&&t.closest('.persona-approval-head[data-action="toggle-params"]')&&(oi(),Ml())},{capture:!0});let so=e=>{let t=e.target.closest('button[data-expand-header="true"]');t&&io(t)},io=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;oi(),Ml();let n=Js;n&&pl();let o=n&&m?.holdScroll(t,ft,n,jl,Ol,si,()=>Js===n),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,n=e?b:f;n.has(r)?n.delete(r):n.add(r),m&&(e?m.updateReasoningBubbleUI:m.updateToolBubbleUI)(r,t,n,l)}else if("approval"===a&&E){let e="expanded"===((!1===l.approval?void 0:l.approval)?.detailsDisplay??"collapsed"),n=y.get(r)??e;y.set(r,!n),E.updateApprovalDetailsUI(r,t,l,y)}o?.(),As.delete(r)};vt.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),so(e))}),vt.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&so(e)}),vt.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),so(e))}),vt.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=vt.getRootNode(),n="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!n||n.isCollapsed)return;let o=n.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(o);a&&a!==o&&(t.setData("text/plain",a),e.preventDefault())});let lo,co=new Map,po=new Map,uo=0,ho=()=>{vt.querySelectorAll(".persona-tool-bubble[data-tool-call-id]").forEach(e=>{e.toggleAttribute("data-persona-revealed",po.has(e.dataset.messageId))})},mo=()=>{window.clearTimeout(lo),lo=void 0,po.forEach(e=>window.clearTimeout(e)),po.clear(),ho()},go=null,fo="idle",yo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},wo=()=>{vt.querySelectorAll('[data-action="read-aloud"]').forEach(e=>{let t=e.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;((e,t)=>{let{icon:r,label:n}=yo[t];e.setAttribute("aria-label",n),e.title=n,e.setAttribute("aria-pressed","idle"===t?"false":"true"),e.classList.toggle("persona-message-action-active","idle"!==t),e.classList.toggle("persona-message-action-loading","loading"===t);let o=Ee(r,14,"currentColor",2);o&&(e.innerHTML="",e.appendChild(o))})(e,t&&t===go?fo:"idle")})};vt.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 n=r.getAttribute("data-actions-for");if(!n)return;let o=t.getAttribute("data-action");if("copy"===o){let e=ts.getMessages().find(e=>e.id===n);if(e&&ot){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=oe(pe,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=oe(he,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),ot(e)}}else if("read-aloud"===o)ts.toggleReadAloud(n);else if("upvote"===o||"downvote"===o){let e="upvote"===o?"thumbs-up":"thumbs-down";if((co.get(n)??null)===o){co.delete(n),t.classList.remove("persona-message-action-active");let r=Ee(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let a="upvote"===o?"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))}co.set(n,o),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=ts.getMessages().find(e=>e.id===n);l&&at&&at({type:o,messageId:l.id,message:l})}}else if("regenerate"===o)xo?.regenerate(n);else if("edit"===o)xo?.edit(n);else if("quote"===o)xo?.quote(n);else if(o?.startsWith("custom:")){let e=o.slice(7),r=l.messageActions?.custom?.find(t=>t.id===e),a=ts.getMessages().find(e=>e.id===n);if(!r||!a)return;try{r.onSelect(a)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let xo=null;vt.addEventListener("click",e=>{let t=e.target.closest("button[data-approval-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest(".persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;let o=t.getAttribute("data-approval-action");if(!o)return;let a="approve"===o?"approved":"denied",s=ts.getMessages().find(e=>e.id===n);if(!s?.approval)return;let i=r.querySelector("[data-approval-buttons]");i&&i.querySelectorAll("button").forEach(e=>{e.disabled=!0,e.style.opacity="0.5",e.style.cursor="not-allowed"}),cr(s.approval)?ts.resolveWebMcpApproval(n,a):ts.resolveApproval(s.approval,a)});let Co=null,So=!1,ko=null,Ao=()=>{},Mo="none",To=null,Eo={artifacts:[],selectedId:null},Ro=!1,No=!1,Ho=!1,Do=!1,Fo=()=>Do||Eo.artifacts.some(e=>"panel"===Io(l.features?.artifacts,e)),zo=()=>Eo.artifacts.length>0&&!Ro&&Fo(),Oo={current:null},qo=(e,t)=>{let r=ts.getArtifactById(t),n=r?.markdown,o=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!n){let t=(e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]"))?.getAttribute("data-message-id");if(t){let e=ts.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);n=t?.props?.markdown,o=t?.props?.title||o,t?.props?.file&&"object"==typeof t.props.file&&(a=t.props.file),!r&&"string"==typeof t?.props?.artifactType&&(s=t.props.artifactType)}catch{}}}return{markdown:n,title:o,file:a,artifactType:s}};vt.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:n,title:o,file:a}=qo(t,r);if(!n)return;let s=Et();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:o,markdown:n,file:a}))}),vt.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 n=t.closest("[data-artifact-inline]"),o=n?null:t.closest("[data-open-artifact]"),a=n?n.getAttribute("data-artifact-inline"):o?.getAttribute("data-open-artifact")??null,s=(n?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}=qo(t,a??""),u={artifactId:a,title:d,artifactType:p,markdown:i,file:c};try{Promise.resolve(s.onClick(u)).catch(()=>{})}catch{}}),vt.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-copy-artifact");if(!r)return;let n=ts.getArtifactById(r),o=Et();if(!o)return;let a="";if(n)a=o.artifactCopyText(n);else{let{markdown:e,file:n,artifactType:s}=qo(t,r);"markdown"===s&&(a=o.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...n?{file:n}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=oe(pe,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=oe(he,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),vt.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})&&(Ro=!1,Do=!0,No=!0,Ho=!0,ts.selectArtifact(r),Ba())}),vt.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 n=r.getAttribute("data-open-artifact");n&&!0!==l.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:n})&&(e.preventDefault(),e.stopPropagation(),Ro=!1,Do=!0,ts.selectArtifact(n),Ba())}),vt.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 jo=mt.composerOverlay,_o=e=>{Wt().catch(()=>{}),Pn(e,l,jo)},Uo=null,Vo={instanceId:o,mount:e,overlay:jo,sessionRef:Oo,config:()=>l},Ko=!1,Qo=e=>t=>{let r=t.target,n=r?.closest?.("[data-persona-ask-sheet-for]");if(!n||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let o=r=>{Uo??=r.createAskUserSheetHandlers(Vo),Uo[e](t)},a=Ht();a?o(a):Ko||(Ko=!0,Wt().then(e=>{Ko=!1,n.isConnected&&o(e)},()=>{Ko=!1}))};jo.addEventListener("click",Qo("click")),jo.addEventListener("keydown",Qo("keydown"));let Jo=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=jo.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let n=Number(e.key),o=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[n-1];o&&(e.preventDefault(),o.click())};document.addEventListener("keydown",Jo);let Go=null,Yo=null,Xo=()=>{},Zo=!1,ta="",ra="",ba=()=>{let e=Gc?.railShell?Gc.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360},xa=()=>{},Ia=()=>{let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,n=l.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>n)&&(ne||il(l))},Ea=()=>!Fd(l)||!zo()||e.classList.contains("persona-artifact-narrow-host")||Ia()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":jd(l)?"detached":"welded",Ba=()=>{if(!Co||!Fd(l))return;_d(e,l),Ud(e,l),xa();let t=l.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=ut.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let n=zo();Co.setVisible(n),Co.update(Eo),Ro?(Co.setMobileOpen(!1),Co.element.classList.add("persona-hidden"),Co.backdrop?.classList.add("persona-hidden"),No=!1,Ho=!1):Eo.artifacts.length>0&&Fo()?(Co.element.classList.remove("persona-hidden"),Co.setMobileOpen(!0)):(Co.setMobileOpen(!1),Co.element.classList.add("persona-hidden"),Co.backdrop?.classList.add("persona-hidden"),No=!1,Ho=!1);let o=!0===l.features?.artifacts?.layout?.showExpandToggle;if(Co.setExpandToggleVisible(o),Co.setCopyButtonVisible(!0===l.features?.artifacts?.layout?.showCopyButton),Co.setRefreshButtonVisible("function"==typeof l.features?.artifacts?.layout?.onDocumentToolbarRefresh),Co.setCustomActions(l.features?.artifacts?.toolbarActions??[]),Co.setStyleConfig(l),Co.setTabFade(l.features?.artifacts?.layout?.tabFade),Co.setRenderTabBar(l.features?.artifacts?.renderTabBar),!o&&!Ho&&(No=!1),No!==Zo){let e=Co.element;No?(ta=e.style.width,ra=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(ta&&(e.style.width=ta),ra&&(e.style.maxWidth=ra),ta="",ra=""),Zo=No}e.classList.toggle("persona-artifact-expanded",No),Co.setExpanded(No);let a=Ea();a!==Mo&&(Mo=a,Ao()),Xo()};if(Fd(l)){ut.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(gt),Go=r,r.appendChild(t),ut.appendChild(r);let n=t=>{So||Co||(Co=t.createArtifactPane(l,{onSelect:e=>Oo.current?.selectArtifact(e),onDismiss:()=>{Ro=!0,Ba()},onToggleExpand:()=>{let e=!No,t=Eo.selectedId??Eo.artifacts[Eo.artifacts.length-1]?.id??null;!0!==l.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(No=e,e||(Ho=!1),Ba())}}),Yo=t.createArtifactResizer({mount:e,splitRoot:r,pane:Co,getConfig:()=>l,chatMinWidth:ba,isVisible:zo}),Co.element.classList.add("persona-hidden"),r.appendChild(Co.element),Co.backdrop&&ut.appendChild(Co.backdrop),Xo(),Ba())},o=Et();o?n(o):(Bt(()=>{let e=Et();e&&n(e)}),Tt().catch(()=>{})),Xo=()=>Yo?.update(),xa=()=>{if(!ne||!Co||l.launcher?.sidebarMode||il(l)&&"emerge"===dl(l).reveal)return;let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,n=l.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=n||!function(e,t){return!(!t||!Fd(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(l,ne))return;let o=hd(l).width,a=l.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";zo()?(ut.style.width=a,ut.style.maxWidth=a):(ut.style.width=o,ut.style.maxWidth=o)},typeof ResizeObserver<"u"&&(ko=new ResizeObserver(()=>{Ba()}),ko.observe(ut))}else ut.appendChild(gt);me()&&ht&&(mt.peekBanner&&ht.appendChild(mt.peekBanner),ht.appendChild(tr)),e.appendChild(pt),ht&&e.appendChild(ht);let La=()=>{let t=Ia()||me()&&"fullscreen"===l.launcher?.composerBar?.expandedSize||!0===l.launcher?.fullHeight&&!l.launcher?.sidebarMode&&!il(l);if(vt.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",vt.style.setProperty("--persona-transcript-gap",vt.style.gap),me()){ut.style.width="100%",ut.style.maxWidth="100%";let e=l.launcher?.composerBar??{},t="expanded"===pt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return gt.style.background="",gt.style.border="",gt.style.borderRadius="",gt.style.overflow="",void(gt.style.boxShadow="");let n=l.theme?.components?.panel,o=di(l),a=(e,t)=>null==e||""===e?t:Us(o,e)??e;return gt.style.background="var(--persona-surface, #ffffff)",gt.style.border=a(n?.border,"1px solid var(--persona-border)"),gt.style.borderRadius=a(n?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),gt.style.boxShadow=a(n?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(gt.style.overflow="hidden")}let r=il(l),n=l.launcher?.sidebarMode??!1,o=as(l)||r||n||(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&&ne,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":n?"sidebar":a?"inline":"floating",B=c?.modes?.[E];T?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let L=T?A:n||b?"none":A,R=T?M:b?"none":n?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",L="none");let P=T?I:n||b?"0":I,N=u(B?.border??c?.border,C(E,"border",L)),$=u(B?.shadow??c?.shadow,C(E,"shadow",R)),W=u(B?.borderRadius??c?.borderRadius,C(E,"borderRadius",P)),H=Ea(),D="detached"===H,F="welded"===H;e.classList.toggle("persona-artifact-detached-split",D),e.classList.toggle("persona-artifact-welded-split",F);let z="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",O="flush"==("flush"===l.features?.artifacts?.layout?.chatSurface?"flush":"card")&&Fd(l)&&jd(l)&&a&&!r;e.classList.toggle("persona-artifact-chat-flush",O);let q=D||O?"none":$,j=D?A:F?"none":N,_=D?I:W;O&&(j="none",_="0");let U=null!=B?.borderRadius&&""!==B.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,V=O&&!U?"0":W,K=ft.scrollTop;e.style.cssText="",pt.style.cssText="",ut.style.cssText="",gt.style.cssText="",ft.style.cssText="",Mn||(tr.style.cssText="",!1===l.layout?.showFooter&&(tr.style.display="none")),qe&&(ft.style.display="none"),(o||a)&&(e.style.minWidth="0");let Q=()=>{K<=0||(ft.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ft.scrollTop===K)return;let e=ft.scrollHeight-ft.clientHeight;e<=0||(ft.scrollTop=Math.min(K,e))})};if(b)return pt.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"),pt.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 `,ut.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 ",gt.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 ",ft.style.flex="1 1 0%",ft.style.minHeight="0",ft.style.overflowY="auto",tr.style.flexShrink="0",Ur(),ue=!0,void Q();let J=hd(l);if(n||r){if(r)if("emerge"!==dl(l).reveal||s)ut.style.width="100%",ut.style.maxWidth="100%";else{let e=dl(l).width;ut.style.width=e,ut.style.maxWidth=e}}else a?(pt.style.width=md(l),ut.style.width="100%",ut.style.maxWidth="100%"):(ut.style.width=J.width,ut.style.maxWidth=J.maxWidth);if(xa(),ut.style.boxShadow=q,ut.style.borderRadius=V,D?ut.style.border="none":F&&(ut.style.border=N),gt.style.border=j,gt.style.borderRadius=_,gt.style.boxShadow=D&&!O?z:"",O&&(gt.style.background="transparent",ft.style.background="transparent",tr.style.background="transparent",tr.style.borderTop="none"),F){let e=l.features?.artifacts?.layout;To=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||Dd(l,void 0,"split.outerRadius")||Dd(l,void 0,"pane.borderRadius")||W}else To=null;let G=null!=B?.border||null!=c?.border;if(r&&!b&&!T&&!D&&!F&&!G&&(gt.style.border="none","right"===dl(l).side?gt.style.borderLeft="1px solid var(--persona-border)":gt.style.borderRight="1px solid var(--persona-border)"),r&&!b&&F&&!G&&("right"===dl(l).side?ut.style.borderLeft="1px solid var(--persona-border)":ut.style.borderRight="1px solid var(--persona-border)"),o&&(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%"),pt.style.display="flex",pt.style.flexDirection="column",pt.style.flex="1 1 0%",pt.style.minHeight="0",pt.style.maxHeight="100%",pt.style.height="100%",a&&(pt.style.overflow="hidden"),ut.style.display="flex",ut.style.flexDirection="column",ut.style.flex="1 1 0%",ut.style.minHeight="0",ut.style.maxHeight="100%",ut.style.height="100%",D||(ut.style.overflow="hidden"),gt.style.display="flex",gt.style.flexDirection="column",gt.style.flex="1 1 0%",gt.style.minHeight="0",gt.style.maxHeight="100%",gt.style.overflow="hidden",ft.style.flex="1 1 0%",ft.style.minHeight="0",ft.style.overflowY="auto",tr.style.flexShrink="0"),a&&(T||D||O)&&!r&&(O||(pt.style.padding="var(--persona-panel-inset)"),pt.style.background="var(--persona-panel-canvas-bg)"),pt.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"),!n&&!a&&!r&&(fl[v]??fl["bottom-right"]).split(" ").forEach(e=>pt.classList.add(e)),n){let e=rs(l).sidebarWidth?l.launcher?.sidebarWidth??"420px":Us(di(l),"components.panel.width")??"420px";pt.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 `,ut.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 `,ut.style.setProperty("width","100%","important"),ut.style.setProperty("max-width","100%","important"),gt.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&&!O?`box-shadow: ${z} !important;`:""}\n ${O?"background: transparent !important;":""}\n `,Mn||(tr.style.cssText=`\n flex-shrink: 0 !important;\n border-top: none !important;\n padding: 8px 16px 12px 16px !important;\n ${O?"background: transparent !important;":""}\n ${!1===l.layout?.showFooter?"display: none !important;":""}\n `)}if(!a&&!r){let e=n?"":"padding-top: 1.25em !important;",t=n?"":`z-index: ${l.launcher?.zIndex??1e5} !important;`;pt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}Ur(),Q()},Pa=()=>{e.style.setProperty("--persona-content-max-width",gi(l,me()))},Na=!1;function $a(){l.layout?.topFade&&ft.scrollTop>1?ft.setAttribute("data-persona-top-fade","true"):ft.removeAttribute("data-persona-top-fade"),Er.hidden=!me()||Tr.hidden||ft.scrollHeight-ft.clientHeight-ft.scrollTop<=1,Er.hidden||(Er.style.bottom=gt.getBoundingClientRect().bottom-Tr.getBoundingClientRect().top-gt.clientTop+"px")}let Ha=()=>{$a();let t=fi(l,me());me()&&l.composer?.placement&&!0===l.debug&&!Na&&(Na=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=Wr();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",Dr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),Vr()},Da=()=>{if(me())return;let t=il(l),r=l.launcher?.sidebarMode??!1;if(as(l)||t||r||l.launcher?.fullHeight||!ne)return;let n=e.ownerDocument.defaultView??window,o=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640;if(o&&n.innerWidth<=a)return;let s=hd(l);ut.style.height=s.height,ut.style.maxHeight=s.maxHeight};La(),ui(e,l),_d(e,l),Ud(e,l),Pa(),Ha(),Ao=()=>{La(),Da(),ui(e,l),_d(e,l),Ud(e,l),Pa(),Ha(),To?e.style.setProperty("--persona-artifact-welded-outer-radius",To):e.style.removeProperty("--persona-artifact-welded-outer-radius"),et(),Ze()};let Fa=[];Fa.push(()=>Jn.destroy()),Fa.push(()=>{So=!0}),Fa.push(()=>{M.forEach(e=>e()),A.destroy()}),Fa.push(()=>{document.removeEventListener("keydown",Jo)}),Fa.push(()=>{null!==Rr&&clearTimeout(Rr)});let za=null,qa=null;Fa.push(()=>{za?.(),za=null,qa?.(),qa=null}),ko&&Fa.push(()=>{ko?.disconnect(),ko=null}),Fa.push(()=>{Yo?.destroy(),Yo=null,Co?.element.style.removeProperty("width"),Co?.element.style.removeProperty("maxWidth"),Co?.destroy()}),Te&&Fa.push(()=>{ze=!0,Fe=null,null!==_e&&(cancelAnimationFrame(_e),_e=null),Oe?.destroy(),Oe=null,He?.destroy(),He=null,Pe=null});let _a=null,Ua=()=>{if(_a&&=(_a(),null),"auto"===l.colorScheme){let e=li(l);_a=mi(t=>{t!==e&&(e=t,Ao(),Ba(),ts&&(zs++,gd(vt,ts.getMessages(),Ae)))})}};Ua(),Fa.push(()=>{_a&&=(_a(),null)}),Fa.push(()=>{R=!0,L?.()}),Fa.push(()=>{W=!0});let Va=!1;Fa.push(()=>{Va=!0});let Ka=(t,r)=>{let n=Di(t,r);return n||!Wi.includes(t)?n:(rl().then(n=>{if(Va)return;Hi(n.wipe),Hi(n.glyphCycle);let o=Di(t,r);o&&Xi(o,e)}).catch(()=>{}),null)},Ja=l.features?.streamAnimation;if(Ja?.type&&"none"!==Ja.type){let t=Ka(Ja.type,Ja.plugins);t&&Xi(t,e),Fa.push(()=>Yi(e))}let Ga=gl(Ct),Ya=gl(wt),Xa=gl(xt),Za=gl(Tr),es=[Ga,Ya,Xa,Za];Fa.push(()=>{es.forEach(e=>e.destroy())});let ts,ns=null,os=null,is=!1,ls=0,ds=null,cs=new Set;Fa.push(()=>cs.clear());let ps=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),us=e=>{for(let t=e.length-1;t>=0;t--)if(Dn(e[t]))return e[t].id??null;return null},hs=!1,ms=!1,fs=!1,bs=(e,t)=>{ms||!0!==l.debug||t.enabled&&!t.expose&&(is||fs&&(ts.isStreaming()||e.some(Dn)||(ms=!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."))))},ys=e=>{if(!ts)return;let t=e??ts.getMessages();if(Ct.removeAttribute("data-persona-suggestions-below"),Ct.parentElement===tr&&tr.insertBefore(Ct,tr.firstChild),cs.size){let e=new Set(t.map(e=>e.id));for(let t of cs)e.has(t)||cs.delete(t)}let r=e=>{e.render([],ts,St,t)},n=e=>{es.forEach(t=>{t!==e&&r(t)})};os&&(ps(t)>ls||us(t)!==ds)&&(os=null);let o=qn(l);bs(t,o);let a=us(t),s=!o.enabled||l.future?.v5Defaults&&a&&cs.has(a)?null:zn(t,l.suggestions?.followUps?.maxItems??(l.future?.v5Defaults?5:4));if(l.future?.v5Defaults&&ts.isStreaming())return void es.forEach(r);let i=os??s,d=os?"host":"agent";if(i){let e=l.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),o="after-message"===("auto"===r?me()?"composer":"after-message":r)?Xa:me()?Za:Ga;return n(o),void o.render(i,ts,St,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?$r()?5:3:4),config:l,plugins:S,submitPrompt:Zp})}if(t.some(e=>"user"===e.role))return void es.forEach(r);let c=!0===l.future?.v5Defaults,p=$r(),u=l.suggestions?.starters??(c?{}:void 0);if(u){let e=pd(Wr(),t),o=u.placement??"auto",a="auto"===o?e?"welcome":"composer":o;if("welcome"===a&&!e)return hs||!0!==l.debug||(hs=!0,console.warn('[persona] Starters are hidden: suggestions.starters.placement is "welcome", but welcome is disabled. Use "auto" or "composer".')),void es.forEach(r);Ct.toggleAttribute("data-persona-suggestions-below","below-composer"===a),"below-composer"===a?At.after(Ct):tr.insertBefore(Ct,tr.firstChild);let s="welcome"===a?Ya:Ga;n(s),s.render(u.items??l.suggestionChips,ts,St,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:S,submitPrompt:Zp})}else n(Ga),Ga.render(l.suggestionChips,ts,St,t,l.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:l,plugins:S,submitPrompt:Zp})},ws=()=>{if(!l.future?.v5Defaults||!ts)return;os=null;let e=us(ts.getMessages());e&&cs.add(e),ys()},Ss=()=>{os&&(os=null,ys())},ks=!1,As=new Map,Is=new Set,Ts=new Map,Es=new Map,Bs=new Map,Ls=new Map,Rs=e=>{let t=Ls.get(e);if(Ls.delete(e),Bs.delete(e),id(vt,e)?.removeAttribute("data-preserve-runtime"),t){t.controller.abort();try{t.handle.destroy?.()}catch(e){console.error("[AgentWidget] Component cleanup failed:",e)}}};Fa.push(()=>{for(let e of Ls.keys())Rs(e)});let Ps=new Map,Ns=new Map,$s=e=>{Ns.get(e)?.abort(),Ns.delete(e),Ps.delete(e)},Ws=()=>{for(let e of Ns.keys())$s(e)};Fa.push(Ws);let Hs=null,Ds=null;function Fs(){if(!Hs)return;let e=Hs;Hs=null,Ds?.destroy(),Ds=null,As.delete(e),gt.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),ts&&gd(vt,ts.getMessages(),Ae)}let zs=0,Os=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),qs=0,js=null,Vs=!1,Ks=!1,Qs=0,Js=null,Gs=null,Ys=!1,Xs=!1,Zs=null,ei=!0,ti=!1,ri=null,ni=!1,oi=()=>{uo++,ni=!0,pi()},ai=null,si=24,ii=null,ci=()=>{e.setAttribute("data-persona-scrollbar",Sr()),"on-scroll"!==Sr()&&(null!==ii&&clearTimeout(ii),ii=null,ft.removeAttribute("data-persona-scrollbar-visible"))},pi=()=>{"on-scroll"===Sr()&&(ft.setAttribute("data-persona-scrollbar-visible",""),null!==ii&&clearTimeout(ii),ii=setTimeout(()=>{ii=null,Jt(ft,24)&&ft.removeAttribute("data-persona-scrollbar-visible")},1e3))};ci(),Fa.push(()=>{null!==ii&&clearTimeout(ii)});let hi=new Map,yi=!1,vi=null,xi={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Yn();let ki=l.voiceRecognition?.autoResume??!1,Ai=()=>ts.isVoiceActive()||ts.isBargeInActive(),Ei=!1,Bi=e=>{z.emit("voice:state",{active:xi.active,source:e,timestamp:Date.now()})},Ri=()=>{Z(e=>({...e,voiceState:{active:xi.active,timestamp:Date.now(),manuallyDeactivated:xi.manuallyDeactivated}}))},Ni=()=>{Ei=!0,xi.active&&Ri()};typeof window<"u"&&(window.addEventListener("pagehide",Ni),Fa.push(()=>window.removeEventListener("pagehide",Ni)));let $i=()=>ts?fp(ts.getMessages()).filter(e=>!e.__skipPersist):[],zi=null,Oi=(e,t)=>{typeof console<"u"&&console.error(e,t)},qi=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{Oi(t,e)}):null}catch(e){return Oi(t,e),null}},n=zi?zi.then(()=>r()??void 0):r();if(!n)return;let o=n.finally(()=>{zi===o&&(zi=null)});zi=o};function ji(e){if(null!==Ui||!O?.save)return;let t=e?fp(e):ts?$i():[],r=q&&ts?.getResumableHandle();r&&(_={..._,durableResume:{executionId:r.executionId,after:r.lastEventId}});let n={messages:t,metadata:_,artifacts:Eo.artifacts,selectedArtifactId:Eo.selectedId,..._i?{draft:_i}:{}};qi(()=>O.save(n),"[AgentWidget] Failed to persist state:")}let _i,Ui=null,Ji=()=>!(!O?.save||!1===l.persistState||"object"==typeof l.persistState&&!1===l.persistState.persist?.draft),Gi=function(e){let t=e.delay??500,r=null,n=!1,o=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{n||(o(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{n||null===r||(o(),e.write())},cancel:o,destroy:()=>{n=!0,o()}}}({write:()=>{if(!Ji())return;let e=Jr.getState(),t=ha({text:e.text,mentionRefs:e.mentionRefs,contentSegments:jp(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(_i)&&(_i=t,ji())}});function Zi(){Ji()&&Gi.schedule()}function el(){Gi.flush()}function tl(e){if(!Ji())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),o=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(e=>e.id)),s=(e.activeModeIds??[]).filter(e=>a.has(e)),i=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...o?{mentionRefs:n}:{},...o&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(l.contextMentions?.sources??[]).map(e=>e.id),modelIds:(l.composer?.models??[]).map(e=>e.id),modes:l.composer?.modes??[]});t&&(_i=e,St&&!St.value&&(St.value=t.text,St.dispatchEvent(new Event("input",{bubbles:!0})),Gr()),t.selectedModelId&&(Jr.setSelectedModelId(t.selectedModelId),dn?.repaint()),sn(t.activeModeIds??[]),t.quote&&un(t.quote),Gi.cancel())}function ol(){Gi.cancel(),_i&&(_i=void 0,Ji()&&ji())}let al=Yt(),cl=()=>pt.querySelector("#persona-scroll-container")||ft,pl=()=>{al.cancel(),Vs=!1},hl=()=>{null!==js&&(cancelAnimationFrame(js),js=null),Ks=!1,pl()},bl=()=>{let e=ts?.getStatus();return ks&&"paused"!==e&&"resuming"!==e&&"error"!==e&&!ts?.getMessages().some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)},yl=()=>bl()&&Cl()&&("anchor-top"!==br()||xr()),vl=()=>{kr.update(l,"true"===Ar.getAttribute("data-persona-scroll-to-bottom-visible"),yl(),Qs)},Cl=()=>!(yr()&&Os.isFollowing()||(()=>{let e=jl(Js?.spacerHeight??0,!1),t=ft.getBoundingClientRect(),r=tr.getBoundingClientRect(),n=r.height>0&&r.bottom>t.top?Math.min(ft.clientHeight,Math.max(0,r.top-t.top-ft.clientTop)):ft.clientHeight;return e-ft.scrollTop-n<=24})()),Sl=()=>!!ts&&ts.getMessages().length>0,Al=()=>{if(!1===l.features?.scrollToBottom?.enabled||qe||Ye&&"panel"===Xe)return kr.update(l,!1),void(Ar.parentNode&&Ar.remove());let e=Ir();Ar.parentNode!==e&&e.insertBefore(Ar,e===gt?Tr:null),qr();let t=Qt(ft)>0,r=!Rl.active&&t&&Cl()&&Sl();r||(Qs=0),kr.update(l,r,yl(),Qs)},Ml=()=>{Os.pause()&&(hl(),Al())},El=()=>{Os.resume(),0!==Qs&&(Qs=0,vl()),Al()},Bl=(e=!1)=>{!Rl.active&&yr()&&Sl()&&Os.isFollowing()&&(e||ks)&&(null!==js&&(cancelAnimationFrame(js),js=null),Ks=!0,js=requestAnimationFrame(()=>{js=null,Ks=!1,Os.isFollowing()&&Nl(cl(),e?220:140)}))},Ll=(e,t,r,n=()=>!0)=>{pl(),Vs=!0,al.start(e,t,r,()=>{qs=e.scrollTop},()=>{Vs=!1},n)},Rl=Xt(ft,gt,()=>{qs=ft.scrollTop},()=>{El(),Bl(!0),Al()},()=>{Os.pause(),Al()}),Nl=(e,t=500)=>{let r=Qt(e)-e.scrollTop;Math.abs(r)<1?qs=e.scrollTop:Math.abs(r)>=80?(pl(),Vs=!0,e.scrollTop=Qt(e),qs=e.scrollTop,Vs=!1):Ll(e,()=>Qt(e),t,()=>Os.isFollowing())},Hl=()=>{if(!Sl())return void Al();let e=cl();Vs=!0,e.scrollTop=Qt(e),qs=e.scrollTop,Vs=!1,Al()},Dl=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=ft.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??ft.ownerDocument.getSelection()})(),ft),zl=()=>{if("last-user-turn"!==(Be.restorePosition??"bottom"))return!1;let e=ts?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>"user"===e.role);if(!t)return!1;let r=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(t.id):t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=ft.querySelector(`[data-message-id="${r}"]`);if(!n)return!1;let o=Math.min(Math.max(0,Or(n)-vr()),Qt(ft));return Vs=!0,ft.scrollTop=o,qs=ft.scrollTop,Vs=!1,"follow"===br()&&!Jt(ft,24)&&Os.pause(),Al(),!0},Ol=e=>{let t=Math.max(0,Math.round(e));Br.style.height=`${t}px`,Br.style.display=t>0?"":"none",Js&&(Js.spacerHeight=Math.max(0,e))},jl=(e,t=!0)=>{let r=parseFloat(getComputedStyle(ft).paddingBottom)||0,n=0;for(let e of ft.children){let t=e;t!==Br&&0!==t.offsetHeight&&(n=Math.max(n,Or(t)+t.offsetHeight))}let o=ft.scrollHeight-e,a=n>0?Math.min(n+r,o):o;return t?a:a-r},Ul=()=>{null!==Gs&&(cancelAnimationFrame(Gs),Gs=null),Rl.cancel(),pl(),Js=null,Br.style.height="0px",Br.style.display="none"},Vl=e=>ft.querySelector(`[data-message-id="${(e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'))(e)}"]`),Kl=e=>{let t=Vl(e);return t?.closest("[data-persona-turn-activity]")??t},Yl=e=>{null!==Gs&&cancelAnimationFrame(Gs),Gs=requestAnimationFrame(()=>{Gs=null;let t=Kl(e);if(!t)return;let r=Or(t),n=jl(Js?.spacerHeight??0),{targetScrollTop:o,spacerHeight:a}=Gt({anchorOffsetTop:r,topOffset:vr(),viewportHeight:ft.clientHeight,contentHeight:n,slack:24});Js={pending:0,initialSpacerHeight:a,contentHeightAtAnchor:n,spacerHeight:a},Ol(a),Ll(ft,()=>t.isConnected?Math.max(0,Or(t)-vr()):o,220)})},Xl=()=>{if("anchor-top"!==br()||!Js||!ri)return;let e=Kl(ri);if(!e)return;pl();let t=Js.spacerHeight,r=jl(t),{targetScrollTop:n,spacerHeight:o}=Gt({anchorOffsetTop:Or(e),topOffset:vr(),viewportHeight:ft.clientHeight,contentHeight:r,slack:24});Js={pending:0,initialSpacerHeight:o,contentHeightAtAnchor:r,spacerHeight:o},Ol(o),Vs=!0,ft.scrollTop=n,qs=ft.scrollTop,Vs=!1,Al()},Zl=e=>{if(null===Zs)return!0;let t=Vl(Zs),r=Kl(e);if(!t||!r)return!0;let n=Or(r)-Or(t);return vr()+n>ft.clientHeight-96},nd=(e,t)=>{let r="user"===t?"user":"assistant",n=l.layout?.messages?.[r],o=n?.width??"content",a=n?.maxWidth??("full"===o?`var(--persona-message-${r}-max-width, 100%)`:void 0);e.classList.add("persona-message-row"),e.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${o}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",o),a?e.style.setProperty("--persona-message-row-max-width",a):e.style.removeProperty("--persona-message-row-max-width")},sd=(e,t)=>{let r=document.createElement("div");return r.className="persona-flex",r.id=`wrapper-${e}`,r.setAttribute("data-wrapper-id",e),nd(r,t),r},id=(e,t)=>Array.from(e.querySelectorAll("[data-wrapper-id]")).find(e=>e.getAttribute("data-wrapper-id")===t),dd=(t,r,n)=>{let o=new Set;g(),i?.observeMessages(r,o);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=S.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator??l.loadingIndicator?.render,v=new Set,w=new Map,x=new Set,C=S.some(e=>e.renderAskUserQuestion),k=[],A=[],M=!1!==l.enableComponentStreaming,T=!1!==l.approval,L=[],R=l.messageActions;if(l.future?.v5Defaults&&void 0===R?.visibility)for(let e=r.length-1;e>=0;e--)if("assistant"===r[e].role&&!r[e].variant){p=r[e].id;break}let P=!0!==R?.showRegenerate&&"block"!==l.errorDisplay||!1===R?.enabled||!0===Oo.current?.isStreaming()?null:function(e){for(let t=e.length-1;t>=0;--t){let r=e[t];if("user"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return Bo(e,r.id)?r.id:null}return null}(r),N=!0===R?.showEdit&&!1!==R.enabled,W=!0===R?.showQuote&&!1!==R.enabled,H=null,D=l.features?.reasoningDisplay?.completedVisibility,z=e=>"removed"===D||"removed-when-short"===D&&((e,t)=>{let r=t?.durationMs??15e3,n=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<n})(e,l.features?.reasoningDisplay?.shortThinkThreshold),O="removed"===l.features?.toolCallDisplay?.completedVisibility,q=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?z(e.reasoning):O&&"tool"===e.variant&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;r.forEach(o=>{if(q(o))return;if(v.add(o.id),w.set(o.id,o.role),("tool"===o.variant&&o.toolCall&&Ie||"reasoning"===o.variant&&o.reasoning&&Me)&&!g())return void a.appendChild(sd(o.id,o.role));if(Hs===o.id&&Ds){let e=sd(o.id,o.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void(H={messageId:o.id,element:Ds.element})}let s=C&&vn(o),i=T&&"approval"===o.variant&&!!o.approval,I=!s&&"assistant"===o.role&&!o.variant&&M&&$o(o);!i&&Ps.has(o.id)&&(id(t,o.id)?.removeAttribute("data-preserve-runtime"),$s(o.id)),!I&&Bs.has(o.id)&&(id(t,o.id)?.removeAttribute("data-preserve-runtime"),Rs(o.id));let D=vn(o)?`:${o.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${o.agentMetadata?.askUserQuestionAnswers?Object.keys(o.agentMetadata.askUserQuestionAnswers).length:0}`:"",z={isLastAssistant:o.id===p,canRegenerate:P===o.id&&(!0===R?.showRegenerate||!0===o.dispatchError),canEdit:N&&Lo(o),canQuote:W&&!o.variant&&(o.content?.trim().length??0)>0},O=`${z.canRegenerate?"r":""}${z.canEdit?"e":""}${z.canQuote?"q":""}${z.isLastAssistant?"l":""}`,j=o.approval?.toolCallId?r.filter(e=>!("tool"!==e.variant||e.toolCall?.id!==o.approval?.toolCallId||e.agentMetadata?.executionId&&o.approval?.executionId&&e.agentMetadata.executionId!==o.approval.executionId)):[],_=1===j.length?j[0].toolCall:void 0,U=_&&"pending"!==_.status?{toolCallId:_.id,status:"running"===_.status?"running":!1===_.success||_.error?"failed":"completed"}:void 0,V=Li(o,zs)+D+`:${O}`+(i?`:${o.approval?.toolCallId??""}:${JSON.stringify(U)}`:""),K=s||i||I||o.dispatchError&&"block"===l.errorDisplay&&!E?null:function(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}(As,o.id,V);if(K){if(c.has(o.id)&&Ts.get(o.id)===V){let e=document.createElement("div");e.id=`wrapper-${o.id}`,e.setAttribute("data-wrapper-id",o.id),e.setAttribute("data-persona-reuse","true"),a.appendChild(e)}else a.appendChild(K.cloneNode(!0));return d&&u.set(o.id,V),void(vn(o)&&o.toolCall?.id&&!0===o.agentMetadata?.awaitingLocalTool&&!o.agentMetadata?.askUserQuestionAnswered&&(x.add(o.toolCall.id),_o(o)))}let Q=null,J=()=>{if(o.dispatchError&&"block"===l.errorDisplay){let e=$();if(e)return e.createErrorBlock(o,n,!0===z.canRegenerate)}let e=Ql(o,n,l.layout?.messages,l.messageActions,0,{loadingIndicatorRenderer:h,widgetConfig:l,actionEligibility:z});return e.dataset.personaDefaultMessage="true",e},G=S.find(e=>!!("reasoning"===o.variant&&e.renderReasoning||"tool"===o.variant&&e.renderToolCall||!o.variant&&e.renderMessage));if(vn(o)&&!0===o.agentMetadata?.askUserQuestionAnswered)return Es.delete(o.id),void id(t,o.id)?.removeAttribute("data-preserve-runtime");if(Dn(o)&&qn(l).enabled)return;if(vn(o)&&!1!==l.features?.askUserQuestion?.enabled){let e=S.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&Oo.current){let t=Es.get(o.id),r=t!==V,n=null;if(r){let{payload:t,complete:r}=xn(o),a=o.id,s=()=>Oo.current?.getMessages().find(e=>e.id===a);n=e.renderAskUserQuestion({message:o,payload:t,complete:r,resolve:e=>{let t=s();t&&Oo.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Oo.current?.markAskUserQuestionResolved(e),Oo.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:l})}if(r&&null===n&&null==t)return void(!0===o.agentMetadata?.awaitingLocalTool&&!o.agentMetadata?.askUserQuestionAnswered&&(x.add(o.toolCall.id),_o(o)));let s=sd(o.id,o.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),a.appendChild(s),void k.push({messageId:o.id,fingerprint:V,bubble:n})}return void(!0===o.agentMetadata?.awaitingLocalTool&&!o.agentMetadata?.askUserQuestionAnswered&&(x.add(o.toolCall.id),_o(o)))}if(i){let t=$();if(!t)return void a.appendChild(sd(o.id,o.role));let r=S.find(e=>"function"==typeof e.renderApproval)??B,n=Ps.get(o.id),s=null,i=!1;if(n!==V&&r?.renderApproval){let a=o.id,d=!1,c=(e,t)=>{let r=Oo.current?.getMessages().find(e=>e.id===a);d||"pending"!==r?.approval?.status||(d=!0,cr(r.approval)?Oo.current?.resolveWebMcpApproval(r.id,e):Oo.current?.resolveApproval(r.approval,e,t))};$s(o.id);let p=new AbortController;Ns.set(o.id,p);let u={message:o,execution:U,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??=B?.renderApproval?.({...u,signal:m.signal})??t.createApprovalBubble(o,l,y),h);s=r===B?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===n&&"pending"===o.approval?.status&&!1!==l.approval&&"focused"===l.approval?.keyboardShortcuts&&e.contains(b.activeElement)}let d=sd(o.id,o.role);return d.setAttribute("data-approval-plugin-stub","true"),d.setAttribute("data-preserve-runtime","true"),a.appendChild(d),void L.push({messageId:o.id,fingerprint:V,bubble:s,focusDefault:i})}if(G)if("reasoning"===o.variant&&o.reasoning&&G.renderReasoning){if(!Me)return;Q=G.renderReasoning({message:o,defaultRenderer:()=>m.createReasoningBubble(o,l,b),config:l})}else if("tool"===o.variant&&o.toolCall&&G.renderToolCall){if(!Ie)return;Q=G.renderToolCall({message:o,defaultRenderer:()=>m.createToolBubble(o,l,f),config:l})}else G.renderMessage&&(Q=G.renderMessage({message:o,defaultRenderer:()=>{let e=J();return"user"!==o.role&&F(e,o,l,ts),e},config:l}));if(Q&&Ls.has(o.id)&&Rs(o.id),!Q&&I){let e=Wo(o);if(e){let r=Bs.get(o.id),s=!1!==l.wrapComponentDirectiveInBubble&&!1!==yt(l,e.component)?.bubbleChrome,i=`${Li(o,zs)}:${s}:${e.raw}`,d=Ls.get(o.id),c=bt(l,e.component),p=d?.renderer!==c||d?.component!==e.component,u=r!==i||p;d&&(d.context.message=o,d.context.config=l);let h=null;if(u){let r=null;if(d&&!p&&d.handle.update){d.context.message=o,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),Rs(o.id)}}else{Rs(o.id);let t=new AbortController,a={config:l,message:o,signal:t.signal,updateProps:e=>{queueMicrotask(()=>{t.signal.aborted||Oo.current?.updateComponentProps(o.id,e)})}},s=Po(e,{config:l,message:o,transform:n,signal:t.signal,onPropsUpdate:a.updateProps,context:a});if(s){let n="element"in s?s:{element:s};r=n.element,Ls.set(o.id,{renderer:c,component:e.component,controller:t,handle:n,context:a})}else t.abort()}if(r&&"PersonaArtifactInline"===e.component){let e=r.hasAttribute("data-artifact-inline")?r:r.querySelector("[data-artifact-inline]"),n=e?.getAttribute("data-artifact-inline")??"",a=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(n):n,s=n?t.querySelector(`#wrapper-${o.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"].join(" "),e.id=`bubble-${o.id}`,e.setAttribute("data-message-id",o.id),o.content&&o.content.trim()){let t=document.createElement("div");t.className="persona-mb-3 persona-text-sm persona-leading-relaxed",t.innerHTML=n({text:o.content,message:o,streaming:!!o.streaming,raw:o.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-${o.id}`,e.setAttribute("data-message-id",o.id),e.setAttribute("data-persona-component-directive","true"),o.content&&o.content.trim()){let t=document.createElement("div");t.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",t.innerHTML=n({text:o.content,message:o,streaming:!!o.streaming,raw:o.rawContent}),e.appendChild(t)}e.appendChild(r),h=e}}if(h||Ls.has(o.id)){let e=sd(o.id,o.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void A.push({messageId:o.id,fingerprint:i,bubble:h})}}}if(!Q)if("reasoning"===o.variant&&o.reasoning){if(!Me)return;Q=m.createReasoningBubble(o,l,b)}else if("tool"===o.variant&&o.toolCall){if(!Ie)return;Q=m.createToolBubble(o,l,f)}else if("approval"===o.variant&&o.approval){if(!1===l.approval)return;let e=$();if(!e)return;Q=e.createApprovalBubble(o,l,y)}else{let e=l.layout?.messages;Q=e?.renderUserMessage&&"user"===o.role?e.renderUserMessage({message:o,config:l,streaming:!!o.streaming}):e?.renderAssistantMessage&&"assistant"===o.role?e.renderAssistantMessage({message:o,config:l,streaming:!!o.streaming}):J(),"user"!==o.role&&Q&&F(Q,o,l,ts)}let Y=sd(o.id,o.role);Y.appendChild(Q),function(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}(As,o.id,V,Y),a.appendChild(Y),d&&u.set(o.id,V)}),mt.composerOverlay&&mt.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!x.has(t)&&Nn(mt.composerOverlay,t)});let j=g()?.groupToolRows({root:e,config:l,messages:r,tempContainer:a,streaming:!!I&&ts.isStreaming(),runActivity:ts?.getRunActivity(),showToolCalls:Ie,showReasoning:Me,dropCompletedToolCalls:O,dropReasoningRow:z,createMessageRow:sd,activityIds:o,activityLifecycle:i,toolExpansionState:f});i?.prune(o);for(let e of Ls.keys())v.has(e)||Rs(e);for(let e of Ns.keys())v.has(e)||$s(e);!function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(As,v);let _=e=>"tool"===e.variant&&!Ie||"reasoning"===e.variant&&!Me||q(e),U=r.some(e=>"assistant"===e.role&&e.streaming&&!_(e)),V=r.length-1;for(;V>=0&&_(r[V]);)V--;let K=V>=0?r[V]:void 0,Q=V<r.length-1,J="assistant"===K?.role&&!K.streaming&&"approval"!==K.variant&&!Q;if(!j&&ks&&r.some(e=>"user"===e.role)&&!U&&!J){let e={config:l,streaming:!0,location:"standalone",defaultRenderer:()=>Fl(l)},t=S.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator?.(e)??l.loadingIndicator?.render?.(e)??Fl(l);if(t){let e=document.createElement("div"),r=!1!==l.loadingIndicator?.showBubble,n=l.layout?.messages?.layout??"bubble";e.className=r?ql("assistant",n).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),e.setAttribute("data-typing-indicator","true"),r&&(e.style.color="var(--persona-message-assistant-text, var(--persona-text))","flat"!==n&&(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 o=sd("typing-indicator","assistant");o.appendChild(e),a.appendChild(o)}}if(!ks&&r.length>0){let e=r[r.length-1],t={config:l,lastMessage:e,messageCount:r.length},n=S.find(e=>e.renderIdleIndicator)?.renderIdleIndicator?.(t)??l.loadingIndicator?.renderIdle?.(t);if(n){let e=document.createElement("div");e.className=!1===l.loadingIndicator?.showBubble?["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "):["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "),e.setAttribute("data-idle-indicator","true"),e.appendChild(n);let t=sd("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),Ts=u;for(let e of Array.from(t.querySelectorAll(":scope > [data-persona-reuse]"))){let t=As.get(e.getAttribute("data-wrapper-id")??"");t?e.replaceWith(t.wrapper.cloneNode(!0)):e.remove()}if(Hr(t),H){let{messageId:e,element:r}=H,n=id(t,e);n&&r.parentElement!==n&&(nd(n,w.get(e)??"user"),n.replaceChildren(r))}if(k.length>0)for(let{messageId:e,fingerprint:r,bubble:n}of k){let o=id(t,e);o&&(nd(o,w.get(e)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Es.set(e,r)))}if(Es.size>0)for(let e of Es.keys())v.has(e)||Es.delete(e);if(A.length>0)for(let{messageId:e,fingerprint:r,bubble:n}of A){let o=id(t,e);o&&(nd(o,w.get(e)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Bs.set(e,r)))}if(Bs.size>0)for(let e of Bs.keys())v.has(e)||Bs.delete(e);if(L.length>0)for(let{messageId:e,fingerprint:r,bubble:n,focusDefault:o}of L){let a=id(t,e);a&&(nd(a,w.get(e)??"assistant"),null!==n&&(a.replaceChildren(n),a.setAttribute("data-bubble-fp",r),Ps.set(e,r),o&&n.querySelector('[data-action="allow"]')?.focus()))}if(Ps.size>0)for(let e of Ps.keys())v.has(e)||Ps.delete(e);g(),s?.sync(),i?.sync()},ud=()=>{jr().catch(()=>{})},gd=(e,t,r)=>{if(t.length>0&&ud(),dd(e,t,r),wo(),po.size>0){for(let[e,r]of po)t.some(t=>t.id===e)||(window.clearTimeout(r),po.delete(e));ho()}},yd=null,vd=()=>{if(yd)return;let t=e=>{let t=e.composedPath();t.includes(pt)||ht&&t.includes(ht)||Nd(!1,"user")};yd=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},wd=()=>{yd&&=((e.ownerDocument??document).removeEventListener("pointerdown",yd,!0),null)};Fa.push(()=>wd());let xd=null,Cd=()=>{if(xd)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Nd(!1,"user"))};xd=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},Ad=()=>{xd&&=((e.ownerDocument??document).removeEventListener("keydown",xd,!0),null)};Fa.push(()=>Ad());let Id=!1,Td=new Set,Ed=()=>l.launcher?.composerBar?.peek?.streamAnimation||l.features?.streamAnimation,Bd=()=>{if(!me())return;let t=mt.peekBanner,r=mt.peekTextNode;if(!t||!r)return;if(fe)return void t.classList.remove("persona-pill-peek--visible");let n,o=ts?.getMessages()??[];for(let e=o.length-1;e>=0;e--){let t=o[e];if("assistant"===t.role&&t.content){n=t;break}}if(!n)return void t.classList.remove("persona-pill-peek--visible");let a=n.content,s=!!n.streaming,i=Ed(),l=Pi(i),d="none"===l.type?null:Ka(l.type,i?.plugins),c=!0===d?.isAnimating?.(n),p=null!==d&&(s||c);p&&d&&!Td.has(d.name)&&(Xi(d,e),Td.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,n,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),o=m.length>100?m.slice(-100):m,a=Mr(o);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Vi(a,d.wrap,`peek-${n.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&o.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:n.id,message:n,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${o}`:o;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=ks||Id;t.classList.toggle("persona-pill-peek--visible",g)};if(me()){let e=mt.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Nd(!0,"user")};e.addEventListener("pointerdown",t),Fa.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Id||(Id=!0,Bd())},r=()=>{Id&&(Id=!1,Bd())};ut.addEventListener("pointerenter",t),ut.addEventListener("pointerleave",r),Fa.push(()=>{ut.removeEventListener("pointerenter",t),ut.removeEventListener("pointerleave",r)}),ht&&(ht.addEventListener("pointerenter",t),ht.addEventListener("pointerleave",r),Fa.push(()=>{ht.removeEventListener("pointerenter",t),ht.removeEventListener("pointerleave",r)}))}let Ld=()=>{if(fe&&ud(),!ge())return;if(me()){let e=(l.launcher?.composerBar??{}).expandedSize??"anchored",t=fe?"expanded":"collapsed";return pt.dataset.state=t,pt.dataset.expandedSize=e,ht&&(ht.dataset.state=t,ht.dataset.expandedSize=e),pt.style.removeProperty("display"),pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=l.launcher?.composerBar??{},r=t.expandedSize??"anchored",n=t.bottomOffset??"16px",o=t.collapsedMaxWidth,a=t.expandedMaxWidth??"880px",s=t.expandedTopOffset??"5vh",i=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)";_r();let p=pt.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",ht){let e=ht.style;e.bottom=n,e.width=o??""}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(${n} + var(--persona-pill-area-height, var(--persona-measured-pill-area-height, 80px)))`,p.top=s,p.width=a,p.maxWidth=c))})(fe),gt.style.display=fe?"flex":"none",Ao(),fe?(vd(),Cd()):(wd(),Ad()),void Bd()}let t=il(l),r=e.ownerDocument.defaultView??window,n=l.launcher?.mobileBreakpoint??640,o=l.launcher?.mobileFullscreen??!0,a=r.innerWidth<=n,s=o&&a&&ne,i=dl(l).reveal;fe?(pt.style.removeProperty("display"),pt.style.display=t?"flex":"",pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-95","persona-opacity-0"),ut.classList.add("persona-scale-100","persona-opacity-100"),Xu?(Xu.setPanelOpen(!0),Xu.element.style.display="none"):Zu&&(Zu.style.display="none")):(t?!t||"overlay"!==i&&"push"!==i||s?(pt.style.setProperty("display","none","important"),pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(pt.style.removeProperty("display"),pt.style.display="flex",pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(pt.style.display="",pt.classList.add("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-100","persona-opacity-100"),ut.classList.add("persona-scale-95","persona-opacity-0")),Xu?(Xu.setPanelOpen(!1),Xu.element.style.display=t?"none":""):Zu&&(Zu.style.display=t?"none":""))},Nd=(t,r="user")=>{if(!ge()||fe===t)return;let n=fe;fe=t,Ld();let o=(()=>{let t=l.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,n=l.launcher?.mobileFullscreen??!0,o=l.launcher?.mobileBreakpoint??640,a=r.innerWidth<=o,s=il(l)&&n&&a,i=me()&&"fullscreen"===(l.launcher?.composerBar?.expandedSize??"fullscreen");return t||n&&a&&ne||s||i})();if(fe&&o){if(!za){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(za=nl(r,l.launcher?.zIndex??1e5))}qa||=sl(e.ownerDocument)}else fe||(za?.(),za=null,qa?.(),qa=null);fe&&(nh(),zl()||("follow"===br()?Bl(!0):Hl()));let a={open:fe,source:r,timestamp:Date.now()};fe&&!n?z.emit("widget:opened",a):!fe&&n&&z.emit("widget:closed",a),z.emit("widget:state",{open:fe,launcherEnabled:ne,voiceActive:xi.active,streaming:ts.isStreaming()})},$d={inputDisabled:!1,sendDisabled:!1},Wd=()=>$d.inputDisabled,zd=()=>_t(l.voiceRecognition?.provider)&&!!ts&&(ts.isBargeInActive()||["listening","processing","speaking"].includes(ts.getVoiceStatus())),Od=()=>$d.inputDisabled||$d.sendDisabled;function qd(){if(!kt)return;if("streaming"===Jr.getState().phase)return void(kt.disabled=!1);let e=!!Kr&&!Kr.isReady();kt.disabled=Od()||e}function Vd(){if(!sr)return;let e=Jr.getState(),t="when-text"===l.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;sr.toggleAttribute("data-persona-send-hidden",t)}function Kd(){let e=Aa(l.composer?.inputDisabled),t=Aa(l.composer?.sendDisabled);$d={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Jr.setInputDisabled(e.disabled),Jr.setSendDisabled(t.disabled);let r="streaming"===Jr.getState().phase,n=e.disabled,o=r||n;St&&(St instanceof HTMLTextAreaElement?St.disabled=n:St.setAttribute("contenteditable",n?"false":"true"),St.setAttribute("aria-disabled",n?"true":"false")),pr&&(pr.disabled=n),gr&&(gr.disabled=n);for(let e of Qr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=n});lr&&(lr.disabled=n||r&&!zd()),es.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",o?"true":"false")}),e.buttons.forEach(e=>{e.disabled=o})}),pc.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement?e.disabled=o:e.setAttribute("aria-disabled",o?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=o})}),tr.dataset.personaComposerStreaming=r?"true":"false",tr.dataset.personaComposerInputDisabled=n?"true":"false",tr.dataset.personaComposerSendDisabled=Od()?"true":"false",tr.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=r)}),qd(),function(){let e=($d.inputDisabled?$d.inputReason:void 0)??($d.sendDisabled?$d.sendReason:void 0);if(me()){let t=At??tr;e?t.setAttribute("title",e):t.removeAttribute("title"),tr.toggleAttribute(pp,!!e)}else if(e)Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.setAttribute(pp,""),Mt.removeAttribute(up),Mt.textContent=e,ur(Mt,l.statusIndicator??{},"idle");else if(Mt.hasAttribute(pp)&&(Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),Mt.removeAttribute(pp),I)){let e=ts.getStatus();lt(Mt,it(e),l.statusIndicator??{},e)}}()}let Qd=e=>{Jr.setStreaming(e),ir(e?"stop":"send"),Kd()},Jd=()=>{e.hasAttribute("data-persona-preparing")?u.ready.then(Jd,()=>{}):xi.active||St&&St.focus()};z.on("widget:opened",()=>{l.autoFocusInput&&setTimeout(()=>Jd(),200)});let Gd=null,Yd=!1,Xd=!It.hidden,Zd=null,ec=!U,tc=null;Fa.push(()=>{tc?.cancel(),tc=null});let rc,nc,oc=t=>{let r=cd(t);if(r===Dr)return;Dr=r,e.setAttribute("data-persona-conversation-state",r);let n=zr();Vr(),ec&&(tc?.cancel(),tc=ad(tr,"active"===r?n:zr(),"active"===r?"drop":"rise","centered"===Wr().layout?320:260)),Xl()},ac=null,sc=null,ic=null,lc=!1,dc=e=>{let t=Wr(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==ac||t.icon!==rc)&&(ac=r,rc=t.icon,Gl({host:It,iconHolder:Lt,kicker:Pt,title:Nt,subtitle:$t,starterSuggestions:wt},t));let n=void 0===t.message?null:`${l.layout?.messages?.layout??"bubble"}|${t.message}`;n!==sc&&(sc=n,rd(Rt,t.message,l));let o=e??(ts?ts.getMessages():l.initialMessages);oc(o);let a=Yd,s=!a&&pd(t,o),i=s!==Xd;if(Xd=s,ic)return Zd?.cancel(),Zd=null,a!==lc&&(lc=a,a?td(ft,It,null):ed(ft,It,ic)),void Jl(ft,It,!a);if(i&&!s&&!a&&"on-first-message"===t.dismiss&&ec)return void(Zd=od(It,e=>{Zd===e&&(Zd=null),!Xd&&!ic&&(Jl(ft,It,!1),Xl()),e?.cancel()}));if(Zd){if(!s&&!a)return;Zd.cancel(),Zd=null}let d=!It.hidden;Jl(ft,It,s),!s&&d&&Xl()},cc=[],pc=[],uc=!1,hc=null,gc=()=>{pc.length=0;let e=cc.splice(0,cc.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};Fa.push(gc);let fc=(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 n=l.suggestions?.starters,o=ml({item:{...r,behavior:r.behavior??n?.behavior??"send"},index:t,surface:"starter",source:"config",variant:n?.variant??"card",streaming:!!I&&ts.isStreaming(),config:l,plugins:S,chipsConfig:l.suggestionChipsConfig,session:ts,getTextarea:()=>St,eventTarget:It,submitPrompt:Zp});return pc.push(o),o},bc=()=>{if(uc)return;uc=!0;let e=Wr();hc=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,nc=e.icon;try{gc(),td(ft,It,ic),ic=null,lc=!1;let t=ts?ts.getMessages():l.initialMessages,r=pd(e,t),n=0,o=null;for(let t of S)if(t.renderWelcome&&(o=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>It,sendMessage:e=>{if(!ts||ts.isStreaming())return;let t=e.trim();t&&ts.sendMessage(t)},requestRender:()=>bc(),renderStarter:e=>fc(e,n++),storage:T(t.id),onCleanup:e=>{cc.push(e)}}),o))break;o&&o!==It&&(ic=o,ed(ft,It,o))}finally{uc=!1}dc()},yc=()=>{dc(),Mn||(St.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Jr.getState().activeModeIds,l.composer?.modes)??l.copy?.inputPlaceholder??"How can I help...",!l.sendButton?.useIcon&&!ts?.isStreaming()&&(kt.textContent=l.copy?.sendButtonLabel??"Send")),St.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',St.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},vc=!!l.setStoredConversationId,Sc=e=>Z(t=>{let r={...t};return delete r[e],r}),kc=e=>{let t=_[e];return"string"==typeof t?t:null},Ac=()=>{let e=_.durableResume;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.executionId&&t.executionId.length>0&&"string"==typeof t.after&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};l.clientToken&&(l={...l,getStoredSessionId:()=>kc("sessionId"),setStoredSessionId:e=>{Z(t=>({...t,sessionId:e}))},clearStoredSessionId:l.clearStoredSessionId??(()=>Sc("sessionId")),getStoredConversationId:l.getStoredConversationId??(()=>kc("conversationId")),setStoredConversationId:l.setStoredConversationId??(e=>{Z(t=>({...t,conversationId:e}))}),clearStoredConversationId:l.clearStoredConversationId??(()=>Sc("conversationId"))});let Ic=()=>l.clientToken??null,Tc=e=>((e,t,r)=>{let n="",o="",a="",s=!1,i=!1,l=0,d=null,c=null,p=new Set,u=()=>{if(r||s)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return s=!0,null}},h=()=>{let e=u();if(!e)return d;try{return e.getItem(n)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let n={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(n)},g=e=>{i||(null===e.key||e.key===n)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await Kc(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await Kc(`${e}\0${t}`)}`}})(e,t);n=s.storageKey,o=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(o);if(!t)return null;let r=JSON.parse(t);return"number"==typeof r?.expiresAt&&"string"==typeof r?.ownerNonce?r:null}catch{return null}},v=e=>{let t=u();if(t)try{y()?.ownerNonce===e&&t.removeItem(o)}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(n,e);function n(){clearTimeout(r),w.delete(n),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===o)&&n()}w.add(n),window.addEventListener("storage",a)});return{ready:f,get:async()=>(await f,m(h(),"external"),d),async set(e){await f;let t=u();if(t)try{t.setItem(n,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(n)}catch{s=!0}m(null,"local")},revision:()=>l,subscribe:e=>(p.add(e),()=>{p.delete(e)}),async withFirstInitLock(e){await f;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):u()?(async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=Date.now()+15e3;for(;!i&&Date.now()<r;){let r=u();if(!r)break;let n=Date.now(),a=y();if(a&&a.expiresAt>n&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-n,500));else{try{r.setItem(o,JSON.stringify({ownerNonce:t,expiresAt:n+1e4}))}catch{s=!0;break}if(await 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:(n,o,a)=>n===e&&o===t&&a===r,destroy(){i=!0,p.clear(),typeof window<"u"&&window.removeEventListener("storage",g),c&&v(c);for(let e of[...w])e()}}})(e,Le(),!1===l.persistState),Ec=Ic(),Bc=Ec?Tc(Ec):null,Lc={...Bc?{visitorStore:Bc}:{},historyBootstrapReady:!0!==l.features?.history?.enabled||op()?V:Promise.all([V,Q]).then(()=>{}),getStoredMessageCursor:()=>kc("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?Sc("historyMessageCursor"):Z(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:()=>{let e=_.pendingDisplayProjections;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.conversationId&&Array.isArray(t.messageIds)?{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>"string"==typeof e)}:null},setPendingDisplayProjections:e=>{e?Z(t=>({...t,pendingDisplayProjections:e})):Sc("pendingDisplayProjections")},getStoredResumableHandle:Ac,setStoredResumableHandle:e=>{e?Z(t=>({...t,durableResume:e})):Sc("durableResume")},shouldResumeDurableConversation:()=>q&&null!==Ac(),...vc?{}:{getStoredConversationRevision:()=>kc("conversationRevision"),setStoredConversationRevision:e=>{null===e?Sc("conversationRevision"):Z(t=>({...t,conversationRevision:e}))}}};if(q){let t=l.onExecutionState,r=e.ownerDocument.defaultView,n=!1,o=()=>n=!0,a=()=>n=!1;r?.addEventListener("pagehide",o),r?.addEventListener("pageshow",a),Fa.push(()=>{r?.removeEventListener("pagehide",o),r?.removeEventListener("pageshow",a)}),l={...l,reconnectStream:l.reconnectStream??(e=>ts.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!n)&&Lc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Rc=null,Pc=e=>"user"===e.role||"approval"===e.variant||!0===e.agentMetadata?.awaitingLocalTool||vn(e),Nc=null,$c=null,Fc=null,Oc=null,jc=e=>{let t,r;!e.length&&l.future?.v5Defaults&&(os=null),Nc=e;for(let n=e.length-1;n>=0;--n){let o=e[n];if(!t&&"user"===o.role&&(t=o),!r&&"assistant"===o.role&&(r=o),t&&r)break}gd(vt,e,Ae),Et()?.updateInlineArtifactBlocks(vt,Eo.artifacts,{suppressTransition:ks}),Rc??=setInterval(()=>{let e=vt.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Rc),void(Rc=null);let t=Date.now();e.forEach(e=>{m?.updateActivityElapsed(e,t)})},100),dc(e),ys(e),Bl(!ks),(e=>{let t=new Map;e.forEach(e=>{let r=hi.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(z.emit("assistant:message",e),!Xs&&("anchor-top"!==br()||xr())&&Cl()&&(Qs+=1,vl(),Al(),Nr(1===Qs?"1 new message below.":`${Qs} new messages below.`))),"assistant"===e.role&&(r?.streaming||Is.has(e.id))&&!1===e.streaming&&z.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&z.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):z.emit("approval:requested",{approval:e.approval,message:e}))}),hi.clear(),t.forEach((e,t)=>{hi.set(t,e)}),Is.clear()})(e),Al(),Oe?.update(),0===e.length&&(Ul(),ei=!0,ti=!1,ri=null,ni=!1),!Ys||Xs?(Ys=!0,Zs=t?.id??null,ai=r?.id??null):t&&t.id!==Zs?(Zs=t.id,(e=>{let t=br();"follow"===t?(El(),Bl(!0)):"anchor-top"===t&&(ei=!1,ti=!0,ni=!1,ri=e,Yl(e))})(t.id)):r&&r.id!==ai&&"anchor-top"===br()&&(ti?ei=!1:(ei=!0,Ul(),El(),Bl(!0))),r&&(ai=r.id),(e=>{if("anchor-top"!==br()||!ti||ni||Dl())return;let t=null===Zs;for(let r of e)if(t){if(Kt(r)){if(r.id===ri||!Zl(r.id))return;return ri=r.id,void Yl(r.id)}}else r.id===Zs&&(t=!0)})(e);let n=xi.lastUserMessageId;t&&t.id!==n&&(xi.lastUserMessageId=t.id,z.emit("user:message",t)),xi.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!q)return ji(e);Oc=e,queueMicrotask(()=>{Oc===e&&(Oc=null,ji($c??e))})})(e),Bd(),z.emit("messages:changed",e)},_c=()=>{null!==Fc&&(cancelAnimationFrame(Fc),Fc=null);let e=$c;$c=null,e&&jc(e)},Qc=()=>{null!==Fc&&cancelAnimationFrame(Fc),Fc=null,$c=null};ts=new c(l,{onRunStarted:e=>z.emit("run:started",e),onRunFinished(e){_c(),l.turnActivity?.enabled&&gd(vt,ts.getMessages(),Ae),z.emit("run:finished",e)},onMessagesChanged(e){(e=>{if(0===e.length)return Qc(),void jc(e);let t=$c??Nc;ks&&t&&((e,t)=>{if(t.length<e.length)return!1;for(let r=0;r<t.length;r+=1){let n=t[r];if(n!==e[r]){if(Pc(n))return!1;"assistant"===n.role&&n.streaming&&Is.add(n.id)}}return!0})(t,e)?($c=e,null===Fc&&(Fc=requestAnimationFrame(()=>{Fc=null;let e=$c;$c=null,e&&jc(e)}))):(_c(),jc(e))})(e)},onStatusChanged(e){let t=l.statusIndicator??{};lt(Mt,(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),Al(),Oe?.update(),nt()},onStreamingChanged(e){e||(0===ts?.getMessages().length?Qc():_c()),ks=e,e?ws():l.future?.v5Defaults&&ys(),Qd(e),nt(),ts&&gd(vt,ts.getMessages(),Ae),e||(Bl(!0),(()=>{if(!Js||Js.spacerHeight<=0||Js.pending)return;let e=jl(Js.spacerHeight),t=Math.max(0,Math.round(ft.scrollTop)+ft.clientHeight-e+24);t<Js.spacerHeight&&(Ol(t),Al())})(),fs=!0,ts&&bs(ts.getMessages(),qn(l))),Al(),Oe?.update(),Nr(e?"Responding…":"Response complete."),Bd()},onVoiceStatusChanged(e){if(z.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!_t(l.voiceRecognition?.provider))return;let t=ts.getVoiceNotice();switch(t&&Jp(t,1e4),e){case"listening":if(!yi){let e=ts.getVoiceDisclosure();e&&(yi=!0,me()?(vi=St.placeholder,St.placeholder=e,Nr(e)):Jp(e,1e4))}Nu(),Lu();break;case"processing":Nu(),Ru();break;case"speaking":Nu(),Pu();break;default:"idle"===e&&ts.isBargeInActive()?(Nu(),Lu(),lr?.setAttribute("aria-label","End voice session")):(xi.active=!1,yi=!1,null!==vi&&(St.placeholder=vi,vi=null),Nu(),Bi("system"),Ei||Ri())}},onArtifactsState(e){Eo=e,0===e.artifacts.length&&(Do=!1),Et()?.updateInlineArtifactBlocks(vt,e.artifacts,{suppressTransition:ks}),Ba(),ji()},onHistoryStateChanged(e){tt(e)},onHistoryNotice(e){rt(e)},onHistoryScopeInvalidated(){Ep(),Gc?.clearConversationOpenPending()},onConversationExecutionState(e){z.emit("conversation:executionState",e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?z.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?z.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):z.emit("stream:resumed",{executionId:t,after:r})}},Lc),Oo.current=ts,Fa.push(()=>ts.cancel()),Fa.push(()=>{ts.destroy(),Bc?.destroy(),Bc=null});let Jc=null;if(ts.onReadAloudChange((e,t)=>{go=e,fo=t,wo();let r=e??Jc;e&&(Jc=e);let n=r?ts.getMessages().find(e=>e.id===r)??null:null;z.emit("message:read-aloud",{messageId:r,message:n,state:t,timestamp:Date.now()}),"idle"===t&&(Jc=null)}),I=!0,Ys=!0,!0===l.voiceRecognition?.enabled&&Ut(l))try{ts.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let Gc=null,Xc=null,Zc=!1,ep=ts.getHistoryState(),tp=()=>!0===l.features?.history?.enabled,rp=e=>{e&&(Lr.textContent="",Lr.textContent=e)},sp=()=>{M.forEach(e=>e()),M=[];let t=Gc,r=t?.railCollapseShortcut();t&&r&&M.push(A.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===l.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>Ye&&"rail"===Xe&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of l.layout?.header?.trailingActions??[])t.shortcut&&M.push(A.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 S)for(let t of e.shortcuts??[])M.push(A.register({...t,id:`${e.id}:${t.id}`}))};sp();let ip=null,wp=!1,xp=()=>{if(!zt)return;let e="conversation"===l.layout?.header?.titleSource,t=e&&ip?.trim()||null;zt.textContent=t??l.launcher?.title??"Chat Assistant";let r=zt.closest(".persona-combo-btn");if(!r)return;let n=!e||null!==ts.getActiveConversationId();r.setAttribute("data-persona-menu-locked",n?"false":"true"),r.setAttribute("aria-haspopup",n?"true":"false"),n||r.setAttribute("aria-expanded","false"),r.style.cursor=n?"pointer":"default";let o=r.querySelector("svg");o&&(o.style.display=n?"":"none")};xp(),gt.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=ts.getActiveConversationId();r&&("delete"===t?Pp(e=>e.requestDeleteConversation(r)):"star"===t&&ts.canUpdateConversations()&&Pp(e=>e.updateHistoryConversation(r,{starred:!wp})).catch(()=>{}))});let Cp=new Map,Sp=(e=ts.getActiveConversationId(),t=Gc?.historyOperationScope()??l.features?.history?.scope??(l.getIdentityProof?"verified-user":"browser"))=>JSON.stringify([t,e]),kp=null,Ap=0,Mp=()=>{let e=ft.getBoundingClientRect().top,t=ft.clientHeight>0?Array.from(vt.querySelectorAll("[data-message-id]")).find(t=>t.getBoundingClientRect().bottom>e):void 0;return{top:ft.scrollTop,anchorId:t?.dataset.messageId,anchorOffset:t?t.getBoundingClientRect().top-e:0,following:Os.isFollowing(),followFallback:ei,anchored:ti,anchoredId:ri,readerEngaged:ni,anchor:Js?{...Js}:null,unread:Qs}},Ip=e=>{ei=e.followFallback,ti=e.anchored,ri=e.anchoredId,ni=e.readerEngaged,Js=e.anchor?{...e.anchor,pending:0}:null,Ol(e.anchor?.spacerHeight??0),e.following?Os.resume():Os.pause(),Qs=e.unread;let t=Array.from(vt.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e.anchorId);Vs=!0,e.following&&yr()?ft.scrollTop=Qt(ft):t?ft.scrollTop+=t.getBoundingClientRect().top-ft.getBoundingClientRect().top-e.anchorOffset:ft.scrollTop=e.top,Vs=!1,qs=ft.scrollTop,ah=Qt(ft),vl(),$a(),Al()},Tp=(e=!1,t=!0)=>{let r=e?void 0:Cp.get(Sp());Qr?.clear(),Kr?.setPreviewsContainer(null),Kr=r?.attachments??(l.attachments?.enabled?tn():null),Kr?.updateConfig(Zr()),Kr?.remountPreviews(fr),rn(Kr?.getAttachments()??[]);let n=r?.draft,o=Qr?.getInlineInput();r?.document&&o?.setDocument?o.setDocument(r.document):o?o.setValueWithCaret(n?.text??"",(n?.text??"").length):St.value=n?.text??"",Qr?.restoreDraft(r?.mentions??[]),Gr(),Yr(),Jr.setSelectedModelId(n?l.composer?.models?.some(e=>e.id===n.selectedModelId)?n.selectedModelId:void 0:l.composer?.selectedModelId),dn?.repaint(),sn(ga(n?.activeModeIds??l.composer?.defaultActiveModeIds??[],nn())),un(n?.quote),fn(r?.pending),ou(),Ul(),hl(),Gc?.cancelConversationOpenTakeover(),Gd&&(Gd.hidden=!0),Yd=!1,vt.style.removeProperty("display"),r?Ip(r.reading):(El(),zl()||Hl()),t&&(_i=Ji()?ha({...Jr.getState(),contentSegments:jp()}):void 0),Gi.cancel(),t&&ji(),kp={key:Sp(),reading:r?.reading??Mp()}},Ep=(e,t=!0,r=!0)=>{for(let[t,r]of Cp)(void 0===e||JSON.parse(t)[1]===e)&&(r.attachments?.destroy({release:!0}),Kr===r.attachments&&(Kr=null),Cp.delete(t));(void 0===e||e===ts.getActiveConversationId())&&(++Ap,Ui=null,Vp?.abort(),Vp=null,gu(),Kr?.destroy({release:!0}),Kr=null,t&&Tp(!0,r),kp=null)};tt=e=>{ep=e,Gc?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),Qd(e.sendBlocked||ks),Gc?.syncEarlierMessagesPill()},rt=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(Ep(),Gc?.clearConversationOpenPending(),As.clear(),Ul(),El()),rp(e.message),Gc?.historySurface?.view.refresh()};let Bp={getBubbleClasses:ql,parseCombo:wi,formatCombo:Ci,ariaCombo:Si,usesSessionVoiceForConfig:Ut,applyBubbleGeometry:_l,resolveThemeDefaults:_s,composerStore:Jr,get attachmentManager(){return Kr},set attachmentManager(e){Kr=e},get composerConversationGeneration(){return Ap},set composerConversationGeneration(e){Ap=e},get submissionAbort(){return Vp},set submissionAbort(e){Vp=e},persistState:ji,applyMessageRowLayout:nd,SessionHistoryError:d,instanceId:o,discardConversationContinuity:Ep,clearPersistedDraft:ol,saveConversationContinuity:()=>{gu(),Tu("system"),Ut(l)&&ts.cleanupVoice(),++Ap,Vp?.abort(),Vp=null,Jr.setPreparing(!1),Fs(),el();let e=Jr.getState(),t=Sp();Cp.set(t,{draft:{text:e.text,mentionRefs:[...e.mentionRefs],contentSegments:jp(),quote:e.quote,selectedModelId:e.selectedModelId,activeModeIds:[...e.activeModeIds]},document:Qr?.getInlineInput()?.getDocument?.(),mentions:Qr?.captureDraft()??[],attachments:Kr,pending:e.pendingSubmission,reading:kp?.key===t?kp.reading:Mp()}),Gi.cancel()},restoreConversationContinuity:Tp,get pendingConversationReading(){return kp},set pendingConversationReading(e){kp=e},conversationStateKey:Sp,captureConversationReading:Mp,restoreConversationReading:Ip,get conversationPersistenceOwner(){return Ui},set conversationPersistenceOwner(e){Ui=e},setComposerDisabled:Qd,get actionManager(){return re},get activeConversationTitle(){return ip},announceHistory:rp,get applyRailChrome(){return et},set applyRailChrome(e){et=e},get artifactSplitRoot(){return Go},get body(){return ft},get config(){return l},get container(){return gt},get conversationOpenPendingEl(){return Gd},set conversationOpenPendingEl(e){Gd=e},get conversationOpenTakeover(){return Yd},set conversationOpenTakeover(e){Yd=e},currentKeyPrefix:Le,destroyCallbacks:Fa,eventBus:z,get footer(){return tr},get header(){return er},get historyChromeSync(){return nt},set historyChromeSync(e){nt=e},historyFeatureEnabled:tp,get historyInternals(){return Lc},set historyInternals(e){Lc=e},get historyPresentation(){return Xe},set historyPresentation(e){Xe=e},get historySessionState(){return ep},get historyVisible(){return Ye},set historyVisible(e){Ye=e},get isStreaming(){return ks},jumpToBottomInstant:Hl,get lastAppliedMessages(){return Nc},set lastAppliedMessages(e){Nc=e},get launcherEnabled(){return ne},get launcherSurfaceInstance(){return Xu},maybeFocusInput:Jd,messageCache:As,get messagesWrapper(){return vt},mount:e,get open(){return fe},panel:ut,panelElements:mt,panelSuggestions:Tr,panelSuggestionsFade:Er,get persistentMetadata(){return _},set persistentMetadata(e){_=e},plugins:S,get reapplyHistoryHostChrome(){return Ze},set reapplyHistoryHostChrome(e){Ze=e},repinAnchoredMessage:Xl,resetAnchorState:Ul,restoreScrollPosition:zl,resumeAutoScroll:El,runStorageMutation:qi,get session(){return ts},setActiveConversationSummary:e=>{wp=!0===e?.starred,(e=>{e!==ip&&(ip=e,xp())})(e&&e.title.trim()||null),xp()},storageAdapter:O,get suppressScrollSend(){return Xs},set suppressScrollSend(e){Xs=e},syncScrollToBottomButton:Al,scrollToBottomButton:Ar,updateWelcome:dc,getHistoryProviderFactory:ap,historyErrors:{HistoryClientError:n,HistoryProviderError:a},isDockedMountMode:il,renderLucideIcon:Ee,loadHistoryView:Yc,createHeaderIconButton:wl,attachTooltip:Qa},Lp=e=>(!Gc&&!Zc&&(Gc=e.createHistoryShell(Bp),Gc.railCollapseShortcut()&&sp()),Gc),Rp=()=>{if(Gc)return Promise.resolve(Gc);let e=op();return e?Promise.resolve(Lp(e)):(Xc??=np().then(Lp,e=>{throw Xc=null,e}),Xc)},Pp=e=>{let t=op(),r=Gc??(t?Lp(t):null);return r?e(r):Rp().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},Np=()=>{Gc?.syncHistoryPresentation()};Fa.push(()=>{Zc=!0}),tp()&&Rp().catch(()=>{}).finally(K),l.clientToken&&(!0===l.features?.history?.enabled||"mount"===l.sessionInit)&&ts.initClientSession().then(()=>{let e=Gc;if(e?.historyAvailable())return ts.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Gc?.syncEarlierMessagesPill()}).catch(e=>{l.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let $p=()=>ts.warmClientSession(),Wp=e=>{let t=l.sessionInit??"input",r=En?.input??St,n=e.target;r&&("input"===e.type?("input"===t||"focus"===t)&&n===r&&e.inputType&&r.value.trim():"focus"===t&&("keyup"===e.type?n===r&&"Tab"===e.key:(En?.form??At)?.contains(n)))&&$p()},Hp=["input","pointerdown","keyup"];Hp.forEach(t=>e.addEventListener(t,Wp));let Dp,Fp,zp=()=>{let e=Fp;Fp=void 0;try{"function"==typeof e&&e()}catch{}},Op=()=>{let t=l.clientToken&&"function"==typeof l.sessionInit?l.sessionInit:void 0;if(t!==Dp){zp(),Dp=t;try{Fp=t?.({warm:$p,mount:e})}catch{}}};Op(),Fa.push(()=>{Hp.forEach(t=>e.removeEventListener(t,Wp)),zp()}),(Te||l.onSSEEvent)&&ts.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ke(e,t)});let qp=()=>{let e=l.resume??(q?Lc.getStoredResumableHandle?.():null);e&&"function"==typeof l.reconnectStream&&ts.resumeFromHandle(e)};U?U.then(e=>{if(e){if(e.metadata&&(_=gp(e.metadata),re.syncFromMetadata()),e.messages?.length){Xs=!0;try{ts.hydrateMessages(e.messages)}finally{Xs=!1}ud()}e.artifacts?.length&&ts.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),tl(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{ec=!0,x(),qp()}):(tl(C),qp());let jp=()=>{let e=St.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},_p=!1,Up=0,Vp=null,Kp=()=>{St.value="",St.style.height="auto",Gr(),ou()},Qp=null;function Jp(e,t=4e3){Nr(e),!me()&&Mt&&(Mt.hasAttribute(pp)||(Mt.setAttribute(up,""),Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.textContent=e,ur(Mt,l.statusIndicator??{},"idle"),Qp&&clearTimeout(Qp),Qp=setTimeout(()=>{if(Qp=null,Mt?.hasAttribute(up)&&(Mt.removeAttribute(up),Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),I)){let e=ts.getStatus();lt(Mt,it(e),l.statusIndicator??{},e)}},t)))}let Gp=(e={})=>{if(mu()||Gd)return;let t=Ap,r=(e.overrideText??St?.value??"").trim();return e.resolveInlineCommand&&r?(Qr?.takeInlineCommand(r)??Promise.resolve(null)).then(n=>{if(t===Ap)return Yp(e,r,n)}):Yp(e,r,null)},Yp=(e,t,r)=>{if("action"===r?.kind)return Kp(),Qr?.clear(),void Yr();let n="server"===r?.kind?r.mentions:null,o="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:o,hasAttachments:(Kr?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:Kr?.isReady()??!0,hasMentions:Qr?.hasMentions()??!1,hasServerMentions:!!n,inputDisabled:Wd(),sendDisabled:Od()}))return;let s=ts.isStreaming()?mn():"block";if("defer-one"===s&&!e.pending)return Jr.getState().pendingSubmission?void Jp("One message is already queued. Edit or remove it first."):void function(e){let t=Jr.getState(),r=Kr?.hasAttachments()??!1,n=r?[...Kr.getContentParts()]:[];r&&e.sendText&&n.push(bo(e.sendText)),fn(Ma({text:e.sendText,contentParts:n.length?n:void 0,mentionRefs:[...Qr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:jp(),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&&Kp(),r&&Kr.clearAttachments(),Qr?.clear(),Yr(),t.quote&&un(void 0),ol(),Qn.release(),Yn(),Nr("Message queued. It sends when the response finishes.")}({intent:e,sendText:o,serverMentions:n});let i={text:o,mentionRefs:[...Qr?.getMentionRefs()??[],...n?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:jp(),options:{...Jr.getState().selectedModelId&&{selectedModelId:Jr.getState().selectedModelId},...Jr.getState().activeModeIds.length>0&&{activeModeIds:[...Jr.getState().activeModeIds]},...Jr.getState().quote&&{quote:{...Jr.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(!Kr?.hasAttachments())return;let e=[...Kr.getContentParts()];return i.text&&e.push(bo(i.text)),e};i.contentParts=d();let c=()=>{Fs(),me()&&(fe||(l.launcher?.composerBar?.expandOnSubmit??1)&&Nd(!0,"auto"));let t=Qr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,n]=await Promise.allSettled([e.finalize(),t.finalize()]),o=[];return"fulfilled"===r.status?o.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===n.status?o.push(n.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",n.reason),(e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:vp(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}))(o)}}:e:t)(t,n),o=d();!1!==e.consumeDraft&&Kp();let a={selectedModelId:i.options.selectedModelId,activeModeIds:i.options.activeModeIds},c="interrupt"===s;c&&ts.cancel(),ts.sendMessage(i.text,{contentParts:o,mentions:r??void 0,contentSegments:i.contentSegments,viaVoice:i.viaVoice,composerOptions:a,...i.options.quote&&{quote:i.options.quote},...c&&{interrupt:!0}}),Kr?.hasAttachments()&&Kr.clearAttachments(),t&&Qr?.clear(),Yr();let p=Jr.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&&sn(u),Jr.getState().quote&&un(void 0),ol(),Qn.release(),Yn()},p=l.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;Vp=u;let h=Ap,m=e=>{u.signal.aborted||h!==Ap||(Vp===u&&(Vp=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 Jr.setPreparing(!0),g.then(m).finally(()=>{h===Ap&&Jr.setPreparing(!1)});m(g)};xo={regenerate:function(e){if(ts.isStreaming())return;let t=Bo(ts.getMessages(),e);t&&(Fs(),ts.resubmitFrom(t,{reason:"retry"})&&Xl())},edit:function(e){if(!0!==l.messageActions?.showEdit)return;let t=ts.getMessages().find(t=>t.id===e);t&&Lo(t)&&Hs!==e&&(Fs(),Hs=e,Ds=ua({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=Ds;Hs=null,Ds=null,r?.destroy(),As.delete(e),ts.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?Xl():gd(vt,ts.getMessages(),Ae)}(e,t),onCancel:()=>Fs()}),As.delete(e),gd(vt,ts.getMessages(),Ae),Ds.focus())},quote:e=>{let t=ts.getMessages().find(t=>t.id===e)?.content?.trim();t&&(un({text:t,messageId:e}),St?.focus())}};let Xp=async e=>{if(mu())return void(l.voiceRecognition?.dictation?.showSend&&!Od()&&fu(!0));if(_p)return;_p=!0;let t=++Up;try{await Gp({resolveInlineCommand:!0,...e})}finally{t===Up&&(_p=!1)}};function Zp(e){Od()||(Kp(),eu(e,{consumeDraft:!1}))}let eu=(e,t)=>{if(_p)return;_p=!0;let r=++Up,n=()=>{r===Up&&(_p=!1)};try{let r=Gp({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},tu=e=>{e.preventDefault(),ts.isStreaming()?(ts.cancel(),De?.reset(),Oe?.update()):_p||Xp()},ru={...Ti},nu=!1,ou=()=>{ru={...Ti}},au=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(gt)&&(Vp?(Vp.abort(),Vp=null,e.preventDefault(),e.stopImmediatePropagation()):ts.isStreaming()&&(ts.cancel(),De?.reset(),Oe?.update(),ou(),e.preventDefault(),e.stopImmediatePropagation()))},su=null,iu=null,lu=!1,du=null,cu=null,pu=0,uu=Object.freeze({phase:"idle",recordingId:0,transcript:"",interimTranscript:"",error:null,audioLevel:null}),hu=()=>!!l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&xu(),mu=()=>lu||["recording","processing"].includes(su?.getState().phase??"idle"),gu=()=>{if(++pu,lu=!1,cu=null,du){du=null,iu?.element.remove(),iu=null;let{audioLevel:e,...t}=uu;return z.emit("dictation:state",{...t,instanceId:o,timestamp:Date.now()}),!0}return su?.cancel()??!1},fu=(e=!1)=>lu?(cu=e||!0===cu,!0):su?.finish(e)||e&&su?.send()||!1,bu=()=>{if(Wd()||ts.isStreaming()||mu()||zd())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&&!Mu()||"custom"===t.type&&!t.custom)return!1;!fe&&ge()&&Nd(!0,"system"),du&&gu();let r={text:St.value,logicalEnd:Qr?.getInlineInput()?.getLogicalText().length??null,readOnly:St.readOnly,contentEditable:St.getAttribute("contenteditable")};lu=!0,cu=null;let n=++pu;return Je().then(a=>{n===pu&&(lu=!1,su??=a.createDictationSession({instanceId:o,getTextarea:()=>St,getFooter:()=>tr,getConfig:()=>l,plugins:S,getInlineInput:()=>Qr?.getInlineInput(),isInputDisabled:Wd,isSendBlocked:Od,syncText:Gr,onSend:()=>{Xp({viaVoice:!0})},rendererDeps:{renderLucideIcon:Ee,attachTooltip:Qa},onState:(e,t)=>{let{audioLevel:r,...n}=e;z.emit("dictation:state",{...n,instanceId:o,timestamp:Date.now()}),xi.active="recording"===e.phase,Cu(t?"recording"===e.phase?"recording":"processing":"idle"),Bi("system")}}),ts.stopSpeaking(),su.start(t,{autoSend:!xu(),pauseDuration:e?.pauseDuration},r),null!==cu&&(su.finish(cu),cu=null))}).catch(e=>{if(n!==pu)return;lu=!1;let t=e instanceof Error?e.message:"Unable to load dictation.";du=Object.freeze({...uu,recordingId:n,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",()=>{gu()}),r.append(a),iu={element:r},tr.append(r);let{audioLevel:s,...i}=du;z.emit("dictation:state",{...i,instanceId:o,timestamp:Date.now()})}),!0};Fa.push(()=>{++pu,su?.destroy(),iu?.destroy?.(),iu?.element.remove()}),l.voiceRecognition?.dictation&&Je().catch(()=>{});let yu,vu=null,wu=!1,xu=()=>"review"===l.voiceRecognition?.completionBehavior;function Cu(e){lr&&xs(lr,l,e,ts.getVoiceInterruptionMode()),tr?.setAttribute("data-persona-voice-state",e),"recording"===e?function(){ku=!0;let e=e=>{ku&&(Su??=e.createVoiceLevelIndicator({targets:()=>[dr??lr?.parentElement,tr].filter(e=>!!e),sample:()=>{let e=su?.getState();return"recording"===e?.phase?{level:e.audioLevel,fallback:!1}:{level:I?ts.getVoiceLevel():null,fallback:!0}}}),Su.start())},t=Ge();t?e(t):Je().then(e,()=>{})}():Au()}let Su,ku=!1;function Au(){ku=!1,Su?.stop()}let Mu=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Iu=(e="user")=>{if(wu||ts.isStreaming())return;let t=Mu();if(!t)return;vu=new t;let r=vu,n=l.voiceRecognition??{},o=n.pauseDuration??2e3;vu.continuous=n.provider?.browser?.continuous??!0,vu.interimResults=!0,vu.lang=n.provider?.browser?.language??"en-US";let a,s=St.value,i=(e,t)=>{let n=n=>{vu===r&&wu&&(a??=n.createBrowserRecognitionHandlers({textarea:St,initialText:s,pauseDuration:o,isActive:()=>vu===r&&wu,syncText:Gr,stop:Tu,review:xu,submit:()=>{Xp({viaVoice:!0})}}),yu=()=>a?.dispose(),a[e](t))},i=Ge();i?n(i):Je().then(n,()=>{vu===r&&Tu("system")})};r.onresult=e=>i("result",e),r.onerror=e=>i("error",e),r.onend=e=>i("end",e);try{vu.start(),wu=!0,xi.active=!0,"system"!==e&&(xi.manuallyDeactivated=!1),Bi(e),Ri(),Yn(),lr&&(lr.classList.add("persona-voice-recording"),Cu("recording"),lr.setAttribute("aria-label","Stop voice recognition"))}catch{Tu("system")}},Tu=(e="user")=>{if(wu){if(wu=!1,yu?.(),yu=void 0,vu){try{vu.stop()}catch{}vu=null}xi.active=!1,Bi(e),Ei||Ri(),Yn(),lr&&(lr.classList.remove("persona-voice-recording"),Cu("idle"),lr.setAttribute("aria-label",l.voiceRecognition?.tooltipText??"Start voice recognition"))}},Eu=null,Bu=e=>{let t=t=>{Eu??=t.createMicStateStyles({mic:()=>lr,config:()=>l,session:()=>ts,setMicState:Cu}),e(Eu)},r=jt();r?t(r):qt().then(t,()=>{})},Lu=()=>Bu(e=>e.recording()),Ru=()=>Bu(e=>e.processing()),Pu=()=>Bu(e=>e.speaking()),Nu=()=>Bu(e=>e.reset()),$u=()=>{if(!Wd())if(hu())"recording"===su?.getState().phase?su.finish():mu()||bu();else if(_t(l.voiceRecognition?.provider)){let e=ts.getVoiceStatus(),t=ts.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;if("cancel"===t&&("processing"===e||"speaking"===e))return void ts.stopVoicePlayback();if(ts.isBargeInActive())return ts.stopVoicePlayback(),void ts.deactivateBargeIn().then(()=>{xi.active=!1,xi.manuallyDeactivated=!0,Ri(),Bi("user"),Nu()});ts.toggleVoice().then(()=>{xi.active=Ai(),xi.manuallyDeactivated=!xi.active,Ri(),Bi("user"),xi.active?Lu():Nu()})}else if(wu){let e=St.value.trim();xi.manuallyDeactivated=!0,Ri(),Tu("user"),e&&!xu()&&Xp()}else xi.manuallyDeactivated=!1,Ri(),Iu("user")};bn=$u;let Wu=()=>ts.prewarmVoice(),Hu=()=>{let e=l.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!l.clientToken&&"hover"))},Du=e=>{"hover"===Hu()&&lr?.contains(e.target)&&Wu()},Fu=["pointerover","pointerdown","focusin"];Fu.forEach(t=>e.addEventListener(t,Du));let zu,Ou,qu=null,ju=()=>{let e=Ou;Ou=void 0;try{"function"==typeof e&&e()}catch{}},_u=()=>{let t=Hu(),r="function"==typeof t&&lr?t:void 0,n=r?lr:null;if((r!==zu||n!==qu)&&(ju(),zu=r,qu=n,r&&n))try{Ou=r({warm:Wu,micButton:n,mount:e})}catch{}};_u(),Fa.push(()=>{Fu.forEach(t=>e.removeEventListener(t,Du)),ju()}),lr&&Fa.push(()=>{_t(l.voiceRecognition?.provider)?(ts.isVoiceActive()&&ts.toggleVoice(),Nu()):Tu("system")});let Uu=z.on("assistant:complete",()=>{let e=Jr.getState().pendingSubmission,t=Ap,r=be;e&&setTimeout(()=>{ve(r)&&!ts.isStreaming()&&t===Ap&&Jr.getState().pendingSubmission===e&&function(){let e=Jr.getState().pendingSubmission;e&&(fn(void 0),eu(e.text,{consumeDraft:!1,pending:e}))}()},0)});Fa.push(Uu);let Vu=z.on("assistant:complete",()=>{if(!ki||xi.active||xi.manuallyDeactivated||"assistant"===ki&&!xi.lastUserMessageWasVoice)return;let e=Ap,t=be;setTimeout(()=>{ve(t)&&e===Ap&&!xi.active&&!xi.manuallyDeactivated&&(_t(l.voiceRecognition?.provider)?ts.toggleVoice().then(()=>{ve(t)&&e===Ap&&(xi.active=ts.isVoiceActive(),Bi("auto"),ts.isVoiceActive()&&Lu())}):Iu("auto"))},600)});Fa.push(Vu);let Ku=!1,Qu=e=>{e.persisted&&!Ku&&(Ku=!0,Ei=!0,we(),Ap++,Up++,_p=!1,Vp?.abort(),Vp=null,Jr.setPreparing(!1),gu(),Tu("system"),ts.cancel(),ts.stopSpeaking(),ts.cleanupVoice(),De?.reset(),Oe?.update())},Ju=e=>{e.persisted&&Ku&&(Ku=!1,Ei=!1,!0===l.voiceRecognition?.enabled&&Ut(l)&&ts.setupVoice())};window.addEventListener("pagehide",Qu),window.addEventListener("pageshow",Ju),Fa.push(()=>{window.removeEventListener("pagehide",Qu),window.removeEventListener("pageshow",Ju)});let Gu=z.on("action:resubmit",()=>{xe()});Fa.push(Gu);let Yu=()=>{Nd(!fe,"user")},Xu=null,Zu=null;if(ne&&!me()){let{instance:e,element:t}=kd({config:l,plugins:S,onToggle:Yu});Xu=e,e||(Zu=t)}Xu?e.appendChild(Xu.element):Zu&&e.appendChild(Zu),Ld(),ys(),yc(),bc(),Qd(ts.isStreaming()),zl()||("follow"===br()?Bl(!0):Hl()),(()=>{if(!1===l.voiceRecognition?.enabled||l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&"review"===l.voiceRecognition.completionBehavior)return;let e=gp(_.voiceState),t=!!e.active,r=Number(e.timestamp??0);if(xi.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4){let e=be;setTimeout(()=>{ve(e)&&(xi.active||(xi.manuallyDeactivated=!1,_t(l.voiceRecognition?.provider)?ts.toggleVoice().then(()=>{ve(e)&&(xi.active=Ai(),Bi("restore"),xi.active?Lu():(Ri(),Jp("Tap the mic to resume your voice call",1e4)))}):Iu("restore")))},_t(l.voiceRecognition?.provider)?0:1e3)}})(),se&&(!ne||me()?setTimeout(()=>Jd(),0):fe&&setTimeout(()=>Jd(),200));let eh=null,th=()=>{eh&&(eh.disconnect(),eh.observe(tr),eh.observe(gt),eh.observe(It),eh.observe(Tr))},rh=$r(),nh=()=>{if(me())return qr(),void Ld();let t=il(l),r=l.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,o=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640,s=n.innerWidth<=a,i=o&&s&≠try{if(i)return Ao(),void(Mo=Ea());let e=!1;ue&&(ue=!1,Ao(),e=!0);let n=Ea();if(!e&&n!==Mo&&(Ao(),e=!0),Mo=n,e&&Xo(),!ne&&!t)return ut.style.height="",void(r||(pt.style.width=md(l),ut.style.width="100%",ut.style.maxWidth="100%"));if(!r&&!t){let e=hd(l);ut.style.width=e.width,ut.style.maxWidth=e.maxWidth}xa(),Da()}finally{qr(),Vr();let t=$r();if(t!==rh&&(rh=t,dc(),ys()),Ld(),fe&&ne){let t=(e.ownerDocument.defaultView??window).innerWidth<=(l.launcher?.mobileBreakpoint??640),r=l.launcher?.sidebarMode??!1,n=l.launcher?.mobileFullscreen??!0,o=il(l)&&n&&t,a=r||n&&t&&ne||o;if(a&&!qa){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!za&&(za=nl(r,l.launcher?.zIndex??1e5)),qa=sl(e.ownerDocument)}else a||(za?.(),za=null,qa?.(),qa=null)}}};nh();let oh=e.ownerDocument.defaultView??window;if(oh.addEventListener("resize",nh),Fa.push(()=>oh.removeEventListener("resize",nh)),typeof ResizeObserver<"u"){eh=new ResizeObserver(()=>{Vr(),Al()}),th(),Fa.push(()=>{eh?.disconnect(),eh=null});let e=new ResizeObserver(()=>{Np()});e.observe(gt),Fa.push(()=>e.disconnect())}oh.addEventListener("resize",Np),Fa.push(()=>oh.removeEventListener("resize",Np)),qs=ft.scrollTop;let ah=Qt(ft),sh=()=>{$a();let e=ft.scrollTop,t=Qt(ft),r=t<ah;if(ah=t,Rl.interrupted||!yr())return qs=e,void Al();let{action:n,nextLastScrollTop:o}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-n;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&o&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!o?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Os.isFollowing(),currentScrollTop:e,lastScrollTop:qs,nearBottom:Jt(ft,24),userScrollThreshold:4,isAutoScrolling:Rl.active||Vs||Ks||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});qs=o,"resume"!==n||Dl()?"pause"===n?Ml():Al():El()};if(ft.addEventListener("scroll",sh,{passive:!0}),Fa.push(()=>ft.removeEventListener("scroll",sh)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(yr()){if(Al(),!Os.isFollowing()||Jt(ft,1))return;Bl(!ks)}else{if(Js&&Js.initialSpacerHeight>0&&!Js.pending){let e=ft.scrollHeight-Js.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:Js.initialSpacerHeight,contentHeightAtAnchor:Js.contentHeightAtAnchor,currentContentHeight:e});t!==Js.spacerHeight&&Ol(t)}Al()}})(),$a(),Hr(vt)});e.observe(vt),e.observe(ft),Fa.push(()=>e.disconnect())}let ih=()=>{yr()&&Os.isFollowing()&&Dl()&&Ml()},lh=ft.ownerDocument;lh.addEventListener("selectionchange",ih),Fa.push(()=>{lh.removeEventListener("selectionchange",ih)});let dh=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),ch=e=>{dh.has(e.key)&&(oi(),wr()&&yr()&&Os.isFollowing()&&Ml())},ph=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(oi(),wr()&&yr()&&Os.isFollowing()&&Ml())};ft.addEventListener("keydown",ch),ft.addEventListener("focusin",ph),Fa.push(()=>{ft.removeEventListener("keydown",ch),ft.removeEventListener("focusin",ph)});let uh=e=>{if(Rl.interruptedBy(e))return void oi();if(0!==e.deltaY&&oi(),!yr())return;let t=function(e){let{following:t,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return t&&r<0?"pause":!t&&o&&r>0&&n?"resume":"none"}({following:Os.isFollowing(),deltaY:e.deltaY,nearBottom:Jt(ft,24),resumeWhenNearBottom:!0});"pause"===t?Ml():"resume"===t&&!Dl()&&El()};ft.addEventListener("wheel",uh,{passive:!0}),ft.addEventListener("touchmove",oi,{passive:!0}),ft.addEventListener("pointerdown",oi,{passive:!0}),Fa.push(()=>{ft.removeEventListener("touchmove",oi),ft.removeEventListener("pointerdown",oi)}),Fa.push(()=>ft.removeEventListener("wheel",uh)),Ar.addEventListener("click",()=>{Ul(),hl(),Os.pause(),Rl.start(l),Al()}),Fa.push(()=>Rl.destroy()),Fa.push(()=>kr.destroy()),Fa.push(()=>{hl(),Ul()});let hh=()=>{Dt&&(ns&&=(Dt.removeEventListener("click",ns),null),ge()?(Dt.style.display="",ns=()=>{Nd(!1,"user")},Dt.addEventListener("click",ns)):Dt.style.display="none")};hh(),(()=>{let{clearChatButton:e}=mt;e&&e.addEventListener("click",()=>{let e=Gc;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{l.debug&&console.warn("[AgentWidget] New conversation failed:",e)});ts.clearMessages(),l.layout?.topFade&&(ft.scrollTop=0),ft.removeAttribute("data-persona-top-fade"),As.clear(),El(),Nn(mt.composerOverlay);try{localStorage.removeItem(cp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==cp)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:o,timestamp:(new Date).toISOString()}});window.dispatchEvent(t),ol(),O?.clear&&qi(()=>O.clear(),"[AgentWidget] Failed to clear storage adapter:"),_={},re.syncFromMetadata(),Ep(ts.getActiveConversationId(),!0,!1),Kp(),ol(),fn(void 0),un(void 0),Fs(),He?.clear(),De?.reset(),Oe?.update()})})();let mh=[["keydown",e=>{if(St&&!Wd()&&(e.isComposing||!Qr?.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===St.selectionStart&&0===St.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:n,atStart:o,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!o)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:n}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let e=a.index+1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}({direction:"ArrowUp"===e.key?"up":"down",history:ts.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:St.value,atStart:t,state:ru});if(ru=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!St)return;nu=!0,St.value=e,St.dispatchEvent(new Event("input",{bubbles:!0})),nu=!1;let t=St.value.length;St.setSelectionRange(t,t)})(r.value))}if(Ca(e,{submitKey:l.composer?.submitKey,insertNewlineOnTouchEnter:l.composer?.insertNewlineOnTouchEnter,coarsePointer:wa(St)}))if(ts.isStreaming()){if(e.preventDefault(),"block"===mn()||_p||Od())return;ou(),Xp()}else _p||Od()?e.preventDefault():(ou(),e.preventDefault(),kt.click())}}],["input",e=>{nu||(ws(),e.isComposing||Qr?.handleInput(e.inputType??void 0),ou())}],["input",Gr],["input",Yr],["keyup",Yr],["paste",async e=>{if(!0!==l.attachments?.enabled||!Kr||Wd())return;let t=function(e){if(!e)return[];let t=[],r=Array.from(e.items??[]);for(let e of r){if("file"!==e.kind||!e.type.startsWith("image/"))continue;let r=e.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let n=hp[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${n}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let r of Array.from(e.files??[]))r.type.startsWith("image/")&&t.push(r);return t}(e.clipboardData);0!==t.length&&(e.preventDefault(),await Kr.handleFiles(t))}],["focus",()=>Qr?.prefetch()]],gh=e=>{if(e)for(let[t,r]of mh)En?.addListener(e,t,r)},fh=()=>{En&&(En.addListener(En.form,"submit",tu),En.addListener(En.footer,"click",Yr),gh(St),lr&&En.addListener(lr,"click",$u),_u())};fh();let bh=()=>{Qr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of mh)En?.removeListener(e,t,r)})(t),St=e,En&&(En.input=e),gh(e),Bn(),Kd(),Gr(),su?.refresh()})};bh();let yh=!1;function vh(){if(!yh){yh=!0;try{oo.detach(["footer-top","footer-bottom","composer-start","composer-end","composer-before-send"]);let e=St?.value??"",t=tr.ownerDocument??document,r=!!St&&t.activeElement===St;Au(),En?.destroy(),En=null,Qr?.destroy(),Qr=null;let n=null,o=()=>(n=me()?Wl({config:l}):$l({config:l}),n.footer),a=In(o)??o();ct.replaceComposer(a),tr=ct.composer.footer,!1===l.layout?.showFooter&&(tr.style.display="none");let s=null!==n&&a===n.footer;Mn=!s,ir=s?n.setSendButtonMode:()=>{},An(tr),Ln(tr),$n(),Wn(),Hn(),bh(),Un(),Vn(),Kn(),fh();let i=es.indexOf(Ga);if(Ga.destroy(),Ga=gl(Ct),i>=0&&(es[i]=Ga),oo.remount(),St&&(St.value=e),Gr(),Yr(),yc(),ys(),Qd(ts.isStreaming()),"transient"===l.statusIndicator?.mode&&!me()){let e=ts.getStatus();lt(Mt,it(e),l.statusIndicator,e)}xi.active&&Cu("recording"),su?.refresh(),Ao(),th(),qr(),Yn(),Vd(),r&&St?.focus()}finally{yh=!1}}}let wh=e.ownerDocument??document;wh.addEventListener("keydown",au,!0);let xh=()=>{el()},Ch=()=>{"hidden"===wh.visibilityState&&el()};typeof window<"u"&&(window.addEventListener("pagehide",xh),wh.addEventListener("visibilitychange",Ch),Fa.push(()=>{window.removeEventListener("pagehide",xh),wh.removeEventListener("visibilitychange",Ch)}));let Sh="persona-attachment-drop-active",kh=0,Ah=()=>{kh=0,gt.classList.remove(Sh)},Mh=()=>!0===l.attachments?.enabled&&null!==Kr&&!Wd(),Ih=e=>{mp(e.dataTransfer)&&Mh()&&(kh++,1===kh&>.classList.add(Sh))},Th=e=>{mp(e.dataTransfer)&&Mh()&&(kh--,kh<=0&&Ah())},Eh=e=>{mp(e.dataTransfer)&&Mh()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},Bh=e=>{if(!mp(e.dataTransfer)||!Mh())return;e.preventDefault(),e.stopPropagation(),Ah();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&Kr.handleFiles(t)};gt.addEventListener("dragenter",Ih,!0),gt.addEventListener("dragleave",Th,!0),e.addEventListener("dragover",Eh,!0),e.addEventListener("drop",Bh,!0);let Lh=e.ownerDocument,Rh=e=>{Mh()&&e.preventDefault()},Ph=e=>{Mh()&&e.preventDefault()};Lh.addEventListener("dragover",Rh),Lh.addEventListener("drop",Ph),Fa.push(()=>{En?.destroy(),En=null,Au(),_n=!0,Fn?.destroy(),Fn=null,cn?.destroy(),cn=null,pn?.destroy(),pn=null,gn?.destroy(),gn=null,dn=null,el(),Gi.destroy(),Qp&&clearTimeout(Qp),Fs(),Vp?.abort(),Vp=null,Gc?.clearConversationOpenPending(),Ep(void 0,!1),Kr?.destroy(),Kr=null,Jr.destroy(),wh.removeEventListener("keydown",au,!0),Qr?.destroy()}),Fa.push(()=>{gt.removeEventListener("dragenter",Ih,!0),gt.removeEventListener("dragleave",Th,!0),e.removeEventListener("dragover",Eh,!0),e.removeEventListener("drop",Bh,!0),Lh.removeEventListener("dragover",Rh),Lh.removeEventListener("drop",Ph),Ah()}),Fa.push(()=>{ts.cancel()}),Xu?Fa.push(()=>{Xu?.destroy()}):Zu&&Fa.push(()=>{Zu?.remove()}),r?.registerHostMove?.(t=>{let r=ft.scrollTop,n=yr()&&Os.isFollowing(),o=ft.getBoundingClientRect().top,a=!n&&ft.clientHeight>0?Array.from(vt.querySelectorAll("[data-message-id]")).find(e=>e.getBoundingClientRect().bottom>o):void 0,s=a?a.getBoundingClientRect().top-o:0;hl(),t(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),nh(),et(),n?ft.scrollTop=Qt(ft):a?ft.scrollTop+=a.getBoundingClientRect().top-ft.getBoundingClientRect().top-s:ft.scrollTop=r,!n&&!ni&&Xl(),qs=ft.scrollTop,ah=Qt(ft),$a(),Al(),e.dispatchEvent(new Event("persona:internal:host-moved"))});let Nh=e=>{!fe&&ge()&&Nd(!0,"system"),vt.querySelector(".persona-feedback-container")?.remove();let t=e();vt.appendChild(t),t.scrollIntoView({behavior:"smooth",block:"end"})},$h=!1,Wh=[],Hh=!1,Dh=()=>{let e=Wh;Wh=[],Hh=!0;try{for(let t of e)Fh.update(t)}finally{Hh=!1}},Fh={get ready(){return u.ready},get instanceId(){return o},update(t){if(!Hh){Wh.push(t);let e=Wh.reduce(Mc,{...l,features:w}),r=Vt(mc(e));if(r.length)return void u.prepare(r,Dh,$h);if(Wh.length>1)return void u.prepare([],Dh,$h);Wh=[]}r?.diagnostics||Hc(h,t);let n=t.voiceRecognition;n&&(!1===n.enabled||n.dictation?.provider&&n.dictation.provider!==l.voiceRecognition?.dictation?.provider||n.provider?.custom&&n.provider.custom!==l.voiceRecognition?.provider?.custom)&&gu();let o=!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=l.features?.streamAnimation?.type,b=!0===l.features?.history?.enabled,y=l.features?.history?.provider,x=l.getIdentityProof,C=l.clientToken,k=l.contextMentions;l=Mc({...l,features:w},t),w=l.features,l=mc(l),v(),Ao(),Ba(),l.colorScheme!==i&&Ua();let A=Cc.getForInstance(l.plugins);S.length=0,S.push(...A),sp(),ne=l.launcher?.enabled??!0,ae=l.launcher?.autoExpand??!1,Me=l.features?.showReasoning??!0,Ie=l.features?.showToolCalls??!0,Rl.cancel();let M=br();Be=l.features?.scrollBehavior??{},M!==br()&&(Ul(),El()),ci(),Al();let I=Te;if(Te=l.features?.showEventStreamToggle??!1,Te&&!I){if(He||(Qe(),ts.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ke(e,t)})),!kn&&er){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:"");kn=st("button",t),kn.style.width="28px",kn.style.height="28px",kn.style.color=kl.actionIconColor,kn.type="button",kn.setAttribute("aria-label","Event Stream"),kn.title="Event Stream";let r=oe(de,"18px","currentColor",1.5);r&&kn.appendChild(r);let n=mt.clearChatButtonWrapper,o=mt.closeButtonWrapper,a=n||o;a&&a.parentNode===er?er.insertBefore(kn,a):er.appendChild(kn),kn.addEventListener("click",()=>{qe?Sn():Cn()})}}else!Te&&I&&(Sn(),Oe?.destroy(),Oe=null,kn&&=(kn.remove(),null),He?.clear(),Pe?.destroy(),He=null,Pe=null,De?.reset(),De=null,Fe=null);if(!1===l.launcher?.enabled&&Xu&&(Xu.destroy(),Xu=null),!1===l.launcher?.enabled&&Zu&&(Zu.remove(),Zu=null),!1!==l.launcher?.enabled&&!Xu&&!Zu){let{instance:t,element:r}=kd({config:l,plugins:S,onToggle:Yu});Xu=t,t||(Zu=r),e.appendChild(r)}Xu&&Xu.update(l),xp(),Ot&&void 0!==l.launcher?.subtitle&&(Ot.textContent=l.launcher.subtitle);let T=l.layout?.header;if(T?.layout!==ce&&er){let e=T?Pl(l,T,{showClose:ge(),onClose:()=>Nd(!1,"user")}):Il({config:l,showClose:ge(),onClose:()=>Nd(!1,"user")});ct.replaceHeader(e),er=ct.header.element,Ft=ct.header.iconHolder,zt=ct.header.headerTitle,Ot=ct.header.headerSubtitle,Dt=ct.header.closeButton,ce=T?.layout,xp()}else if(T){if(Ft&&(Ft.style.display=!1===T.showIcon?"none":""),zt&&(zt.style.display=!1===T.showTitle?"none":""),Ot&&(Ot.style.display=!1===T.showSubtitle?"none":""),Dt){let e=ge()&&!1!==T.showCloseButton;Dt.style.display=e?"":"none"}if(mt.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){mt.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=mt;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=ss(l);er&&(er.style.display=E?"":"none");let B=!1!==l.layout?.showFooter;tr&&(tr.style.display=B?"":"none"),qr(),Al(),ne===le?ae!==ie&&Nd(ae,"auto"):ne?Nd(ae,"auto"):(fe=!0,Ld()),ie=ae,le=ne,nh(),hh();let L=JSON.stringify(l.messageActions)!==JSON.stringify(a),R=JSON.stringify(l.layout?.messages)!==JSON.stringify(s)||l.layout?.messages?.renderAssistantMessage!==s?.renderAssistantMessage||l.layout?.messages?.renderUserMessage!==s?.renderUserMessage,P=l.iterationDisplay!==d,N=(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);(!0===l.future?.v5Defaults!==o||"toolCall"in t||L||R||"loadingIndicator"in t||P||N||"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)&&ts&&(zs++,gd(vt,ts.getMessages(),Ae));let $=l.features?.streamAnimation?.type;if($!==f&&$&&"none"!==$){let t=Ka($,l.features?.streamAnimation?.plugins);t&&Xi(t,e)}let W=l.launcher??{},H=W.headerIconHidden??!1,D=l.layout?.header?.showIcon,F=H||!1===D,O=W.headerIconName,q=W.headerIconSize??"40px";if(Ft){let e=er,t=e?.querySelector(".persona-flex-col");if(F)Ft.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Ft.style.display="",Ft.style.height=q,Ft.style.width=q,e&&t&&(e.contains(Ft)?Ft.nextSibling!==t&&(Ft.remove(),e.insertBefore(Ft,t)):e.insertBefore(Ft,t)),O){let e=parseFloat(q)||24,t=Ee(O,.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))`,Ft.replaceChildren(t)):Ft.textContent=W.agentIconText??"💬"}else if(W.iconUrl){let e=Ft.querySelector("img");if(e)e.src=W.iconUrl,e.style.height=q,e.style.width=q;else{let e=document.createElement("img");e.src=W.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=q,e.style.width=q,Ft.replaceChildren(e)}}else{let e=Ft.querySelector("svg"),t=Ft.querySelector("img");(e||t)&&Ft.replaceChildren(),Ft.textContent=W.agentIconText??"💬"}let r=Ft.querySelector("img");r&&(r.style.height=q,r.style.width=q)}}let j=l.layout?.header?.showTitle,_=l.layout?.header?.showSubtitle;if(zt&&(zt.style.display=!1===j?"none":""),Ot&&(Ot.style.display=!1===_?"none":""),Dt){let e=ge()&&!1!==l.layout?.header?.showCloseButton;Dt.style.display=e?"":"none";let t=W.closeButtonPlacement??"inline",{closeButtonWrapper:r}=mt,n="top-right"===t,o=r?.classList.contains("persona-absolute");if(r&&n!==o)if(r.remove(),n){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=Gc?.railColumn??gt;e.style.position="relative",e.appendChild(r)}else{let e=W.clearChat?.placement??"inline";r.className=(W.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",er&&er.appendChild(r)}xl(Dt,l,"close",{buttonSize:me()?Dt.style.width:void 0,iconSize:me()?fd:void 0});let a=W.closeButtonTooltipText??"Close chat",s=W.closeButtonShowTooltip??!0;Dt.setAttribute("aria-label",a),r&&Qa({anchor:Dt,trigger:r,text:()=>Dt?.getAttribute("aria-label")??a,enabled:s})}let{clearChatButton:U,clearChatButtonWrapper:V}=mt;if(U){let e=W.clearChat??{},t=e.enabled??!0,r=l.layout?.header?.showClearChat,n=void 0===r?t:r,o=e.placement??"inline";if(V){V.style.display=n?"":"none";let{closeButtonWrapper:e}=mt;!me()&&e&&!e.classList.contains("persona-absolute")&&(n?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===o,r=V.classList.contains("persona-absolute");if(!me()&&t!==r&&n){if(V.remove(),t){V.className="persona-absolute persona-top-4 persona-z-50",V.style.right="48px";let e=Gc?.railColumn??gt;e.style.position="relative",e.appendChild(V)}else{V.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",V.style.right="";let e=mt.closeButtonWrapper;er&&e&&e.parentElement===er?er.insertBefore(V,e):er&&er.appendChild(V)}let e=mt.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(n){xl(U,l,"clear",{buttonSize:me()?U.style.width:void 0,iconSize:me()?bd:void 0});let t=e.tooltipText??"Clear chat",r=e.showTooltip??!0;U.setAttribute("aria-label",t),V&&Qa({anchor:U,trigger:V,text:()=>U?.getAttribute("aria-label")??t,enabled:r})}}let K=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Dc],Q=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[zc.message,zc.messageAndClick];re=qc({parsers:K,handlers:Q,getSessionMetadata:X,updateSessionMetadata:Z,emit:z.emit,captureResubmitGuard:()=>{let e=be;return()=>ve(e)},documentRef:typeof document<"u"?document:null}),Ae=bp(l,re,ke),(()=>{let e=Ic();if(e&&Bc?.matches(e,Le(),!1===l.persistState)||!e&&!Bc)return;Bc?.destroy(),Bc=e?Tc(e):null;let t={...Lc};Bc?t.visitorStore=Bc:delete t.visitorStore,Lc=t,ts.setHistoryInternals(Lc)})(),ts.updateConfig(l),Op(),(!0===l.features?.history?.enabled!==b||l.features?.history?.provider!==y||l.getIdentityProof!==x||l.clientToken!==C)&&(Gc?.closeHistory({restoreFocus:!1}),(l.getIdentityProof!==x||l.clientToken!==C)&&Gc?.discardConversationContinuity(),Gc?.installHistoryProvider()),Gc?.syncHistoryChromeImpl(),Np(),tp()&&!Gc&&Rp().catch(()=>{}),gd(vt,ts.getMessages(),Ae),ys(),yc(),(()=>{let e=Wr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==hc||e.icon!==nc)&&bc()})(),Qd(ts.isStreaming()),k!==l.contextMentions&&vh();let J=!0===l.voiceRecognition?.enabled&&!1!==l.voiceRecognition.showButton,G=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),Y=_t(l.voiceRecognition?.provider),ee=G||Y||"custom"===l.voiceRecognition?.dictation?.provider?.type;if(J&&ee)if(lr&&dr){let e=l.voiceRecognition??{},t=lr.getAttribute("data-state");xs(lr,l,"recording"===t||"processing"===t||"speaking"===t?t:"idle",ts.getVoiceInterruptionMode());let r=e.tooltipText??"Start voice recognition",n=e.showTooltip??!1;"idle"===t&&lr.setAttribute("aria-label",r),dr&&Qa({anchor:lr,trigger:dr,text:()=>lr?.getAttribute("aria-label")??r,enabled:n}),dr.style.display="",lr.disabled=Wd()||ts.isStreaming()&&!zd()}else{let e=Cs(l);if(e){lr=e.button,dr=e.wrapper;let t=sr&&sr.parentElement===ar?sr:null;ar?ar.insertBefore(dr,t):At?.appendChild(dr),En&&(En.micButton=lr),En?.addListener(lr,"click",$u),lr.disabled=Wd()||ts.isStreaming()&&!zd()}}else lr&&dr&&(dr.style.display="none",(!0!==l.voiceRecognition?.enabled||!ee)&&(_t(l.voiceRecognition?.provider)?ts.isVoiceActive()&&ts.toggleVoice():wu&&Tu()));if(_u(),!0===l.attachments?.enabled){if(mr&&pr){mr.style.display="";let e=l.attachments??{};gr&&(gr.accept=(e.allowedTypes??vo).join(","),gr.multiple=(e.maxFiles??4)>1)}else{let e=l.attachments??{};fr||(fr=st("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fr.style.display="none",(St.parentElement??At).insertBefore(fr,St)),gr||(gr=document.createElement("input"),gr.type="file",gr.accept=(e.allowedTypes??vo).join(","),gr.multiple=(e.maxFiles??4)>1,gr.style.display="none",gr.setAttribute("aria-label","Attach files"),(St.parentElement??At).insertBefore(gr,St)),mr=st("div","persona-send-button-wrapper"),pr=st("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${oa} ${aa}`),pr.type="button",pr.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";pr.style.fontSize="18px",pr.style.lineHeight="1";let r=Ee(t,24,"currentColor",1.5);r?pr.appendChild(r):pr.textContent="📎",pr.addEventListener("click",e=>{e.preventDefault(),gr?.click()}),mr.appendChild(pr);let n=e.buttonTooltipText??"Attach file";Qa({anchor:pr,trigger:mr,text:()=>pr?.getAttribute("aria-label")??n}),or?or.append(mr):At.appendChild(mr),En&&(En.attachmentButton=pr,En.attachmentInput=gr??void 0,En.attachmentPreviews=fr??void 0),!Kr&&gr&&fr&&(Kr=tn(),Kr.setPreviewsContainer(fr),En?.addListener(gr,"change",async()=>{Kr&&gr?.files&&(await Kr.handleFileSelect(gr.files),gr.value="")}))}if(gt.querySelector(".persona-attachment-drop-overlay")?.remove(),gt.appendChild(yp(l.attachments?.dropOverlay)),pr){let e=l.attachments??{},t=e.buttonTooltipText??"Attach file";pr.setAttribute("aria-label",t),pr.textContent="";let r=Ee(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?pr.appendChild(r):pr.textContent="📎",mr&&Qa({anchor:pr,trigger:mr,text:()=>pr?.getAttribute("aria-label")??t})}}else mr&&(mr.style.display="none"),Kr&&Kr.clearAttachments(),gt.querySelector(".persona-attachment-drop-overlay")?.remove();let te=l.sendButton?.tooltipText??"Send message",se=l.sendButton?.showTooltip??!1;vs(kt,l),ts.isStreaming()||kt.setAttribute("aria-label",te),Vd(),sr&&Qa({anchor:kt,trigger:sr,text:()=>kt.getAttribute("aria-label")??te,enabled:se});let pe=new Set([Kr,...Array.from(Cp.values(),e=>e.attachments)]);for(let e of pe)e?.updateConfig(Zr());"plugins"in t&&Kr?.remountPreviews(fr),Xn(),Ha();let ue=ga(Jr.getState().activeModeIds,l.composer?.modes);Jr.setActiveModeIds(ue),on().length>0!=!!cn&&Vn(),cn?.render(ue,on()),dn?.repaint(),Fn?Fn.resolve():Un();let he=gi(l,me());if(Pa(),he){vt.style.maxWidth=he,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%",Rt.style.maxWidth=he,Rt.style.marginLeft="auto",Rt.style.marginRight="auto",Rt.style.width="100%";for(let e of[At,Ct,fr,Mt])e&&(e.style.maxWidth=he,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{vt.style.maxWidth="",vt.style.marginLeft="",vt.style.marginRight="",vt.style.width="",Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight="",Rt.style.width="";for(let e of[At,Ct,fr,Mt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let ye=l.statusIndicator??{};if(hr(Mt,At,ye),ur(Mt,ye,ts?.getStatus()??"idle"),ts){let e=ts.getStatus();lt(Mt,(e=>"idle"===e?ye.idleText??dt.idle:"connecting"===e?ye.connectingText??dt.connecting:"connected"===e?ye.connectedText??dt.connected:"error"===e?ye.errorText??dt.error:"paused"===e?ye.pausedText??dt.paused:"resuming"===e?ye.resumingText??dt.resuming:dt[e])(e),ye,e)}Mt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let we="left"===ye.align?"persona-text-left":"center"===ye.align?"persona-text-center":"persona-text-right";Mt.classList.add(we),Bn(),Kd(),Yn(),Ze(),eo(l.layout?.slots??{}),mu()&&Wd()&&gu(),su?.refresh(),oo.update(),qh()},open(){ge()&&Nd(!0,"api")},close(){ge()&&Nd(!1,"api")},toggle(){ge()&&Nd(!fe,"api")},reconnect(){ts.reconnectNow()},clearChat(){gu(),Ws(),Ro=!1,i?.clear(),mo(),f.clear(),b.clear(),y.clear(),ts.clearMessages(),l.layout?.topFade&&(ft.scrollTop=0),ft.removeAttribute("data-persona-top-fade"),As.clear(),El();try{localStorage.removeItem(cp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${cp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==cp)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:o,timestamp:(new Date).toISOString()}});window.dispatchEvent(e),ol(),O?.clear&&qi(()=>O.clear(),"[AgentWidget] Failed to clear storage adapter:"),_={},re.syncFromMetadata(),Ep(ts.getActiveConversationId(),!0,!1),Kp(),ol(),fn(void 0),un(void 0),Fs(),He?.clear(),De?.reset(),Oe?.update()},setMessage:e=>!(!St||mu()||ts.isStreaming()||Wd()||(!fe&&ge()&&Nd(!0,"system"),St.value=e,St.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(ts.isStreaming()||mu()||Od())return!1;let t=e?.trim()||St.value.trim();return!!t&&(!fe&&ge()&&Nd(!0,"system"),St.value="",St.style.height="auto",Gr(),eu(t,{consumeDraft:!1}),!0)},getComposerState:()=>Jr.getState(),setComposerModes(e){sn(function(e,t,r){let n=[];for(let o of e)n.includes(o)||(n=ma(n,o,t,r));return n}(e,nn(),l.composer?.modeGroups))},setQuote(e){let t=e?.text?.trim();t&&un({...e,text:t})},clearQuote(){un(void 0)},startDictation:bu,finishDictation:()=>fu(),cancelDictation:()=>{let e=lu;return gu()||e},sendDictation:()=>!(!l.voiceRecognition?.dictation?.showSend||Od())&&fu(!0),getDictationState:()=>du??su?.getState()??uu,startVoiceRecognition:()=>!ts.isStreaming()&&!mu()&&(hu()&&!l.voiceRecognition?.dictation?.provider&&"runtype"!==l.voiceRecognition?.provider?.type?bu():_t(l.voiceRecognition?.provider)?(ts.isVoiceActive()||ts.isBargeInActive()||(!fe&&ge()&&Nd(!0,"system"),xi.manuallyDeactivated=!1,Ri(),ts.toggleVoice().then(()=>{xi.active=Ai(),Ri(),Bi("user"),xi.active&&Lu()})),!0):!!wu||!!Mu()&&(!fe&&ge()&&Nd(!0,"system"),xi.manuallyDeactivated=!1,Ri(),Iu("user"),!0)),stopVoiceRecognition:()=>mu()?fu():_t(l.voiceRecognition?.provider)?!(!ts.isVoiceActive()&&!ts.isBargeInActive()||((ts.isBargeInActive()?ts.deactivateBargeIn():ts.toggleVoice()).then(()=>{xi.active=!1,xi.manuallyDeactivated=!0,Ri(),Bi("user"),Nu()}),0)):!!wu&&(xi.manuallyDeactivated=!0,Ri(),Tu("user"),!0),injectMessage:e=>(!fe&&ge()&&Nd(!0,"system"),ts.injectMessage(e)),injectAssistantMessage(e){!fe&&ge()&&Nd(!0,"system");let t=ts.injectAssistantMessage(e);return Ce&&(Ce=!1,Se&&=(clearTimeout(Se),null),xe()),t},injectUserMessage:e=>(!fe&&ge()&&Nd(!0,"system"),ts.injectUserMessage(e)),injectSystemMessage:e=>(!fe&&ge()&&Nd(!0,"system"),ts.injectSystemMessage(e)),injectMessageBatch:e=>(!fe&&ge()&&Nd(!0,"system"),ts.injectMessageBatch(e)),injectComponentDirective:e=>(!fe&&ge()&&Nd(!0,"system"),ts.injectComponentDirective(e)),updateComponentProps:(e,t)=>ts.updateComponentProps(e,t),removeComponentMessage:e=>ts.removeComponentMessage(e),injectTestMessage(e){!fe&&ge()&&Nd(!0,"system"),ts.injectTestEvent(e)},connectStream:async(e,t)=>ts.connectStream(e,t),__pushEventStreamEvent(e){Te&&(Qe(),Ke(e.type,e.payload))},showEventStream(){Te&&Cn()},hideEventStream(){qe&&Sn()},isEventStreamVisible:()=>qe,listConversations:e=>ts.listConversations(e),getActiveConversationId:()=>ts.getActiveConversationId(),openConversation:(e,t)=>Pp(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus,busy:t?.busy})),startNewConversation:e=>Pp(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){$p()},deleteConversation:e=>Pp(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Pp(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Pp(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Pp(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Pp(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Bc;if(!e)return null;let t=await e.get();return e===Bc?t:null},getHistoryIdentityStatus(){let e=Gc?.historyProvider;return e?e.getIdentityStatus():tp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>tp()?Pp(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){Gc?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>Ye,showArtifacts(){Fd(l)&&(Ro=!1,Do=!0,Ba(),Co?.setMobileOpen(!0))},hideArtifacts(){Fd(l)&&(Ro=!0,Ba())},upsertArtifact:e=>Fd(l)?("panel"===Io(l.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Ro=!1,Do=!0),ts.upsertArtifact(e)):null,selectArtifact(e){Fd(l)&&ts.selectArtifact(e)},clearArtifacts(){Fd(l)&&ts.clearArtifacts()},getArtifacts:()=>ts?.getArtifacts()??[],getSelectedArtifactId:()=>ts?.getSelectedArtifactId()??null,focusInput:()=>!(ne&&!fe&&!me()||!St||(St.focus(),0)),revealToolCall(e,t={}){let r=Array.from(ft.querySelectorAll(".persona-tool-bubble[data-tool-call-id]")).find(t=>t.dataset.toolCallId===e);if(!r)return!1;let n=e=>Array.from(e.querySelectorAll('button[data-expand-header="true"]')).find(t=>t.closest(".persona-tool-bubble")===e),o=e=>{"false"===e?.getAttribute("aria-expanded")&&io(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=>o(n(e)));let s=n(r);!1!==t.expand&&o(s),oi(),Rl.cancel(),Ml();let i=uo,l=s??r,d=()=>!ye&&i===uo&&ft.contains(l),c="function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,p=()=>{let e=Or(l)-(ft.clientHeight-l.offsetHeight)/2;return Math.max(0,Math.min(e,Qt(ft)))},u=()=>{d()&&(c?(pl(),Vs=!0,ft.scrollTop=p(),qs=ft.scrollTop,Vs=!1):Ll(ft,p,200,d))};window.clearTimeout(lo),u(),lo=window.setTimeout(()=>{lo=void 0,u()},200);let h=t.highlightMs??2e3;if(h>0){let e=r.dataset.messageId;window.clearTimeout(po.get(e)),po.set(e,window.setTimeout(()=>{po.delete(e),ho()},h)),r.setAttribute("data-persona-revealed","")}return!0},async resolveApproval(e,t,r){let n=ts.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!n?.approval)throw Error(`Approval not found: ${e}`);if(!cr(n.approval))return ts.resolveApproval(n.approval,t,r);ts.resolveWebMcpApproval(n.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void Ss();let r=ts?ts.getMessages():[];os=t,is=!0,ls=ps(r),ds=us(r),ys(r)})(e)},clearFollowUpSuggestions(){Ss()},getMessages:()=>ts.getMessages(),getStatus:()=>ts.getStatus(),getPersistentMetadata:()=>({..._}),updatePersistentMetadata(e){Z(e)},on:(e,t)=>z.on(e,t),off(e,t){z.off(e,t)},isOpen:()=>ge()&&fe,isVoiceActive:()=>xi.active,toggleReadAloud(e){ts.toggleReadAloud(e)},stopReadAloud(){ts.stopSpeaking()},getReadAloudState:e=>ts.getReadAloudState(e),onReadAloudChange:e=>ts.onReadAloudChange(e),getState:()=>({open:ge()&&fe,launcherEnabled:ne,voiceActive:xi.active,streaming:ts.isStreaming()}),showCSATFeedback(e){Nh(()=>lp({onSubmit:async(t,r)=>{ts.isClientTokenMode()&&await ts.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},showNPSFeedback(e){Nh(()=>dp({onSubmit:async(t,r)=>{ts.isClientTokenMode()&&await ts.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},submitCSATFeedback:async(e,t)=>ts.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>ts.submitNPSFeedback(e,t),destroy(){ye=!0,we(),u.destroy(),oo.destroy(),e.removeEventListener("click",ao),_c(),Fa.forEach(e=>e()),null!=Rc&&(clearInterval(Rc),Rc=null),i?.destroy(),s?.destroy(),mo(),f.clear(),b.clear(),y.clear(),z.dispose(),pt.remove(),ht?.remove(),Xu?.destroy(),Zu?.remove(),ns&&Dt.removeEventListener("click",ns)}};if((r?.debugTools||l.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Fh,getMessages:Fh.getMessages,getStatus:Fh.getStatus,getMetadata:Fh.getPersistentMetadata,updateMetadata:Fh.updatePersistentMetadata,clearHistory:()=>Fh.clearChat(),setVoiceActive:e=>e?Fh.startVoiceRecognition():Fh.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Fa.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===o)&&t(r)};window.addEventListener(e,r),Fa.push(()=>window.removeEventListener(e,r))};e("persona:focusInput",()=>Fh.focusInput()),Te&&(e("persona:showEventStream",()=>Fh.showEventStream()),e("persona:hideEventStream",()=>Fh.hideEventStream())),e("persona:showHistory",()=>Fh.showHistory()),e("persona:hideHistory",()=>Fh.hideHistory()),e("persona:showArtifacts",()=>Fh.showArtifacts()),e("persona:hideArtifacts",()=>Fh.hideArtifacts()),e("persona:upsertArtifact",e=>{e?.artifact&&Fh.upsertArtifact(e.artifact)}),e("persona:selectArtifact",e=>{"string"==typeof e?.id&&Fh.selectArtifact(e.id)}),e("persona:clearArtifacts",()=>Fh.clearArtifacts())}let zh=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(zh&&ge()){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}}(zh.storage),r=`${zh.keyPrefix}widget-open`,n=`${zh.keyPrefix}widget-voice`,a=`${zh.keyPrefix}widget-voice-mode`;if(t){let s=zh.persist?.openState&&"true"===t.getItem(r),i=zh.persist?.voiceState&&"true"===t.getItem(n),l=zh.persist?.voiceState&&"true"===t.getItem(a);if(s&&(Xu?.setPanelOpen(!0,"auto"),setTimeout(()=>{Fh.open(),setTimeout(()=>{if(i||l)Fh.startVoiceRecognition();else if(zh.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),zh.persist?.openState&&(z.on("widget:opened",()=>{t.setItem(r,"true")}),z.on("widget:closed",()=>{t.setItem(r,"false")})),zh.persist?.voiceState&&(z.on("voice:state",e=>{t.setItem(n,e.active?"true":"false")}),z.on("user:message",e=>{t.setItem(a,e.viaVoice?"true":"false")})),zh.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(n),t.removeItem(a)},s=t=>{t.detail?.instanceId===o&&e()};window.addEventListener("persona:clear-chat",s),Fa.push(()=>{window.removeEventListener("persona:clear-chat",s)})}}}J&&ge()&&(Xu?.setPanelOpen(!0,"auto"),setTimeout(()=>{Fh.open()},0)),Bd(),P=()=>{ts&&(zs++,As.clear(),gd(vt,ts.getMessages(),Ae))},ts.getMessages().length>0&&ud(),D=P;let Oh=Bt(()=>{P?.(),Et()?.updateInlineArtifactBlocks(vt,Eo.artifacts,{suppressTransition:!0}),Ba()});Fa.push(Oh);let qh=()=>{let t=Vt(l);$h||t.push(...r?.preparation??[]),tp()&&!Gc&&t.push(Rp()),t.length||e.hasAttribute("data-persona-preparing")?u.prepare(t,()=>{Fn||Un(),cn||Vn(),g(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),P?.(),$h=!0}):$h=!0};return qh(),Fh},xp=(e,t)=>{let r=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,t*parseFloat(o[1])/100):420},Cp=(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"},Sp=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=""},kp=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Sp(e)},Ap=e=>{e.style.transition=""},Mp=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=""},Ip=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Tp=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ep=(e,t,r,n)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=n):(e.style.padding="",e.style.background="",e.style.boxSizing="")},Bp=(e,t)=>il(t)?((e,t)=>{let{ownerDocument:r}=e,n=e.parentElement;if(!n)throw Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if("BODY"===o||"HTML"===o)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),n.insertBefore(s,e),l.appendChild(e);let u=null,h=()=>{u?.disconnect(),u=null},m=null,g=()=>{m=!0===t?.launcher?.detachedPanel?(e=>{let t=di(e),r=t.components?.panel,n=(e,r)=>null==e||""===e?r:Us(t,e)??e;return{inset:n(r?.inset,Es),canvasBackground:n(r?.canvasBackground,Bs)}})(t):null};g();let f=()=>{((e,t,r,n,o,a,s,i)=>{let l=dl(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,n,o)=>{o?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,n),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(n))})(e,t,r,n,d),((e,t,r,n,o,a)=>{let s=a?t:e;"left"===o?s.firstElementChild!==n&&s.replaceChildren(n,r):s.lastElementChild!==n&&s.replaceChildren(r,n)})(e,t,r,n,l.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=l.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,g=a?.launcher?.mobileBreakpoint??640,f=null!=h&&h.innerWidth<=g;if(m&&f&&s)e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Mp(t),Ap(n),kp(n),Ip(r),Tp(o,n),Ep(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??1e5),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.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"),kp(n),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(n,l.maxHeight),Ep(n,c&&s,p,u),"overlay"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Mp(t),Ap(n),Ip(r),Tp(o,n);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=l.width,n.style.maxWidth=l.width,n.style.minWidth=l.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=a,n.style.transform=d,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2","right"===l.side?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if("push"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ap(n),Sp(n),Tp(o,n);let a=xp(l.width,e.clientWidth),i=Math.max(0,e.clientWidth),d=l.animate?"margin-left 180ms ease":"none",c="right"===l.side?s?-a:0:s?0:-a;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${i+a}px`,t.style.transition=d,t.style.marginLeft=`${c}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${i}px`,r.style.maxWidth=`${i}px`,r.style.minWidth=`${i}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=l.width,n.style.minWidth=l.width,n.style.maxWidth=l.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Mp(t),Sp(n),Ip(r),Tp(o,n);let a="emerge"===l.reveal;a?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let i=s?l.width:"0px",d=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease"+(c?", padding 180ms ease":""):"none",u=!s;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(n,l.maxHeight),n.style.overflow=a||u?"hidden":"visible",n.style.transition=d,a){n.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${xp(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;o.style.width=t,o.style.minWidth=t,o.style.maxWidth=t,o.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},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 n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(n);let o=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),o&&!a&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(!1===t.maxHeight?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")})(s,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(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Cp(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Cp(r,e)},destroy(){r.remove()}}})(e,t),Lp=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let n=r.cloneNode(!0),o=new Promise((e,t)=>{n.onload=()=>e(),n.onerror=()=>t(Error("Unable to load the widget stylesheet"))});return e.insertBefore(n,e.firstChild),o},Rp=[],Pp=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Np=new Set(["button","a","input","select","textarea","details","summary"]),$p=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Wp=/\b(product|card|item|listing|result)\b/i,Hp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function Dp(e){let t="string"==typeof e.className?e.className:"";if(Wp.test(t)||e.id&&Wp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Wp.test(r.value))return!0}return!1}function Fp(e){return Hp.test((e.textContent??"").trim())}function zp(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 Op(e){let t=e.match(Hp);return t?t[0]:null}function qp(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 jp(e){return Dp(e)&&Fp(e)&&(zp(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function _p(e){return!Dp(e)||Fp(e)||!zp(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let Up=[{id:"commerce-card",scoreElement:e=>jp(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||Hp.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===jp(e))return null;let{title:r,href:n}=qp(e),o=Op((e.textContent??"").trim())??Op(t.text)??"",a=function(e){let t=[],r=e=>{let r=e.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(e=>r(e.textContent??"")),e.querySelectorAll('[role="button"]').forEach(e=>r(e.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(e=>{r(e.value??"")}),t.slice(0,6)}(e);return[n&&r?`[${r}](${n})${o?`: ${o}`:""}`:r?`${r}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>_p(e),formatSummary(e,t){if(0===_p(e))return null;let{title:r,href:n}=qp(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Vp(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let Kp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Qp(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||Np.has(t)||r&&$p.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function Jp(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 Gp(e){let t={},r=e.id;r&&(t.id=r);let n=e.getAttribute("href");n&&(t.href=n);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let l=e.getAttribute("role");l&&(t.role=l);for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];n.name.startsWith("data-")&&(t[n.name]=n.value)}return t}function Yp(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Vp(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of Kp){let n=e.getAttribute(r);if(n){let o=`${t}[${r}="${Vp(n)}"]`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(e=>Vp(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${n}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function Xp(e,t){let r=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Yp(e),tagName:r,text:n,role:e.getAttribute("role"),interactivity:Qp(e),attributes:Gp(e)}}function Zp(e,t,r,n){let o=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,n);r>0&&(o+=r,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function eu(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 tu={components:{panel:{borderRadius:"0",shadow:"none"}}},ru={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}}}},nu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:tu}},ou={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:tu}},au={shop:ru,minimal:nu,fullscreen:ou},su=typeof document<"u"?document.currentScript?.src??null:null,iu=(e,t=`host ${e} alongside it`)=>{let r=0;return()=>{let n=su?.replace(/index\.global\.js($|\?)/,`${e}$1`);return n&&n!==su?import(`${n}${r?`#retry-${r}`:""}`).catch(e=>{throw r++,e}):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${su??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))}};return(e=>{or=e})(iu("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),rt(iu("markdown-parsers.js")),qr(iu("client-stream.js")),to(iu("client-history.js")),$t(iu("ui-extras.js")),ho(iu("session-actions.js")),rp(iu("history-shell.js")),(e=>{Oo=e})(iu("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),La(iu("context-mentions.js")),$a(iu("context-mentions-inline.js")),Gc(iu("history-view.js")),tl(iu("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),Ld(iu("approval-ui.js")),Ot(iu("voice-runtime.js")),on(iu("voice-client-tools.js")),It(iu("artifacts-ui.js")),vc(iu("forms-ui.js")),ie(iu("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),en(iu("webmcp-runtime.js")),Uo(iu("session-reconnect.js")),Wd(iu("event-stream-view.js")),Ne(iu("composer-actions-runtime.js")),Qe(iu("dictation-runtime.js")),so(iu("background-runtime.js")),Lc(iu("config-diagnostics.js")),J(iu("activity-ui.js")),Oe(iu("loading-label-runtime.js")),Jr(iu("client-dispatch.js")),te(iu("turn-activity-ui.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=_n,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=jn,e.ASK_USER_QUESTION_TOOL_NAME=cn,e.AgentWidgetClient=o,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=zs,e.DEFAULT_WIDGET_CONFIG=hs,e.HistoryProviderError=a,e.PRESETS=au,e.PRESET_FULLSCREEN=ou,e.PRESET_MINIMAL=nu,e.PRESET_SHOP=ru,e.ReadAloudController=i,e.SUGGEST_REPLIES_CLIENT_TOOL=Hn,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=Wn,e.SUGGEST_REPLIES_TOOL_NAME=$n,e.THEME_ZONES={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"},e.VERSION=Yn,e.WEBMCP_TOOL_PREFIX=er,e.applyFeaturePreferences=hc,e.applyThemeVariables=ui,e.attachHeaderToContainer=Tl,e.buildComposer=$l,e.buildDefaultHeader=El,e.buildHeader=Il,e.buildHeaderWithLayout=Pl,e.buildMinimalHeader=Bl,e.builtInClientToolsForDispatch=Un,e.canonicalArtifactDisplayMode=ko,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",o=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,i=t.mode??"structured",l=t.maxCandidates??Math.max(500,10*r),d=e.rules??Up;return"simple"===i&&e.rules&&e.rules.length>0?(typeof console<"u"&&"function"==typeof console.warn&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.'),d=[]):"simple"===i&&(d=[]),{mode:i,maxElements:r,maxCandidates:l,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],n=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(Pp.has(s)){a=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Jp(t)){a=o.nextNode();continue}let i=Xp(t,e.maxTextLength),l=i.text.length>0,d=Object.keys(i.attributes).length>0&&!Object.keys(i.attributes).every(e=>"role"===e);if(!l&&!d){a=o.nextNode();continue}n.has(i.selector)||(n.add(i.selector),r.push(i))}a=o.nextNode()}let s=[],i=[];for(let e of r)"static"===e.interactivity?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},n=new Set,o=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(Pp.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Jp(t)){i=s.nextNode();continue}let d=Xp(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||n.has(d.selector)){i=s.nextNode();continue}n.add(d.selector);let{score:u,formattingRule:h}=Zp(t,d,e.rules,r);o.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}o.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-n});let l=[];for(let t of o){if(l.length>=e.maxElements)break;eu(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-n}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let n=e.formattingRule.formatSummary(e.el,e.enriched,r);n&&(t=n)}let n={...e.enriched};return t&&(n.formattedSummary=t),n})}(t,r):[]},e.componentRegistry=ft,e.createActionManager=qc,e.createAgentExperience=wp,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"),kn(r,t);let n=st("span","persona-ask-stub-label"),{complete:o}=xn(e);return n.textContent=o?"Awaiting your response…":"Preparing options…",r.appendChild(n),r},e.createBubbleWithLayout=(e,t,r,n,o,a)=>{let s=r??{};return"user"===e.role&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):"assistant"===e.role&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ql(e,t,r,n,0,a)},e.createCSATFeedback=lp,e.createComboButton=gt,e.createComponentMiddleware=function(){let e=Ro();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=Ro,e.createDefaultSanitizer=Rr,e.createDirectivePostprocessor=e=>{let t=Sr(e);return e=>{let r=[],n=Er(e,r),o=t(n);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Ir(t)}"></div>`;o=o.replace(r,n)}),o}},e.createDropdownMenu=ct,e.createFlexibleJsonStreamParser=e=>{let t=null,n=0,o=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?Vn(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?Vn(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<=n)return null===t?null:{text:t,raw:e};try{let n=(0,r.parse)(e,r.STR|r.OBJ),a=o(n);null!==a&&(t=a)}catch{}return n=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=Jn,e.createLabelButton=ut,e.createLocalStorageAdapter=Vc,e.createMarkdownProcessor=Cr,e.createMarkdownProcessorFromConfig=Sr,e.createMessageActions=Kl,e.createNPSFeedback=dp,e.createPlainTextParser=Kn,e.createRegexJsonParser=Qn,e.createSplitButton=mt,e.createStandardBubble=Ql,e.createTextPart=bo,e.createTheme=Js,e.createThemeObserver=mi,e.createToggleGroup=ht,e.createTypingIndicator=Fl,e.createWidgetHostLayout=Bp,e.createXmlParser=Gn,e.defaultActionHandlers=zc,e.defaultJsonActionParser=Dc,e.defaultParseRules=Up,e.detectColorScheme=ii,e.directivePostprocessor=e=>{let t=[],r=Er(e,t),n=Ar(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Ir(t)}"></div>`;n=n.replace(r,o)}),n},e.ensureAskUserQuestionSheet=Pn,e.escapeHtml=Mr,e.extractComponentDirectiveFromMessage=Wo,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",n=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&n.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||o[t.interactivity].push(t);if(o.clickable.length>0){let e=o.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);n.push(`Interactive elements:\n${e.join("\n")}`)}if(o.navigable.length>0){let e=o.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);n.push(`Navigation links:\n${e.join("\n")}`)}if(o.input.length>0){let e=o.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);n.push(`Form inputs:\n${e.join("\n")}`)}if(o.static.length>0){let e=o.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);n.push(`Content:\n${e.join("\n")}`)}return n.join("\n\n")},e.generateAssistantMessageId=dn,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=Yp,e.generateUserMessageId=ln,e.getActiveTheme=di,e.getAgentWidgetHandles=()=>[...Rp],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 au[e]},e.hasComponentDirective=$o,e.hasImages=fo,e.headerLayouts=Ll,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),n=!0===e.useShadowDom,o=r.ownerDocument,a=r.id||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,s=e.config,i=Wc(s),l=Bp(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=o.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"),n){let t=e.attachShadow({mode:"open"});t.appendChild(i),r=Lp(t,o)}else e.appendChild(i),Lp(e,o);return i.setAttribute("data-persona-instance",a),{mount:i,stylesReady:r}},f=()=>{l.syncWidgetState(t.getState())},b=()=>{let{mount:r,stylesReady:n}=g(l.host,s);t=wp(r,s,{debugTools:e.debugTools,registerHostMove:e=>{h=e},diagnostics:i,preparation:n?[n]:[]}),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=Bp(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 n="string"==typeof e?o.querySelector(e):e;if(!(n instanceof HTMLElement)||n.ownerDocument!==o||n.getRootNode()!==o||l.host.getRootNode()!==o||l.host.contains(n))throw Error("Invalid widget move target: expected a connected light-DOM container in the same document");n!==r&&(h(()=>function(e,t,r){let n=e.ownerDocument,o=n.activeElement;for(;o?.shadowRoot?.activeElement;)o=o.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(o)?o:null,i=s,l=i?.selectionStart,d=i?.selectionEnd,c=i?.selectionDirection,p=(s?.getRootNode())?.getSelection?.()??n.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,n,!1!==t?.preserveFocus)),r=n)},on(e,r){if(c)return()=>{};let n=[...m].find(t=>t.event===e&&t.handler===r);if(n)return n.unsubscribe;let o=()=>{},a={event:e,handler:r,bind:()=>{o=t.on(e,r)},unsubscribe:()=>{o(),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){Hc(i,e);let r=Mc(s??{},e),n=il(s),o=il(r),a=ll(s),d=ll(r);n!==o||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=Rp.indexOf(w);-1!==t&&Rp.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,n){if("host"===r)return l.host;if(r in e)return Reflect.get(e,r,n);let o=t[r];return"function"==typeof o?o.bind(t):o}});return Rp.push(w),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w},e.isAskUserQuestionMessage=vn,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=Dn,e.isWebMcpToolName=lr,e.isWelcomeVisible=pd,e.latestAgentSuggestions=zn,e.listRegisteredStreamAnimations=()=>Array.from($i.keys()),e.loadMarkdownParsers=nt,e.markdownPostprocessor=Ar,e.mergeWithDefaults=gs,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=Ao,e.onMarkdownParsersReady=ot,e.parseAskUserQuestionPayload=xn,e.parseSuggestRepliesPayload=Fn,e.parseWidgetPreferenceSlice=dc,e.pickBestVoice=Fo,e.pluginRegistry=Cc,e.preprocessStreamingMarkdown=xr,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=Nn,e.renderComponentDirective=Po,e.renderLoadingIndicatorWithFallback=zl,e.renderLucideIcon=Ee,e.resolveArtifactDisplay=Mo,e.resolveArtifactDisplayMode=Io,e.resolveConfigPreferences=mc,e.resolveDockConfig=dl,e.resolveSanitizer=Pr,e.resolveTokens=Vs,e.resolveWelcomeConfig=ld,e.stripWebMcpPrefix=ir,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,n,o,a,s,i,l,d,c,p,u,h=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),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 n=t?`${t}.${e}`:e;return g(r)?f(r,n):[n]})}function b(e,t){let r=t.split(".");for(let t=0;t<r.length;t++){let n=r[t];if(!g(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(void 0===(e=e[n])||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 n=t[m];if(n)return n;let o=new Set(y(e,r));for(let e of r){let r=b(t,e);"clear"===r&&o.delete(e),"explicit"===r&&o.add(e)}return[...o]}function C(e,t,r){let n={...e};for(let e of t){if(r.includes(e))continue;let t=e.split("."),o=n;for(let e of t.slice(0,-1)){let t=o[e];if(!g(t)){o=void 0;break}o[e]={...t},o=o[e]}o&&delete o[t[t.length-1]]}return n}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,n]of Object.entries(t)){let t=r[e];r[e]=S(t)&&S(n)?k(t,n):n}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 n=/^rgba?\(\s*([^)]*)\)$/i.exec(t);if(!n)return;let o=n[1].trim().split(/\s*[,/]\s*|\s+/);if(4===o.length&&/^(?:1(?:\.0+)?|100%)$/.test(o[3])&&o.pop(),3!==o.length)return;let a=o.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 n=t/255;return e+(n<=.04045?n/12.92:((n+.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(n=>{W(e,n)!==t.values[n]&&("explicit"===b(e,n)?r.add(n):r.delete(n))}),[...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,j=(e,t,r)=>{let n=e,o=r??n?.colorScheme??L(n?.brand)??"light",a="dark"===o||"auto"===o&&(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}`)},q={defaultProvenance:y,suppliedPath:b,hasExplicitThemeStyle:j,getExplicitLegacyStyle:z},_=e=>{let{fallbackImport:t,resetOnSetLoader:r=!1}=e,n=null,o=null,a=null;return{setLoader:e=>{n=e,r&&(o=null,a=null)},load:()=>{if(o)return Promise.resolve(o);if(a)return a;let e=n??t;try{return a=e().then(e=>(o=e,e)).catch(e=>{throw a=null,e}),a}catch(e){return Promise.reject(e)}},provide:e=>{o=e},getSync:()=>o}},{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,ne=()=>Promise.all([Z(),G()]).then(([e,t])=>(Object.assign(t.turnUi,e),re=e)),oe=(e,t=24,r="currentColor",n=2)=>{if(!Array.isArray(e))return null;let o=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(n),"stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"}))o.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 n=document.createElementNS("http://www.w3.org/2000/svg",e);for(let[e,t]of Object.entries(r))"stroke"!==e&&n.setAttribute(e,String(t));o.appendChild(n)}return o},{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 n=Ce.get(r);if(!n)continue;Se.delete(t),e++;let o=oe(n);if(o)for(t.removeAttribute("data-persona-icon-pending");o.firstChild;)t.appendChild(o.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",n=2)=>{let o=Ce.get(e);if(o)return oe(o,t,r,n);if(xe.includes(e)){let o=((e,t,r)=>{let n=oe([],e,t,r);return n.setAttribute("data-persona-icon-pending","true"),n})(t,r,n);return Se.size>=500&&Se.delete(Se.keys().next().value),Se.set(o,e),Te()?.catch(e=>{console.warn("[Persona] Failed to load the icons-extra chunk",e)}),o}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,je=De,qe=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,nt=()=>{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))},ot=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 n=document.createElement(e);if(t.className&&(n.className=t.className),void 0!==t.text&&(n.textContent=t.text),t.attrs)for(let[e,r]of Object.entries(t.attrs))n.setAttribute(e,r);if(t.style){let e=n.style,r=t.style;for(let t of Object.keys(r)){let n=r[t];null!=n&&(e[t]=n)}}let o=r.filter(e=>null!=e);return o.length>0&&n.append(...o),n},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:n,position:o="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"===o?i.style.right="0":i.style.left="0");for(let e of t){if(e.dividerBefore){let e=document.createElement("hr");i.appendChild(e)}let t=document.createElement("button");if(t.type="button",t.setAttribute("role","menuitem"),t.setAttribute("data-dropdown-item-id",e.id),e.destructive&&t.setAttribute("data-destructive",""),e.icon){let r=Ee(e.icon,16,"currentColor",1.5);r&&t.appendChild(r)}let n=document.createElement("span");n.textContent=e.label,t.appendChild(n),t.addEventListener("click",t=>{t.stopPropagation(),c(),r(e.id)}),i.appendChild(t)}let l=null;function d(){let e=i.classList.contains("persona-hidden");(function(){if(!a)return;let e=n.getBoundingClientRect();i.style.top=`${e.bottom+4}px`,"bottom-right"===o?(i.style.right=window.innerWidth-e.right+"px",i.style.left="auto"):(i.style.left=`${e.left}px`,i.style.right="auto")})(),i.classList.remove("persona-hidden"),e&&s?.(!0),requestAnimationFrame(()=>{let e=e=>{!i.contains(e.target)&&!n.contains(e.target)&&c()};document.addEventListener("click",e,!0),l=()=>document.removeEventListener("click",e,!0)})}function c(){let e=!i.classList.contains("persona-hidden");i.classList.add("persona-hidden"),l?.(),l=null,e&&s?.(!1)}return a&&a.appendChild(i),{element:i,show:d,hide:c,toggle:function(){i.classList.contains("persona-hidden")?d():c()},destroy:function(){c(),i.remove()}}}function pt(e){let{icon:t,label:r,size:n,strokeWidth:o,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,n??16,"currentColor",o??2);if(c&&d.appendChild(c),i&&d.addEventListener("click",i),l)for(let[e,t]of Object.entries(l))d.setAttribute(e,t);return d}function ut(e){let{icon:t,label:r,variant:n="default",size:o="sm",iconSize:a,className:s,onClick:i,aria:l}=e,d="persona-label-btn";"default"!==n&&(d+=" persona-label-btn--"+n),d+=" persona-label-btn--"+o,s&&(d+=" "+s);let c=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:n,className:o}=e,a=st("div","persona-toggle-group"+(o?" "+o:""));a.setAttribute("role","group");let s=r,i=[];function l(){for(let e of i)e.btn.setAttribute("aria-pressed",e.id===s?"true":"false")}for(let e of t){let t;e.icon?t=pt({icon:e.icon,label:e.label,className:e.className,onClick:()=>{s=e.id,l(),n(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(),n(e.id)})),t.setAttribute("aria-pressed",e.id===s?"true":"false"),i.push({id:e.id,btn:t}),a.appendChild(t)}return{element:a,setSelected:function(e){s=e,l()}}}function mt(e){let{label:t,icon:r,iconSize:n,iconOnly:o,menuItems:a,onSelect:s,onPrimary:i,position:l="bottom-left",portal:d,chevronLabel:c="More options",chevronIconSize:p,className:u,primaryClassName:h,chevronClassName:m}=e,g=st("div","persona-split-btn"+(u?" "+u:"")),f={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:i},b=o&&r?pt({...f,icon:r,size:n??14}):ut({...f,icon:r,iconSize:n??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:n,onSelect:o,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:n,onSelect:e=>{d.setAttribute("aria-expanded","false"),o(e)},anchor:d,position:a,portal:s});return s||d.appendChild(u.element),d.addEventListener("click",e=>{if(e.stopPropagation(),"true"===d.getAttribute("data-persona-menu-locked"))return;let t=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",t?"false":"true"),u.toggle()}),d.addEventListener("keydown",e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),d.click())}),{element:d,setLabel:e=>{c.textContent=e,d.setAttribute("aria-label",e)},open:()=>{d.setAttribute("aria-expanded","true"),u.show()},close:()=>{d.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let e=!u.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",e?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),d.remove()}}}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:qe(),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):ot(()=>{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(),je()]).then(([e])=>Mt(e)),Et=()=>{if(kt)return kt;if(!qe())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,jt=Ot,qt=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,n)=>{e&&!r&&t.push(n())};r(!0,We(),$e),r(!0,at(),nt);let n=!0===e.turnActivity?.enabled;r(n,re,ne);let o=n||!1!==e.features?.showToolCalls||!1!==e.features?.showReasoning;r(o,Y(),G),r(o||"none"!==e.loadingLabel?.animation&&(!!e.loadingLabel?.animate||"label"===(e.loadingIndicator?.variant??(e.future?.v5Defaults?"label":"dots"))),qe(),je),r(!1!==e.voiceRecognition?.enabled,Ge(),Je),r(!1!==e.voiceRecognition?.enabled&&Ut(e),qt(),jt),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"assistant"===e.role&&"tool"!==e.variant&&"reasoning"!==e.variant&&("approval"===e.variant||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length))}function Qt(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Jt(e,t){return Qt(e)-e.scrollTop<=t}function Gt(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 Yt(){let e=null,t=()=>{null!==e&&cancelAnimationFrame(e),e=null};return{get active(){return null!==e},cancel:t,start(r,n,o,a,s,i=()=>!0){t();let l=r.scrollTop,d=performance.now();if(Math.abs(n()-l)<1)return r.scrollTop=n(),a(),void s();let c=p=>{if(!i())return t(),void s();let u=Math.min(Math.max(0,(p-d)/o),1);r.scrollTop=l+(n()-l)*(1-(1-u)**3),a(),u<1?e=requestAnimationFrame(c):(e=null,s())};e=requestAnimationFrame(c)}}}function Xt(e,t,r,n,o){let a,s=Yt(),i=!1,l=!1,d=e=>{e&&(l=!1),s.active&&(s.cancel(),a=e,l=!!e,o())},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 o="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;!o||p||0===c?(e.scrollTop=Qt(e),r(),n()):s.start(e,()=>Qt(e),c,r,n)},destroy(){i=!0,s.cancel(),e.removeEventListener("wheel",p),e.removeEventListener("touchstart",d),e.removeEventListener("pointerdown",d),t.removeEventListener("keydown",c)}}}function Zt(e,t,r){let n=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");n.type="button",n.setAttribute("data-persona-scroll-to-bottom-visible","false"),n.disabled=!0,n.tabIndex=-1,n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-scroll-to-bottom","true");let o=st("span","persona-flex persona-items-center persona-justify-center");o.setAttribute("aria-hidden","true");let a=st("span",""),s=st("span","");s.setAttribute("data-persona-scroll-to-bottom-count",""),n.appendChild(o),n.appendChild(a),n.appendChild(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;p.reducedMotion=h?.matches??!1;let m=e=>console.warn("Persona scroll icon failed",e),g=()=>({config:c,state:{...p},view:t,signal:d.signal}),f=()=>{d?.abort();try{l?.destroy?.()}catch(e){m(e)}l=void 0,d=void 0,o.innerHTML="",u=""},b=()=>{if(l?.element)return;let t=c.features?.scrollToBottom,r="generating-below"===p.activity&&"dots"===(t?.streamingIndicator??(c.future?.v5Defaults?"dots":"arrow")),n=r?"dots":`arrow:${t?.iconName??"arrow-down"}`;if(u!==n)if(u=n,o.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)}o.appendChild(e)}else{let r=e(t?.iconName??"arrow-down","14px","currentColor",2);r&&o.appendChild(r)}},y=e=>{let t=!1===c.features?.scrollToBottom?.enabled?void 0:c.features?.scrollToBottom?.renderIcon;if(t!==i){if(f(),i=t,i){d=new AbortController;try{let e=i(g());l=e&&"element"in e?e:e?{element:e}:void 0,l?.element&&o.appendChild(l.element)}catch(e){m(e),f()}}}else if(e&&l?.update)try{l.update(g())}catch(e){m(e),f()}b()},v=e=>Object.keys(e).some(t=>e[t]!==p[t]),w=e=>{let t=v(e);p=e,y(t)},x=()=>w({...p,hovered:!0}),C=()=>w({...p,hovered:!1}),S=()=>w({...p,focused:!0}),k=()=>w({...p,focused:!1}),A=()=>w({...p,reducedMotion:h?.matches??!1}),M=new AbortController;for(let[e,t]of[["mouseenter",x],["mouseleave",C],["focus",S],["blur",k]])n.addEventListener(e,t,{signal:M.signal});return h?.addEventListener?.("change",A),{element:n,update(e,t,o=!1,i=0){let l=c.features?.scrollToBottom,d=e.features?.scrollToBottom,u=c.future?.v5Defaults!==e.future?.v5Defaults||["enabled","iconName","label","streamingIndicator","transition","scrollBehavior","scrollDurationMs"].some(e=>l?.[e]!==d?.[e]);c=e;let h=c.features?.scrollToBottom;t&&=!1!==h?.enabled;let m=n.getRootNode().activeElement===n;n.setAttribute("data-persona-scroll-to-bottom-visible",String(t));let g=!1===h?.enabled?"none":h?.transition??(c.future?.v5Defaults?"fade":"none");n.setAttribute("data-persona-scroll-to-bottom-transition",g),o&&t?n.setAttribute("data-persona-scroll-to-bottom-streaming",""):n.removeAttribute("data-persona-scroll-to-bottom-streaming"),n.style.display=t||"none"!==g?"":"none",n.disabled=!t,n.tabIndex=t?0:-1,n.setAttribute("aria-hidden",String(!t)),!t&&m&&(n.blur(),r&&(r.hasAttribute("tabindex")||(r.tabIndex=-1),r.focus({preventScroll:!0})));let f=h?.label??"",b=f||"Jump to latest";n.setAttribute("aria-label",`${b}${i>0?` (${i} new)`:""}${o&&t?" (response streaming below)":""}`),n.title=f,n.setAttribute("data-persona-scroll-to-bottom-has-label",String(!!f)),a.textContent=f,a.style.display=f?"":"none",s.textContent=i>0?String(i):"",s.style.display=i>0?"":"none";let w={...p,visible:t,hovered:t&&p.hovered,focused:t&&p.focused,activity:o&&t?"generating-below":"idle"},x=u||v(w);p=w,y(x)},destroy(){f(),M.abort(),h?.removeEventListener?.("change",A),n.remove()}}}let er="webmcp:",tr=new Map,rr=e=>{tr.clear();for(let t of e){let e=t.title?.trim();e&&tr.set(t.name,e)}},nr=e=>tr.get(ir(e)),or=null;function ar(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`${sr(e,0).toString(36)}.${sr(e,2654435761).toString(36)}`}(t.join(""))}`}function sr(e,t){let r=3735928559^t,n=1103547991^t;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);r=Math.imul(r^o,2654435761),n=Math.imul(n^o,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)}let ir=e=>e.startsWith("webmcp:")?e.slice(7):e,lr=e=>e.startsWith(er),dr=()=>or?or():import("@mcp-b/webmcp-polyfill");function cr(e){return"webmcp"===e.toolType&&!e.executionId}function pr(e){let t=e.approval,r="pending"===t?.status&&cr(t),n=!1,o=t=>t.name&&lr(t.name)&&(n=!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?o(e.toolCall):void 0,s=e.tools?.map(o);return{...e,streaming:!n&&!r&&e.streaming,...r?{approval:{...t,status:"timeout",interrupted:!0}}:{},...a?{toolCall:a}:{},...s?{tools:s}:{},...n&&e.agentMetadata?.awaitingLocalTool?{agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}}:{}}}let ur=(e,t,r)=>{let n="transient"===t.mode,o=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=((e,t)=>!1!==e.visible&&("transient"!==e.mode||"connecting"===t||"paused"===t||"resuming"===t||"error"===t))(t,r)||n&&o&&!1!==t.visible?"":"none",e.classList.toggle("persona-mt-2",!n),e.classList.toggle("persona-mb-2",n)},hr=(e,t,r)=>{t.parentElement&&e.parentElement===t.parentElement&&("transient"===r.mode?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))},mr=/^\s*\|?[\s:|-]*-[\s:|-]*$/,gr=e=>e.includes("|"),fr=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())},br=e=>`| ${e.join(" | ")} |`,yr=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,vr=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),wr=e=>{if(!e||!e.includes("|"))return e;let t=e.split("\n"),r=!1;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1];if(!gr(n)||mr.test(n)||!mr.test(o))continue;let a=fr(n).length;if(a<1)continue;let s=yr(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()||!gr(e))break;let n=br(vr(fr(e),a));t[i]!==n&&(t[i]=n,r=!0)}e=i-1}return r?t.join("\n"):e},xr=(e,t)=>t?(at()?.stabilizeStreamingMarkdown??wr)(e):e,Cr=e=>{let t=null;return r=>{let n=at();if(!n)return Mr(r);if(!t){let{Marked:r}=n,o=e?.markedOptions;t=new r({gfm:o?.gfm??!0,breaks:o?.breaks??!0,pedantic:o?.pedantic,silent:o?.silent});let a=(e=>{if(!e)return;let t={},r=e;if(r.heading){let e=r.heading;t.heading=(t,r,n)=>e({type:"heading",raw:n,depth:r,text:t,tokens:[]})}if(r.code){let e=r.code;t.code=(t,r,n)=>e({type:"code",raw:"",text:t,lang:r,escaped:n})}if(r.blockquote){let e=r.blockquote;t.blockquote=t=>e({type:"blockquote",raw:"",text:t,tokens:[]})}if(r.table){let e=r.table;t.table=(t,r)=>e({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:t,bodyHtml:r})}if(r.link){let e=r.link;t.link=(t,r,n)=>e({type:"link",raw:"",href:t,title:r??null,text:n,tokens:[]})}if(r.image){let e=r.image;t.image=(t,r,n)=>e({type:"image",raw:"",href:t,title:r??null,text:n})}if(r.list){let e=r.list;t.list=(t,r,n)=>e({type:"list",raw:"",ordered:r,start:n,loose:!1,items:[],itemsHtml:t})}if(r.listitem){let e=r.listitem;t.listitem=(t,r,n)=>e({type:"list_item",raw:"",task:r,checked:n,loose:!1,text:t,tokens:[]})}if(r.paragraph){let e=r.paragraph;t.paragraph=t=>e({type:"paragraph",raw:"",text:t,tokens:[]})}if(r.codespan){let e=r.codespan;t.codespan=t=>e({type:"codespan",raw:"",text:t})}if(r.strong){let e=r.strong;t.strong=t=>e({type:"strong",raw:"",text:t,tokens:[]})}if(r.em){let e=r.em;t.em=t=>e({type:"em",raw:"",text:t,tokens:[]})}if(r.del){let e=r.del;t.del=t=>e({type:"del",raw:"",text:t,tokens:[]})}if(r.html){let e=r.html;t.html=t=>e({type:"html",raw:t,text:t})}if(r.text){let e=r.text;t.text=t=>e({type:"text",raw:t,text:t})}if(r.checkbox){let e=r.checkbox;t.checkbox=t=>e({checked:t})}return r.hr&&(t.hr=r.hr),r.br&&(t.br=r.br),t})(e?.renderer);a&&t.use({renderer:a})}return t.parse(r)}},Sr=e=>e?Cr({markedOptions:e.options,renderer:e.renderer}):Cr(),kr=Cr(),Ar=e=>kr(e),Mr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Ir=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Tr=e=>`%%FORM_PLACEHOLDER_${e}%%`,Er=(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=Tr(t.length);return t.push({token:r,type:String(e.type)}),r}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,r)=>{let n=Tr(t.length);return t.push({token:n,type:r}),n}),r},Lr={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(".")},Br=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Rr=()=>{let e=null;return t=>{let r=at();if(!r)return Mr(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:")&&!Br.test(e)&&(t.attrValue="",t.keepAttr=!1)}})}return e.sanitize(t,Lr)}},Pr=e=>!1===e?null:"function"==typeof e?e:Rr(),Nr="var(--persona-md-table-scroll-fade, 24px)",$r=new WeakSet;function Wr(e){let t=e.scrollWidth-e.clientWidth;if(t<=1)return void e.removeAttribute("data-persona-scroll-x");e.setAttribute("data-persona-scroll-x","");let r="rtl"===getComputedStyle(e).direction?t+e.scrollLeft:e.scrollLeft,n=t-r;e.style.setProperty("--persona-fade-l",r<=1?"0px":Nr),e.style.setProperty("--persona-fade-r",n<=1?"0px":Nr)}function Hr(e){$r.has(e)||($r.add(e),e.addEventListener("scroll",e=>{let t=e.target;t?.classList?.contains("persona-table-scroll")&&Wr(t)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Wr)}let{setLoader:Dr,load:Or,provide:Fr,getSync:zr}=_({fallbackImport:()=>import("./client-stream")}),jr=Dr,qr=Or,_r=zr,{setLoader:Ur,load:Vr,provide:Kr,getSync:Qr}=_({fallbackImport:()=>import("./client-dispatch")}),Jr=Ur,Gr=Vr,Yr=Qr,{setLoader:Xr,load:Zr}=_({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),en=Xr,tn=Zr,{setLoader:rn,load:nn}=_({fallbackImport:()=>import("@runtypelabs/persona/voice-client-tools")}),on=rn,an=nn;function sn(e){return e.startsWith("agent_")?{kind:"agentId",agentId:e}:e.startsWith("flow_")?{kind:"flowId",flowId:e}:null}function ln(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function dn(){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=>{var r,n,o=e&&e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),a=e&&e.__exportStar||function(e,t){for(var r in e)"default"!==r&&!Object.prototype.hasOwnProperty.call(t,r)&&o(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let s=t();function i(e,t=s.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return l(e.trim(),t)}Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return s.Allow}}),a(t(),e),r=class extends Error{},e.PartialJSON=r,n=class extends Error{},e.MalformedJSON=n,e.parseJSON=i;let l=(e,t)=>{let o=e.length,a=0,i=e=>{throw new r(`${e} at position ${a}`)},l=e=>{throw new n(`${e} at position ${a}`)},d=()=>(m(),a>=o&&i("Unexpected end of input"),'"'===e[a]?c():"{"===e[a]?p():"["===e[a]?u():"null"===e.substring(a,a+4)||s.Allow.NULL&t&&o-a<4&&"null".startsWith(e.substring(a))?(a+=4,null):"true"===e.substring(a,a+4)||s.Allow.BOOL&t&&o-a<4&&"true".startsWith(e.substring(a))?(a+=4,!0):"false"===e.substring(a,a+5)||s.Allow.BOOL&t&&o-a<5&&"false".startsWith(e.substring(a))?(a+=5,!1):"Infinity"===e.substring(a,a+8)||s.Allow.INFINITY&t&&o-a<8&&"Infinity".startsWith(e.substring(a))?(a+=8,1/0):"-Infinity"===e.substring(a,a+9)||s.Allow._INFINITY&t&&1<o-a&&o-a<9&&"-Infinity".startsWith(e.substring(a))?(a+=9,-1/0):"NaN"===e.substring(a,a+3)||s.Allow.NAN&t&&o-a<3&&"NaN".startsWith(e.substring(a))?(a+=3,NaN):h()),c=()=>{let r=a,n=!1;for(a++;a<o&&('"'!==e[a]||n&&"\\"===e[a-1]);)n="\\"===e[a]&&!n,a++;if('"'==e.charAt(a))try{return JSON.parse(e.substring(r,++a-Number(n)))}catch(e){l(String(e))}else if(s.Allow.STR&t)try{return JSON.parse(e.substring(r,a-Number(n))+'"')}catch{return JSON.parse(e.substring(r,e.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},p=()=>{a++,m();let r={};try{for(;"}"!==e[a];){if(m(),a>=o&&s.Allow.OBJ&t)return r;let n=c();m(),a++;try{r[n]=d()}catch(e){if(s.Allow.OBJ&t)return r;throw e}m(),","===e[a]&&a++}}catch{if(s.Allow.OBJ&t)return r;i("Expected '}' at end of object")}return a++,r},u=()=>{a++;let r=[];try{for(;"]"!==e[a];)r.push(d()),m(),","===e[a]&&a++}catch{if(s.Allow.ARR&t)return r;i("Expected ']' at end of array")}return a++,r},h=()=>{if(0===a){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(s.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(r))}}let r=a;for("-"===e[a]&&a++;e[a]&&-1===",]}".indexOf(e[a]);)a++;a==o&&!(s.Allow.NUM&t)&&i("Unterminated number literal");try{return JSON.parse(e.substring(r,a))}catch{"-"===e.substring(r,a)&&i("Not sure what '-' is");try{return JSON.parse(e.substring(r,e.lastIndexOf("e")))}catch(e){l(String(e))}}},m=()=>{for(;a<o&&" \n\r\t".includes(e[a]);)a++};return d()};e.parse=i})();let cn="ask_user_question",pn="data-persona-ask-sheet-for",un="Type your own answer here",hn="Send",mn="data-ask-question-count",gn="data-ask-answers",fn="data-ask-grouped",bn=!1,yn=e=>e.replace(/["\\]/g,"\\$&"),vn=e=>"tool"===e.variant&&!!e.toolCall&&"ask_user_question"===e.toolCall.name,wn=e=>e?.features?.askUserQuestion??{},xn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n="complete"===t.status;if(t.args&&"object"==typeof t.args)return{payload:t.args,complete:n};let o=t.chunks;if(!o||0===o.length)return{payload:null,complete:n};try{let e=o.join(""),t=(0,r.parse)(e,r.STR|r.OBJ|r.ARR);if(t&&"object"==typeof t)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},Cn=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!bn&&(bn=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Sn={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"},kn=(e,t)=>{Object.entries(Sn).forEach(([r,n])=>{let o=z(t,`features.askUserQuestion.styles.${r}`);"string"==typeof o&&o?e.style.setProperty(n,o):e.style.removeProperty(n)})},An=(e,t,r)=>{if("rows"!==e)return null;let n=st("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let e=st("span","persona-ask-row-check");n.appendChild(e)}else{let e=st("span","persona-ask-row-badge");e.textContent=String(r+1),n.appendChild(e)}return n},Mn=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},In=(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 n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=e.freeTextPlaceholder??un,n.setAttribute("data-ask-free-text-input","true"),r.appendChild(n),"rows"!==t){let t=st("button","persona-ask-free-text-submit persona-pointer-events-auto");t.type="button",t.textContent=e.submitLabel??hn,t.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(t)}return r},Tn=e=>{let t=e.getAttribute(gn);if(!t)return{};try{let e=JSON.parse(t);return e&&"object"==typeof e?e:{}}catch{return{}}},En=e=>{let t=Number(e.getAttribute("data-ask-current-index")??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ln=e=>{let t=Number(e.getAttribute("data-ask-question-count")??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Bn=e=>"true"===e.getAttribute(fn),Rn=(e,t,r)=>{let n=wn(r),o=(e=>"pills"===e.getAttribute("data-ask-layout")?"pills":"rows")(e),{payload:a,complete:s}=xn(t),i=Bn(e),l=En(e),d=Ln(e),c=i?((e,t)=>Cn(e)[t]??null)(a,l):(e=>Cn(e)[0]??null)(a),p=!!c?.multiSelect,u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${l+1}/${d}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let m=e.querySelector('[data-ask-question="true"]');if(m){let e="string"==typeof c?.question?c.question:"";m.textContent=e,m.classList.toggle("persona-ask-question-skeleton",!e&&!s)}let g=e.querySelector('[data-ask-pill-list="true"]');if(g){let e=((e,t,r,n)=>{let o=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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&"string"==typeof e.label&&e.label.length>0);if(0===s.length&&!r){for(let e=0;e<3;e++)o.appendChild(Mn(n));return o}if(s.forEach((e,t)=>{o.appendChild(((e,t,r,n)=>{let o=st("button","rows"===r?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",n?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),"rows"===r){let a=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)}o.appendChild(a);let i=An(r,n,t);i&&o.appendChild(i)}else o.textContent=e.label,e.description&&(o.title=e.description);return o})(e,t,n,a))}),!1!==e?.allowFreeText){let e="rows"===n?"Other":"Other…";if("rows"===n){let r=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??un,l.setAttribute("data-ask-free-text-input","true"),l.setAttribute("aria-label",t.freeTextLabel??e),i.appendChild(l),r.appendChild(i);let d=An(n,a,s.length);d&&r.appendChild(d),o.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,o.appendChild(r)}}return o})(c,n,s,o);g.replaceWith(e)}if("rows"!==o){let t=e.querySelector('[data-ask-free-text-row="true"]');t&&t.replaceWith(In(n,o))}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??hn,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t})(n)),e.setAttribute("data-multi-select",p?"true":"false");let b=e.querySelector('[data-ask-nav-row="true"]');if(i){let t=((e,t,r)=>{let n=st("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let o=st("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=r.backLabel??"Back",o.setAttribute("data-ask-user-action","back"),o.disabled=0===e,n.appendChild(o);let a=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),n.appendChild(a),n})(l,d,n);b?b.replaceWith(t):e.appendChild(t)}else b&&b.remove();(e=>{let t=Tn(e)[En(e)],r=new Set;"string"==typeof t?r.add(t):Array.isArray(t)&&t.forEach(e=>r.add(e));let n=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');n.forEach(e=>{let t=e.getAttribute("data-option-label")??"",n=r.has(t);e.setAttribute("aria-pressed",n?"true":"false"),e.classList.toggle("persona-ask-pill-selected",n)});let o=new Set(Array.from(n).map(e=>e.getAttribute("data-option-label")??"")),a=e.querySelector('[data-ask-free-text-input="true"]');a&&("string"==typeof t&&t.length>0&&!o.has(t)?(a.value=t,a.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):a.value="")})(e),(e=>{if(!Bn(e))return;let t=Tn(e)[En(e)],r="string"==typeof t&&t.length>0||Array.isArray(t)&&t.length>0,n=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');n&&(n.disabled=!r);let o=e.querySelector('[data-ask-user-action="submit-multi"]');o&&(o.disabled=0===Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).length)})(e)},Pn=(e,t,r)=>{if(!r||!vn(e)||!1===wn(t).enabled)return;let n=e.toolCall.id;r.querySelectorAll(`[${pn}]`).forEach(e=>{e.getAttribute(pn)!==n&&e.remove()});let o=r.querySelector(`[${pn}="${yn(n)}"]`);if(o)return void((e,t,r)=>{kn(e,r);let{payload:n}=xn(t),o=Math.max(1,Cn(n).length);o>Ln(e)&&(e.setAttribute(mn,String(o)),o>1&&!Bn(e)&&e.setAttribute(fn,"true")),Rn(e,t,r)})(o,e,t);let{payload:a}=xn(e),s=((e,t,r)=>{let n=wn(t),o=(e=>"pills"===e.layout?"pills":"rows")(n),a=e.toolCall.id,s=Cn(r),i=Math.max(1,s.length),l=i>1,d=((e,t)=>{let r=e.agentMetadata?.askUserQuestionAnswers;if(!r||"object"!=typeof r)return{};let n={};return t.forEach((e,t)=>{let o="string"==typeof e?.question?e.question:"";if(o&&Object.prototype.hasOwnProperty.call(r,o)){let e=r[o];("string"==typeof e||Array.isArray(e))&&(n[t]=e)}}),n})(e,s),c=l?((e,t)=>{let r=e.agentMetadata?.askUserQuestionIndex;return"number"==typeof r&&Number.isFinite(r)?Math.max(0,Math.min(t-1,Math.floor(r))):0})(e,i):0,p=st("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(pn,a),p.setAttribute("data-tool-call-id",a),p.setAttribute("data-message-id",e.id),p.setAttribute(mn,String(i)),p.setAttribute("data-ask-current-index",String(c)),p.setAttribute(fn,l?"true":"false"),p.setAttribute("data-ask-layout",o),((e,t)=>{e.setAttribute(gn,JSON.stringify(t))})(p,d),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),void 0!==n.slideInMs&&p.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),kn(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"===o?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return g.setAttribute("data-ask-pill-list","true"),g.setAttribute("role","group"),p.appendChild(g),"rows"!==o&&p.appendChild(In(n,o)),Rn(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p})(e,t,a);r.appendChild(s)},Nn=(e,t)=>{if(!e)return;let r=t?`[${pn}="${yn(t)}"]`:`[${pn}]`;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)})},$n="suggest_replies",Wn={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},Hn={name:$n,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:Wn,origin:"sdk",annotations:{readOnlyHint:!0}},Dn=e=>"tool"===e.variant&&"suggest_replies"===e.toolCall?.name,On=(e,t=4)=>{let r=e;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}let n=r?.suggestions;if(!Array.isArray(n))return[];let o=n.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 o.length>t?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of ${t}; extra suggestions dropped.`),o.slice(0,t)):o},Fn=(e,t=4)=>{for(let r=e.length-1;r>=0;r--){let n=e[r];if("user"===n.role)return null;if(!Dn(n))continue;let o=On(n.toolCall?.args,t);return o.length>0?o:null}return null},zn=new Set,jn=e=>{let t=e?.suggestions?.followUps,r=e?.features?.suggestReplies,n=e=>{let n=t?.[e],o=r?.[e];void 0!==n&&void 0!==o&&n!==o&&((e,t,r)=>{let n=`${e}:${t}:${r}`;zn.has(n)||(zn.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))})(e,o,n)};e&&(n("enabled"),n("expose"));let o=t?.enabled??r?.enabled??!0;return{enabled:o,expose:!!o&&(t?.expose??r?.expose??!1)}},qn={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},_n={name:cn,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:qn,origin:"sdk",annotations:{readOnlyHint:!0}},Un=e=>{let t=[],r=e?.features?.askUserQuestion;return!0===r?.expose&&!1!==r.enabled&&t.push(_n),jn(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?Hn:{...Hn,parametersSchema:{...Wn,properties:{suggestions:{...Wn.properties.suggestions,maxItems:r,description:`1-${r} short, distinct follow-up replies, phrased in the user's voice.`}}}}})(e)),t},Vn=e=>e.replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Kn=()=>({processChunk:()=>null,getExtractedText:()=>null,__isPlainTextParser:!0}),Qn=()=>(()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:async r=>{let n=r.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(r.length<=t)return null===e?null:{text:e,raw:r};let o=(e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/)?.[1]||e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/)?.[1];if(!t)return null;try{return Vn(t)}catch{return t}})(r);return null!==o&&(e=o),t=r.length,null===e?null:{text:e,raw:r}},close:async()=>{}}})(),Jn=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return null!==e||""===e?{text:e||"",raw:n}:null;try{let t=(0,r.parse)(n,r.STR|r.OBJ);t&&"object"==typeof t&&(t.component&&"string"==typeof t.component?e="string"==typeof t.text?Vn(t.text):"":"init"===t.type&&t.form?e="":"string"==typeof t.text&&(e=Vn(t.text)))}catch{}return t=n.length,null===e?null:{text:e,raw:n}},close:()=>{}}},Gn=()=>{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}},Yn="4.32.2",{setLoader:Xn,load:Zn,provide:eo}=_({fallbackImport:()=>import("./client-history")}),to=Xn,ro=Zn;n=class extends Error{constructor(e,t,r){super(t),this.name="HistoryClientError",this.code=e,void 0!==r?.retryAfterSeconds&&(this.retryAfterSeconds=r.retryAfterSeconds)}};let no=e=>"reason"in e?e.reason:void 0;o=class{#e;#t;#r;#n;#o;#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.#o=e,this.#n=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":Yn,...e.headers},this.#r=!!e.debug,this.#a=e.streamParser??function(e){switch(e){case"json":return Jn;case"regex-json":return Qn;case"xml":return Gn;default:return Kn}}(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 tn().then(t=>{let r=new t.WebMcpBridge(e,{recordToolDisplayTitles:rr,getToolDisplayTitle:nr,loadPolyfill:dr});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.#o.webmcp?.enabled?(this.#k||=this.#T(this.#o.webmcp),this.#k):Promise.resolve(null)}updateConfig(e){this.#o=e}setHistoryInternals(e){this.#n=e}cancelStreams(){if(this.#u+=1,this.#o.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.#o.webmcp?.enabled)return null;let e=()=>this.#E(),t={open:async e=>(await an()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await((await e())?.snapshotForDispatch())??[];return{tools:t,fingerprint:ar(t)}},onChange:t=>{let r=null,n=!1;return e().then(e=>{e&&!n&&(r=e.watchToolChanges(t))}),()=>{n=!0,r?.()}},execute:async(t,r,n)=>{let o=await e();return o?o.executeVoiceToolCall(t,r,n):{status:"failed",error:{message:"WebMCP runtime failed to load."}}}};return t}executeWebMcpToolCall(e,t,r,n){return!0===this.#o.webmcp?.enabled?this.#E().then(o=>o?o.executeToolCall(e,t,r,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]}):null}getSSEEventCallback(){return this.#p}isClientTokenMode(){return!!this.#o.clientToken}#L(){let{agentId:e,flowId:t,target:r,targetProviders:n}=this.#o;if(!r)return{agentId:e,flowId:t};let o=function(e,t){let r=e.trim();if(!r)throw Error("[Persona] `target` is empty.");let n=r.indexOf(":");if(n>0){let e=r.slice(0,n),o=r.slice(n+1);if("runtype"===e){let e=sn(o);if(e)return e;throw Error(`[Persona] target "runtype:${o}" 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(o).payload}}let o=sn(r);if(o)return o;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,n);return"agentId"===o.kind?{agentId:o.agentId}:"flowId"===o.kind?{flowId:o.flowId}:{targetPayload:o.payload}}isAgentMode(){return!(!this.#o.agent&&!this.#L().agentId)}#B(){return this.#o.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 o=t.conversationId,a=await this.readVisitorToken();if(!0!==t.durableRecovery?.enabled||!o||!a)throw new n("visitor_token_missing","Durable recovery is not enabled for this client session");let s=`${this.#B()}/v1/client/conversations/${encodeURIComponent(o)}/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":Yn,"X-Visitor-Token":a},signal:e.signal});if(401!==l.status||r){if(!l.ok)throw await(await ro()).historyErrorFor(this.#P(),l,!0);return l}{r=!0;let e=await ro();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.#o.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#g===e&&(this.#g=null)});return e}#$(){return!0===this.#o.features?.history?.enabled&&this.isClientTokenMode()&&!this.#y}async readVisitorToken(){let e=this.#n.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.#n.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.#o.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.#o.features?.history?.scope?{state:"browser_only",reason:"configured_browser_scope"}:this.#o.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&&no(t)===no(e);if(this.#x=e,!r){this.#n.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#C])t(e)}}async#z(e){return new((Yr()??await Gr()).ClientDispatch)(this.#j()).createClientSession(e)}async#N(){return new((Yr()??await Gr()).ClientDispatch)(this.#j()).initializeSession()}async#q(e){let t=this.#o.getStoredSessionId?.()||null,r=this.#o.getStoredConversationId?.()||null,n=await this.#z({storedSessionId:t,identityProof:e}),o=this.#_(n,r,!1);return this.clientSession=o,this.#g=null,this.#f=!1,this.resetClientToolsFingerprint(),o}#_(e,t,r){let n=e.conversationId;return n&&t&&(r||n!==t)&&this.#n.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:n}),this.#o.setStoredSessionId?.(e.sessionId),n&&(this.#o.setStoredConversationId?.(n),this.#n.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 n("history_disabled","Visitor history is disabled for this surface");await this.#n.historyBootstrapReady;let r=t?.proof??null;if(!await this.readVisitorToken()&&!r)throw new n("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let o=await this.#z({conversationId:e,identityProof:r});return this.#U(o)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error("prepareNewConversationSession() only available in client token mode");await this.#n.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((Yr()??await Gr()).ClientDispatch)(this.#j()).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.#o.identityProvider;if(void 0===t)return;let r,n,o=this.#o.getIdentityProof;if(!t.trim()||!o)throw Error("Chat identity requires identityProvider and getIdentityProof.");try{let t=Promise.resolve().then(()=>o());r=e?await Promise.race([t,new Promise((t,r)=>{n=()=>r(e.reason),e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})]):await t}catch{throw e?.throwIfAborted(),Error("The identity proof provider failed.")}finally{n&&e?.removeEventListener("abort",n)}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.#o},headers:this.#t,getHeaders:this.#c,debug:this.#r,clientApiBase:()=>e.#B(),getClientApiUrl:t=>e.#R(t),getWebMcpBridge:()=>e.#E(),sendWithClientToolsDiff:(t,r,n,o)=>e.#Q(t,r,n,o),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#I;#P(){let e=this;return this.#I??={HistoryClientError:n,get config(){return e.#o},get historyInternals(){return e.#n},get clientSession(){return e.clientSession},clientApiBase:()=>e.#B(),setHistoryIdentityStatus:t=>e.#H(t),browserOnlyStatus:()=>e.#O(),derivedBrowserOnly:()=>e.#F(),reinitWithProof:t=>e.#q(t),isHistoryCapable:()=>e.#$(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await ro()).listConversations(this.#P(),e)}async getConversation(e,t){return(await ro()).getConversation(this.#P(),e,t)}async finalizeDisplayProjections(e,t){return(await ro()).finalizeDisplayProjections(this.#P(),e,t)}async deleteConversation(e,t){return(await ro()).deleteConversation(this.#P(),e,t)}async deleteAllConversations(e){return(await ro()).deleteAllConversations(this.#P(),e)}async resetVisitor(){return(await ro()).resetVisitor(this.#P())}async dispatch(e,t){e.signal?.throwIfAborted(),qr().catch(()=>{});let r=this.isClientTokenMode(),n=this.isAgentMode(),o=`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`;r&&(this.#m=o),t({type:"status",status:"connecting"});let a=Yr()??await Gr().catch(e=>{let n=e instanceof Error?e:Error(String(e));throw(!r||this.#m===o)&&t({type:"error",error:n}),n});if(e.signal?.throwIfAborted(),r&&this.#m!==o)throw new DOMException("Turn superseded","AbortError");let s=new a.ClientDispatch(this.#j());return r?s.dispatchClientToken(e,t,o):n?s.dispatchAgent(e,t):s.dispatchProxy(e,t)}#j(){let e=this;return Object.setPrototypeOf({HistoryClientError:n,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.#n},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,n)=>e.#_(t,r,n),resetSessionWarmLatch:()=>{e.#f=!1},resetClientToolsFingerprint:()=>e.resetClientToolsFingerprint(),clearClientSession:()=>e.clearClientSession(),resolveChatIdentityProof:t=>e.#V(t),routing:()=>e.#L(),builtInClientTools:Un,streamResponse:(...t)=>e.#J(...t)},this.#K())}async processStream(e,t,r,n,o,a,s){t({type:"status",status:"connected"});try{await this.#J(e,t,r,n,o,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,n){return new((Yr()??await Gr()).ClientDispatch)(this.#j()).sendWithClientToolsDiff(e,t,r,n)}async resumeFlow(e,t,r){return(await qr()).resumeFlow(this.#K(),e,t,r)}async#J(e,t,r,n,o,a,s){let{streamResponse:i}=_r()??await qr();return i({config:()=>this.#o,streamGeneration:()=>this.#u,streamReaders:this.#h,createStreamParser:this.#a,parseSSEEvent:this.#d,onSSEEvent:(e,t)=>this.#p?.(e,t)},e,t,r,n,o,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:oo,load:ao}=_({fallbackImport:()=>import("@runtypelabs/persona/background-runtime")}),so=oo,io=ao,{setLoader:lo,load:co,provide:po,getSync:uo}=_({fallbackImport:()=>import("./session-actions")}),ho=lo,mo=co,go=uo;function fo(e){return"string"!=typeof e&&e.some(e=>"image"===e.type)}function bo(e){return{type:"text",text:e}}let yo=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vo=[...yo,"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 wo(e){return function(e){return yo.includes(e)||e.startsWith("image/")}(e.type)}function xo(e,t=vo,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 Co(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 So=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function ko(e){return"card"===e?"collapsed":e}function Ao(e){return e.split(";",1)[0].trim().toLowerCase()}function Mo(e,t){let r=e?.display,n="string"==typeof r?{default:r}:r??{};if(t.file&&n.files){if("string"==typeof n.files)return{mode:ko(n.files),matchedBy:{type:"files"}};let e=t.file.mimeType?Ao(t.file.mimeType):void 0,r=e?function(e,t){if(!e)return;let r=Object.entries(e);for(let[e,n]of r)if(Ao(e)===t)return{mode:ko(n),selector:Ao(e)};let n=`${t.split("/",1)[0]}/*`;for(let[e,t]of r)if(Ao(e)===n)return{mode:ko(t),selector:n}}(n.files.byMediaType,e):void 0;if(e&&r)return{mode:r.mode,matchedBy:{type:"mediaType",mediaType:e,selector:r.selector}};if(n.files.default)return{mode:ko(n.files.default),matchedBy:{type:"files"}}}let o=n.byKind?.[t.artifactType];if(o)return{mode:ko(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:ko(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:ko(s),matchedBy:{type:"preferredMode"}}:n.default?{mode:ko(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Io(e,t){return Mo(e,t).mode}function To(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 Eo(e,t=140){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}…`}function Lo(e,t){let r=e.findIndex(e=>e.id===t);if(r<=0)return null;for(let t=r-1;t>=0;--t)if("user"===e[t].role)return e[t].id;return null}function Bo(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 Ro(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let 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)(n,r.STR|r.OBJ),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Po(e,t){let{config:r,message:n,onPropsUpdate:o}=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:n,config:r,signal:t.signal??(new AbortController).signal,updateProps:e=>{o&&o(e)}};try{return a(e.props,s)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function No(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 $o(e){let t=No(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 Wo(e){let t=No(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 Ho(e){let t=e.content;if("string"!=typeof t||""===t)return;let r=e.contentParts??e.llmContent??e.rawContent??t;return"string"!=typeof r||r!==t?t:void 0}function Do(e,t){let r=new Map;for(let t of e)r.set(t.id,t);for(let e of t)r.set(e.id,e);return[...r.values()].sort((e,t)=>{let r=new Date(e.createdAt).getTime(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a})}function Oo(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 Fo(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 n=window.speechSynthesis;n.cancel();let o=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(o.voice=e)}else a.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(a):Oo(a));void 0!==t.rate&&(o.rate=t.rate),void 0!==t.pitch&&(o.pitch=t.pitch),o.onend=()=>r.onEnd?.(),o.onerror=e=>{let t=e.error;"canceled"===t||"interrupted"===t?r.onEnd?.():r.onError?.(Error(t||"Speech synthesis failed"))},setTimeout(()=>{n.speak(o),r.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},i=class{#e=null;#t=null;#r="idle";#n=new Set;#o=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.#n.add(e),()=>this.#n.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.#o;this.#e?.stop(),this.#s(e,"loading");try{if(!this.#e){let e=await this.#a();if(r!==this.#o)return;if(!e)return void this.#s(null,"idle");this.#e=e}this.#e.speak(t,{onStart:()=>{r===this.#o&&this.#s(e,"playing")},onEnd:()=>{r===this.#o&&this.#s(null,"idle")},onError:()=>{r===this.#o&&this.#s(null,"idle")}})}catch{r===this.#o&&this.#s(null,"idle")}}stop(){this.#o++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#s(e,t){this.#t="idle"===t?null:e,this.#r=t;for(let e of this.#n)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 zo=null,jo=()=>zo?zo():import("./voice/runtype-tts-entry"),{setLoader:qo,load:_o}=_({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Uo=qo,Vo=_o,Ko="apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId".split(".");function Qo(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 n=r.message.trim(),o=/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.?)$/i.test(n),a=/^(Chat backend|Agent execution) request failed: \d{3}\b/.test(n),s=o?"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 n?`${s}\n\n_Details: ${n}_`:s}d=class extends Error{constructor(e,t){super(t),this.name="SessionHistoryError",this.code=e}};let Jo=e=>lr(e)||"suggest_replies"===e;c=class e{#e;#t;#r;#n;#o(e){if(this.#a("cancel"),this.#r=!1,this.#e={runId:`run-${dn()}`,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.#n&&clearTimeout(this.#n),this.#n=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.#n)return;let e=this.#e;this.#n=setTimeout(()=>{this.#n=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;#q;#_;#U;#V;#M;#K;#I;#P;#j;#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.#n=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.#q=null,this.#_=new Map,this.#U=null,this.#V=new Map,this.#M=null,this.#K=null,this.#I=!1,this.#P=null,this.#j=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.#ne()),this.#oe=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,n=!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),n=!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"),n&&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)&&mo().catch(()=>{});let o=e.message.toolCall,a=!!o?.name&&(lr(o.name)||"suggest_replies"===o.name&&jn(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=>({...pr(e),sequence:e.sequence??this.#ve()})),this.messages=this.#we(this.messages),this.client=new o(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&&jt().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&&jo().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;#ne(){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,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,o=this.config.clientToken,a=!1!==e.browserFallback;if(r&&n&&o)return jo().then(({RuntypeSpeechEngine:s,FallbackSpeechEngine:i})=>{let l=new s({host:r,agentId:n,clientToken:o,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new i(l,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):l});if(a&&t)return o&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error("Voice configuration not provided");this.cleanupVoice();let r=this.#ee,n=++this.#A;this.#k=jt().then(async e=>{await r,n===this.#A&&this.#Me(e,e.createVoiceProvider(t))}).catch(e=>{console.error("Failed to setup voice:",e)}).finally(()=>{n===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],n={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(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return!!e&&new Date<e.expiresAt}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){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.#j=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,n=this.config.getIdentityProof?"verified-user":"browser",o=r??(t.capabilities.scopes.includes(n)?n:t.capabilities.scopes[0]??n);if(!t.capabilities.scopes.includes(o))throw new a("unsupported_scope","This history scope is not supported.");return{scope:o}}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.#q;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 n=this.#We(t?.scope),o=++this.#W,a=this.#D;if("background"===t?.busy&&await this.#Fe(),await this.awaitHistorySettled(),o!==this.#W)throw new d("superseded","A later selection won");let s=await r.getPage(e,{context:n});if(o!==this.#W)throw new d("superseded","A later selection won");let i=await r.prepareOpen(e,{context:n}),l=this.#F.then(async()=>{if(o!==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 n=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&&n&&this.#c){let e={conversationId:n,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.#je();for(let e of s.messages)this.#V.set(e.id,e.content);this.#qe();let o=this.#g?.take(this.#B);return this.hydrateMessages(o?.messages??s.messages),o&&(this.hydrateArtifacts(o.artifacts,o.selectedArtifactId,!0),this.#_e(o)),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===n)for(let{event:t,readOnlyReplay:r}of e)this.handleEvent(t,r)}}),c=l.then(()=>{},()=>{});this.#F=c,this.#q=c;try{return await l}finally{this.#q===c&&(this.#q=null)}}loadOlderMessages(e,t,r){let n=this.#$e(),o=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(n,e,a,o).finally(()=>{this.#_.delete(s)});return this.#_.set(s,l),l}async#Ue(e,t,r,n){let o=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:r,...o?{beforeCreatedAt:o}:{},context:n});if(this.#B&&this.#B!==t)return{messages:[],nextMessageCursor:a.nextCursor};let s=this.#Ve(a.messages),i=Do(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&&cr(r.approval)&&r.approval.id===e.approval?.id&&"pending"!==r.approval.status&&"pending"===e.approval?.status)return r;let t=r.agentMetadata?.executionId,n=[...r.toolCall?[r.toolCall]:[],...r.tools??[]];if(t&&n.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return r}return pr(e)})}async startNewConversation(e){let t=this.#$e(),r=this.#We(e?.scope),n=++this.#W,o=this.#D;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:r}),s=this.#F.then(async()=>{if(n!==this.#W)throw a.discard(),new d("superseded","A later action won");e?.onBeforeCommit?.(),this.#H=!0,this.#O=o;try{await this.#ze(a)}finally{this.#H=!1,this.#O=null}if(o!==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.#qe(),this.clientSession&&this.#Le(this.clientSession),e?.onCommitted?.(),this.#He()}),i=s.then(()=>{},()=>{});this.#F=i,this.#q=i;try{await s}finally{this.#q===i&&(this.#q=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.#qe(),this.#He()}async deleteConversation(e,t){let r=this.#$e(),n=this.#We(t?.scope);await this.awaitHistorySettled(),await r.delete(e,{context:n}),this.#g?.clear(e),e===this.#B&&await this.#Ge(n)}async updateConversation(e,t,r){let n=this.#$e();if(!n.update)throw new d("history_unavailable","This history provider cannot update conversations");let o=this.#We(r?.scope);return await this.awaitHistorySettled(),n.update(e,t,{context:o})}canUpdateConversations(){return"function"==typeof this.#Ne?.update}async clearConversationHistory(e){let t=this.#$e(),r=this.#We(e?.scope);await this.awaitHistorySettled();let n=await t.deleteAll({...void 0===e?.targetId?{}:{targetId:e.targetId},context:r});return this.#Re(),await this.#Ge(r),n}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))}#qe(){this.#B?this.config.setStoredConversationId?.(this.#B):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#R),this.historyInternals.setStoredMessageCursor?.(this.#$)}#je(){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.#je(),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.#q=Promise.resolve().then(()=>{this.#N=!1,this.#q=null,this.#He()})}#xe(){let e=this.historyInternals.visitorStore??null;e!==this.#j&&(this.#P?.(),this.#P=null,this.#j=e,e&&(this.#P=e.subscribe(e=>this.#nt(e))))}#nt(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.")}#ot(){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 n=this.#We(e?.scope);this.#N=!0,this.#He();let o=this.#st(t,r,n).finally(()=>{this.#N=null!==this.#z,this.#q===o&&(this.#q=null),this.#He()});return this.#q=o,o}async#st(e,t,r){this.#B=t;let n=this.clientSession?.conversationRevision??this.#R??null,o=this.#I?this.#K:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#I=!1,this.#$=this.historyInternals.getStoredMessageCursor?.()??this.#$,await this.replayPendingProjections(),n&&o&&n===o)return void(this.#R=n);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=Do(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||n||null,this.#V.clear();for(let e of s.messages)this.#V.set(e.id,e.content);this.#qe(),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=Ho(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=Ho(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 o=t.filter(e=>this.#V.get(e.id)!==e.displayContent);if(0===o.length)this.#ut(e,t);else try{let{conversationRevision:r}=await this.client.finalizeDisplayProjections(e,o);for(let e of o)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,o,!0);if(a instanceof n&&("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 n?"request_failed"===e.code:e instanceof Error}#ut(e,t){let r=this.#lt();if(!r||r.conversationId!==e)return;let n=new Set(t.map(e=>e.id)),o=r.messageIds.filter(e=>!n.has(e));this.#et(o.length?{conversationId:e,messageIds:o}: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.#ot(),"new_conversation_required"===this.#z&&await this.#Xe()}static#gt(e){return e instanceof n&&"conversation_deleted"===e.code}async#ft(t,r,n,o,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:n,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(o);if(!l)throw t;this.#dt([l]),await this.client.dispatch({messages:[l],signal:r.signal,assistantMessageId:n,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},n=function(e,t){let r=e.voiceRecognition,n=t.voiceRecognition;return!0===r?.enabled!=(!0===n?.enabled)||r?.provider?.type!==n?.provider?.type||r?.provider?.custom!==n?.provider?.custom||Ut(e)!==Ut(t)||r?.provider?.runtype?.createPlaybackEngine!==n?.provider?.runtype?.createPlaybackEngine||JSON.stringify(r?.provider?.runtype)!==JSON.stringify(n?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}(this.config,r),a=function(e,t){return Ko.some(r=>e[r]!==t[r])}(this.config,r);a&&(this.cancel(),this.#Re()),this.config=r,n&&(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 o(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:n,contentParts:o,id:a,createdAt:s,sequence:i,streaming:l=!1,voiceProcessing:d,voiceCaption:c,rawContent:p}=e;return{id:a??("user"===t?ln():"assistant"===t?dn():`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!==n&&{llmContent:n},...void 0!==o&&{contentParts:o},...void 0!==d&&{voiceProcessing:d},...c&&{voiceCaption:c},...void 0!==p&&{rawContent:p},...void 0!==e.dispatchError&&{dispatchError:e.dispatchError}}}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:n="",llmContent:o,id:a,createdAt:s,sequence:i}=e,l={text:n,component:t,props:r};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...void 0!==o&&{llmContent:o},...void 0!==a&&{id:a},...void 0!==s&&{createdAt:s},...void 0!==i&&{sequence:i}})}updateComponentProps(e,t){let r=this.messages.find(t=>t.id===e),n=r&&Wo(r);return!(!r||"assistant"!==r.role||r.variant||!n||(this.upsertMessage({...r,rawContent:JSON.stringify({text:r.content,component:n.component,props:t})}),0))}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!(!t||"assistant"!==t.role||t.variant||!Wo(t)||(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),0))}async#wt(e,t,r){let n;try{n=await r()}catch{return}let o=n.blocks.join("\n\n"),a=[o,t].filter(Boolean).join("\n\n"),s=Array.isArray(e.contentParts)&&e.contentParts.length>0,i=n.contentParts.length>0;if(s){let t=[];o&&t.push(bo(o)),t.push(...n.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(i){let t=[];a&&t.push(bo(a)),t.push(...n.contentParts),e.contentParts=t}else o&&(e.llmContent=a);Object.keys(n.context).length>0&&(e.mentionContext=n.context)}async sendMessage(e,t){let r=e.trim(),n=!!t?.replayFields&&(void 0!==t.replayFields.llmContent||void 0!==t.replayFields.rawContent||(t.replayFields.contextMentions?.length??0)>0);if(!(r||t?.contentParts&&0!==t.contentParts.length||t?.mentions&&0!==t.mentions.refs.length||n))return;this.#re&&!t?.voiceTurn&&(this.#re.failed=!0,this.#re=null),(this.#q||this.#U||this.#N||this.#Q)&&await this.#mt(),this.stopSpeaking(),this.client.cancelStreams(),this.abortController?.abort(),this.#o(),this.#rt(),this.#ae++,this.#tt();let o=t?.voiceTurn?.userMessageId,a=o?this.messages.find(e=>e.id===o&&"user"===e.role):void 0,s=a?.id??ln(),i=dn();this.#p=null;let l=t?.contentParts&&fo(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:[bo(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(!So(e))return[];let{toolCallId:n,name:o}=e;if("string"!=typeof n||!n||"string"!=typeof o||!o||r.has(n))return[];r.add(n);let a=So(e.arguments)?e.arguments:{},s=e.result??null;return[{id:`voice-tool-${n}`,role:"assistant",variant:"tool",content:"",createdAt:t,streaming:!1,toolCall:{id:n,name:o,status:"complete",args:a,result:s},agentMetadata:{clientToolAnswer:{toolCallId:n,toolName:o,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:n,result:o}=e.clientToolAnswer;return{toolCallId:t,name:r,arguments:n,result:o}});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 n=r+1;for(;n<e.length&&"user"!==e[n].role;)n+=1;return{start:r,end:n}}(this.messages,e);if(!r)return!1;let n=this.messages[r.start],o=t.replacement,a=o?o.text:n.content,s=o?o.contentParts:n.contentParts;if(!(a?.trim()||(s?.length??0)>0||!o&&(n.llmContent?.trim()?.length??0)>0))return!1;let i=o?void 0:{...void 0!==n.llmContent&&{llmContent:n.llmContent},...void 0!==n.rawContent&&{rawContent:n.rawContent},...n.mentionContext&&{mentionContext:n.mentionContext},...n.contextMentions&&{contextMentions:n.contextMentions},...n.quote&&{quote:n.quote}},l=o?this.#Ct(o.options):n.composerOptions,d=o?o.contentSegments:n.contentSegments,c=o?o.options?.quote:void 0,p=o?o.viaVoice:n.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,r.start),this.sendMessage(a??"",{...s?.length?{contentParts:[...s]}:{},...d?.length?{contentSegments:[...d]}:{},...l?{composerOptions:l}:{},...c?{quote:c}:{},...i&&Object.keys(i).length>0?{replayFields:i}:{},viaVoice:!0===p}),!0}#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.#q||this.#U||this.#N||this.#Q)&&await this.#mt(),this.abortController?.abort(),this.#tt(),this.#o();let e=dn();this.#p=null,this.#ue(!0);let t=new AbortController;this.abortController=t;let r=this.#e,n=[...this.messages];try{await this.client.dispatch({messages:n,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.#o(),t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#p=t.assistantMessageId);let r=t?.preserveAssistantId?t.assistantMessageId:void 0,n=!1;for(let e of this.messages)e.streaming&&e.id!==r&&(e.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.#ue(!0);let o=this.#e,a={};try{await this.client.processStream(e,e=>{if(this.#e!==o)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!==o)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},n=`approval-${r.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(t=>{this.webMcpApprovalResolvers.set(n,t),e.signal?.addEventListener("abort",()=>this.resolveWebMcpApproval(n,"timeout"),{once:!0})})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let n=this.messages.find(t=>t.id===e);n?.approval&&this.upsertMessage({...n,approval:{...n.approval,status:t,resolvedAt:Date.now()}}),r("approved"===t)}#oe;#ae;#At(e){let t=this.#oe??={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=go();if(r)return e(r,t);let n=this.#ae;return mo().then(r=>n===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((n,o)=>n.resolveApproval(o,e,t,r))}resolveAskUserQuestion(e,t){return this.#At((r,n)=>r.resolveAskUserQuestion(n,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 n=this.webMcpAwaitBatches.get(t);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,n)),!n.seen.has(r)&&(n.seen.add(r),n.snapshots.push(e))}#fe(){if(0===this.webMcpAwaitBatches.size)return;let e=this.#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,n)=>t.resolveWebMcpToolCallBatch(n,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=To(Io(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...void 0===e.markdown?{}:{markdown:e.markdown}}),n=this.messages.find(e=>e.id===t);n?(n.rawContent=r,n.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 n=To(Io(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...void 0===t.markdown?{}:{markdown:t.markdown}});r.rawContent!==n&&(r.rawContent=n,r.streaming="streaming"===t.status,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#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=>({...pr(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 io();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 n=!0;this.#f=this.#Ne?.subscribeIdentityStatus(()=>{n||(this.#g?.clear(),this.cancel())})??null,n=!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 n={conversationId:r,executionId:t,status:e,detached:!1};this.#Et(n)}#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.#o(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=Vo().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,n)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:n,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=>Qo(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.#o(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)?dn():this.#Ht();t||(t=dn(),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 n=Fo(r.content);n.trim()&&this.readAloud.play(r.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Oo(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||"assistant"!==t.role)return;let r=Fo(t.content||"");if(!r.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:n?.voice,rate:n?.rate,pitch:n?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#xt(e){for(let e of this.messages)e.streaming=!1;let t=Qo(e,this.config.errorMessage);t?this.#Be({id:dn(),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,n=r&&this.messages.find(e=>e.toolCall?.id===r),o=n&&n.toolCall;if(!o||"complete"===o.status||"pending"===t.status)return;let a={...o,status:"complete",approvalStatus:t.status,completedAt:Date.now(),..."approved"===t.status?{superseded:!0}:{success:!1,error:"denied"===t.status?"Denied":"Approval timed out"}};this.upsertMessage({...n,streaming:!1,toolCall:a})}#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,n)=>{if(n!==r||e.toolCall?.name&&lr(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 o={...e,...t};!0===e.agentMetadata?.askUserQuestionAnswered&&t.agentMetadata&&(o.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),!0===e.agentMetadata?.suggestRepliesResolved&&t.agentMetadata&&(o.agentMetadata={...o.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&o.agentMetadata&&!o.agentMetadata.clientToolAnswer&&(o.agentMetadata={...o.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let r=e.approval,n=t.approval;o.approval={...r,...n,executionId:n.executionId||r.executionId,toolCallId:n.toolCallId||r.toolCallId,toolName:n.toolName||r.toolName,description:n.description||r.description,toolType:n.toolType??r.toolType,reason:n.reason??r.reason,parameters:n.parameters??r.parameters}}let s=t.toolCall?.name,i=t.agentMetadata?.executionId,l=t.toolCall?.id;if(s&&Jo(s)&&i&&l&&!0===t.agentMetadata?.awaitingLocalTool){let t=`${i}:${l}`,r=this.webMcpInflightKeys.has(t),n=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,s=e.agentMetadata?.executionId===i&&e.toolCall?.id===l&&void 0!==a&&Jo(a)&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;(r||n||s)&&(o.agentMetadata={...o.agentMetadata??{},awaitingLocalTool:!1},o.toolCall=e.toolCall,o.streaming=e.streaming)}return o});let n=this.messages[r],o=this.messages[r-1],a=this.messages[r+1];(o&&this.#Dt(o,n)>0||a&&this.#Dt(n,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(),n=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(n)&&r!==n)return r-n;let o=e.sequence??0,a=t.sequence??0;return o===a?e.id.localeCompare(t.id):o-a}#we(e){return[...e].sort((e,t)=>this.#Dt(e,t))}};let Go={add:e=>async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;wo(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})}(e)},Yo={allowedTypes:vo,maxFileSize:10485760,maxFiles:4};function Xo(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}p=class e{#e=[];#t;#r=new Set;#n=new Map;#o=null;#a=new Map;#s=new WeakMap;#i=!1;#l=!1;constructor(e={}){this.#t={allowedTypes:e.allowedTypes??Yo.allowedTypes,maxFileSize:e.maxFileSize??Yo.maxFileSize,maxFiles:e.maxFiles??Yo.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:Go}setPreviewsContainer(e){this.#o!==e&&this.#v(),this.#o=e}remountPreviews(e){if(this.#v(),this.#o=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:Yo.allowedTypes),"maxFileSize"in e&&(this.#t.maxFileSize=e.maxFileSize??Yo.maxFileSize),"maxFiles"in e&&(this.#t.maxFiles=e.maxFiles??Yo.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.#o);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=xo(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 n={id:Xo(),file:r,previewUrl:wo(r)?URL.createObjectURL(r):null,contentPart:null,status:this.#d()?"uploading":"processing",progress:this.#d()?0:void 0};this.#e.push(n),this.#f(n),t.push(n),this.#w(n)}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(),n=()=>this.#i||t.signal.aborted||this.#a.get(e.id)!==t||!this.#e.includes(e);try{let o=await r.add(e.file,{signal:t.signal,onProgress:t=>{n()||"uploading"!==e.status||(e.progress=(e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0)(t),this.#b(e),this.#m())}});if(n())return void(this.#i&&this.#l&&this.#h(o,r));this.#s.set(e,r),e.contentPart=o,e.status="ready",e.progress=void 0,e.error=void 0}catch(t){if(n())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 n=this.#o?.querySelector(`[data-attachment-id="${e}"]`);n&&n.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.#o&&(this.#o.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.#o=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:wo(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,n="",o=e=>{r=e;let{state:o}=r,a=JSON.stringify([r.config.attachments?.preview,o.lineCount,o.previewUrl]);n!==a&&(n=a,(()=>{let{state:e}=r,n=r.config.attachments?.preview,o="image"===e.kind,a=o?n?.image:n?.file,s=o?n?.image?.layout??"thumbnail":n?.file?.layout??"tile";if(t.dataset.kind=e.kind,t.dataset.layout=s,t.dataset.fileIcon=String(!1!==n?.file?.icon),t.dataset.iconPlacement=n?.file?.iconPlacement??"start",t.dataset.removeVisibility=a?.remove?.visibility??"always",t.dataset.removePlacement=a?.remove?.placement??"overlap",t.replaceChildren(),o&&e.previewUrl){let r=it("img",{className:"persona-attachment-image",attrs:{src:e.previewUrl,alt:e.name},style:{objectFit:n?.image?.fit??"cover"}}),o=n?.image?.name??"hidden";if("chip"===s||"hidden"!==o){let n=st("div","persona-attachment-image-card");n.append(r),"hidden"!==o&&n.append(it("span",{className:"persona-attachment-file-name",text:"basename"===o?e.name.replace(/\.[^.]+$/,""):e.name})),t.append(n)}else t.append(r)}else{let r=st("div","persona-attachment-file"),o=e.mimeType,a=o.includes("spreadsheet")||o.includes("excel")?ge:"application/json"===o?me:"application/pdf"===o||o.startsWith("text/")||o.includes("word")?fe:be,s=(n?.file?.iconName?Ee(n.file.iconName,20,"currentColor",1.5):null)??oe(a,20,"currentColor",1.5);s&&!1!==n?.file?.icon&&(s.classList.add("persona-attachment-file-icon"),r.append(s));let i=st("div","persona-attachment-file-copy"),l=n?.file?.name??"hidden";"hidden"!==l&&i.append(it("span",{className:"persona-attachment-file-name",text:"basename"===l?e.name.replace(/\.[^.]+$/,""):e.name}));let d=n?.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=n?.file?.badge??"type";"none"!==p&&r.append(it("span",{className:"persona-attachment-file-badge",text:"extension"===p?e.name.match(/\.([^.]+)$/)?.[1].toUpperCase()??Co(o,e.name):Co(o,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=oe(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=o.status,t.setAttribute("aria-busy",String("uploading"===o.status||"processing"===o.status)),t.title="error"===o.status?`${o.name}: ${o.error??"Upload failed"}`:o.name;let s=t.querySelector(".persona-attachment-progress__bar");s&&(s.style.width="number"==typeof o.progress?`${Math.round(100*o.progress)}%`:"")};return o(e),{element:t,update:o}}(t)};return t}#f(e){if(!this.#o)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 n=r instanceof HTMLElement?{element:r}:r;n.element.dataset.attachmentId=e.id,this.#n.set(e.id,n),this.#o.appendChild(n.element)}#b(e){try{this.#n.get(e.id)?.update?.(this.#g(e))}catch(e){console.error("[AttachmentManager] preview update failed:",e)}}#y(e){let t=this.#n.get(e);if(t){this.#n.delete(e);try{t.destroy?.()}catch(e){console.error("[AttachmentManager] preview cleanup failed:",e)}finally{t.element.remove()}}}#v(){for(let e of this.#n.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 n=new FileReader;n.onload=()=>e(String(n.result??"")),n.onerror=()=>r(n.error),n.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.#o&&(this.#o.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 Zo=(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,n=!1,o=!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(n=!1,o||0===t.size)return;let e=a();for(let r of[...t])try{r(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",e)}},i=()=>{r=null,!o&&!n&&(n=!0,queueMicrotask(s))};return{getState:a,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,i())},setAttachments:t=>{((e,t)=>e.length===t.length&&e.every((e,r)=>{let n=t[r];return e.id===n.id&&e.name===n.name&&e.mimeType===n.mimeType&&e.size===n.size&&e.status===n.status&&e.progress===n.progress&&e.error===n.error}))(e.attachments,t)||(e.attachments=[...t],i())},setMentionRefs:t=>{Zo(e.mentionRefs,t)||(e.mentionRefs=[...t],i())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,i())},setActiveModeIds:t=>{Zo(e.activeModeIds,t)||(e.activeModeIds=[...t],i())},setQuote:t=>{let r=e.quote;(r?.text!==t?.text||r?.messageId!==t?.messageId||r?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,i())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,i())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,i())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,i())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,i())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,i())},flush:()=>{n&&s()},destroy:()=>{o=!0,n=!1,t.clear()}}}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 na(e,t={}){let r=ta(e,"[data-persona-composer-form]"),n=ta(e,"[data-persona-composer-input]");if(!r||!n){let e=`[Persona] composer surface is missing required element(s): ${[!r&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(r||n))throw Error(e);return typeof console<"u"&&console.warn(e),null}let o={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=o.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=o.body??n.parentElement??r,l=(e,t,r,n,o)=>{if(t)return t;a.add(e);let s=ra(r,n);return o.appendChild(s),s},d=l("actionsStart",o.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",r),c=l("actionsEnd",o.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",r),p=l("suggestions",o.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),u=l("status",o.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[];return{footer:e,form:r,input:n,header:s,body:i,actionsStart:d,actionsEnd:c,suggestions:p,status:u,attachmentInput: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:o,addListener:(e,t,r,n)=>{e.addEventListener(t,r,n),h.push({target:e,type:t,handler:r,options:n})},removeListener:(e,t,r,n)=>{e.removeEventListener(t,r,n),h=h.filter(n=>!((e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler)(n,{target:e,type:t,handler:r}))},destroy:()=>{for(let e of h)e.target.removeEventListener(e.type,e.handler,e.options);h=[]}}}let oa="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 n=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 n.reduce((e,r)=>{let n=t.getComputedStyle(r);return e+("contents"===n.display?ia(r,t):Math.max(r.getBoundingClientRect().width,r.scrollWidth))+sa(n.marginLeft)+sa(n.marginRight)},0)+Math.max(0,n.length-1)*sa(r.columnGap)+sa(r.paddingLeft)+sa(r.paddingRight)}function la(e){let t=null,r=null,n=null,o=null,a=0,s=!0,i=!1,l=!1,d=()=>{null!==o&&t?.form.ownerDocument.defaultView?.cancelAnimationFrame(o),o=null,r?.disconnect(),n?.disconnect(),r=null,n=null,t?.form.ownerDocument.defaultView?.removeEventListener("resize",c)},c=()=>{if(l||null!==o)return;let r=t?.form.ownerDocument.defaultView;r&&(o=r.requestAnimationFrame(()=>{o=null,l||e.onMeasure()}))};return{measure:()=>{if(l)return s;let o=e.getSurface();if(o?.form!==t?.form||o?.input!==t?.input||o?.start!==t?.start||o?.end!==t?.end){d(),t=o,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 n=[t.form,t.start,t.end,t.input];for(let e of n)r.observe(e)}void 0!==e.MutationObserver&&(n=new e.MutationObserver(e=>{e.some(e=>e.target!==t?.input||"attributes"!==e.type)&&c()}),n.observe(t.form,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["class","style","hidden"]}))}}t&&o&&(t.resizeInput=o.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,n){return e<=0?n:e>=t+2*r+120+(n?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 n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(r,n):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="",n=!1,o=r=>{let n=st("span","persona-composer-quote-bar"),o=st("div","persona-composer-quote-content");if(r.sourceLabel){let e=st("div","persona-composer-quote-source");e.textContent=r.sourceLabel,o.appendChild(e)}let a=it("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});a.textContent=Eo(r.text),o.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(n,o,s)};return{element:t,render:e=>{if(n)return;let a=e?`${e.sourceLabel??""}\0${e.text}`:"";a!==r&&(r=a,e?(o(e),t.style.display="flex"):(t.replaceChildren(),t.style.display="none"))},destroy:()=>{n=!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,n=!1,o=(e,t,r,n)=>{let o=it("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":t,[r]:""}}),a=Ee(e,12,"currentColor",2);return a?o.appendChild(a):o.textContent=t,o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o};return{element:t,render:a=>{if(n||a===r)return;if(r=a,!a)return t.replaceChildren(),void(t.style.display="none");let s=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=Eo(e.text??"",90);if(t)return t;let r=e.contentParts?.length??0;return r>0?1===r?"1 attachment":`${r} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(", "):"Queued message"})(a),t.replaceChildren(s,i,o("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),o("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}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 n=()=>{r.style.height="auto",r.style.height=`${r.scrollHeight}px`};r.addEventListener("input",n);let o=st("div","persona-message-edit-actions"),a=(e,t,r,n)=>{let o=it("button",{className:`persona-message-edit-button ${t}`,attrs:{type:"button",[r]:""},text:e});return o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),n()}),o},s=()=>{let t=r.value.trim();t&&e.onSave(t)};return o.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",s)),r.addEventListener("keydown",t=>{"Escape"===t.key?(t.preventDefault(),t.stopPropagation(),e.onCancel()):"Enter"===t.key&&!t.shiftKey&&(t.preventDefault(),s())}),t.append(r,o),{element:t,getValue:()=>r.value,focus:()=>{r.focus();let e=r.value.length;r.setSelectionRange(e,e),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}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,n){let o=r.find(e=>e.id===t);if(!o)return[...e];let a=e.includes(t),s=new Set(e);if(a)s.delete(t);else{if("single"===((e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null)(o,n)){let e=r.filter(e=>e.groupId===o.groupId).map(e=>e.id);s=new Set([...s].filter(t=>!e.includes(t)))}s.add(t)}return r.filter(e=>s.has(e.id)).map(e=>e.id)}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 n=parseFloat(r);return Number.isFinite(n)&&n>0?n: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){if("Enter"!==e.key||e.shiftKey||e.isComposing)return!1;let r=!0===e.metaKey||!0===e.ctrlKey,n=t.submitKey??"enter";return"none"!==n&&("mod-enter"===n?r:r||!Ca(t))}function ka(e,t){e.setAttribute("enterkeyhint",function(e){return"enter"===(e.submitKey??"enter")?Ca(e)?"enter":"send":"enter"}(t))}function Aa(e,t){let r=t?.autocomplete;e.setAttribute("autocomplete","string"==typeof r&&r?r:"off");let n=(t,r)=>{void 0===r?e.removeAttribute(t):e.setAttribute(t,r)};n("autocapitalize","string"==typeof t?.autocapitalize?t.autocapitalize:void 0),n("spellcheck","boolean"==typeof t?.spellcheck?String(t.spellcheck):void 0),n("inputmode","string"==typeof t?.inputmode&&t.inputmode?t.inputmode:void 0),n("aria-label","string"==typeof t?.ariaLabel&&t.ariaLabel?t.ariaLabel:void 0)}function Ma(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 Ia(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 Ta(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 Ea(e,t,r){let n;try{n=e(Ia(t),{signal:r})}catch(e){return{status:"error",error:e}}return(e=>"function"==typeof e?.then)(n)?Promise.resolve(n).then(e=>r.aborted?{status:"aborted"}:Ta(t,e),e=>r.aborted?{status:"aborted"}:{status:"error",error:e}):Ta(t,n)}let{setLoader:La,load:Ba}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ra=La,Pa=Ba,{setLoader:Na,load:$a}=_({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Wa=Na,Ha=$a,Da=400,Oa=300,Fa=0,za=e=>Math.max(0,e);function ja(e){void 0!==e.delayMs&&(Da=za(e.delayMs)),void 0!==e.skipDelayMs&&(Oa=za(e.skipDelayMs))}let qa=new WeakMap;function _a(e){qa.get(e)?.hide()}let Ua=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Va=e=>{let t=e.getRootNode?.();return Ua(t)?t:e.closest("dialog[open]")??e.ownerDocument.body},Ka=(e,t,r)=>Math.min(Math.max(e,t),Math.max(t,r)),Qa=[...["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 Ja(e){qa.get(e.anchor)?.destroy();let t,{anchor:r,trigger:n=r,text:o,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 o?o():o).trim(),v=()=>("function"==typeof a?a():a??"").trim(),w=()=>za(e.delayMs??Da),x=()=>za(e.skipDelayMs??Oa),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(),n=r.getBoundingClientRect(),o=p.getBoundingClientRect(),a=e.documentElement.clientWidth||t.innerWidth,s=e.documentElement.clientHeight||t.innerHeight,u=a-l-o.width,h=n.left+n.width/2-o.width/2,m=Ka(h,l,u),g=n.top-l,f=s-l-n.bottom,b=g>=o.height+i||g>=f?"top":"bottom",y="top"===b?n.top-i-o.height:n.bottom+i,v=s-l-o.height,w=Ka(y,l,v),x=n.left+n.width/2,C=Math.max(10,o.width-10),S=Ka(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=Va(r);if(!e||!t)return;let n=d(),o=c();p=n.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex="100001";let a=o.getComputedStyle?.(r);if(a){for(let e of Qa){let t=a.getPropertyValue(e).trim();t&&p.style.setProperty(e,t)}a.fontFamily&&(p.style.fontFamily=a.fontFamily)}u=n.createElement("span"),u.className="persona-control-tooltip__label",u.textContent=e,p.appendChild(u);let i=v();i&&(h=n.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=i,p.appendChild(h));let l=n.createElement("span");l.className="persona-control-tooltip__arrow",p.appendChild(l),t.appendChild(p),k(),p.dataset.state="open";let g=()=>{if(!r.isConnected)return void S();u&&(u.textContent=y()),h&&(h.textContent=v());let e=Va(r);p&&e&&p.parentNode!==e&&e.appendChild(p),k()};o.addEventListener("scroll",g,!0),o.addEventListener("resize",g);let f=r.closest("[data-persona-root]");f?.addEventListener("persona:internal:host-moved",g);let w=r.getRootNode(),x=Ua(w)?w:n.documentElement,C=typeof MutationObserver>"u"?null:new MutationObserver(()=>{r.isConnected||S()});C?.observe(x,{childList:!0,subtree:!0}),m=()=>{o.removeEventListener("scroll",g,!0),o.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()};n.addEventListener("mouseenter",I),n.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(),n.removeEventListener("mouseenter",I),n.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 Ga=(e,t,r,n)=>{let[o,a]=t.split(".");return[e?.theme,e?.darkTheme].some(e=>void 0!==e?.components?.[o]?.[a]?.[r])?`var(--persona-components-${t.replace(".","-")}-${r}, ${n})`:n},Ya=(e,t)=>{let r=e&&z(e,t);return"string"==typeof r&&r?r:void 0},Xa=(e,t,r,n)=>{let o=t.startsWith("var(");e.classList.toggle("persona-theme-padding",o),e.style.padding=o?"":t,o?e.style.setProperty("--persona-theme-padding",t):e.style.removeProperty("--persona-theme-padding"),r&&(e.style.paddingLeft=e.style.paddingRight=r),n&&(e.style.paddingTop=e.style.paddingBottom=n)},Za=(e,t,r)=>{let n=t.startsWith("var(")&&t.includes("--persona-components-");e.classList.toggle("persona-control-size",n),n?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??""},es=Symbol("persona.panelAliasProvenance"),ts=(e,t)=>null!=e&&Object.prototype.hasOwnProperty.call(e,t),rs=(e,t)=>ts(e,t)&&void 0!==e[t],ns=e=>{let t=e?.[es];return t?{...t}:(e=>({launcherWidth:rs(e?.launcher,"width"),legacyLauncherWidth:rs(e,"launcherWidth"),sidebarWidth:rs(e?.launcher,"sidebarWidth"),dockWidth:rs(e?.launcher?.dock,"width")}))(e)},os=(e,t)=>(Object.defineProperty(e,es,{value:t,enumerable:!0,configurable:!0}),e),as=(e,t)=>os(e,ns(t)),ss=e=>!0===e?.layout?.embedded&&!1===e.launcher?.enabled&&!e.launcher.sidebarMode&&"floating"===(e.launcher.mountMode??"floating"),is=e=>e?.layout?.showHeader??!ss(e),ls="min(440px, calc(100vw - 24px))",ds={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:ls,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},cs={},ps={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"},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 us(e){return!0===e?.future?.v5Defaults?"v5":"v4"}function hs(e){let t="v5"===us(e)?ps:cs;return k(ds,t)}let ms=hs();function gs(e,t){if(e||t)return e?t?k(e,t):e:t}function fs(e){let t=hs(e);return e?O(w(as({...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:gs(t.theme,e.theme),darkTheme:gs(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let r=t.features?.artifacts,n=e.features?.artifacts,o=t.features?.scrollToBottom,a=e.features?.scrollToBottom,s=t.features?.scrollBehavior,i=e.features?.scrollBehavior,l=t.features?.streamAnimation,d=e.features?.streamAnimation,c=t.features?.askUserQuestion,p=e.features?.askUserQuestion,u=t.features?.history,h=e.features?.history,m=void 0===r&&void 0===n?void 0:{...r,...n,layout:{...r?.layout,...n?.layout}},g=void 0===o&&void 0===a?void 0:{...o,...a},f=void 0===s&&void 0===i?void 0:{...s,...i},b=void 0===l&&void 0===d?void 0:{...l,...d},y=void 0===c&&void 0===p?void 0:{...c,...p,styles:{...c?.styles,...p?.styles}},v=void 0===u&&void 0===h?void 0:{...u,...h,copy:{...u?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay,...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===g?{}:{scrollToBottom:g},...void 0===f?{}:{scrollBehavior:f},...void 0===m?{}:{artifacts:m},...void 0===b?{}:{streamAnimation:b},...void 0===y?{}:{askUserQuestion:y},...void 0===v?{}:{history:v}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,ps),e):O(w(as(t),void 0,ps))}let bs=(e,t)=>{let r=st("textarea");r.setAttribute("data-persona-composer-input",""),r.placeholder=e?.copy?.inputPlaceholder??"How can I help...",r.dir="auto",ka(r,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(r)}),Aa(r,e?.composer?.inputAttributes),r.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",r.rows=1,r.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',r.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=va(e?.composer?.maxLines,t?.defaultMaxLines??3),o=20*n+"px";return r.style.maxHeight=o,r.style.overflowY="auto",r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.addEventListener("focus",()=>{r.style.border="none",r.style.outline="none",r.style.borderWidth="0",r.style.borderStyle="none",r.style.borderColor="transparent",r.style.boxShadow="none"}),r.addEventListener("blur",()=>{r.style.border="none",r.style.outline="none"}),{textarea:r,attachAutoResize:()=>{r.addEventListener("input",()=>{r.style.height="auto";let e=Math.min(r.scrollHeight,(()=>{let e=r.style.maxHeight;if(e!==o){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=n*ya(r);return o=`${t}px`,r.style.maxHeight=o,t})());r.style.height=`${e}px`})}}},ys="[data-persona-glyph-stack]",vs=new WeakMap,ws=(e,t,r=!0)=>{vs.set(e,t);let n=t?.sendButton??{},o=n.useIcon??!1,a="stop"===e.getAttribute("data-persona-send-mode")?"stop":"send",s=e=>Ya(t,`sendButton.${e}`),i=(e,r)=>Ga(t,"composer.send",e,r),l=s("size")||n.size;e.style.fontSize=o?"18px":"",e.style.lineHeight=o?"1":"",e.className=lt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${oa}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!s("backgroundColor")&&"persona-bg-persona-primary",!o&&!s("textColor")&&"persona-text-white"),Za(e,o?l||(i("size","")?i("size","var(--persona-composer-control-size, 40px)"):""):"",o?l:void 0);let d=i("foreground",o?"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":"#ffffff"),c=i("background",o?"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","")||(o?d:"")),e.style.backgroundColor=(o?s("backgroundColor"):void 0)||(i("background","")?"stop"===a?`var(--persona-button-stop-bg, ${c})`:c:"");let p=s("borderWidth")||(i("borderWidth","")?i("borderWidth",n.borderWidth||"0px"):n.borderWidth||"");e.style.borderWidth=p,e.style.borderStyle=p?"solid":"",e.style.borderColor=s("borderColor")||(i("borderColor","")?i("borderColor",n.borderColor||"transparent"):n.borderColor||""),e.style.borderRadius=i("borderRadius","")?i("borderRadius","var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))"):"",Xa(e,i("padding",o?"0":"8px 16px"),o?void 0:s("paddingX")||(i("padding","")?void 0:n.paddingX),o?void 0:s("paddingY")||(i("padding","")?void 0:n.paddingY));let u=parseFloat(n.iconSize??"")||Math.round(.5*(parseFloat(n.size??"")||40));if(r)if(e.replaceChildren(),o){let t=n.iconStrokeWidth??2,r=n.iconName?Ee(n.iconName,u,"currentColor",t):null,o=Ee(n.stopIconName??"square",u,"currentColor",t);r&&o?e.appendChild(((e,t,r="send")=>{let n=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"),n.append(e,t),n})(r,o,a)):r?e.appendChild(r):e.textContent=n.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)}},xs=e=>{let t=e?.sendButton,r=st("div","persona-send-button-wrapper"),n=it("button",{attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"}});return ws(n,e),n.setAttribute("aria-label",t?.tooltipText??"Send message"),r.appendChild(n),Ja({anchor:n,trigger:r,text:()=>n.getAttribute("aria-label")??"",enabled:t?.showTooltip??!1}),{button:n,wrapper:r,setMode:e=>{if(n.getAttribute("data-persona-send-mode")===e)return;n.setAttribute("data-persona-send-mode",e),n.setAttribute("aria-label","stop"===e?t?.stopTooltipText??"Stop generating":t?.tooltipText??"Send message");let r=vs.get(n);ws(n,r,!1),n.querySelector(ys)?.setAttribute("data-mode",e),r?.sendButton?.useIcon||(n.textContent="stop"===e?r?.copy?.stopButtonLabel??"Stop":r?.copy?.sendButtonLabel??"Send")},glyphStack:n.querySelector(ys)}},Cs=(e,t,r="idle",n="none")=>{let o=t?.voiceRecognition??{},a=e=>Ya(t,`voiceRecognition.${e}`),s=(e,r)=>Ga(t,"voice.control",e,r),i=a("iconSize")||o.iconSize;Za(e,i||(s("size","")?s("size","var(--persona-composer-control-size, 40px)"):""),i),e.classList.add(oa),e.classList.toggle(aa,!i&&!s("size","")),e.style.fontSize="18px",e.style.lineHeight="1";let l=a("iconColor")||Ya(t,"sendButton.textColor")||s("foreground","var(--persona-text, #111827)"),d=a("backgroundColor")||Ya(t,"sendButton.backgroundColor")||s("background",o.backgroundColor||"transparent"),c=a("borderColor")||s("borderColor",o.borderColor||"transparent"),p=a("borderWidth")||s("borderWidth",o.borderWidth||"");e.style.borderWidth=p,e.style.borderStyle=p?"solid":"",e.style.borderRadius=s("borderRadius","")?s("borderRadius","var(--persona-button-radius)"):"",Xa(e,s("padding","")?s("padding","0px"):"",a("paddingX")||(s("padding","")?void 0:o.paddingX),a("paddingY")||(s("padding","")?void 0:o.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, ${o.recordingBorderColor||c})`,g=l,f=d,b=c,y=o.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=o.processingIconName??"loader";else if("speaking"===r){let e="barge-in"===n;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=o.speakingIconName??("cancel"===n?"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(o.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="🎤"},Ss=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),n="runtype"===t.provider?.type,o="custom"===t.provider?.type||"custom"===t.dictation?.provider?.type;if(!(r||n||o))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"}});Cs(s,e),a.appendChild(s);let i=t.tooltipText??"Start voice recognition";return Ja({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??i,enabled:t.showTooltip??!1}),{button:s,wrapper:a}},ks=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 n=st("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??vo).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let o=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 ${oa} ${aa}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(o,24,"currentColor",1.5);i?s.appendChild(i):s.textContent="📎",s.addEventListener("click",e=>{e.preventDefault(),n.click()}),a.appendChild(s);let l=t.buttonTooltipText??"Attach file";return Ja({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??l}),{button:s,wrapper:a,input:n,previewsContainer:r}},As=e=>{let t=e?.statusIndicator??{},r="left"===t.align?"persona-text-left":"center"===t.align?"persona-text-center":"persona-text-right",n=st("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status",""),ur(n,t,"idle");let o=t.idleText??"Online";if(t.idleLink){let e=st("a");e.href=t.idleLink,e.target="_blank",e.rel="noopener noreferrer",e.textContent=o,e.style.color="inherit",e.style.textDecoration="none",n.appendChild(e)}else n.textContent=o;return n},Ms=()=>it("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Is(e){let{config:t,onOpen:r}=e,n=t.buttonIconName??"plus",o=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 ${oa} ${aa}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":o,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),i=Ee(n,24,"currentColor",1.5);return i?s.appendChild(i):s.textContent="+",s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r()}),a.appendChild(s),Ja({anchor:s,trigger:a,text:()=>s.getAttribute("aria-label")??o}),{button:s,wrapper:a}}let Ts=e=>e?.launcher?.variant??(!0===e?.future?.v5Defaults?"circle":"pill"),Es={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"},Ls="16px",Bs="transparent",Rs={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"}},Ps={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"}},Ns={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:ls,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ls,canvasBackground:Bs,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},$s=Rs.colors.gray,Ws={...Rs,colors:{...Rs.colors,gray:$s}},Hs={...Rs,colors:{...Rs.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"}},Ds=Ws,Os=Ps,Fs={...Ps,colors:{...Ps.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Ps.typography,fontSize:"14px",lineHeight:"1.5"}},zs=Os,js=Ns,qs={...Ns,scrollToBottom:{...Ns.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:Es,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:{...Ns.input,borderRadius:"palette.radius.full"},introCard:{...Ns.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Ns.suggestion.chip,fontWeight:"400"},card:{...Ns.suggestion.card,fontWeight:"400"},list:{...Ns.suggestion.list,fontWeight:"400"}},panel:{...Ns.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Ns.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:{...Ns.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Ns.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:{...Ns.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},artifact:{...Ns.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:{...Ns.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)"}},_s=js,Us=e=>"v5"===(e=>us({future:e}))(e)?{palette:Hs,semantic:Fs,components:qs}:{palette:Ws,semantic:Os,components:js};function Vs(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),n=e;for(let e of r){if(null==n)return;n=n[e]}return"string"==typeof n&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Vs(e,n):n}function Ks(e){let t={};function r(n,o){for(let[a,s]of Object.entries(n)){let n=`${o}.${a}`;if("string"==typeof s){let r=Vs(e,s);void 0!==r&&(t[n]={path:n,value:r,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else"object"==typeof s&&s&&r(s,n)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Qs(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 Js(e,t){let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t&&"object"==typeof t&&!Array.isArray(t)&&n&&"object"==typeof n&&!Array.isArray(n)?Js(t,n):n}return r}function Gs(e,t={}){let r=Us(t.future),n=e?.components,o={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:n?Js(r.components,n):r.components},a=n?.activity;for(let e of["toolBubble","reasoningBubble"]){let t=o.components[e]={...o.components[e]};for(let r of["rowHeight","labelSize","iconSize","indent","bodySurface"])void 0!==a?.[r]&&("bodySurface"!==r||void 0===n?.[e]?.bodySurface)&&(t[r]=a[r])}let s=n?.collapsibleWidget?.surface;"v4"===us(t)&&void 0!==s&&void 0===a?.bodySurface&&(o.components.activity={...o.components.activity,bodySurface:s});let i=n?.header;void 0!==i?.padding&&void 0===i.minimalPadding&&(o.components.header.minimalPadding=o.components.header.padding);let l=n?.composer;o.components.composer={...o.components.composer},void 0!==l?.padding&&void 0===l.expandedPadding&&(o.components.composer.expandedPadding=l.padding),void 0!==n?.input?.borderRadius&&void 0===l?.expandedBorderRadius&&(o.components.composer.expandedBorderRadius=n.input.borderRadius);let d=n?.message;if(void 0!==d?.gap&&void 0===d.fullscreenGap&&(o.components.message.fullscreenGap=o.components.message.gap),!1!==t.validate){let e=Qs(o);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(", ")}`)}if(t.plugins)for(let e of t.plugins)o=e.transform(o);return o}let Ys=e=>"0"===e.trim()?"0px":e,Xs="--persona-",Zs=(e,t)=>{for(let[r,...n]of t){let t;for(let r of n)if(t=61===r.charCodeAt(0)?r.slice(1):e[Xs+r],void 0!==t)break;void 0!==t&&(e[Xs+r]=t)}},ei=[["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 ti(e){let t=(e=>{let t=Ks(e),r={};for(let[e,n]of Object.entries(t))r[`--persona-${e.replace(/\./g,"-")}`]=n.value;return r})(e);Zs(t,ei),Zs(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),Zs(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"]]),Zs(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"]}`,Zs(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",Zs(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,n,o,a="")=>{if(r)for(let[s,i,l]of o){let o=r[a+s];o&&(t[`--persona-${n}${i}`]=l?Vs(e,o)??o:o)}};Zs(t,[["header-bg","components-header-background","surface"]]);let n=t["--persona-header-bg"],o=t["--persona-components-header-foreground"],a=o?`color-mix(in srgb, ${o} 72%, ${n})`:void 0;t["--persona-header-border"]=t["--persona-components-header-border"]??(o?`color-mix(in srgb, ${o} 14%, ${n})`:void 0)??t["--persona-divider"],Zs(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"]??o??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"],Zs(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 n=e(s.exitDurationMs);void 0!==n&&(t["--persona-history-exit-ms"]=n),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,"message-action-",[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]],"--persona-components-messageActions-"),Zs(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,Zs(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"]]),Zs(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),Zs(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"]]),Zs(t,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Zs(t,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Zs(t,[["md-hr-color","components-markdown-hr-color","divider"]]),Zs(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 n=t[`--persona-components-collapsibleWidget-${e}`]??t[`--persona-${r}`];void 0!==n&&(t[`--persona-cw-${e}`]=n,t[`--cw-${e}`]=n)}Zs(t,[["message-border","components-message-border","border"]]),Zs(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"]]);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 n=m.toolbar;r(n,"artifact-toolbar-icon-",[["iconHoverColor","hover-color"],["iconHoverBackground","hover-bg"],["iconPadding","padding"],["iconBorderRadius","radius"],["iconBorder","border"]]),n.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Ys(n.toggleGroupGap)),n.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=n.toggleBorderRadius),n.toggleGroupPadding&&(t["--persona-artifact-toolbar-toggle-group-padding"]=Ys(n.toggleGroupPadding)),r(n,"artifact-toolbar-toggle-group-",[["toggleGroupBorder","border"],["toggleGroupBorderRadius","radius"]]),n.toggleGroupBackground&&(t["--persona-artifact-toolbar-toggle-group-bg"]=Vs(e,n.toggleGroupBackground)??n.toggleGroupBackground),r(n,"artifact-toolbar-copy-",[["copyBackground","bg"],["copyBorder","border"],["copyColor","color"]]),n.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Ys(n.copyBorderRadius)),n.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=n.copyPadding),n.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=n.copyMenuBackground,t["--persona-dropdown-bg"]=t["--persona-dropdown-bg"]??n.copyMenuBackground),n.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=n.copyMenuBorder,t["--persona-dropdown-border"]=t["--persona-dropdown-border"]??n.copyMenuBorder),n.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=n.copyMenuShadow,t["--persona-dropdown-shadow"]=t["--persona-dropdown-shadow"]??n.copyMenuShadow),n.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=n.copyMenuBorderRadius,t["--persona-dropdown-radius"]=t["--persona-dropdown-radius"]??n.copyMenuBorderRadius),n.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=n.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=t["--persona-dropdown-item-hover-bg"]??n.copyMenuItemHoverBackground),r(n,"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"]=Vs(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"]=Vs(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[n,o,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*n+.7152*o+.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 ri={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)"}}}},ni={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={...ni,colors:{...ni.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"}}},ai=ri,si={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:{...ri.components,button:{...ri.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:{...ri.components?.eventStream,badge:{...ri.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"}}}}},ii=e=>{if(e&&"object"==typeof e&&!Array.isArray(e))return e},li=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",di=e=>(e=>{let t=e?.colorScheme??L(e?.brand)??"light";return"light"===t?"light":"dark"===t?"dark":li()})(e),ci=e=>{let t=di(e),r=k(((e,t="light",r,n=!1)=>{let o={};if(!e)return o;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);o.palette={colors:{primary:e,accent:e}},o.semantic={colors:{primary:e[500],accent:e[500],interactive:{default:e[500],hover:e[600],focus:e[500],active:e[700]}}},o.components={button:{primary:{background:e[500],foreground:t}},launcher:{background:e[500],foreground:t},header:n?{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:{user:n?{background:"color-mix(in srgb, var(--persona-primary) 12%, var(--persona-container))",text:"semantic.colors.text"}:{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)),n=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);o.palette={...o.palette,colors:{...o.palette?.colors,gray:d}},o.semantic={...o.semantic,colors:{...o.semantic?.colors,surface:n,background:n,container:a,border:i,divider:i,text:l,textMuted:T(r,"#ffffff"===l?255:0,.65)}},o.components={...o.components,panel:{background:n},header:{...o.components?.header,background:n,foreground:l},composer:{footerBackground:n}}}if(a){let e=A(o.semantic?.colors?.surface)??("dark"===t?[15,15,16]:[255,255,255]),r=I(a),n="#ffffff"===E(e)?255:0;for(let t=0;t<=1;t+=.1){r=T(a,n,t);let o=M(A(r)),s=M(e);if((Math.max(o,s)+.05)/(Math.min(o,s)+.05)>=4.5)break}o.components={...o.components,markdown:{link:{foreground:r}},input:{focus:{border:r,ring:r}}}}e.font?.trim()&&(o.semantic={...o.semantic,typography:{fontFamily:e.font}});let i={none:"0px",sm:"4px",md:"8px",lg:"16px"}[e.radius??"none"];e.radius&&i&&(o.palette={...o.palette,radius:{none:"0px",sm:i,md:i,lg:i,xl:i,"2xl":i}},o.components={...o.components,input:{...o.components?.input,borderRadius:i},header:{...o.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;o.semantic={...o.semantic,typography:{...o.semantic?.typography,fontSize:`${e}px`}},o.components={...o.components,header:{...o.components?.header,minHeight:`${t}px`,padding:`${r}px 16px`,minimalPadding:`${r}px 16px`},history:{railHeader:{minHeight:`${t}px`}},composer:{...o.components?.composer,fontSize:`${e}px`,padding:`${r}px`,gap:r/2+"px"},message:{...o.components?.message,gap:`${r}px`,user:{...o.components?.message?.user,fontSize:`${e}px`},assistant:{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)";o.palette={...o.palette,shadows:{sm:a,md:a,lg:a,xl:a,"2xl":a}};let i=(e,r="")=>{let o={};if(n&&"message.assistant"===r)return o;for(let[n,l]of Object.entries(e))if(n.toLowerCase().endsWith("shadow")){o[n]=a;let r="shadow"===n?"border":n.replace(/Shadow$/,"Border");r in e&&(o[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}.${n}`:n);Object.keys(e).length&&(o[n]=e)}return o},l=r?i(r):{};o.components=k(o.components,l),o.components={...o.components,panel:{...o.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:{...o.components?.launcher,shadow:a,border:"semantic.colors.border"},composer:{...o.components?.composer,shadow:a,borderColor:"semantic.colors.border"},toolBubble:{shadow:a},reasoningBubble:{shadow:a}}}return o})(e?.brand,t,Us(e?.future).components,e?.future?.v5Defaults),ii(e?.theme)),n=k({components:{launcher:"circle"===Ts(e)?Es:{...js.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},...ss(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),o=ii(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,n=t.darkTheme?.components?.panel?.width;return null==("dark"===di(t)?n??r:r)?{...e,components:{...e.components,panel:{...e.components.panel,width:"v5"===us(t)?"400px":"420px"}}}:e})("dark"===t?((e,t={})=>{let r=(e=>"v5"===us({future:e})?{palette:oi,components:si}:{palette:ni,components:ai})(t.future),n=k(r.components,e??{})??{};return Gs({...n,palette:{...n.palette,colors:"v5"===us(t)?k(r.palette.colors,n.palette?.colors):{...r.palette.colors,...n.palette?.colors}}},{validate:!1,future:t.future})})(k(n??{},o??{}),{future:e?.future}):((e,t={})=>Gs(e,t))(n,{future:e?.future}),e);return Object.defineProperty(a,pi,{value:[...P,"suggestion.chip.padding","suggestion.chip.fontWeight"].filter(r=>j(e,r,t))}),a},pi=Symbol("persona.themeConsumerPaths"),ui=new WeakMap,hi=(e,t)=>{mi(e,(e=>{let t=ti(e);t["--persona-suggestion-compat-padding"]="6px 12px",t["--persona-suggestion-compat-weight"]="500";for(let r of e[pi]??[]){let e=r.split(".").join("-"),n=t[`--persona-components-${e}`];void 0!==n&&(t["suggestion.chip.padding"===r?"--persona-suggestion-compat-padding":"suggestion.chip.fontWeight"===r?"--persona-suggestion-compat-weight":`--persona-consumer-${e}`]=n)}return t})(ci(t)),t)},mi=(e,t,r)=>{for(let r of ui.get(e)??[])r in t||e.style.removeProperty(r);ui.set(e,Object.keys(t));for(let[r,n]of Object.entries(t))e.style.setProperty(r,n);e.setAttribute("data-persona-color-scheme",di(r)),e.setAttribute("data-persona-defaults",us(r))},gi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let r=new MutationObserver(()=>{e(li())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window<"u"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(li());r.addEventListener?(r.addEventListener("change",n),t.push(()=>r.removeEventListener("change",n))):r.addListener&&(r.addListener(n),t.push(()=>r.removeListener(n)))}return()=>{t.forEach(e=>e())}},fi=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px"),bi=(e,t)=>t||"overlay"!==e?.composer?.placement?"block":"overlay",yi=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},vi=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},wi=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},xi=e=>{let t=e.toLowerCase().split("+").map(e=>e.trim()),r=t.pop(),n={key:r,mod:!1,shift:!1,alt:!1};for(let r of t)if("mod"===r||"cmd"===r||"ctrl"===r)n.mod=!0;else if("shift"===r)n.shift=!0;else{if("alt"!==r&&"option"!==r)return wi("unknown modifier in",e),null;n.alt=!0}return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(r)||!/^([^+\s]|[a-z]{2,12})$/.test(r)?(wi("unsupported",e),null):("space"===r&&(n.key=" "),n)},Ci=(e,t)=>{let r=xi(e);if(!r)return"";let n=vi(),o=(e=>"ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space".split(" ").find(t=>t.toLowerCase()===e)??(" "===e?"Space":1===e.length?e.toUpperCase():e[0].toUpperCase()+e.slice(1)))(r.key);if(!t&&n)return`${r.alt?"⌥":""}${r.shift?"⇧":""}⌘${o}`;let a=[t?n?"Meta":"Control":"Ctrl"];return r.alt&&a.push("Alt"),r.shift&&a.push("Shift"),a.push(o),a.join("+")},Si=e=>Ci(e,!1),ki=e=>Ci(e,!0),Ai=(e,t)=>t.key?.toLowerCase()===e.key&&(vi()?t.metaKey:t.ctrlKey)===e.mod&&!(vi()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Mi=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t||e.isContentEditable},Ii=e=>{let t=new Map,r=e?.ownerDocument??(typeof document<"u"?document:null),n=(t,r)=>{if("page"===(t.scope??"widget"))return!0;if(!e)return!1;let n=r.composedPath?.();return n?.length?n.includes(e):e.contains(r.target)},o=e=>{if(e.isComposing||!t.size)return;let r=e.composedPath?.()[0]??e.target;for(let o of t.values())if(Ai(o.parsed,e)&&!1!==o.when?.()&&n(o,e)&&(o.allowInInput||!Mi(r))){e.preventDefault();try{o.run(e)}catch(e){wi(`${o.id} threw on`,o.combo),console.warn(e)}return}};return r?.addEventListener("keydown",o),{register(e){let r=xi(e.combo);if(!r)return()=>{};let n=`${r.mod?"m":""}${r.shift?"s":""}${r.alt?"a":""}${r.key}`,o=t.get(n);return o?(wi(`${o.id} already owns`,e.combo),()=>{}):(t.set(n,{...e,parsed:r}),e.element?.setAttribute("aria-keyshortcuts",ki(e.combo)),()=>{t.get(n)?.id===e.id&&t.delete(n),e.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),r?.removeEventListener("keydown",o)}}};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,o){if(!1===o.callbacks.beforeNodeAdded(t))return null;if(o.idMap.has(t)){let a=document.createElement(t.tagName);return e.insertBefore(a,r),n(a,t,o),o.callbacks.afterNodeAdded(a),a}{let n=document.importNode(t,!0);return e.insertBefore(n,r),o.callbacks.afterNodeAdded(n),n}}let t=function(){function e(e,t,r){let n=e.idMap.get(t),o=e.idMap.get(r);if(!o||!n)return!1;for(let e of n)if(o.has(e))return!0;return!1}function t(e,t){let r=e,n=t;return r.nodeType===n.nodeType&&r.tagName===n.tagName&&(!r.getAttribute?.("id")||r.getAttribute?.("id")===n.getAttribute?.("id"))}return function(r,n,o,a){let s=null,i=n.nextSibling,l=0,d=o;for(;d&&d!=a;){if(t(d,n)){if(e(r,d,n))return d;null===s&&(r.idMap.has(d)||(s=d))}if(null===s&&i&&t(d,i)&&(l++,i=i.nextSibling,l>=2&&(s=void 0)),r.activeElementAndParents.includes(d))break;d=d.nextSibling}return s||null}}();function r(e,t){if(e.idMap.has(t))s(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;t.parentNode?.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function o(e,t,n){let o=t;for(;o&&o!==n;){let t=o;o=o.nextSibling,r(e,t)}return o}function a(e,t,r,n){let o=n.target.getAttribute?.("id")===t&&n.target||n.target.querySelector(`[id="${t}"]`)||n.pantry.querySelector(`[id="${t}"]`);return function(e,t){let r=e.getAttribute("id");for(;e=e.parentNode;){let n=t.idMap.get(e);n&&(n.delete(r),n.size||t.idMap.delete(e))}}(o,n),s(e,o,r),o}function s(e,t,r){if(e.moveBefore)try{e.moveBefore(t,r)}catch{e.insertBefore(t,r)}else e.insertBefore(t,r)}return function(s,i,l,d=null,c=null){i instanceof HTMLTemplateElement&&l instanceof HTMLTemplateElement&&(i=i.content,l=l.content),d||=i.firstChild;for(let r of l.childNodes){if(d&&d!=c){let e=t(s,r,d,c);if(e){e!==d&&o(s,d,e),n(e,r,s),d=e.nextSibling;continue}}if(r instanceof Element){let e=r.getAttribute("id");if(s.persistentIds.has(e)){let t=a(i,e,d,s);n(t,r,s),d=t.nextSibling;continue}}let l=e(i,r,d,s);l&&(d=l.nextSibling)}for(;d&&d!=c;){let e=d;d=d.nextSibling,r(s,e)}}}(),n=function(){function e(e,r,n){let a=r.nodeType;if(1===a){let a=e,i=r,l=a.attributes,d=i.attributes;for(let e of d)o(e.name,a,"update",n)||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(o(t.name,a,"remove",n))continue;a.removeAttribute(t.name)}}s(a,n)||t(a,i,n)}(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;n(e,t,"checked",r),n(e,t,"disabled",r),t.hasAttribute("value")?s!==a&&(o("value",e,"update",r)||(e.setAttribute("value",a),e.value=a)):o("value",e,"remove",r)||(e.value="",e.removeAttribute("value"))}else if(e instanceof HTMLOptionElement&&t instanceof HTMLOptionElement)n(e,t,"selected",r);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let n=t.value,a=e.value;if(o("value",e,"update",r))return;n!==a&&(e.value=n),e.firstChild&&e.firstChild.nodeValue!==n&&(e.firstChild.nodeValue=n)}}function n(e,t,r,n){let a=t[r];if(a!==e[r]){let s=o(r,e,"update",n);s||(e[r]=t[r]),a?s||e.setAttribute(r,""):o(r,e,"remove",n)||e.removeAttribute(r)}}function o(e,t,r,n){return!("value"!==e||!n.ignoreActiveValue||t!==document.activeElement)||!1===n.callbacks.beforeAttributeUpdated(e,t,r)}function s(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(t,n,o){return o.ignoreActive&&t===document.activeElement?null:(!1===o.callbacks.beforeNodeMorphed(t,n)||(t instanceof HTMLHeadElement&&o.head.ignore||(t instanceof HTMLHeadElement&&"morph"!==o.head.style?a(t,n,o):(e(t,n,o),s(t,o)||r(o,t,n))),o.callbacks.afterNodeMorphed(t,n)),t)}}();function o(e,t,r,n){if(e.head.block){let o=t.querySelector("head"),s=r.querySelector("head");if(o&&s){let t=a(o,s,e);return Promise.all(t).then(()=>n(Object.assign(e,{head:{block:!1,ignore:!0}})))}}return n(e)}function a(e,t,r){let n=[],o=[],a=[],s=[],i=new Map;for(let e of t.children)i.set(e.outerHTML,e);for(let t of e.children){let e=i.has(t.outerHTML),n=r.head.shouldReAppend(t),l=r.head.shouldPreserve(t);e||l?n?o.push(t):(i.delete(t.outerHTML),a.push(t)):"append"===r.head.style?n&&(o.push(t),s.push(t)):!1!==r.head.shouldRemove(t)&&o.push(t)}s.push(...i.values());let l=[];for(let t of s){let o=document.createRange().createContextualFragment(t.outerHTML).firstChild;if(!1!==r.callbacks.beforeNodeAdded(o)){if("href"in o&&o.href||"src"in o&&o.src){let e,t=new Promise(function(t){e=t});o.addEventListener("load",function(){e()}),l.push(t)}e.appendChild(o),r.callbacks.afterNodeAdded(o),n.push(o)}}for(let t of o)!1!==r.callbacks.beforeNodeRemoved(t)&&(e.removeChild(t),r.callbacks.afterNodeRemoved(t));return r.head.afterHeadMorphed(e,{added:n,kept:a,removed:o}),l}let 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 n(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 o(e){let t=Array.from(e.querySelectorAll("[id]"));return e.getAttribute?.("id")&&t.push(e),t}function a(e,t,r,n){for(let o of n){let n=o.getAttribute("id");if(t.has(n)){let t=o;for(;t;){let o=e.get(t);if(o??(o=new Set,e.set(t,o)),o.add(n),t===r)break;t=t.parentElement}}}}function s(e,t){let r=o(e),n=o(t),s=function(e,t){let r=new Set,n=new Map;for(let{id:t,tagName:o}of e)n.has(t)?r.add(t):n.set(t,o);let o=new Set;for(let{id:e,tagName:a}of t)o.has(e)?r.add(e):n.get(e)===a&&o.add(e);for(let e of r)o.delete(e);return o}(r,n),i=new Map;return a(i,s,e,r),a(i,s,t.__idiomorphRoot||t,n),{persistentIds:s,idMap:i}}return function(t,o,a){let{persistentIds:i,idMap:l}=s(t,o),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:o,config:d,morphStyle:c,ignoreActive:d.ignoreActive,ignoreActiveValue:d.ignoreActiveValue,restoreFocus:d.restoreFocus,idMap:l,persistentIds:i,pantry:r(),activeElementAndParents:n(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 n=r.querySelectorAll(e);for(let e=0;e<n.length;e++)t.push(n[e])}return t},[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function r(n){if(null==n)return document.createElement("div");if("string"==typeof n)return r(function(t){let r=new DOMParser,n=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let o=r.parseFromString(t,"text/html");if(n.match(/<\/html>/))return e.add(o),o;{let t=o.firstChild;return t&&e.add(t),t}}{let n=r.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(n),n}}(n));if(e.has(n))return n;if(n instanceof Node){if(n.parentNode)return new t(n);{let e=document.createElement("div");return e.append(n),e}}{let e=document.createElement("div");for(let t of[...n])e.append(t);return e}}}}();return{morph:function(e,t,n={}){e=i(e);let a=l(t),d=s(e,a,n),c=function(e,t){if(!e.config.restoreFocus)return t();let r=document.activeElement;if(!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return t();let{id:n,selectionStart:o,selectionEnd:a}=r,s=t();return n&&n!==document.activeElement?.getAttribute("id")&&(r=e.target.querySelector(`[id="${n}"]`),r?.focus()),r&&!r.selectionEnd&&a&&r.setSelectionRange(o,a),s}(d,()=>o(d,e,a,t=>"innerHTML"===t.morphStyle?(r(t,e,a),Array.from(e.childNodes)):function(e,t,n){let o=l(t);return r(e,o,n,t,t.nextSibling),Array.from(o.childNodes)}(t,e,a)));return d.pantry.remove(),c},defaults:t}}();let Ti=(e,t,r={})=>{let{preserveTypingAnimation:n=!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(n){if(e.classList.contains("persona-animate-typing")||e.hasAttribute("data-preserve-runtime"))return!1;if(e.hasAttribute("data-tool-elapsed"))return!(t instanceof HTMLElement&&t.getAttribute("data-tool-elapsed")===e.getAttribute("data-tool-elapsed"))&&void 0;if(e.hasAttribute("data-preserve-animation"))return t instanceof HTMLElement&&(!t.hasAttribute("data-preserve-animation")||(e.dataset.personaLoadingLabel?e.dataset.personaLoadingAnimation!==t.dataset.personaLoadingAnimation:e.textContent!==t.textContent))&&void 0}}}}})},Ei={index:-1,draft:""},Li=new WeakMap;function Bi(e){if("string"==typeof e)return e.length;if(!e)return 0;if("object"!=typeof e)return JSON.stringify(e)?.length??0;let t=Li.get(e);return void 0===t&&(t=JSON.stringify(e)?.length??0,Li.set(e,t)),t}function Ri(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.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)??"",Bi(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 Pi=["pre","code","a","script","style"],Ni=e=>({type:e?.type??"none",placeholder:e?.placeholder??"none",speed:e?.speed??120,duration:e?.duration??1800,buffer:e?.buffer??"none"}),$i=[{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"}],Wi=new Map;for(let e of $i)Wi.set(e.name,e);let Hi=["wipe","glyph-cycle"],Di=e=>{Wi.set(e.name,e)},Oi=(e,t)=>"none"===e?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Wi.get(e)??null,Fi=(e,t,r,n,o)=>{if(!o)return e;if(r?.bufferContent)return r.bufferContent(e,n);if(!e)return e;if("word"===t){let t=e.search(/\s(?=\S*$)/);return t<0?"":e.slice(0,t)}if("line"===t){let t=e.lastIndexOf("\n");return t<0?"":e.slice(0,t)}return e},zi=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${r}-${n}`,o.style.setProperty("--char-index",String(n)),o.textContent=t,o},ji=(e,t,r,n)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${r}-${n}`,o.style.setProperty("--word-index",String(n)),o.textContent=t,o},qi=/\s/,_i=(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},Ui=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=0;for(;i<a.length;)if(qi.test(a[i])){let e=i;for(;e<a.length&&qi.test(a[e]);)e+=1;s.appendChild(n.createTextNode(a.slice(i,e))),i=e}else{let e=n.createElement("span");e.className="persona-stream-word-group";let o=i;for(;o<a.length&&!qi.test(a[o]);)e.appendChild(zi(n,a[o],t,r.value)),r.value+=1,o+=1;s.appendChild(e),i=o}o.replaceChild(s,e)},Vi=(e,t,r)=>{let n=e.ownerDocument,o=e.parentNode;if(!n||!o)return;let a=e.nodeValue??"";if(!a)return;let s=n.createDocumentFragment(),i=a.split(/(\s+)/);for(let e of i)e&&(/^\s+$/.test(e)?s.appendChild(n.createTextNode(e)):(s.appendChild(ji(n,e,t,r.value)),r.value+=1));o.replaceChild(s,e)},Ki=(e,t,r,n)=>{if(!e||typeof document>"u")return e;let o=document.createElement("div");o.innerHTML=e;let a=new Set((n?.skipTags??Pi).map(e=>e.toLowerCase())),s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],l=s.nextNode();for(;l;)_i(l,a)||i.push(l),l=s.nextNode();let d={value:n?.startIndex??0},c="char"===t?Ui:Vi;for(let e of i)c(e,r,d);return o.innerHTML},Qi=(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},Ji=(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},Gi=new WeakMap,Yi=new WeakMap,Xi=e=>{let t=Yi.get(e);if(t){for(let e of t.values())"function"==typeof e&&e();t.clear()}},Zi=(e,t)=>{((e,t)=>{if(!e.styles)return;let r=Gi.get(t);if(r||(r=new Set,Gi.set(t,r)),r.has(e.name)){let n=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${n}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)})(e,t),((e,t)=>{if(!e.onAttach)return;let r=Yi.get(t);if(r||(r=new Map,Yi.set(t,r)),r.has(e.name))return;let n=e.onAttach(t);r.set(e.name,n)})(e,t)},{setLoader:el,load:tl}=_({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),rl=el,nl=tl;function ol(e,t=1e5){let r=e.style.position,n=e.style.zIndex,o=e.style.isolation,a=getComputedStyle(e),s="static"===a.position||""===a.position;return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=n,e.style.isolation=o}}let al=0,sl=null;function il(e=document){if(al++,1===al){let t=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;sl={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,al=Math.max(0,al-1),0===al&&sl)){let t=e.body,r=e.defaultView??window;t.style.overflow=sl.originalOverflow,t.style.position=sl.originalPosition,t.style.top=sl.originalTop,t.style.width=sl.originalWidth,r.scrollTo(0,sl.scrollY),sl=null}}}let ll=e=>"docked"===(e?.launcher?.mountMode??"floating"),dl=e=>"composer-bar"===(e?.launcher?.mountMode??"floating"),cl=e=>{let t=e?.launcher?.dock,r=ns(e).dockWidth?t?.width:Vs(ci(e),"components.panel.width");return{side:t?.side??"right",width:r??"420px",animate:t?.animate??!0,reveal:t?.reveal??"resize",maxHeight:t?.maxHeight??"100dvh"}},pl=e=>e.closest("[data-persona-instance]")?.dataset.personaInstance,ul=e=>"followUp"===e?"follow-up":e,hl=(e,t=0)=>{if("string"==typeof e){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:"default"}:null}let r=e.label.trim();if(!r)return null;let n=e.prompt?.trim()||r;return{id:e.id?.trim()||n||`suggestion-${t}`,label:r,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},ml=new WeakSet,gl=e=>{let{item:t,index:r,surface:n,source:o,variant:a,streaming:s,config:i,plugins:l,chipsConfig:d,session:c,getTextarea:p,eventTarget:u,submitPrompt:h}=e,m="followUp"===n,g=t.behavior,f=()=>{if(c.isStreaming()||u.closest("[inert]"))return;let e={instanceId:pl(u),suggestion:{...t},surface:n,source:o,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:pl(u),suggestion:t.prompt},bubbles:!0,composed:!0})),!r)return;for(let e of l)if(!1===e.onSuggestionSelect?.({suggestion:{...t},surface:n,source:o,variant:a,config:i}))return;let s=p();"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}`),n=e=>j(i,`suggestion.chip.${e}`,"light")||j(i,`suggestion.chip.${e}`,"dark");d?.fontWeight&&(e.style.fontWeight=!r("fontWeight")&&n("fontWeight")?"var(--persona-suggestion-compat-weight, 500)":d.fontWeight);let o=n("padding");o&&(e.classList.add("persona-theme-padding"),e.style.setProperty("--persona-theme-padding","var(--persona-suggestion-compat-padding, 6px 12px)")),d?.paddingX&&(r("paddingX")||!o)&&(e.style.paddingLeft=d.paddingX,e.style.paddingRight=d.paddingX),d?.paddingY&&(r("paddingY")||!o)&&(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=oe(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:n,source:o,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},fl=e=>{let t=[],r=[],n=null,o=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(o=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),n=parseFloat(r.paddingLeft)||0,o=parseFloat(r.paddingRight)||0;e.style.setProperty("--persona-suggestion-bleed-left",`${n}px`),e.style.setProperty("--persona-suggestion-bleed-right",`${o}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:n}px`),e.style.setProperty("--persona-suggestion-inset-right",`${i?.width?s.right-i.right:o}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,n=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),s=n<=4,i=n>=t-4,l=r?!i:!s,d=r?!s:!i;e.toggleAttribute("data-scroll-left",l),e.toggleAttribute("data-scroll-right",d)},i=()=>{null!==o||"function"!=typeof requestAnimationFrame?"function"!=typeof requestAnimationFrame&&s():o=requestAnimationFrame(s)};e.addEventListener("scroll",i,{passive:!0});let l="function"==typeof ResizeObserver?new ResizeObserver(i):null;return l?.observe(e),{buttons:t,elements:r,destroy:()=>{e.removeEventListener("scroll",i),l?.disconnect(),null!==o&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o),o=null},render:(o,l,d,c,p,u)=>{e.replaceChildren(),t.length=0,r.length=0;let h=u?.source??"config",m=u?.surface??("config"===h?"starter":"followUp"),g="followUp"===m,f=u?.variant??"chip",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";!ml.has(v)&&!0===v.debug&&"chip"!==f&&void 0!==v.suggestions?.[C]?.overflow&&(ml.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(hl).filter(e=>null!==e).map(e=>({...e,behavior:e.behavior??b})),k=S(o??[]);w.forEach(e=>{e.transformSuggestions&&(k=S(e.transformSuggestions({suggestions:k.map(e=>({...e})),surface:m,source:h,config:v})))});let A=void 0===x?k:k.slice(0,x);if(!A.length)return e.hidden=!0,n=null,void a();if(!g&&(c??l.getMessages()).some(e=>"user"===e.role))return e.hidden=!0,void(n=null);e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=ul(m),e.dataset.variant=f,e.dataset.overflow=y;let M=document.createDocumentFragment(),I=l.isStreaming();A.forEach((n,o)=>{let a=gl({item:n,index:o,surface:m,source:h,variant:f,streaming:I,config:v,plugins:w,chipsConfig:p,session:l,getTextarea:()=>d,eventTarget:e,submitPrompt:u?.submitPrompt});M.appendChild(a),r.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll("button"))].forEach(e=>{t.includes(e)||(e.disabled=I,t.push(e))})}),e.appendChild(M),s(),i();let T=JSON.stringify({normalized:A,surface:m,variant:f,source:h});T!==n&&(n=T,(e=>{typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||e.forEach((e,t)=>{"function"==typeof e.animate&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:60*t,easing:"ease-out",fill:"backwards"})})})(r),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{instanceId:pl(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:pl(e),suggestions:A.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},bl={"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"},yl={x:[1.4,1.05]},vl="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",wl=(e,t,r={})=>{let{iconSize:n,iconText:o}=r,[a,s]=yl[t]??[1,1.5],i=!n;e.classList.toggle("persona-header-control--glyph",i),e.classList.toggle("persona-header-control--sparse",i&&1!==a);let l=Ee(t,`${Math.round((parseFloat(n??"")||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)):o&&(e.textContent=o)},xl=e=>{let{ariaLabel:t,tooltip:r=!0,tooltipHint:n,iconName:o,iconText:a,wrapperClassName:s=vl,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||Al.actionIconColor,backgroundColor:c,border:w?`${p||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:h,paddingLeft:m,paddingRight:m,paddingTop:g,paddingBottom:g}});return o?wl(x,o,{iconSize:l,iconText:a}):a&&(x.textContent=a),v.appendChild(x),Ja({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??t,hint:n,enabled:r}),{button:x,wrapper:v}},Cl=(e,t,r,n={})=>{let o=t?.launcher,a=o?.clearChat,s=e=>Ya(t,(e=>"close"===r?`launcher.closeButton${e[0].toUpperCase()}${e.slice(1)}`:`launcher.clearChat.${"color"===e?"iconColor":e}`)(e)),i=(e,n)=>Ga(t,`header.${r}`,e,n),l=(e,t,r)=>s(e)||i(t,r),d=n.buttonSize||s("size");Za(e,d||i("size","var(--persona-header-control-size, 32px)"),d),!d&&""===i("size","")&&(e.style.width=e.style.height="");let c="close"===r?o?.closeButtonBackgroundColor:a?.backgroundColor;e.style.color=l("color","foreground",Al.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?o?.closeButtonBorderWidth:a?.borderWidth,u="close"===r?o?.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?o?.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?o?.closeButtonPaddingX:a?.paddingX,f="close"===r?o?.closeButtonPaddingY:a?.paddingY,b=i("padding","0px");Xa(e,b,s("paddingX")||("0px"===b?g:void 0),s("paddingY")||("0px"===b?f:void 0));let y="close"===r?o?.closeButtonIconName??"x":a?.iconName??"refresh-cw";wl(e,y,{iconSize:n.iconSize,iconText:"close"===r?o?.closeButtonIconText??"×":void 0});let v=e.querySelector("svg");if(v){let e=yl[y]?.[0]??1,t=i("iconSize","");!n.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})`)}},Sl=(e,t={})=>{let{showClose:r=!0,wrapperClassName:n=vl,buttonSize:o,iconSize:a}=t,s=e?.launcher??{},i=s.closeButtonTooltipText??"Close chat",l=s.closeButtonShowTooltip??!0,{button:d,wrapper:c}=xl({ariaLabel:i,tooltip:l,iconName:s.closeButtonIconName??"x",iconText:s.closeButtonIconText??"×",wrapperClassName:n,size:o??s.closeButtonSize,iconSize:a,color:s.closeButtonColor,backgroundColor:s.closeButtonBackgroundColor,borderWidth:s.closeButtonBorderWidth,borderColor:s.closeButtonBorderColor,borderRadius:s.closeButtonBorderRadius,paddingX:s.closeButtonPaddingX,paddingY:s.closeButtonPaddingY,hidden:!r});return Cl(d,e,"close",{buttonSize:o,iconSize:a}),{button:d,wrapper:c}},kl=(e,t={})=>{let{wrapperClassName:r="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",buttonSize:n,iconSize:o}=t,a=(e?.launcher??{}).clearChat??{},s=a.tooltipText??"Clear chat",i=a.showTooltip??!0,{button:l,wrapper:d}=xl({ariaLabel:s,tooltip:i,iconName:a.iconName??"refresh-cw",wrapperClassName:r,size:n??a.size,iconSize:o,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return Cl(l,e,"clear",{buttonSize:n,iconSize:o}),{button:l,wrapper:d}},Al={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)"},Ml={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)"},Il={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)"},Tl=e=>{let{config:t,showClose:r=!0}=e,n=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:Al.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=t?.launcher??{},a=o.headerIconSize??"40px",s=o.closeButtonPlacement??"inline",i=o.headerIconHidden??!1,l=o.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:Al.titleColor,...Ml}}),u=it("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Al.subtitleColor,...Il}});c.append(p,u),i?n.append(c):n.append(d,c);let h=o.clearChat??{},m=h.enabled??!0,g=h.placement??"inline",f=null,b=null;if(m){let e=kl(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&&n.appendChild(b)}let{button:y,wrapper:v}=Sl(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&&n.appendChild(v),{header:n,iconHolder:d,headerTitle:p,headerSubtitle:u,closeButton:y,closeButtonWrapper:v,clearChatButton:f,clearChatButtonWrapper:b}},El=(e,t,r)=>{let n=r?.launcher??{},o=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),"top-right"===o&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&"top-right"===a&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))},Ll=e=>{let t=Tl({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},Bl=e=>{let{config:t,showClose:r=!0,onClose:n,layoutHeaderConfig:o,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=Al.minHeight,i.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let l,d,c=o?.titleMenu;if(c){let e=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}}))},n=c.onSelect(t);n instanceof Promise?n.then(r,()=>{}):r(n)},hover:c.hover,className:""});l=e.element,l.style.color=Al.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=Al.titleColor,Object.assign(d.style,Ml),d.textContent=s.title??"Chat Assistant",l.appendChild(d),o?.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let e=o.onTitleClick;l.addEventListener("click",t=>{t.target.closest("button")||e()}),l.addEventListener("keydown",t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),e())})}let e=o?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??"10px",l.style.padding=e.padding??"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{l.style.backgroundColor=e.background??"",l.style.borderColor=e.border??""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:u,wrapper:h}=Sl(t,{showClose:r,wrapperClassName:p});n&&u.addEventListener("click",n);let m=st("div","persona-flex persona-items-center persona-gap-1");c||function(e,t,r){if(t?.length)for(let n of t){let{button:t,wrapper:o}=xl({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?Si(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(t.setAttribute("data-persona-header-action",n.id),n.shortcut){let e=ki(n.shortcut);e&&t.setAttribute("aria-keyshortcuts",e)}if(n.menuItems?.length){let e=ct({items:n.menuItems,onSelect:e=>r?.(e),anchor:o,position:"bottom-right"});o.appendChild(e.element),t.addEventListener("click",t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener("click",()=>r?.(n.id));e.appendChild(o)}}(m,o?.trailingActions,o?.onAction??a);let g=s.clearChat??{},f=null,b=null;if(g.enabled??1){let e=g.placement??"inline",r=kl(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}},Rl={default:Ll,minimal:Bl},Pl=e=>Rl[e]??Rl.default,Nl=(e,t,r)=>{if(t?.render){let n=t.render({config:e,onClose:r?.onClose,onClearChat:r?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),o=st("div");o.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:n,iconHolder:o,headerTitle:a,headerSubtitle:s,closeButton:i,closeButtonWrapper:l,clearChatButton:null,clearChatButtonWrapper:null}}let n=Pl(t?.layout??"default")({config:e,showClose:t?.showCloseButton??r?.showClose??!0,onClose:r?.onClose,onClearChat:r?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(!1===t.showIcon&&(n.iconHolder.style.display="none"),!1===t.showTitle&&(n.headerTitle.style.display="none"),!1===t.showSubtitle&&(n.headerSubtitle.style.display="none"),!1===t.showCloseButton&&(n.closeButton.style.display="none"),!1===t.showClearChat&&n.clearChatButtonWrapper&&(n.clearChatButtonWrapper.style.display="none")),n};function $l(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 Wl=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"}}),n=Ms(),o=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}=bs(t);s();let i=xs(t),l=Ss(t),d=ks(t),c=As(t),p=it("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(p),d&&(p.append(d.previewsContainer),o.append(d.input)),o.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),o.append(u),o.addEventListener("click",e=>{$l(o,e)}),"transient"===t?.statusIndicator?.mode?r.append(n,c,o):r.append(n,o,c),{footer:r,suggestions:n,composerForm:o,header:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}},Hl=e=>{let{config:t}=e,r=it("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Ms(),o=As(t);o.style.display="none";let{textarea:a,attachAutoResize:s}=bs(t,{defaultMaxLines:5});s();let i=xs(t),l=Ss(t),d=ks(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=>{$l(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(n,c,o);let m=c;return{footer:r,suggestions:n,composerForm:c,header:h,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:l?.button??null,micButtonWrapper:l?.wrapper??null,statusText:o,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:p,rightActions:u,setSendButtonMode:i.setMode}};function Dl(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 n=Ee(e.iconName??"at-sign",13,"currentColor",2);if(n){let e=st("span","persona-mention-token-icon");e.appendChild(n),r.appendChild(e)}return r.appendChild(it("span",{className:"persona-mention-token-label",text:`@${e.label}`})),r}let Ol=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(":"))},Fl=(e={})=>{let t=e.loadingIndicator,r=e.future?.v5Defaults;if("label"===(t?.variant??(r?"label":"dots"))){let n=it("div",{className:"persona-loading-label",attrs:{role:"status"}});r&&!0!==t?.showBubble&&n.classList.add("persona-activity-row","persona-activity-header");let o=e.features?.toolCallDisplay,a=t?.iconVisibility??(!1!==o?.grouped&&"collapsible"===(o?.groupedMode??"collapsible")?o?.groupIconVisibility:void 0)??o?.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"),n.appendChild(e))}let i=it("span",{text:t?.label??"Thinking…"});return n.appendChild(i),qe()?.applyLoadingLabel(i,e,"waiting"),n}let n=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",n.appendChild(t)}let o=st("span","persona-sr-only");return o.textContent="Loading",n.appendChild(o),n},zl=(e,t,r)=>t?.({config:r??{},streaming:!0,location:e,defaultRenderer:()=>Fl(r)})??Fl(r),jl=(e,t,r="div")=>{let n=st(r,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return n.textContent=t.format?t.format(o):o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ql=(e,t="bubble")=>{let r=["persona-message-bubble"];switch(t){case"flat":"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),"user"===e?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3")}return r},_l={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"}},Ul=(e,t,r="bubble",n)=>{if(!n)return;let o="user"===t?"user":"assistant",a=_l[r??"bubble"]??_l.bubble;n.padding&&(e.style.padding=`var(--persona-message-${o}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${o}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${o}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${o}-font-family, inherit)`)},Vl=e=>`custom:${e}`,Kl=(e,t)=>"user"!==t&&"assistant"!==t?[]:(e?.custom??[]).filter(e=>(e.roles??["assistant"]).includes(t)),Ql=(e,t,r,n,o=!1)=>{let a=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&!0===n?.canRegenerate,c=(t.showEdit??!1)&&!0===n?.canEdit,p=(t.showQuote??!1)&&!1!==n?.canQuote,u=Kl(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??(o&&n?.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":""} ${o?"persona-message-actions-adaptive":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let b=(e,t,r)=>{let n=pt({icon:e,label:t,size:14,className:"persona-message-action-btn",chromeless:!0});return n.setAttribute("data-action",r),n};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,Vl(e.id)));return f},Jl=(e,t,r,n,o,a)=>{let s=r??{},i=s.layout??"bubble",l=s.avatar,d=s.timestamp,c=l?.show??!1,p=d?.show??!1,u=l?.position??"left",h=d?.position??"below",m=ql(e.role,i),g=st("div",m.join(" "));g.id=`bubble-${e.id}`,g.setAttribute("data-message-id",e.id),g.setAttribute("data-persona-theme-zone","user"===e.role?"user-message":"assistant-message");let f=Us(a?.widgetConfig?.future).components.message,b=a?.widgetConfig?.theme?.components?.message;Ul(g,e.role,i,"user"===e.role?{...f.user,...b?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...f.assistant,...b?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),"flat"===i?(g.style.backgroundColor="transparent",g.style.color="user"===e.role?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):"user"===e.role?(g.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",g.style.color="var(--persona-message-user-text, white)"):"assistant"===e.role&&(g.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",g.style.color="var(--persona-message-assistant-text, var(--persona-text))");let y=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"image"===e.type&&"string"==typeof e.image&&e.image.trim().length>0):[])(e),v=e.content?.trim()??"",w=y.length>0&&"[Image]"===v,x=Ni(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,S="assistant"===e.role&&"none"!==x.type?Oi(x.type,C):null,k="assistant"===e.role&&!0===S?.isAnimating?.(e),A="assistant"===e.role&&null!==S&&(!!e.streaming||k);A&&S?.bubbleClass&&g.classList.add(S.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),A&&S&&(S.containerClass&&M.classList.add(S.containerClass),M.style.setProperty("--persona-stream-step",`${x.speed}ms`),M.style.setProperty("--persona-stream-duration",`${x.duration}ms`));let I=A?Fi(e.content??"",x.buffer,S,e,!!e.streaming):e.content??"",T=()=>{let r=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent});return A&&"char"===S?.wrap?Ki(r,"char",e.id,{skipTags:S.skipTags}):A&&"word"===S?.wrap?Ki(r,"word",e.id,{skipTags:S.skipTags}):r},E=null;if(w?(E=document.createElement("div"),E.innerHTML=T(),E.style.display="none",M.appendChild(E)):e.contentSegments?.length?((e,t,r,n)=>{let o=Math.random().toString(36).slice(2,8),a=e=>`${o}:${e}`,s=r(t.map((e,t)=>"text"===e.kind?e.text:a(t)).join(""));if(!t.every((e,t)=>"text"===e.kind||s.includes(a(t))))return void e.replaceChildren(((e,t)=>{let r=document.createDocumentFragment();for(let n of e)"text"===n.kind?r.appendChild(document.createTextNode(n.text)):r.appendChild(Dl(n.ref,{readonly:!0,render:t}));return r})(t,n));e.innerHTML=s;let i=RegExp(`${o}:(\\d+)`),l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),d=[];for(let e=l.nextNode();e;e=l.nextNode())d.push(e);for(let e of d){let r=e;for(let e=i.exec(r.data);e;e=i.exec(r.data)){let o=t[Number(e[1])],a=r.splitText(e.index);a.data=a.data.slice(e[0].length),"mention"===o?.kind&&a.parentNode?.insertBefore(Dl(o.ref,{readonly:!0,render:n}),a),r=a}}})(M,e.contentSegments,r=>t({text:r,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=T(),A&&S?.useCaret&&!w&&v){let e=Qi(),t=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),r=t[t.length-1];if(r?.parentNode)r.parentNode.insertBefore(e,r.nextSibling);else{let t=M.lastElementChild;t?t.appendChild(e):M.appendChild(e)}}if(p&&"inline"===h&&e.createdAt){let t=jl(e,d,"span");t.classList.add("persona-timestamp-inline");let r=M.lastElementChild;r?r.appendChild(t):M.appendChild(t)}if(y.length>0){let e=((e,t,r)=>{if(0===e.length)return null;try{let n=st("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let o=0,a=!1,s=()=>{a||(a=!0,n.remove(),r?.())};return e.forEach((e,t)=>{let r=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;o+=1,r.addEventListener("error",()=>{a||(a=!0,o=Math.max(0,o-1),r.remove(),0===o&&s())}),r.addEventListener("load",()=>{a=!0}),(e=>{let t=e.toLowerCase();return!(t.startsWith("data:image/svg+xml")||!/^(?:https?|blob):/i.test(e)&&!t.startsWith("data:image/")&&e.includes(":"))})(e.image)?(r.src=e.image,n.appendChild(r)):(a=!0,o=Math.max(0,o-1),r.remove())}),0===o?(s(),null):n}catch{return r?.(),null}})(y,!w&&!!v,()=>{w&&E&&(E.style.display="")});e?g.appendChild(e):w&&E&&(E.style.display="")}let L=(e=>e.contentParts&&0!==e.contentParts.length?e.contentParts.filter(e=>"audio"===e.type&&"string"==typeof e.audio&&e.audio.trim().length>0):[])(e);if(L.length>0){let e=(e=>{if(0===e.length)return null;try{let t=st("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(e=>{if(!Ol(e.audio))return;let n=st("audio");n.controls=!0,n.preload="metadata",n.src=e.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(L);e&&g.appendChild(e)}let B=(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(B.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(!Ol(e.video))return;let n=st("video");n.controls=!0,n.preload="metadata",n.src=e.video,n.style.display="block",n.style.width="100%",n.style.maxWidth="320px",n.style.maxHeight="320px",n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(B);e&&g.appendChild(e)}let R=(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(R.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(!Ol(e.data))return;let n=st("a");n.href=e.data,n.download=e.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=e.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),0===r?(t.remove(),null):t}catch{return null}})(R);e&&g.appendChild(e)}let P=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}}),n=st("span","persona-mention-chip-icon"),o=Ee(r.iconName??"at-sign",13,"currentColor",2);o&&n.appendChild(o),e.appendChild(n),e.appendChild(it("span",{className:"persona-mention-chip-label",text:r.label})),t.appendChild(e)}return t})(e.contextMentions);if(P&&g.appendChild(P),g.appendChild(M),p&&"below"===h&&e.createdAt){let t=jl(e,d);t.classList.add("persona-mt-1"),g.appendChild(t)}let N="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 n=t?.[e];return(void 0===n?r:n)||null})(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&"assistant"===e.role){let e=!(!I||!I.trim()),t="skeleton"===x.placeholder,r=t&&"line"===x.buffer&&e;if(e)r&&g.appendChild(Ji());else if(t)g.appendChild(Ji());else{let e=zl("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);e&&g.appendChild(e)}}N&&e.stopReason&&!e.streaming&&(v||(M.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,N)));let $="assistant"===e.role&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&!1!==n?.enabled,W=a?.actionEligibility,H="user"===e.role&&!e.streaming&&!1!==n?.enabled&&(!0===n?.showEdit&&!0===W?.canEdit||!0===n?.showQuote&&!0===W?.canQuote||Kl(n,"user").length>0);if(($||H)&&n){let t=Ql(e,H?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,0,W,!0===a?.widgetConfig?.future?.v5Defaults&&void 0===n.visibility);g.appendChild(t)}if(!c||"system"===e.role)return g;let D=st("div","persona-message-with-avatar persona-flex persona-gap-2 "+("user"===e.role?"persona-flex-row-reverse":"")),O=((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"),n="user"===t?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let e=st("img");e.src=n,e.alt="user"===t?"User":"Assistant",e.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(e)}else r.textContent=n,r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent="user"===t?"U":"A",r.classList.add("user"===t?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r})(l,e.role);return"right"===u||"left"===u&&"user"===e.role?D.append(g,O):D.append(O,g),D},Gl=(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)},Yl=(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")},Xl="data-persona-welcome-overlay",Zl="persona-welcome-overlay-active",ed=new WeakMap,td=(e,t,r)=>{r.setAttribute("data-persona-welcome-plugin",""),t.appendChild(r),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Xl,""),e.classList.contains(Zl)||(ed.set(e,e.scrollTop),e.classList.add(Zl),e.scrollTop=0)},rd=(e,t,r)=>{r&&r!==t&&r.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Xl),e.classList.contains(Zl)&&(e.classList.remove(Zl),e.scrollTop=ed.get(e)??e.scrollTop,ed.delete(e))},nd=(e,t,r)=>{if(e.replaceChildren(),!t)return void(e.hidden=!0);let n=r?.layout?.messages?.layout??"bubble",o=it("div",{className:ql("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:"flat"===n?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(it("div",{className:"persona-flex"},o)),e.hidden=!1},od=()=>typeof window<"u"&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ad=(e,t)=>{if(od()||"function"!=typeof e.animate||!e.isConnected)return t(null),null;let r=e.getBoundingClientRect(),n=e.parentElement,o=0,a=0,s=0;if(n){let t=getComputedStyle(n);o=parseFloat(t.rowGap)||0;let i=e.previousElementSibling,l=e.nextElementSibling,d=n.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-n.scrollTop;a=Math.max(0,i?r.top-i.getBoundingClientRect().bottom-o:r.top-d),s=Math.max(0,l?l.getBoundingClientRect().top-r.bottom-o:0)}let i=e.style.overflow;e.style.overflow="hidden";let l=getComputedStyle(e),d=parseFloat(l.paddingTop)||0,c=parseFloat(l.paddingBottom)||0,p=e.animate([{opacity:"1",transform:"none",height:`${r.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${c}px`,marginTop:`${a}px`,marginBottom:`${s}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:-o+"px"}],{duration:180,easing:"ease-out",fill:"forwards"}),u=!1,h=()=>{u||(u=!0,e.style.overflow=i,t(p))};return p.finished.then(h).catch(h),p},sd=(e,t,r,n=260)=>{if(t<=1||od()||"function"!=typeof e.animate||!e.isConnected)return null;let o="drop"===r?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:n,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})},id=new WeakSet,ld=(e,t)=>!!e&&void 0!==e[t],dd=(e,t=!0===e?.launcher?.fullHeight&&!e.launcher.sidebarMode&&"docked"!==e.launcher.mountMode)=>{let r=e?.welcome,n=e?.copy,o=!0===e?.future?.v5Defaults,a=r?.layout??(o?"centered":"top"),s=ld(r,"variant")?r.variant:!1===n?.showWelcomeCard?"none":"card",i="hero"!==s||o||void 0!==r?.layout?ld(r,"dismiss")?r.dismiss:o||"hero"===s?"on-first-message":"never":"on-first-message",l=[];for(let[e,t]of[["title","welcomeTitle"],["subtitle","welcomeSubtitle"],["variant","showWelcomeCard"]])ld(r,e)&&ld(n,t)&&l.push(`welcome.${e} and copy.${t} are both set; welcome.${e} wins. copy.${t} is deprecated.`);"hero"===s&&ld(r,"message")&&l.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!o&&void 0===r?.layout&&"hero"===s&&ld(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!==yi(r?.anchorComposerTop);return ld(r,"anchorComposerTop")&&!c&&l.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),"center"!==d&&(ld(r,"anchorComposerTop")||ld(r,"composerGap"))&&l.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),((e,t)=>{e&&!0===e.debug&&t.length&&!id.has(e)&&(id.add(e),t.forEach(e=>console.warn(`[persona] ${e}`)))})(e,l),{title:ld(r,"title")?r.title:n?.welcomeTitle??(o?"What can I help with?":"Hello 👋"),kicker:r?.kicker??"",subtitle:ld(r,"subtitle")?r.subtitle:n?.welcomeSubtitle??(o?"":"I can answer questions and help you get things done here."),icon:r?.icon,align:"start"===r?.align||"center"===r?.align?r.align:"centered"===a?"center":void 0,iconPlacement:r?.icon&&"function"!=typeof r.icon&&"inline"===r.icon.placement?"inline":"above",variant:s,dismiss:i,message:"hero"===s?void 0:r?.message,layout:a,anchor:d,anchorComposerTop:c?r.anchorComposerTop:"44%",composerGap:r?.composerGap?.trim()||"24px"}},cd=(e=[])=>e.some(e=>"user"===e.role||"assistant"===e.role&&(e.content.trim()||e.contentParts?.some(e=>"text"!==e.type||e.text.trim())||e.toolCall||e.tools?.length||e.reasoning||e.approval)),pd=e=>cd(e)?"active":"empty",ud=(e,t)=>"none"!==e.variant&&("never"===e.dismiss||!cd(t)),hd="var(--persona-components-panel-height)",md=e=>{let t=ns(e),r=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,n=e?.launcher?.heightOffset??0;return{width:r??"var(--persona-components-panel-width)",maxWidth:r??"var(--persona-components-panel-maxWidth)",height:0===n?`max(200px, ${hd})`:`max(200px, calc(${hd} - ${n}px))`,maxHeight:"var(--persona-components-panel-maxHeight)"}},gd=e=>{let t=ns(e);return t.launcherWidth||t.legacyLauncherWidth||void 0!==e?.theme?.components?.panel?.width?md(e).width:"100%"},fd="16px",bd="10px",yd="14px",vd=e=>{let t=it("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":ul(e)}});return t.hidden=!0,t},wd=(e,t)=>{let r=((e,t,r={})=>{let n=it("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let o=st("p","persona-welcome-kicker");o.hidden=!0;let a=st("h2","persona-welcome-title"),s=st("p","persona-welcome-subtitle"),i=it("div",{className:"persona-welcome-head-text"},o,a),l=it("div",{className:"persona-welcome-title-row"},n,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:n,kicker:o,title:a,subtitle:s,starterSuggestions:t}})(0,vd("starter"),{flatShadow:ll(e)}),n=dd(e);Yl(r,n),Gl(t,r.host,ud(n,e?.initialMessages));let o=(()=>{let e=it("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e})();return nd(o,n.message,e),{welcome:r,greetingHost:o}},xd=(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 n=e=>{let t=e.launcher??{},n=ll(e),o="circle"===Ts(e);o?(r.dataset.personaLauncherVariant="circle",r.setAttribute("aria-label",t.title??"Open chat")):(r.removeAttribute("data-persona-launcher-variant"),r.removeAttribute("aria-label"));let a=r.querySelector("[data-role='launcher-title']");if(a){let e=t.title??"Chat Assistant";a.textContent=e,a.setAttribute("title",e)}let s=r.querySelector("[data-role='launcher-subtitle']");if(s){let e=t.subtitle??"Here to help you get answers fast";s.textContent=e,s.setAttribute("title",e)}let i=r.querySelector(".persona-flex-col");i&&(t.textHidden||n||o?i.style.display="none":i.style.display="");let l=r.querySelector("[data-role='launcher-icon']");if(l)if(t.agentIconHidden)l.style.display="none";else{let e=t.agentIconSize??"40px";if(l.style.height=e,l.style.width=e,t.agentIconBackgroundColor?(l.style.backgroundColor=t.agentIconBackgroundColor,l.classList.remove("persona-bg-persona-primary")):(l.style.backgroundColor="",l.classList.add("persona-bg-persona-primary")),l.innerHTML="",t.agentIconName){let r=parseFloat(e)||24,n=Ee(t.agentIconName,.6*r,"var(--persona-text-inverse, #ffffff)",1.5);n?(l.appendChild(n),l.style.display=""):(l.textContent=t.agentIconText??"💬",l.style.display="")}else t.iconUrl?l.style.display="none":(l.textContent=t.agentIconText??"💬",l.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let e=t.agentIconSize??"40px";d.style.height=e,d.style.width=e,!t.iconUrl||t.agentIconName||t.agentIconHidden?d.style.display="none":(d.src=t.iconUrl,d.style.display="block")}let c=r.querySelector("[data-role='launcher-call-to-action-icon']");if(c){let e=t.callToActionIconSize??"32px";c.style.height=e,c.style.width=e,t.callToActionIconBackgroundColor?(c.style.backgroundColor=t.callToActionIconBackgroundColor,c.classList.remove("persona-bg-persona-primary")):(c.style.backgroundColor="",c.classList.add("persona-bg-persona-primary")),t.callToActionIconColor?(c.style.color=t.callToActionIconColor,c.classList.remove("persona-text-persona-call-to-action")):(c.style.color="",c.classList.add("persona-text-persona-call-to-action"));let r=0;if(t.callToActionIconPadding?(c.style.boxSizing="border-box",c.style.padding=t.callToActionIconPadding,r=2*(parseFloat(t.callToActionIconPadding)||0)):(c.style.boxSizing="",c.style.padding=""),t.callToActionIconHidden||o)c.style.display="none";else if(c.style.display=n?"none":"",c.innerHTML="",t.callToActionIconName){let n=Math.max((parseFloat(e)||24)-r,8),o=Ee(t.callToActionIconName,n,"currentColor",1.5);o?c.appendChild(o):c.textContent=t.callToActionIconText??"↗"}else c.textContent=t.callToActionIconText??"↗"}let p=t.position&&bl[t.position]?bl[t.position]:bl["bottom-right"];r.className=n?"persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer":`persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer ${p}`,n||(r.style.zIndex=String(t.zIndex??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,n?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=t.collapsedMaxWidth??"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")};return e&&n(e),{element:r,update:n,destroy:()=>{r.removeEventListener("click",t),r.remove()}}},Cd=new Set,Sd=e=>{let t=e?.persistState;return`${("object"==typeof t?t?.keyPrefix:void 0)??"persona-"}teaser-dismissed`},kd=({config:e,showClose:t})=>{let{wrapper:r,panel:n,pillRoot:o}=(e=>{let t=e?.launcher?.enabled??!0,r=ll(e);if(dl(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 n=st("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");n.style.width="100%",r.appendChild(n);let o=st("div","persona-widget-pill-root");return o.setAttribute("data-persona-composer-bar",""),o.dataset.state="collapsed",o.dataset.expandedSize=t.expandedSize??"anchored",o.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:r,panel:n,pillRoot:o}}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=gd(e),r.style.width="100%",t.appendChild(r),{wrapper:t,panel:r}}let n=e?.launcher??{},o=n.position&&bl[n.position]?bl[n.position]:bl["bottom-right"],a=st("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let s=st("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=md(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(dl(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:n,wrapper:o}=Sl(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:fd,iconSize:bd});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let a=null,s=null;if(e?.launcher?.clearChat?.enabled??1){let t=kl(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:fd,iconSize:yd});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}=wd(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=vd("followUp"),b=fi(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=Hl({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=oe(ye,16,"currentColor",1.5);r&&t.appendChild(r);let n=st("span","persona-pill-peek__text"),o=st("span","persona-pill-peek__caret"),a=oe(ue,16,"currentColor",1.5);return a&&o.appendChild(a),e.append(t,n,o),{root:e,textNode:n}})();return r.append(i,o,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:n,closeButtonWrapper:o,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"}}),n=e?.layout?.header,o=is(e),a=n?Nl(e,n,{showClose:t}):Tl({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}=wd(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=vd("followUp"),g=fi(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=Wl({config:e}),b=!1!==e?.layout?.showFooter;o||(a.header.style.display="none"),El(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:n,pillRoot:o},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},l={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:l,composer:d,replaceHeader:e=>(l.element.replaceWith(e.header),l.element=e.header,l.iconHolder=e.iconHolder,l.headerTitle=e.headerTitle,l.headerSubtitle=e.headerSubtitle,l.closeButton=e.closeButton,l.closeButtonWrapper=e.closeButtonWrapper,l.clearChatButton=e.clearChatButton,l.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{d.footer.replaceWith(e),d.footer=e}}},Ad=({config:e,plugins:t,onToggle:r})=>{let n=t.find(e=>e.renderLauncher);if(n?.renderLauncher){let t=n.renderLauncher({config:e,defaultRenderer:()=>xd(e,r).element,onToggle:r});if(t)return{instance:null,element:t}}let o=((e,t)=>{let r=st("div","persona-launcher-surface");r.setAttribute("data-persona-launcher-surface","true");let n=e??{},o=null,a=null,s=null,i=null,l=null,d=!1,c=!1,p=!1,u=!1,h=()=>"once"===(o?.frequency??"once")&&!1!==n.persistState,m=()=>{null!==l&&(clearTimeout(l),l=null)},g=e=>{m(),p=!0,a&&d&&(d=!1,a.hidden=!0),((e,t)=>{if(Cd.add(e),t)try{window.localStorage.setItem(e,"1")}catch{}})(Sd(n),e&&h())},f=e=>{o&&!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=xd(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=n.launcher?.position??"bottom-right",t=bl[e]??bl["bottom-right"];a?(r.className=lt("persona-launcher-surface",t),r.setAttribute("data-teaser",e),r.style.zIndex=String(n.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&&!ll(e??{})?t:null})(e);o=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"),o&&a&&(p||c||u||((e,t)=>{if(Cd.has(e))return!0;if(!t)return!1;try{return"1"===window.localStorage.getItem(e)}catch{return!1}})(Sd(n),h())||(m(),l=setTimeout(b,Math.max(0,o.delayMs??0))))):x()};return r.appendChild(w.element),e&&(S(e),C()),{element:r,launcher:w,get teaser(){return a?{element:a,show:b,dismiss:g}:null},setPanelOpen:(e,t="user")=>{u=e,e&&f(t)},update:e=>{n=e,w.update(e),S(e),C()},destroy:()=>{x(),w.destroy(),r.remove()}}})(e,r);return{instance:o,element:o.element}},Md=new WeakMap;async function Id(e){let t=e.closest("[data-persona-tool-detail]"),r=t?.querySelector("pre");if(!r)return;let n=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(Md.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"}Md.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",n),e.title=n,Md.delete(e)},1800))}let{setLoader:Td,load:Ed,provide:Ld,getSync:Bd}=_({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),Rd=Td,Pd=Ed,Nd=Bd,{setLoader:$d,load:Wd}=_({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),Hd=$d,Dd=Wd;function Od(e,t,r){return t?.trim()||(j(e,`artifact.${r}`)?`var(--persona-components-artifact-${r.split(".").join("-")})`:void 0)}function Fd(e){return!0===e?.features?.artifacts?.enabled}function zd(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"),!Fd(t))return;let r=t.features?.artifacts?.layout,n=Od(t,r?.paneBorder,"pane.border"),o=Od(t,r?.paneBorderLeft,"pane.borderLeft");n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}let jd=["panel","seamless","detached"];function qd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&jd.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function _d(e){return!(!e||!Fd(e))&&"detached"===qd(e)}function Ud(e,t){if(!Fd(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 zd(e,t);let r=t.features?.artifacts?.layout,n="detached"===qd(t)?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",r?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",r?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",r?.paneMaxWidth??"28rem"),r?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",r.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),r?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=Od(t,r?.paneBackground,"pane.background");o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let a=Od(t,r?.panePadding,"pane.padding");a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=[[Od(t,r?.documentToolbarIconColor,"toolbar.iconColor"),"--persona-artifact-doc-toolbar-icon-color"],[Od(t,r?.documentToolbarToggleActiveBackground,"toolbar.toggleActiveBackground"),"--persona-artifact-doc-toggle-active-bg"],[Od(t,r?.documentToolbarToggleActiveBorderColor,"toolbar.toggleActiveBorderColor"),"--persona-artifact-doc-toggle-active-border"],[Od(t,r?.documentToolbarToggleActiveColor,"toolbar.toggleActiveColor"),"--persona-artifact-doc-toggle-active-color"]];for(let[t,r]of s){let n=t?.trim();n?e.style.setProperty(r,n):e.style.removeProperty(r)}zd(e,t)}function Vd(e,t){for(let t of jd)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"),!Fd(t))return;let r=t.features?.artifacts?.layout,n=qd(t);e.classList.add(`persona-artifact-appearance-${n}`);let o=Od(t,r?.paneBorderRadius,"pane.borderRadius");o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=Od(t,r?.paneShadow,"pane.shadow");a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=Od(t,r?.chatShadow,"chat.shadow");s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}let Kd=["__proto__","prototype","constructor"],Qd=["collapsed","card","panel","inline"],Jd=["markdown","component"],Gd=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Yd=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Xd=e=>!Kd.includes(e),Zd=e=>Qd.includes(e),ec=e=>Object.keys(e).length>0;function tc(e,t,r,n){e.push({path:t,code:r,message:n})}let rc="Ignored an unsupported value.",nc={kind:"mode"},oc={kind:"string",message:"Expected a CSS length string."},ac={kind:"boolean"},sc=(...e)=>({kind:"value",accepts:t=>e.includes(t)}),ic={paneWidth:oc,paneMaxWidth:oc,paneMinWidth:oc,expandedPanelWidth:oc,resizableMinWidth:oc,resizableMaxWidth:oc,expandLauncherPanelWhenOpen:ac,resizable:ac},lc={kind:"object",message:"Expected a preference object.",children:{showToolCalls:ac,showReasoning:ac,toolCallDisplay:{kind:"object",children:{layout:sc("row","card"),collapsedMode:sc("tool-call","tool-name","tool-preview"),groupedMode:sc("stack","summary","collapsible"),groupAppearance:sc("plain","inset"),groupSummary:sc("current-action","aggregate"),groupBoundary:sc("adjacent","iteration"),groupSummaryMaxItems:{kind:"value",accepts:e=>Number.isInteger(e)&&e>=0},loadingAnimation:sc("none","pulse","shimmer","shimmer-color","rainbow"),expandable:ac,grouped:ac}},reasoningDisplay:{kind:"object",children:{layout:sc("row","card"),appearance:sc("plain","inset","panel"),expandable:ac,activePreview:ac}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:nc,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:nc,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Jd,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Jd}}},filePreview:{kind:"object",children:{enabled:ac}},layout:{kind:"object",children:ic}}}}};function dc(e,t,r,n){if(void 0!==e)switch(t.kind){case"boolean":return"boolean"==typeof e?e:tc(n,r,"invalid_type","Expected a boolean.");case"string":return"string"==typeof e?e:tc(n,r,"invalid_type",t.message);case"value":return t.accepts(e)?e:tc(n,r,"invalid_value",rc);case"mode":return Zd(e)?ko(e):tc(n,r,"invalid_value",rc);case"modeMap":{if(!Yd(e))return tc(n,r,"invalid_type","Expected an object.");let o="mediaType"===t.keys?void 0:t.keys,a={};for(let[t,s]of Object.entries(e)){let e=o?t:Ao(t);Xd(t)&&(o?o.includes(t):Gd.test(e))?Zd(s)?a[e]=ko(s):tc(n,`${r}.${t}`,"invalid_value","Expected collapsed, panel, or inline."):tc(n,`${r}.${t}`,o?"unknown_key":"invalid_value",o?"Ignored an unsupported selector.":'Expected a MIME type such as "text/html" or a wildcard such as "image/*".')}return ec(a)?a:void 0}case"object":{if(t.bareMode&&Zd(e))return ko(e);if(!Yd(e))return tc(n,r,"invalid_type",t.message??"Expected an object.");let o=Object.keys(t.children),a=e=>r?`${r}.${e}`:e;for(let t of Object.keys(e))(!Xd(t)||!o.includes(t))&&tc(n,a(t),"unknown_key","Ignored because this key is not part of the persisted preference schema.");let s={};for(let r of o){let o=t.children[r],i=dc(e[r],o,a(r),n);if(o.deprecated&&void 0!==e[r]&&tc(n,a(r),"deprecated_key",o.deprecated),void 0===i)continue;let l=o.alias??r,d=s[l];s[l]=Yd(d)&&Yd(i)?{...d,...i}:i}return ec(s)?s:void 0}}}function cc(e){let t=[];return{preferences:(null===e?void 0:dc(e,lc,"",t))??{},issues:t}}function pc(e){if(Array.isArray(e))return e.map(pc);if(!Yd(e))return e;let t={};for(let[r,n]of Object.entries(e))Xd(r)&&void 0!==n&&(t[r]=pc(n));return t}function uc(e,t){let r=pc(e);for(let[e,n]of Object.entries(t)){if(!Xd(e)||void 0===n)continue;let t=r[e];r[e]=Yd(t)&&Yd(n)?uc(t,n):pc(n)}return r}function hc(e,t){if(void 0===t)return pc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byType,...r.byKind,...t.byType,...t.byKind},a=function(e,t){if(void 0===t)return pc(e);if("string"==typeof t)return t;let r="string"==typeof e?{default:e}:e??{},n=t.default??r.default,o={...r.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...ec(o)?{byMediaType:o}:{}};return ec(a)?a:void 0}(r.files,t.files),s={...n?{default:n}:{},...ec(o)?{byKind:o}:{},...void 0===a?{}:{files:a}};return ec(s)?s:void 0}function mc(e={},t){let r=function(e){let t,r={};for(let n of e){let e=cc(n).preferences;t=hc(t,e.artifacts?.display),r=uc(r,e)}let n=r;return n.artifacts&&(void 0===t?delete n.artifacts.display:n.artifacts.display=t),n}(t),n={...e};for(let e of["showToolCalls","showReasoning"])void 0!==r[e]&&(n[e]=r[e]);for(let t of["toolCallDisplay","reasoningDisplay"])r[t]&&Object.assign(n,{[t]:{...e[t],...r[t]}});if(r.artifacts){let t=e.artifacts??{},o={...t};if(void 0!==r.artifacts.display){let e=hc(t.display,r.artifacts.display);void 0!==e&&(o.display=e)}for(let e of["filePreview","layout"])r.artifacts[e]&&(o[e]={...t[e],...r.artifacts[e]});n.artifacts=o}return n}function gc(e){let t=e.preferences;return t&&ec(t)?{...e,features:mc(e.features??{},[t])}:e}let{setLoader:fc,load:bc,provide:yc,getSync:vc}=_({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),wc=fc,xc=bc,Cc=vc,Sc=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()}},kc=e=>"object"==typeof e&&!!e&&!Array.isArray(e),Ac=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Mc=(e,t,r)=>{if(!kc(e)||!kc(t)||Ac.has(r))return t;let n={...e};for(let o of Object.keys(t)){if(void 0===t[o]){delete n[o];continue}let a=r?`${r}.${o}`:o;n[o]=Mc(e[o],t[o],a)}return n};function Ic(e,t){let r=f(ps),n=x(e,t,r),o=v(C(Mc(e,t,""),r,n),n);return D(o,((e,t)=>{if(t[$])return H(t);let r=new Set(H(e));for(let e of N){let n=b(t,e);"clear"===n&&r.delete(e),"explicit"===n&&r.add(e)}return[...r]})(e,t)),os(fs(o),((e,t)=>{let r=t[es];if(r)return{...r};let n=ns(e);return ts(t,"launcherWidth")&&(n.legacyLauncherWidth=void 0!==t.launcherWidth),ts(t,"launcher")&&void 0===t.launcher?(n.launcherWidth=!1,n.sidebarWidth=!1,n.dockWidth=!1,n):(ts(t.launcher,"width")&&(n.launcherWidth=void 0!==t.launcher?.width),ts(t.launcher,"sidebarWidth")&&(n.sidebarWidth=void 0!==t.launcher?.sidebarWidth),ts(t.launcher,"dock")&&void 0===t.launcher?.dock?n.dockWidth=!1:ts(t.launcher?.dock,"width")&&(n.dockWidth=void 0!==t.launcher?.dock?.width),n)})(e,t))}let{setLoader:Tc,load:Ec,provide:Lc,getSync:Bc}=_({fallbackImport:()=>import("@runtypelabs/persona/config-diagnostics")}),Rc=Tc,Pc=Ec,Nc=Bc,$c=[...R,"launcherWidth","suggestionChips","copy.welcomeTitle","copy.welcomeSubtitle","copy.showWelcomeCard","features.suggestReplies.enabled","features.suggestReplies.expose"],Wc=e=>{if(!e.debug)return;let t=Nc();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 Pc().then(()=>Wc(e),()=>{})},Hc=e=>{let t={warned:new Set,current:new Set($c.filter(t=>F(e,t))),debug:!0===e?.debug};return Wc(t),t},Dc=(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 n=b(t,r);"clear"===n&&e.current.delete(r),"explicit"===n&&e.current.add(r)}Object.prototype.hasOwnProperty.call(t,"debug")&&(e.debug=!0===t.debug),Wc(e)},Oc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=(e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e})(e),r=(e=>{let t=e.trim(),r=t.indexOf("{");if(-1===r)return null;let n=0;for(let e=r;e<t.length;e+=1){let o=t[e];if("{"===o&&(n+=1),"}"===o&&(--n,0===n))return t.slice(r,e+1)}return null})(t);if(!r)return null;let n=JSON.parse(r);if(!n||"object"!=typeof n||!n.action)return null;let{action:o,...a}=n;return{type:String(o),payload:a,raw:n}}catch{return null}},Fc=e=>"string"==typeof e?e:null==e?"":String(e),zc={message:e=>{if("message"===e.type)return{handled:!0,displayText:Fc(e.payload.text)}},messageAndClick:(e,t)=>{if("message_and_click"!==e.type)return;let r=e.payload,n=Fc(r.element);if(n&&t.document?.querySelector){let e=t.document.querySelector(n);e?setTimeout(()=>{e.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Fc(r.text)}}},jc=e=>Array.isArray(e)?e.map(e=>String(e)):[],qc=e=>{let t=new Set(jc(e.getSessionMetadata().processedActionMessageIds));return{process:r=>{if(r.streaming||"assistant"!==r.message.role||!r.text||t.has(r.message.id))return null;let n="string"==typeof r.raw&&r.raw||"string"==typeof r.message.rawContent&&r.message.rawContent||"string"==typeof r.text&&r.text||null;!n&&"string"==typeof r.text&&r.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let o=n?e.parsers.reduce((e,t)=>e||t?.({text:n,message:r.message})||null,null):null;if(!o)return null;t.add(r.message.id),(()=>{let r=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:r}))})();let a={action:o,message:r.message};e.emit("action:detected",a);for(let t of e.handlers)if(t)try{let n=e.captureResubmitGuard?.(),s=t(o,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{(!n||n())&&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(jc(e.getSessionMetadata().processedActionMessageIds))}}},_c=e=>e.map(e=>({...e,streaming:!1})),Uc=e=>e.map(e=>({...e,status:"complete"})),Vc=e=>`${e??"persona-"}state`,Kc=(e=Vc())=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?(e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}})(r.getItem(e)):null},save:r=>{let n=t();if(n)try{let t={...r,messages:r.messages?_c(r.messages):void 0,artifacts:r.artifacts?Uc(r.artifacts):void 0};n.setItem(e,JSON.stringify(t))}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",e)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}},Qc=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:Jc,load:Gc}=_({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),Yc=Jc,Xc=Gc,{setLoader:Zc,load:ep,provide:tp,getSync:rp}=_({fallbackImport:()=>import("@runtypelabs/persona/history-shell")}),np=Zc,op=ep,ap=rp;function sp(){return null}let ip=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function lp(e,t,r){let{onSubmit:n,onDismiss:o,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",()=>{o?.(),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 n(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 dp(e){return lp(e,"csat",t=>{let{ratingLabels:r=ip}=e,n=document.createElement("div");n.className="persona-feedback-rating persona-feedback-rating-csat",n.setAttribute("role","radiogroup"),n.setAttribute("aria-label","Satisfaction rating from 1 to 5");let o=[];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),o.forEach((t,r)=>{let n=r<e;t.classList.toggle("selected",n),t.setAttribute("aria-checked",r===e-1?"true":"false")})}),o.push(a),n.appendChild(a)}return{element:n,attentionTarget:n}})}function cp(e){return lp(e,"nps",t=>{let{lowLabel:r="Not likely",highLabel:n="Very likely"}=e,o=document.createElement("div");o.className="persona-feedback-rating persona-feedback-rating-nps",o.setAttribute("role","radiogroup"),o.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=n,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 o.appendChild(a),o.appendChild(l),{element:o,attentionTarget:l}})}let pp="persona-chat-history",up="data-persona-composer-reason",hp="data-persona-composer-notice",mp={"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 gp(e){if(!e)return!1;let t=e.types;return!!t&&("function"==typeof t.contains?t.contains("Files"):Array.from(t).includes("Files"))}let fp=e=>e&&"object"==typeof e?{...e}:{},bp=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})),yp=(e,t,r)=>{let n=e?.markdown?Sr(e.markdown):null,o=Pr(e?.sanitize);e?.postprocessMessage&&o&&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=o?o(t):t}else if(n){let e=xr(s,a.streaming),t=n(e);l=o&&d?o(t):t}else l=Mr(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)),Mr(e.text??"")}}};function vp(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 wp=(e,t)=>{let r={...e};for(let[e,n]of Object.entries(t)){let t=r[e];r[e]=t?{...t,...n}:n}return r},xp=(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 o=e.getAttribute("data-persona-instance")||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;e.setAttribute("data-persona-instance",o),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let s,i,l=fs(t),u=(e=>{let t,r=0,n=!1,o=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 o},prepare(s,l,d=!1){let c=++r;if(a(),!s.length){if(l(),c!==r)return;return i(),void(o=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"))});o=Promise.race([Promise.all(s),p]).then(()=>{if(n)throw Error("Widget destroyed before ready");if(c!==r||(l(),c!==r))return o;i()},e=>{if(!n&&c!==r)return o;throw e}),o.catch(()=>{})},destroy(){n=!0,++r,a(),i()}}})(e),h=r?.diagnostics??Hc(t),m=null,g=()=>{let t=qe();if(s??=t?.createLoadingLabelLifecycle(e,()=>l),m)return m;let r=Y();return r&&t?(r.initActivityUi(Ee,t,q),i=r.createActivityLifecycle(e,()=>l,f,b,ks,_l),m=r):null},f=new Set,b=new Set,y=new Map,v=()=>{ja({delayMs:l.tooltip?.delayMs??400,skipDelayMs:l.tooltip?.skipDelayMs??300})};v();let w=l.features;l=gc(l);let x,C,S=Sc.getForInstance(l.plugins),A=Ii(e),M=[],I=!1,T=(e=>{let t=new Map,r=!1,n=()=>{if(r||!1===e()?.persistState)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return r=!0,null}};return o=>{let a=t=>((e,t,r)=>`${(e=>{let t=e?.persistState;return("object"==typeof t?t?.keyPrefix:void 0)??"persona-"})(e)}plugin:${t}:${r}`)(e(),o,t);return{get:e=>{let o=a(e),s=n();if(s)try{return s.getItem(o)}catch{r=!0}return t.get(o)??null},set:(e,o)=>{let s=a(e),i=n();if(i)try{return void i.setItem(s,o)}catch{r=!0}t.set(s,o)},remove:e=>{let o=a(e);t.delete(o);let s=n();if(s)try{s.removeItem(o)}catch{r=!0}}}}})(()=>l),E=null,L=null,B=null,R=!1,P=null,N=(e,t)=>{E=e,e.initApprovalUi({webMcpToolTitle:nr,popover:t,icons:{render:Ee,node:oe}});let r=e.createBuiltInApprovalPlugin(y);L=r.plugin,B=r.teardown},$=()=>{if(E)return E;let e=Nd(),t=We();return e&&t?(N(e,t),e):(Promise.all([Pd(),$e()]).then(([e,t])=>{R||E||(N(e,t),P?.())}).catch(()=>{}),null)},W=!1,H=!1,D=null,O=(e,t,r,n)=>{if(!e.querySelector("[data-tv-form]"))return;let o=Cc();o?o.enhanceWithForms(e,t,r,n):xc().then(()=>{W||H||!D||(H=!0,D())}).catch(()=>{})},F=((e={instanceId:""})=>{let t=!1,r=new Map,n=(e,t)=>{r.get(e)?.delete(t)};return{on:(e,o)=>t?()=>{}:(r.has(e)||r.set(e,new Set),r.get(e).add(o),()=>n(e,o)),off:n,emit:(t,n)=>{r.get(t)?.forEach(t=>{try{t(n,e)}catch(e){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",e)}})},dispose:()=>{t=!0,r.clear()}}})(Object.freeze({instanceId:o})),z=!1===l.persistState?null:l.storageAdapter??Kc(Vc("object"==typeof l.persistState?l.persistState.keyPrefix:void 0)),j=!!l.clientToken&&"function"!=typeof l.reconnectStream,_={},U=null,V=new Promise(e=>{x=e}),K=()=>{},Q=new Promise(e=>{K=e}),J=!1,G=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&&(J=!0),e}return t}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}return e};if(z?.load)try{let e=z.load();if(e&&"function"==typeof e.then)U=e.then(e=>G(e??{messages:[],metadata:{}}));else{let t=G(e??{messages:[],metadata:{}});t.metadata&&(_=fp(t.metadata)),t.messages?.length&&(l={...l,initialMessages:t.messages}),t.artifacts?.length&&(l={...l,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),C=t.draft}}catch(e){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",e)}else if(l.onStateLoaded)try{let e=G({messages:[],metadata:{}});e.messages?.length&&(l={...l,initialMessages:e.messages})}catch(e){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",e)}U||x();let X=()=>_,Z=e=>{_=e({..._})??{},ji()},ee=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Oc],te=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[zc.message,zc.messageAndClick],re=qc({parsers:ee,handlers:te,getSessionMetadata:X,updateSessionMetadata:Z,emit:F.emit,captureResubmitGuard:()=>{let e=be;return()=>ve(e)},documentRef:typeof document<"u"?document:null});re.syncFromMetadata();let ne=l.launcher?.enabled??!0,ae=l.launcher?.autoExpand??!1,se=l.autoFocusInput??!1,ie=ae,le=ne,ce=l.layout?.header?.layout,ue=!1,me=()=>dl(l),ge=()=>ne||me(),fe=!me()&&(!ne||ae),be=0,ye=!1,ve=e=>!ye&&!Ai&&e===be,we=()=>{be++,Ce=!1,null!==Se&&clearTimeout(Se),Se=null},xe=()=>{let e=be;ve(e)&&setTimeout(()=>{ve(e)&&!es.isStreaming()&&es.continueConversation()},100)},Ce=!1,Se=null,ke=()=>{ve(be)&&(Ce=!0,Se&&clearTimeout(Se),Se=setTimeout(()=>{Ce&&=(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),!1)},1e4))},Ae=yp(l,re,ke),Me=l.features?.showReasoning??!0,Ie=l.features?.showToolCalls??!0,Te=l.features?.showEventStreamToggle??!1,Le=l.features?.scrollBehavior??{},Be=()=>("object"==typeof l.persistState?l.persistState?.keyPrefix:void 0)??"persona-",Re=`${Be()}event-stream`,Pe=null,Ne=l.features?.eventStream?.maxEvents??2e3,He=null,De=null,Oe=null,Fe=!1,ze=null,je=!1,_e=null,Ue=0,Ve=(e,t)=>{He?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Ke=(e,t)=>{De?.processEvent(e,t),He?Ve(e,t):Oe&&(Oe.length>=Ne&&Oe.shift(),Oe.push({type:e,payload:t}))},Qe=()=>{!He&&Te&&(Oe??=[],Dd().then(e=>{if(Fe||He||!Te)return;Pe=new e.EventStreamStore(Re),He=new e.EventStreamBuffer(Ne,Pe),De??=new e.ThroughputTracker,Pe.open().then(()=>He?.restore()).catch(e=>{l.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",e)});let t=Oe??[];Oe=null;for(let e of t)De?.processEvent(e.type,e.payload),Ve(e.type,e.payload)}).catch(()=>{}))};Te&&Qe();let Ye=!1,Xe=null,Ze=()=>{},et=()=>{},tt=()=>{},rt=()=>{},nt=()=>{},ot=e=>{F.emit("message:copy",e),es?.isClientTokenMode()&&es.submitMessageFeedback(e.id,"copy").catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",e)}),l.messageActions?.onCopy?.(e)},at=e=>{F.emit("message:feedback",e),es?.isClientTokenMode()&&es.submitMessageFeedback(e.messageId,e.type).catch(e=>{l.debug&&console.error("[AgentWidget] Failed to submit feedback:",e)}),l.messageActions?.onFeedback?.(e)};l.statusIndicator;let it=(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 lt(e,t,r,n){if(!me()&&("transient"===r.mode||e.classList.contains("persona-mb-2"))&&(hr(e,At,r),ur(e,r,n)),!e.hasAttribute(up)&&!e.hasAttribute(hp))if("idle"===n&&r.idleLink){e.textContent="";let n=document.createElement("a");n.href=r.idleLink,n.target="_blank",n.rel="noopener noreferrer",n.textContent=t,n.style.color="inherit",n.style.textDecoration="none",e.appendChild(n)}else e.textContent=t}let ct=kd({config:l,showClose:ge()}),{wrapper:pt,panel:ut,pillRoot:ht}=ct.shell,mt=ct.panelElements,{container:gt,body:ft,messagesWrapper:vt,starterSuggestions:wt,transcriptSuggestions:xt,suggestions:Ct,textarea:St,sendButton:kt,composerForm:At,statusText:Mt,welcomeHost:It,welcomeIconHolder:Bt,greetingHost:Rt,introKicker:Pt,introTitle:Nt,introSubtitle:$t,closeButton:Dt,iconHolder:Ot,headerTitle:Ft,headerSubtitle:zt,header:er,footer:tr,actionsRow:rr}=mt,or=mt.leftActions,ar=mt.rightActions,sr=mt.sendButtonWrapper,ir=mt.setSendButtonMode,lr=mt.micButton,dr=mt.micButtonWrapper,pr=mt.attachmentButton,mr=mt.attachmentButtonWrapper,gr=mt.attachmentInput,fr=mt.attachmentPreviewsContainer;gt.classList.add("persona-relative"),ft.classList.add("persona-relative");let br=()=>Le.mode??"anchor-top",yr=()=>"follow"===br()||"anchor-top"===br()&&Zs,vr=()=>Le.anchorTopOffset??16,wr=()=>!0===Le.pauseOnInteraction,xr=()=>!1!==Le.showActivityWhilePinned,Cr=()=>!0===Le.announce,Sr=()=>Le.scrollbar??"on-scroll",kr=Zt(Ee,"transcript",ft),Ar=kr.element;gt.appendChild(Ar);let Ir=()=>ft.parentElement??gt,Tr=st("div","persona-panel-suggestions");Tr.setAttribute("data-persona-panel-suggestions",""),Tr.hidden=!0,gt.appendChild(Tr);let Er=st("div","persona-panel-suggestions-fade");Er.setAttribute("aria-hidden","true"),Er.hidden=!0,gt.appendChild(Er);let Lr=st("div","persona-stream-anchor-spacer");Lr.setAttribute("aria-hidden","true"),Lr.setAttribute("data-persona-anchor-spacer",""),Lr.style.flexShrink="0",Lr.style.pointerEvents="none",Lr.style.height="0px",Lr.style.display="none",ft.appendChild(Lr);let Br=st("div","persona-sr-only");Br.setAttribute("aria-live","polite"),Br.setAttribute("aria-atomic","true"),Br.setAttribute("role","status"),Br.setAttribute("data-persona-live-region",""),Object.assign(Br.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"}),gt.appendChild(Br);let Rr=null,Pr=null,Nr=e=>{Cr()&&e&&(Pr=e,null===Rr&&(Rr=setTimeout(()=>{Rr=null,Pr&&Cr()&&(Br.textContent=Pr),Pr=null},400)))},$r=()=>{let t=e.ownerDocument.defaultView??window;return(l.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(l.launcher?.mobileBreakpoint??640)&&(ne||ll(l))||!0===l.launcher?.fullHeight&&!l.launcher.sidebarMode&&!ll(l)},Wr=()=>dd(l,$r()),Dr="empty",Or=0,Fr=()=>Or||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,zr=(e,t=ft)=>{let r=0,n=e;for(;n&&n!==t;)r+=n.offsetTop,n=n.offsetParent;return r},jr=()=>{let e="none"===tr.style.display,t=Ir();if(me()){let r=e||!tr.offsetHeight?0:Math.max(0,t.getBoundingClientRect().bottom-tr.getBoundingClientRect().top),n=Tr.hidden?0:Math.max(0,t.getBoundingClientRect().bottom-Tr.getBoundingClientRect().top);return void(Ar.style.bottom=`${Math.max(r,n)+16}px`)}let r=e?0:tr.offsetHeight;if(r>0&&"overlay"===bi(l,me())){let e=1/0;for(let r of tr.querySelectorAll(":scope > *, [data-persona-composer-header] > *"))!r.hidden&&r.offsetHeight&&"hidden"!==getComputedStyle(r).visibility&&(e=Math.min(e,zr(r,t)));e<1/0&&(r-=e-zr(tr,t))}Ar.style.bottom=`${r+(e?0:Fr())+16}px`};jr();let _r=()=>{if(!me())return;let e="none"===tr.style.display?0:tr.offsetHeight;e>0?pt.style.setProperty("--persona-measured-pill-area-height",`${e+8}px`):pt.style.removeProperty("--persona-measured-pill-area-height"),pt.style.setProperty("--persona-pill-bottom",l.launcher?.composerBar?.bottomOffset??"16px")},Ur=()=>{Mn||(tr.style.marginBottom=Or>0?`${Or}px`:"")},Vr=()=>{let t=bi(l,me()),r=Wr();e.setAttribute("data-persona-welcome-fullscreen",String($r())),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 n="none"===tr.style.display?0:tr.offsetHeight,o="center"===r.anchor&&"empty"===Dr?yi(r.anchorComposerTop)??yi("44%"):null,a=null!==o&&"centered"===r.layout&&void 0===l.welcome?.anchor&&void 0===l.welcome?.anchorComposerTop,s=a?getComputedStyle(ft):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?ft.getBoundingClientRect().top-gt.getBoundingClientRect().top:0,u=!a||It.hidden?0:(It.querySelector("[data-persona-welcome-plugin]")??It).offsetHeight,h=null===o||me()?0:a?Math.max(0,Math.round((gt.clientHeight-p-u-c-n)/2)):(e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight))({columnHeight:gt.clientHeight,footerHeight:n,fraction:o});e.style.setProperty("--persona-composer-overlay-height",`${n}px`),e.style.setProperty("--persona-composer-lift",`${"overlay"===t?h:0}px`),Or="block"===t?h:0,Ur(),_r(),jr(),Na()};kr.update(l,!1);let Kr=null,Qr=null,Jr=ea();Jr.subscribe(e=>{try{gt.dispatchEvent(new CustomEvent("persona:composer:state",{detail:{...e,instanceId:o},bubbles:!0,composed:!0}))}catch{}});let Gr=()=>{Jr.setText(St?.value??"")},Yr=()=>{Jr.setMentionRefs(Qr?.getMentionRefs()??[])},Xr=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}),Zr=()=>({allowedTypes:l.attachments?.allowedTypes,maxFileSize:l.attachments?.maxFileSize,maxFiles:l.attachments?.maxFiles,adapter:l.attachments?.adapter,onFileRejected:l.attachments?.onFileRejected,instanceId:o,widgetConfig:l,preview:l.attachments?.preview,renderAttachmentPreview:en}),en=e=>{for(let t of Sc.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},tn=()=>{let e=p.fromConfig(l.attachments,t=>{Kr===e&&rn(t)});return e.updateConfig(Zr()),e},rn=e=>{let t=Object.freeze(e.map(Xr));Jr.setAttachments(t);try{l.attachments?.onChange?.(t)}catch(e){console.error("[AgentWidget] attachments.onChange failed:",e)}zd()};Jr.setSelectedModelId(l.composer?.selectedModelId);let nn=()=>l.composer?.modes??[],on=()=>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)):[]}(nn(),l.composer?.modeGroups,!!l.future?.v5Defaults);{let e=fa(l.composer?.defaultActiveModeIds??[],nn());e.length&&Jr.setActiveModeIds(e)}function an(e){if(Jr.getState().selectedModelId!==e){Jr.setSelectedModelId(e),dn?.repaint();try{l.composer?.onModelChange?.(e)}catch(e){console.error("[AgentWidget] composer.onModelChange failed:",e)}}}function sn(e){Jr.setActiveModeIds(e),cn?.render(e,on()),dn?.repaint(),On?.resolve(),bc(),Yn()}function ln(t){let r=e.getRootNode(),n=r instanceof ShadowRoot?r.activeElement:e.ownerDocument.activeElement,o=(e=>`core:mode:${e}`)(t),a=On?.getOverflowMenu(),s=n&&(n.closest("[data-persona-composer-action]")?.getAttribute("data-persona-composer-action")===o||a?.trigger.contains(n));if(sn(ga(Jr.getState().activeModeIds,t,nn(),l.composer?.modeGroups)),s&&!n.isConnected){let t=Array.from(e.querySelectorAll("[data-persona-composer-action]")).find(e=>e.getAttribute("data-persona-composer-action")===o)?.querySelector("button")??On?.getOverflowMenu()?.triggerButton;t?.isConnected&&t.focus()}}let dn=null,cn=null,pn=null;function un(e){Jr.setQuote(e),pn?.render(Jr.getState().quote),Yn(),Gi()}let hn=!1;function mn(){let e=l.composer?.streamingSubmitBehavior??"block";return"interrupt"===e?l.clientToken?"interrupt":(!hn&&!0===l.debug&&(hn=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block"):e}let gn=null;function fn(e){Jr.setPendingSubmission(e),gn?.render(Jr.getState().pendingSubmission),Yn()}let bn=null,yn=S.find(e=>e.renderHeader);if(yn?.renderHeader){let e=yn.renderHeader({config:l,defaultRenderer:()=>{let e=Tl({config:l,showClose:ge()});return El(gt,e,l),e.header},onClose:()=>Bd(!1,"user")});e&&er&&(er.replaceWith(e),er=e,ct.header.element=e)}let wn=()=>{ze&&(ft.style.display="none",tr.parentNode?.insertBefore(ze.element,tr),ze.update())},Cn=()=>{if(!He)return void Qe();if(Bl.cancel(),je=!0,ze?wn():Dd().then(e=>{!ze&&je&&He&&(ze=e.createEventStreamView({scroll:{createScrollToLatest:Xt,createScrollToBottomControl:Zt},buffer:He,getFullHistory:()=>He.getAllFromStore(),onClose:()=>Sn(),config:l,plugins:S,getThroughput:()=>De?.getMetric()??{status:"idle"},renderIconByName:Ee,getResponseActive:ul,getConfig:()=>l,getViewVisible:()=>je}),wn())}).catch(()=>{Sn()}),kn){kn.style.boxShadow=`inset 0 0 0 1.5px ${Al.actionIconColor}`;let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&kn.classList.add(e))}let e=()=>{if(!je)return;let t=Date.now();t-Ue>=200&&(ze?.update(),Ue=t),_e=requestAnimationFrame(e)};Ue=0,_e=requestAnimationFrame(e),Sl(),F.emit("eventStream:opened",{timestamp:Date.now()})},Sn=()=>{if(je){if(je=!1,ze&&(ze.update(),ze.element.remove()),ft.style.display="",kn){kn.style.boxShadow="";let e=l.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&kn.classList.remove(e))}null!==_e&&(cancelAnimationFrame(_e),_e=null),Sl(),F.emit("eventStream:closed",{timestamp:Date.now()})}},kn=null;if(Te){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:"");kn=st("button",t),kn.style.width="28px",kn.style.height="28px",kn.style.color=Al.actionIconColor,kn.type="button",kn.setAttribute("aria-label","Event Stream"),kn.title="Event Stream";let r=oe(de,"18px","currentColor",1.5);r&&kn.appendChild(r);let n=mt.clearChatButtonWrapper,o=mt.closeButtonWrapper,a=n||o;a&&a.parentNode===er?er.insertBefore(kn,a):er.appendChild(kn),kn.addEventListener("click",()=>{je?Sn():Cn()})}let An=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??vo).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label",t.buttonTooltipText??"Attach files"),e.appendChild(r)}},Mn=!1,In=e=>{let t=S.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let r=l.composer,n=!!I&&es.isStreaming();return t.renderComposer({config:l,defaultRenderer:e,requestRender:()=>yh(),storage:T(t.id),onSubmit:e=>{es&&!es.isStreaming()&&Zp(e.trim(),{consumeDraft:!1})},streaming:n,disabled:n,openAttachmentPicker:()=>{$d()||gr?.click()},models:r?.models,selectedModelId:Jr.getState().selectedModelId??r?.selectedModelId,onModelChange:e=>an(e),onVoiceToggle:!0===l.voiceRecognition?.enabled?()=>{bn?.()}:void 0})},Tn=In(()=>Wl({config:l}).footer);Tn&&(ct.replaceComposer(Tn),tr=ct.composer.footer,Mn=!0);let En=null;function Ln(){let e=St;if(!e)return;let t=l.composer?.inputAttributes,r=t?.ariaLabel||e instanceof HTMLTextAreaElement?null:e.getAttribute("aria-label");Aa(e,t),r&&e.setAttribute("aria-label",r),ka(e,{submitKey:l.composer?.submitKey,insertNewlineOnTouchEnter:l.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(e)}),wa(e,va(l.composer?.maxLines,me()?5:3))}let Bn=e=>{En=na(e,{debug:!0===l.debug}),En&&(e=>{At=e.form,St=e.input,sr=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(kt=e.sendButton),e.micButton&&(lr=e.micButton,dr=e.micButton.parentElement),e.found.status&&(Mt=e.found.status),e.found.suggestions&&(Ct=e.found.suggestions),e.attachmentButton&&(pr=e.attachmentButton,mr=e.attachmentButton.parentElement),gr=e.attachmentInput??null,fr=e.attachmentPreviews??null,e.found.actionsRow&&(rr=e.found.actionsRow),or=e.found.actionsStart,ar=e.found.actionsEnd})(En),Ln()};An(tr),Bn(tr),Gr();let Rn=fi(l,me());Rn&&(vt.style.maxWidth=Rn,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%",Rt.style.maxWidth=Rn,Rt.style.marginLeft="auto",Rt.style.marginRight="auto",Rt.style.width="100%",wt.style.maxWidth=Rn,xt.style.maxWidth=Rn,xt.style.marginLeft="auto",xt.style.marginRight="auto",xt.style.width="100%");let $n=()=>{let e=fi(l,me());if(e&&!me())for(let t of[At,Ct,fr,Mt])t&&(t.style.maxWidth=e,t.style.marginLeft="auto",t.style.marginRight="auto",t.style.width="100%")};$n();let Wn=()=>{l.attachments?.enabled&&gr&&fr&&(Kr?Kr.remountPreviews(fr):(Kr=tn(),Kr.setPreviewsContainer(fr)),En?.addListener(gr,"change",e=>{let t=e.target;Kr?.handleFileSelect(t.files),t.value=""}),gt.querySelector(".persona-attachment-drop-overlay")||gt.appendChild(vp(l.attachments.dropOverlay)))};Wn();let Hn=()=>{if(!l.contextMentions?.enabled||!St)return;let e=Ht();if(!e){let e=St;return void Wt().then(()=>{!Qr&&St===e&&e.isConnected&&(Hn(),On?.resolve())},()=>{})}let t=En?.header??null,r=t?ca(t):void 0;if(Qr=e.createContextMentionOrchestrator({deps:{loadContextMentions:Pa,loadContextMentionsInline:Ha,renderLucideIcon:Ee,createMentionButton:Is},config:l,textarea:St,anchor:At??St,getMessages:()=>es.getMessages(),liveRegionHost:gt,chipRow:r}),Qr&&!r){let e=St;e.parentElement?.insertBefore(Qr.contextRow,e)}};Hn();let On=null,zn={getState:()=>Jr.getState(),getValue:()=>St?.value??"",setValue:e=>{St&&(St.value=e,St.dispatchEvent(new Event("input",{bubbles:!0})),Gr())},submit:()=>{!function(e){e&&("function"==typeof e.requestSubmit?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}(En?.form??null)},openAttachmentPicker:()=>{$d()||gr?.click()},toggleVoice:()=>{bn?.()},requestRender:()=>On?.resolve()},qn=()=>{let e=[];return(Qr?.affordanceButtons??[]).forEach((t,r)=>{e.push({id:`core:mention-${r}`,placement:"start",order:100+r,element:t,managed:!0})}),mr&&e.push({id:"core:attachment",placement:"start",order:200,element:mr}),dr&&e.push({id:"core:mic",placement:"end",order:800,element:dr}),sr&&e.push({id:"core:send",placement:"end",order:1e3,element:sr}),e},_n=!1,Un=()=>{if(_n)return;let e=We();e&&(On?.destroy(),On=e.createComposerActionRenderer({deps:{renderLucideIcon:Ee,attachTooltip:Ja,hideTooltipFor:_a},getBindings:()=>En,collect:()=>({builtIns:qn(),configActions:[...(dn??=We().createComposerCoreControls({getConfig:()=>l,getState:()=>Jr.getState(),getModes:nn,getChipModes:on,hasComposerPlugin:()=>S.some(e=>e.renderComposer),renderIcon:Ee,onModelChange:an,onModeChange:ln}),dn.collect()),...l.composer?.actions??[]],plugins:S,contributionContext:{config:l,getState:()=>Jr.getState(),requestRender:()=>On?.resolve()},debug:!0===l.debug}),actionContext:zn,getState:()=>Jr.getState(),getOverflow:()=>l.composer?.actionOverflow,reportError:(e,t)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),On.resolve())};Un();let Vn=()=>{if(cn?.destroy(),cn=null,!on().length)return;let e=En?.header;if(!e)return;let t=We();t&&(cn=t.createComposerModeChipRow({renderIcon:Ee,row:ca(e),onRemove:e=>ln(e),initialIds:Jr.getState().activeModeIds}),cn.render(Jr.getState().activeModeIds,on()))};Vn();let Kn=()=>{pn?.destroy(),pn=null,gn?.destroy(),gn=null;let e=En?.header;e&&(pn=pa({onDismiss:()=>un(void 0)}),e.appendChild(pn.element),pn.render(Jr.getState().quote),"defer-one"===mn()&&(gn=ua({onEdit:()=>function(){let e=Jr.getState().pendingSubmission;e&&(fn(void 0),St&&(St.value=e.text,St.dispatchEvent(new Event("input",{bubbles:!0})),Gr()),e.options.selectedModelId&&(Jr.setSelectedModelId(e.options.selectedModelId),dn?.repaint()),e.options.activeModeIds?.length&&sn(e.options.activeModeIds),e.options.quote&&un(e.options.quote),St?.focus())}(),onRemove:()=>fn(void 0)}),e.appendChild(gn.element),gn.render(Jr.getState().pendingSubmission)))};Kn();let Qn=function(){let e=!1;return{observe:(t,r)=>r?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}(),Jn=la({getSurface:()=>me()||!En?null:{form:En.form,input:En.input,start:En.actionsStart,end:En.actionsEnd,resizeInput:"single-row"===l.composer?.layout},onMeasure:()=>Yn()}),Gn=()=>{let e=En?.header?.querySelector(da);if(e)return e.childElementCount>0;let t=Jr.getState();return t.mentionRefs.length>0||fa(t.activeModeIds,on()).length>0};function Yn(){let e=Jr.getState(),t=Jn.measure(),r="single-row"!==l.composer?.layout&&"single-row"!==l.composer?.attachmentLayout||t,n=Jn.toolbarCrowded();tr.hasAttribute("data-persona-composer-crowded")!==n&&tr.toggleAttribute("data-persona-composer-crowded",n),tr.hasAttribute("data-persona-composer-fit")!==r&&tr.toggleAttribute("data-persona-composer-fit",r);let o=Qn.observe(r&&function(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let r=t.getComputedStyle(e),n=Number.parseFloat(r.lineHeight),o=Number.parseFloat(r.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(o)&&o>0?1.4*o:0;if(!a)return!1;let s=(Number.parseFloat(r.paddingTop)||0)+(Number.parseFloat(r.paddingBottom)||0),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}(St),e.text);tr.toggleAttribute("data-persona-has-attachments",e.attachments.length>0),tr.toggleAttribute("data-persona-attachment-row-compact",ba({text:e.text,wrapped:o,hasAttachments:!1,hasChips:Gn(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission}));let a=ba({text:e.text,wrapped:o,hasAttachments:e.attachments.length>0,hasChips:Gn(),hasQuote:void 0!==e.quote,hasPendingSubmission:void 0!==e.pendingSubmission});tr.hasAttribute("data-persona-composer-compact")!==a&&tr.toggleAttribute("data-persona-composer-compact",a);let s=!a||!r||"single-row"!==l.composer?.layout;tr.hasAttribute("data-persona-composer-expanded")!==s&&tr.toggleAttribute("data-persona-composer-expanded",s)}function Xn(){"single-row"!==l.composer?.layout||me()?tr.removeAttribute("data-persona-composer-layout"):tr.setAttribute("data-persona-composer-layout","single-row"),l.composer?.attachmentLayout?tr.setAttribute("data-persona-attachment-layout",l.composer.attachmentLayout):tr.removeAttribute("data-persona-attachment-layout"),Yn()}Xn(),Jr.subscribe(()=>{On?.sync(),zd(),jd(),Yn(),Gi()}),jd();let Zn=!1,eo=e=>{if(Zn||!0!==l.debug)return;let t=["messages","composer"].filter(t=>e[t]);t.length&&(Zn=!0,console.warn(`[persona] Ignoring deprecated layout.slots.${t.join(" / layout.slots.")}. Use message render hooks or the renderComposer plugin hook.`))},to=new Map,ro=new Map,no=e=>{let t=to.get(e);if(t)return t.element;let r=null;if("body-top"===e&&(r=ft.querySelector("[data-persona-intro-card]")),"messages"===e)return vt;if("composer"===e)return At;if("footer-top"===e&&(r=Ct),"footer-bottom"===e&&(r=Mt),r?.parentNode){let t=document.createComment(`persona:${e}`);r.before(t),to.set(e,{anchor:t,element:r})}return r},oo=function(e){let t=new Map,r=(t,r)=>({slot:t,signal:r.abort.signal,config:e.config(),defaultContent:()=>e.defaultContent(t)}),n=(r,n)=>{t.delete(r),n.abort.abort();try{n.result.destroy?.()}catch(e){console.error(`[AgentWidget] Error destroying slot "${r}":`,e)}e.remove(r,n.result.element)};return{update(){let o=e.config().layout?.slots??{};for(let[e,r]of t)o[e]!==r.renderer&&n(e,r);for(let[a,s]of Object.entries(o)){if(!s)continue;let o=t.get(a);try{if(o){if(o.result.update){let t=o.result.update(r(a,o));void 0!==t&&t!==o.result.element&&(e.remove(a,o.result.element),o.result.element=t)}}else{o={renderer:s,abort:new AbortController,result:{element:null}},t.set(a,o);let e=s(r(a,o));o.result=null===e||"nodeType"in e?{element:e}:e}o.result.element&&e.mount(a,o.result.element)}catch(e){o&&n(a,o),console.error(`[AgentWidget] Error rendering slot "${a}":`,e)}}},remount(){for(let[r,n]of t)n.result.element&&e.mount(r,n.result.element)},detach(r){for(let n of r){let r=t.get(n);r&&e.remove(n,r.result.element)}},destroy(){for(let[e,r]of t)n(e,r)}}}({config:()=>l,defaultContent:no,remove(e,t){if("messages"===e||"composer"===e)return;t?.remove(),ro.get(e)?.remove(),ro.delete(e);let r=to.get(e);r&&(r.anchor.replaceWith(r.element),to.delete(e))},mount(e,t){if(!("messages"===e||"composer"===e||t.parentNode&&pt.contains(t))){if("body-top"===e||"footer-top"===e||"footer-bottom"===e){let r=no(e),n=to.get(e);if(r&&n?.anchor.parentNode)return n.anchor.after(t),void(r!==t&&!t.contains(r)&&r.remove())}switch(e){case"header-left":er.prepend(t);break;case"header-right":er.append(t);break;case"header-center":{let e=er.querySelector(".persona-flex-col");e?e.after(t):er.append(t);break}case"body-top":ft.prepend(t);break;case"body-bottom":ft.append(t);break;case"footer-top":tr.prepend(t);break;case"footer-bottom":tr.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),vt.before(r),ro.set(e,r);break}case"composer-start":case"composer-end":case"composer-before-send":{let r="composer-start"===e?or:"composer-end"===e?ar:sr?.parentElement;if(!r)break;let n=document.createElement("div");n.setAttribute("data-persona-layout-slot",e),n.style.cssText="display:flex;align-items:center;min-width:0;max-width:100%",n.append(t),"composer-start"===e?r.prepend(n):"composer-before-send"===e?sr?.before(n):r.append(n),ro.set(e,n);break}}}}});eo(l.layout?.slots??{}),oo.update();let ao=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 n=r.closest("a[href]");if(!n||!e.contains(n)||n.hasAttribute("download")||n.closest("[data-persona-root]")!==e)return;let o=n.getAttribute("target")??n.ownerDocument.querySelector("base[target]")?.getAttribute("target");if((!o||"_self"===o.toLowerCase())&&/^(https?:|mailto:|tel:)/i.test(n.href))try{l.onLinkClick({url:n.href,anchor:n,originalEvent:t,preventDefault:()=>t.preventDefault()})}catch(e){console.error("[AgentWidget] onLinkClick failed:",e)}};e.addEventListener("click",ao),vt.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(),Id(r))}),vt.addEventListener("click",e=>{let t=e.target;t instanceof Element&&t.closest('.persona-approval-head[data-action="toggle-params"]')&&(ni(),kl())},{capture:!0});let so=e=>{let t=e.target.closest('button[data-expand-header="true"]');t&&io(t)},io=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;ni(),kl();let n=Qs;n&&sl();let o=n&&m?.holdScroll(t,ft,n,zl,Ol,ai,()=>Qs===n),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,n=e?b:f;n.has(r)?n.delete(r):n.add(r),m&&(e?m.updateReasoningBubbleUI:m.updateToolBubbleUI)(r,t,n,l)}else if("approval"===a&&E){let e="expanded"===((!1===l.approval?void 0:l.approval)?.detailsDisplay??"collapsed"),n=y.get(r)??e;y.set(r,!n),E.updateApprovalDetailsUI(r,t,l,y)}o?.(),ks.delete(r)};vt.addEventListener("pointerdown",e=>{e.target.closest('button[data-expand-header="true"]')&&(e.preventDefault(),so(e))}),vt.addEventListener("click",e=>{0===e.detail&&e.target.closest(".persona-activity-row")&&so(e)}),vt.addEventListener("keydown",e=>{let t=e.target;("Enter"===e.key||" "===e.key)&&t.closest('button[data-expand-header="true"]')&&(e.preventDefault(),so(e))}),vt.addEventListener("copy",e=>{let{clipboardData:t}=e;if(!t)return;let r=vt.getRootNode(),n="function"==typeof r.getSelection?r.getSelection():window.getSelection();if(!n||n.isCollapsed)return;let o=n.toString(),a=(e=>e.replace(/^\n+/,"").replace(/\s+$/,""))(o);a&&a!==o&&(t.setData("text/plain",a),e.preventDefault())});let lo,co=new Map,po=new Map,uo=0,ho=()=>{vt.querySelectorAll(".persona-tool-bubble[data-tool-call-id]").forEach(e=>{e.toggleAttribute("data-persona-revealed",po.has(e.dataset.messageId))})},mo=()=>{window.clearTimeout(lo),lo=void 0,po.forEach(e=>window.clearTimeout(e)),po.clear(),ho()},go=null,fo="idle",yo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading…"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},wo=()=>{vt.querySelectorAll('[data-action="read-aloud"]').forEach(e=>{let t=e.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;((e,t)=>{let{icon:r,label:n}=yo[t];e.setAttribute("aria-label",n),e.title=n,e.setAttribute("aria-pressed","idle"===t?"false":"true"),e.classList.toggle("persona-message-action-active","idle"!==t),e.classList.toggle("persona-message-action-loading","loading"===t);let o=Ee(r,14,"currentColor",2);o&&(e.innerHTML="",e.appendChild(o))})(e,t&&t===go?fo:"idle")})};vt.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 n=r.getAttribute("data-actions-for");if(!n)return;let o=t.getAttribute("data-action");if("copy"===o){let e=es.getMessages().find(e=>e.id===n);if(e&&ot){let r=e.content||"";navigator.clipboard.writeText(r).then(()=>{t.classList.add("persona-message-action-success");let e=oe(pe,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e)),setTimeout(()=>{t.classList.remove("persona-message-action-success");let e=oe(he,14,"currentColor",2);e&&(t.innerHTML="",t.appendChild(e))},2e3)}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",e)}),ot(e)}}else if("read-aloud"===o)es.toggleReadAloud(n);else if("upvote"===o||"downvote"===o){let e="upvote"===o?"thumbs-up":"thumbs-down";if((co.get(n)??null)===o){co.delete(n),t.classList.remove("persona-message-action-active");let r=Ee(e,14,"currentColor",2);r&&(t.innerHTML="",t.appendChild(r))}else{let a="upvote"===o?"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))}co.set(n,o),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=es.getMessages().find(e=>e.id===n);l&&at&&at({type:o,messageId:l.id,message:l})}}else if("regenerate"===o)xo?.regenerate(n);else if("edit"===o)xo?.edit(n);else if("quote"===o)xo?.quote(n);else if(o?.startsWith("custom:")){let e=o.slice(7),r=l.messageActions?.custom?.find(t=>t.id===e),a=es.getMessages().find(e=>e.id===n);if(!r||!a)return;try{r.onSelect(a)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let xo=null;vt.addEventListener("click",e=>{let t=e.target.closest("button[data-approval-action]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.closest(".persona-approval-bubble");if(!r)return;let n=r.getAttribute("data-message-id");if(!n)return;let o=t.getAttribute("data-approval-action");if(!o)return;let a="approve"===o?"approved":"denied",s=es.getMessages().find(e=>e.id===n);if(!s?.approval)return;let i=r.querySelector("[data-approval-buttons]");i&&i.querySelectorAll("button").forEach(e=>{e.disabled=!0,e.style.opacity="0.5",e.style.cursor="not-allowed"}),cr(s.approval)?es.resolveWebMcpApproval(n,a):es.resolveApproval(s.approval,a)});let Co=null,So=!1,ko=null,Ao=()=>{},Mo="none",To=null,Eo={artifacts:[],selectedId:null},Ro=!1,No=!1,Ho=!1,Do=!1,Oo=()=>Do||Eo.artifacts.some(e=>"panel"===Io(l.features?.artifacts,e)),Fo=()=>Eo.artifacts.length>0&&!Ro&&Oo(),zo={current:null},jo=(e,t)=>{let r=es.getArtifactById(t),n=r?.markdown,o=r?.title||"artifact",a=r?.file,s=r?.artifactType??"markdown";if(!n){let t=(e.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]"))?.getAttribute("data-message-id");if(t){let e=es.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);n=t?.props?.markdown,o=t?.props?.title||o,t?.props?.file&&"object"==typeof t.props.file&&(a=t.props.file),!r&&"string"==typeof t?.props?.artifactType&&(s=t.props.artifactType)}catch{}}}return{markdown:n,title:o,file:a,artifactType:s}};vt.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:n,title:o,file:a}=jo(t,r);if(!n)return;let s=Et();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:o,markdown:n,file:a}))}),vt.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 n=t.closest("[data-artifact-inline]"),o=n?null:t.closest("[data-open-artifact]"),a=n?n.getAttribute("data-artifact-inline"):o?.getAttribute("data-open-artifact")??null,s=(n?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}=jo(t,a??""),u={artifactId:a,title:d,artifactType:p,markdown:i,file:c};try{Promise.resolve(s.onClick(u)).catch(()=>{})}catch{}}),vt.addEventListener("click",e=>{let t=e.target.closest("[data-copy-artifact]");if(!t)return;e.preventDefault(),e.stopPropagation();let r=t.getAttribute("data-copy-artifact");if(!r)return;let n=es.getArtifactById(r),o=Et();if(!o)return;let a="";if(n)a=o.artifactCopyText(n);else{let{markdown:e,file:n,artifactType:s}=jo(t,r);"markdown"===s&&(a=o.artifactCopyText({id:r,artifactType:"markdown",status:"complete",markdown:e??"",...n?{file:n}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=oe(pe,16,"currentColor",2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=oe(he,16,"currentColor",2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),vt.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})&&(Ro=!1,Do=!0,No=!0,Ho=!0,es.selectArtifact(r),Ta())}),vt.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 n=r.getAttribute("data-open-artifact");n&&!0!==l.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:n})&&(e.preventDefault(),e.stopPropagation(),Ro=!1,Do=!0,es.selectArtifact(n),Ta())}),vt.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 qo=mt.composerOverlay,_o=e=>{Wt().catch(()=>{}),Pn(e,l,qo)},Uo=null,Vo={instanceId:o,mount:e,overlay:qo,sessionRef:zo,config:()=>l},Ko=!1,Qo=e=>t=>{let r=t.target,n=r?.closest?.("[data-persona-ask-sheet-for]");if(!n||!("click"===e?r?.closest("[data-ask-user-action]"):"Enter"===t.key&&r?.matches?.('[data-ask-free-text-input="true"]')))return;let o=r=>{Uo??=r.createAskUserSheetHandlers(Vo),Uo[e](t)},a=Ht();a?o(a):Ko||(Ko=!0,Wt().then(e=>{Ko=!1,n.isConnected&&o(e)},()=>{Ko=!1}))};qo.addEventListener("click",Qo("click")),qo.addEventListener("keydown",Qo("keydown"));let Jo=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=qo.querySelector("[data-persona-ask-sheet-for]");if(!r||"rows"!==r.getAttribute("data-ask-layout")||"true"===r.getAttribute("data-multi-select"))return;let n=Number(e.key),o=r.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[n-1];o&&(e.preventDefault(),o.click())};document.addEventListener("keydown",Jo);let Go=null,Yo=null,Xo=()=>{},Zo=!1,ta="",ra="",sa=()=>{let e=Jc?.railShell?Jc.railHost:null,t=e?.isConnected?e:null,r=t?t.getBoundingClientRect().width:0;return r<=0?200:r+360},ia=()=>{},ya=()=>{let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,n=l.launcher?.mobileBreakpoint??640;return!(!r||t.innerWidth>n)&&(ne||ll(l))},Ca=()=>!Fd(l)||!Fo()||e.classList.contains("persona-artifact-narrow-host")||ya()||(e.ownerDocument.defaultView??window).innerWidth<641?"none":_d(l)?"detached":"welded",Ta=()=>{if(!Co||!Fd(l))return;Ud(e,l),Vd(e,l),ia();let t=l.features?.artifacts?.layout?.narrowHostMaxWidth??520,r=ut.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",r>0&&r<=t);let n=Fo();Co.setVisible(n),Co.update(Eo),Ro?(Co.setMobileOpen(!1),Co.element.classList.add("persona-hidden"),Co.backdrop?.classList.add("persona-hidden"),No=!1,Ho=!1):Eo.artifacts.length>0&&Oo()?(Co.element.classList.remove("persona-hidden"),Co.setMobileOpen(!0)):(Co.setMobileOpen(!1),Co.element.classList.add("persona-hidden"),Co.backdrop?.classList.add("persona-hidden"),No=!1,Ho=!1);let o=!0===l.features?.artifacts?.layout?.showExpandToggle;if(Co.setExpandToggleVisible(o),Co.setCopyButtonVisible(!0===l.features?.artifacts?.layout?.showCopyButton),Co.setRefreshButtonVisible("function"==typeof l.features?.artifacts?.layout?.onDocumentToolbarRefresh),Co.setCustomActions(l.features?.artifacts?.toolbarActions??[]),Co.setStyleConfig(l),Co.setTabFade(l.features?.artifacts?.layout?.tabFade),Co.setRenderTabBar(l.features?.artifacts?.renderTabBar),!o&&!Ho&&(No=!1),No!==Zo){let e=Co.element;No?(ta=e.style.width,ra=e.style.maxWidth,e.style.removeProperty("width"),e.style.removeProperty("max-width")):(ta&&(e.style.width=ta),ra&&(e.style.maxWidth=ra),ta="",ra=""),Zo=No}e.classList.toggle("persona-artifact-expanded",No),Co.setExpanded(No);let a=Ca();a!==Mo&&(Mo=a,Ao()),Xo()};if(Fd(l)){ut.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(gt),Go=r,r.appendChild(t),ut.appendChild(r);let n=t=>{So||Co||(Co=t.createArtifactPane(l,{onSelect:e=>zo.current?.selectArtifact(e),onDismiss:()=>{Ro=!0,Ta()},onToggleExpand:()=>{let e=!No,t=Eo.selectedId??Eo.artifacts[Eo.artifacts.length-1]?.id??null;!0!==l.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:t,expanded:e})&&(No=e,e||(Ho=!1),Ta())}}),Yo=t.createArtifactResizer({mount:e,splitRoot:r,pane:Co,getConfig:()=>l,chatMinWidth:sa,isVisible:Fo}),Co.element.classList.add("persona-hidden"),r.appendChild(Co.element),Co.backdrop&&ut.appendChild(Co.backdrop),Xo(),Ta())},o=Et();o?n(o):(Lt(()=>{let e=Et();e&&n(e)}),Tt().catch(()=>{})),Xo=()=>Yo?.update(),ia=()=>{if(!ne||!Co||l.launcher?.sidebarMode||ll(l)&&"emerge"===cl(l).reveal)return;let t=e.ownerDocument.defaultView??window,r=l.launcher?.mobileFullscreen??!0,n=l.launcher?.mobileBreakpoint??640;if(r&&t.innerWidth<=n||!function(e,t){return!(!t||!Fd(e))&&!1!==e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen}(l,ne))return;let o=md(l).width,a=l.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Fo()?(ut.style.width=a,ut.style.maxWidth=a):(ut.style.width=o,ut.style.maxWidth=o)},typeof ResizeObserver<"u"&&(ko=new ResizeObserver(()=>{Ta()}),ko.observe(ut))}else ut.appendChild(gt);me()&&ht&&(mt.peekBanner&&ht.appendChild(mt.peekBanner),ht.appendChild(tr)),e.appendChild(pt),ht&&e.appendChild(ht);let La=()=>{let t=ya()||me()&&"fullscreen"===l.launcher?.composerBar?.expandedSize||!0===l.launcher?.fullHeight&&!l.launcher?.sidebarMode&&!ll(l);if(vt.style.gap=t?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",vt.style.setProperty("--persona-transcript-gap",vt.style.gap),me()){ut.style.width="100%",ut.style.maxWidth="100%";let e=l.launcher?.composerBar??{},t="expanded"===pt.dataset.state,r=e.expandedSize??"anchored";if(!t||"fullscreen"===r)return gt.style.background="",gt.style.border="",gt.style.borderRadius="",gt.style.overflow="",void(gt.style.boxShadow="");let n=l.theme?.components?.panel,o=ci(l),a=(e,t)=>null==e||""===e?t:Vs(o,e)??e;return gt.style.background="var(--persona-surface, #ffffff)",gt.style.border=a(n?.border,"1px solid var(--persona-border)"),gt.style.borderRadius=a(n?.borderRadius,"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))"),gt.style.boxShadow=a(n?.shadow,"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))"),void(gt.style.overflow="hidden")}let r=ll(l),n=l.launcher?.sidebarMode??!1,o=ss(l)||r||n||(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"===di(l)?k(i??{},d??{}):i,p=ci(l),u=(e,t)=>null==e||""===e?t:Vs(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&&ne,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":n?"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:n||b?"none":A,R=T?M:b?"none":n?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:n||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=Ca(),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")&&Fd(l)&&_d(l)&&a&&!r;e.classList.toggle("persona-artifact-chat-flush",z);let j=D||z?"none":$,q=D?A:O?"none":N,_=D?I:W;z&&(q="none",_="0");let U=null!=L?.borderRadius&&""!==L.borderRadius||null!=c?.borderRadius&&""!==c.borderRadius,V=z&&!U?"0":W,K=ft.scrollTop;e.style.cssText="",pt.style.cssText="",ut.style.cssText="",gt.style.cssText="",ft.style.cssText="",Mn||(tr.style.cssText="",!1===l.layout?.showFooter&&(tr.style.display="none")),je&&(ft.style.display="none"),(o||a)&&(e.style.minWidth="0");let Q=()=>{K<=0||(ft.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ft.scrollTop===K)return;let e=ft.scrollHeight-ft.clientHeight;e<=0||(ft.scrollTop=Math.min(K,e))})};if(b)return pt.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"),pt.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 `,ut.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 ",gt.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 ",ft.style.flex="1 1 0%",ft.style.minHeight="0",ft.style.overflowY="auto",tr.style.flexShrink="0",Ur(),ue=!0,void Q();let J=md(l);if(n||r){if(r)if("emerge"!==cl(l).reveal||s)ut.style.width="100%",ut.style.maxWidth="100%";else{let e=cl(l).width;ut.style.width=e,ut.style.maxWidth=e}}else a?(pt.style.width=gd(l),ut.style.width="100%",ut.style.maxWidth="100%"):(ut.style.width=J.width,ut.style.maxWidth=J.maxWidth);if(ia(),ut.style.boxShadow=j,ut.style.borderRadius=V,D?ut.style.border="none":O&&(ut.style.border=N),gt.style.border=q,gt.style.borderRadius=_,gt.style.boxShadow=D&&!z?F:"",z&&(gt.style.background="transparent",ft.style.background="transparent",tr.style.background="transparent",tr.style.borderTop="none"),O){let e=l.features?.artifacts?.layout;To=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||Od(l,void 0,"split.outerRadius")||Od(l,void 0,"pane.borderRadius")||W}else To=null;let G=null!=L?.border||null!=c?.border;if(r&&!b&&!T&&!D&&!O&&!G&&(gt.style.border="none","right"===cl(l).side?gt.style.borderLeft="1px solid var(--persona-border)":gt.style.borderRight="1px solid var(--persona-border)"),r&&!b&&O&&!G&&("right"===cl(l).side?ut.style.borderLeft="1px solid var(--persona-border)":ut.style.borderRight="1px solid var(--persona-border)"),o&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",ss(l)&&(e.style.flex="1 1 0%"),a&&(e.style.width="100%"),pt.style.display="flex",pt.style.flexDirection="column",pt.style.flex="1 1 0%",pt.style.minHeight="0",pt.style.maxHeight="100%",pt.style.height="100%",a&&(pt.style.overflow="hidden"),ut.style.display="flex",ut.style.flexDirection="column",ut.style.flex="1 1 0%",ut.style.minHeight="0",ut.style.maxHeight="100%",ut.style.height="100%",D||(ut.style.overflow="hidden"),gt.style.display="flex",gt.style.flexDirection="column",gt.style.flex="1 1 0%",gt.style.minHeight="0",gt.style.maxHeight="100%",gt.style.overflow="hidden",ft.style.flex="1 1 0%",ft.style.minHeight="0",ft.style.overflowY="auto",tr.style.flexShrink="0"),a&&(T||D||z)&&!r&&(z||(pt.style.padding="var(--persona-panel-inset)"),pt.style.background="var(--persona-panel-canvas-bg)"),pt.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"),!n&&!a&&!r&&(bl[v]??bl["bottom-right"]).split(" ").forEach(e=>pt.classList.add(e)),n){let e=ns(l).sidebarWidth?l.launcher?.sidebarWidth??"420px":Vs(ci(l),"components.panel.width")??"420px";pt.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 `,ut.style.cssText=`\n position: relative !important;\n display: flex !important;\n flex-direction: column !important;\n flex: 1 1 0% !important;\n width: 100% !important;\n max-width: 100% !important;\n height: 100% !important;\n min-height: 0 !important;\n margin: 0 !important;\n padding: 0 !important;\n box-shadow: ${j} !important;\n border-radius: ${V} !important;\n ${D?"border: none !important;":O?`border: ${N} !important;`:""}\n `,ut.style.setProperty("width","100%","important"),ut.style.setProperty("max-width","100%","important"),gt.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: ${q} !important;\n ${D&&!z?`box-shadow: ${F} !important;`:""}\n ${z?"background: transparent !important;":""}\n `,Mn||(tr.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=n?"":"padding-top: 1.25em !important;",t=n?"":`z-index: ${l.launcher?.zIndex??1e5} !important;`;pt.style.cssText+="max-height: -moz-available !important; max-height: stretch !important;"+e+t}Ur(),Q()},Ba=()=>{e.style.setProperty("--persona-content-max-width",fi(l,me()))},Ra=!1;function Na(){l.layout?.topFade&&ft.scrollTop>1?ft.setAttribute("data-persona-top-fade","true"):ft.removeAttribute("data-persona-top-fade"),Er.hidden=!me()||Tr.hidden||ft.scrollHeight-ft.clientHeight-ft.scrollTop<=1,Er.hidden||(Er.style.bottom=gt.getBoundingClientRect().bottom-Tr.getBoundingClientRect().top-gt.clientTop+"px")}let $a=()=>{Na();let t=bi(l,me());me()&&l.composer?.placement&&!0===l.debug&&!Ra&&(Ra=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let r=Wr();e.setAttribute("data-persona-composer-placement",t),e.setAttribute("data-persona-conversation-state",Dr),e.setAttribute("data-persona-welcome-anchor",r.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",r.composerGap??"24px"),Vr()},Wa=()=>{if(me())return;let t=ll(l),r=l.launcher?.sidebarMode??!1;if(ss(l)||t||r||l.launcher?.fullHeight||!ne)return;let n=e.ownerDocument.defaultView??window,o=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640;if(o&&n.innerWidth<=a)return;let s=md(l);ut.style.height=s.height,ut.style.maxHeight=s.maxHeight};La(),hi(e,l),Ud(e,l),Vd(e,l),Ba(),$a(),Ao=()=>{La(),Wa(),hi(e,l),Ud(e,l),Vd(e,l),Ba(),$a(),To?e.style.setProperty("--persona-artifact-welded-outer-radius",To):e.style.removeProperty("--persona-artifact-welded-outer-radius"),et(),Ze()};let Da=[];Da.push(()=>Jn.destroy()),Da.push(()=>{So=!0}),Da.push(()=>{M.forEach(e=>e()),A.destroy()}),Da.push(()=>{document.removeEventListener("keydown",Jo)}),Da.push(()=>{null!==Rr&&clearTimeout(Rr)});let Oa=null,Fa=null;Da.push(()=>{Oa?.(),Oa=null,Fa?.(),Fa=null}),ko&&Da.push(()=>{ko?.disconnect(),ko=null}),Da.push(()=>{Yo?.destroy(),Yo=null,Co?.element.style.removeProperty("width"),Co?.element.style.removeProperty("maxWidth"),Co?.destroy()}),Te&&Da.push(()=>{Fe=!0,Oe=null,null!==_e&&(cancelAnimationFrame(_e),_e=null),ze?.destroy(),ze=null,He?.destroy(),He=null,Pe=null});let za=null,qa=()=>{if(za&&=(za(),null),"auto"===l.colorScheme){let e=di(l);za=gi(t=>{t!==e&&(e=t,Ao(),Ta(),es&&(Os++,cd(vt,es.getMessages(),Ae)))})}};qa(),Da.push(()=>{za&&=(za(),null)}),Da.push(()=>{R=!0,B?.()}),Da.push(()=>{W=!0});let Ua=!1;Da.push(()=>{Ua=!0});let Va=(t,r)=>{let n=Oi(t,r);return n||!Hi.includes(t)?n:(nl().then(n=>{if(Ua)return;Di(n.wipe),Di(n.glyphCycle);let o=Oi(t,r);o&&Zi(o,e)}).catch(()=>{}),null)},Ka=l.features?.streamAnimation;if(Ka?.type&&"none"!==Ka.type){let t=Va(Ka.type,Ka.plugins);t&&Zi(t,e),Da.push(()=>Xi(e))}let Qa=fl(Ct),Ga=fl(wt),Ya=fl(xt),Xa=fl(Tr),Za=[Qa,Ga,Ya,Xa];Da.push(()=>{Za.forEach(e=>e.destroy())});let es,ts=null,rs=null,os=!1,as=0,ls=null,ds=new Set;Da.push(()=>ds.clear());let cs=e=>e.reduce((e,t)=>"user"===t.role?e+1:e,0),ps=e=>{for(let t=e.length-1;t>=0;t--)if(Dn(e[t]))return e[t].id??null;return null},us=!1,hs=!1,ms=!1,gs=(e,t)=>{hs||!0!==l.debug||t.enabled&&!t.expose&&(os||ms&&(es.isStreaming()||e.some(Dn)||(hs=!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."))))},bs=e=>{if(!es)return;let t=e??es.getMessages();if(Ct.removeAttribute("data-persona-suggestions-below"),Ct.parentElement===tr&&tr.insertBefore(Ct,tr.firstChild),ds.size){let e=new Set(t.map(e=>e.id));for(let t of ds)e.has(t)||ds.delete(t)}let r=e=>{e.render([],es,St,t)},n=e=>{Za.forEach(t=>{t!==e&&r(t)})};rs&&(cs(t)>as||ps(t)!==ls)&&(rs=null);let o=jn(l);gs(t,o);let a=ps(t),s=!o.enabled||l.future?.v5Defaults&&a&&ds.has(a)?null:Fn(t,l.suggestions?.followUps?.maxItems??(l.future?.v5Defaults?5:4));if(l.future?.v5Defaults&&es.isStreaming())return void Za.forEach(r);let i=rs??s,d=rs?"host":"agent";if(i){let e=l.suggestions?.followUps,r=e?.placement??(e?"auto":"composer"),o="after-message"===("auto"===r?me()?"composer":"after-message":r)?Ya:me()?Xa:Qa;return n(o),void o.render(i,es,St,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?$r()?5:3:4),config:l,plugins:S,submitPrompt:Xp})}if(t.some(e=>"user"===e.role))return void Za.forEach(r);let c=!0===l.future?.v5Defaults,p=$r(),u=l.suggestions?.starters??(c?{}:void 0);if(u){let e=ud(Wr(),t),o=u.placement??"auto",a="auto"===o?e?"welcome":"composer":o;if("welcome"===a&&!e)return us||!0!==l.debug||(us=!0,console.warn('[persona] Starters are hidden: suggestions.starters.placement is "welcome", but welcome is disabled. Use "auto" or "composer".')),void Za.forEach(r);Ct.toggleAttribute("data-persona-suggestions-below","below-composer"===a),"below-composer"===a?At.after(Ct):tr.insertBefore(Ct,tr.firstChild);let s="welcome"===a?Ga:Qa;n(s),s.render(u.items??l.suggestionChips,es,St,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:S,submitPrompt:Xp})}else n(Qa),Qa.render(l.suggestionChips,es,St,t,l.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:l,plugins:S,submitPrompt:Xp})},ys=()=>{if(!l.future?.v5Defaults||!es)return;rs=null;let e=ps(es.getMessages());e&&ds.add(e),bs()},vs=()=>{rs&&(rs=null,bs())},xs=!1,ks=new Map,As=new Set,Ms=new Map,Ts=new Map,Es=new Map,Ls=new Map,Bs=e=>{let t=Ls.get(e);if(Ls.delete(e),Es.delete(e),od(vt,e)?.removeAttribute("data-preserve-runtime"),t){t.controller.abort();try{t.handle.destroy?.()}catch(e){console.error("[AgentWidget] Component cleanup failed:",e)}}};Da.push(()=>{for(let e of Ls.keys())Bs(e)});let Rs=new Map,Ps=new Map,Ns=e=>{Ps.get(e)?.abort(),Ps.delete(e),Rs.delete(e)},$s=()=>{for(let e of Ps.keys())Ns(e)};Da.push($s);let Ws=null,Hs=null;function Ds(){if(!Ws)return;let e=Ws;Ws=null,Hs?.destroy(),Hs=null,ks.delete(e),gt.querySelector(`#wrapper-${e}`)?.removeAttribute("data-preserve-runtime"),es&&cd(vt,es.getMessages(),Ae)}let Os=0,Fs=function(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>!!t&&(t=!1,!0),resume:()=>!t&&(t=!0,!0)}}(),zs=0,js=null,qs=!1,_s=!1,Ks=0,Qs=null,Js=null,Gs=!1,Ys=!1,Xs=null,Zs=!0,ei=!1,ti=null,ri=!1,ni=()=>{uo++,ri=!0,li()},oi=null,ai=24,si=null,ii=()=>{e.setAttribute("data-persona-scrollbar",Sr()),"on-scroll"!==Sr()&&(null!==si&&clearTimeout(si),si=null,ft.removeAttribute("data-persona-scrollbar-visible"))},li=()=>{"on-scroll"===Sr()&&(ft.setAttribute("data-persona-scrollbar-visible",""),null!==si&&clearTimeout(si),si=setTimeout(()=>{si=null,Jt(ft,24)&&ft.removeAttribute("data-persona-scrollbar-visible")},1e3))};ii(),Da.push(()=>{null!==si&&clearTimeout(si)});let pi=new Map,ui=!1,mi=null,vi={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Yn();let wi=l.voiceRecognition?.autoResume??!1,Ci=()=>es.isVoiceActive()||es.isBargeInActive(),Ai=!1,Mi=e=>{F.emit("voice:state",{active:vi.active,source:e,timestamp:Date.now()})},Li=()=>{Z(e=>({...e,voiceState:{active:vi.active,timestamp:Date.now(),manuallyDeactivated:vi.manuallyDeactivated}}))},Bi=()=>{Ai=!0,vi.active&&Li()};typeof window<"u"&&(window.addEventListener("pagehide",Bi),Da.push(()=>window.removeEventListener("pagehide",Bi)));let Pi=()=>es?bp(es.getMessages()).filter(e=>!e.__skipPersist):[],$i=null,Wi=(e,t)=>{typeof console<"u"&&console.error(e,t)},zi=(e,t)=>{let r=()=>{try{let r=e();return r&&"function"==typeof r.then?Promise.resolve(r).catch(e=>{Wi(t,e)}):null}catch(e){return Wi(t,e),null}},n=$i?$i.then(()=>r()??void 0):r();if(!n)return;let o=n.finally(()=>{$i===o&&($i=null)});$i=o};function ji(e){if(null!==_i||!z?.save)return;let t=e?bp(e):es?Pi():[],r=j&&es?.getResumableHandle();r&&(_={..._,durableResume:{executionId:r.executionId,after:r.lastEventId}});let n={messages:t,metadata:_,artifacts:Eo.artifacts,selectedArtifactId:Eo.selectedId,...qi?{draft:qi}:{}};zi(()=>z.save(n),"[AgentWidget] Failed to persist state:")}let qi,_i=null,Ui=()=>!(!z?.save||!1===l.persistState||"object"==typeof l.persistState&&!1===l.persistState.persist?.draft),Vi=function(e){let t=e.delay??500,r=null,n=!1,o=()=>{null!==r&&(clearTimeout(r),r=null)};return{schedule:()=>{n||(o(),r=setTimeout(()=>{r=null,e.write()},t))},flush:()=>{n||null===r||(o(),e.write())},cancel:o,destroy:()=>{n=!0,o()}}}({write:()=>{if(!Ui())return;let e=Jr.getState(),t=ma({text:e.text,mentionRefs:e.mentionRefs,contentSegments:jp(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(qi)&&(qi=t,ji())}});function Gi(){Ui()&&Vi.schedule()}function Yi(){Vi.flush()}function el(e){if(!Ui())return;let t=function(e,t){if(!e||"string"!=typeof e.text)return;let r=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(e=>r.has(e.sourceId)),o=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(e=>e.id)),s=(e.activeModeIds??[]).filter(e=>a.has(e)),i=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...o?{mentionRefs:n}:{},...o&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...i?{selectedModelId:i}:{},...s.length?{activeModeIds:s}:{},...e.quote?.text?{quote:e.quote}:{}}}(e,{mentionSourceIds:(l.contextMentions?.sources??[]).map(e=>e.id),modelIds:(l.composer?.models??[]).map(e=>e.id),modes:l.composer?.modes??[]});t&&(qi=e,St&&!St.value&&(St.value=t.text,St.dispatchEvent(new Event("input",{bubbles:!0})),Gr()),t.selectedModelId&&(Jr.setSelectedModelId(t.selectedModelId),dn?.repaint()),sn(t.activeModeIds??[]),t.quote&&un(t.quote),Vi.cancel())}function tl(){Vi.cancel(),qi&&(qi=void 0,Ui()&&ji())}let rl=Yt(),al=()=>pt.querySelector("#persona-scroll-container")||ft,sl=()=>{rl.cancel(),qs=!1},pl=()=>{null!==js&&(cancelAnimationFrame(js),js=null),_s=!1,sl()},ul=()=>{let e=es?.getStatus();return xs&&"paused"!==e&&"resuming"!==e&&"error"!==e&&!es?.getMessages().some(e=>!0===e.agentMetadata?.awaitingLocalTool&&!0!==e.agentMetadata.askUserQuestionAnswered||"approval"===e.variant&&"pending"===e.approval?.status)},ml=()=>ul()&&vl()&&("anchor-top"!==br()||xr()),yl=()=>{kr.update(l,"true"===Ar.getAttribute("data-persona-scroll-to-bottom-visible"),ml(),Ks)},vl=()=>!(yr()&&Fs.isFollowing()||(()=>{let e=zl(Qs?.spacerHeight??0,!1),t=ft.getBoundingClientRect(),r=tr.getBoundingClientRect(),n=r.height>0&&r.bottom>t.top?Math.min(ft.clientHeight,Math.max(0,r.top-t.top-ft.clientTop)):ft.clientHeight;return e-ft.scrollTop-n<=24})()),wl=()=>!!es&&es.getMessages().length>0,Sl=()=>{if(!1===l.features?.scrollToBottom?.enabled||je||Ye&&"panel"===Xe)return kr.update(l,!1),void(Ar.parentNode&&Ar.remove());let e=Ir();Ar.parentNode!==e&&e.insertBefore(Ar,e===gt?Tr:null),jr();let t=Qt(ft)>0,r=!Bl.active&&t&&vl()&&wl();r||(Ks=0),kr.update(l,r,ml(),Ks)},kl=()=>{Fs.pause()&&(pl(),Sl())},Ml=()=>{Fs.resume(),0!==Ks&&(Ks=0,yl()),Sl()},Il=(e=!1)=>{!Bl.active&&yr()&&wl()&&Fs.isFollowing()&&(e||xs)&&(null!==js&&(cancelAnimationFrame(js),js=null),_s=!0,js=requestAnimationFrame(()=>{js=null,_s=!1,Fs.isFollowing()&&Rl(al(),e?220:140)}))},Ll=(e,t,r,n=()=>!0)=>{sl(),qs=!0,rl.start(e,t,r,()=>{zs=e.scrollTop},()=>{qs=!1},n)},Bl=Xt(ft,gt,()=>{zs=ft.scrollTop},()=>{Ml(),Il(!0),Sl()},()=>{Fs.pause(),Sl()}),Rl=(e,t=500)=>{let r=Qt(e)-e.scrollTop;Math.abs(r)<1?zs=e.scrollTop:Math.abs(r)>=80?(sl(),qs=!0,e.scrollTop=Qt(e),zs=e.scrollTop,qs=!1):Ll(e,()=>Qt(e),t,()=>Fs.isFollowing())},Pl=()=>{if(!wl())return void Sl();let e=al();qs=!0,e.scrollTop=Qt(e),zs=e.scrollTop,qs=!1,Sl()},$l=()=>function(e,t){return!(!e||e.isCollapsed)&&(t.contains(e.anchorNode)||t.contains(e.focusNode))}((()=>{let e=ft.getRootNode();return("function"==typeof e.getSelection?e.getSelection():null)??ft.ownerDocument.getSelection()})(),ft),Dl=()=>{if("last-user-turn"!==(Le.restorePosition??"bottom"))return!1;let e=es?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>"user"===e.role);if(!t)return!1;let r=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(t.id):t.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=ft.querySelector(`[data-message-id="${r}"]`);if(!n)return!1;let o=Math.min(Math.max(0,zr(n)-vr()),Qt(ft));return qs=!0,ft.scrollTop=o,zs=ft.scrollTop,qs=!1,"follow"===br()&&!Jt(ft,24)&&Fs.pause(),Sl(),!0},Ol=e=>{let t=Math.max(0,Math.round(e));Lr.style.height=`${t}px`,Lr.style.display=t>0?"":"none",Qs&&(Qs.spacerHeight=Math.max(0,e))},zl=(e,t=!0)=>{let r=parseFloat(getComputedStyle(ft).paddingBottom)||0,n=0;for(let e of ft.children){let t=e;t!==Lr&&0!==t.offsetHeight&&(n=Math.max(n,zr(t)+t.offsetHeight))}let o=ft.scrollHeight-e,a=n>0?Math.min(n+r,o):o;return t?a:a-r},jl=()=>{null!==Js&&(cancelAnimationFrame(Js),Js=null),Bl.cancel(),sl(),Qs=null,Lr.style.height="0px",Lr.style.display="none"},_l=e=>ft.querySelector(`[data-message-id="${(e=>typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'))(e)}"]`),Vl=e=>{let t=_l(e);return t?.closest("[data-persona-turn-activity]")??t},Kl=e=>{null!==Js&&cancelAnimationFrame(Js),Js=requestAnimationFrame(()=>{Js=null;let t=Vl(e);if(!t)return;let r=zr(t),n=zl(Qs?.spacerHeight??0),{targetScrollTop:o,spacerHeight:a}=Gt({anchorOffsetTop:r,topOffset:vr(),viewportHeight:ft.clientHeight,contentHeight:n,slack:24});Qs={pending:0,initialSpacerHeight:a,contentHeightAtAnchor:n,spacerHeight:a},Ol(a),Ll(ft,()=>t.isConnected?Math.max(0,zr(t)-vr()):o,220)})},Ql=()=>{if("anchor-top"!==br()||!Qs||!ti)return;let e=Vl(ti);if(!e)return;sl();let t=Qs.spacerHeight,r=zl(t),{targetScrollTop:n,spacerHeight:o}=Gt({anchorOffsetTop:zr(e),topOffset:vr(),viewportHeight:ft.clientHeight,contentHeight:r,slack:24});Qs={pending:0,initialSpacerHeight:o,contentHeightAtAnchor:r,spacerHeight:o},Ol(o),qs=!0,ft.scrollTop=n,zs=ft.scrollTop,qs=!1,Sl()},Xl=e=>{if(null===Xs)return!0;let t=_l(Xs),r=Vl(e);if(!t||!r)return!0;let n=zr(r)-zr(t);return vr()+n>ft.clientHeight-96},Zl=(e,t)=>{let r="user"===t?"user":"assistant",n=l.layout?.messages?.[r],o=n?.width??"content",a=n?.maxWidth??("full"===o?`var(--persona-message-${r}-max-width, 100%)`:void 0);e.classList.add("persona-message-row"),e.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${o}`),e.classList.toggle("persona-justify-end","user"===t),e.setAttribute("data-message-role",t),e.setAttribute("data-message-width",o),a?e.style.setProperty("--persona-message-row-max-width",a):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),Zl(r,t),r},od=(e,t)=>Array.from(e.querySelectorAll("[data-wrapper-id]")).find(e=>e.getAttribute("data-wrapper-id")===t),id=(t,r,n)=>{let o=new Set;g(),i?.observeMessages(r,o);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=S.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator??l.loadingIndicator?.render,v=new Set,w=new Map,x=new Set,C=S.some(e=>e.renderAskUserQuestion),k=[],A=[],M=!1!==l.enableComponentStreaming,T=!1!==l.approval,B=[],R=l.messageActions;if(l.future?.v5Defaults&&void 0===R?.visibility)for(let e=r.length-1;e>=0;e--)if("assistant"===r[e].role&&!r[e].variant){p=r[e].id;break}let P=!0!==R?.showRegenerate&&"block"!==l.errorDisplay||!1===R?.enabled||!0===zo.current?.isStreaming()?null:function(e){for(let t=e.length-1;t>=0;--t){let r=e[t];if("user"===r.role||r.streaming)return null;if("assistant"===r.role&&!r.variant)return Lo(e,r.id)?r.id:null}return null}(r),N=!0===R?.showEdit&&!1!==R.enabled,W=!0===R?.showQuote&&!1!==R.enabled,H=null,D=l.features?.reasoningDisplay?.completedVisibility,F=e=>"removed"===D||"removed-when-short"===D&&((e,t)=>{let r=t?.durationMs??15e3,n=t?.chars??1200;return"number"==typeof e.durationMs?e.durationMs<r:(e.chunks??[]).join("").length<n})(e,l.features?.reasoningDisplay?.shortThinkThreshold),z="removed"===l.features?.toolCallDisplay?.completedVisibility,j=e=>"reasoning"===e.variant&&"complete"===e.reasoning?.status?F(e.reasoning):z&&"tool"===e.variant&&"complete"===e.toolCall?.status&&!e.toolCall.interrupted;r.forEach(o=>{if(j(o))return;if(v.add(o.id),w.set(o.id,o.role),("tool"===o.variant&&o.toolCall&&Ie||"reasoning"===o.variant&&o.reasoning&&Me)&&!g())return void a.appendChild(ed(o.id,o.role));if(Ws===o.id&&Hs){let e=ed(o.id,o.role);return e.setAttribute("data-persona-message-edit-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void(H={messageId:o.id,element:Hs.element})}let s=C&&vn(o),i=T&&"approval"===o.variant&&!!o.approval,I=!s&&"assistant"===o.role&&!o.variant&&M&&$o(o);!i&&Rs.has(o.id)&&(od(t,o.id)?.removeAttribute("data-preserve-runtime"),Ns(o.id)),!I&&Es.has(o.id)&&(od(t,o.id)?.removeAttribute("data-preserve-runtime"),Bs(o.id));let D=vn(o)?`:${o.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${o.agentMetadata?.askUserQuestionAnswers?Object.keys(o.agentMetadata.askUserQuestionAnswers).length:0}`:"",F={isLastAssistant:o.id===p,canRegenerate:P===o.id&&(!0===R?.showRegenerate||!0===o.dispatchError),canEdit:N&&Bo(o),canQuote:W&&!o.variant&&(o.content?.trim().length??0)>0},z=`${F.canRegenerate?"r":""}${F.canEdit?"e":""}${F.canQuote?"q":""}${F.isLastAssistant?"l":""}`,q=o.approval?.toolCallId?r.filter(e=>!("tool"!==e.variant||e.toolCall?.id!==o.approval?.toolCallId||e.agentMetadata?.executionId&&o.approval?.executionId&&e.agentMetadata.executionId!==o.approval.executionId)):[],_=1===q.length?q[0].toolCall:void 0,U=_&&"pending"!==_.status?{toolCallId:_.id,status:"running"===_.status?"running":!1===_.success||_.error?"failed":"completed"}:void 0,V=Ri(o,Os)+D+`:${z}`+(i?`:${o.approval?.toolCallId??""}:${JSON.stringify(U)}`:""),K=s||i||I||o.dispatchError&&"block"===l.errorDisplay&&!E?null:function(e,t,r){let n=e.get(t);return n&&n.fingerprint===r?n.wrapper:null}(ks,o.id,V);if(K){if(c.has(o.id)&&Ms.get(o.id)===V){let e=document.createElement("div");e.id=`wrapper-${o.id}`,e.setAttribute("data-wrapper-id",o.id),e.setAttribute("data-persona-reuse","true"),a.appendChild(e)}else a.appendChild(K.cloneNode(!0));return d&&u.set(o.id,V),void(vn(o)&&o.toolCall?.id&&!0===o.agentMetadata?.awaitingLocalTool&&!o.agentMetadata?.askUserQuestionAnswered&&(x.add(o.toolCall.id),_o(o)))}let Q=null,J=()=>{if(o.dispatchError&&"block"===l.errorDisplay){let e=$();if(e)return e.createErrorBlock(o,n,!0===F.canRegenerate)}let e=Jl(o,n,l.layout?.messages,l.messageActions,0,{loadingIndicatorRenderer:h,widgetConfig:l,actionEligibility:F});return e.dataset.personaDefaultMessage="true",e},G=S.find(e=>!!("reasoning"===o.variant&&e.renderReasoning||"tool"===o.variant&&e.renderToolCall||!o.variant&&e.renderMessage));if(vn(o)&&!0===o.agentMetadata?.askUserQuestionAnswered)return Ts.delete(o.id),void od(t,o.id)?.removeAttribute("data-preserve-runtime");if(Dn(o)&&jn(l).enabled)return;if(vn(o)&&!1!==l.features?.askUserQuestion?.enabled){let e=S.find(e=>"function"==typeof e.renderAskUserQuestion);if(e&&zo.current){let t=Ts.get(o.id),r=t!==V,n=null;if(r){let{payload:t,complete:r}=xn(o),a=o.id,s=()=>zo.current?.getMessages().find(e=>e.id===a);n=e.renderAskUserQuestion({message:o,payload:t,complete:r,resolve:e=>{let t=s();t&&zo.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(zo.current?.markAskUserQuestionResolved(e),zo.current?.resolveAskUserQuestion(e,"(dismissed)"))},config:l})}if(r&&null===n&&null==t)return void(!0===o.agentMetadata?.awaitingLocalTool&&!o.agentMetadata?.askUserQuestionAnswered&&(x.add(o.toolCall.id),_o(o)));let s=ed(o.id,o.role);return s.setAttribute("data-ask-plugin-stub","true"),s.setAttribute("data-preserve-runtime","true"),a.appendChild(s),void k.push({messageId:o.id,fingerprint:V,bubble:n})}return void(!0===o.agentMetadata?.awaitingLocalTool&&!o.agentMetadata?.askUserQuestionAnswered&&(x.add(o.toolCall.id),_o(o)))}if(i){let t=$();if(!t)return void a.appendChild(ed(o.id,o.role));let r=S.find(e=>"function"==typeof e.renderApproval)??L,n=Rs.get(o.id),s=null,i=!1;if(n!==V&&r?.renderApproval){let a=o.id,d=!1,c=(e,t)=>{let r=zo.current?.getMessages().find(e=>e.id===a);d||"pending"!==r?.approval?.status||(d=!0,cr(r.approval)?zo.current?.resolveWebMcpApproval(r.id,e):zo.current?.resolveApproval(r.approval,e,t))};Ns(o.id);let p=new AbortController;Ps.set(o.id,p);let u={message:o,execution:U,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??=L?.renderApproval?.({...u,signal:m.signal})??t.createApprovalBubble(o,l,y),h);s=r===L?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===n&&"pending"===o.approval?.status&&!1!==l.approval&&"focused"===l.approval?.keyboardShortcuts&&e.contains(b.activeElement)}let d=ed(o.id,o.role);return d.setAttribute("data-approval-plugin-stub","true"),d.setAttribute("data-preserve-runtime","true"),a.appendChild(d),void B.push({messageId:o.id,fingerprint:V,bubble:s,focusDefault:i})}if(G)if("reasoning"===o.variant&&o.reasoning&&G.renderReasoning){if(!Me)return;Q=G.renderReasoning({message:o,defaultRenderer:()=>m.createReasoningBubble(o,l,b),config:l})}else if("tool"===o.variant&&o.toolCall&&G.renderToolCall){if(!Ie)return;Q=G.renderToolCall({message:o,defaultRenderer:()=>m.createToolBubble(o,l,f),config:l})}else G.renderMessage&&(Q=G.renderMessage({message:o,defaultRenderer:()=>{let e=J();return"user"!==o.role&&O(e,o,l,es),e},config:l}));if(Q&&Ls.has(o.id)&&Bs(o.id),!Q&&I){let e=Wo(o);if(e){let r=Es.get(o.id),s=!1!==l.wrapComponentDirectiveInBubble&&!1!==yt(l,e.component)?.bubbleChrome,i=`${Ri(o,Os)}:${s}:${e.raw}`,d=Ls.get(o.id),c=bt(l,e.component),p=d?.renderer!==c||d?.component!==e.component,u=r!==i||p;d&&(d.context.message=o,d.context.config=l);let h=null;if(u){let r=null;if(d&&!p&&d.handle.update){d.context.message=o,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),Bs(o.id)}}else{Bs(o.id);let t=new AbortController,a={config:l,message:o,signal:t.signal,updateProps:e=>{queueMicrotask(()=>{t.signal.aborted||zo.current?.updateComponentProps(o.id,e)})}},s=Po(e,{config:l,message:o,transform:n,signal:t.signal,onPropsUpdate:a.updateProps,context:a});if(s){let n="element"in s?s:{element:s};r=n.element,Ls.set(o.id,{renderer:c,component:e.component,controller:t,handle:n,context:a})}else t.abort()}if(r&&"PersonaArtifactInline"===e.component){let e=r.hasAttribute("data-artifact-inline")?r:r.querySelector("[data-artifact-inline]"),n=e?.getAttribute("data-artifact-inline")??"",a=typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(n):n,s=n?t.querySelector(`#wrapper-${o.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"].join(" "),e.id=`bubble-${o.id}`,e.setAttribute("data-message-id",o.id),o.content&&o.content.trim()){let t=document.createElement("div");t.className="persona-mb-3 persona-text-sm persona-leading-relaxed",t.innerHTML=n({text:o.content,message:o,streaming:!!o.streaming,raw:o.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-${o.id}`,e.setAttribute("data-message-id",o.id),e.setAttribute("data-persona-component-directive","true"),o.content&&o.content.trim()){let t=document.createElement("div");t.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",t.innerHTML=n({text:o.content,message:o,streaming:!!o.streaming,raw:o.rawContent}),e.appendChild(t)}e.appendChild(r),h=e}}if(h||Ls.has(o.id)){let e=ed(o.id,o.role);return e.setAttribute("data-component-directive-stub","true"),e.setAttribute("data-preserve-runtime","true"),a.appendChild(e),void A.push({messageId:o.id,fingerprint:i,bubble:h})}}}if(!Q)if("reasoning"===o.variant&&o.reasoning){if(!Me)return;Q=m.createReasoningBubble(o,l,b)}else if("tool"===o.variant&&o.toolCall){if(!Ie)return;Q=m.createToolBubble(o,l,f)}else if("approval"===o.variant&&o.approval){if(!1===l.approval)return;let e=$();if(!e)return;Q=e.createApprovalBubble(o,l,y)}else{let e=l.layout?.messages;Q=e?.renderUserMessage&&"user"===o.role?e.renderUserMessage({message:o,config:l,streaming:!!o.streaming}):e?.renderAssistantMessage&&"assistant"===o.role?e.renderAssistantMessage({message:o,config:l,streaming:!!o.streaming}):J(),"user"!==o.role&&Q&&O(Q,o,l,es)}let Y=ed(o.id,o.role);Y.appendChild(Q),function(e,t,r,n){e.set(t,{fingerprint:r,wrapper:n})}(ks,o.id,V,Y),a.appendChild(Y),d&&u.set(o.id,V)}),mt.composerOverlay&&mt.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(e=>{let t=e.getAttribute("data-persona-ask-sheet-for");t&&!x.has(t)&&Nn(mt.composerOverlay,t)});let q=g()?.groupToolRows({root:e,config:l,messages:r,tempContainer:a,streaming:!!I&&es.isStreaming(),runActivity:es?.getRunActivity(),showToolCalls:Ie,showReasoning:Me,dropCompletedToolCalls:z,dropReasoningRow:F,createMessageRow:ed,activityIds:o,activityLifecycle:i,toolExpansionState:f});i?.prune(o);for(let e of Ls.keys())v.has(e)||Bs(e);for(let e of Ps.keys())v.has(e)||Ns(e);!function(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}(ks,v);let _=e=>"tool"===e.variant&&!Ie||"reasoning"===e.variant&&!Me||j(e),U=r.some(e=>"assistant"===e.role&&e.streaming&&!_(e)),V=r.length-1;for(;V>=0&&_(r[V]);)V--;let K=V>=0?r[V]:void 0,Q=V<r.length-1,J="assistant"===K?.role&&!K.streaming&&"approval"!==K.variant&&!Q;if(!q&&xs&&r.some(e=>"user"===e.role)&&!U&&!J){let e={config:l,streaming:!0,location:"standalone",defaultRenderer:()=>Fl(l)},t=S.find(e=>e.renderLoadingIndicator)?.renderLoadingIndicator?.(e)??l.loadingIndicator?.render?.(e)??Fl(l);if(t){let e=document.createElement("div"),r=!1!==l.loadingIndicator?.showBubble,n=l.layout?.messages?.layout??"bubble";e.className=r?ql("assistant",n).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),e.setAttribute("data-typing-indicator","true"),r&&(e.style.color="var(--persona-message-assistant-text, var(--persona-text))","flat"!==n&&(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 o=ed("typing-indicator","assistant");o.appendChild(e),a.appendChild(o)}}if(!xs&&r.length>0){let e=r[r.length-1],t={config:l,lastMessage:e,messageCount:r.length},n=S.find(e=>e.renderIdleIndicator)?.renderIdleIndicator?.(t)??l.loadingIndicator?.renderIdle?.(t);if(n){let e=document.createElement("div");e.className=!1===l.loadingIndicator?.showBubble?["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "):["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "),e.setAttribute("data-idle-indicator","true"),e.appendChild(n);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),Ti(t,a),Ms=u;for(let e of Array.from(t.querySelectorAll(":scope > [data-persona-reuse]"))){let t=ks.get(e.getAttribute("data-wrapper-id")??"");t?e.replaceWith(t.wrapper.cloneNode(!0)):e.remove()}if(Hr(t),H){let{messageId:e,element:r}=H,n=od(t,e);n&&r.parentElement!==n&&(Zl(n,w.get(e)??"user"),n.replaceChildren(r))}if(k.length>0)for(let{messageId:e,fingerprint:r,bubble:n}of k){let o=od(t,e);o&&(Zl(o,w.get(e)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Ts.set(e,r)))}if(Ts.size>0)for(let e of Ts.keys())v.has(e)||Ts.delete(e);if(A.length>0)for(let{messageId:e,fingerprint:r,bubble:n}of A){let o=od(t,e);o&&(Zl(o,w.get(e)??"assistant"),null!==n&&(o.replaceChildren(n),o.setAttribute("data-bubble-fp",r),Es.set(e,r)))}if(Es.size>0)for(let e of Es.keys())v.has(e)||Es.delete(e);if(B.length>0)for(let{messageId:e,fingerprint:r,bubble:n,focusDefault:o}of B){let a=od(t,e);a&&(Zl(a,w.get(e)??"assistant"),null!==n&&(a.replaceChildren(n),a.setAttribute("data-bubble-fp",r),Rs.set(e,r),o&&n.querySelector('[data-action="allow"]')?.focus()))}if(Rs.size>0)for(let e of Rs.keys())v.has(e)||Rs.delete(e);g(),s?.sync(),i?.sync()},ld=()=>{qr().catch(()=>{})},cd=(e,t,r)=>{if(t.length>0&&ld(),id(e,t,r),wo(),po.size>0){for(let[e,r]of po)t.some(t=>t.id===e)||(window.clearTimeout(r),po.delete(e));ho()}},hd=null,fd=()=>{if(hd)return;let t=e=>{let t=e.composedPath();t.includes(pt)||ht&&t.includes(ht)||Bd(!1,"user")};hd=t,(e.ownerDocument??document).addEventListener("pointerdown",t,!0)},vd=()=>{hd&&=((e.ownerDocument??document).removeEventListener("pointerdown",hd,!0),null)};Da.push(()=>vd());let wd=null,xd=()=>{if(wd)return;let t=e=>{"Escape"===e.key&&(e.isComposing||Bd(!1,"user"))};wd=t,(e.ownerDocument??document).addEventListener("keydown",t,!0)},Cd=()=>{wd&&=((e.ownerDocument??document).removeEventListener("keydown",wd,!0),null)};Da.push(()=>Cd());let Sd=!1,Md=new Set,Td=()=>l.launcher?.composerBar?.peek?.streamAnimation||l.features?.streamAnimation,Ed=()=>{if(!me())return;let t=mt.peekBanner,r=mt.peekTextNode;if(!t||!r)return;if(fe)return void t.classList.remove("persona-pill-peek--visible");let n,o=es?.getMessages()??[];for(let e=o.length-1;e>=0;e--){let t=o[e];if("assistant"===t.role&&t.content){n=t;break}}if(!n)return void t.classList.remove("persona-pill-peek--visible");let a=n.content,s=!!n.streaming,i=Td(),l=Ni(i),d="none"===l.type?null:Va(l.type,i?.plugins),c=!0===d?.isAnimating?.(n),p=null!==d&&(s||c);p&&d&&!Md.has(d.name)&&(Zi(d,e),Md.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,n,s):a;if(!p||"skeleton"!==l.placeholder||!s||m&&m.trim()){let e=Math.max(0,m.length-100),o=m.length>100?m.slice(-100):m,a=Mr(o);if(p&&d){let s=a;("char"===d.wrap||"word"===d.wrap)&&(s=Ki(a,d.wrap,`peek-${n.id}`,{skipTags:d.skipTags,startIndex:e}));let i=document.createElement("div");if(i.innerHTML=s,d.useCaret&&o.length>0){let e=Qi(),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)}Ti(r,i),d.onAfterRender?.({container:r,bubble:t,messageId:n.id,message:n,speed:l.speed,duration:l.duration})}else{let e=m.length>100?`…${o}`:o;r.textContent!==e&&(r.textContent=e)}}else{let e=document.createElement("div"),t=Ji();t.classList.add("persona-pill-peek__skeleton"),e.appendChild(t),Ti(r,e)}let g=xs||Sd;t.classList.toggle("persona-pill-peek--visible",g)};if(me()){let e=mt.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Bd(!0,"user")};e.addEventListener("pointerdown",t),Da.push(()=>{e.removeEventListener("pointerdown",t)})}let t=()=>{Sd||(Sd=!0,Ed())},r=()=>{Sd&&(Sd=!1,Ed())};ut.addEventListener("pointerenter",t),ut.addEventListener("pointerleave",r),Da.push(()=>{ut.removeEventListener("pointerenter",t),ut.removeEventListener("pointerleave",r)}),ht&&(ht.addEventListener("pointerenter",t),ht.addEventListener("pointerleave",r),Da.push(()=>{ht.removeEventListener("pointerenter",t),ht.removeEventListener("pointerleave",r)}))}let Ld=()=>{if(fe&&ld(),!ge())return;if(me()){let e=(l.launcher?.composerBar??{}).expandedSize??"anchored",t=fe?"expanded":"collapsed";return pt.dataset.state=t,pt.dataset.expandedSize=e,ht&&(ht.dataset.state=t,ht.dataset.expandedSize=e),pt.style.removeProperty("display"),pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),(e=>{let t=l.launcher?.composerBar??{},r=t.expandedSize??"anchored",n=t.bottomOffset??"16px",o=t.collapsedMaxWidth,a=t.expandedMaxWidth??"880px",s=t.expandedTopOffset??"5vh",i=t.modalMaxWidth??"880px",d=t.modalMaxHeight??"min(90vh, 800px)",c="calc(100vw - 32px)";_r();let p=pt.style;if(p.left="",p.right="",p.top="",p.bottom="",p.transform="",p.width="",p.maxWidth="",p.height="",p.maxHeight="",ht){let e=ht.style;e.bottom=n,e.width=o??""}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(${n} + var(--persona-pill-area-height, var(--persona-measured-pill-area-height, 80px)))`,p.top=s,p.width=a,p.maxWidth=c))})(fe),gt.style.display=fe?"flex":"none",Ao(),fe?(fd(),xd()):(vd(),Cd()),void Ed()}let t=ll(l),r=e.ownerDocument.defaultView??window,n=l.launcher?.mobileBreakpoint??640,o=l.launcher?.mobileFullscreen??!0,a=r.innerWidth<=n,s=o&&a&&ne,i=cl(l).reveal;fe?(pt.style.removeProperty("display"),pt.style.display=t?"flex":"",pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-95","persona-opacity-0"),ut.classList.add("persona-scale-100","persona-opacity-100"),Yu?(Yu.setPanelOpen(!0),Yu.element.style.display="none"):Xu&&(Xu.style.display="none")):(t?!t||"overlay"!==i&&"push"!==i||s?(pt.style.setProperty("display","none","important"),pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(pt.style.removeProperty("display"),pt.style.display="flex",pt.classList.remove("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(pt.style.display="",pt.classList.add("persona-pointer-events-none","persona-opacity-0"),ut.classList.remove("persona-scale-100","persona-opacity-100"),ut.classList.add("persona-scale-95","persona-opacity-0")),Yu?(Yu.setPanelOpen(!1),Yu.element.style.display=t?"none":""):Xu&&(Xu.style.display=t?"none":""))},Bd=(t,r="user")=>{if(!ge()||fe===t)return;let n=fe;fe=t,Ld();let o=(()=>{let t=l.launcher?.sidebarMode??!1,r=e.ownerDocument.defaultView??window,n=l.launcher?.mobileFullscreen??!0,o=l.launcher?.mobileBreakpoint??640,a=r.innerWidth<=o,s=ll(l)&&n&&a,i=me()&&"fullscreen"===(l.launcher?.composerBar?.expandedSize??"fullscreen");return t||n&&a&&ne||s||i})();if(fe&&o){if(!Oa){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&(Oa=ol(r,l.launcher?.zIndex??1e5))}Fa||=il(e.ownerDocument)}else fe||(Oa?.(),Oa=null,Fa?.(),Fa=null);fe&&(rh(),Dl()||("follow"===br()?Il(!0):Pl()));let a={open:fe,source:r,timestamp:Date.now()};fe&&!n?F.emit("widget:opened",a):!fe&&n&&F.emit("widget:closed",a),F.emit("widget:state",{open:fe,launcherEnabled:ne,voiceActive:vi.active,streaming:es.isStreaming()})},Rd={inputDisabled:!1,sendDisabled:!1},$d=()=>Rd.inputDisabled,Wd=()=>_t(l.voiceRecognition?.provider)&&!!es&&(es.isBargeInActive()||["listening","processing","speaking"].includes(es.getVoiceStatus())),Hd=()=>Rd.inputDisabled||Rd.sendDisabled;function zd(){if(!kt)return;if("streaming"===Jr.getState().phase)return void(kt.disabled=!1);let e=!!Kr&&!Kr.isReady();kt.disabled=Hd()||e}function jd(){if(!sr)return;let e=Jr.getState(),t="when-text"===l.sendButton?.visibility&&"streaming"!==e.phase&&0===e.text.trim().length&&0===e.attachments.length;sr.toggleAttribute("data-persona-send-hidden",t)}function qd(){let e=Ma(l.composer?.inputDisabled),t=Ma(l.composer?.sendDisabled);Rd={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Jr.setInputDisabled(e.disabled),Jr.setSendDisabled(t.disabled);let r="streaming"===Jr.getState().phase,n=e.disabled,o=r||n;St&&(St instanceof HTMLTextAreaElement?St.disabled=n:St.setAttribute("contenteditable",n?"false":"true"),St.setAttribute("aria-disabled",n?"true":"false")),pr&&(pr.disabled=n),gr&&(gr.disabled=n);for(let e of Qr?.affordanceButtons??[])e.querySelectorAll("button").forEach(e=>{e.disabled=n});lr&&(lr.disabled=n||r&&!Wd()),Za.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement||e.setAttribute("aria-disabled",o?"true":"false")}),e.buttons.forEach(e=>{e.disabled=o})}),cc.forEach(e=>{e.toggleAttribute("data-disabled",o),e instanceof HTMLButtonElement?e.disabled=o:e.setAttribute("aria-disabled",o?"true":"false"),e.querySelectorAll("button").forEach(e=>{e.disabled=o})}),tr.dataset.personaComposerStreaming=r?"true":"false",tr.dataset.personaComposerInputDisabled=n?"true":"false",tr.dataset.personaComposerSendDisabled=Hd()?"true":"false",tr.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=r)}),zd(),function(){let e=(Rd.inputDisabled?Rd.inputReason:void 0)??(Rd.sendDisabled?Rd.sendReason:void 0);if(me()){let t=At??tr;e?t.setAttribute("title",e):t.removeAttribute("title"),tr.toggleAttribute(up,!!e)}else if(e)Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.setAttribute(up,""),Mt.removeAttribute(hp),Mt.textContent=e,ur(Mt,l.statusIndicator??{},"idle");else if(Mt.hasAttribute(up)&&(Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),Mt.removeAttribute(up),I)){let e=es.getStatus();lt(Mt,it(e),l.statusIndicator??{},e)}}()}let Kd=e=>{Jr.setStreaming(e),ir(e?"stop":"send"),qd()},Qd=()=>{e.hasAttribute("data-persona-preparing")?u.ready.then(Qd,()=>{}):vi.active||St&&St.focus()};F.on("widget:opened",()=>{l.autoFocusInput&&setTimeout(()=>Qd(),200)});let Jd=null,Gd=!1,Yd=!It.hidden,Xd=null,Zd=!U,ec=null;Da.push(()=>{ec?.cancel(),ec=null});let tc,rc,nc=t=>{let r=pd(t);if(r===Dr)return;Dr=r,e.setAttribute("data-persona-conversation-state",r);let n=Fr();Vr(),Zd&&(ec?.cancel(),ec=sd(tr,"active"===r?n:Fr(),"active"===r?"drop":"rise","centered"===Wr().layout?320:260)),Ql()},oc=null,ac=null,sc=null,ic=!1,lc=e=>{let t=Wr(),r=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??"bottom"}|${t.align??""}|${t.iconPlacement}|${t.kicker??""}|${t.title}|${t.subtitle}`;(r!==oc||t.icon!==tc)&&(oc=r,tc=t.icon,Yl({host:It,iconHolder:Bt,kicker:Pt,title:Nt,subtitle:$t,starterSuggestions:wt},t));let n=void 0===t.message?null:`${l.layout?.messages?.layout??"bubble"}|${t.message}`;n!==ac&&(ac=n,nd(Rt,t.message,l));let o=e??(es?es.getMessages():l.initialMessages);nc(o);let a=Gd,s=!a&&ud(t,o),i=s!==Yd;if(Yd=s,sc)return Xd?.cancel(),Xd=null,a!==ic&&(ic=a,a?rd(ft,It,null):td(ft,It,sc)),void Gl(ft,It,!a);if(i&&!s&&!a&&"on-first-message"===t.dismiss&&Zd)return void(Xd=ad(It,e=>{Xd===e&&(Xd=null),!Yd&&!sc&&(Gl(ft,It,!1),Ql()),e?.cancel()}));if(Xd){if(!s&&!a)return;Xd.cancel(),Xd=null}let d=!It.hidden;Gl(ft,It,s),!s&&d&&Ql()},dc=[],cc=[],pc=!1,uc=null,hc=()=>{cc.length=0;let e=dc.splice(0,dc.length);for(let t of e)try{t()}catch(e){console.warn("[persona] renderWelcome cleanup threw",e)}};Da.push(hc);let mc=(e,t)=>{let r=hl(e,t);if(!r)return!0===l.debug&&console.warn("[persona] renderStarter received a suggestion with no label"),st("span");let n=l.suggestions?.starters,o=gl({item:{...r,behavior:r.behavior??n?.behavior??"send"},index:t,surface:"starter",source:"config",variant:n?.variant??"card",streaming:!!I&&es.isStreaming(),config:l,plugins:S,chipsConfig:l.suggestionChipsConfig,session:es,getTextarea:()=>St,eventTarget:It,submitPrompt:Xp});return cc.push(o),o},fc=()=>{if(pc)return;pc=!0;let e=Wr();uc=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`,rc=e.icon;try{hc(),rd(ft,It,sc),sc=null,ic=!1;let t=es?es.getMessages():l.initialMessages,r=ud(e,t),n=0,o=null;for(let t of S)if(t.renderWelcome&&(o=t.renderWelcome({config:e,variant:e.variant,visible:r,defaultRenderer:()=>It,sendMessage:e=>{if(!es||es.isStreaming())return;let t=e.trim();t&&es.sendMessage(t)},requestRender:()=>fc(),renderStarter:e=>mc(e,n++),storage:T(t.id),onCleanup:e=>{dc.push(e)}}),o))break;o&&o!==It&&(sc=o,td(ft,It,o))}finally{pc=!1}lc()},bc=()=>{lc(),Mn||(St.placeholder=function(e,t){if(t?.length&&0!==e.length)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}(Jr.getState().activeModeIds,l.composer?.modes)??l.copy?.inputPlaceholder??"How can I help...",!l.sendButton?.useIcon&&!es?.isStreaming()&&(kt.textContent=l.copy?.sendButtonLabel??"Send")),St.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',St.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},yc=!!l.setStoredConversationId,vc=e=>Z(t=>{let r={...t};return delete r[e],r}),wc=e=>{let t=_[e];return"string"==typeof t?t:null},kc=()=>{let e=_.durableResume;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.executionId&&t.executionId.length>0&&"string"==typeof t.after&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};l.clientToken&&(l={...l,getStoredSessionId:()=>wc("sessionId"),setStoredSessionId:e=>{Z(t=>({...t,sessionId:e}))},clearStoredSessionId:l.clearStoredSessionId??(()=>vc("sessionId")),getStoredConversationId:l.getStoredConversationId??(()=>wc("conversationId")),setStoredConversationId:l.setStoredConversationId??(e=>{Z(t=>({...t,conversationId:e}))}),clearStoredConversationId:l.clearStoredConversationId??(()=>vc("conversationId"))});let Ac=()=>l.clientToken??null,Mc=e=>((e,t,r)=>{let n="",o="",a="",s=!1,i=!1,l=0,d=null,c=null,p=new Set,u=()=>{if(r||s)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return s=!0,null}},h=()=>{let e=u();if(!e)return d;try{return e.getItem(n)}catch{return s=!0,d}},m=(e,t)=>{if(i||e===d)return;let r=d;d=e,l+=1;let n={previousToken:r,token:e,source:t,revision:l};for(let e of p)e(n)},g=e=>{i||(null===e.key||e.key===n)&&m(null===e.key?null:e.newValue??null,"external")},f=(async()=>{let s=await(async(e,t)=>{let r=await Qc(e);return{storageKey:`${t}visitor:${r}`,leaseKey:`${t}visitor-init-lock:${r}`,lockName:`persona-visitor-init:${await Qc(`${e}\0${t}`)}`}})(e,t);n=s.storageKey,o=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(o);if(!t)return null;let r=JSON.parse(t);return"number"==typeof r?.expiresAt&&"string"==typeof r?.ownerNonce?r:null}catch{return null}},v=e=>{let t=u();if(t)try{y()?.ownerNonce===e&&t.removeItem(o)}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(n,e);function n(){clearTimeout(r),w.delete(n),window.removeEventListener("storage",a),t()}function a(e){(null===e.key||e.key===o)&&n()}w.add(n),window.addEventListener("storage",a)});return{ready:f,get:async()=>(await f,m(h(),"external"),d),async set(e){await f;let t=u();if(t)try{t.setItem(n,e)}catch{s=!0}m(e,"local")},async clear(){await f;let e=u();if(e)try{e.removeItem(n)}catch{s=!0}m(null,"local")},revision:()=>l,subscribe:e=>(p.add(e),()=>{p.delete(e)}),async withFirstInitLock(e){await f;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):u()?(async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=Date.now()+15e3;for(;!i&&Date.now()<r;){let r=u();if(!r)break;let n=Date.now(),a=y();if(a&&a.expiresAt>n&&a.ownerNonce!==t)await C(Math.min(a.expiresAt-n,500));else{try{r.setItem(o,JSON.stringify({ownerNonce:t,expiresAt:n+1e4}))}catch{s=!0;break}if(await 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:(n,o,a)=>n===e&&o===t&&a===r,destroy(){i=!0,p.clear(),typeof window<"u"&&window.removeEventListener("storage",g),c&&v(c);for(let e of[...w])e()}}})(e,Be(),!1===l.persistState),Tc=Ac(),Ec=Tc?Mc(Tc):null,Lc={...Ec?{visitorStore:Ec}:{},historyBootstrapReady:!0!==l.features?.history?.enabled||ap()?V:Promise.all([V,Q]).then(()=>{}),getStoredMessageCursor:()=>wc("historyMessageCursor"),setStoredMessageCursor:e=>{null===e?vc("historyMessageCursor"):Z(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:()=>{let e=_.pendingDisplayProjections;if(!e||"object"!=typeof e)return null;let t=e;return"string"==typeof t.conversationId&&Array.isArray(t.messageIds)?{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>"string"==typeof e)}:null},setPendingDisplayProjections:e=>{e?Z(t=>({...t,pendingDisplayProjections:e})):vc("pendingDisplayProjections")},getStoredResumableHandle:kc,setStoredResumableHandle:e=>{e?Z(t=>({...t,durableResume:e})):vc("durableResume")},shouldResumeDurableConversation:()=>j&&null!==kc(),...yc?{}:{getStoredConversationRevision:()=>wc("conversationRevision"),setStoredConversationRevision:e=>{null===e?vc("conversationRevision"):Z(t=>({...t,conversationRevision:e}))}}};if(j){let t=l.onExecutionState,r=e.ownerDocument.defaultView,n=!1,o=()=>n=!0,a=()=>n=!1;r?.addEventListener("pagehide",o),r?.addEventListener("pageshow",a),Da.push(()=>{r?.removeEventListener("pagehide",o),r?.removeEventListener("pageshow",a)}),l={...l,reconnectStream:l.reconnectStream??(e=>es.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!n)&&Lc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let Bc=null,Rc=e=>"user"===e.role||"approval"===e.variant||!0===e.agentMetadata?.awaitingLocalTool||vn(e),Pc=null,Nc=null,$c=null,Wc=null,Fc=e=>{let t,r;!e.length&&l.future?.v5Defaults&&(rs=null),Pc=e;for(let n=e.length-1;n>=0;--n){let o=e[n];if(!t&&"user"===o.role&&(t=o),!r&&"assistant"===o.role&&(r=o),t&&r)break}cd(vt,e,Ae),Et()?.updateInlineArtifactBlocks(vt,Eo.artifacts,{suppressTransition:xs}),Bc??=setInterval(()=>{let e=vt.querySelectorAll("[data-tool-elapsed]");if(0===e.length)return clearInterval(Bc),void(Bc=null);let t=Date.now();e.forEach(e=>{m?.updateActivityElapsed(e,t)})},100),lc(e),bs(e),Il(!xs),(e=>{let t=new Map;e.forEach(e=>{let r=pi.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!r&&"assistant"===e.role&&(F.emit("assistant:message",e),!Ys&&("anchor-top"!==br()||xr())&&vl()&&(Ks+=1,yl(),Sl(),Nr(1===Ks?"1 new message below.":`${Ks} new messages below.`))),"assistant"===e.role&&(r?.streaming||As.has(e.id))&&!1===e.streaming&&F.emit("assistant:complete",e),"approval"===e.variant&&e.approval&&(r?"pending"!==e.approval.status&&F.emit("approval:resolved",{approval:e.approval,decision:e.approval.status}):F.emit("approval:requested",{approval:e.approval,message:e}))}),pi.clear(),t.forEach((e,t)=>{pi.set(t,e)}),As.clear()})(e),Sl(),ze?.update(),0===e.length&&(jl(),Zs=!0,ei=!1,ti=null,ri=!1),!Gs||Ys?(Gs=!0,Xs=t?.id??null,oi=r?.id??null):t&&t.id!==Xs?(Xs=t.id,(e=>{let t=br();"follow"===t?(Ml(),Il(!0)):"anchor-top"===t&&(Zs=!1,ei=!0,ri=!1,ti=e,Kl(e))})(t.id)):r&&r.id!==oi&&"anchor-top"===br()&&(ei?Zs=!1:(Zs=!0,jl(),Ml(),Il(!0))),r&&(oi=r.id),(e=>{if("anchor-top"!==br()||!ei||ri||$l())return;let t=null===Xs;for(let r of e)if(t){if(Kt(r)){if(r.id===ti||!Xl(r.id))return;return ti=r.id,void Kl(r.id)}}else r.id===Xs&&(t=!0)})(e);let n=vi.lastUserMessageId;t&&t.id!==n&&(vi.lastUserMessageId=t.id,F.emit("user:message",t)),vi.lastUserMessageWasVoice=!!t?.viaVoice,(e=>{if(!j)return ji(e);Wc=e,queueMicrotask(()=>{Wc===e&&(Wc=null,ji(Nc??e))})})(e),Ed(),F.emit("messages:changed",e)},jc=()=>{null!==$c&&(cancelAnimationFrame($c),$c=null);let e=Nc;Nc=null,e&&Fc(e)},_c=()=>{null!==$c&&cancelAnimationFrame($c),$c=null,Nc=null};es=new c(l,{onRunStarted:e=>F.emit("run:started",e),onRunFinished(e){jc(),l.turnActivity?.enabled&&cd(vt,es.getMessages(),Ae),F.emit("run:finished",e)},onMessagesChanged(e){(e=>{if(0===e.length)return _c(),void Fc(e);let t=Nc??Pc;xs&&t&&((e,t)=>{if(t.length<e.length)return!1;for(let r=0;r<t.length;r+=1){let n=t[r];if(n!==e[r]){if(Rc(n))return!1;"assistant"===n.role&&n.streaming&&As.add(n.id)}}return!0})(t,e)?(Nc=e,null===$c&&($c=requestAnimationFrame(()=>{$c=null;let e=Nc;Nc=null,e&&Fc(e)}))):(jc(),Fc(e))})(e)},onStatusChanged(e){let t=l.statusIndicator??{};lt(Mt,(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),Sl(),ze?.update(),nt()},onStreamingChanged(e){e||(0===es?.getMessages().length?_c():jc()),xs=e,e?ys():l.future?.v5Defaults&&bs(),Kd(e),nt(),es&&cd(vt,es.getMessages(),Ae),e||(Il(!0),(()=>{if(!Qs||Qs.spacerHeight<=0||Qs.pending)return;let e=zl(Qs.spacerHeight),t=Math.max(0,Math.round(ft.scrollTop)+ft.clientHeight-e+24);t<Qs.spacerHeight&&(Ol(t),Sl())})(),ms=!0,es&&gs(es.getMessages(),jn(l))),Sl(),ze?.update(),Nr(e?"Responding…":"Response complete."),Ed()},onVoiceStatusChanged(e){if(F.emit("voice:status",{status:e,timestamp:Date.now()}),"disconnected"!==e&&!_t(l.voiceRecognition?.provider))return;let t=es.getVoiceNotice();switch(t&&Qp(t,1e4),e){case"listening":if(!ui){let e=es.getVoiceDisclosure();e&&(ui=!0,me()?(mi=St.placeholder,St.placeholder=e,Nr(e)):Qp(e,1e4))}Pu(),Lu();break;case"processing":Pu(),Bu();break;case"speaking":Pu(),Ru();break;default:"idle"===e&&es.isBargeInActive()?(Pu(),Lu(),lr?.setAttribute("aria-label","End voice session")):(vi.active=!1,ui=!1,null!==mi&&(St.placeholder=mi,mi=null),Pu(),Mi("system"),Ai||Li())}},onArtifactsState(e){Eo=e,0===e.artifacts.length&&(Do=!1),Et()?.updateInlineArtifactBlocks(vt,e.artifacts,{suppressTransition:xs}),Ta(),ji()},onHistoryStateChanged(e){tt(e)},onHistoryNotice(e){rt(e)},onHistoryScopeInvalidated(){Tp(),Jc?.clearConversationOpenPending()},onConversationExecutionState(e){F.emit("conversation:executionState",e)},onReconnect(e){let{executionId:t,lastEventId:r}=e.handle;"paused"===e.phase?F.emit("stream:paused",{executionId:t,after:r}):"resuming"===e.phase?F.emit("stream:resuming",{executionId:t,after:r,attempt:e.attempt??1}):F.emit("stream:resumed",{executionId:t,after:r})}},Lc),zo.current=es,Da.push(()=>es.cancel()),Da.push(()=>{es.destroy(),Ec?.destroy(),Ec=null});let Uc=null;if(es.onReadAloudChange((e,t)=>{go=e,fo=t,wo();let r=e??Uc;e&&(Uc=e);let n=r?es.getMessages().find(e=>e.id===r)??null:null;F.emit("message:read-aloud",{messageId:r,message:n,state:t,timestamp:Date.now()}),"idle"===t&&(Uc=null)}),I=!0,Gs=!0,!0===l.voiceRecognition?.enabled&&Ut(l))try{es.setupVoice()}catch(e){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",e)}let Jc=null,Gc=null,Yc=!1,Zc=es.getHistoryState(),ep=()=>!0===l.features?.history?.enabled,tp=e=>{e&&(Br.textContent="",Br.textContent=e)},rp=()=>{M.forEach(e=>e()),M=[];let t=Jc,r=t?.railCollapseShortcut();t&&r&&M.push(A.register({id:"history-rail-collapse",combo:r.combo,scope:"page"===l.features?.history?.rail?.collapseShortcutScope?"page":"widget",when:()=>Ye&&"rail"===Xe&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of l.layout?.header?.trailingActions??[])t.shortcut&&M.push(A.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 S)for(let t of e.shortcuts??[])M.push(A.register({...t,id:`${e.id}:${t.id}`}))};rp();let np=null,ip=!1,lp=()=>{if(!Ft)return;let e="conversation"===l.layout?.header?.titleSource,t=e&&np?.trim()||null;Ft.textContent=t??l.launcher?.title??"Chat Assistant";let r=Ft.closest(".persona-combo-btn");if(!r)return;let n=!e||null!==es.getActiveConversationId();r.setAttribute("data-persona-menu-locked",n?"false":"true"),r.setAttribute("aria-haspopup",n?"true":"false"),n||r.setAttribute("aria-expanded","false"),r.style.cursor=n?"pointer":"default";let o=r.querySelector("svg");o&&(o.style.display=n?"":"none")};lp(),gt.addEventListener("persona:title-menu-builtin",e=>{let t=e.detail?.actionId,r=es.getActiveConversationId();r&&("delete"===t?Rp(e=>e.requestDeleteConversation(r)):"star"===t&&es.canUpdateConversations()&&Rp(e=>e.updateHistoryConversation(r,{starred:!ip})).catch(()=>{}))});let xp=new Map,Cp=(e=es.getActiveConversationId(),t=Jc?.historyOperationScope()??l.features?.history?.scope??(l.getIdentityProof?"verified-user":"browser"))=>JSON.stringify([t,e]),Sp=null,kp=0,Ap=()=>{let e=ft.getBoundingClientRect().top,t=ft.clientHeight>0?Array.from(vt.querySelectorAll("[data-message-id]")).find(t=>t.getBoundingClientRect().bottom>e):void 0;return{top:ft.scrollTop,anchorId:t?.dataset.messageId,anchorOffset:t?t.getBoundingClientRect().top-e:0,following:Fs.isFollowing(),followFallback:Zs,anchored:ei,anchoredId:ti,readerEngaged:ri,anchor:Qs?{...Qs}:null,unread:Ks}},Mp=e=>{Zs=e.followFallback,ei=e.anchored,ti=e.anchoredId,ri=e.readerEngaged,Qs=e.anchor?{...e.anchor,pending:0}:null,Ol(e.anchor?.spacerHeight??0),e.following?Fs.resume():Fs.pause(),Ks=e.unread;let t=Array.from(vt.querySelectorAll("[data-message-id]")).find(t=>t.dataset.messageId===e.anchorId);qs=!0,e.following&&yr()?ft.scrollTop=Qt(ft):t?ft.scrollTop+=t.getBoundingClientRect().top-ft.getBoundingClientRect().top-e.anchorOffset:ft.scrollTop=e.top,qs=!1,zs=ft.scrollTop,oh=Qt(ft),yl(),Na(),Sl()},Ip=(e=!1,t=!0)=>{let r=e?void 0:xp.get(Cp());Qr?.clear(),Kr?.setPreviewsContainer(null),Kr=r?.attachments??(l.attachments?.enabled?tn():null),Kr?.updateConfig(Zr()),Kr?.remountPreviews(fr),rn(Kr?.getAttachments()??[]);let n=r?.draft,o=Qr?.getInlineInput();r?.document&&o?.setDocument?o.setDocument(r.document):o?o.setValueWithCaret(n?.text??"",(n?.text??"").length):St.value=n?.text??"",Qr?.restoreDraft(r?.mentions??[]),Gr(),Yr(),Jr.setSelectedModelId(n?l.composer?.models?.some(e=>e.id===n.selectedModelId)?n.selectedModelId:void 0:l.composer?.selectedModelId),dn?.repaint(),sn(fa(n?.activeModeIds??l.composer?.defaultActiveModeIds??[],nn())),un(n?.quote),fn(r?.pending),nu(),jl(),pl(),Jc?.cancelConversationOpenTakeover(),Jd&&(Jd.hidden=!0),Gd=!1,vt.style.removeProperty("display"),r?Mp(r.reading):(Ml(),Dl()||Pl()),t&&(qi=Ui()?ma({...Jr.getState(),contentSegments:jp()}):void 0),Vi.cancel(),t&&ji(),Sp={key:Cp(),reading:r?.reading??Ap()}},Tp=(e,t=!0,r=!0)=>{for(let[t,r]of xp)(void 0===e||JSON.parse(t)[1]===e)&&(r.attachments?.destroy({release:!0}),Kr===r.attachments&&(Kr=null),xp.delete(t));(void 0===e||e===es.getActiveConversationId())&&(++kp,_i=null,Up?.abort(),Up=null,mu(),Kr?.destroy({release:!0}),Kr=null,t&&Ip(!0,r),Sp=null)};tt=e=>{Zc=e,Jc?.historySurface?.view.setNewConversationRequired("new_conversation_required"===e.recovery),Kd(e.sendBlocked||xs),Jc?.syncEarlierMessagesPill()},rt=e=>{("history_continuity_reset"===e.code||"conversation_deleted_recovered"===e.code)&&(Tp(),Jc?.clearConversationOpenPending(),ks.clear(),jl(),Ml()),tp(e.message),Jc?.historySurface?.view.refresh()};let Ep={getBubbleClasses:ql,parseCombo:xi,formatCombo:Si,ariaCombo:ki,usesSessionVoiceForConfig:Ut,applyBubbleGeometry:Ul,resolveThemeDefaults:Us,composerStore:Jr,get attachmentManager(){return Kr},set attachmentManager(e){Kr=e},get composerConversationGeneration(){return kp},set composerConversationGeneration(e){kp=e},get submissionAbort(){return Up},set submissionAbort(e){Up=e},persistState:ji,applyMessageRowLayout:Zl,SessionHistoryError:d,instanceId:o,discardConversationContinuity:Tp,clearPersistedDraft:tl,saveConversationContinuity:()=>{mu(),Iu("system"),Ut(l)&&es.cleanupVoice(),++kp,Up?.abort(),Up=null,Jr.setPreparing(!1),Ds(),Yi();let e=Jr.getState(),t=Cp();xp.set(t,{draft:{text:e.text,mentionRefs:[...e.mentionRefs],contentSegments:jp(),quote:e.quote,selectedModelId:e.selectedModelId,activeModeIds:[...e.activeModeIds]},document:Qr?.getInlineInput()?.getDocument?.(),mentions:Qr?.captureDraft()??[],attachments:Kr,pending:e.pendingSubmission,reading:Sp?.key===t?Sp.reading:Ap()}),Vi.cancel()},restoreConversationContinuity:Ip,get pendingConversationReading(){return Sp},set pendingConversationReading(e){Sp=e},conversationStateKey:Cp,captureConversationReading:Ap,restoreConversationReading:Mp,get conversationPersistenceOwner(){return _i},set conversationPersistenceOwner(e){_i=e},setComposerDisabled:Kd,get actionManager(){return re},get activeConversationTitle(){return np},announceHistory:tp,get applyRailChrome(){return et},set applyRailChrome(e){et=e},get artifactSplitRoot(){return Go},get body(){return ft},get config(){return l},get container(){return gt},get conversationOpenPendingEl(){return Jd},set conversationOpenPendingEl(e){Jd=e},get conversationOpenTakeover(){return Gd},set conversationOpenTakeover(e){Gd=e},currentKeyPrefix:Be,destroyCallbacks:Da,eventBus:F,get footer(){return tr},get header(){return er},get historyChromeSync(){return nt},set historyChromeSync(e){nt=e},historyFeatureEnabled:ep,get historyInternals(){return Lc},set historyInternals(e){Lc=e},get historyPresentation(){return Xe},set historyPresentation(e){Xe=e},get historySessionState(){return Zc},get historyVisible(){return Ye},set historyVisible(e){Ye=e},get isStreaming(){return xs},jumpToBottomInstant:Pl,get lastAppliedMessages(){return Pc},set lastAppliedMessages(e){Pc=e},get launcherEnabled(){return ne},get launcherSurfaceInstance(){return Yu},maybeFocusInput:Qd,messageCache:ks,get messagesWrapper(){return vt},mount:e,get open(){return fe},panel:ut,panelElements:mt,panelSuggestions:Tr,panelSuggestionsFade:Er,get persistentMetadata(){return _},set persistentMetadata(e){_=e},plugins:S,get reapplyHistoryHostChrome(){return Ze},set reapplyHistoryHostChrome(e){Ze=e},repinAnchoredMessage:Ql,resetAnchorState:jl,restoreScrollPosition:Dl,resumeAutoScroll:Ml,runStorageMutation:zi,get session(){return es},setActiveConversationSummary:e=>{ip=!0===e?.starred,(e=>{e!==np&&(np=e,lp())})(e&&e.title.trim()||null),lp()},storageAdapter:z,get suppressScrollSend(){return Ys},set suppressScrollSend(e){Ys=e},syncScrollToBottomButton:Sl,scrollToBottomButton:Ar,updateWelcome:lc,getHistoryProviderFactory:sp,historyErrors:{HistoryClientError:n,HistoryProviderError:a},isDockedMountMode:ll,renderLucideIcon:Ee,loadHistoryView:Xc,createHeaderIconButton:xl,attachTooltip:Ja},Lp=e=>(!Jc&&!Yc&&(Jc=e.createHistoryShell(Ep),Jc.railCollapseShortcut()&&rp()),Jc),Bp=()=>{if(Jc)return Promise.resolve(Jc);let e=ap();return e?Promise.resolve(Lp(e)):(Gc??=op().then(Lp,e=>{throw Gc=null,e}),Gc)},Rp=e=>{let t=ap(),r=Jc??(t?Lp(t):null);return r?e(r):Bp().then(t=>{if(!t)throw Error("[AgentWidget] The widget was destroyed");return e(t)})},Pp=()=>{Jc?.syncHistoryPresentation()};Da.push(()=>{Yc=!0}),ep()&&Bp().catch(()=>{}).finally(K),l.clientToken&&(!0===l.features?.history?.enabled||"mount"===l.sessionInit)&&es.initClientSession().then(()=>{let e=Jc;if(e?.historyAvailable())return es.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Jc?.syncEarlierMessagesPill()}).catch(e=>{l.debug&&console.warn("[AgentWidget] Pre-init client session failed:",e)});let Np=()=>es.warmClientSession(),$p=e=>{let t=l.sessionInit??"input",r=En?.input??St,n=e.target;r&&("input"===e.type?("input"===t||"focus"===t)&&n===r&&e.inputType&&r.value.trim():"focus"===t&&("keyup"===e.type?n===r&&"Tab"===e.key:(En?.form??At)?.contains(n)))&&Np()},Wp=["input","pointerdown","keyup"];Wp.forEach(t=>e.addEventListener(t,$p));let Hp,Dp,Op=()=>{let e=Dp;Dp=void 0;try{"function"==typeof e&&e()}catch{}},Fp=()=>{let t=l.clientToken&&"function"==typeof l.sessionInit?l.sessionInit:void 0;if(t!==Hp){Op(),Hp=t;try{Dp=t?.({warm:Np,mount:e})}catch{}}};Fp(),Da.push(()=>{Wp.forEach(t=>e.removeEventListener(t,$p)),Op()}),(Te||l.onSSEEvent)&&es.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ke(e,t)});let zp=()=>{let e=l.resume??(j?Lc.getStoredResumableHandle?.():null);e&&"function"==typeof l.reconnectStream&&es.resumeFromHandle(e)};U?U.then(e=>{if(e){if(e.metadata&&(_=fp(e.metadata),re.syncFromMetadata()),e.messages?.length){Ys=!0;try{es.hydrateMessages(e.messages)}finally{Ys=!1}ld()}e.artifacts?.length&&es.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),el(e.draft)}}).catch(e=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",e)}).finally(()=>{Zd=!0,x(),zp()}):(el(C),zp());let jp=()=>{let e=St.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>"mention"===e.kind)?e.contentSegments:void 0},qp=!1,_p=0,Up=null,Vp=()=>{St.value="",St.style.height="auto",Gr(),nu()},Kp=null;function Qp(e,t=4e3){Nr(e),!me()&&Mt&&(Mt.hasAttribute(up)||(Mt.setAttribute(hp,""),Mt.setAttribute("role","status"),Mt.setAttribute("aria-live","polite"),Mt.textContent=e,ur(Mt,l.statusIndicator??{},"idle"),Kp&&clearTimeout(Kp),Kp=setTimeout(()=>{if(Kp=null,Mt?.hasAttribute(hp)&&(Mt.removeAttribute(hp),Mt.removeAttribute("role"),Mt.removeAttribute("aria-live"),I)){let e=es.getStatus();lt(Mt,it(e),l.statusIndicator??{},e)}},t)))}let Jp=(e={})=>{if(hu()||Jd)return;let t=kp,r=(e.overrideText??St?.value??"").trim();return e.resolveInlineCommand&&r?(Qr?.takeInlineCommand(r)??Promise.resolve(null)).then(n=>{if(t===kp)return Gp(e,r,n)}):Gp(e,r,null)},Gp=(e,t,r)=>{if("action"===r?.kind)return Vp(),Qr?.clear(),void Yr();let n="server"===r?.kind?r.mentions:null,o="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:o,hasAttachments:(Kr?.hasAttachments()??!1)||(a?.length??0)>0,attachmentsReady:Kr?.isReady()??!0,hasMentions:Qr?.hasMentions()??!1,hasServerMentions:!!n,inputDisabled:$d(),sendDisabled:Hd()}))return;let s=es.isStreaming()?mn():"block";if("defer-one"===s&&!e.pending)return Jr.getState().pendingSubmission?void Qp("One message is already queued. Edit or remove it first."):void function(e){let t=Jr.getState(),r=Kr?.hasAttachments()??!1,n=r?[...Kr.getContentParts()]:[];r&&e.sendText&&n.push(bo(e.sendText)),fn(Ia({text:e.sendText,contentParts:n.length?n:void 0,mentionRefs:[...Qr?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:jp(),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&&Vp(),r&&Kr.clearAttachments(),Qr?.clear(),Yr(),t.quote&&un(void 0),tl(),Qn.release(),Yn(),Nr("Message queued. It sends when the response finishes.")}({intent:e,sendText:o,serverMentions:n});let i={text:o,mentionRefs:[...Qr?.getMentionRefs()??[],...n?.refs??[]],contentSegments:"prompt"===r?.kind?void 0:jp(),options:{...Jr.getState().selectedModelId&&{selectedModelId:Jr.getState().selectedModelId},...Jr.getState().activeModeIds.length>0&&{activeModeIds:[...Jr.getState().activeModeIds]},...Jr.getState().quote&&{quote:{...Jr.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(!Kr?.hasAttachments())return;let e=[...Kr.getContentParts()];return i.text&&e.push(bo(i.text)),e};i.contentParts=d();let c=()=>{Ds(),me()&&(fe||(l.launcher?.composerBar?.expandOnSubmit??1)&&Bd(!0,"auto"));let t=Qr?.collectForSubmit()??null,r=((e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[r,n]=await Promise.allSettled([e.finalize(),t.finalize()]),o=[];return"fulfilled"===r.status?o.push(r.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",r.reason),"fulfilled"===n.status?o.push(n.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",n.reason),(e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:wp(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}))(o)}}:e:t)(t,n),o=d();!1!==e.consumeDraft&&Vp();let a={selectedModelId:i.options.selectedModelId,activeModeIds:i.options.activeModeIds},c="interrupt"===s;c&&es.cancel(),es.sendMessage(i.text,{contentParts:o,mentions:r??void 0,contentSegments:i.contentSegments,viaVoice:i.viaVoice,composerOptions:a,...i.options.quote&&{quote:i.options.quote},...c&&{interrupt:!0}}),Kr?.hasAttachments()&&Kr.clearAttachments(),t&&Qr?.clear(),Yr();let p=Jr.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&&sn(u),Jr.getState().quote&&un(void 0),tl(),Qn.release(),Yn()},p=l.composer?.onBeforeSend;if(!p)return void c();let u=new AbortController;Up=u;let h=kp,m=e=>{u.signal.aborted||h!==kp||(Up===u&&(Up=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=Ea(p,i,u.signal);if(g instanceof Promise)return Jr.setPreparing(!0),g.then(m).finally(()=>{h===kp&&Jr.setPreparing(!1)});m(g)};xo={regenerate:function(e){if(es.isStreaming())return;let t=Lo(es.getMessages(),e);t&&(Ds(),es.resubmitFrom(t,{reason:"retry"})&&Ql())},edit:function(e){if(!0!==l.messageActions?.showEdit)return;let t=es.getMessages().find(t=>t.id===e);t&&Bo(t)&&Ws!==e&&(Ds(),Ws=e,Hs=ha({messageId:e,initialText:t.content,onSave:t=>function(e,t){let r=Hs;Ws=null,Hs=null,r?.destroy(),ks.delete(e),es.resubmitFrom(e,{reason:"edit",replacement:{text:t,mentionRefs:[],options:{}}})?Ql():cd(vt,es.getMessages(),Ae)}(e,t),onCancel:()=>Ds()}),ks.delete(e),cd(vt,es.getMessages(),Ae),Hs.focus())},quote:e=>{let t=es.getMessages().find(t=>t.id===e)?.content?.trim();t&&(un({text:t,messageId:e}),St?.focus())}};let Yp=async e=>{if(hu())return void(l.voiceRecognition?.dictation?.showSend&&!Hd()&&gu(!0));if(qp)return;qp=!0;let t=++_p;try{await Jp({resolveInlineCommand:!0,...e})}finally{t===_p&&(qp=!1)}};function Xp(e){Hd()||(Vp(),Zp(e,{consumeDraft:!1}))}let Zp=(e,t)=>{if(qp)return;qp=!0;let r=++_p,n=()=>{r===_p&&(qp=!1)};try{let r=Jp({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},eu=e=>{e.preventDefault(),es.isStreaming()?(es.cancel(),De?.reset(),ze?.update()):qp||Yp()},tu={...Ei},ru=!1,nu=()=>{tu={...Ei}},ou=e=>{"Escape"!==e.key||e.isComposing||e.composedPath().includes(gt)&&(Up?(Up.abort(),Up=null,e.preventDefault(),e.stopImmediatePropagation()):es.isStreaming()&&(es.cancel(),De?.reset(),ze?.update(),nu(),e.preventDefault(),e.stopImmediatePropagation()))},au=null,su=null,iu=!1,lu=null,du=null,cu=0,pu=Object.freeze({phase:"idle",recordingId:0,transcript:"",interimTranscript:"",error:null,audioLevel:null}),uu=()=>!!l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&wu(),hu=()=>iu||["recording","processing"].includes(au?.getState().phase??"idle"),mu=()=>{if(++cu,iu=!1,du=null,lu){lu=null,su?.element.remove(),su=null;let{audioLevel:e,...t}=pu;return F.emit("dictation:state",{...t,instanceId:o,timestamp:Date.now()}),!0}return au?.cancel()??!1},gu=(e=!1)=>iu?(du=e||!0===du,!0):au?.finish(e)||e&&au?.send()||!1,fu=()=>{if($d()||es.isStreaming()||hu()||Wd())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&&!Au()||"custom"===t.type&&!t.custom)return!1;!fe&&ge()&&Bd(!0,"system"),lu&&mu();let r={text:St.value,logicalEnd:Qr?.getInlineInput()?.getLogicalText().length??null,readOnly:St.readOnly,contentEditable:St.getAttribute("contenteditable")};iu=!0,du=null;let n=++cu;return Je().then(a=>{n===cu&&(iu=!1,au??=a.createDictationSession({instanceId:o,getTextarea:()=>St,getFooter:()=>tr,getConfig:()=>l,plugins:S,getInlineInput:()=>Qr?.getInlineInput(),isInputDisabled:$d,isSendBlocked:Hd,syncText:Gr,onSend:()=>{Yp({viaVoice:!0})},rendererDeps:{renderLucideIcon:Ee,attachTooltip:Ja},onState:(e,t)=>{let{audioLevel:r,...n}=e;F.emit("dictation:state",{...n,instanceId:o,timestamp:Date.now()}),vi.active="recording"===e.phase,xu(t?"recording"===e.phase?"recording":"processing":"idle"),Mi("system")}}),es.stopSpeaking(),au.start(t,{autoSend:!wu(),pauseDuration:e?.pauseDuration},r),null!==du&&(au.finish(du),du=null))}).catch(e=>{if(n!==cu)return;iu=!1;let t=e instanceof Error?e.message:"Unable to load dictation.";lu=Object.freeze({...pu,recordingId:n,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",()=>{mu()}),r.append(a),su={element:r},tr.append(r);let{audioLevel:s,...i}=lu;F.emit("dictation:state",{...i,instanceId:o,timestamp:Date.now()})}),!0};Da.push(()=>{++cu,au?.destroy(),su?.destroy?.(),su?.element.remove()}),l.voiceRecognition?.dictation&&Je().catch(()=>{});let bu,yu=null,vu=!1,wu=()=>"review"===l.voiceRecognition?.completionBehavior;function xu(e){lr&&Cs(lr,l,e,es.getVoiceInterruptionMode()),tr?.setAttribute("data-persona-voice-state",e),"recording"===e?function(){Su=!0;let e=e=>{Su&&(Cu??=e.createVoiceLevelIndicator({targets:()=>[dr??lr?.parentElement,tr].filter(e=>!!e),sample:()=>{let e=au?.getState();return"recording"===e?.phase?{level:e.audioLevel,fallback:!1}:{level:I?es.getVoiceLevel():null,fallback:!0}}}),Cu.start())},t=Ge();t?e(t):Je().then(e,()=>{})}():ku()}let Cu,Su=!1;function ku(){Su=!1,Cu?.stop()}let Au=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Mu=(e="user")=>{if(vu||es.isStreaming())return;let t=Au();if(!t)return;yu=new t;let r=yu,n=l.voiceRecognition??{},o=n.pauseDuration??2e3;yu.continuous=n.provider?.browser?.continuous??!0,yu.interimResults=!0,yu.lang=n.provider?.browser?.language??"en-US";let a,s=St.value,i=(e,t)=>{let n=n=>{yu===r&&vu&&(a??=n.createBrowserRecognitionHandlers({textarea:St,initialText:s,pauseDuration:o,isActive:()=>yu===r&&vu,syncText:Gr,stop:Iu,review:wu,submit:()=>{Yp({viaVoice:!0})}}),bu=()=>a?.dispose(),a[e](t))},i=Ge();i?n(i):Je().then(n,()=>{yu===r&&Iu("system")})};r.onresult=e=>i("result",e),r.onerror=e=>i("error",e),r.onend=e=>i("end",e);try{yu.start(),vu=!0,vi.active=!0,"system"!==e&&(vi.manuallyDeactivated=!1),Mi(e),Li(),Yn(),lr&&(lr.classList.add("persona-voice-recording"),xu("recording"),lr.setAttribute("aria-label","Stop voice recognition"))}catch{Iu("system")}},Iu=(e="user")=>{if(vu){if(vu=!1,bu?.(),bu=void 0,yu){try{yu.stop()}catch{}yu=null}vi.active=!1,Mi(e),Ai||Li(),Yn(),lr&&(lr.classList.remove("persona-voice-recording"),xu("idle"),lr.setAttribute("aria-label",l.voiceRecognition?.tooltipText??"Start voice recognition"))}},Tu=null,Eu=e=>{let t=t=>{Tu??=t.createMicStateStyles({mic:()=>lr,config:()=>l,session:()=>es,setMicState:xu}),e(Tu)},r=qt();r?t(r):jt().then(t,()=>{})},Lu=()=>Eu(e=>e.recording()),Bu=()=>Eu(e=>e.processing()),Ru=()=>Eu(e=>e.speaking()),Pu=()=>Eu(e=>e.reset()),Nu=()=>{if(!$d())if(uu())"recording"===au?.getState().phase?au.finish():hu()||fu();else if(_t(l.voiceRecognition?.provider)){let e=es.getVoiceStatus(),t=es.getVoiceInterruptionMode();if("none"===t&&("processing"===e||"speaking"===e))return;if("cancel"===t&&("processing"===e||"speaking"===e))return void es.stopVoicePlayback();if(es.isBargeInActive())return es.stopVoicePlayback(),void es.deactivateBargeIn().then(()=>{vi.active=!1,vi.manuallyDeactivated=!0,Li(),Mi("user"),Pu()});es.toggleVoice().then(()=>{vi.active=Ci(),vi.manuallyDeactivated=!vi.active,Li(),Mi("user"),vi.active?Lu():Pu()})}else if(vu){let e=St.value.trim();vi.manuallyDeactivated=!0,Li(),Iu("user"),e&&!wu()&&Yp()}else vi.manuallyDeactivated=!1,Li(),Mu("user")};bn=Nu;let $u=()=>es.prewarmVoice(),Wu=()=>{let e=l.voiceRecognition;return!0===e?.enabled&&(e.prewarm??(!!l.clientToken&&"hover"))},Hu=e=>{"hover"===Wu()&&lr?.contains(e.target)&&$u()},Du=["pointerover","pointerdown","focusin"];Du.forEach(t=>e.addEventListener(t,Hu));let Ou,Fu,zu=null,ju=()=>{let e=Fu;Fu=void 0;try{"function"==typeof e&&e()}catch{}},qu=()=>{let t=Wu(),r="function"==typeof t&&lr?t:void 0,n=r?lr:null;if((r!==Ou||n!==zu)&&(ju(),Ou=r,zu=n,r&&n))try{Fu=r({warm:$u,micButton:n,mount:e})}catch{}};qu(),Da.push(()=>{Du.forEach(t=>e.removeEventListener(t,Hu)),ju()}),lr&&Da.push(()=>{_t(l.voiceRecognition?.provider)?(es.isVoiceActive()&&es.toggleVoice(),Pu()):Iu("system")});let _u=F.on("assistant:complete",()=>{let e=Jr.getState().pendingSubmission,t=kp,r=be;e&&setTimeout(()=>{ve(r)&&!es.isStreaming()&&t===kp&&Jr.getState().pendingSubmission===e&&function(){let e=Jr.getState().pendingSubmission;e&&(fn(void 0),Zp(e.text,{consumeDraft:!1,pending:e}))}()},0)});Da.push(_u);let Uu=F.on("assistant:complete",()=>{if(!wi||vi.active||vi.manuallyDeactivated||"assistant"===wi&&!vi.lastUserMessageWasVoice)return;let e=kp,t=be;setTimeout(()=>{ve(t)&&e===kp&&!vi.active&&!vi.manuallyDeactivated&&(_t(l.voiceRecognition?.provider)?es.toggleVoice().then(()=>{ve(t)&&e===kp&&(vi.active=es.isVoiceActive(),Mi("auto"),es.isVoiceActive()&&Lu())}):Mu("auto"))},600)});Da.push(Uu);let Vu=!1,Ku=e=>{e.persisted&&!Vu&&(Vu=!0,Ai=!0,we(),kp++,_p++,qp=!1,Up?.abort(),Up=null,Jr.setPreparing(!1),mu(),Iu("system"),es.cancel(),es.stopSpeaking(),es.cleanupVoice(),De?.reset(),ze?.update())},Qu=e=>{e.persisted&&Vu&&(Vu=!1,Ai=!1,!0===l.voiceRecognition?.enabled&&Ut(l)&&es.setupVoice())};window.addEventListener("pagehide",Ku),window.addEventListener("pageshow",Qu),Da.push(()=>{window.removeEventListener("pagehide",Ku),window.removeEventListener("pageshow",Qu)});let Ju=F.on("action:resubmit",()=>{xe()});Da.push(Ju);let Gu=()=>{Bd(!fe,"user")},Yu=null,Xu=null;if(ne&&!me()){let{instance:e,element:t}=Ad({config:l,plugins:S,onToggle:Gu});Yu=e,e||(Xu=t)}Yu?e.appendChild(Yu.element):Xu&&e.appendChild(Xu),Ld(),bs(),bc(),fc(),Kd(es.isStreaming()),Dl()||("follow"===br()?Il(!0):Pl()),(()=>{if(!1===l.voiceRecognition?.enabled||l.voiceRecognition?.dictation||"custom"===l.voiceRecognition?.provider?.type&&"review"===l.voiceRecognition.completionBehavior)return;let e=fp(_.voiceState),t=!!e.active,r=Number(e.timestamp??0);if(vi.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-r<3e4){let e=be;setTimeout(()=>{ve(e)&&(vi.active||(vi.manuallyDeactivated=!1,_t(l.voiceRecognition?.provider)?es.toggleVoice().then(()=>{ve(e)&&(vi.active=Ci(),Mi("restore"),vi.active?Lu():(Li(),Qp("Tap the mic to resume your voice call",1e4)))}):Mu("restore")))},_t(l.voiceRecognition?.provider)?0:1e3)}})(),se&&(!ne||me()?setTimeout(()=>Qd(),0):fe&&setTimeout(()=>Qd(),200));let Zu=null,eh=()=>{Zu&&(Zu.disconnect(),Zu.observe(tr),Zu.observe(gt),Zu.observe(It),Zu.observe(Tr))},th=$r(),rh=()=>{if(me())return jr(),void Ld();let t=ll(l),r=l.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,o=l.launcher?.mobileFullscreen??!0,a=l.launcher?.mobileBreakpoint??640,s=n.innerWidth<=a,i=o&&s&≠try{if(i)return Ao(),void(Mo=Ca());let e=!1;ue&&(ue=!1,Ao(),e=!0);let n=Ca();if(!e&&n!==Mo&&(Ao(),e=!0),Mo=n,e&&Xo(),!ne&&!t)return ut.style.height="",void(r||(pt.style.width=gd(l),ut.style.width="100%",ut.style.maxWidth="100%"));if(!r&&!t){let e=md(l);ut.style.width=e.width,ut.style.maxWidth=e.maxWidth}ia(),Wa()}finally{jr(),Vr();let t=$r();if(t!==th&&(th=t,lc(),bs()),Ld(),fe&&ne){let t=(e.ownerDocument.defaultView??window).innerWidth<=(l.launcher?.mobileBreakpoint??640),r=l.launcher?.sidebarMode??!1,n=l.launcher?.mobileFullscreen??!0,o=ll(l)&&n&&t,a=r||n&&t&&ne||o;if(a&&!Fa){let t=e.getRootNode(),r=t instanceof ShadowRoot?t.host:e.closest(".persona-host");r&&!Oa&&(Oa=ol(r,l.launcher?.zIndex??1e5)),Fa=il(e.ownerDocument)}else a||(Oa?.(),Oa=null,Fa?.(),Fa=null)}}};rh();let nh=e.ownerDocument.defaultView??window;if(nh.addEventListener("resize",rh),Da.push(()=>nh.removeEventListener("resize",rh)),typeof ResizeObserver<"u"){Zu=new ResizeObserver(()=>{Vr(),Sl()}),eh(),Da.push(()=>{Zu?.disconnect(),Zu=null});let e=new ResizeObserver(()=>{Pp()});e.observe(gt),Da.push(()=>e.disconnect())}nh.addEventListener("resize",Pp),Da.push(()=>nh.removeEventListener("resize",Pp)),zs=ft.scrollTop;let oh=Qt(ft),ah=()=>{Na();let e=ft.scrollTop,t=Qt(ft),r=t<oh;if(oh=t,Bl.interrupted||!yr())return zs=e,void Sl();let{action:n,nextLastScrollTop:o}=function(e){let{following:t,currentScrollTop:r,lastScrollTop:n,nearBottom:o,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:l=!0,resumeRequiresDownwardScroll:d=!1}=e,c=r-n;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:r}:!t&&o&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:r}:t&&i&&c<0||t&&l&&!o?{action:"pause",delta:c,nextLastScrollTop:r}:{action:"none",delta:c,nextLastScrollTop:r}}({following:Fs.isFollowing(),currentScrollTop:e,lastScrollTop:zs,nearBottom:Jt(ft,24),userScrollThreshold:4,isAutoScrolling:Bl.active||qs||_s||r,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});zs=o,"resume"!==n||$l()?"pause"===n?kl():Sl():Ml()};if(ft.addEventListener("scroll",ah,{passive:!0}),Da.push(()=>ft.removeEventListener("scroll",ah)),typeof ResizeObserver<"u"){let e=new ResizeObserver(()=>{(()=>{if(yr()){if(Sl(),!Fs.isFollowing()||Jt(ft,1))return;Il(!xs)}else{if(Qs&&Qs.initialSpacerHeight>0&&!Qs.pending){let e=ft.scrollHeight-Qs.spacerHeight,t=function(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}({initialSpacerHeight:Qs.initialSpacerHeight,contentHeightAtAnchor:Qs.contentHeightAtAnchor,currentContentHeight:e});t!==Qs.spacerHeight&&Ol(t)}Sl()}})(),Na(),Hr(vt)});e.observe(vt),e.observe(ft),Da.push(()=>e.disconnect())}let sh=()=>{yr()&&Fs.isFollowing()&&$l()&&kl()},ih=ft.ownerDocument;ih.addEventListener("selectionchange",sh),Da.push(()=>{ih.removeEventListener("selectionchange",sh)});let lh=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),dh=e=>{lh.has(e.key)&&(ni(),wr()&&yr()&&Fs.isFollowing()&&kl())},ch=e=>{e.target?.closest("a, button, [tabindex], input, textarea, select")&&(ni(),wr()&&yr()&&Fs.isFollowing()&&kl())};ft.addEventListener("keydown",dh),ft.addEventListener("focusin",ch),Da.push(()=>{ft.removeEventListener("keydown",dh),ft.removeEventListener("focusin",ch)});let ph=e=>{if(Bl.interruptedBy(e))return void ni();if(0!==e.deltaY&&ni(),!yr())return;let t=function(e){let{following:t,deltaY:r,nearBottom:n=!1,resumeWhenNearBottom:o=!1}=e;return t&&r<0?"pause":!t&&o&&r>0&&n?"resume":"none"}({following:Fs.isFollowing(),deltaY:e.deltaY,nearBottom:Jt(ft,24),resumeWhenNearBottom:!0});"pause"===t?kl():"resume"===t&&!$l()&&Ml()};ft.addEventListener("wheel",ph,{passive:!0}),ft.addEventListener("touchmove",ni,{passive:!0}),ft.addEventListener("pointerdown",ni,{passive:!0}),Da.push(()=>{ft.removeEventListener("touchmove",ni),ft.removeEventListener("pointerdown",ni)}),Da.push(()=>ft.removeEventListener("wheel",ph)),Ar.addEventListener("click",()=>{jl(),pl(),Fs.pause(),Bl.start(l),Sl()}),Da.push(()=>Bl.destroy()),Da.push(()=>kr.destroy()),Da.push(()=>{pl(),jl()});let uh=()=>{Dt&&(ts&&=(Dt.removeEventListener("click",ts),null),ge()?(Dt.style.display="",ts=()=>{Bd(!1,"user")},Dt.addEventListener("click",ts)):Dt.style.display="none")};uh(),(()=>{let{clearChatButton:e}=mt;e&&e.addEventListener("click",()=>{let e=Jc;if(e?.historyAvailable())return void e.startNewConversation({focusComposer:!0}).catch(e=>{l.debug&&console.warn("[AgentWidget] New conversation failed:",e)});es.clearMessages(),l.layout?.topFade&&(ft.scrollTop=0),ft.removeAttribute("data-persona-top-fade"),ks.clear(),Ml(),Nn(mt.composerOverlay);try{localStorage.removeItem(pp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==pp)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:o,timestamp:(new Date).toISOString()}});window.dispatchEvent(t),tl(),z?.clear&&zi(()=>z.clear(),"[AgentWidget] Failed to clear storage adapter:"),_={},re.syncFromMetadata(),Tp(es.getActiveConversationId(),!0,!1),Vp(),tl(),fn(void 0),un(void 0),Ds(),He?.clear(),De?.reset(),ze?.update()})})();let hh=[["keydown",e=>{if(St&&!$d()&&(e.isComposing||!Qr?.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===St.selectionStart&&0===St.selectionEnd,r=function(e){let{direction:t,history:r,currentValue:n,atStart:o,state:a}=e,s=-1!==a.index;if(0===r.length)return{handled:!1,state:a};if("up"===t){if(!s&&!o)return{handled:!1,state:a};if(!s){let e=r.length-1;return{handled:!0,value:r[e],state:{index:e,draft:n}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let e=a.index+1;return{handled:!0,value:r[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}({direction:"ArrowUp"===e.key?"up":"down",history:es.getMessages().filter(e=>"user"===e.role).map(e=>e.content??"").filter(e=>e.length>0),currentValue:St.value,atStart:t,state:tu});if(tu=r.state,r.handled)return e.preventDefault(),void(void 0!==r.value&&(e=>{if(!St)return;ru=!0,St.value=e,St.dispatchEvent(new Event("input",{bubbles:!0})),ru=!1;let t=St.value.length;St.setSelectionRange(t,t)})(r.value))}if(Sa(e,{submitKey:l.composer?.submitKey,insertNewlineOnTouchEnter:l.composer?.insertNewlineOnTouchEnter,coarsePointer:xa(St)}))if(es.isStreaming()){if(e.preventDefault(),"block"===mn()||qp||Hd())return;nu(),Yp()}else qp||Hd()?e.preventDefault():(nu(),e.preventDefault(),kt.click())}}],["input",e=>{ru||(ys(),e.isComposing||Qr?.handleInput(e.inputType??void 0),nu())}],["input",Gr],["input",Yr],["keyup",Yr],["paste",async e=>{if(!0!==l.attachments?.enabled||!Kr||$d())return;let t=function(e){if(!e)return[];let t=[],r=Array.from(e.items??[]);for(let e of r){if("file"!==e.kind||!e.type.startsWith("image/"))continue;let r=e.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let n=mp[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${n}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let r of Array.from(e.files??[]))r.type.startsWith("image/")&&t.push(r);return t}(e.clipboardData);0!==t.length&&(e.preventDefault(),await Kr.handleFiles(t))}],["focus",()=>Qr?.prefetch()]],mh=e=>{if(e)for(let[t,r]of hh)En?.addListener(e,t,r)},gh=()=>{En&&(En.addListener(En.form,"submit",eu),En.addListener(En.footer,"click",Yr),mh(St),lr&&En.addListener(lr,"click",Nu),qu())};gh();let fh=()=>{Qr?.onComposerSwap((e,t)=>{(e=>{if(e)for(let[t,r]of hh)En?.removeListener(e,t,r)})(t),St=e,En&&(En.input=e),mh(e),Ln(),qd(),Gr(),au?.refresh()})};fh();let bh=!1;function yh(){if(!bh){bh=!0;try{oo.detach(["footer-top","footer-bottom","composer-start","composer-end","composer-before-send"]);let e=St?.value??"",t=tr.ownerDocument??document,r=!!St&&t.activeElement===St;ku(),En?.destroy(),En=null,Qr?.destroy(),Qr=null;let n=null,o=()=>(n=me()?Hl({config:l}):Wl({config:l}),n.footer),a=In(o)??o();ct.replaceComposer(a),tr=ct.composer.footer,!1===l.layout?.showFooter&&(tr.style.display="none");let s=null!==n&&a===n.footer;Mn=!s,ir=s?n.setSendButtonMode:()=>{},An(tr),Bn(tr),$n(),Wn(),Hn(),fh(),Un(),Vn(),Kn(),gh();let i=Za.indexOf(Qa);if(Qa.destroy(),Qa=fl(Ct),i>=0&&(Za[i]=Qa),oo.remount(),St&&(St.value=e),Gr(),Yr(),bc(),bs(),Kd(es.isStreaming()),"transient"===l.statusIndicator?.mode&&!me()){let e=es.getStatus();lt(Mt,it(e),l.statusIndicator,e)}vi.active&&xu("recording"),au?.refresh(),Ao(),eh(),jr(),Yn(),jd(),r&&St?.focus()}finally{bh=!1}}}let vh=e.ownerDocument??document;vh.addEventListener("keydown",ou,!0);let wh=()=>{Yi()},xh=()=>{"hidden"===vh.visibilityState&&Yi()};typeof window<"u"&&(window.addEventListener("pagehide",wh),vh.addEventListener("visibilitychange",xh),Da.push(()=>{window.removeEventListener("pagehide",wh),vh.removeEventListener("visibilitychange",xh)}));let Ch="persona-attachment-drop-active",Sh=0,kh=()=>{Sh=0,gt.classList.remove(Ch)},Ah=()=>!0===l.attachments?.enabled&&null!==Kr&&!$d(),Mh=e=>{gp(e.dataTransfer)&&Ah()&&(Sh++,1===Sh&>.classList.add(Ch))},Ih=e=>{gp(e.dataTransfer)&&Ah()&&(Sh--,Sh<=0&&kh())},Th=e=>{gp(e.dataTransfer)&&Ah()&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},Eh=e=>{if(!gp(e.dataTransfer)||!Ah())return;e.preventDefault(),e.stopPropagation(),kh();let t=Array.from(e.dataTransfer.files??[]);0!==t.length&&Kr.handleFiles(t)};gt.addEventListener("dragenter",Mh,!0),gt.addEventListener("dragleave",Ih,!0),e.addEventListener("dragover",Th,!0),e.addEventListener("drop",Eh,!0);let Lh=e.ownerDocument,Bh=e=>{Ah()&&e.preventDefault()},Rh=e=>{Ah()&&e.preventDefault()};Lh.addEventListener("dragover",Bh),Lh.addEventListener("drop",Rh),Da.push(()=>{En?.destroy(),En=null,ku(),_n=!0,On?.destroy(),On=null,cn?.destroy(),cn=null,pn?.destroy(),pn=null,gn?.destroy(),gn=null,dn=null,Yi(),Vi.destroy(),Kp&&clearTimeout(Kp),Ds(),Up?.abort(),Up=null,Jc?.clearConversationOpenPending(),Tp(void 0,!1),Kr?.destroy(),Kr=null,Jr.destroy(),vh.removeEventListener("keydown",ou,!0),Qr?.destroy()}),Da.push(()=>{gt.removeEventListener("dragenter",Mh,!0),gt.removeEventListener("dragleave",Ih,!0),e.removeEventListener("dragover",Th,!0),e.removeEventListener("drop",Eh,!0),Lh.removeEventListener("dragover",Bh),Lh.removeEventListener("drop",Rh),kh()}),Da.push(()=>{es.cancel()}),Yu?Da.push(()=>{Yu?.destroy()}):Xu&&Da.push(()=>{Xu?.remove()}),r?.registerHostMove?.(t=>{let r=ft.scrollTop,n=yr()&&Fs.isFollowing(),o=ft.getBoundingClientRect().top,a=!n&&ft.clientHeight>0?Array.from(vt.querySelectorAll("[data-message-id]")).find(e=>e.getBoundingClientRect().bottom>o):void 0,s=a?a.getBoundingClientRect().top-o:0;pl(),t(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),rh(),et(),n?ft.scrollTop=Qt(ft):a?ft.scrollTop+=a.getBoundingClientRect().top-ft.getBoundingClientRect().top-s:ft.scrollTop=r,!n&&!ri&&Ql(),zs=ft.scrollTop,oh=Qt(ft),Na(),Sl(),e.dispatchEvent(new Event("persona:internal:host-moved"))});let Ph=e=>{!fe&&ge()&&Bd(!0,"system"),vt.querySelector(".persona-feedback-container")?.remove();let t=e();vt.appendChild(t),t.scrollIntoView({behavior:"smooth",block:"end"})},Nh=!1,$h=[],Wh=!1,Hh=()=>{let e=$h;$h=[],Wh=!0;try{for(let t of e)Dh.update(t)}finally{Wh=!1}},Dh={get ready(){return u.ready},get instanceId(){return o},update(t){if(!Wh){$h.push(t);let e=$h.reduce(Ic,{...l,features:w}),r=Vt(gc(e));if(r.length)return void u.prepare(r,Hh,Nh);if($h.length>1)return void u.prepare([],Hh,Nh);$h=[]}r?.diagnostics||Dc(h,t);let n=t.voiceRecognition;n&&(!1===n.enabled||n.dictation?.provider&&n.dictation.provider!==l.voiceRecognition?.dictation?.provider||n.provider?.custom&&n.provider.custom!==l.voiceRecognition?.provider?.custom)&&mu();let o=!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=l.features?.streamAnimation?.type,b=!0===l.features?.history?.enabled,y=l.features?.history?.provider,x=l.getIdentityProof,C=l.clientToken,k=l.contextMentions;l=Ic({...l,features:w},t),w=l.features,l=gc(l),v(),Ao(),Ta(),l.colorScheme!==i&&qa();let A=Sc.getForInstance(l.plugins);S.length=0,S.push(...A),rp(),ne=l.launcher?.enabled??!0,ae=l.launcher?.autoExpand??!1,Me=l.features?.showReasoning??!0,Ie=l.features?.showToolCalls??!0,Bl.cancel();let M=br();Le=l.features?.scrollBehavior??{},M!==br()&&(jl(),Ml()),ii(),Sl();let I=Te;if(Te=l.features?.showEventStreamToggle??!1,Te&&!I){if(He||(Qe(),es.setSSEEventCallback((e,t)=>{l.onSSEEvent?.(e,t),Ke(e,t)})),!kn&&er){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:"");kn=st("button",t),kn.style.width="28px",kn.style.height="28px",kn.style.color=Al.actionIconColor,kn.type="button",kn.setAttribute("aria-label","Event Stream"),kn.title="Event Stream";let r=oe(de,"18px","currentColor",1.5);r&&kn.appendChild(r);let n=mt.clearChatButtonWrapper,o=mt.closeButtonWrapper,a=n||o;a&&a.parentNode===er?er.insertBefore(kn,a):er.appendChild(kn),kn.addEventListener("click",()=>{je?Sn():Cn()})}}else!Te&&I&&(Sn(),ze?.destroy(),ze=null,kn&&=(kn.remove(),null),He?.clear(),Pe?.destroy(),He=null,Pe=null,De?.reset(),De=null,Oe=null);if(!1===l.launcher?.enabled&&Yu&&(Yu.destroy(),Yu=null),!1===l.launcher?.enabled&&Xu&&(Xu.remove(),Xu=null),!1!==l.launcher?.enabled&&!Yu&&!Xu){let{instance:t,element:r}=Ad({config:l,plugins:S,onToggle:Gu});Yu=t,t||(Xu=r),e.appendChild(r)}Yu&&Yu.update(l),lp(),zt&&void 0!==l.launcher?.subtitle&&(zt.textContent=l.launcher.subtitle);let T=l.layout?.header;if(T?.layout!==ce&&er){let e=T?Nl(l,T,{showClose:ge(),onClose:()=>Bd(!1,"user")}):Tl({config:l,showClose:ge(),onClose:()=>Bd(!1,"user")});ct.replaceHeader(e),er=ct.header.element,Ot=ct.header.iconHolder,Ft=ct.header.headerTitle,zt=ct.header.headerSubtitle,Dt=ct.header.closeButton,ce=T?.layout,lp()}else if(T){if(Ot&&(Ot.style.display=!1===T.showIcon?"none":""),Ft&&(Ft.style.display=!1===T.showTitle?"none":""),zt&&(zt.style.display=!1===T.showSubtitle?"none":""),Dt){let e=ge()&&!1!==T.showCloseButton;Dt.style.display=e?"":"none"}if(mt.clearChatButtonWrapper){let e=T.showClearChat;if(void 0!==e){mt.clearChatButtonWrapper.style.display=e?"":"none";let{closeButtonWrapper:t}=mt;t&&!t.classList.contains("persona-absolute")&&(e?t.classList.remove("persona-ml-auto"):t.classList.add("persona-ml-auto"))}}}let E=is(l);er&&(er.style.display=E?"":"none");let L=!1!==l.layout?.showFooter;tr&&(tr.style.display=L?"":"none"),jr(),Sl(),ne===le?ae!==ie&&Bd(ae,"auto"):ne?Bd(ae,"auto"):(fe=!0,Ld()),ie=ae,le=ne,rh(),uh();let B=JSON.stringify(l.messageActions)!==JSON.stringify(a),R=JSON.stringify(l.layout?.messages)!==JSON.stringify(s)||l.layout?.messages?.renderAssistantMessage!==s?.renderAssistantMessage||l.layout?.messages?.renderUserMessage!==s?.renderUserMessage,P=l.iterationDisplay!==d,N=(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);(!0===l.future?.v5Defaults!==o||"toolCall"in t||B||R||"loadingIndicator"in t||P||N||"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)&&es&&(Os++,cd(vt,es.getMessages(),Ae));let $=l.features?.streamAnimation?.type;if($!==f&&$&&"none"!==$){let t=Va($,l.features?.streamAnimation?.plugins);t&&Zi(t,e)}let W=l.launcher??{},H=W.headerIconHidden??!1,D=l.layout?.header?.showIcon,O=H||!1===D,z=W.headerIconName,j=W.headerIconSize??"40px";if(Ot){let e=er,t=e?.querySelector(".persona-flex-col");if(O)Ot.style.display="none",e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(Ot.style.display="",Ot.style.height=j,Ot.style.width=j,e&&t&&(e.contains(Ot)?Ot.nextSibling!==t&&(Ot.remove(),e.insertBefore(Ot,t)):e.insertBefore(Ot,t)),z){let e=parseFloat(j)||24,t=Ee(z,.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))`,Ot.replaceChildren(t)):Ot.textContent=W.agentIconText??"💬"}else if(W.iconUrl){let e=Ot.querySelector("img");if(e)e.src=W.iconUrl,e.style.height=j,e.style.width=j;else{let e=document.createElement("img");e.src=W.iconUrl,e.alt="",e.className="persona-rounded-xl persona-object-cover",e.style.height=j,e.style.width=j,Ot.replaceChildren(e)}}else{let e=Ot.querySelector("svg"),t=Ot.querySelector("img");(e||t)&&Ot.replaceChildren(),Ot.textContent=W.agentIconText??"💬"}let r=Ot.querySelector("img");r&&(r.style.height=j,r.style.width=j)}}let q=l.layout?.header?.showTitle,_=l.layout?.header?.showSubtitle;if(Ft&&(Ft.style.display=!1===q?"none":""),zt&&(zt.style.display=!1===_?"none":""),Dt){let e=ge()&&!1!==l.layout?.header?.showCloseButton;Dt.style.display=e?"":"none";let t=W.closeButtonPlacement??"inline",{closeButtonWrapper:r}=mt,n="top-right"===t,o=r?.classList.contains("persona-absolute");if(r&&n!==o)if(r.remove(),n){r.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let e=Jc?.railColumn??gt;e.style.position="relative",e.appendChild(r)}else{let e=W.clearChat?.placement??"inline";r.className=(W.clearChat?.enabled??1)&&"inline"===e?"":"persona-ml-auto",er&&er.appendChild(r)}Cl(Dt,l,"close",{buttonSize:me()?Dt.style.width:void 0,iconSize:me()?bd:void 0});let a=W.closeButtonTooltipText??"Close chat",s=W.closeButtonShowTooltip??!0;Dt.setAttribute("aria-label",a),r&&Ja({anchor:Dt,trigger:r,text:()=>Dt?.getAttribute("aria-label")??a,enabled:s})}let{clearChatButton:U,clearChatButtonWrapper:V}=mt;if(U){let e=W.clearChat??{},t=e.enabled??!0,r=l.layout?.header?.showClearChat,n=void 0===r?t:r,o=e.placement??"inline";if(V){V.style.display=n?"":"none";let{closeButtonWrapper:e}=mt;!me()&&e&&!e.classList.contains("persona-absolute")&&(n?e.classList.remove("persona-ml-auto"):e.classList.add("persona-ml-auto"));let t="top-right"===o,r=V.classList.contains("persona-absolute");if(!me()&&t!==r&&n){if(V.remove(),t){V.className="persona-absolute persona-top-4 persona-z-50",V.style.right="48px";let e=Jc?.railColumn??gt;e.style.position="relative",e.appendChild(V)}else{V.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",V.style.right="";let e=mt.closeButtonWrapper;er&&e&&e.parentElement===er?er.insertBefore(V,e):er&&er.appendChild(V)}let e=mt.closeButtonWrapper;e&&!e.classList.contains("persona-absolute")&&(t?e.classList.add("persona-ml-auto"):e.classList.remove("persona-ml-auto"))}}if(n){Cl(U,l,"clear",{buttonSize:me()?U.style.width:void 0,iconSize:me()?yd:void 0});let t=e.tooltipText??"Clear chat",r=e.showTooltip??!0;U.setAttribute("aria-label",t),V&&Ja({anchor:U,trigger:V,text:()=>U?.getAttribute("aria-label")??t,enabled:r})}}let K=l.actionParsers&&l.actionParsers.length?l.actionParsers:[Oc],Q=l.actionHandlers&&l.actionHandlers.length?l.actionHandlers:[zc.message,zc.messageAndClick];re=qc({parsers:K,handlers:Q,getSessionMetadata:X,updateSessionMetadata:Z,emit:F.emit,captureResubmitGuard:()=>{let e=be;return()=>ve(e)},documentRef:typeof document<"u"?document:null}),Ae=yp(l,re,ke),(()=>{let e=Ac();if(e&&Ec?.matches(e,Be(),!1===l.persistState)||!e&&!Ec)return;Ec?.destroy(),Ec=e?Mc(e):null;let t={...Lc};Ec?t.visitorStore=Ec:delete t.visitorStore,Lc=t,es.setHistoryInternals(Lc)})(),es.updateConfig(l),Fp(),(!0===l.features?.history?.enabled!==b||l.features?.history?.provider!==y||l.getIdentityProof!==x||l.clientToken!==C)&&(Jc?.closeHistory({restoreFocus:!1}),(l.getIdentityProof!==x||l.clientToken!==C)&&Jc?.discardConversationContinuity(),Jc?.installHistoryProvider()),Jc?.syncHistoryChromeImpl(),Pp(),ep()&&!Jc&&Bp().catch(()=>{}),cd(vt,es.getMessages(),Ae),bs(),bc(),(()=>{let e=Wr();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??""}`!==uc||e.icon!==rc)&&fc()})(),Kd(es.isStreaming()),k!==l.contextMentions&&yh();let J=!0===l.voiceRecognition?.enabled&&!1!==l.voiceRecognition.showButton,G=typeof window<"u"&&(void 0!==window.webkitSpeechRecognition||void 0!==window.SpeechRecognition),Y=_t(l.voiceRecognition?.provider),ee=G||Y||"custom"===l.voiceRecognition?.dictation?.provider?.type;if(J&&ee)if(lr&&dr){let e=l.voiceRecognition??{},t=lr.getAttribute("data-state");Cs(lr,l,"recording"===t||"processing"===t||"speaking"===t?t:"idle",es.getVoiceInterruptionMode());let r=e.tooltipText??"Start voice recognition",n=e.showTooltip??!1;"idle"===t&&lr.setAttribute("aria-label",r),dr&&Ja({anchor:lr,trigger:dr,text:()=>lr?.getAttribute("aria-label")??r,enabled:n}),dr.style.display="",lr.disabled=$d()||es.isStreaming()&&!Wd()}else{let e=Ss(l);if(e){lr=e.button,dr=e.wrapper;let t=sr&&sr.parentElement===ar?sr:null;ar?ar.insertBefore(dr,t):At?.appendChild(dr),En&&(En.micButton=lr),En?.addListener(lr,"click",Nu),lr.disabled=$d()||es.isStreaming()&&!Wd()}}else lr&&dr&&(dr.style.display="none",(!0!==l.voiceRecognition?.enabled||!ee)&&(_t(l.voiceRecognition?.provider)?es.isVoiceActive()&&es.toggleVoice():vu&&Iu()));if(qu(),!0===l.attachments?.enabled){if(mr&&pr){mr.style.display="";let e=l.attachments??{};gr&&(gr.accept=(e.allowedTypes??vo).join(","),gr.multiple=(e.maxFiles??4)>1)}else{let e=l.attachments??{};fr||(fr=st("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fr.style.display="none",(St.parentElement??At).insertBefore(fr,St)),gr||(gr=document.createElement("input"),gr.type="file",gr.accept=(e.allowedTypes??vo).join(","),gr.multiple=(e.maxFiles??4)>1,gr.style.display="none",gr.setAttribute("aria-label","Attach files"),(St.parentElement??At).insertBefore(gr,St)),mr=st("div","persona-send-button-wrapper"),pr=st("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${oa} ${aa}`),pr.type="button",pr.setAttribute("aria-label",e.buttonTooltipText??"Attach file");let t=e.buttonIconName??"paperclip";pr.style.fontSize="18px",pr.style.lineHeight="1";let r=Ee(t,24,"currentColor",1.5);r?pr.appendChild(r):pr.textContent="📎",pr.addEventListener("click",e=>{e.preventDefault(),gr?.click()}),mr.appendChild(pr);let n=e.buttonTooltipText??"Attach file";Ja({anchor:pr,trigger:mr,text:()=>pr?.getAttribute("aria-label")??n}),or?or.append(mr):At.appendChild(mr),En&&(En.attachmentButton=pr,En.attachmentInput=gr??void 0,En.attachmentPreviews=fr??void 0),!Kr&&gr&&fr&&(Kr=tn(),Kr.setPreviewsContainer(fr),En?.addListener(gr,"change",async()=>{Kr&&gr?.files&&(await Kr.handleFileSelect(gr.files),gr.value="")}))}if(gt.querySelector(".persona-attachment-drop-overlay")?.remove(),gt.appendChild(vp(l.attachments?.dropOverlay)),pr){let e=l.attachments??{},t=e.buttonTooltipText??"Attach file";pr.setAttribute("aria-label",t),pr.textContent="";let r=Ee(e.buttonIconName??"paperclip",24,"currentColor",1.5);r?pr.appendChild(r):pr.textContent="📎",mr&&Ja({anchor:pr,trigger:mr,text:()=>pr?.getAttribute("aria-label")??t})}}else mr&&(mr.style.display="none"),Kr&&Kr.clearAttachments(),gt.querySelector(".persona-attachment-drop-overlay")?.remove();let te=l.sendButton?.tooltipText??"Send message",se=l.sendButton?.showTooltip??!1;ws(kt,l),es.isStreaming()||kt.setAttribute("aria-label",te),jd(),sr&&Ja({anchor:kt,trigger:sr,text:()=>kt.getAttribute("aria-label")??te,enabled:se});let pe=new Set([Kr,...Array.from(xp.values(),e=>e.attachments)]);for(let e of pe)e?.updateConfig(Zr());"plugins"in t&&Kr?.remountPreviews(fr),Xn(),$a();let ue=fa(Jr.getState().activeModeIds,l.composer?.modes);Jr.setActiveModeIds(ue),on().length>0!=!!cn&&Vn(),cn?.render(ue,on()),dn?.repaint(),On?On.resolve():Un();let he=fi(l,me());if(Ba(),he){vt.style.maxWidth=he,vt.style.marginLeft="auto",vt.style.marginRight="auto",vt.style.width="100%",Rt.style.maxWidth=he,Rt.style.marginLeft="auto",Rt.style.marginRight="auto",Rt.style.width="100%";for(let e of[At,Ct,fr,Mt])e&&(e.style.maxWidth=he,e.style.marginLeft="auto",e.style.marginRight="auto",e.style.width="100%")}else{vt.style.maxWidth="",vt.style.marginLeft="",vt.style.marginRight="",vt.style.width="",Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight="",Rt.style.width="";for(let e of[At,Ct,fr,Mt])e&&(e.style.maxWidth="",e.style.marginLeft="",e.style.marginRight="",e.style.width="")}let ye=l.statusIndicator??{};if(hr(Mt,At,ye),ur(Mt,ye,es?.getStatus()??"idle"),es){let e=es.getStatus();lt(Mt,(e=>"idle"===e?ye.idleText??dt.idle:"connecting"===e?ye.connectingText??dt.connecting:"connected"===e?ye.connectedText??dt.connected:"error"===e?ye.errorText??dt.error:"paused"===e?ye.pausedText??dt.paused:"resuming"===e?ye.resumingText??dt.resuming:dt[e])(e),ye,e)}Mt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let we="left"===ye.align?"persona-text-left":"center"===ye.align?"persona-text-center":"persona-text-right";Mt.classList.add(we),Ln(),qd(),Yn(),Ze(),eo(l.layout?.slots??{}),hu()&&$d()&&mu(),au?.refresh(),oo.update(),zh()},open(){ge()&&Bd(!0,"api")},close(){ge()&&Bd(!1,"api")},toggle(){ge()&&Bd(!fe,"api")},reconnect(){es.reconnectNow()},clearChat(){mu(),$s(),Ro=!1,i?.clear(),mo(),f.clear(),b.clear(),y.clear(),es.clearMessages(),l.layout?.topFade&&(ft.scrollTop=0),ft.removeAttribute("data-persona-top-fade"),ks.clear(),Ml();try{localStorage.removeItem(pp),l.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pp}`)}catch(e){console.error("[AgentWidget] Failed to clear default localStorage:",e)}if(l.clearChatHistoryStorageKey&&l.clearChatHistoryStorageKey!==pp)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:o,timestamp:(new Date).toISOString()}});window.dispatchEvent(e),tl(),z?.clear&&zi(()=>z.clear(),"[AgentWidget] Failed to clear storage adapter:"),_={},re.syncFromMetadata(),Tp(es.getActiveConversationId(),!0,!1),Vp(),tl(),fn(void 0),un(void 0),Ds(),He?.clear(),De?.reset(),ze?.update()},setMessage:e=>!(!St||hu()||es.isStreaming()||$d()||(!fe&&ge()&&Bd(!0,"system"),St.value=e,St.dispatchEvent(new Event("input",{bubbles:!0})),0)),submitMessage(e){if(es.isStreaming()||hu()||Hd())return!1;let t=e?.trim()||St.value.trim();return!!t&&(!fe&&ge()&&Bd(!0,"system"),St.value="",St.style.height="auto",Gr(),Zp(t,{consumeDraft:!1}),!0)},getComposerState:()=>Jr.getState(),setComposerModes(e){sn(function(e,t,r){let n=[];for(let o of e)n.includes(o)||(n=ga(n,o,t,r));return n}(e,nn(),l.composer?.modeGroups))},setQuote(e){let t=e?.text?.trim();t&&un({...e,text:t})},clearQuote(){un(void 0)},startDictation:fu,finishDictation:()=>gu(),cancelDictation:()=>{let e=iu;return mu()||e},sendDictation:()=>!(!l.voiceRecognition?.dictation?.showSend||Hd())&&gu(!0),getDictationState:()=>lu??au?.getState()??pu,startVoiceRecognition:()=>!es.isStreaming()&&!hu()&&(uu()&&!l.voiceRecognition?.dictation?.provider&&"runtype"!==l.voiceRecognition?.provider?.type?fu():_t(l.voiceRecognition?.provider)?(es.isVoiceActive()||es.isBargeInActive()||(!fe&&ge()&&Bd(!0,"system"),vi.manuallyDeactivated=!1,Li(),es.toggleVoice().then(()=>{vi.active=Ci(),Li(),Mi("user"),vi.active&&Lu()})),!0):!!vu||!!Au()&&(!fe&&ge()&&Bd(!0,"system"),vi.manuallyDeactivated=!1,Li(),Mu("user"),!0)),stopVoiceRecognition:()=>hu()?gu():_t(l.voiceRecognition?.provider)?!(!es.isVoiceActive()&&!es.isBargeInActive()||((es.isBargeInActive()?es.deactivateBargeIn():es.toggleVoice()).then(()=>{vi.active=!1,vi.manuallyDeactivated=!0,Li(),Mi("user"),Pu()}),0)):!!vu&&(vi.manuallyDeactivated=!0,Li(),Iu("user"),!0),injectMessage:e=>(!fe&&ge()&&Bd(!0,"system"),es.injectMessage(e)),injectAssistantMessage(e){!fe&&ge()&&Bd(!0,"system");let t=es.injectAssistantMessage(e);return Ce&&(Ce=!1,Se&&=(clearTimeout(Se),null),xe()),t},injectUserMessage:e=>(!fe&&ge()&&Bd(!0,"system"),es.injectUserMessage(e)),injectSystemMessage:e=>(!fe&&ge()&&Bd(!0,"system"),es.injectSystemMessage(e)),injectMessageBatch:e=>(!fe&&ge()&&Bd(!0,"system"),es.injectMessageBatch(e)),injectComponentDirective:e=>(!fe&&ge()&&Bd(!0,"system"),es.injectComponentDirective(e)),updateComponentProps:(e,t)=>es.updateComponentProps(e,t),removeComponentMessage:e=>es.removeComponentMessage(e),injectTestMessage(e){!fe&&ge()&&Bd(!0,"system"),es.injectTestEvent(e)},connectStream:async(e,t)=>es.connectStream(e,t),__pushEventStreamEvent(e){Te&&(Qe(),Ke(e.type,e.payload))},showEventStream(){Te&&Cn()},hideEventStream(){je&&Sn()},isEventStreamVisible:()=>je,listConversations:e=>es.listConversations(e),getActiveConversationId:()=>es.getActiveConversationId(),openConversation:(e,t)=>Rp(r=>r.openHistoryConversation(e,{focusComposer:!0===t?.focus,busy:t?.busy})),startNewConversation:e=>Rp(t=>t.startNewConversation({focusComposer:!0===e?.focus})),warmSession(){Np()},deleteConversation:e=>Rp(t=>t.deleteHistoryConversation(e)),renameConversation:(e,t)=>Rp(r=>r.updateHistoryConversation(e,{title:t})),setConversationStarred:(e,t)=>Rp(r=>r.updateHistoryConversation(e,{starred:t})),clearConversationHistory:e=>Rp(t=>t.clearConversationHistory(e)),resetHistoryIdentity:()=>Rp(e=>e.resetHistoryIdentity()),async getVisitorToken(){let e=Ec;if(!e)return null;let t=await e.get();return e===Ec?t:null},getHistoryIdentityStatus(){let e=Jc?.historyProvider;return e?e.getIdentityStatus():ep()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory:e=>ep()?Rp(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...void 0===e?.focus?{}:{focus:e.focus}})):Promise.resolve(),hideHistory(e){Jc?.closeHistory(void 0===e?.restoreFocus?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible:()=>Ye,showArtifacts(){Fd(l)&&(Ro=!1,Do=!0,Ta(),Co?.setMobileOpen(!0))},hideArtifacts(){Fd(l)&&(Ro=!0,Ta())},upsertArtifact:e=>Fd(l)?("panel"===Io(l.features?.artifacts,{artifactType:e.artifactType,..."markdown"===e.artifactType&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})&&(Ro=!1,Do=!0),es.upsertArtifact(e)):null,selectArtifact(e){Fd(l)&&es.selectArtifact(e)},clearArtifacts(){Fd(l)&&es.clearArtifacts()},getArtifacts:()=>es?.getArtifacts()??[],getSelectedArtifactId:()=>es?.getSelectedArtifactId()??null,focusInput:()=>!(ne&&!fe&&!me()||!St||(St.focus(),0)),revealToolCall(e,t={}){let r=Array.from(ft.querySelectorAll(".persona-tool-bubble[data-tool-call-id]")).find(t=>t.dataset.toolCallId===e);if(!r)return!1;let n=e=>Array.from(e.querySelectorAll('button[data-expand-header="true"]')).find(t=>t.closest(".persona-tool-bubble")===e),o=e=>{"false"===e?.getAttribute("aria-expanded")&&io(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=>o(n(e)));let s=n(r);!1!==t.expand&&o(s),ni(),Bl.cancel(),kl();let i=uo,l=s??r,d=()=>!ye&&i===uo&&ft.contains(l),c="function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,p=()=>{let e=zr(l)-(ft.clientHeight-l.offsetHeight)/2;return Math.max(0,Math.min(e,Qt(ft)))},u=()=>{d()&&(c?(sl(),qs=!0,ft.scrollTop=p(),zs=ft.scrollTop,qs=!1):Ll(ft,p,200,d))};window.clearTimeout(lo),u(),lo=window.setTimeout(()=>{lo=void 0,u()},200);let h=t.highlightMs??2e3;if(h>0){let e=r.dataset.messageId;window.clearTimeout(po.get(e)),po.set(e,window.setTimeout(()=>{po.delete(e),ho()},h)),r.setAttribute("data-persona-revealed","")}return!0},async resolveApproval(e,t,r){let n=es.getMessages().find(t=>"approval"===t.variant&&t.approval?.id===e);if(!n?.approval)throw Error(`Approval not found: ${e}`);if(!cr(n.approval))return es.resolveApproval(n.approval,t,r);es.resolveWebMcpApproval(n.id,t)},setFollowUpSuggestions(e){(e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length)return void vs();let r=es?es.getMessages():[];rs=t,os=!0,as=cs(r),ls=ps(r),bs(r)})(e)},clearFollowUpSuggestions(){vs()},getMessages:()=>es.getMessages(),getStatus:()=>es.getStatus(),getPersistentMetadata:()=>({..._}),updatePersistentMetadata(e){Z(e)},on:(e,t)=>F.on(e,t),off(e,t){F.off(e,t)},isOpen:()=>ge()&&fe,isVoiceActive:()=>vi.active,toggleReadAloud(e){es.toggleReadAloud(e)},stopReadAloud(){es.stopSpeaking()},getReadAloudState:e=>es.getReadAloudState(e),onReadAloudChange:e=>es.onReadAloudChange(e),getState:()=>({open:ge()&&fe,launcherEnabled:ne,voiceActive:vi.active,streaming:es.isStreaming()}),showCSATFeedback(e){Ph(()=>dp({onSubmit:async(t,r)=>{es.isClientTokenMode()&&await es.submitCSATFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},showNPSFeedback(e){Ph(()=>cp({onSubmit:async(t,r)=>{es.isClientTokenMode()&&await es.submitNPSFeedback(t,r),e?.onSubmit?.(t,r)},onDismiss:e?.onDismiss,...e}))},submitCSATFeedback:async(e,t)=>es.submitCSATFeedback(e,t),submitNPSFeedback:async(e,t)=>es.submitNPSFeedback(e,t),destroy(){ye=!0,we(),u.destroy(),oo.destroy(),e.removeEventListener("click",ao),jc(),Da.forEach(e=>e()),null!=Bc&&(clearInterval(Bc),Bc=null),i?.destroy(),s?.destroy(),mo(),f.clear(),b.clear(),y.clear(),F.dispose(),pt.remove(),ht?.remove(),Yu?.destroy(),Xu?.remove(),ts&&Dt.removeEventListener("click",ts)}};if((r?.debugTools||l.debug)&&typeof window<"u"){let e=window.AgentWidgetBrowser,t={controller:Dh,getMessages:Dh.getMessages,getStatus:Dh.getStatus,getMetadata:Dh.getPersistentMetadata,updateMetadata:Dh.updatePersistentMetadata,clearHistory:()=>Dh.clearChat(),setVoiceActive:e=>e?Dh.startVoiceRecognition():Dh.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Da.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===o)&&t(r)};window.addEventListener(e,r),Da.push(()=>window.removeEventListener(e,r))};e("persona:focusInput",()=>Dh.focusInput()),Te&&(e("persona:showEventStream",()=>Dh.showEventStream()),e("persona:hideEventStream",()=>Dh.hideEventStream())),e("persona:showHistory",()=>Dh.showHistory()),e("persona:hideHistory",()=>Dh.hideHistory()),e("persona:showArtifacts",()=>Dh.showArtifacts()),e("persona:hideArtifacts",()=>Dh.hideArtifacts()),e("persona:upsertArtifact",e=>{e?.artifact&&Dh.upsertArtifact(e.artifact)}),e("persona:selectArtifact",e=>{"string"==typeof e?.id&&Dh.selectArtifact(e.id)}),e("persona:clearArtifacts",()=>Dh.clearArtifacts())}let Oh=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(Oh&&ge()){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}}(Oh.storage),r=`${Oh.keyPrefix}widget-open`,n=`${Oh.keyPrefix}widget-voice`,a=`${Oh.keyPrefix}widget-voice-mode`;if(t){let s=Oh.persist?.openState&&"true"===t.getItem(r),i=Oh.persist?.voiceState&&"true"===t.getItem(n),l=Oh.persist?.voiceState&&"true"===t.getItem(a);if(s&&(Yu?.setPanelOpen(!0,"auto"),setTimeout(()=>{Dh.open(),setTimeout(()=>{if(i||l)Dh.startVoiceRecognition();else if(Oh.persist?.focusInput){let t=e.querySelector("textarea");t&&t.focus()}},100)},0)),Oh.persist?.openState&&(F.on("widget:opened",()=>{t.setItem(r,"true")}),F.on("widget:closed",()=>{t.setItem(r,"false")})),Oh.persist?.voiceState&&(F.on("voice:state",e=>{t.setItem(n,e.active?"true":"false")}),F.on("user:message",e=>{t.setItem(a,e.viaVoice?"true":"false")})),Oh.clearOnChatClear){let e=()=>{t.removeItem(r),t.removeItem(n),t.removeItem(a)},s=t=>{t.detail?.instanceId===o&&e()};window.addEventListener("persona:clear-chat",s),Da.push(()=>{window.removeEventListener("persona:clear-chat",s)})}}}J&&ge()&&(Yu?.setPanelOpen(!0,"auto"),setTimeout(()=>{Dh.open()},0)),Ed(),P=()=>{es&&(Os++,ks.clear(),cd(vt,es.getMessages(),Ae))},es.getMessages().length>0&&ld(),D=P;let Fh=Lt(()=>{P?.(),Et()?.updateInlineArtifactBlocks(vt,Eo.artifacts,{suppressTransition:!0}),Ta()});Da.push(Fh);let zh=()=>{let t=Vt(l);Nh||t.push(...r?.preparation??[]),ep()&&!Jc&&t.push(Bp()),t.length||e.hasAttribute("data-persona-preparing")?u.prepare(t,()=>{On||Un(),cn||Vn(),g(),We()?.ensureComposerActionStyles(e),Et()?.ensureArtifactStyles(e),P?.(),Nh=!0}):Nh=!0};return zh(),Dh},Cp=(e,t)=>{let r=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(n)return Math.max(0,parseFloat(n[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(r);return o?Math.max(0,t*parseFloat(o[1])/100):420},Sp=(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"},kp=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Ap=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",kp(e)},Mp=e=>{e.style.transition=""},Ip=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=""},Tp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ep=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Lp=(e,t,r,n)=>{t?(e.style.boxSizing="border-box",e.style.padding=r,e.style.background=n):(e.style.padding="",e.style.background="",e.style.boxSizing="")},Bp=(e,t)=>ll(t)?((e,t)=>{let{ownerDocument:r}=e,n=e.parentElement;if(!n)throw Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if("BODY"===o||"HTML"===o)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),n.insertBefore(s,e),l.appendChild(e);let u=null,h=()=>{u?.disconnect(),u=null},m=null,g=()=>{m=!0===t?.launcher?.detachedPanel?(e=>{let t=ci(e),r=t.components?.panel,n=(e,r)=>null==e||""===e?r:Vs(t,e)??e;return{inset:n(r?.inset,Ls),canvasBackground:n(r?.canvasBackground,Bs)}})(t):null};g();let f=()=>{((e,t,r,n,o,a,s,i)=>{let l=cl(a),d="push"===l.reveal,c=null!=i,p=i?.inset??"",u=i?.canvasBackground??"";((e,t,r,n,o)=>{o?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,n),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(n))})(e,t,r,n,d),((e,t,r,n,o,a)=>{let s=a?t:e;"left"===o?s.firstElementChild!==n&&s.replaceChildren(n,r):s.lastElementChild!==n&&s.replaceChildren(r,n)})(e,t,r,n,l.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=l.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,g=a?.launcher?.mobileBreakpoint??640,f=null!=h&&h.innerWidth<=g;if(m&&f&&s)e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ip(t),Mp(n),Ap(n),Tp(r),Ep(o,n),Lp(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??1e5),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.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"),Ap(n),((e,t)=>{!1===t?e.style.maxHeight="":(e.style.maxHeight="100vh",e.style.maxHeight=t)})(n,l.maxHeight),Lp(n,c&&s,p,u),"overlay"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ip(t),Mp(n),Tp(r),Ep(o,n);let a=l.animate?"transform 180ms ease":"none",i="right"===l.side?"translateX(100%)":"translateX(-100%)",d=s?"translateX(0)":i;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=l.width,n.style.maxWidth=l.width,n.style.minWidth=l.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=a,n.style.transform=d,n.style.pointerEvents=s?"auto":"none",n.style.zIndex="2","right"===l.side?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if("push"===l.reveal){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Mp(n),kp(n),Ep(o,n);let a=Cp(l.width,e.clientWidth),i=Math.max(0,e.clientWidth),d=l.animate?"margin-left 180ms ease":"none",c="right"===l.side?s?-a:0:s?0:-a;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${i+a}px`,t.style.transition=d,t.style.marginLeft=`${c}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${i}px`,r.style.maxWidth=`${i}px`,r.style.minWidth=`${i}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=l.width,n.style.minWidth=l.width,n.style.maxWidth=l.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ip(t),kp(n),Tp(r),Ep(o,n);let a="emerge"===l.reveal;a?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let i=s?l.width:"0px",d=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease"+(c?", padding 180ms ease":""):"none",u=!s;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",((e,t)=>{!1===t?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")})(n,l.maxHeight),n.style.overflow=a||u?"hidden":"visible",n.style.transition=d,a){n.style.alignItems="right"===l.side?"flex-start":"flex-end";let t=c?`calc(${Cp(l.width,e.clientWidth)}px - (2 * ${p}))`:l.width;o.style.width=t,o.style.minWidth=t,o.style.maxWidth=t,o.style.boxSizing="border-box"}}})(s,i,l,d,c,t,p,m)},b=null,y=()=>{b?.(),b=null,!0===t?.launcher?.detachedPanel&&"auto"===t?.colorScheme&&(b=gi(()=>{g(),f()}))},v=!1,w=()=>{f(),h(),"push"===cl(t).reveal&&typeof ResizeObserver<"u"&&(u=new ResizeObserver(()=>{f()}),u.observe(s)),p&&!v&&"true"!==s.dataset.personaDockMobileFullscreen&&(v=!0,((e,t)=>{let r=e.parentElement;if(!r)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(n);let o=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),o&&!a&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(!1===t.maxHeight?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")})(s,cl(t)))},x=s.ownerDocument.defaultView,C=()=>{w()};return x?.addEventListener("resize",C),"push"===cl(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(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),s.remove()}}})(e,t):((e,t)=>{let r=e.ownerDocument.createElement("div");return Sp(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(e){Sp(r,e)},destroy(){r.remove()}}})(e,t),Rp=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let r=t.head.querySelector("link[data-persona]");if(!r)return;let n=r.cloneNode(!0),o=new Promise((e,t)=>{n.onload=()=>e(),n.onerror=()=>t(Error("Unable to load the widget stylesheet"))});return e.insertBefore(n,e.firstChild),o},Pp=[],Np=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),$p=new Set(["button","a","input","select","textarea","details","summary"]),Wp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Hp=/\b(product|card|item|listing|result)\b/i,Dp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function Op(e){let t="string"==typeof e.className?e.className:"";if(Hp.test(t)||e.id&&Hp.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Hp.test(r.value))return!0}return!1}function Fp(e){return Dp.test((e.textContent??"").trim())}function zp(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 jp(e){let t=e.match(Dp);return t?t[0]:null}function qp(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 _p(e){return Op(e)&&Fp(e)&&(zp(e)||function(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}(e))?5200:0}function Up(e){return!Op(e)||Fp(e)||!zp(e)||(e.textContent??"").trim().length<20||!e.querySelector("h1, h2, h3, h4, h5, h6, .title")&&!e.querySelector(".snippet, .description, p")?0:2800}let Vp=[{id:"commerce-card",scoreElement:e=>_p(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||Dp.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(0===_p(e))return null;let{title:r,href:n}=qp(e),o=jp((e.textContent??"").trim())??jp(t.text)??"",a=function(e){let t=[],r=e=>{let r=e.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(e=>r(e.textContent??"")),e.querySelectorAll('[role="button"]').forEach(e=>r(e.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(e=>{r(e.value??"")}),t.slice(0,6)}(e);return[n&&r?`[${r}](${n})${o?`: ${o}`:""}`:r?`${r}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join("\n")}},{id:"result-card",scoreElement:e=>Up(e),formatSummary(e,t){if(0===Up(e))return null;let{title:r,href:n}=qp(e);return[n&&r?`[${r}](${n})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join("\n")}}];function Kp(e){return typeof CSS<"u"&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}let Qp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Jp(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&&Wp.has(r)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"true"===e.getAttribute("contenteditable")?"clickable":"static"}function Gp(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 Yp(e){let t={},r=e.id;r&&(t.id=r);let n=e.getAttribute("href");n&&(t.href=n);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let i=e.getAttribute("name");i&&(t.name=i);let l=e.getAttribute("role");l&&(t.role=l);for(let r=0;r<e.attributes.length;r++){let n=e.attributes[r];n.name.startsWith("data-")&&(t[n.name]=n.value)}return t}function Xp(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Kp(e.id)}`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}for(let r of Qp){let n=e.getAttribute(r);if(n){let o=`${t}[${r}="${Kp(n)}"]`;try{if(1===e.ownerDocument.querySelectorAll(o).length)return o}catch{}}}let r=Array.from(e.classList).filter(e=>e&&!e.startsWith("persona-")).slice(0,3);if(r.length>0){let n=`${t}.${r.map(e=>Kp(e)).join(".")}`;try{if(1===e.ownerDocument.querySelectorAll(n).length)return n}catch{}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0){let t=`${n}:nth-of-type(${r+1})`;try{if(1===e.ownerDocument.querySelectorAll(t).length)return t}catch{}}}}let n=e.parentElement;if(n){let r=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function Zp(e,t){let r=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:Xp(e),tagName:r,text:n,role:e.getAttribute("role"),interactivity:Jp(e),attributes:Yp(e)}}function eu(e,t,r,n){let o=function(e){return"static"===e?100:3e3}(t.interactivity),a=null;for(let s of r){let r=s.scoreElement(e,t,n);r>0&&(o+=r,s.formatSummary&&!a&&(a=s))}return{score:o,formattingRule:a}}function tu(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 ru={components:{panel:{borderRadius:"0",shadow:"none"}}},nu={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:ls},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}}}},ou={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:ru}},au={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:ru}},su={shop:nu,minimal:ou,fullscreen:au},iu=typeof document<"u"&&(document.currentScript?.src??"").replace(/^https:\/\/cdn\.runtype\.com\/persona\/latest\//,"https://cdn.runtype.com/persona/4.32.2/")||null,lu=(e,t=`host ${e} alongside it`)=>{let r=0;return()=>{let n=iu?.replace(/index\.global\.js($|\?)/,`${e}$1`);return n&&n!==iu?import(`${n}${r?`#retry-${r}`:""}`).catch(e=>{throw r++,e}):Promise.reject(Error(`Could not derive the ${e} URL from the widget script URL (${iu??"unavailable"}). Self-hosted deployments that rename index.global.js should ${t}.`))}};return(e=>{or=e})(lu("webmcp-polyfill.js","install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp")),rt(lu("markdown-parsers.js")),jr(lu("client-stream.js")),to(lu("client-history.js")),$t(lu("ui-extras.js")),ho(lu("session-actions.js")),np(lu("history-shell.js")),(e=>{zo=e})(lu("runtype-tts.js","host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly")),Ra(lu("context-mentions.js")),Wa(lu("context-mentions-inline.js")),Yc(lu("history-view.js")),rl(lu("animations-extra.js","host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin")),Rd(lu("approval-ui.js")),zt(lu("voice-runtime.js")),on(lu("voice-client-tools.js")),It(lu("artifacts-ui.js")),wc(lu("forms-ui.js")),ie(lu("icons-extra.js","host icons-extra.js alongside it, or register the icons they use via registerIcons()")),en(lu("webmcp-runtime.js")),Uo(lu("session-reconnect.js")),Hd(lu("event-stream-view.js")),Ne(lu("composer-actions-runtime.js")),Qe(lu("dictation-runtime.js")),so(lu("background-runtime.js")),Rc(lu("config-diagnostics.js")),J(lu("activity-ui.js")),ze(lu("loading-label-runtime.js")),Jr(lu("client-dispatch.js")),te(lu("turn-activity-ui.js")),e.ASK_USER_QUESTION_CLIENT_TOOL=_n,e.ASK_USER_QUESTION_PARAMETERS_SCHEMA=qn,e.ASK_USER_QUESTION_TOOL_NAME=cn,e.AgentWidgetClient=o,e.AgentWidgetSession=c,e.AttachmentManager=p,e.BrowserSpeechEngine=s,e.DEFAULT_COMPONENTS=_s,e.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH="440px",e.DEFAULT_FLOATING_LAUNCHER_WIDTH=ls,e.DEFAULT_PALETTE=Ds,e.DEFAULT_SEMANTIC=zs,e.DEFAULT_WIDGET_CONFIG=ms,e.HistoryProviderError=a,e.PRESETS=su,e.PRESET_FULLSCREEN=au,e.PRESET_MINIMAL=ou,e.PRESET_SHOP=nu,e.ReadAloudController=i,e.SUGGEST_REPLIES_CLIENT_TOOL=Hn,e.SUGGEST_REPLIES_PARAMETERS_SCHEMA=Wn,e.SUGGEST_REPLIES_TOOL_NAME=$n,e.THEME_ZONES={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"},e.VERSION=Yn,e.WEBMCP_TOOL_PREFIX=er,e.applyFeaturePreferences=mc,e.applyThemeVariables=hi,e.attachHeaderToContainer=El,e.buildComposer=Wl,e.buildDefaultHeader=Ll,e.buildHeader=Tl,e.buildHeaderWithLayout=Nl,e.buildMinimalHeader=Bl,e.builtInClientToolsForDispatch=Un,e.canonicalArtifactDisplayMode=ko,e.collectEnrichedPageContext=function(e={}){let t=function(e){let t=e.options??{},r=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",o=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,i=t.mode??"structured",l=t.maxCandidates??Math.max(500,10*r),d=e.rules??Vp;return"simple"===i&&e.rules&&e.rules.length>0?(typeof console<"u"&&"function"==typeof console.warn&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.'),d=[]):"simple"===i&&(d=[]),{mode:i,maxElements:r,maxCandidates:l,excludeSelector:n,maxTextLength:o,visibleOnly:a,root:s,rules:d}}(e),r=t.root??document.body;return r?"simple"===t.mode?function(e,t){let r=[],n=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=o.currentNode;for(;a&&r.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,s=t.tagName.toLowerCase();if(Np.has(s)){a=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Gp(t)){a=o.nextNode();continue}let i=Zp(t,e.maxTextLength),l=i.text.length>0,d=Object.keys(i.attributes).length>0&&!Object.keys(i.attributes).every(e=>"role"===e);if(!l&&!d){a=o.nextNode();continue}n.has(i.selector)||(n.add(i.selector),r.push(i))}a=o.nextNode()}let s=[],i=[];for(let e of r)"static"===e.interactivity?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},n=new Set,o=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=s.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let t=i,l=t.tagName.toLowerCase();if(Np.has(l)){i=s.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){i=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Gp(t)){i=s.nextNode();continue}let d=Zp(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||n.has(d.selector)){i=s.nextNode();continue}n.add(d.selector);let{score:u,formattingRule:h}=eu(t,d,e.rules,r);o.push({el:t,domIndex:a,enriched:d,score:u,formattingRule:h}),a+=1}i=s.nextNode()}o.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:r-n});let l=[];for(let t of o){if(l.length>=e.maxElements)break;tu(l,t)||l.push(t)}return l.sort((e,t)=>{let r=+("static"===e.enriched.interactivity),n=+("static"===t.enriched.interactivity);return r===n?1===r&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:r-n}),l.map(e=>{let t;if(e.formattingRule?.formatSummary){let n=e.formattingRule.formatSummary(e.el,e.enriched,r);n&&(t=n)}let n={...e.enriched};return t&&(n.formattedSummary=t),n})}(t,r):[]},e.componentRegistry=ft,e.createActionManager=qc,e.createAgentExperience=xp,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"),kn(r,t);let n=st("span","persona-ask-stub-label"),{complete:o}=xn(e);return n.textContent=o?"Awaiting your response…":"Preparing options…",r.appendChild(n),r},e.createBubbleWithLayout=(e,t,r,n,o,a)=>{let s=r??{};return"user"===e.role&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):"assistant"===e.role&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Jl(e,t,r,n,0,a)},e.createCSATFeedback=dp,e.createComboButton=gt,e.createComponentMiddleware=function(){let e=Ro();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}},e.createComponentStreamParser=Ro,e.createDefaultSanitizer=Rr,e.createDirectivePostprocessor=e=>{let t=Sr(e);return e=>{let r=[],n=Er(e,r),o=t(n);return r.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=`<div class="persona-form-directive" data-tv-form="${Ir(t)}"></div>`;o=o.replace(r,n)}),o}},e.createDropdownMenu=ct,e.createFlexibleJsonStreamParser=e=>{let t=null,n=0,o=e||(e=>{if(!e||"object"!=typeof e)return null;let t=e=>"string"==typeof e?Vn(e):null;if(e.component&&"string"==typeof e.component)return"string"==typeof e.text?Vn(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<=n)return null===t?null:{text:t,raw:e};try{let n=(0,r.parse)(e,r.STR|r.OBJ),a=o(n);null!==a&&(t=a)}catch{}return n=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=Jn,e.createLabelButton=ut,e.createLocalStorageAdapter=Kc,e.createMarkdownProcessor=Cr,e.createMarkdownProcessorFromConfig=Sr,e.createMessageActions=Ql,e.createNPSFeedback=cp,e.createPlainTextParser=Kn,e.createRegexJsonParser=Qn,e.createSplitButton=mt,e.createStandardBubble=Jl,e.createTextPart=bo,e.createTheme=Gs,e.createThemeObserver=gi,e.createToggleGroup=ht,e.createTypingIndicator=Fl,e.createWidgetHostLayout=Bp,e.createXmlParser=Gn,e.defaultActionHandlers=zc,e.defaultJsonActionParser=Oc,e.defaultParseRules=Vp,e.detectColorScheme=li,e.directivePostprocessor=e=>{let t=[],r=Er(e,t),n=Ar(r);return t.forEach(({token:e,type:t})=>{let r=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=`<div class="persona-form-directive" data-tv-form="${Ir(t)}"></div>`;n=n.replace(r,o)}),n},e.ensureAskUserQuestionSheet=Pn,e.escapeHtml=Mr,e.extractComponentDirectiveFromMessage=Wo,e.fileToImagePart=async function(e){return new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>r(Error("Failed to read file")),n.readAsDataURL(e)})},e.formatEnrichedContext=function(e,t={}){if(0===e.length)return"No page elements found.";let r=t.mode??"structured",n=[];if("structured"===r){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&n.push(`Structured summaries:\n${t.map(e=>`- ${e.split("\n").join("\n ")}`).join("\n")}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let t of e)"structured"===r&&t.formattedSummary||o[t.interactivity].push(t);if(o.clickable.length>0){let e=o.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);n.push(`Interactive elements:\n${e.join("\n")}`)}if(o.navigable.length>0){let e=o.navigable.map(e=>`- ${e.selector}${e.attributes.href?`[href="${e.attributes.href}"]`:""}: "${e.text.substring(0,100)}" (navigable)`);n.push(`Navigation links:\n${e.join("\n")}`)}if(o.input.length>0){let e=o.input.map(e=>`- ${e.selector}${e.attributes.type?`[type="${e.attributes.type}"]`:""}: "${e.text.substring(0,100)}" (input)`);n.push(`Form inputs:\n${e.join("\n")}`)}if(o.static.length>0){let e=o.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);n.push(`Content:\n${e.join("\n")}`)}return n.join("\n\n")},e.generateAssistantMessageId=dn,e.generateMessageId=function(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`},e.generateStableSelector=Xp,e.generateUserMessageId=ln,e.getActiveTheme=ci,e.getAgentWidgetHandles=()=>[...Pp],e.getColorScheme=di,e.getDisplayText=function(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("")},e.getHeaderLayout=Pl,e.getImageParts=function(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)},e.getPreset=function(e){return su[e]},e.hasComponentDirective=$o,e.hasImages=fo,e.headerLayouts=Rl,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),n=!0===e.useShadowDom,o=r.ownerDocument,a=r.id||`persona-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,s=e.config,i=Hc(s),l=Bp(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)||ll(t),i=o.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"),n){let t=e.attachShadow({mode:"open"});t.appendChild(i),r=Rp(t,o)}else e.appendChild(i),Rp(e,o);return i.setAttribute("data-persona-instance",a),{mount:i,stylesReady:r}},f=()=>{l.syncWidgetState(t.getState())},b=()=>{let{mount:r,stylesReady:n}=g(l.host,s);t=xp(r,s,{debugTools:e.debugTools,registerHostMove:e=>{h=e},diagnostics:i,preparation:n?[n]:[]}),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=Bp(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 n="string"==typeof e?o.querySelector(e):e;if(!(n instanceof HTMLElement)||n.ownerDocument!==o||n.getRootNode()!==o||l.host.getRootNode()!==o||l.host.contains(n))throw Error("Invalid widget move target: expected a connected light-DOM container in the same document");n!==r&&(h(()=>function(e,t,r){let n=e.ownerDocument,o=n.activeElement;for(;o?.shadowRoot?.activeElement;)o=o.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(o)?o:null,i=s,l=i?.selectionStart,d=i?.selectionEnd,c=i?.selectionDirection,p=(s?.getRootNode())?.getSelection?.()??n.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,n,!1!==t?.preserveFocus)),r=n)},on(e,r){if(c)return()=>{};let n=[...m].find(t=>t.event===e&&t.handler===r);if(n)return n.unsubscribe;let o=()=>{},a={event:e,handler:r,bind:()=>{o=t.on(e,r)},unsubscribe:()=>{o(),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){Dc(i,e);let r=Ic(s??{},e),n=ll(s),o=ll(r),a=dl(s),d=dl(r);n!==o||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=Pp.indexOf(w);-1!==t&&Pp.splice(t,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},{get(e,r,n){if("host"===r)return l.host;if(r in e)return Reflect.get(e,r,n);let o=t[r];return"function"==typeof o?o.bind(t):o}});return Pp.push(w),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w},e.isAskUserQuestionMessage=vn,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=ll,e.isHistoryProviderError=function(e){return e instanceof a},e.isSuggestRepliesMessage=Dn,e.isWebMcpToolName=lr,e.isWelcomeVisible=ud,e.latestAgentSuggestions=Fn,e.listRegisteredStreamAnimations=()=>Array.from(Wi.keys()),e.loadMarkdownParsers=nt,e.markdownPostprocessor=Ar,e.mergeWithDefaults=fs,e.normalizeContent=function(e){return"string"==typeof e?[{type:"text",text:e}]:e},e.normalizeMediaType=Ao,e.onMarkdownParsersReady=ot,e.parseAskUserQuestionPayload=xn,e.parseSuggestRepliesPayload=On,e.parseWidgetPreferenceSlice=cc,e.pickBestVoice=Oo,e.pluginRegistry=Sc,e.preprocessStreamingMarkdown=xr,e.registerIcons=e=>{for(let[t,r]of Object.entries(e))Ce.set(t,r);Ie()>0&&!ke&&Me(!1)},e.registerStreamAnimationPlugin=Di,e.removeAskUserQuestionSheet=Nn,e.renderComponentDirective=Po,e.renderLoadingIndicatorWithFallback=zl,e.renderLucideIcon=Ee,e.resolveArtifactDisplay=Mo,e.resolveArtifactDisplayMode=Io,e.resolveConfigPreferences=gc,e.resolveDockConfig=cl,e.resolveSanitizer=Pr,e.resolveTokens=Ks,e.resolveWelcomeConfig=dd,e.stripWebMcpPrefix=ir,e.themeToCssVariables=ti,e.unregisterStreamAnimationPlugin=e=>{$i.some(t=>t.name===e)||Wi.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=Qs,e}({});
|
|
8
8
|
//# sourceMappingURL=index.global.js.map
|