@runtypelabs/persona 4.21.0 → 4.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,32 +1,32 @@
1
- "use strict";var AgentWidget=(()=>{var uT=Object.create;var sc=Object.defineProperty;var pT=Object.getOwnPropertyDescriptor;var fT=Object.getOwnPropertyNames;var mT=Object.getPrototypeOf,gT=Object.prototype.hasOwnProperty;var ho=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var av=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hT=(e,t)=>{for(var o in t)sc(e,o,{get:t[o],enumerable:!0})},iv=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of fT(t))!gT.call(e,r)&&r!==o&&sc(e,r,{get:()=>t[r],enumerable:!(n=pT(t,r))||n.enumerable});return e};var Zt=(e,t,o)=>(o=e!=null?uT(mT(e)):{},iv(t||!e||!e.__esModule?sc(o,"default",{value:e,enumerable:!0}):o,e)),yT=e=>iv(sc({},"__esModule",{value:!0}),e);var Bf=av(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.Allow=be.ALL=be.COLLECTION=be.ATOM=be.SPECIAL=be.INF=be._INFINITY=be.INFINITY=be.NAN=be.BOOL=be.NULL=be.OBJ=be.ARR=be.NUM=be.STR=void 0;be.STR=1;be.NUM=2;be.ARR=4;be.OBJ=8;be.NULL=16;be.BOOL=32;be.NAN=64;be.INFINITY=128;be._INFINITY=256;be.INF=be.INFINITY|be._INFINITY;be.SPECIAL=be.NULL|be.BOOL|be.INF|be.NAN;be.ATOM=be.STR|be.NUM|be.SPECIAL;be.COLLECTION=be.ARR|be.OBJ;be.ALL=be.ATOM|be.COLLECTION;be.Allow={STR:be.STR,NUM:be.NUM,ARR:be.ARR,OBJ:be.OBJ,NULL:be.NULL,BOOL:be.BOOL,NAN:be.NAN,INFINITY:be.INFINITY,_INFINITY:be._INFINITY,INF:be.INF,SPECIAL:be.SPECIAL,ATOM:be.ATOM,COLLECTION:be.COLLECTION,ALL:be.ALL};be.default=be.Allow});var pc=av(ro=>{"use strict";var WT=ro&&ro.__createBinding||(Object.create?(function(e,t,o,n){n===void 0&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}):(function(e,t,o,n){n===void 0&&(n=o),e[n]=t[o]})),BT=ro&&ro.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&WT(t,e,o)};Object.defineProperty(ro,"__esModule",{value:!0});ro.Allow=ro.MalformedJSON=ro.PartialJSON=ro.parseJSON=ro.parse=void 0;var yo=Bf();Object.defineProperty(ro,"Allow",{enumerable:!0,get:function(){return yo.Allow}});BT(Bf(),ro);var cc=class extends Error{};ro.PartialJSON=cc;var uc=class extends Error{};ro.MalformedJSON=uc;function Hv(e,t=yo.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return OT(e.trim(),t)}ro.parseJSON=Hv;var OT=(e,t)=>{let o=e.length,n=0,r=h=>{throw new cc(`${h} at position ${n}`)},a=h=>{throw new uc(`${h} at position ${n}`)},i=()=>(m(),n>=o&&r("Unexpected end of input"),e[n]==='"'?d():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||yo.Allow.NULL&t&&o-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||yo.Allow.BOOL&t&&o-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||yo.Allow.BOOL&t&&o-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||yo.Allow.INFINITY&t&&o-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||yo.Allow._INFINITY&t&&1<o-n&&o-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||yo.Allow.NAN&t&&o-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),d=()=>{let h=n,y=!1;for(n++;n<o&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(h,++n-Number(y)))}catch(x){a(String(x))}else if(yo.Allow.STR&t)try{return JSON.parse(e.substring(h,n-Number(y))+'"')}catch{return JSON.parse(e.substring(h,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,m();let h={};try{for(;e[n]!=="}";){if(m(),n>=o&&yo.Allow.OBJ&t)return h;let y=d();m(),n++;try{let x=i();h[y]=x}catch(x){if(yo.Allow.OBJ&t)return h;throw x}m(),e[n]===","&&n++}}catch{if(yo.Allow.OBJ&t)return h;r("Expected '}' at end of object")}return n++,h},u=()=>{n++;let h=[];try{for(;e[n]!=="]";)h.push(i()),m(),e[n]===","&&n++}catch{if(yo.Allow.ARR&t)return h;r("Expected ']' at end of array")}return n++,h},p=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(yo.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(y))}}let h=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==o&&!(yo.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(h,n))}catch{e.substring(h,n)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(h,e.lastIndexOf("e")))}catch(x){a(String(x))}}},m=()=>{for(;n<o&&`
2
- \r `.includes(e[n]);)n++};return i()},DT=Hv;ro.parse=DT});var E0={};hT(E0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Vf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>$f,ASK_USER_QUESTION_TOOL_NAME:()=>nl,AgentWidgetClient:()=>Os,AgentWidgetSession:()=>_a,AttachmentManager:()=>Fs,BrowserSpeechEngine:()=>Ds,DEFAULT_COMPONENTS:()=>dg,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Vc,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>zo,DEFAULT_PALETTE:()=>ig,DEFAULT_SEMANTIC:()=>lg,DEFAULT_WIDGET_CONFIG:()=>rt,HistoryProviderError:()=>ln,PRESETS:()=>Sh,PRESET_FULLSCREEN:()=>Ch,PRESET_MINIMAL:()=>xh,PRESET_SHOP:()=>vh,ReadAloudController:()=>Da,SUGGEST_REPLIES_CLIENT_TOOL:()=>hc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Uf,SUGGEST_REPLIES_TOOL_NAME:()=>Fn,THEME_ZONES:()=>NC,VERSION:()=>Un,WEBMCP_TOOL_PREFIX:()=>el,applyFeaturePreferences:()=>th,applyThemeVariables:()=>Us,attachHeaderToContainer:()=>Vs,buildComposer:()=>Ks,buildDefaultHeader:()=>Tg,buildHeader:()=>mr,buildHeaderWithLayout:()=>Ya,buildMinimalHeader:()=>Eg,builtInClientToolsForDispatch:()=>Wa,canonicalArtifactDisplayMode:()=>Ro,collectEnrichedPageContext:()=>qw,componentRegistry:()=>Cn,createActionManager:()=>ql,createAgentExperience:()=>Vu,createAskUserQuestionBubble:()=>zv,createBubbleWithLayout:()=>SS,createCSATFeedback:()=>Uu,createComboButton:()=>bu,createComponentMiddleware:()=>Cw,createComponentStreamParser:()=>_u,createDefaultSanitizer:()=>kf,createDirectivePostprocessor:()=>pv,createDropdownMenu:()=>js,createFlexibleJsonStreamParser:()=>Yv,createIconButton:()=>zs,createImagePart:()=>Pc,createJsonStreamParser:()=>Mc,createLabelButton:()=>Mg,createLocalStorageAdapter:()=>Ou,createMarkdownProcessor:()=>Ji,createMarkdownProcessorFromConfig:()=>Zi,createMessageActions:()=>Hg,createNPSFeedback:()=>qu,createPlainTextParser:()=>wc,createRegexJsonParser:()=>Ac,createSplitButton:()=>mS,createStandardBubble:()=>Ja,createTextPart:()=>an,createTheme:()=>wl,createThemeObserver:()=>Ka,createToggleGroup:()=>fS,createTypingIndicator:()=>Gs,createWidgetHostLayout:()=>Vl,createXmlParser:()=>Tc,defaultActionHandlers:()=>Ys,defaultJsonActionParser:()=>Ul,defaultParseRules:()=>yh,detectColorScheme:()=>Al,directivePostprocessor:()=>fv,ensureAskUserQuestionSheet:()=>Ha,escapeHtml:()=>dr,extractComponentDirectiveFromMessage:()=>Fu,fileToImagePart:()=>tx,formatEnrichedContext:()=>$w,generateAssistantMessageId:()=>Fr,generateMessageId:()=>Iv,generateStableSelector:()=>bh,generateUserMessageId:()=>La,getActiveTheme:()=>Kr,getColorScheme:()=>lu,getDisplayText:()=>Ec,getHeaderLayout:()=>Pg,getImageParts:()=>ex,getPreset:()=>jw,hasComponentDirective:()=>$l,hasImages:()=>Oa,headerLayouts:()=>vu,initAgentWidget:()=>Iw,isAskUserQuestionMessage:()=>cr,isComponentDirectiveType:()=>xw,isDockedMountMode:()=>St,isHistoryProviderError:()=>wx,isSuggestRepliesMessage:()=>Bs,isWebMcpToolName:()=>_r,isWelcomeVisible:()=>Yr,latestAgentSuggestions:()=>yc,listRegisteredStreamAnimations:()=>bg,loadMarkdownParsers:()=>ic,markdownPostprocessor:()=>Pf,mergeWithDefaults:()=>ja,normalizeContent:()=>Zv,normalizeMediaType:()=>Nr,onMarkdownParsersReady:()=>ka,parseAskUserQuestionPayload:()=>ur,parseSuggestRepliesPayload:()=>qf,parseWidgetPreferenceSlice:()=>eh,pickBestVoice:()=>cl,pluginRegistry:()=>Fl,registerIcons:()=>Bx,registerStreamAnimationPlugin:()=>Ga,removeAskUserQuestionSheet:()=>$r,renderComponentDirective:()=>Nu,renderLoadingIndicatorWithFallback:()=>Rg,renderLucideIcon:()=>ce,resolveArtifactDisplay:()=>Wf,resolveArtifactDisplayMode:()=>Nn,resolveConfigPreferences:()=>Nl,resolveDockConfig:()=>Wo,resolveSanitizer:()=>lc,resolveTokens:()=>au,resolveWelcomeConfig:()=>xn,stripWebMcpPrefix:()=>Hf,themeToCssVariables:()=>iu,unregisterStreamAnimationPlugin:()=>yg,validateImageFile:()=>ox,validateTheme:()=>cg});var mt=e=>{let{fallbackImport:t,resetOnSetLoader:o=!1}=e,n=null,r=null,a=null;return{setLoader:p=>{n=p,o&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(n??t)().then(m=>(r=m,m)).catch(m=>{throw a=null,m}),a),provide:p=>{r=p},getSync:()=>r}};var{setLoader:bT,load:vT,provide:O0,getSync:Ef}=mt({fallbackImport:()=>import("./markdown-parsers-entry")}),ac=new Set,xT=()=>{let e=[...ac];ac.clear();for(let t of e)try{t()}catch{}},lv=bT,ic=()=>{let e=Ef();return e?Promise.resolve(e):vT().then(t=>(xT(),t))},ka=e=>Ef()?()=>{}:(ac.add(e),()=>{ac.delete(e)});var _n=Ef;var CT=e=>{if(!e)return;let t={},o=e;if(o.heading){let n=o.heading;t.heading=(r,a,i)=>n({type:"heading",raw:i,depth:a,text:r,tokens:[]})}if(o.code){let n=o.code;t.code=(r,a,i)=>n({type:"code",raw:"",text:r,lang:a,escaped:i})}if(o.blockquote){let n=o.blockquote;t.blockquote=r=>n({type:"blockquote",raw:"",text:r,tokens:[]})}if(o.table){let n=o.table;t.table=(r,a)=>n({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:a})}if(o.link){let n=o.link;t.link=(r,a,i)=>n({type:"link",raw:"",href:r,title:a??null,text:i,tokens:[]})}if(o.image){let n=o.image;t.image=(r,a,i)=>n({type:"image",raw:"",href:r,title:a??null,text:i})}if(o.list){let n=o.list;t.list=(r,a,i)=>n({type:"list",raw:"",ordered:a,start:i,loose:!1,items:[],itemsHtml:r})}if(o.listitem){let n=o.listitem;t.listitem=(r,a,i)=>n({type:"list_item",raw:"",task:a,checked:i,loose:!1,text:r,tokens:[]})}if(o.paragraph){let n=o.paragraph;t.paragraph=r=>n({type:"paragraph",raw:"",text:r,tokens:[]})}if(o.codespan){let n=o.codespan;t.codespan=r=>n({type:"codespan",raw:"",text:r})}if(o.strong){let n=o.strong;t.strong=r=>n({type:"strong",raw:"",text:r,tokens:[]})}if(o.em){let n=o.em;t.em=r=>n({type:"em",raw:"",text:r,tokens:[]})}if(o.del){let n=o.del;t.del=r=>n({type:"del",raw:"",text:r,tokens:[]})}if(o.html){let n=o.html;t.html=r=>n({type:"html",raw:r,text:r})}if(o.text){let n=o.text;t.text=r=>n({type:"text",raw:r,text:r})}if(o.checkbox){let n=o.checkbox;t.checkbox=r=>n({checked:r})}return o.hr&&(t.hr=o.hr),o.br&&(t.br=o.br),t},Ji=e=>{let t=null;return o=>{let n=_n();if(!n)return dr(o);if(!t){let{Marked:r}=n,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let i=CT(e?.renderer);i&&t.use({renderer:i})}return t.parse(o)}},Zi=e=>e?Ji({markedOptions:e.options,renderer:e.renderer}):Ji(),ST=Ji(),Pf=e=>ST(e),dr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),cv=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),dv=e=>`%%FORM_PLACEHOLDER_${e}%%`,uv=(e,t)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let i=dv(t.length);return t.push({token:i,type:String(a.type)}),i}}catch{return n}return n}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,r)=>{let a=dv(t.length);return t.push({token:a,type:r}),a}),o},pv=e=>{let t=Zi(e);return o=>{let n=[],r=uv(o,n),a=t(r);return n.forEach(({token:i,type:d})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${cv(d)}"></div>`;a=a.replace(c,p)}),a}},fv=e=>{let t=[],o=uv(e,t),n=Pf(o);return t.forEach(({token:r,type:a})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${cv(a)}"></div>`;n=n.replace(i,c)}),n};var wT={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},AT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,kf=()=>{let e=null;return t=>{let o=_n();if(!o)return dr(t);if(!e){let{DOMPurify:n}=o;e=n(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let i=a.attrValue;i.toLowerCase().startsWith("data:")&&!AT.test(i)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,wT)}},lc=e=>e===!1?null:typeof e=="function"?e:kf();var mv=/^\s*\|?[\s:|-]*-[\s:|-]*$/,gv=e=>e.includes("|"),hv=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(o=>o.trim())},MT=e=>`| ${e.join(" | ")} |`,TT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,ET=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),yv=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
- `),o=!1;for(let n=0;n<t.length-1;n++){let r=t[n],a=t[n+1];if(!gv(r)||mv.test(r)||!mv.test(a))continue;let i=hv(r).length;if(i<1)continue;let d=TT(i);t[n+1]!==d&&(t[n+1]=d,o=!0);let c=n+2;for(;c<t.length;c++){let u=t[c];if(u.trim()===""||!gv(u))break;let p=MT(ET(hv(u),i));t[c]!==p&&(t[c]=p,o=!0)}n=c-1}return o?t.join(`
4
- `):e};var bv="var(--persona-md-table-scroll-fade, 24px)",vv=new WeakSet;function Cv(e){e.querySelectorAll("table").forEach(o=>{if(o.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",o.replaceWith(r),r.appendChild(o)})}function xv(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let n=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty("--persona-fade-l",n<=1?"0px":bv),e.style.setProperty("--persona-fade-r",r<=1?"0px":bv)}function Lf(e){vv.has(e)||(vv.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&xv(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(xv)}var el="webmcp:",If=new Map,wv=e=>{If.clear();for(let t of e){let o=t.title?.trim();o&&If.set(t.name,o)}},dc=e=>If.get(Hf(e)),Rf=null,Av=e=>{Rf=e};function Mv(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${PT(t.join(""))}`}function Sv(e,t){let o=3735928559^t,n=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);o=Math.imul(o^a,2654435761),n=Math.imul(n^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&n)+(o>>>0)}function PT(e){let t=Sv(e,0).toString(36),o=Sv(e,2654435761).toString(36);return`${t}.${o}`}var Hf=e=>e.startsWith(el)?e.slice(el.length):e,_r=e=>e.startsWith(el),Tv=()=>Rf?Rf():import("@mcp-b/webmcp-polyfill");var{setLoader:kT,load:LT}=mt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Ev=kT,Pv=LT;function Ro(e){return e==="card"?"collapsed":e}function Nr(e){return e.split(";",1)[0].trim().toLowerCase()}function IT(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if(Nr(r)===t)return{mode:Ro(a),selector:Nr(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if(Nr(r)===n)return{mode:Ro(a),selector:n}}function Wf(e,t){let o=e?.display,n=typeof o=="string"?{default:o}:o??{};if(t.file&&n.files){if(typeof n.files=="string")return{mode:Ro(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?Nr(t.file.mimeType):void 0,c=d?IT(n.files.byMediaType,d):void 0;if(d&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:d,selector:c.selector}};if(n.files.default)return{mode:Ro(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:Ro(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=n.byType?.[t.artifactType];if(a)return{mode:Ro(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Ro(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:Ro(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Nn(e,t){return Wf(e,t).mode}function tl(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var RT="agent_",HT="flow_";function kv(e){return e.startsWith(RT)?{kind:"agentId",agentId:e}:e.startsWith(HT)?{kind:"flowId",flowId:e}:null}function Lv(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let n=o.indexOf(":");if(n>0){let i=o.slice(0,n),d=o.slice(n+1);if(i==="runtype"){let u=kv(d);if(u)return u;throw new Error(`[Persona] target "runtype:${d}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(d).payload}}let r=kv(o);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Iv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function La(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Rv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var Ur=Zt(pc(),1);var I=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o};var Y=(e,t={},...o)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),t.attrs)for(let[a,i]of Object.entries(t.attrs))n.setAttribute(a,i);if(t.style){let a=n.style,i=t.style;for(let d of Object.keys(i)){let c=i[d];c!=null&&(a[d]=c)}}let r=o.filter(a=>a!=null);return r.length>0&&n.append(...r),n},bo=(...e)=>e.filter(Boolean).join(" ");var nl="ask_user_question",ol=8,Ia="data-persona-ask-sheet-for",_T="Other",NT="Other\u2026",Bv="Type your own answer here",Ov="Send",FT="Next",UT="Back",qT="Submit all",$T="Skip",VT=3,Of="data-ask-current-index",Df="data-ask-question-count",Dv="data-ask-answers",_f="data-ask-grouped",_v="data-ask-layout",jT=e=>e.layout==="pills"?"pills":"rows",zT=e=>e.getAttribute(_v)==="pills"?"pills":"rows",Wv=!1,Nv=e=>e.replace(/["\\]/g,"\\$&"),cr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===nl,fc=e=>e?.features?.askUserQuestion??{},ur=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:o};try{let r=n.join(""),a=(0,Ur.parse)(r,Ur.STR|Ur.OBJ|Ur.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},rl=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ol&&!Wv&&(Wv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ol}.`)),t.slice(0,ol)},KT=e=>rl(e)[0]??null,GT=(e,t)=>rl(e)[t]??null,Fv=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},Uv=(e,t,o)=>{if(e!=="rows")return null;let n=I("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let r=I("span","persona-ask-row-check");n.appendChild(r)}else{let r=I("span","persona-ask-row-badge");r.textContent=String(o+1),n.appendChild(r)}return n},XT=(e,t,o,n)=>{let a=I("button",o==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let i=I("span","persona-ask-row-content"),d=I("span","persona-ask-row-label");if(d.textContent=e.label,i.appendChild(d),e.description){let u=I("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}a.appendChild(i);let c=Uv(o,n,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},QT=e=>{let o=I("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return o.setAttribute("aria-hidden","true"),o},YT=(e,t,o,n)=>{let a=I("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!o){for(let p=0;p<VT;p++)a.appendChild(QT(n));return a}if(c.forEach((p,m)=>{a.appendChild(XT(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?_T:NT;if(n==="rows"){let m=I("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let h=I("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??Bv,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let x=Uv(n,i,c.length);x&&m.appendChild(x),a.appendChild(m)}else{let m=I("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??p,a.appendChild(m)}}return a},qv=(e,t)=>{let n=I("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Bv,r.setAttribute("data-ask-free-text-input","true"),n.appendChild(r),t!=="rows"){let a=I("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Ov,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},JT=e=>{let t=I("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=I("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??Ov,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},ZT=(e,t,o)=>{let n=I("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let r=I("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=o.backLabel??UT,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,n.appendChild(r);let a=I("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=I("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=o.skipLabel??$T,i.setAttribute("data-ask-user-action","skip"),a.appendChild(i);let d=I("button","persona-ask-nav-next persona-pointer-events-auto");d.type="button";let c=e===t-1;return d.textContent=c?o.submitAllLabel??qT:o.nextLabel??FT,d.setAttribute("data-ask-user-action",c?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Ws=e=>{let t=e.getAttribute(Dv);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},$v=(e,t)=>{e.setAttribute(Dv,JSON.stringify(t))},sn=e=>{let t=Number(e.getAttribute(Of)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},eE=(e,t)=>{e.setAttribute(Of,String(Math.max(0,Math.floor(t))))},Ra=e=>{let t=Number(e.getAttribute(Df)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},qr=e=>e.getAttribute(_f)==="true",tE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let n={};return t.forEach((r,a)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(o,i)){let d=o[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},oE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},mc=(e,t)=>{let{payload:o}=ur(t),n=rl(o),r=Ws(e),a={},i=new Set;return n.forEach((d,c)=>{let u=typeof d?.question=="string"?d.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,c)&&(a[u]=r[c]))}),a},Vv=e=>{let t=Ws(e),o=sn(e),n=t[o],r=new Set;typeof n=="string"?r.add(n):Array.isArray(n)&&n.forEach(c=>r.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{let u=c.getAttribute("data-option-label")??"",p=r.has(u);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(a).map(c=>c.getAttribute("data-option-label")??"")),d=e.querySelector('[data-ask-free-text-input="true"]');d&&(typeof n=="string"&&n.length>0&&!i.has(n)?(d.value=n,d.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):d.value="")},jv=e=>{if(!qr(e))return;let t=Ws(e),o=sn(e),n=t[o],r=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let d=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=d.length===0}},Nf=(e,t,o)=>{let n=fc(o),r=zT(e),{payload:a,complete:i}=ur(t),d=qr(e),c=sn(e),u=Ra(e),p=d?GT(a,c):KT(a),m=!!p?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=d?`${c+1}/${u}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let P=typeof p?.question=="string"?p.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!i)}let T=e.querySelector('[data-ask-pill-list="true"]');if(T){let P=YT(p,n,i,r);T.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(qv(n,r))}let w=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!w?e.appendChild(JT(n)):(!m||d)&&w&&w.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(d){let P=ZT(c,u,n);k?k.replaceWith(P):e.appendChild(P)}else k&&k.remove();Vv(e),jv(e)},nE=(e,t,o)=>{let n=fc(t),r=jT(n),a=e.toolCall.id,i=rl(o),d=Math.max(1,i.length),c=d>1,u=tE(e,i),p=c?oE(e,d):0,m=I("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ia,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(Df,String(d)),m.setAttribute(Of,String(p)),m.setAttribute(_f,c?"true":"false"),m.setAttribute(_v,r),$v(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Fv(m,n);let h=I("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=I("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let x=I("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",h.appendChild(x),m.appendChild(h);let w=I("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),m.appendChild(w),r!=="rows"&&m.appendChild(qv(n,r)),Nf(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},rE=(e,t,o)=>{let{payload:n}=ur(t),r=Math.max(1,rl(n).length);r>Ra(e)&&(e.setAttribute(Df,String(r)),r>1&&!qr(e)&&e.setAttribute(_f,"true")),Nf(e,t,o)},zv=(e,t)=>{let o=I("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let n=fc(t);Fv(o,n);let r=I("span","persona-ask-stub-label"),{complete:a}=ur(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},Ha=(e,t,o)=>{if(!o||!cr(e)||fc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${Ia}]`).forEach(u=>{u.getAttribute(Ia)!==r&&u.remove()});let i=o.querySelector(`[${Ia}="${Nv(r)}"]`);if(i){rE(i,e,t);return}let{payload:d}=ur(e),c=nE(e,t,d);o.appendChild(c)},$r=(e,t)=>{if(!e)return;let o=t?`[${Ia}="${Nv(t)}"]`:`[${Ia}]`;e.querySelectorAll(o).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},Ff=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Vr=(e,t)=>{let o=Ws(e),n=sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,$v(e,o),Vv(e),jv(e)},gc=(e,t,o,n)=>{let r=Ra(e),a=Math.max(0,Math.min(r-1,n));eE(e,a),Nf(e,t,o)};var Fn="suggest_replies";var Uf={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},hc={name:Fn,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:Uf,origin:"sdk",annotations:{readOnlyHint:!0}},Gv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Bs=e=>e.variant==="tool"&&e.toolCall?.name===Fn,qf=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let n=o.flatMap(r=>{if(typeof r=="string"){let d=r.trim();return d?[d]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let i={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(i.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(i.description=a.description.trim()),[i]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},yc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Bs(o))continue;let n=qf(o.toolCall?.args);return n.length>0?n:null}return null},Kv=new Set,sE=(e,t,o)=>{let n=`${e}:${t}:${o}`;Kv.has(n)||(Kv.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},jr=e=>{let t=e?.suggestions?.followUps,o=e?.features?.suggestReplies,n=i=>{let d=t?.[i],c=o?.[i];d===void 0||c===void 0||d!==c&&sE(i,c,d)};e&&(n("enabled"),n("expose"));let r=t?.enabled??o?.enabled??!0,a=r?t?.expose??o?.expose??!1:!1;return{enabled:r,expose:a}};var $f={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ol,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},Vf={name:nl,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:$f,origin:"sdk",annotations:{readOnlyHint:!0}},Wa=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(Vf),jr(e).expose&&t.push(hc),t};var pr=Zt(pc(),1),bc=e=>e.replace(/\\n/g,`
5
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),vc=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},aE=e=>{let t=e.completedAt??Date.now(),o=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Xv=e=>e.status==="complete"?aE(e):e.status==="pending"?"Waiting":"",iE=e=>{let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Qv=e=>e.status==="complete"?iE(e):"Using tool...",xc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},al=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xc(t)},Cc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xc(t)},jf=(e,t,o)=>{if(!t)return o;let n=e.name?.trim()||"tool",r=al(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,r)},Sc=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),n=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,i;for(;(i=r.exec(o))!==null;)i.index>a&&sl(n,o.slice(a,i.index),[]),i[1]!==void 0?sl(n,i[1],["bold"]):i[2]!==void 0?sl(n,i[2],["italic"]):i[3]!==void 0&&sl(n,i[3],["dim"]),a=i.index+i[0].length;return a<o.length&&sl(n,o.slice(a),[]),n},sl=(e,t,o)=>{let n=t.split("{duration}");for(let r=0;r<n.length;r++)n[r]&&e.push({text:n[r],styles:o}),r<n.length-1&&e.push({text:"{duration}",styles:o,isDuration:!0})},lE=()=>{let e=null,t=0,o=n=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
1
+ "use strict";var AgentWidget=(()=>{var fT=Object.create;var ac=Object.defineProperty;var mT=Object.getOwnPropertyDescriptor;var gT=Object.getOwnPropertyNames;var hT=Object.getPrototypeOf,yT=Object.prototype.hasOwnProperty;var fo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var iv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),bT=(e,t)=>{for(var o in t)ac(e,o,{get:t[o],enumerable:!0})},lv=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of gT(t))!yT.call(e,r)&&r!==o&&ac(e,r,{get:()=>t[r],enumerable:!(n=mT(t,r))||n.enumerable});return e};var Zt=(e,t,o)=>(o=e!=null?fT(hT(e)):{},lv(t||!e||!e.__esModule?ac(o,"default",{value:e,enumerable:!0}):o,e)),vT=e=>lv(ac({},"__esModule",{value:!0}),e);var Of=iv(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Allow=ye.ALL=ye.COLLECTION=ye.ATOM=ye.SPECIAL=ye.INF=ye._INFINITY=ye.INFINITY=ye.NAN=ye.BOOL=ye.NULL=ye.OBJ=ye.ARR=ye.NUM=ye.STR=void 0;ye.STR=1;ye.NUM=2;ye.ARR=4;ye.OBJ=8;ye.NULL=16;ye.BOOL=32;ye.NAN=64;ye.INFINITY=128;ye._INFINITY=256;ye.INF=ye.INFINITY|ye._INFINITY;ye.SPECIAL=ye.NULL|ye.BOOL|ye.INF|ye.NAN;ye.ATOM=ye.STR|ye.NUM|ye.SPECIAL;ye.COLLECTION=ye.ARR|ye.OBJ;ye.ALL=ye.ATOM|ye.COLLECTION;ye.Allow={STR:ye.STR,NUM:ye.NUM,ARR:ye.ARR,OBJ:ye.OBJ,NULL:ye.NULL,BOOL:ye.BOOL,NAN:ye.NAN,INFINITY:ye.INFINITY,_INFINITY:ye._INFINITY,INF:ye.INF,SPECIAL:ye.SPECIAL,ATOM:ye.ATOM,COLLECTION:ye.COLLECTION,ALL:ye.ALL};ye.default=ye.Allow});var fc=iv(no=>{"use strict";var OT=no&&no.__createBinding||(Object.create?(function(e,t,o,n){n===void 0&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}):(function(e,t,o,n){n===void 0&&(n=o),e[n]=t[o]})),DT=no&&no.__exportStar||function(e,t){for(var o in e)o!=="default"&&!Object.prototype.hasOwnProperty.call(t,o)&&OT(t,e,o)};Object.defineProperty(no,"__esModule",{value:!0});no.Allow=no.MalformedJSON=no.PartialJSON=no.parseJSON=no.parse=void 0;var mo=Of();Object.defineProperty(no,"Allow",{enumerable:!0,get:function(){return mo.Allow}});DT(Of(),no);var uc=class extends Error{};no.PartialJSON=uc;var pc=class extends Error{};no.MalformedJSON=pc;function Wv(e,t=mo.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return _T(e.trim(),t)}no.parseJSON=Wv;var _T=(e,t)=>{let o=e.length,n=0,r=h=>{throw new uc(`${h} at position ${n}`)},a=h=>{throw new pc(`${h} at position ${n}`)},i=()=>(m(),n>=o&&r("Unexpected end of input"),e[n]==='"'?d():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||mo.Allow.NULL&t&&o-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||mo.Allow.BOOL&t&&o-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||mo.Allow.BOOL&t&&o-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||mo.Allow.INFINITY&t&&o-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||mo.Allow._INFINITY&t&&1<o-n&&o-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||mo.Allow.NAN&t&&o-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):p()),d=()=>{let h=n,y=!1;for(n++;n<o&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(h,++n-Number(y)))}catch(x){a(String(x))}else if(mo.Allow.STR&t)try{return JSON.parse(e.substring(h,n-Number(y))+'"')}catch{return JSON.parse(e.substring(h,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,m();let h={};try{for(;e[n]!=="}";){if(m(),n>=o&&mo.Allow.OBJ&t)return h;let y=d();m(),n++;try{let x=i();h[y]=x}catch(x){if(mo.Allow.OBJ&t)return h;throw x}m(),e[n]===","&&n++}}catch{if(mo.Allow.OBJ&t)return h;r("Expected '}' at end of object")}return n++,h},u=()=>{n++;let h=[];try{for(;e[n]!=="]";)h.push(i()),m(),e[n]===","&&n++}catch{if(mo.Allow.ARR&t)return h;r("Expected ']' at end of array")}return n++,h},p=()=>{if(n===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(mo.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(y))}}let h=n;for(e[n]==="-"&&n++;e[n]&&",]}".indexOf(e[n])===-1;)n++;n==o&&!(mo.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(h,n))}catch{e.substring(h,n)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(h,e.lastIndexOf("e")))}catch(x){a(String(x))}}},m=()=>{for(;n<o&&`
2
+ \r `.includes(e[n]);)n++};return i()},NT=Wv;no.parse=NT});var k0={};bT(k0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>jf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Vf,ASK_USER_QUESTION_TOOL_NAME:()=>rl,AgentWidgetClient:()=>_s,AgentWidgetSession:()=>qa,AttachmentManager:()=>qs,BrowserSpeechEngine:()=>Ns,DEFAULT_COMPONENTS:()=>cg,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>jc,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>$o,DEFAULT_PALETTE:()=>lg,DEFAULT_SEMANTIC:()=>dg,DEFAULT_WIDGET_CONFIG:()=>st,HistoryProviderError:()=>sn,PRESETS:()=>wh,PRESET_FULLSCREEN:()=>Sh,PRESET_MINIMAL:()=>Ch,PRESET_SHOP:()=>xh,ReadAloudController:()=>Ua,SUGGEST_REPLIES_CLIENT_TOOL:()=>yc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>qf,SUGGEST_REPLIES_TOOL_NAME:()=>Un,THEME_ZONES:()=>FC,VERSION:()=>qn,WEBMCP_TOOL_PREFIX:()=>tl,applyFeaturePreferences:()=>oh,applyThemeVariables:()=>$s,attachHeaderToContainer:()=>zs,buildComposer:()=>Xs,buildDefaultHeader:()=>Eg,buildHeader:()=>yr,buildHeaderWithLayout:()=>ti,buildMinimalHeader:()=>Pg,builtInClientToolsForDispatch:()=>_a,canonicalArtifactDisplayMode:()=>ko,collectEnrichedPageContext:()=>$w,componentRegistry:()=>vn,createActionManager:()=>$l,createAgentExperience:()=>ju,createAskUserQuestionBubble:()=>Kv,createBubbleWithLayout:()=>wS,createCSATFeedback:()=>qu,createComboButton:()=>vu,createComponentMiddleware:()=>Sw,createComponentStreamParser:()=>Nu,createDefaultSanitizer:()=>Lf,createDirectivePostprocessor:()=>fv,createDropdownMenu:()=>Ks,createFlexibleJsonStreamParser:()=>Jv,createIconButton:()=>Gs,createImagePart:()=>kc,createJsonStreamParser:()=>Tc,createLabelButton:()=>Tg,createLocalStorageAdapter:()=>Du,createMarkdownProcessor:()=>Zi,createMarkdownProcessorFromConfig:()=>el,createMessageActions:()=>Wg,createNPSFeedback:()=>$u,createPlainTextParser:()=>Ac,createRegexJsonParser:()=>Mc,createSplitButton:()=>gS,createStandardBubble:()=>oi,createTextPart:()=>rn,createTheme:()=>Al,createThemeObserver:()=>Ya,createToggleGroup:()=>mS,createTypingIndicator:()=>Qs,createWidgetHostLayout:()=>jl,createXmlParser:()=>Ec,defaultActionHandlers:()=>Zs,defaultJsonActionParser:()=>ql,defaultParseRules:()=>bh,detectColorScheme:()=>Ml,directivePostprocessor:()=>mv,ensureAskUserQuestionSheet:()=>Da,escapeHtml:()=>pr,extractComponentDirectiveFromMessage:()=>Uu,fileToImagePart:()=>ox,formatEnrichedContext:()=>Vw,generateAssistantMessageId:()=>Vr,generateMessageId:()=>Rv,generateStableSelector:()=>vh,generateUserMessageId:()=>Wa,getActiveTheme:()=>Yr,getColorScheme:()=>du,getDisplayText:()=>Pc,getHeaderLayout:()=>kg,getImageParts:()=>tx,getPreset:()=>zw,hasComponentDirective:()=>Vl,hasImages:()=>Fa,headerLayouts:()=>xu,initAgentWidget:()=>Rw,isAskUserQuestionMessage:()=>fr,isComponentDirectiveType:()=>Cw,isDockedMountMode:()=>Ct,isHistoryProviderError:()=>Ax,isSuggestRepliesMessage:()=>Ds,isWebMcpToolName:()=>qr,isWelcomeVisible:()=>ts,latestAgentSuggestions:()=>bc,listRegisteredStreamAnimations:()=>vg,loadMarkdownParsers:()=>lc,markdownPostprocessor:()=>kf,mergeWithDefaults:()=>Xa,normalizeContent:()=>ex,normalizeMediaType:()=>$r,onMarkdownParsersReady:()=>Ha,parseAskUserQuestionPayload:()=>mr,parseSuggestRepliesPayload:()=>$f,parseWidgetPreferenceSlice:()=>th,pickBestVoice:()=>ul,pluginRegistry:()=>Ul,registerIcons:()=>Ox,registerStreamAnimationPlugin:()=>Ja,removeAskUserQuestionSheet:()=>Kr,renderComponentDirective:()=>Fu,renderLoadingIndicatorWithFallback:()=>Hg,renderLucideIcon:()=>ue,resolveArtifactDisplay:()=>Bf,resolveArtifactDisplayMode:()=>Fn,resolveConfigPreferences:()=>Fl,resolveDockConfig:()=>Io,resolveSanitizer:()=>dc,resolveTokens:()=>iu,resolveWelcomeConfig:()=>bn,stripWebMcpPrefix:()=>Wf,themeToCssVariables:()=>lu,unregisterStreamAnimationPlugin:()=>bg,validateImageFile:()=>nx,validateTheme:()=>ug});var gt=e=>{let{fallbackImport:t,resetOnSetLoader:o=!1}=e,n=null,r=null,a=null;return{setLoader:p=>{n=p,o&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(n??t)().then(m=>(r=m,m)).catch(m=>{throw a=null,m}),a),provide:p=>{r=p},getSync:()=>r}};var{setLoader:xT,load:CT,provide:_0,getSync:Pf}=gt({fallbackImport:()=>import("./markdown-parsers-entry")}),ic=new Set,ST=()=>{let e=[...ic];ic.clear();for(let t of e)try{t()}catch{}},dv=xT,lc=()=>{let e=Pf();return e?Promise.resolve(e):CT().then(t=>(ST(),t))},Ha=e=>Pf()?()=>{}:(ic.add(e),()=>{ic.delete(e)});var Nn=Pf;var wT=e=>{if(!e)return;let t={},o=e;if(o.heading){let n=o.heading;t.heading=(r,a,i)=>n({type:"heading",raw:i,depth:a,text:r,tokens:[]})}if(o.code){let n=o.code;t.code=(r,a,i)=>n({type:"code",raw:"",text:r,lang:a,escaped:i})}if(o.blockquote){let n=o.blockquote;t.blockquote=r=>n({type:"blockquote",raw:"",text:r,tokens:[]})}if(o.table){let n=o.table;t.table=(r,a)=>n({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:a})}if(o.link){let n=o.link;t.link=(r,a,i)=>n({type:"link",raw:"",href:r,title:a??null,text:i,tokens:[]})}if(o.image){let n=o.image;t.image=(r,a,i)=>n({type:"image",raw:"",href:r,title:a??null,text:i})}if(o.list){let n=o.list;t.list=(r,a,i)=>n({type:"list",raw:"",ordered:a,start:i,loose:!1,items:[],itemsHtml:r})}if(o.listitem){let n=o.listitem;t.listitem=(r,a,i)=>n({type:"list_item",raw:"",task:a,checked:i,loose:!1,text:r,tokens:[]})}if(o.paragraph){let n=o.paragraph;t.paragraph=r=>n({type:"paragraph",raw:"",text:r,tokens:[]})}if(o.codespan){let n=o.codespan;t.codespan=r=>n({type:"codespan",raw:"",text:r})}if(o.strong){let n=o.strong;t.strong=r=>n({type:"strong",raw:"",text:r,tokens:[]})}if(o.em){let n=o.em;t.em=r=>n({type:"em",raw:"",text:r,tokens:[]})}if(o.del){let n=o.del;t.del=r=>n({type:"del",raw:"",text:r,tokens:[]})}if(o.html){let n=o.html;t.html=r=>n({type:"html",raw:r,text:r})}if(o.text){let n=o.text;t.text=r=>n({type:"text",raw:r,text:r})}if(o.checkbox){let n=o.checkbox;t.checkbox=r=>n({checked:r})}return o.hr&&(t.hr=o.hr),o.br&&(t.br=o.br),t},Zi=e=>{let t=null;return o=>{let n=Nn();if(!n)return pr(o);if(!t){let{Marked:r}=n,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let i=wT(e?.renderer);i&&t.use({renderer:i})}return t.parse(o)}},el=e=>e?Zi({markedOptions:e.options,renderer:e.renderer}):Zi(),AT=Zi(),kf=e=>AT(e),pr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),uv=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),cv=e=>`%%FORM_PLACEHOLDER_${e}%%`,pv=(e,t)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let i=cv(t.length);return t.push({token:i,type:String(a.type)}),i}}catch{return n}return n}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,r)=>{let a=cv(t.length);return t.push({token:a,type:r}),a}),o},fv=e=>{let t=el(e);return o=>{let n=[],r=pv(o,n),a=t(r);return n.forEach(({token:i,type:d})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${uv(d)}"></div>`;a=a.replace(c,p)}),a}},mv=e=>{let t=[],o=pv(e,t),n=kf(o);return t.forEach(({token:r,type:a})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${uv(a)}"></div>`;n=n.replace(i,c)}),n};var MT={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},TT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Lf=()=>{let e=null;return t=>{let o=Nn();if(!o)return pr(t);if(!e){let{DOMPurify:n}=o;e=n(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let i=a.attrValue;i.toLowerCase().startsWith("data:")&&!TT.test(i)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,MT)}},dc=e=>e===!1?null:typeof e=="function"?e:Lf();var gv=/^\s*\|?[\s:|-]*-[\s:|-]*$/,hv=e=>e.includes("|"),yv=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(o=>o.trim())},ET=e=>`| ${e.join(" | ")} |`,PT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,kT=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),bv=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
+ `),o=!1;for(let n=0;n<t.length-1;n++){let r=t[n],a=t[n+1];if(!hv(r)||gv.test(r)||!gv.test(a))continue;let i=yv(r).length;if(i<1)continue;let d=PT(i);t[n+1]!==d&&(t[n+1]=d,o=!0);let c=n+2;for(;c<t.length;c++){let u=t[c];if(u.trim()===""||!hv(u))break;let p=ET(kT(yv(u),i));t[c]!==p&&(t[c]=p,o=!0)}n=c-1}return o?t.join(`
4
+ `):e};var vv="var(--persona-md-table-scroll-fade, 24px)",xv=new WeakSet;function Sv(e){e.querySelectorAll("table").forEach(o=>{if(o.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",o.replaceWith(r),r.appendChild(o)})}function Cv(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let n=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty("--persona-fade-l",n<=1?"0px":vv),e.style.setProperty("--persona-fade-r",r<=1?"0px":vv)}function If(e){xv.has(e)||(xv.add(e),e.addEventListener("scroll",t=>{let o=t.target;o?.classList?.contains("persona-table-scroll")&&Cv(o)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Cv)}var tl="webmcp:",Rf=new Map,Av=e=>{Rf.clear();for(let t of e){let o=t.title?.trim();o&&Rf.set(t.name,o)}},cc=e=>Rf.get(Wf(e)),Hf=null,Mv=e=>{Hf=e};function Tv(e){if(e.length===0)return"0:empty";let t=e.map(o=>[o.name,o.description??"",o.parametersSchema?JSON.stringify(o.parametersSchema):"",o.origin??"",o.annotations?JSON.stringify(o.annotations):""].join("")).sort();return`${e.length}:${LT(t.join(""))}`}function wv(e,t){let o=3735928559^t,n=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);o=Math.imul(o^a,2654435761),n=Math.imul(n^a,1597334677)}return o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),4294967296*(2097151&n)+(o>>>0)}function LT(e){let t=wv(e,0).toString(36),o=wv(e,2654435761).toString(36);return`${t}.${o}`}var Wf=e=>e.startsWith(tl)?e.slice(tl.length):e,qr=e=>e.startsWith(tl),Ev=()=>Hf?Hf():import("@mcp-b/webmcp-polyfill");var{setLoader:IT,load:RT}=gt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")}),Pv=IT,kv=RT;function ko(e){return e==="card"?"collapsed":e}function $r(e){return e.split(";",1)[0].trim().toLowerCase()}function HT(e,t){if(!e)return;let o=Object.entries(e);for(let[r,a]of o)if($r(r)===t)return{mode:ko(a),selector:$r(r)};let n=`${t.split("/",1)[0]}/*`;for(let[r,a]of o)if($r(r)===n)return{mode:ko(a),selector:n}}function Bf(e,t){let o=e?.display,n=typeof o=="string"?{default:o}:o??{};if(t.file&&n.files){if(typeof n.files=="string")return{mode:ko(n.files),matchedBy:{type:"files"}};let d=t.file.mimeType?$r(t.file.mimeType):void 0,c=d?HT(n.files.byMediaType,d):void 0;if(d&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:d,selector:c.selector}};if(n.files.default)return{mode:ko(n.files.default),matchedBy:{type:"files"}}}let r=n.byKind?.[t.artifactType];if(r)return{mode:ko(r),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 i=t.presentation?.preferredMode;return i?{mode:ko(i),matchedBy:{type:"preferredMode"}}:n.default?{mode:ko(n.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Fn(e,t){return Bf(e,t).mode}function ol(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var WT="agent_",BT="flow_";function Lv(e){return e.startsWith(WT)?{kind:"agentId",agentId:e}:e.startsWith(BT)?{kind:"flowId",flowId:e}:null}function Iv(e,t){let o=e.trim();if(!o)throw new Error("[Persona] `target` is empty.");let n=o.indexOf(":");if(n>0){let i=o.slice(0,n),d=o.slice(n+1);if(i==="runtype"){let u=Lv(d);if(u)return u;throw new Error(`[Persona] target "runtype:${d}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(d).payload}}let r=Lv(o);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(o).payload};throw new Error(`[Persona] target "${o}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${o}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Rv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Wa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Vr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Hv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var jr=Zt(fc(),1);var I=(e,t)=>{let o=document.createElement(e);return t&&(o.className=t),o};var Y=(e,t={},...o)=>{let n=document.createElement(e);if(t.className&&(n.className=t.className),t.text!==void 0&&(n.textContent=t.text),t.attrs)for(let[a,i]of Object.entries(t.attrs))n.setAttribute(a,i);if(t.style){let a=n.style,i=t.style;for(let d of Object.keys(i)){let c=i[d];c!=null&&(a[d]=c)}}let r=o.filter(a=>a!=null);return r.length>0&&n.append(...r),n},go=(...e)=>e.filter(Boolean).join(" ");var rl="ask_user_question",nl=8,Ba="data-persona-ask-sheet-for",FT="Other",UT="Other\u2026",Ov="Type your own answer here",Dv="Send",qT="Next",$T="Back",VT="Submit all",jT="Skip",zT=3,Df="data-ask-current-index",_f="data-ask-question-count",_v="data-ask-answers",Nf="data-ask-grouped",Nv="data-ask-layout",KT=e=>e.layout==="pills"?"pills":"rows",GT=e=>e.getAttribute(Nv)==="pills"?"pills":"rows",Bv=!1,Fv=e=>e.replace(/["\\]/g,"\\$&"),fr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===rl,mc=e=>e?.features?.askUserQuestion??{},mr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:o};let n=t.chunks;if(!n||n.length===0)return{payload:null,complete:o};try{let r=n.join(""),a=(0,jr.parse)(r,jr.STR|jr.OBJ|jr.ARR);if(a&&typeof a=="object")return{payload:a,complete:o}}catch{}return{payload:null,complete:o}},sl=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>nl&&!Bv&&(Bv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${nl}.`)),t.slice(0,nl)},XT=e=>sl(e)[0]??null,QT=(e,t)=>sl(e)[t]??null,Uv=(e,t)=>{let o=t.styles;o&&(o.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",o.sheetBackground),o.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",o.sheetBorder),o.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",o.sheetShadow),o.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",o.pillBackground),o.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",o.pillBackgroundSelected),o.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",o.pillTextColor),o.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",o.pillTextColorSelected),o.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",o.pillBorderRadius),o.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",o.customInputBackground))},qv=(e,t,o)=>{if(e!=="rows")return null;let n=I("span","persona-ask-row-affordance");if(n.setAttribute("aria-hidden","true"),t){let r=I("span","persona-ask-row-check");n.appendChild(r)}else{let r=I("span","persona-ask-row-badge");r.textContent=String(o+1),n.appendChild(r)}return n},YT=(e,t,o,n)=>{let a=I("button",o==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",n?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),o==="rows"){let i=I("span","persona-ask-row-content"),d=I("span","persona-ask-row-label");if(d.textContent=e.label,i.appendChild(d),e.description){let u=I("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}a.appendChild(i);let c=qv(o,n,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},JT=e=>{let o=I("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return o.setAttribute("aria-hidden","true"),o},ZT=(e,t,o,n)=>{let a=I("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!o){for(let p=0;p<zT;p++)a.appendChild(JT(n));return a}if(c.forEach((p,m)=>{a.appendChild(YT(p,m,n,i))}),e?.allowFreeText!==!1){let p=n==="rows"?FT:UT;if(n==="rows"){let m=I("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(c.length)),m.setAttribute("data-ask-other-row","true");let h=I("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??Ov,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let x=qv(n,i,c.length);x&&m.appendChild(x),a.appendChild(m)}else{let m=I("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??p,a.appendChild(m)}}return a},$v=(e,t)=>{let n=I("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");n.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Ov,r.setAttribute("data-ask-free-text-input","true"),n.appendChild(r),t!=="rows"){let a=I("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Dv,a.setAttribute("data-ask-user-action","submit-free-text"),n.appendChild(a)}return n},eE=e=>{let t=I("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let o=I("button","persona-ask-multi-submit persona-pointer-events-auto");return o.type="button",o.textContent=e.submitLabel??Dv,o.setAttribute("data-ask-user-action","submit-multi"),o.disabled=!0,t.appendChild(o),t},tE=(e,t,o)=>{let n=I("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");n.setAttribute("data-ask-nav-row","true");let r=I("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=o.backLabel??$T,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,n.appendChild(r);let a=I("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=I("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=o.skipLabel??jT,i.setAttribute("data-ask-user-action","skip"),a.appendChild(i);let d=I("button","persona-ask-nav-next persona-pointer-events-auto");d.type="button";let c=e===t-1;return d.textContent=c?o.submitAllLabel??VT:o.nextLabel??qT,d.setAttribute("data-ask-user-action",c?"submit-all":"next"),d.disabled=!0,a.appendChild(d),n.appendChild(a),n},Os=e=>{let t=e.getAttribute(_v);if(!t)return{};try{let o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return{}}},Vv=(e,t)=>{e.setAttribute(_v,JSON.stringify(t))},nn=e=>{let t=Number(e.getAttribute(Df)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},oE=(e,t)=>{e.setAttribute(Df,String(Math.max(0,Math.floor(t))))},Oa=e=>{let t=Number(e.getAttribute(_f)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},zr=e=>e.getAttribute(Nf)==="true",nE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionAnswers;if(!o||typeof o!="object")return{};let n={};return t.forEach((r,a)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(o,i)){let d=o[i];(typeof d=="string"||Array.isArray(d))&&(n[a]=d)}}),n},rE=(e,t)=>{let o=e.agentMetadata?.askUserQuestionIndex;return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(t-1,Math.floor(o)))},gc=(e,t)=>{let{payload:o}=mr(t),n=sl(o),r=Os(e),a={},i=new Set;return n.forEach((d,c)=>{let u=typeof d?.question=="string"?d.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,c)&&(a[u]=r[c]))}),a},jv=e=>{let t=Os(e),o=nn(e),n=t[o],r=new Set;typeof n=="string"?r.add(n):Array.isArray(n)&&n.forEach(c=>r.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{let u=c.getAttribute("data-option-label")??"",p=r.has(u);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(a).map(c=>c.getAttribute("data-option-label")??"")),d=e.querySelector('[data-ask-free-text-input="true"]');d&&(typeof n=="string"&&n.length>0&&!i.has(n)?(d.value=n,d.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):d.value="")},zv=e=>{if(!zr(e))return;let t=Os(e),o=nn(e),n=t[o],r=typeof n=="string"&&n.length>0||Array.isArray(n)&&n.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let d=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=d.length===0}},Ff=(e,t,o)=>{let n=mc(o),r=GT(e),{payload:a,complete:i}=mr(t),d=zr(e),c=nn(e),u=Oa(e),p=d?QT(a,c):XT(a),m=!!p?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=d?`${c+1}/${u}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let P=typeof p?.question=="string"?p.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!i)}let T=e.querySelector('[data-ask-pill-list="true"]');if(T){let P=ZT(p,n,i,r);T.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith($v(n,r))}let w=e.querySelector('[data-ask-multi-actions="true"]');!d&&m&&!w?e.appendChild(eE(n)):(!m||d)&&w&&w.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(d){let P=tE(c,u,n);k?k.replaceWith(P):e.appendChild(P)}else k&&k.remove();jv(e),zv(e)},sE=(e,t,o)=>{let n=mc(t),r=KT(n),a=e.toolCall.id,i=sl(o),d=Math.max(1,i.length),c=d>1,u=nE(e,i),p=c?rE(e,d):0,m=I("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ba,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(_f,String(d)),m.setAttribute(Df,String(p)),m.setAttribute(Nf,c?"true":"false"),m.setAttribute(Nv,r),Vv(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),n.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${n.slideInMs}ms`),Uv(m,n);let h=I("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=I("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let x=I("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",h.appendChild(x),m.appendChild(h);let w=I("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),m.appendChild(w),r!=="rows"&&m.appendChild($v(n,r)),Ff(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},aE=(e,t,o)=>{let{payload:n}=mr(t),r=Math.max(1,sl(n).length);r>Oa(e)&&(e.setAttribute(_f,String(r)),r>1&&!zr(e)&&e.setAttribute(Nf,"true")),Ff(e,t,o)},Kv=(e,t)=>{let o=I("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.setAttribute("data-bubble-type","ask-user-question");let n=mc(t);Uv(o,n);let r=I("span","persona-ask-stub-label"),{complete:a}=mr(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",o.appendChild(r),o},Da=(e,t,o)=>{if(!o||!fr(e)||mc(t).enabled===!1)return;let r=e.toolCall.id;o.querySelectorAll(`[${Ba}]`).forEach(u=>{u.getAttribute(Ba)!==r&&u.remove()});let i=o.querySelector(`[${Ba}="${Fv(r)}"]`);if(i){aE(i,e,t);return}let{payload:d}=mr(e),c=sE(e,t,d);o.appendChild(c)},Kr=(e,t)=>{if(!e)return;let o=t?`[${Ba}="${Fv(t)}"]`:`[${Ba}]`;e.querySelectorAll(o).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},Uf=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Gr=(e,t)=>{let o=Os(e),n=nn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete o[n]:o[n]=t,Vv(e,o),jv(e),zv(e)},hc=(e,t,o,n)=>{let r=Oa(e),a=Math.max(0,Math.min(r-1,n));oE(e,a),Ff(e,t,o)};var Un="suggest_replies";var qf={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},yc={name:Un,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:qf,origin:"sdk",annotations:{readOnlyHint:!0}},Xv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ds=e=>e.variant==="tool"&&e.toolCall?.name===Un,$f=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let o=t?.suggestions;if(!Array.isArray(o))return[];let n=o.flatMap(r=>{if(typeof r=="string"){let d=r.trim();return d?[d]:[]}if(!r||typeof r!="object")return[];let a=r;if(typeof a.label!="string"||!a.label.trim())return[];let i={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(i.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(i.description=a.description.trim()),[i]});return n.length>4?(console.warn(`[persona] suggest_replies: ${n.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),n.slice(0,4)):n},bc=e=>{for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user")return null;if(!Ds(o))continue;let n=$f(o.toolCall?.args);return n.length>0?n:null}return null},Gv=new Set,iE=(e,t,o)=>{let n=`${e}:${t}:${o}`;Gv.has(n)||(Gv.add(n),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Xr=e=>{let t=e?.suggestions?.followUps,o=e?.features?.suggestReplies,n=i=>{let d=t?.[i],c=o?.[i];d===void 0||c===void 0||d!==c&&iE(i,c,d)};e&&(n("enabled"),n("expose"));let r=t?.enabled??o?.enabled??!0,a=r?t?.expose??o?.expose??!1:!1;return{enabled:r,expose:a}};var Vf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:nl,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},jf={name:rl,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:Vf,origin:"sdk",annotations:{readOnlyHint:!0}},_a=e=>{let t=[],o=e?.features?.askUserQuestion;return o?.expose===!0&&o.enabled!==!1&&t.push(jf),Xr(e).expose&&t.push(yc),t};var gr=Zt(fc(),1),vc=e=>e.replace(/\\n/g,`
5
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),xc=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},lE=e=>{let t=e.completedAt??Date.now(),o=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Qv=e=>e.status==="complete"?lE(e):e.status==="pending"?"Waiting":"",dE=e=>{let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Yv=e=>e.status==="complete"?dE(e):"Using tool...",Cc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},il=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Cc(t)},Sc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Cc(t)},zf=(e,t,o)=>{if(!t)return o;let n=e.name?.trim()||"tool",r=il(e);return t.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,r)},wc=(e,t)=>{let o=e.replace(/\{toolName\}/g,t),n=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,i;for(;(i=r.exec(o))!==null;)i.index>a&&al(n,o.slice(a,i.index),[]),i[1]!==void 0?al(n,i[1],["bold"]):i[2]!==void 0?al(n,i[2],["italic"]):i[3]!==void 0&&al(n,i[3],["dim"]),a=i.index+i[0].length;return a<o.length&&al(n,o.slice(a),[]),n},al=(e,t,o)=>{let n=t.split("{duration}");for(let r=0;r<n.length;r++)n[r]&&e.push({text:n[r],styles:o}),r<n.length-1&&e.push({text:"{duration}",styles:o,isDuration:!0})},cE=()=>{let e=null,t=0,o=n=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=n.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
6
6
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,d=n.match(i);if(d&&d[1])try{return d[1].replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=o(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},il=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},wc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ac=()=>{let e=lE();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Mc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,pr.parse)(o,pr.STR|pr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?bc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=bc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Yv=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?bc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?bc(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return i(a.on_load_text)||i(a.text)||null;case"message":case"message_and_click":case"checkout":return i(a.text)||null;default:return i(a.text)||i(a.display_text)||i(a.message)||null}return i(a.text)||i(a.display_text)||i(a.message)||i(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let i=a.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let d=(0,pr.parse)(a,pr.STR|pr.OBJ),c=r(d);c!==null&&(t=c)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Tc=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Jv="4.21.0";var Un=Jv;var Ba="[Image]";function Zv(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ec(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Oa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ex(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function an(e){return{type:"text",text:e}}function Pc(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function tx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function ox(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var nx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],cE=["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"],fr=[...nx,...cE];function uE(e){return nx.includes(e)||e.startsWith("image/")}function kc(e){return uE(e.type)}function rx(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function sx(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;kc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function ax(e,t=fr,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function pE(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ix(e,t){let o=pE(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var fE=["user","assistant","system"],mE=0;function lx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Lc(e){return typeof e=="string"?e:void 0}function gE(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?an(t.text):null;case"image":return typeof t.image=="string"?Pc(t.image,{mimeType:Lc(t.mimeType),alt:Lc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?rx(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Lc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Lc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function hE(e,t){let o=lx(t),n=e.map(i=>lx(i.timestamp)),r=new Array(e.length),a=0;for(;a<n.length;){let i=n[a];if(i!==null){r[a]=i,a+=1;continue}let d=a;for(;d+1<n.length&&n[d+1]===null;)d+=1;let c=d-a+1,u=a>0?r[a-1]:null,p=d+1<n.length?n[d+1]:null,m=p!==null&&o!==null?Math.min(p,o):p??o;for(let h=0;h<c;h+=1)r[a+h]=m!==null?m-(c-h):u!==null?u+h+1:mE+h;a=d+1}return r.map(i=>new Date(i).toISOString())}function dx(e,t){let o=hE(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!fE.includes(r.role))return;let i=r.role,d=o[a];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};n.push({id:r.id,role:i,content:"",createdAt:d,agentMetadata:c});return}if(typeof r.displayContent=="string"){n.push({id:r.id,role:i,content:r.displayContent,createdAt:d});return}if(typeof r.content=="string"){n.push({id:r.id,role:i,content:r.content,createdAt:d});return}if(Array.isArray(r.content)){let c=r.content.map(gE).filter(p=>p!==null),u=Ec(c);n.push({id:r.id,role:i,content:u||(Oa(c)?Ba:""),createdAt:d,...c.length>0&&{contentParts:c}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function ll(e){let t=e.content;if(typeof t!="string"||t==="")return;let o=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof o=="string"&&o===t))return t}function dl(e,t){let o=new Map;for(let n of e)o.set(n.id,n);for(let n of t)o.set(n.id,n);return[...o.values()].sort((n,r)=>{let a=new Date(n.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(i)&&a!==i)return a-i;let d=n.sequence??0,c=r.sequence??0;return d!==c?d-c:n.id.localeCompare(r.id)})}var yE="https://api.runtype.com/v1/dispatch",cx="https://api.runtype.com",Fe=class extends Error{constructor(t,o,n){super(o),this.name="HistoryClientError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}},ux=32768,zf=49152,px=e=>{let t=e??{},o=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:o,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},fx=e=>"reason"in e?e.reason:void 0,mx="The identity proof was not admitted; account history is unavailable",gx="The identity proof was rejected",hx="The request carried no visitor credential",yx="The stored visitor belongs to a different signed-in user",Kf=(e,t)=>e instanceof Fe&&e.code===t;function bE(e){let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var Gf=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function vE(e){switch(e){case"json":return Mc;case"regex-json":return Ac;case"xml":return Tc;default:return wc}}var bx=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function xE(e,t){if(!e)return t;let o=e.trim(),n=t.trim();if(o.length===0)return t;if(n.length===0)return e;let r=bx(o);if(!bx(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=il(e);return il(t)!==null&&i===null?t:e}var Os=class{constructor(t={},o={}){this.config=t;this.historyInternals=o;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??yE,this.headers={"Content-Type":"application/json","X-Persona-Version":Un,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??vE(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return Pv().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:wv,getToolDisplayTitle:dc,loadPolyfill:Tv});return this.pendingWebMcpConfirmHandler!==void 0&&n.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=n,n}).catch(o=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",o),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,n){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,o,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:n,targetProviders:r}=this.config;if(!n)return{agentId:t,flowId:o};let a=Lv(n,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||cx}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let o=await this.initSession(),n=!1;for(;;){let r=o.conversationId,a=await this.readVisitorToken();if(o.durableRecovery?.enabled!==!0||!r||!a)throw new Fe("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,d=new URLSearchParams({sessionId:o.sessionId,after:t.after}),c=await fetch(`${i}?${d}`,{method:"GET",headers:{"X-Persona-Version":Un,"X-Visitor-Token":a},signal:t.signal});if(c.status===401&&!n){n=!0,o=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let o=this.getHistoryIdentityStatus(),n=o.state===t.state&&fx(o)===fx(t);if(this.historyIdentityStatus=t,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let o=this.isHistoryCapable()&&!t.omitVisitorFields,n=!t.omitVisitorFields,r=null;(o||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let a=this.routing(),i=a.agentId??a.flowId,d=o||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...o&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(o||n)&&r?{visitorToken:r}:{},...o&&t.identityProof?{identityProof:t.identityProof}:{},...d?{conversationId:d}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un},body:JSON.stringify(c)});if(u.status===400&&n){let m={...c};delete m.durableRecovery,u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un},body:JSON.stringify(m)})}if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(o&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),d)throw new Fe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new Fe("history_disabled","Durable recovery is disabled for this surface"):(o||t.durableResume)&&u.status===401&&m.error==="visitor_required"?new Fe("visitor_required","Visitor credential no longer resolves"):d&&u.status===404?new Fe("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):u.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let p=await u.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId??p.flow?.id?{targetId:p.targetId??p.flow?.id}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,o=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!o)return this.ordinaryInit(t,!1);let n=await this.readVisitorToken();if(t&&n)try{let r=await this.createClientSession({conversationId:t,durableResume:o});return o&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Kf(r,"not_found")&&!Kf(r,"visitor_required")&&!Kf(r,"history_disabled"))throw r;return o&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,o){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.doOrdinaryInit(t,o)):this.doOrdinaryInit(t,o)}async doOrdinaryInit(t,o){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),a=await this.claimFirstConversation(r);return this.finishInit(a,t,o)}async reinitWithProof(t){let o=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:o,identityProof:t}),a=this.finishInit(r,n,!1);return this.clientSession=a,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),a}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,o,n){let r=t.conversationId;return r&&o&&(n||r!==o)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:o,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let o=!1;return{session:t,commit:()=>{o||(o=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{o=!0}}}async prepareConversationSession(t,o){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Fe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let n=o?.proof??null;if(!await this.readVisitorToken()&&!n)throw new Fe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let a=await this.createClientSession({conversationId:t,identityProof:n});return this.prepared(a)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:o})}historyUrl(t,o){let n=new URLSearchParams;for(let[a,i]of Object.entries(o))i===void 0||i===""||n.set(a,String(i));let r=n.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let o=this.config.features?.history?.scope;return o||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,o){let n=this.config.getIdentityProof;if(!n)return o&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;o&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await n()??null}catch{throw o&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Fe("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Fe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return o&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,o,n){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(o);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Fe("proof_not_admitted",mx);return r}async readErrorCode(t){let o=await t.json().catch(()=>({}));return typeof o.error=="string"?o.error:typeof o.message=="string"?o.message:""}async recoverFromUnauthorized(t,o,n){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Fe("invalid_identity_proof",gx);if(r.includes("visitor token required"))throw new Fe("visitor_token_missing",hx);if(r.includes("visitor_identity_mismatch")){if(!o)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Fe("visitor_identity_mismatch",yx);return this.reinitWithProof(o)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Fe("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,o){let n=await this.readErrorCode(t);if(t.status===404)return new Fe("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new Fe("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&n.includes("identity_proof_not_admitted"))return o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Fe("proof_not_admitted",mx);if(t.status===401){let r=n.toLowerCase();return r.includes("invalid_identity_proof")?(o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Fe("invalid_identity_proof",gx)):r.includes("visitor token required")?new Fe("visitor_token_missing",hx):r.includes("visitor_identity_mismatch")?new Fe("visitor_identity_mismatch",yx):new Fe("unauthorized",n||"History request was not authorized")}return new Fe("request_failed",n||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,o,n){let r=t?.toLowerCase()??null;if(o){if(r==="admitted"){n&&this.setHistoryIdentityStatus({state:"verified"});return}throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Fe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Fe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Fe("identity_contract_violation","Server admitted an identity proof that was never sent");n&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,o){this.assertHistoryUsable();let n=o.trackIdentity!==!1,r=await this.initSession(),a=null;this.resolveHistoryScope(o.scope)==="verified-user"&&(a=await this.resolveIdentityProof(r,n),a&&(r=await this.bindIdentity(r,a,n)));let i=this.historyInternals.visitorStore,d=!1;for(;;){let c=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!o.visitorTokenOptional)throw new Fe("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...o.query,sessionId:r.sessionId}),{method:o.method,headers:{"X-Persona-Version":Un,...u?{"X-Visitor-Token":u}:{},...a?{"X-Identity-Proof":a}:{},...o.body!==void 0?{"Content-Type":"application/json"}:{}},...o.body!==void 0?{body:JSON.stringify(o.body)}:{},...o.keepalive?{keepalive:!0}:{}});if(p.status===401&&!d){d=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),a,n);continue}if(!p.ok)throw await this.historyErrorFor(p,n);let m=p.headers.get("X-History-Identity-Status"),h=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new Fe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,a!==null,n),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Fe("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let o=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(o?.data)?o.data:[]).map(px),nextCursor:typeof o?.nextCursor=="string"?o.nextCursor:null}}async getConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...o?.messageCursor?{messageCursor:o.messageCursor}:{}},...o?.scope?{scope:o.scope}:{}}),r=n&&typeof n.conversation=="object"&&n.conversation!==null?n.conversation:n;return{summary:px(r),messages:Array.isArray(n?.messages)?n.messages:[],nextMessageCursor:typeof n?.nextMessageCursor=="string"?n.nextMessageCursor:null,conversationRevision:typeof n?.conversationRevision=="string"?n.conversationRevision:null}}async finalizeDisplayProjections(t,o){this.assertHistoryUsable();let n=0;for(let c of o){let u=c.displayContent.length;if(u>ux)throw new Fe("payload_too_large",`displayContent exceeds the ${ux} character limit`);n+=u}if(n>zf)throw new Fe("payload_too_large",`Display projection batch exceeds the ${zf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,a=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:o},scope:"browser",keepalive:n<=zf,trackIdentity:!1}),d=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return d&&this.clientSession?.conversationId===t&&(r?.revision()??0)===a&&this.historyInternals.setStoredConversationRevision?.(d),{conversationRevision:d}}async deleteConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...o?.scope?{scope:o.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async deleteAllConversations(t){let o=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){let n=Rv();this.currentClientTurnId=n;let r=()=>this.currentClientTurnId===n,a=i=>{r()&&o(i)};o({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:x}),x}let d=await this.buildPayload(t.messages),c=i.durableRecovery?.enabled===!0?await this.readVisitorToken():null,u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,p=this.isHistoryCapable(),m={sessionId:i.sessionId,messages:t.messages.filter(Gf).map(x=>{let T=p?ll(x):void 0;return{id:x.id,role:x.role,content:x.contentParts??x.llmContent??x.rawContent??x.content,...T!==void 0&&{displayContent:T}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:n,...t.interrupt&&{submitMode:"interrupt"}},{response:h,commit:y}=await this.sendWithClientToolsDiff(i.sessionId,d.clientTools,x=>{let T={...m,...x};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",T),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Un,...c?{"X-Visitor-Token":c}:{}},body:JSON.stringify(T),signal:t.signal})});if(!h.ok){let x=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let w=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:w}),w}if(h.status===429){let w=new Error(x.hint||"Message limit reached for this session.");throw a({type:"error",error:w}),w}if(h.status===410&&x.error==="conversation_deleted"){let w=new Fe("conversation_deleted","This conversation was deleted");throw a({type:"error",error:w}),w}let T=new Error(x.error||"Failed to send message");throw a({type:"error",error:T}),T}if(!h.body){let x=new Error("No response body received");throw a({type:"error",error:x}),x}y(),a({type:"status",status:"connected"});try{await this.streamResponse(h.body,a,t.assistantMessageId)}finally{a({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!(d instanceof Fe)&&!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&a({type:"error",error:d}),d}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,n,r){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,n,r)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(n,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,n,r){let a=!!(o&&o.length>0),i=a?Mv(o):void 0,d=this.clientToolsFingerprintSessionId===t,c=a&&d&&this.lastSentClientToolsFingerprint===i,u=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let h=0;;h++){if(m=await n({...a&&(p||!c)&&o?{clientTools:o}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),m.status===409&&h===0&&a&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,n){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||cx}/resume`,i,d=null;if(r){let p=await this.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(d=await this.readVisitorToken())}let c={"Content-Type":"application/json",...d?{"X-Visitor-Token":d}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let u={executionId:t,toolOutputs:o,streamResponse:n?.streamResponse??!0,...n?.after?{after:n.after}:{}};if(i&&(u.sessionId=i),r&&i){let p=[...Wa(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(i,p,y=>{let x={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(a,{method:"POST",headers:c,body:JSON.stringify(x),signal:n?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(a,{method:"POST",headers:c,body:JSON.stringify(u),signal:n?.signal})}latestMentionContext(t){for(let o=t.length-1;o>=0;o--){let n=t[o];if(n.role==="user")return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async buildContextAggregate(t){let o={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let n=this.latestMentionContext(t);return n&&Object.assign(o,n),Object.keys(o).length?o:null}normalizeComposerOptions(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}applyInlineAgentModel(t,o){let n=o?.selectedModelId;return!n||!("model"in t)?t:this.config.composer?.models?.some(a=>a.id===n)?{...t,model:n}:t}async buildAgentPayload(t,o){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Gf).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),a=this.normalizeComposerOptions(o),i={agent:this.applyInlineAgentModel(this.config.agent??{agentId:n},a),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};a&&(i.composerOptions=a);let d=[...Wa(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];d.length>0&&(i.clientTools=d);let c=await this.buildContextAggregate(t);return c&&(i.context=c),i}async buildPayload(t,o){let n=t.slice().filter(Gf).sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),r=this.routing(),a={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[u,p]of Object.entries(r.targetPayload))u!=="messages"&&(a[u]=p);let i=[...Wa(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];i.length>0&&(a.clientTools=i);let d=await this.buildContextAggregate(t);d&&(a.context=d);let c=this.normalizeComposerOptions(o);if(c&&(a.composerOptions=c),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...a},config:this.config});if(u&&typeof u=="object"){let p=u;return a.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=a.clientTools),p}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return a}async handleCustomSSEEvent(t,o,n,r,a,i){if(!this.parseSSEEvent)return!1;try{let d=await this.parseSSEEvent(t);if(d===null)return!1;let c=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=m,r(m),m},u=p=>n.current?n.current:c(p);if(d.text!==void 0){d.partId!==void 0&&i.current!==null&&d.partId!==i.current&&(n.current&&(n.current.streaming=!1,r(n.current)),c(d.partId)),d.partId!==void 0&&(i.current=d.partId);let p=u(d.partId);d.partId!==void 0&&!p.partId&&(p.partId=d.partId),p.content+=d.text,r(p)}return d.done&&(n.current&&(n.current.streaming=!1,r(n.current)),i.current=null,o({type:"status",status:"idle"})),d.error&&(i.current=null,o({type:"error",error:new Error(d.error)})),!0}catch(d){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",d),!1}}async streamResponse(t,o,n,r){let a=t.getReader(),i=new TextDecoder,d="",c=Date.now(),u=0,p=()=>c+u++,m=B=>{let ee=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,S=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,U=B.tools?B.tools.map(q=>({...q,chunks:q.chunks?[...q.chunks]:void 0})):void 0;return{...B,reasoning:ee,toolCall:S,tools:U}},h=B=>{if(B.role!=="assistant"||B.variant)return!0;let ee=Array.isArray(B.contentParts)&&B.contentParts.length>0,S=typeof B.rawContent=="string"&&B.rawContent.trim()!=="";return typeof B.content=="string"&&B.content.trim()!==""||ee||S||!!B.stopReason},y=B=>{h(B)&&o({type:"message",message:m(B)})},x=null,T=null,w={current:null},k={current:null},P=null,R="",b=new Map,A=new Map,C=new Map,L=new Map,F=new Map,X={lastId:null,byStep:new Map},G={lastId:null,byCall:new Map},E=B=>{if(B==null)return null;try{return String(B)}catch{return null}},O=B=>E(B.stepId??B.step_id??B.step??B.parentId??B.flowStepId??B.flow_step_id),D=B=>E(B.callId??B.call_id??B.requestId??B.request_id??B.toolCallId??B.tool_call_id??B.stepId??B.step_id),W=n,te=!1,Q=()=>{if(x)return x;let B,ee="",S=P;return!te&&W?(B=W,te=!0,ee=r??""):W&&S?B=`${W}_${S}`:B=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:B,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(x),x},de=(B,ee)=>{X.lastId=ee,B&&X.byStep.set(B,ee)},pe=(B,ee)=>{let S=B.reasoningId??B.id,U=O(B);if(S){let $=String(S);return de(U,$),$}if(U){let $=X.byStep.get(U);if($)return X.lastId=$,$}if(X.lastId&&!ee)return X.lastId;if(!ee)return null;let q=`reason-${p()}`;return de(U,q),q},Ce=B=>{let ee=L.get(B);if(ee)return ee;let S={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:B,status:"streaming",chunks:[]}};return L.set(B,S),y(S),S},Ee=(B,ee)=>{G.lastId=ee,B&&G.byCall.set(B,ee)},ge=new Set,Ke=new Map,Bt=new Set,Le=new Map,j=B=>{if(!B)return!1;let ee=B.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},qe=(B,ee)=>{let S=B.toolId??B.id,U=D(B);if(S){let $=String(S);return Ee(U,$),$}if(U){let $=G.byCall.get(U);if($)return G.lastId=$,$}if(G.lastId&&!ee)return G.lastId;if(!ee)return null;let q=`tool-${p()}`;return Ee(U,q),q},Ge=B=>{let ee=F.get(B);if(ee)return ee;let S={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:B,status:"pending"}};return F.set(B,S),y(S),S},Ae=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let ee=Number(B);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let S=Date.parse(B);if(!Number.isNaN(S))return S}return Date.now()},De=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},he=new Map,gt=new Map,dn=new Map,Js=(B,ee,S)=>{let U=dn.get(B);U||(U=[],dn.set(B,U));let q=0,$=U.length;for(;q<$;){let ne=q+$>>>1;U[ne].seq<ee?q=ne+1:$=ne}U[q]?.seq===ee?U[q]={seq:ee,text:S}:U.splice(q,0,{seq:ee,text:S});let oe="";for(let ne=0;ne<U.length;ne++)oe+=U[ne].text;return oe},oo=(B,ee)=>{let S=De(ee),U=gt.get(B.id),q=xE(U,S);B.rawContent=q;let $=he.get(B.id),oe=$e=>{let Ht=B.content??"";$e.trim()!==""&&(Ht.trim().length===0||$e.startsWith(Ht)||$e.trimStart().startsWith(Ht.trim()))&&(B.content=$e)},ne=()=>{if($){let $e=$.close?.();$e instanceof Promise&&$e.catch(()=>{})}he.delete(B.id),gt.delete(B.id),B.streaming=!1,y(B)};if(!$){oe(S),ne();return}let ie=il(q);if(ie!==null&&ie.trim()!==""){oe(ie),ne();return}let xe=$e=>{let Ht=typeof $e=="string"?$e:$e?.text??null;if(Ht!==null&&Ht.trim()!=="")return Ht;let wt=$.getExtractedText();return wt!==null&&wt.trim()!==""?wt:S},ht;try{ht=$.processChunk(q)}catch{oe(S),ne();return}if(ht instanceof Promise){ht.then($e=>{oe(xe($e)),ne()}).catch(()=>{oe(S),ne()});return}oe(xe(ht)),ne()},Xo=null,Sn=(B,ee,S,U)=>{B.rawContent=ee,he.has(B.id)||he.set(B.id,this.createStreamParser());let q=he.get(B.id),$=ee.trim().startsWith("{")||ee.trim().startsWith("[");if($&&gt.set(B.id,ee),q.__isPlainTextParser===!0){B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B);return}let ne=q.processChunk(ee);if(ne instanceof Promise)ne.then(ie=>{let xe=typeof ie=="string"?ie:ie?.text??null;xe!==null&&xe.trim()!==""?(B.content=xe,y(B)):!$&&!ee.trim().startsWith("<")&&(B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B))}).catch(()=>{B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B)});else{let ie=typeof ne=="string"?ne:ne?.text??null;ie!==null&&ie.trim()!==""?(B.content=ie,y(B)):!$&&!ee.trim().startsWith("<")&&(B.content=U!==void 0?ee:B.content+S,gt.delete(B.id),he.delete(B.id),B.rawContent=void 0,y(B))}},Rt=(B,ee)=>{let S=ee??B.content;if(S==null||S===""){B.streaming=!1,y(B);return}let q=gt.get(B.id)??De(S);B.rawContent=q;let $=he.get(B.id),oe=null,ne=!1;if($&&(oe=$.getExtractedText(),oe===null&&(oe=il(q)),oe===null)){let ie=$.processChunk(q);ie instanceof Promise?(ne=!0,ie.then(xe=>{let ht=typeof xe=="string"?xe:xe?.text??null;ht!==null&&(B.content=ht,B.streaming=!1,he.delete(B.id),gt.delete(B.id),y(B))}).catch(()=>{})):oe=typeof ie=="string"?ie:ie?.text??null}if(!ne){oe!==null&&oe.trim()!==""?B.content=oe:gt.has(B.id)||(B.content=De(S));let ie=he.get(B.id);if(ie){let xe=ie.close?.();xe instanceof Promise&&xe.catch(()=>{}),he.delete(B.id)}gt.delete(B.id),B.streaming=!1,y(B)}},Jr=(B,ee,S)=>{let U=A.get(B);if(U)return U;let q={id:`nested-${ee}-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...S?{variant:S}:{},...S==="reasoning"?{reasoning:{id:B,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return A.set(B,q),y(q),q},Ao=[],wn,di=new Map,Zr=0,po="agent",ci=!1,Tt=null,ut=null,cn=new Map,jl=this.config.iterationDisplay??"separate";for(wn=()=>{for(let B=0;B<Ao.length;B++){let ee=Ao[B].payloadType,S=Ao[B].payload;if(!ci&&po!=="flow"&&typeof S.stepType=="string"&&(po="flow"),ee==="reasoning_start"){let U=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(U&&q){b.set(U,q),Jr(U,q,"reasoning");continue}let $=pe(S,!0)??`reason-${p()}`,oe=Ce($);oe.reasoning=oe.reasoning??{id:$,status:"streaming",chunks:[]},oe.reasoning.startedAt=oe.reasoning.startedAt??Ae(S.startedAt??S.timestamp),oe.reasoning.completedAt=void 0,oe.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(oe.reasoning.scope=S.scope),oe.streaming=!0,oe.reasoning.status="streaming",y(oe)}else if(ee==="reasoning_delta"){let U=typeof S.id=="string"?S.id:null;if(U&&b.has(U)&&A.has(U)){let ne=A.get(U),ie=S.reasoningText??S.text??S.delta??"";ie&&S.hidden!==!0&&ne.reasoning&&(ne.reasoning.chunks.push(String(ie)),y(ne));continue}let q=pe(S,!1)??pe(S,!0)??`reason-${p()}`,$=Ce(q);$.reasoning=$.reasoning??{id:q,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??Ae(S.startedAt??S.timestamp);let oe=S.reasoningText??S.text??S.delta??"";if(oe&&S.hidden!==!0){let ne=typeof S.sequenceIndex=="number"?S.sequenceIndex:void 0;if(ne!==void 0){let ie=Js(q,ne,String(oe));$.reasoning.chunks=[ie]}else $.reasoning.chunks.push(String(oe))}if($.reasoning.status=S.done?"complete":"streaming",S.done){$.reasoning.completedAt=Ae(S.completedAt??S.timestamp);let ne=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-ne)}$.streaming=$.reasoning.status!=="complete",y($)}else if(ee==="reasoning_complete"){let U=typeof S.id=="string"?S.id:null;if(U&&b.has(U)&&A.has(U)){let ie=A.get(U);if(ie.reasoning){let xe=typeof S.text=="string"?S.text:"";xe&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(xe),ie.reasoning.status="complete",ie.streaming=!1,y(ie)}b.delete(U),A.delete(U);continue}let q=pe(S,!1)??pe(S,!0)??`reason-${p()}`,$=typeof S.text=="string"?S.text:"";!L.get(q)&&($||S.scope==="loop")&&Ce(q);let oe=L.get(q);if(oe?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(oe.reasoning.scope=S.scope),$&&oe.reasoning.chunks.length===0&&oe.reasoning.chunks.push($),oe.reasoning.status="complete",oe.reasoning.completedAt=Ae(S.completedAt??S.timestamp);let ie=oe.reasoning.startedAt??Date.now();oe.reasoning.durationMs=Math.max(0,(oe.reasoning.completedAt??Date.now())-ie),oe.streaming=!1,y(oe)}let ne=O(S);ne&&X.byStep.delete(ne)}else if(ee==="tool_start"){x&&(x.streaming=!1,y(x),x=null),typeof S.iteration=="number"&&(Zr=S.iteration);let U=(typeof S.toolCallId=="string"?S.toolCallId:void 0)??qe(S,!0)??`tool-${p()}`,q=S.toolName??S.name;if(j(q)){ge.add(U);continue}Ee(D(S),U);let $=Ge(U),oe=$.toolCall??{id:U,status:"pending"};oe.name=q??oe.name,oe.status="running",S.parameters!==void 0?oe.args=S.parameters:S.args!==void 0&&(oe.args=S.args),oe.startedAt=oe.startedAt??Ae(S.startedAt??S.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,$.toolCall=oe,$.streaming=!0,S.executionId&&($.agentMetadata={executionId:S.executionId,iteration:S.iteration}),y($)}else if(ee==="tool_output_delta"){let U=qe(S,!1)??qe(S,!0)??`tool-${p()}`;if(ge.has(U))continue;let q=Ge(U),$=q.toolCall??{id:U,status:"running"};$.startedAt=$.startedAt??Ae(S.startedAt??S.timestamp);let oe=S.text??S.delta??S.message??"";oe&&($.chunks=$.chunks??[],$.chunks.push(String(oe))),$.status="running",q.toolCall=$,q.streaming=!0;let ne=S.agentContext;(ne||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:ne?.executionId??S.executionId,iteration:ne?.iteration??S.iteration}),y(q)}else if(ee==="tool_complete"){let U=qe(S,!1)??qe(S,!0)??`tool-${p()}`;if(ge.has(U)){ge.delete(U);continue}let q=Ge(U),$=q.toolCall??{id:U,status:"running"};$.status="complete",S.result!==void 0&&($.result=S.result),typeof S.duration=="number"&&($.duration=S.duration),$.completedAt=Ae(S.completedAt??S.timestamp);let oe=S.duration??S.executionTime;if(typeof oe=="number")$.durationMs=oe;else{let xe=$.startedAt??Date.now();$.durationMs=Math.max(0,($.completedAt??Date.now())-xe)}q.toolCall=$,q.streaming=!1;let ne=S.agentContext;(ne||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:ne?.executionId??S.executionId,iteration:ne?.iteration??S.iteration}),y(q);let ie=D(S);ie&&G.byCall.delete(ie)}else if(ee==="await"&&S.toolName){let U=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,q=U??S.toolId??`local-${p()}`,$=Ge(q),oe=S.toolName,ne=S.origin==="webmcp"&&!_r(oe)?`webmcp:${oe}`:oe,ie=_r(ne),xe=$.toolCall??{id:q,status:"pending"};xe.name=ne,xe.args=S.parameters,xe.status=ie?"running":"complete",xe.chunks=xe.chunks??[],xe.startedAt=xe.startedAt??Ae(S.startedAt??S.timestamp??S.awaitedAt),ie?(xe.completedAt=void 0,xe.duration=void 0,xe.durationMs=void 0):xe.completedAt=xe.completedAt??xe.startedAt,$.toolCall=xe,$.streaming=!1,$.agentMetadata={...$.agentMetadata,executionId:S.executionId??$.agentMetadata?.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},y($)}else if(ee==="text_start"){let U=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(U&&q){b.set(U,q);continue}let $=x;$&&(po==="flow"?(Rt($),Xo=$):($.streaming=!1,y($)),x=null),P=typeof S.id=="string"?S.id:P,R=""}else if(ee==="text_delta"){let U=typeof S.id=="string"?S.id:null,q=U?b.get(U):void 0;if(U&&q){let ne=typeof S.delta=="string"?S.delta:"",ie=(C.get(U)??"")+ne;if(C.set(U,ie),ie.trim()==="")continue;let xe=Jr(U,q);xe.agentMetadata={...xe.agentMetadata,executionId:S.executionId,parentToolId:q},Sn(xe,ie,ne,void 0);continue}if(P=typeof S.id=="string"?S.id:P,po==="flow"){let ne=typeof S.delta=="string"?S.delta:"";if(R+=ne,R.trim()==="")continue;let ie=Q();ie.agentMetadata={executionId:S.executionId,iteration:S.iteration},Sn(ie,R,ne,void 0),T=ie;continue}let $=typeof S.delta=="string"?S.delta:"";R+=$;let oe=Q();oe.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:Tt??void 0,agentName:ut?.agentName},Sn(oe,R,$,void 0),T=oe}else if(ee==="text_complete"){let U=typeof S.id=="string"?S.id:null;if(U&&b.has(U)){let $=A.get(U);$&&Rt($),b.delete(U),C.delete(U),A.delete(U);continue}let q=x;q&&(po==="flow"?(Rt(q),Xo=q):((q.content??"")===""&&typeof S.text=="string"&&(q.content=S.text),q.streaming=!1,y(q)),x=null),P=null,R=""}else if(ee==="step_complete"){let U=S.stepType,q=S.executionType;if(U==="tool"||q==="context")continue;if(S.success===!1){let $=S.error,oe=typeof $=="string"&&$!==""?$:$!=null&&typeof $=="object"&&Reflect.has($,"message")?String($.message??"Step failed"):"Step failed";o({type:"error",error:new Error(oe)});let ne=x;ne&&ne.streaming&&(ne.streaming=!1,y(ne)),o({type:"status",status:"idle"});continue}{let $=Xo;Xo=null;let oe=S.stopReason,ne=S.result?.response;if($)oe&&($.stopReason=oe),ne!=null?oo($,ne):$.streaming!==!1&&(he.delete($.id),gt.delete($.id),$.streaming=!1,y($));else{let ie=ne!=null&&ne!=="";if(ie||oe){let xe=Q();oe&&(xe.stopReason=oe),ie?Rt(xe,ne):(xe.streaming=!1,y(xe))}}continue}}else if(ee==="execution_start")po=S.kind==="flow"?"flow":"agent",ci=!0,po==="agent"&&(ut={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??"",status:"running",currentIteration:0,maxTurns:S.maxTurns??1,startedAt:Ae(S.startedAt)});else if(ee==="turn_start"){let U=typeof S.iteration=="number"?S.iteration:Zr;if(U!==Zr){if(ut&&(ut.currentIteration=U),jl==="separate"&&U>1){let q=x;q&&(q.streaming=!1,y(q),cn.set(U-1,q),x=null)}Zr=U}Tt=typeof S.id=="string"?S.id:null,T=null}else if(ee==="tool_input_delta"){let U=S.toolCallId??G.lastId;if(U){let q=F.get(U);q?.toolCall&&(q.toolCall.chunks=q.toolCall.chunks??[],q.toolCall.chunks.push(S.delta??""),y(q))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let U=S.stopReason,q=x??T;if(U&&q!==null){let $=S.id;(!$||q.agentMetadata?.turnId===$)&&(q.stopReason=U,y(q))}Tt===S.id&&(Tt=null)}else if(ee==="media_start"){let U=String(S.id);di.set(U,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,role:typeof S.role=="string"?S.role:void 0,toolCallId:S.toolCallId,parts:[]})}else if(ee==="media_delta"){let U=di.get(String(S.id));U&&typeof S.delta=="string"&&U.parts.push(S.delta)}else if(ee==="media_complete"){let U=String(S.id),q=di.get(U);di.delete(U);let $=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",oe=typeof S.data=="string"?S.data:void 0,ne=typeof S.url=="string"?S.url:q&&q.parts.length>0?q.parts.join(""):void 0,ie=null;if(oe)ie={type:"media",data:oe,mediaType:$};else if(ne){let Ht=$.toLowerCase();ie={type:Ht==="image"||Ht.startsWith("image/")?"image-url":"file-url",url:ne,mediaType:$}}let xe=S.toolCallId??q?.toolCallId,ht=ie?[ie]:[],$e=[];for(let Ht of ht){if(!Ht||typeof Ht!="object")continue;let wt=Ht,es=typeof wt.type=="string"?wt.type:void 0,Bo=typeof wt.mediaType=="string"?wt.mediaType.toLowerCase():"",qt=null,fo="";if(es==="media"){let ao=typeof wt.data=="string"?wt.data:void 0;if(!ao)continue;fo=Bo.length>0?Bo:"application/octet-stream",qt=`data:${fo};base64,${ao}`}else if(es==="image-url"){let ao=typeof wt.url=="string"?wt.url:void 0;if(!ao)continue;fo=Bo,qt=ao}else if(es==="file-url"){let ao=typeof wt.url=="string"?wt.url:void 0;if(!ao)continue;fo=Bo,qt=ao}else continue;if(qt)if(es==="image-url"||fo.startsWith("image/"))$e.push({type:"image",image:qt,...fo.includes("/")?{mimeType:fo}:{}});else if(fo.startsWith("audio/"))$e.push({type:"audio",audio:qt,mimeType:fo});else if(fo.startsWith("video/"))$e.push({type:"video",video:qt,mimeType:fo});else{let ao=fo||"application/octet-stream";$e.push({type:"file",data:qt,mimeType:ao,filename:bE(ao)})}}if($e.length>0){let Ht=p(),wt=xe,Bo={id:`agent-media-${typeof wt=="string"&&wt.length>0?`${wt}-${Ht}`:String(Ht)}`,role:"assistant",content:"",contentParts:$e,createdAt:new Date().toISOString(),streaming:!1,sequence:Ht,agentMetadata:{executionId:S.executionId,iteration:typeof S.iteration=="number"?S.iteration:Zr}};y(Bo);let qt=x;qt&&(qt.streaming=!1,y(qt)),x=null,w.current=null}}else if(ee==="execution_complete"){let U=S.kind??po;U==="agent"&&ut&&(ut.status=S.success?"complete":"error",ut.completedAt=Ae(S.completedAt),ut.stopReason=S.stopReason);let q=x;q&&(U==="flow"&&q.streaming!==!1?Rt(q):(q.streaming=!1,y(q)),x=null),P=null,R="",Xo=null,o({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let U=typeof S.error=="string"?S.error:S.error?.message??"Execution error";o({type:"error",error:new Error(U)})}else if(ee!=="ping"){if(ee==="approval_start"){let U=S.approvalId??`approval-${p()}`,q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:"pending",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};y(q)}else if(ee==="step_await"&&S.awaitReason==="approval_required"){let U=S.approvalId??`approval-${p()}`,q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:"pending",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};y(q)}else if(ee==="approval_complete"){let U=S.approvalId;if(U){let $={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:U,status:S.decision??"approved",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:S.toolName??"",description:S.description??"",resolvedAt:Date.now()}};y($)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let U=S.artifactType,q=String(S.id),$=typeof S.title=="string"?S.title:void 0,oe=S.file,ne;oe&&typeof oe=="object"&&!Array.isArray(oe)&&typeof oe.path=="string"&&typeof oe.mimeType=="string"&&(ne={path:oe.path,mimeType:oe.mimeType,...typeof oe.language=="string"?{language:oe.language}:{}}),o({type:"artifact_start",id:q,artifactType:U,title:$,component:typeof S.component=="string"?S.component:void 0,...ne?{file:ne}:{}});let ie=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?{...S.props}:void 0;if(Le.set(q,{markdown:"",title:$,file:ne,...ie?{props:ie}:{}}),!Bt.has(q)){Bt.add(q);let xe=Nn(this.config.features?.artifacts,{artifactType:U,...ne?{file:ne}:{}}),ht=typeof S.component=="string"?S.component:void 0,$e={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:tl(xe,{artifactId:q,title:$,artifactType:U,status:"streaming",...ne?{file:ne}:{},...ht?{component:ht}:{}})};Ke.set(q,$e),y($e)}}else if(ee==="artifact_delta"){let U=String(S.id),q=typeof S.delta=="string"?S.delta:String(S.delta??"");o({type:"artifact_delta",id:U,artDelta:q});let $=Le.get(U);$&&($.markdown+=q)}else if(ee==="artifact_update"){let U=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};o({type:"artifact_update",id:String(S.id),props:U,component:typeof S.component=="string"?S.component:void 0});let q=Le.get(String(S.id));q&&(q.props={...q.props??{},...U})}else if(ee==="artifact_complete"){let U=String(S.id);o({type:"artifact_complete",id:U});let q=Ke.get(U);if(q){q.streaming=!1;try{let $=JSON.parse(q.rawContent??"{}");if($.props){$.props.status="complete";let oe=Le.get(U);oe?.markdown&&($.props.markdown=oe.markdown),oe?.file&&($.props.file=oe.file),$.component==="PersonaArtifactInline"&&oe?.props&&Object.keys(oe.props).length>0&&($.props.componentProps=oe.props)}q.rawContent=JSON.stringify($)}catch{}Le.delete(U),y(q),Ke.delete(U)}}}else if(ee==="transcript_insert"){let U=S.message;if(!U||typeof U!="object")continue;let q=String(U.id??`msg-${p()}`),$=U.role,ne={id:q,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:p()};if(y(ne),ne.rawContent)try{let xe=JSON.parse(ne.rawContent)?.props?.artifactId;typeof xe=="string"&&Bt.add(xe)}catch{}x=null,w.current=null,he.delete(q),gt.delete(q)}else if(ee==="error"){if(S.recoverable===!1&&S.error!=null&&S.error!==""){let U=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";o({type:"error",error:new Error(U)});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let U=null;if(S.error instanceof Error)U=S.error;else if(ee==="dispatch_error"){let q=S.message??S.error;q!=null&&q!==""&&(U=new Error(String(q)))}else{let q=S.error;typeof q=="string"&&q!==""?U=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(U=new Error(String(q.message??q)))}if(U){o({type:"error",error:U});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}}}}Ao.length=0};;){let{done:B,value:ee}=await a.read();if(B)break;d+=i.decode(ee,{stream:!0});let S=d.split(`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return d[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=t)return e!==null?{text:e,raw:n}:null;let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=o(n);return a!==null&&(e=a),t=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},ll=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ac=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Mc=()=>{let e=cE();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Tc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,gr.parse)(o,gr.STR|gr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?vc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=vc(r.text)))}catch{}return t=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Jv=e=>{let t=null,o=0,r=e||(a=>{if(!a||typeof a!="object")return null;let i=d=>typeof d=="string"?vc(d):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?vc(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return i(a.on_load_text)||i(a.text)||null;case"message":case"message_and_click":case"checkout":return i(a.text)||null;default:return i(a.text)||i(a.display_text)||i(a.message)||null}return i(a.text)||i(a.display_text)||i(a.message)||i(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let i=a.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(a.length<=o)return t!==null?{text:t,raw:a}:null;try{let d=(0,gr.parse)(a,gr.STR|gr.OBJ),c=r(d);c!==null&&(t=c)}catch{}return o=a.length,{text:t||"",raw:a}},close:()=>{}}},Ec=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Zv="4.21.1";var qn=Zv;var Na="[Image]";function ex(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pc(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Fa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function tx(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function rn(e){return{type:"text",text:e}}function kc(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function ox(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function nx(e,t=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var rx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],pE=["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"],hr=[...rx,...pE];function fE(e){return rx.includes(e)||e.startsWith("image/")}function Lc(e){return fE(e.type)}function sx(e,t,o){return{type:"file",data:e,mimeType:t,filename:o}}async function ax(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;Lc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},n.onerror=()=>o(new Error("Failed to read file")),n.readAsDataURL(e)})}function ix(e,t=hr,o=10*1024*1024){return t.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function mE(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function lx(e,t){let o=mE(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var gE=["user","assistant","system"],hE=0;function dx(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Ic(e){return typeof e=="string"?e:void 0}function yE(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?rn(t.text):null;case"image":return typeof t.image=="string"?kc(t.image,{mimeType:Ic(t.mimeType),alt:Ic(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?sx(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Ic(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Ic(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function bE(e,t){let o=dx(t),n=e.map(i=>dx(i.timestamp)),r=new Array(e.length),a=0;for(;a<n.length;){let i=n[a];if(i!==null){r[a]=i,a+=1;continue}let d=a;for(;d+1<n.length&&n[d+1]===null;)d+=1;let c=d-a+1,u=a>0?r[a-1]:null,p=d+1<n.length?n[d+1]:null,m=p!==null&&o!==null?Math.min(p,o):p??o;for(let h=0;h<c;h+=1)r[a+h]=m!==null?m-(c-h):u!==null?u+h+1:hE+h;a=d+1}return r.map(i=>new Date(i).toISOString())}function cx(e,t){let o=bE(e,t?.beforeCreatedAt),n=[];return e.forEach((r,a)=>{if(typeof r?.id!="string"||r.id===""||!gE.includes(r.role))return;let i=r.role,d=o[a];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};n.push({id:r.id,role:i,content:"",createdAt:d,agentMetadata:c});return}if(typeof r.displayContent=="string"){n.push({id:r.id,role:i,content:r.displayContent,createdAt:d});return}if(typeof r.content=="string"){n.push({id:r.id,role:i,content:r.content,createdAt:d});return}if(Array.isArray(r.content)){let c=r.content.map(yE).filter(p=>p!==null),u=Pc(c);n.push({id:r.id,role:i,content:u||(Fa(c)?Na:""),createdAt:d,...c.length>0&&{contentParts:c}});return}n.push({id:r.id,role:i,content:"",createdAt:d})}),n}function dl(e){let t=e.content;if(typeof t!="string"||t==="")return;let o=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof o=="string"&&o===t))return t}function cl(e,t){let o=new Map;for(let n of e)o.set(n.id,n);for(let n of t)o.set(n.id,n);return[...o.values()].sort((n,r)=>{let a=new Date(n.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(a)&&!Number.isNaN(i)&&a!==i)return a-i;let d=n.sequence??0,c=r.sequence??0;return d!==c?d-c:n.id.localeCompare(r.id)})}var vE="https://api.runtype.com/v1/dispatch",ux="https://api.runtype.com",qe=class extends Error{constructor(t,o,n){super(o),this.name="HistoryClientError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}},px=32768,Kf=49152,fx=e=>{let t=e??{},o=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:o,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},mx=e=>"reason"in e?e.reason:void 0,gx="The identity proof was not admitted; account history is unavailable",hx="The identity proof was rejected",yx="The request carried no visitor credential",bx="The stored visitor belongs to a different signed-in user",Gf=(e,t)=>e instanceof qe&&e.code===t;function xE(e){let t=e.toLowerCase(),n={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(n)return`attachment.${n}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var Xf=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function CE(e){switch(e){case"json":return Tc;case"regex-json":return Mc;case"xml":return Ec;default:return Ac}}var vx=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function SE(e,t){if(!e)return t;let o=e.trim(),n=t.trim();if(o.length===0)return t;if(n.length===0)return e;let r=vx(o);if(!vx(n))return e;if(!r||n===o||n.startsWith(o))return t;let i=ll(e);return ll(t)!==null&&i===null?t:e}var _s=class{constructor(t={},o={}){this.config=t;this.historyInternals=o;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??vE,this.headers={"Content-Type":"application/json","X-Persona-Version":qn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??CE(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return kv().then(o=>{let n=new o.WebMcpBridge(t,{recordToolDisplayTitles:Av,getToolDisplayTitle:cc,loadPolyfill:Ev});return this.pendingWebMcpConfirmHandler!==void 0&&n.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=n,n}).catch(o=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",o),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,o,n){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,o,n):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:o,target:n,targetProviders:r}=this.config;if(!n)return{agentId:t,flowId:o};let a=Iv(n,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ux}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let o=await this.initSession(),n=!1;for(;;){let r=o.conversationId,a=await this.readVisitorToken();if(o.durableRecovery?.enabled!==!0||!r||!a)throw new qe("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,d=new URLSearchParams({sessionId:o.sessionId,after:t.after}),c=await fetch(`${i}?${d}`,{method:"GET",headers:{"X-Persona-Version":qn,"X-Visitor-Token":a},signal:t.signal});if(c.status===401&&!n){n=!0,o=await this.recoverFromUnauthorized(await this.readErrorCode(c),null,!0);continue}if(!c.ok)throw await this.historyErrorFor(c,!0);return c}}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let o=this.getHistoryIdentityStatus(),n=o.state===t.state&&mx(o)===mx(t);if(this.historyIdentityStatus=t,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let o=this.isHistoryCapable()&&!t.omitVisitorFields,n=!t.omitVisitorFields,r=null;(o||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let a=this.routing(),i=a.agentId??a.flowId,d=o||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...o&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(o||n)&&r?{visitorToken:r}:{},...o&&t.identityProof?{identityProof:t.identityProof}:{},...d?{conversationId:d}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qn},body:JSON.stringify(c)});if(u.status===400&&n){let m={...c};delete m.durableRecovery,u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qn},body:JSON.stringify(m)})}if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(o&&u.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),d)throw new qe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw u.status===403&&m.error==="durable_recovery_disabled"?new qe("history_disabled","Durable recovery is disabled for this surface"):(o||t.durableResume)&&u.status===401&&m.error==="visitor_required"?new qe("visitor_required","Visitor credential no longer resolves"):d&&u.status===404?new qe("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):u.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let p=await u.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId??p.flow?.id?{targetId:p.targetId??p.flow?.id}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,o=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!o)return this.ordinaryInit(t,!1);let n=await this.readVisitorToken();if(t&&n)try{let r=await this.createClientSession({conversationId:t,durableResume:o});return o&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Gf(r,"not_found")&&!Gf(r,"visitor_required")&&!Gf(r,"history_disabled"))throw r;return o&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,o){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.doOrdinaryInit(t,o)):this.doOrdinaryInit(t,o)}async doOrdinaryInit(t,o){let n=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),a=await this.claimFirstConversation(r);return this.finishInit(a,t,o)}async reinitWithProof(t){let o=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:o,identityProof:t}),a=this.finishInit(r,n,!1);return this.clientSession=a,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),a}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,o,n){let r=t.conversationId;return r&&o&&(n||r!==o)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:o,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let o=!1;return{session:t,commit:()=>{o||(o=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{o=!0}}}async prepareConversationSession(t,o){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new qe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let n=o?.proof??null;if(!await this.readVisitorToken()&&!n)throw new qe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let a=await this.createClientSession({conversationId:t,identityProof:n});return this.prepared(a)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qn},body:JSON.stringify(r)});if(!a.ok){let i=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:t,type:o})}async submitCSATFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:t,comment:o})}async submitNPSFeedback(t,o){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:t,comment:o})}historyUrl(t,o){let n=new URLSearchParams;for(let[a,i]of Object.entries(o))i===void 0||i===""||n.set(a,String(i));let r=n.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let o=this.config.features?.history?.scope;return o||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,o){let n=this.config.getIdentityProof;if(!n)return o&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;o&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await n()??null}catch{throw o&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new qe("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new qe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return o&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,o,n){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(o);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new qe("proof_not_admitted",gx);return r}async readErrorCode(t){let o=await t.json().catch(()=>({}));return typeof o.error=="string"?o.error:typeof o.message=="string"?o.message:""}async recoverFromUnauthorized(t,o,n){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new qe("invalid_identity_proof",hx);if(r.includes("visitor token required"))throw new qe("visitor_token_missing",yx);if(r.includes("visitor_identity_mismatch")){if(!o)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new qe("visitor_identity_mismatch",bx);return this.reinitWithProof(o)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new qe("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,o){let n=await this.readErrorCode(t);if(t.status===404)return new qe("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new qe("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&n.includes("identity_proof_not_admitted"))return o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new qe("proof_not_admitted",gx);if(t.status===401){let r=n.toLowerCase();return r.includes("invalid_identity_proof")?(o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new qe("invalid_identity_proof",hx)):r.includes("visitor token required")?new qe("visitor_token_missing",yx):r.includes("visitor_identity_mismatch")?new qe("visitor_identity_mismatch",bx):new qe("unauthorized",n||"History request was not authorized")}return new qe("request_failed",n||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,o,n){let r=t?.toLowerCase()??null;if(o){if(r==="admitted"){n&&this.setHistoryIdentityStatus({state:"verified"});return}throw n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new qe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new qe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new qe("identity_contract_violation","Server admitted an identity proof that was never sent");n&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,o){this.assertHistoryUsable();let n=o.trackIdentity!==!1,r=await this.initSession(),a=null;this.resolveHistoryScope(o.scope)==="verified-user"&&(a=await this.resolveIdentityProof(r,n),a&&(r=await this.bindIdentity(r,a,n)));let i=this.historyInternals.visitorStore,d=!1;for(;;){let c=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!o.visitorTokenOptional)throw new qe("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...o.query,sessionId:r.sessionId}),{method:o.method,headers:{"X-Persona-Version":qn,...u?{"X-Visitor-Token":u}:{},...a?{"X-Identity-Proof":a}:{},...o.body!==void 0?{"Content-Type":"application/json"}:{}},...o.body!==void 0?{body:JSON.stringify(o.body)}:{},...o.keepalive?{keepalive:!0}:{}});if(p.status===401&&!d){d=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),a,n);continue}if(!p.ok)throw await this.historyErrorFor(p,n);let m=p.headers.get("X-History-Identity-Status"),h=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new qe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,a!==null,n),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new qe("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let o=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(o?.data)?o.data:[]).map(fx),nextCursor:typeof o?.nextCursor=="string"?o.nextCursor:null}}async getConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...o?.messageCursor?{messageCursor:o.messageCursor}:{}},...o?.scope?{scope:o.scope}:{}}),r=n&&typeof n.conversation=="object"&&n.conversation!==null?n.conversation:n;return{summary:fx(r),messages:Array.isArray(n?.messages)?n.messages:[],nextMessageCursor:typeof n?.nextMessageCursor=="string"?n.nextMessageCursor:null,conversationRevision:typeof n?.conversationRevision=="string"?n.conversationRevision:null}}async finalizeDisplayProjections(t,o){this.assertHistoryUsable();let n=0;for(let c of o){let u=c.displayContent.length;if(u>px)throw new qe("payload_too_large",`displayContent exceeds the ${px} character limit`);n+=u}if(n>Kf)throw new qe("payload_too_large",`Display projection batch exceeds the ${Kf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,a=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:o},scope:"browser",keepalive:n<=Kf,trackIdentity:!1}),d=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return d&&this.clientSession?.conversationId===t&&(r?.revision()??0)===a&&this.historyInternals.setStoredConversationRevision?.(d),{conversationRevision:d}}async deleteConversation(t,o){let n=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...o?.scope?{scope:o.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async deleteAllConversations(t){let o=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,o){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,o):this.isAgentMode()?this.dispatchAgent(t,o):this.dispatchProxy(t,o)}async dispatchClientToken(t,o){let n=Hv();this.currentClientTurnId=n;let r=()=>this.currentClientTurnId===n,a=i=>{r()&&o(i)};o({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:x}),x}let d=await this.buildPayload(t.messages),c=i.durableRecovery?.enabled===!0?await this.readVisitorToken():null,u=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,p=this.isHistoryCapable(),m={sessionId:i.sessionId,messages:t.messages.filter(Xf).map(x=>{let T=p?dl(x):void 0;return{id:x.id,role:x.role,content:x.contentParts??x.llmContent??x.rawContent??x.content,...T!==void 0&&{displayContent:T}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:n,...t.interrupt&&{submitMode:"interrupt"}},{response:h,commit:y}=await this.sendWithClientToolsDiff(i.sessionId,d.clientTools,x=>{let T={...m,...x};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",T),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":qn,...c?{"X-Visitor-Token":c}:{}},body:JSON.stringify(T),signal:t.signal})});if(!h.ok){let x=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let w=new Error("Session expired. Please refresh to continue.");throw a({type:"error",error:w}),w}if(h.status===429){let w=new Error(x.hint||"Message limit reached for this session.");throw a({type:"error",error:w}),w}if(h.status===410&&x.error==="conversation_deleted"){let w=new qe("conversation_deleted","This conversation was deleted");throw a({type:"error",error:w}),w}let T=new Error(x.error||"Failed to send message");throw a({type:"error",error:T}),T}if(!h.body){let x=new Error("No response body received");throw a({type:"error",error:x}),x}y(),a({type:"status",status:"connected"});try{await this.streamResponse(h.body,a,t.assistantMessageId)}finally{a({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!(d instanceof qe)&&!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&a({type:"error",error:d}),d}}async dispatchProxy(t,o){o({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o)}finally{o({type:"status",status:"idle"})}}async dispatchAgent(t,o){o({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw o({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(n),signal:t.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw o({type:"error",error:i}),i}o({type:"status",status:"connected"});try{await this.streamResponse(a.body,o,t.assistantMessageId)}finally{o({type:"status",status:"idle"})}}async processStream(t,o,n,r){o({type:"status",status:"connected"});try{await this.streamResponse(t,o,n,r)}finally{o({type:"status",status:"idle"})}}async resolveApproval(t,o){let n=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(n,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:o,streamResponse:!0})})}async sendWithClientToolsDiff(t,o,n,r){let a=!!(o&&o.length>0),i=a?Tv(o):void 0,d=this.clientToolsFingerprintSessionId===t,c=a&&d&&this.lastSentClientToolsFingerprint===i,u=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let h=0;;h++){if(m=await n({...a&&(p||!c)&&o?{clientTools:o}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),m.status===409&&h===0&&a&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,o,n){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ux}/resume`,i,d=null;if(r){let p=await this.initSession();i=p.sessionId,p.durableRecovery?.enabled===!0&&(d=await this.readVisitorToken())}let c={"Content-Type":"application/json",...d?{"X-Visitor-Token":d}:{},...this.headers};this.getHeaders&&Object.assign(c,await this.getHeaders());let u={executionId:t,toolOutputs:o,streamResponse:n?.streamResponse??!0,...n?.after?{after:n.after}:{}};if(i&&(u.sessionId=i),r&&i){let p=[..._a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(i,p,y=>{let x={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",x),fetch(a,{method:"POST",headers:c,body:JSON.stringify(x),signal:n?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(a,{method:"POST",headers:c,body:JSON.stringify(u),signal:n?.signal})}latestMentionContext(t){for(let o=t.length-1;o>=0;o--){let n=t[o];if(n.role==="user")return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async buildContextAggregate(t){let o={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let n=this.latestMentionContext(t);return n&&Object.assign(o,n),Object.keys(o).length?o:null}normalizeComposerOptions(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}applyInlineAgentModel(t,o){let n=o?.selectedModelId;return!n||!("model"in t)?t:this.config.composer?.models?.some(a=>a.id===n)?{...t,model:n}:t}async buildAgentPayload(t,o){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Xf).filter(u=>u.role==="user"||u.role==="assistant"||u.role==="system").filter(u=>!u.variant||u.variant==="assistant").sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),a=this.normalizeComposerOptions(o),i={agent:this.applyInlineAgentModel(this.config.agent??{agentId:n},a),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};a&&(i.composerOptions=a);let d=[..._a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];d.length>0&&(i.clientTools=d);let c=await this.buildContextAggregate(t);return c&&(i.context=c),i}async buildPayload(t,o){let n=t.slice().filter(Xf).sort((u,p)=>{let m=new Date(u.createdAt).getTime(),h=new Date(p.createdAt).getTime();return m-h}).map(u=>({role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,createdAt:u.createdAt})),r=this.routing(),a={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[u,p]of Object.entries(r.targetPayload))u!=="messages"&&(a[u]=p);let i=[..._a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];i.length>0&&(a.clientTools=i);let d=await this.buildContextAggregate(t);d&&(a.context=d);let c=this.normalizeComposerOptions(o);if(c&&(a.composerOptions=c),this.requestMiddleware)try{let u=await this.requestMiddleware({payload:{...a},config:this.config});if(u&&typeof u=="object"){let p=u;return a.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=a.clientTools),p}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}return a}async handleCustomSSEEvent(t,o,n,r,a,i){if(!this.parseSSEEvent)return!1;try{let d=await this.parseSSEEvent(t);if(d===null)return!1;let c=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return n.current=m,r(m),m},u=p=>n.current?n.current:c(p);if(d.text!==void 0){d.partId!==void 0&&i.current!==null&&d.partId!==i.current&&(n.current&&(n.current.streaming=!1,r(n.current)),c(d.partId)),d.partId!==void 0&&(i.current=d.partId);let p=u(d.partId);d.partId!==void 0&&!p.partId&&(p.partId=d.partId),p.content+=d.text,r(p)}return d.done&&(n.current&&(n.current.streaming=!1,r(n.current)),i.current=null,o({type:"status",status:"idle"})),d.error&&(i.current=null,o({type:"error",error:new Error(d.error)})),!0}catch(d){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",d),!1}}async streamResponse(t,o,n,r){let a=t.getReader(),i=new TextDecoder,d="",c=Date.now(),u=0,p=()=>c+u++,m=F=>{let J=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,S=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,N=F.tools?F.tools.map(q=>({...q,chunks:q.chunks?[...q.chunks]:void 0})):void 0;return{...F,reasoning:J,toolCall:S,tools:N}},h=F=>{if(F.role!=="assistant"||F.variant)return!0;let J=Array.isArray(F.contentParts)&&F.contentParts.length>0,S=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||J||S||!!F.stopReason},y=F=>{h(F)&&o({type:"message",message:m(F)})},x=null,T=null,w={current:null},k={current:null},P=null,H="",b=new Map,A=new Map,C=new Map,L=new Map,U=new Map,Q={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},E=F=>{if(F==null)return null;try{return String(F)}catch{return null}},B=F=>E(F.stepId??F.step_id??F.step??F.parentId??F.flowStepId??F.flow_step_id),D=F=>E(F.callId??F.call_id??F.requestId??F.request_id??F.toolCallId??F.tool_call_id??F.stepId??F.step_id),W=n,te=!1,X=()=>{if(x)return x;let F,J="",S=P;return!te&&W?(F=W,te=!0,J=r??""):W&&S?F=`${W}_${S}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:F,role:"assistant",content:J,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(x),x},fe=(F,J)=>{Q.lastId=J,F&&Q.byStep.set(F,J)},le=(F,J)=>{let S=F.reasoningId??F.id,N=B(F);if(S){let V=String(S);return fe(N,V),V}if(N){let V=Q.byStep.get(N);if(V)return Q.lastId=V,V}if(Q.lastId&&!J)return Q.lastId;if(!J)return null;let q=`reason-${p()}`;return fe(N,q),q},xe=F=>{let J=L.get(F);if(J)return J;let S={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:F,status:"streaming",chunks:[]}};return L.set(F,S),y(S),S},Re=(F,J)=>{$.lastId=J,F&&$.byCall.set(F,J)},He=new Set,we=new Map,pt=new Set,ke=new Map,z=F=>{if(!F)return!1;let J=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return J==="emit_artifact_markdown"||J==="emit_artifact_component"},Ve=(F,J)=>{let S=F.toolId??F.id,N=D(F);if(S){let V=String(S);return Re(N,V),V}if(N){let V=$.byCall.get(N);if(V)return $.lastId=V,V}if($.lastId&&!J)return $.lastId;if(!J)return null;let q=`tool-${p()}`;return Re(N,q),q},Xe=F=>{let J=U.get(F);if(J)return J;let S={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:F,status:"pending"}};return U.set(F,S),y(S),S},At=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let J=Number(F);if(!Number.isNaN(J)&&Number.isFinite(J))return J;let S=Date.parse(F);if(!Number.isNaN(S))return S}return Date.now()},Ie=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},Pe=new Map,be=new Map,xn=new Map,Cn=(F,J,S)=>{let N=xn.get(F);N||(N=[],xn.set(F,N));let q=0,V=N.length;for(;q<V;){let se=q+V>>>1;N[se].seq<J?q=se+1:V=se}N[q]?.seq===J?N[q]={seq:J,text:S}:N.splice(q,0,{seq:J,text:S});let oe="";for(let se=0;se<N.length;se++)oe+=N[se].text;return oe},ea=(F,J)=>{let S=Ie(J),N=be.get(F.id),q=SE(N,S);F.rawContent=q;let V=Pe.get(F.id),oe=Be=>{let Rt=F.content??"";Be.trim()!==""&&(Rt.trim().length===0||Be.startsWith(Rt)||Be.trimStart().startsWith(Rt.trim()))&&(F.content=Be)},se=()=>{if(V){let Be=V.close?.();Be instanceof Promise&&Be.catch(()=>{})}Pe.delete(F.id),be.delete(F.id),F.streaming=!1,y(F)};if(!V){oe(S),se();return}let ie=ll(q);if(ie!==null&&ie.trim()!==""){oe(ie),se();return}let de=Be=>{let Rt=typeof Be=="string"?Be:Be?.text??null;if(Rt!==null&&Rt.trim()!=="")return Rt;let Mt=V.getExtractedText();return Mt!==null&&Mt.trim()!==""?Mt:S},Ft;try{Ft=V.processChunk(q)}catch{oe(S),se();return}if(Ft instanceof Promise){Ft.then(Be=>{oe(de(Be)),se()}).catch(()=>{oe(S),se()});return}oe(de(Ft)),se()},It=null,Sn=(F,J,S,N)=>{F.rawContent=J,Pe.has(F.id)||Pe.set(F.id,this.createStreamParser());let q=Pe.get(F.id),V=J.trim().startsWith("{")||J.trim().startsWith("[");if(V&&be.set(F.id,J),q.__isPlainTextParser===!0){F.content=N!==void 0?J:F.content+S,be.delete(F.id),Pe.delete(F.id),F.rawContent=void 0,y(F);return}let se=q.processChunk(J);if(se instanceof Promise)se.then(ie=>{let de=typeof ie=="string"?ie:ie?.text??null;de!==null&&de.trim()!==""?(F.content=de,y(F)):!V&&!J.trim().startsWith("<")&&(F.content=N!==void 0?J:F.content+S,be.delete(F.id),Pe.delete(F.id),F.rawContent=void 0,y(F))}).catch(()=>{F.content=N!==void 0?J:F.content+S,be.delete(F.id),Pe.delete(F.id),F.rawContent=void 0,y(F)});else{let ie=typeof se=="string"?se:se?.text??null;ie!==null&&ie.trim()!==""?(F.content=ie,y(F)):!V&&!J.trim().startsWith("<")&&(F.content=N!==void 0?J:F.content+S,be.delete(F.id),Pe.delete(F.id),F.rawContent=void 0,y(F))}},zo=(F,J)=>{let S=J??F.content;if(S==null||S===""){F.streaming=!1,y(F);return}let q=be.get(F.id)??Ie(S);F.rawContent=q;let V=Pe.get(F.id),oe=null,se=!1;if(V&&(oe=V.getExtractedText(),oe===null&&(oe=ll(q)),oe===null)){let ie=V.processChunk(q);ie instanceof Promise?(se=!0,ie.then(de=>{let Ft=typeof de=="string"?de:de?.text??null;Ft!==null&&(F.content=Ft,F.streaming=!1,Pe.delete(F.id),be.delete(F.id),y(F))}).catch(()=>{})):oe=typeof ie=="string"?ie:ie?.text??null}if(!se){oe!==null&&oe.trim()!==""?F.content=oe:be.has(F.id)||(F.content=Ie(S));let ie=Pe.get(F.id);if(ie){let de=ie.close?.();de instanceof Promise&&de.catch(()=>{}),Pe.delete(F.id)}be.delete(F.id),F.streaming=!1,y(F)}},so=(F,J,S)=>{let N=A.get(F);if(N)return N;let q={id:`nested-${J}-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...S?{variant:S}:{},...S==="reasoning"?{reasoning:{id:F,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:J}};return A.set(F,q),y(q),q},wn=[],Ko,an=new Map,ta=0,An="agent",Kn=!1,os=null,tt=null,Ro=new Map,ln=this.config.iterationDisplay??"separate";for(Ko=()=>{for(let F=0;F<wn.length;F++){let J=wn[F].payloadType,S=wn[F].payload;if(!Kn&&An!=="flow"&&typeof S.stepType=="string"&&(An="flow"),J==="reasoning_start"){let N=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&q){b.set(N,q),so(N,q,"reasoning");continue}let V=le(S,!0)??`reason-${p()}`,oe=xe(V);oe.reasoning=oe.reasoning??{id:V,status:"streaming",chunks:[]},oe.reasoning.startedAt=oe.reasoning.startedAt??At(S.startedAt??S.timestamp),oe.reasoning.completedAt=void 0,oe.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(oe.reasoning.scope=S.scope),oe.streaming=!0,oe.reasoning.status="streaming",y(oe)}else if(J==="reasoning_delta"){let N=typeof S.id=="string"?S.id:null;if(N&&b.has(N)&&A.has(N)){let se=A.get(N),ie=S.reasoningText??S.text??S.delta??"";ie&&S.hidden!==!0&&se.reasoning&&(se.reasoning.chunks.push(String(ie)),y(se));continue}let q=le(S,!1)??le(S,!0)??`reason-${p()}`,V=xe(q);V.reasoning=V.reasoning??{id:q,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??At(S.startedAt??S.timestamp);let oe=S.reasoningText??S.text??S.delta??"";if(oe&&S.hidden!==!0){let se=typeof S.sequenceIndex=="number"?S.sequenceIndex:void 0;if(se!==void 0){let ie=Cn(q,se,String(oe));V.reasoning.chunks=[ie]}else V.reasoning.chunks.push(String(oe))}if(V.reasoning.status=S.done?"complete":"streaming",S.done){V.reasoning.completedAt=At(S.completedAt??S.timestamp);let se=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-se)}V.streaming=V.reasoning.status!=="complete",y(V)}else if(J==="reasoning_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&b.has(N)&&A.has(N)){let ie=A.get(N);if(ie.reasoning){let de=typeof S.text=="string"?S.text:"";de&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(de),ie.reasoning.status="complete",ie.streaming=!1,y(ie)}b.delete(N),A.delete(N);continue}let q=le(S,!1)??le(S,!0)??`reason-${p()}`,V=typeof S.text=="string"?S.text:"";!L.get(q)&&(V||S.scope==="loop")&&xe(q);let oe=L.get(q);if(oe?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(oe.reasoning.scope=S.scope),V&&oe.reasoning.chunks.length===0&&oe.reasoning.chunks.push(V),oe.reasoning.status="complete",oe.reasoning.completedAt=At(S.completedAt??S.timestamp);let ie=oe.reasoning.startedAt??Date.now();oe.reasoning.durationMs=Math.max(0,(oe.reasoning.completedAt??Date.now())-ie),oe.streaming=!1,y(oe)}let se=B(S);se&&Q.byStep.delete(se)}else if(J==="tool_start"){x&&(x.streaming=!1,y(x),x=null),typeof S.iteration=="number"&&(ta=S.iteration);let N=(typeof S.toolCallId=="string"?S.toolCallId:void 0)??Ve(S,!0)??`tool-${p()}`,q=S.toolName??S.name;if(z(q)){He.add(N);continue}Re(D(S),N);let V=Xe(N),oe=V.toolCall??{id:N,status:"pending"};oe.name=q??oe.name,oe.status="running",S.parameters!==void 0?oe.args=S.parameters:S.args!==void 0&&(oe.args=S.args),oe.startedAt=oe.startedAt??At(S.startedAt??S.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,V.toolCall=oe,V.streaming=!0,S.executionId&&(V.agentMetadata={executionId:S.executionId,iteration:S.iteration}),y(V)}else if(J==="tool_output_delta"){let N=Ve(S,!1)??Ve(S,!0)??`tool-${p()}`;if(He.has(N))continue;let q=Xe(N),V=q.toolCall??{id:N,status:"running"};V.startedAt=V.startedAt??At(S.startedAt??S.timestamp);let oe=S.text??S.delta??S.message??"";oe&&(V.chunks=V.chunks??[],V.chunks.push(String(oe))),V.status="running",q.toolCall=V,q.streaming=!0;let se=S.agentContext;(se||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:se?.executionId??S.executionId,iteration:se?.iteration??S.iteration}),y(q)}else if(J==="tool_complete"){let N=Ve(S,!1)??Ve(S,!0)??`tool-${p()}`;if(He.has(N)){He.delete(N);continue}let q=Xe(N),V=q.toolCall??{id:N,status:"running"};V.status="complete",S.result!==void 0&&(V.result=S.result),typeof S.duration=="number"&&(V.duration=S.duration),V.completedAt=At(S.completedAt??S.timestamp);let oe=S.duration??S.executionTime;if(typeof oe=="number")V.durationMs=oe;else{let de=V.startedAt??Date.now();V.durationMs=Math.max(0,(V.completedAt??Date.now())-de)}q.toolCall=V,q.streaming=!1;let se=S.agentContext;(se||S.executionId)&&(q.agentMetadata=q.agentMetadata??{executionId:se?.executionId??S.executionId,iteration:se?.iteration??S.iteration}),y(q);let ie=D(S);ie&&$.byCall.delete(ie)}else if(J==="await"&&S.toolName){let N=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,q=N??S.toolId??`local-${p()}`,V=Xe(q),oe=S.toolName,se=S.origin==="webmcp"&&!qr(oe)?`webmcp:${oe}`:oe,ie=qr(se),de=V.toolCall??{id:q,status:"pending"};de.name=se,de.args=S.parameters,de.status=ie?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??At(S.startedAt??S.timestamp??S.awaitedAt),ie?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,V.toolCall=de,V.streaming=!1,V.agentMetadata={...V.agentMetadata,executionId:S.executionId??V.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},y(V)}else if(J==="text_start"){let N=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&q){b.set(N,q);continue}let V=x;V&&(An==="flow"?(zo(V),It=V):(V.streaming=!1,y(V)),x=null),P=typeof S.id=="string"?S.id:P,H=""}else if(J==="text_delta"){let N=typeof S.id=="string"?S.id:null,q=N?b.get(N):void 0;if(N&&q){let se=typeof S.delta=="string"?S.delta:"",ie=(C.get(N)??"")+se;if(C.set(N,ie),ie.trim()==="")continue;let de=so(N,q);de.agentMetadata={...de.agentMetadata,executionId:S.executionId,parentToolId:q},Sn(de,ie,se,void 0);continue}if(P=typeof S.id=="string"?S.id:P,An==="flow"){let se=typeof S.delta=="string"?S.delta:"";if(H+=se,H.trim()==="")continue;let ie=X();ie.agentMetadata={executionId:S.executionId,iteration:S.iteration},Sn(ie,H,se,void 0),T=ie;continue}let V=typeof S.delta=="string"?S.delta:"";H+=V;let oe=X();oe.agentMetadata={executionId:S.executionId,iteration:S.iteration,turnId:os??void 0,agentName:tt?.agentName},Sn(oe,H,V,void 0),T=oe}else if(J==="text_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&b.has(N)){let V=A.get(N);V&&zo(V),b.delete(N),C.delete(N),A.delete(N);continue}let q=x;q&&(An==="flow"?(zo(q),It=q):((q.content??"")===""&&typeof S.text=="string"&&(q.content=S.text),q.streaming=!1,y(q)),x=null),P=null,H=""}else if(J==="step_complete"){let N=S.stepType,q=S.executionType;if(N==="tool"||q==="context")continue;if(S.success===!1){let V=S.error,oe=typeof V=="string"&&V!==""?V:V!=null&&typeof V=="object"&&Reflect.has(V,"message")?String(V.message??"Step failed"):"Step failed";o({type:"error",error:new Error(oe)});let se=x;se&&se.streaming&&(se.streaming=!1,y(se)),o({type:"status",status:"idle"});continue}{let V=It;It=null;let oe=S.stopReason,se=S.result?.response;if(V)oe&&(V.stopReason=oe),se!=null?ea(V,se):V.streaming!==!1&&(Pe.delete(V.id),be.delete(V.id),V.streaming=!1,y(V));else{let ie=se!=null&&se!=="";if(ie||oe){let de=X();oe&&(de.stopReason=oe),ie?zo(de,se):(de.streaming=!1,y(de))}}continue}}else if(J==="execution_start")An=S.kind==="flow"?"flow":"agent",Kn=!0,An==="agent"&&(tt={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??"",status:"running",currentIteration:0,maxTurns:S.maxTurns??1,startedAt:At(S.startedAt)});else if(J==="turn_start"){let N=typeof S.iteration=="number"?S.iteration:ta;if(N!==ta){if(tt&&(tt.currentIteration=N),ln==="separate"&&N>1){let q=x;q&&(q.streaming=!1,y(q),Ro.set(N-1,q),x=null)}ta=N}os=typeof S.id=="string"?S.id:null,T=null}else if(J==="tool_input_delta"){let N=S.toolCallId??$.lastId;if(N){let q=U.get(N);q?.toolCall&&(q.toolCall.chunks=q.toolCall.chunks??[],q.toolCall.chunks.push(S.delta??""),y(q))}}else{if(J==="tool_input_complete")continue;if(J==="turn_complete"){let N=S.stopReason,q=x??T;if(N&&q!==null){let V=S.id;(!V||q.agentMetadata?.turnId===V)&&(q.stopReason=N,y(q))}os===S.id&&(os=null)}else if(J==="media_start"){let N=String(S.id);an.set(N,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,role:typeof S.role=="string"?S.role:void 0,toolCallId:S.toolCallId,parts:[]})}else if(J==="media_delta"){let N=an.get(String(S.id));N&&typeof S.delta=="string"&&N.parts.push(S.delta)}else if(J==="media_complete"){let N=String(S.id),q=an.get(N);an.delete(N);let V=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",oe=typeof S.data=="string"?S.data:void 0,se=typeof S.url=="string"?S.url:q&&q.parts.length>0?q.parts.join(""):void 0,ie=null;if(oe)ie={type:"media",data:oe,mediaType:V};else if(se){let Rt=V.toLowerCase();ie={type:Rt==="image"||Rt.startsWith("image/")?"image-url":"file-url",url:se,mediaType:V}}let de=S.toolCallId??q?.toolCallId,Ft=ie?[ie]:[],Be=[];for(let Rt of Ft){if(!Rt||typeof Rt!="object")continue;let Mt=Rt,Gn=typeof Mt.type=="string"?Mt.type:void 0,Cr=typeof Mt.mediaType=="string"?Mt.mediaType.toLowerCase():"",Ut=null,qt="";if(Gn==="media"){let Co=typeof Mt.data=="string"?Mt.data:void 0;if(!Co)continue;qt=Cr.length>0?Cr:"application/octet-stream",Ut=`data:${qt};base64,${Co}`}else if(Gn==="image-url"){let Co=typeof Mt.url=="string"?Mt.url:void 0;if(!Co)continue;qt=Cr,Ut=Co}else if(Gn==="file-url"){let Co=typeof Mt.url=="string"?Mt.url:void 0;if(!Co)continue;qt=Cr,Ut=Co}else continue;if(Ut)if(Gn==="image-url"||qt.startsWith("image/"))Be.push({type:"image",image:Ut,...qt.includes("/")?{mimeType:qt}:{}});else if(qt.startsWith("audio/"))Be.push({type:"audio",audio:Ut,mimeType:qt});else if(qt.startsWith("video/"))Be.push({type:"video",video:Ut,mimeType:qt});else{let Co=qt||"application/octet-stream";Be.push({type:"file",data:Ut,mimeType:Co,filename:xE(Co)})}}if(Be.length>0){let Rt=p(),Mt=de,Cr={id:`agent-media-${typeof Mt=="string"&&Mt.length>0?`${Mt}-${Rt}`:String(Rt)}`,role:"assistant",content:"",contentParts:Be,createdAt:new Date().toISOString(),streaming:!1,sequence:Rt,agentMetadata:{executionId:S.executionId,iteration:typeof S.iteration=="number"?S.iteration:ta}};y(Cr);let Ut=x;Ut&&(Ut.streaming=!1,y(Ut)),x=null,w.current=null}}else if(J==="execution_complete"){let N=S.kind??An;N==="agent"&&tt&&(tt.status=S.success?"complete":"error",tt.completedAt=At(S.completedAt),tt.stopReason=S.stopReason);let q=x;q&&(N==="flow"&&q.streaming!==!1?zo(q):(q.streaming=!1,y(q)),x=null),P=null,H="",It=null,o({type:"status",status:"idle",terminal:!0})}else if(J==="execution_error"){let N=typeof S.error=="string"?S.error:S.error?.message??"Execution error";o({type:"error",error:new Error(N)})}else if(J!=="ping"){if(J==="approval_start"){let N=S.approvalId??`approval-${p()}`,q={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:"pending",agentId:tt?.agentId??"virtual",executionId:S.executionId??tt?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};y(q)}else if(J==="step_await"&&S.awaitReason==="approval_required"){let N=S.approvalId??`approval-${p()}`,q={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:"pending",agentId:tt?.agentId??"virtual",executionId:S.executionId??tt?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};y(q)}else if(J==="approval_complete"){let N=S.approvalId;if(N){let V={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:S.decision??"approved",agentId:tt?.agentId??"virtual",executionId:S.executionId??tt?.executionId??"",toolName:S.toolName??"",description:S.description??"",resolvedAt:Date.now()}};y(V)}}else if(J==="artifact_start"||J==="artifact_delta"||J==="artifact_update"||J==="artifact_complete"){if(J==="artifact_start"){let N=S.artifactType,q=String(S.id),V=typeof S.title=="string"?S.title:void 0,oe=S.file,se;oe&&typeof oe=="object"&&!Array.isArray(oe)&&typeof oe.path=="string"&&typeof oe.mimeType=="string"&&(se={path:oe.path,mimeType:oe.mimeType,...typeof oe.language=="string"?{language:oe.language}:{}}),o({type:"artifact_start",id:q,artifactType:N,title:V,component:typeof S.component=="string"?S.component:void 0,...se?{file:se}:{}});let ie=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?{...S.props}:void 0;if(ke.set(q,{markdown:"",title:V,file:se,...ie?{props:ie}:{}}),!pt.has(q)){pt.add(q);let de=Fn(this.config.features?.artifacts,{artifactType:N,...se?{file:se}:{}}),Ft=typeof S.component=="string"?S.component:void 0,Be={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:ol(de,{artifactId:q,title:V,artifactType:N,status:"streaming",...se?{file:se}:{},...Ft?{component:Ft}:{}})};we.set(q,Be),y(Be)}}else if(J==="artifact_delta"){let N=String(S.id),q=typeof S.delta=="string"?S.delta:String(S.delta??"");o({type:"artifact_delta",id:N,artDelta:q});let V=ke.get(N);V&&(V.markdown+=q)}else if(J==="artifact_update"){let N=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};o({type:"artifact_update",id:String(S.id),props:N,component:typeof S.component=="string"?S.component:void 0});let q=ke.get(String(S.id));q&&(q.props={...q.props??{},...N})}else if(J==="artifact_complete"){let N=String(S.id);o({type:"artifact_complete",id:N});let q=we.get(N);if(q){q.streaming=!1;try{let V=JSON.parse(q.rawContent??"{}");if(V.props){V.props.status="complete";let oe=ke.get(N);oe?.markdown&&(V.props.markdown=oe.markdown),oe?.file&&(V.props.file=oe.file),V.component==="PersonaArtifactInline"&&oe?.props&&Object.keys(oe.props).length>0&&(V.props.componentProps=oe.props)}q.rawContent=JSON.stringify(V)}catch{}ke.delete(N),y(q),we.delete(N)}}}else if(J==="transcript_insert"){let N=S.message;if(!N||typeof N!="object")continue;let q=String(N.id??`msg-${p()}`),V=N.role,se={id:q,role:V==="user"?"user":V==="system"?"system":"assistant",content:typeof N.content=="string"?N.content:"",rawContent:typeof N.rawContent=="string"?N.rawContent:void 0,createdAt:typeof N.createdAt=="string"?N.createdAt:new Date().toISOString(),streaming:N.streaming===!0,...typeof N.variant=="string"?{variant:N.variant}:{},sequence:p()};if(y(se),se.rawContent)try{let de=JSON.parse(se.rawContent)?.props?.artifactId;typeof de=="string"&&pt.add(de)}catch{}x=null,w.current=null,Pe.delete(q),be.delete(q)}else if(J==="error"){if(S.recoverable===!1&&S.error!=null&&S.error!==""){let N=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";o({type:"error",error:new Error(N)});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}else if(J==="step_error"||J==="dispatch_error"||J==="flow_error"){let N=null;if(S.error instanceof Error)N=S.error;else if(J==="dispatch_error"){let q=S.message??S.error;q!=null&&q!==""&&(N=new Error(String(q)))}else{let q=S.error;typeof q=="string"&&q!==""?N=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(N=new Error(String(q.message??q)))}if(N){o({type:"error",error:N});let q=x;q&&q.streaming&&(q.streaming=!1,y(q)),o({type:"status",status:"idle"})}}}}}wn.length=0};;){let{done:F,value:J}=await a.read();if(F)break;d+=i.decode(J,{stream:!0});let S=d.split(`
8
8
 
9
- `);d=S.pop()??"";for(let U of S){let q=U.split(`
10
- `),$="message",oe="",ne=null;for(let $e of q)$e.startsWith("event:")?$=$e.replace("event:","").trim():$e.startsWith("data:")?oe+=$e.replace("data:","").trim():$e.startsWith("id:")&&(ne=$e.slice(3).trim());let ie=()=>{ne!==null&&ne!==""&&o({type:"cursor",id:ne})};if(!oe){ie();continue}let xe;try{xe=JSON.parse(oe)}catch($e){o({type:"error",error:$e instanceof Error?$e:new Error("Failed to parse chat stream payload")});continue}let ht=$!=="message"?$:xe.type??"message";if(this.onSSEEvent?.(ht,xe),this.parseSSEEvent){w.current=x;let $e=await this.handleCustomSSEEvent(xe,o,w,y,p,k);if(w.current&&w.current!==x&&(x=w.current),$e){ie();continue}}Ao.push({payloadType:ht,payload:xe}),wn(),ie()}}wn()}};function CE(e){let t=0;for(let o of e.split(`
11
- `)){let n=/^ {0,3}(`+)/.exec(o);n&&n[1].length>t&&(t=n[1].length)}return t}function vx(e,t){let o="`".repeat(Math.max(3,CE(t)+1));return`${o}${e}
9
+ `);d=S.pop()??"";for(let N of S){let q=N.split(`
10
+ `),V="message",oe="",se=null;for(let Be of q)Be.startsWith("event:")?V=Be.replace("event:","").trim():Be.startsWith("data:")?oe+=Be.replace("data:","").trim():Be.startsWith("id:")&&(se=Be.slice(3).trim());let ie=()=>{se!==null&&se!==""&&o({type:"cursor",id:se})};if(!oe){ie();continue}let de;try{de=JSON.parse(oe)}catch(Be){o({type:"error",error:Be instanceof Error?Be:new Error("Failed to parse chat stream payload")});continue}let Ft=V!=="message"?V:de.type??"message";if(this.onSSEEvent?.(Ft,de),this.parseSSEEvent){w.current=x;let Be=await this.handleCustomSSEEvent(de,o,w,y,p,k);if(w.current&&w.current!==x&&(x=w.current),Be){ie();continue}}wn.push({payloadType:Ft,payload:de}),Ko(),ie()}}Ko()}};function wE(e){let t=0;for(let o of e.split(`
11
+ `)){let n=/^ {0,3}(`+)/.exec(o);n&&n[1].length>t&&(t=n[1].length)}return t}function xx(e,t){let o="`".repeat(Math.max(3,wE(t)+1));return`${o}${e}
12
12
  ${t}
13
- ${o}`}var SE=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function wE(e){let t=e?.text?.trim()??"";return t?vx(SE(e),t):""}function xx(e){let t=wE(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[an(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
13
+ ${o}`}var AE=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function ME(e){let t=e?.text?.trim()??"";return t?xx(AE(e),t):""}function Cx(e){let t=ME(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[rn(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
14
14
 
15
- `)}:{}}function Ic(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function Cx(e,t){let o=e.findIndex(r=>r.id===t);if(o===-1||e[o].role!=="user")return null;let n=o+1;for(;n<e.length&&e[n].role!=="user";)n+=1;return{start:o,end:n}}function Xf(e,t){let o=e.findIndex(n=>n.id===t);if(o<=0)return null;for(let n=o-1;n>=0;n-=1)if(e[n].role==="user")return e[n].id;return null}function Sx(e){for(let t=e.length-1;t>=0;t-=1){let o=e[t];if(o.role==="user"||o.streaming)return null;if(!(o.role!=="assistant"||o.variant))return Xf(e,o.id)?o.id:null}return null}function Qf(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var ln=class extends Error{constructor(t,o,n){super(o),this.name="HistoryProviderError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function wx(e){return e instanceof ln}function cl(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(r=>r.name===o);if(n)return n}return e.find(o=>o.lang.startsWith("en"))??e[0]}var Ds=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,o){if(!e.isSupported()){o.onError?.(new Error("Web Speech API is unavailable"));return}let n=window.speechSynthesis;n.cancel();let r=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let i=a.find(d=>d.name===t.voice);i&&(r.voice=i)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):cl(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>o.onEnd?.(),r.onerror=i=>{let d=i.error;d==="canceled"||d==="interrupted"?o.onEnd?.():o.onError?.(new Error(d||"Speech synthesis failed"))},setTimeout(()=>{n.speak(r),o.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Da=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,o){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,o)}async play(t,o){let n=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(n!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(o,{onStart:()=>{n===this.generation&&this.set(t,"playing")},onEnd:()=>{n===this.generation&&this.set(null,"idle")},onError:()=>{n===this.generation&&this.set(null,"idle")}})}catch{n===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,o){this.activeId=o==="idle"?null:t,this.state=o;for(let n of this.listeners)n(this.activeId,this.state)}};var AE=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Ax(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,o=typeof t=="function"?t():t;return!!o&&typeof o.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:AE()}catch{return!1}}var{setLoader:ME,load:TE}=mt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Mx=ME,Yf=TE;function Jf(e){if(!e)return"";let t=EE(e);return Tx(t!==null?t:e)}function EE(e){let t=e.trim(),o=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(o&&(t=o[1].trim()),!t.startsWith("{"))return null;try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{}return null}function Tx(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
+ `)}:{}}function Rc(e,t=140){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function Sx(e,t){let o=e.findIndex(r=>r.id===t);if(o===-1||e[o].role!=="user")return null;let n=o+1;for(;n<e.length&&e[n].role!=="user";)n+=1;return{start:o,end:n}}function Qf(e,t){let o=e.findIndex(n=>n.id===t);if(o<=0)return null;for(let n=o-1;n>=0;n-=1)if(e[n].role==="user")return e[n].id;return null}function wx(e){for(let t=e.length-1;t>=0;t-=1){let o=e[t];if(o.role==="user"||o.streaming)return null;if(!(o.role!=="assistant"||o.variant))return Qf(e,o.id)?o.id:null}return null}function Yf(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var sn=class extends Error{constructor(t,o,n){super(o),this.name="HistoryProviderError",this.code=t,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function Ax(e){return e instanceof sn}function ul(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(r=>r.name===o);if(n)return n}return e.find(o=>o.lang.startsWith("en"))??e[0]}var Ns=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,o){if(!e.isSupported()){o.onError?.(new Error("Web Speech API is unavailable"));return}let n=window.speechSynthesis;n.cancel();let r=new SpeechSynthesisUtterance(t.text),a=n.getVoices();if(t.voice){let i=a.find(d=>d.name===t.voice);i&&(r.voice=i)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):ul(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>o.onEnd?.(),r.onerror=i=>{let d=i.error;d==="canceled"||d==="interrupted"?o.onEnd?.():o.onError?.(new Error(d||"Speech synthesis failed"))},setTimeout(()=>{n.speak(r),o.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Ua=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,o){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,o)}async play(t,o){let n=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(n!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(o,{onStart:()=>{n===this.generation&&this.set(t,"playing")},onEnd:()=>{n===this.generation&&this.set(null,"idle")},onError:()=>{n===this.generation&&this.set(null,"idle")}})}catch{n===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,o){this.activeId=o==="idle"?null:t,this.state=o;for(let n of this.listeners)n(this.activeId,this.state)}};var TE=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Mx(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,o=typeof t=="function"?t():t;return!!o&&typeof o.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:TE()}catch{return!1}}var{setLoader:EE,load:PE}=gt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")}),Tx=EE,Jf=PE;function Zf(e){if(!e)return"";let t=kE(e);return Ex(t!==null?t:e)}function kE(e){let t=e.trim(),o=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(o&&(t=o[1].trim()),!t.startsWith("{"))return null;try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{}return null}function Ex(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
16
16
  `),t=t.replace(/\n{2,}/g,`
17
- `),t.trim()}var Zf=null,Ex=e=>{Zf=e},em=()=>Zf?Zf():import("./runtype-tts-entry");var{setLoader:PE,load:kE}=mt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),Px=PE,kx=kE;var LE=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function IE(e,t){return LE.some(o=>e[o]!==t[o])}var qn=class extends Error{constructor(t,o){super(o),this.name="SessionHistoryError",this.code=t}};function tm(e,t){let o=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(o);let n="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return o.message?`${n}
17
+ `),t.trim()}var em=null,Px=e=>{em=e},tm=()=>em?em():import("./runtype-tts-entry");var{setLoader:LE,load:IE}=gt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")}),kx=LE,Lx=IE;var RE=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function HE(e,t){return RE.some(o=>e[o]!==t[o])}var $n=class extends Error{constructor(t,o){super(o),this.name="SessionHistoryError",this.code=t}};function om(e,t){let o=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(o);let n="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return o.message?`${n}
18
18
 
19
- _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]}),RE=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Lx=e=>_r(e)||e===Fn,_a=class e{constructor(t={},o,n={}){this.config=t;this.callbacks=o;this.historyInternals=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Da(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,n=!!o?.name&&(_r(o.name)||o.name===Fn&&jr(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&n&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(n),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Os(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&Yf().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!n||!this.config.clientToken||em().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ax(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=Ds.isSupported()?new Ds({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let n=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,i=t.browserFallback!==!1;if(n&&r&&a)return em().then(({RuntypeSpeechEngine:d,FallbackSpeechEngine:c})=>{let u=new d({host:n,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&o?new c(u,o,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");let n=++this.voiceSetupGeneration;this.voiceSetupPromise=Yf().then(r=>{n===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(o))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{n===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(o){console.error("Failed to setup voice:",o)}}wireVoiceProvider(t){try{this.voiceProvider=t;let n=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=d.id}if(i){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=d.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:n,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let o=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:n=>{this.handleHistoryContinuityChanged(n),o?.(n)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new qn("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let o=this.requireHistoryProvider(),n=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",a=n??(o.capabilities.scopes.includes(r)?r:o.capabilities.scopes[0]??r);if(!o.capabilities.scopes.includes(a))throw new ln("unsupported_scope","This history scope is not supported.");return{scope:a}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,o){this.callbacks.onHistoryNotice?.({code:t,message:o})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let o=this.projectionFinalizationPromise;o&&await o.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new qn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,o){let n=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(o?.scope);await this.awaitHistorySettled();let a=++this.historyOpenEpoch,i=await n.getPage(t,{context:r});if(a!==this.historyOpenEpoch)throw new qn("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new qn("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(d)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=d.conversationId||t,this.activeConversationRevision=d.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,o,n){let r=this.requireHistoryProvider(),a=this.historyContext(n?.scope),i=o??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let d=`${t} ${i}`,c=this.olderPageRequests.get(d);if(c)return c;let u=this.fetchOlderPage(r,t,i,a).finally(()=>{this.olderPageRequests.delete(d)});return this.olderPageRequests.set(d,u),u}async fetchOlderPage(t,o,n,r){let a=this.messages[0]?.createdAt,i=await t.getPage(o,{cursor:n,...a?{beforeCreatedAt:a}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==o)return{messages:[],nextMessageCursor:i.nextCursor};let d=dl(this.messages,i.messages);this.messages=this.sortMessages(d.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=i.nextCursor;for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,a=await o.prepareStartNew({context:n});if(r!==this.historyOpenEpoch)throw a.discard(),new qn("superseded","A later action won");await this.installFreshConversation(a)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,o){let n=this.requireHistoryProvider(),r=this.historyContext(o?.scope);await this.awaitHistorySettled(),await n.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,o,n){let r=this.requireHistoryProvider();if(!r.update)throw new qn("history_unavailable","This history provider cannot update conversations");let a=this.historyContext(n?.scope);return await this.awaitHistorySettled(),r.update(t,o,{context:a})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await o.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:n});return await this.recoverFromDestroyedConversation(n),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new qn("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let o=this.historyProvider;if(!o){this.historySendBlocked=!1,this.emitHistoryState();return}try{let n=await o.prepareStartNew({context:t});await this.installFreshConversation(n)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new qn("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let o=this.client.getClientSession();o&&o.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(o)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(o=>this.handleExternalCredentialChange(o))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let o=this.messages.length>0;o||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),o&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let o=this.historyProvider,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!o||!n)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let a=this.runBootReconciliation(o,n,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===a&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=a,a}async runBootReconciliation(t,o,n){this.activeConversationId=o;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,a=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&a&&r===a){this.activeConversationRevision=r;return}let i=await t.getPage(o,{context:n}),d=new Set(i.messages.map(m=>m.id)),c=this.messages.some(m=>d.has(m.id)),u=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>d.has(y.id)||y.id===m?!0:u!==void 0&&y.createdAt<u);p=dl(h,i.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of i.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let o of t){let n=ll(o);n!==void 0&&this.acknowledgedProjections.set(o.id,n)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let o=[];for(let n of this.messages){if(n.role!=="assistant"||n.streaming)continue;let r=ll(n);r!==void 0&&this.acknowledgedProjections.get(n.id)!==r&&o.push({id:n.id,displayContent:r})}o.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:o.map(n=>n.id)}),this.enqueueProjectionFinalization(t,o))}enqueueProjectionFinalization(t,o){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,o,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,o,n){if(this.activeConversationId!==t)return;let r=o.filter(a=>this.acknowledgedProjections.get(a.id)!==a.displayContent);if(r.length===0){this.clearFinalizedMarker(t,o);return}try{let{conversationRevision:a}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&a&&(this.activeConversationRevision=a),this.clearFinalizedMarker(t,o)}catch(a){if(!n&&this.isTransientProjectionError(a)){await this.finalizeProjections(t,r,!0);return}if(a instanceof Fe&&(a.code==="not_found"||a.code==="conversation_deleted")){this.clearFinalizedMarker(t,o);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof Fe?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,o){let n=this.readPendingProjections();if(!n||n.conversationId!==t)return;let r=new Set(o.map(i=>i.id)),a=n.messageIds.filter(i=>!r.has(i));this.setPendingProjections(a.length?{conversationId:t,messageIds:a}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let o=[];for(let n of t.messageIds){let r=this.messages.find(a=>a.id===n);!r||typeof r.content!="string"||o.push({id:n,displayContent:r.content})}if(o.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,o),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof Fe&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,o,n,r,a){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent);return}catch(i){if(!e.isConversationDeleted(i))throw i;let d=await this.recoverFromDeletedConversation(r);if(!d)throw i;this.recordDispatchedProjections([d]),await this.client.dispatch({messages:[d],signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let o=this.messages.find(r=>r.id===t);if(!o)return null;let n={...o};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let a=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(a)}else{this.client.clearClientSession();let a=await this.client.initSession();this.bindActivatedSession(a)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(n),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===n.id)??n}updateConfig(t){let o=this.config.features?.artifacts?.display,n={...this.config,...t},r=JSON.stringify(o)!==JSON.stringify(n.features?.artifacts?.display);if(!IE(this.config,n)){this.config=n,this.client.updateConfig(n),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=n,this.client=new Os(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:n,llmContent:r,contentParts:a,id:i,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:p,rawContent:m}=t,y={id:i??(o==="user"?La():o==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:n,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let n of t){let{role:r,content:a,llmContent:i,contentParts:d,id:c,createdAt:u,sequence:p,streaming:m=!1,voiceProcessing:h,rawContent:y}=n,T={id:c??(r==="user"?La():r==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...i!==void 0&&{llmContent:i},...d!==void 0&&{contentParts:d},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};o.push(T)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:n={},text:r="",llmContent:a,id:i,createdAt:d,sequence:c}=t,u={text:r,component:o,props:n};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...a!==void 0&&{llmContent:a},...i!==void 0&&{id:i},...d!==void 0&&{createdAt:d},...c!==void 0&&{sequence:c}})}async applyMentionBundle(t,o,n){let r;try{r=await n()}catch{return}let a=r.blocks.join(`
19
+ _Details: ${o.message}_`:n}var nm=e=>({isError:!0,content:[{type:"text",text:e}]}),WE=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ix=e=>qr(e)||e===Un,qa=class e{constructor(t={},o,n={}){this.config=t;this.callbacks=o;this.historyInternals=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Ua(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let o=t.message.toolCall,n=!!o?.name&&(qr(o.name)||o.name===Un&&Xr(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&n&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(n),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new _s(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&Jf().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let o=t.host??this.config.apiUrl,n=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!o||!n||!this.config.clientToken||tm().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Mx(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let o=Ns.isSupported()?new Ns({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let n=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,i=t.browserFallback!==!1;if(n&&r&&a)return tm().then(({RuntypeSpeechEngine:d,FallbackSpeechEngine:c})=>{let u=new d({host:n,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&o?new c(u,o,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&o)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),o}return o}setupVoice(t){try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");let n=++this.voiceSetupGeneration;this.voiceSetupPromise=Jf().then(r=>{n===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(o))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{n===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(o){console.error("Failed to setup voice:",o)}}wireVoiceProvider(t){try{this.voiceProvider=t;let n=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=d.id}if(i){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=d.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:n,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let o={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,o){return this.client.submitMessageFeedback(t,o)}async submitCSATFeedback(t,o){return this.client.submitCSATFeedback(t,o)}async submitNPSFeedback(t,o){return this.client.submitNPSFeedback(t,o)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let o=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:n=>{this.handleHistoryContinuityChanged(n),o?.(n)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new $n("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let o=this.requireHistoryProvider(),n=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",a=n??(o.capabilities.scopes.includes(r)?r:o.capabilities.scopes[0]??r);if(!o.capabilities.scopes.includes(a))throw new sn("unsupported_scope","This history scope is not supported.");return{scope:a}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,o){this.callbacks.onHistoryNotice?.({code:t,message:o})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let o=this.projectionFinalizationPromise;o&&await o.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new $n("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,o){let n=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(o?.scope);await this.awaitHistorySettled();let a=++this.historyOpenEpoch,i=await n.getPage(t,{context:r});if(a!==this.historyOpenEpoch)throw new $n("superseded","A later selection won");let d=await n.prepareOpen(t,{context:r});if(a!==this.historyOpenEpoch)throw d.discard(),new $n("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(d)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=d.conversationId||t,this.activeConversationRevision=d.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,o,n){let r=this.requireHistoryProvider(),a=this.historyContext(n?.scope),i=o??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let d=`${t} ${i}`,c=this.olderPageRequests.get(d);if(c)return c;let u=this.fetchOlderPage(r,t,i,a).finally(()=>{this.olderPageRequests.delete(d)});return this.olderPageRequests.set(d,u),u}async fetchOlderPage(t,o,n,r){let a=this.messages[0]?.createdAt,i=await t.getPage(o,{cursor:n,...a?{beforeCreatedAt:a}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==o)return{messages:[],nextMessageCursor:i.nextCursor};let d=cl(this.messages,i.messages);this.messages=this.sortMessages(d.map(c=>this.ensureSequence(c))),this.historyNextMessageCursor=i.nextCursor;for(let c of i.messages)this.acknowledgedProjections.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,a=await o.prepareStartNew({context:n});if(r!==this.historyOpenEpoch)throw a.discard(),new $n("superseded","A later action won");await this.installFreshConversation(a)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,o){let n=this.requireHistoryProvider(),r=this.historyContext(o?.scope);await this.awaitHistorySettled(),await n.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,o,n){let r=this.requireHistoryProvider();if(!r.update)throw new $n("history_unavailable","This history provider cannot update conversations");let a=this.historyContext(n?.scope);return await this.awaitHistorySettled(),r.update(t,o,{context:a})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let o=this.requireHistoryProvider(),n=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await o.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:n});return await this.recoverFromDestroyedConversation(n),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new $n("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let o=this.historyProvider;if(!o){this.historySendBlocked=!1,this.emitHistoryState();return}try{let n=await o.prepareStartNew({context:t});await this.installFreshConversation(n)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new $n("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let o=this.client.getClientSession();o&&o.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(o)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(o=>this.handleExternalCredentialChange(o))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let o=this.messages.length>0;o||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),o&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let o=this.historyProvider,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!o||!n)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let a=this.runBootReconciliation(o,n,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===a&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=a,a}async runBootReconciliation(t,o,n){this.activeConversationId=o;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,a=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&a&&r===a){this.activeConversationRevision=r;return}let i=await t.getPage(o,{context:n}),d=new Set(i.messages.map(m=>m.id)),c=this.messages.some(m=>d.has(m.id)),u=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>d.has(y.id)||y.id===m?!0:u!==void 0&&y.createdAt<u);p=cl(h,i.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of i.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let o of t){let n=dl(o);n!==void 0&&this.acknowledgedProjections.set(o.id,n)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let o=[];for(let n of this.messages){if(n.role!=="assistant"||n.streaming)continue;let r=dl(n);r!==void 0&&this.acknowledgedProjections.get(n.id)!==r&&o.push({id:n.id,displayContent:r})}o.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:o.map(n=>n.id)}),this.enqueueProjectionFinalization(t,o))}enqueueProjectionFinalization(t,o){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,o,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,o,n){if(this.activeConversationId!==t)return;let r=o.filter(a=>this.acknowledgedProjections.get(a.id)!==a.displayContent);if(r.length===0){this.clearFinalizedMarker(t,o);return}try{let{conversationRevision:a}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&a&&(this.activeConversationRevision=a),this.clearFinalizedMarker(t,o)}catch(a){if(!n&&this.isTransientProjectionError(a)){await this.finalizeProjections(t,r,!0);return}if(a instanceof qe&&(a.code==="not_found"||a.code==="conversation_deleted")){this.clearFinalizedMarker(t,o);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof qe?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,o){let n=this.readPendingProjections();if(!n||n.conversationId!==t)return;let r=new Set(o.map(i=>i.id)),a=n.messageIds.filter(i=>!r.has(i));this.setPendingProjections(a.length?{conversationId:t,messageIds:a}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let o=[];for(let n of t.messageIds){let r=this.messages.find(a=>a.id===n);!r||typeof r.content!="string"||o.push({id:n,displayContent:r.content})}if(o.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,o),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof qe&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,o,n,r,a){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions,interrupt:a?.interrupt},this.handleEvent);return}catch(i){if(!e.isConversationDeleted(i))throw i;let d=await this.recoverFromDeletedConversation(r);if(!d)throw i;this.recordDispatchedProjections([d]),await this.client.dispatch({messages:[d],signal:o.signal,assistantMessageId:n,composerOptions:a?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let o=this.messages.find(r=>r.id===t);if(!o)return null;let n={...o};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let a=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(a)}else{this.client.clearClientSession();let a=await this.client.initSession();this.bindActivatedSession(a)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(n),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===n.id)??n}updateConfig(t){let o=this.config.features?.artifacts?.display,n={...this.config,...t},r=JSON.stringify(o)!==JSON.stringify(n.features?.artifacts?.display);if(!HE(this.config,n)){this.config=n,this.client.updateConfig(n),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=n,this.client=new _s(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:o,content:n,llmContent:r,contentParts:a,id:i,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:p,rawContent:m}=t,y={id:i??(o==="user"?Wa():o==="assistant"?Vr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:o,content:n,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let o=[];for(let n of t){let{role:r,content:a,llmContent:i,contentParts:d,id:c,createdAt:u,sequence:p,streaming:m=!1,voiceProcessing:h,rawContent:y}=n,T={id:c??(r==="user"?Wa():r==="assistant"?Vr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...i!==void 0&&{llmContent:i},...d!==void 0&&{contentParts:d},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};o.push(T)}return this.messages=this.sortMessages([...this.messages,...o]),this.callbacks.onMessagesChanged([...this.messages]),o}injectComponentDirective(t){let{component:o,props:n={},text:r="",llmContent:a,id:i,createdAt:d,sequence:c}=t,u={text:r,component:o,props:n};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...a!==void 0&&{llmContent:a},...i!==void 0&&{id:i},...d!==void 0&&{createdAt:d},...c!==void 0&&{sequence:c}})}async applyMentionBundle(t,o,n){let r;try{r=await n()}catch{return}let a=r.blocks.join(`
20
20
 
21
21
  `),i=[a,o].filter(Boolean).join(`
22
22
 
23
- `),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(d){let u=[];a&&u.push(an(a)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(c){let u=[];i&&u.push(an(i)),u.push(...r.contentParts),t.contentParts=u}else a&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,o){let n=t.trim(),r=!!o?.replayFields&&(o.replayFields.llmContent!==void 0||o.replayFields.rawContent!==void 0||(o.replayFields.contextMentions?.length??0)>0);if(!n&&(!o?.contentParts||o.contentParts.length===0)&&(!o?.mentions||o.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let a=La(),i=Fr();this.activeAssistantMessageId=null;let d=o?.contentParts&&Oa(o.contentParts)?Ba:"",c={id:a,role:"user",content:n||d,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts},...o?.mentions&&o.mentions.refs.length>0&&{contextMentions:o.mentions.refs},...o?.contentSegments&&o.contentSegments.length>0&&{contentSegments:o.contentSegments},...o?.composerOptions&&{composerOptions:o.composerOptions},...o?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,o?.mentions){let m=this.messages.find(h=>h.id===a)??c;if(await this.applyMentionBundle(m,n,o.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(o?.quote&&!o.replayFields){let m=this.messages.find(y=>y.id===a)??c,h=xx({quote:o.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...o.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,u,i,a,{composerOptions:o?.composerOptions,interrupt:o?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=tm(m,this.config.errorMessage);if(y){let x={id:i,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,o){let n=Cx(this.messages,t);if(!n)return!1;let r=this.messages[n.start],a=o.replacement,i=a?a.text:r.content,d=a?a.contentParts:r.contentParts;if(!(!!i?.trim()||(d?.length??0)>0||!a&&(r.llmContent?.trim()?.length??0)>0))return!1;let u=a?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},p=a?this.toComposerOptionsPayload(a.options):r.composerOptions,m=a?a.contentSegments:r.contentSegments,h=a?a.options?.quote:void 0,y=a?a.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(i??"",{...d?.length?{contentParts:[...d]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...h?{quote:h}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=Fr();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let i=tm(r,this.config.errorMessage);if(i){let d={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(d)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let n=o?.preserveAssistantId?o.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==n&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${o.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(r=>{this.webMcpApprovalResolvers.set(n,r)})}resolveWebMcpApproval(t,o){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:o,resolvedAt:Date.now()}}),n(o==="approved")}async resolveApproval(t,o,n){let r=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),d={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(d),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,u=c&&typeof c=="object"?c.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),p){let m=null;if(p instanceof Response){if(!p.ok){let h=await p.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof o=="string"?void 0:o;if(i===void 0&&typeof o=="string"){let p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(i={[h]:o})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=t.toolCall.id,c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===0){let p=typeof o=="string"?o:Object.entries(o).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${d}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let x=p[y],T=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";this.appendMessage({id:`ask-user-q-${d}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${d}-${h}`,role:"user",content:T||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[a]:o},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.id;if(!o||!n){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(o);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=o;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}resolveWebMcpToolStartedAt(t){let n=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of n)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Fn?!1:(this.messages.find(n=>n.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,n,r=Date.now(),a){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:n,completedAt:r,duration:void 0,durationMs:Math.max(0,r-n)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let n=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=async c=>{let u=c.toolCall?.name,p=c.toolCall?.id;if(!u||!p)return null;let m=`${t}:${p}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),n.push(m);let h=this.markWebMcpToolRunning(c),y=c.agentMetadata?.webMcpToolCallId??u;if(u===Fn)return{dedupeKey:m,resumeKey:y,output:Gv(),toolMessage:c,startedAt:h,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(u,c.toolCall?.args,r.signal),T;if(!x)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await x}catch(w){let k=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));return k||this.callbacks.onError?.(w instanceof Error?w:new Error(String(w))),this.markWebMcpToolComplete(c,om(k?"Aborted by cancel()":RE(w)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,om("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:T,toolMessage:c,startedAt:h,completedAt:Date.now()}},i;if(this.config.webmcp?.execution==="sequential"){i=[];for(let c of o)i.push(await a(c))}else i=await Promise.all(o.map(a));let d=[];try{if(d=i.filter(p=>p!==null),d.length===0)return;let c={};for(let p of d)c[p.resumeKey]=p.output;let u=await this.client.resumeFlow(t,c,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of d)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===Fn?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let p of d)this.markWebMcpToolComplete(p.toolMessage,om("Aborted by cancel()"),p.startedAt)}finally{for(let c of n)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.name,r=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!n)return;if(!r){let i=`${o}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i))return;this.webMcpInflightKeys.add(i);try{await this.resumeWithToolOutput(o,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(i)}catch(d){this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}finally{this.webMcpInflightKeys.delete(i)}return}let a=`${o}:${r}`;if(!(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(o,[t])}async resumeWithToolOutput(t,o,n,r){let a=await this.client.resumeFlow(t,{[o]:n},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!a.ok){let i=await a.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(o,n),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(n),n}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,n=Nn(this.config.features?.artifacts,t),r=tl(n,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(i=>i.id===o);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let o of this.artifacts.values()){let n=this.messages.find(i=>i.id===`artifact-ref-${o.id}`);if(!n)continue;let r=Nn(this.config.features?.artifacts,o),a=tl(r,{artifactId:o.id,title:o.title,artifactType:o.artifactType,status:o.status,...o.file?{file:o.file}:{},...o.presentation?{presentation:o.presentation}:{},...o.component?{component:o.component}:{},...o.props?{componentProps:o.props}:{},...o.markdown!==void 0?{markdown:o.markdown}:{}});n.rawContent!==a&&(n.rawContent=a,n.streaming=o.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let n=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(n)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=kx().then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,n,r)=>t.connectStream(o,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>tm(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=Fr(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Jf(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return cl(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=Jf(o.content||"");if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),n=this.messages.findIndex(r=>r.id===o.id);if(n===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,a)=>{if(a!==n)return r;let i={...r,...o};if(r.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(i.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(i.agentMetadata={...i.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&o.approval&&r.approval.id===o.approval.id){let p=r.approval,m=o.approval;i.approval={...p,...m,executionId:m.executionId||p.executionId,toolName:m.toolName||p.toolName,description:m.description||p.description,toolType:m.toolType??p.toolType,reason:m.reason??p.reason,parameters:m.parameters??p.parameters}}let d=o.toolCall?.name,c=o.agentMetadata?.executionId,u=o.toolCall?.id;if(d&&Lx(d)&&c&&u&&o.agentMetadata?.awaitingLocalTool===!0){let p=`${c}:${u}`,m=this.webMcpInflightKeys.has(p),h=this.webMcpResolvedKeys.has(p),y=r.toolCall?.name,x=r.agentMetadata?.executionId===c&&r.toolCall?.id===u&&y!==void 0&&Lx(y)&&r.toolCall?.status==="complete";(m||h||x)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,n)=>{let r=new Date(o.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let i=o.sequence??0,d=n.sequence??0;return i!==d?i-d:o.id.localeCompare(n.id)})}};var Na=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var nm=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var rm=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ul=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var sm=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var am=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var im=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var lm=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Fa=[["path",{d:"M20 6 9 17l-5-5"}]];var pl=[["path",{d:"m6 9 6 6 6-6"}]];var dm=[["path",{d:"m15 18-6-6 6-6"}]];var cm=[["path",{d:"m9 18 6-6-6-6"}]];var _s=[["path",{d:"m18 15-6-6-6 6"}]];var um=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var pm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Rc=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Ua=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var fm=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Hc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Wc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var mm=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var gm=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var fl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var ml=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Ns=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var gl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var hm=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var ym=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Bc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var bm=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var vm=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var xm=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var hl=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Cm=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Sm=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var wm=[["path",{d:"M5 12h14"}]];var Oc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Am=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Mm=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Tm=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Em=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]];var Pm=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var km=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Lm=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Im=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Rm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Dc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Hm=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Wm=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Bm=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Om=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Dm=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var _m=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Nm=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Fm=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var yl=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Ft=(e,t=24,o="currentColor",n=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(n)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let i=a[0],d=a[1];if(!d)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(d).forEach(([u,p])=>{u!=="stroke"&&c.setAttribute(u,String(p))}),r.appendChild(c)}),r};var{setLoader:HE,load:WE}=mt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Ix=HE,_c=WE;var BE={activity:Na,"arrow-down":nm,"arrow-up":am,"arrow-up-right":sm,bot:lm,"chevron-down":pl,"chevron-up":_s,"chevron-right":cm,"chevron-left":dm,check:Fa,clipboard:pm,"clipboard-copy":um,"code-xml":Rc,copy:Ua,file:gl,"file-code":fl,"file-spreadsheet":ml,"file-text":Ns,"image-plus":ym,loader:bm,"loader-circle":Bc,mic:Cm,paperclip:Am,quote:Em,"refresh-cw":Pm,search:km,send:Lm,"shield-alert":Im,"shield-check":Rm,"shield-x":Dc,square:Hm,"thumbs-down":Bm,"thumbs-up":Om,upload:Nm,"volume-2":Fm,x:yl,"at-sign":im,"arrow-left":rm,"arrow-right":ul,"external-link":mm,ellipsis:Wc,"ellipsis-vertical":Hc,menu:xm,"panel-left":Oc,plus:Tm,minus:wm,pencil:Mm,trash:_m,"trash-2":Dm,download:fm,maximize:vm,minimize:Sm,"message-square":hl,star:Wm,eye:gm,history:hm},OE=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],bl=new Map(Object.entries(BE)),qa=new Set,Nc=!1,Fc=new Set,Rx=e=>{let t=[...Fc];e&&Fc.clear();for(let o of t)try{o()}catch{}},Hx=e=>Nc?()=>{}:(Fc.add(e),()=>{Fc.delete(e)}),Wx=()=>{let e=0;for(let t of[...qa]){let o=bl.get(t.name);if(!o)continue;qa.delete(t),e++;let n=Ft(o,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},Bx=e=>{for(let[t,o]of Object.entries(e))bl.set(t,o);Wx()>0&&!Nc&&Rx(!1)};var Um=!1,DE=()=>{_c().then(e=>{if(!Nc){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))bl.has(t)||bl.set(t,o);Nc=!0,Wx(),Rx(!0)}}).catch(e=>{Um=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},_E=(e,t,o)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n},ce=(e,t=24,o="currentColor",n=2)=>{let r=bl.get(e);if(r)return Ft(r,t,o,n);if(OE.includes(e)){Um&&(Um=!1);let a=_E(t,o,n);if(qa.size>=500){let i=qa.values().next().value;i&&qa.delete(i)}return qa.add({el:a,name:e,size:t,color:o,strokeWidth:n}),DE(),a}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};var NE={add:e=>sx(e)},FE=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Uc={allowedTypes:fr,maxFileSize:10*1024*1024,maxFiles:4};function UE(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qE(e){return e==="application/pdf"?Ns:e.startsWith("text/")?Ns:e.includes("word")?Ns:e.includes("excel")||e.includes("spreadsheet")?ml:e==="application/json"?fl:gl}var Fs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Uc.allowedTypes,maxFileSize:t.maxFileSize??Uc.maxFileSize,maxFiles:t.maxFiles??Uc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:NE}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let o of this.attachments)this.renderPreview(o)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Uc.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let o=[];for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let r=ax(n,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,i);continue}let a={id:UE(),file:n,previewUrl:kc(n)?URL.createObjectURL(n):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(a),this.renderPreview(a),o.push(a)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(o.map(n=>this.runAdd(n)))}async runAdd(t){let o=new AbortController;this.pendingAdds.set(t.id,o);let n=()=>this.destroyed||o.signal.aborted||this.pendingAdds.get(t.id)!==o||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:o.signal,onProgress:a=>{n()||t.status!=="uploading"||(t.progress=FE(a),this.updatePreview(t),this.notify())}});if(n())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(n())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===o&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let o=this.attachments.find(n=>n.id===t);!o||o.status!=="error"||this.destroyed||(o.status=this.hasCustomAdapter()?"uploading":"processing",o.progress=this.hasCustomAdapter()?0:void 0,o.error=void 0,this.updatePreview(o),this.notify(),this.runAdd(o))}abortAdd(t){let o=this.pendingAdds.get(t);o&&(this.pendingAdds.delete(t),o.abort())}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let n=this.attachments[o];this.abortAdd(t),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(o,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),n.status==="ready"&&n.contentPart&&this.releasePart(n.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let o=this.config.adapter?.remove;if(o)try{let n=o(t,{signal:new AbortController().signal});n&&typeof n.catch=="function"&&n.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(n){console.error("[AttachmentManager] adapter.remove failed:",n)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=kc(t.file),n=I("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",o&&t.previewUrl){let p=I("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",n.appendChild(p)}else{let p=I("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=qE(t.file.type),h=Ft(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=I("span");y.textContent=ix(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",p.appendChild(y),n.appendChild(p)}let r=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),a=I("div","persona-attachment-progress");a.appendChild(I("div","persona-attachment-progress__bar"));let i=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),d=ce("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);d?i.appendChild(d):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(a,i),n.appendChild(r);let c=I("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let u=Ft(yl,10,"var(--persona-text-inverse, #ffffff)",2);u?c.appendChild(u):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(c),this.previewsContainer.appendChild(n),this.applyPreviewState(n,t)}updatePreview(t){let o=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);o&&this.applyPreviewState(o,t)}applyPreviewState(t,o){t.dataset.status=o.status;let n=o.status!=="ready"&&o.status!=="error";t.setAttribute("aria-busy",n?"true":"false"),t.title=o.status==="error"?`${o.file.name}: ${o.error??"Upload failed"}`:o.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let a=o.progress;r.style.width=typeof a=="number"?`${Math.round(a*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o,adapter:t?.adapter})}};var Ox=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),$E=(e,t)=>e.length===t.length&&e.every((o,n)=>{let r=t[n];return o.id===r.id&&o.name===r.name&&o.mimeType===r.mimeType&&o.size===r.size&&o.status===r.status&&o.progress===r.progress&&o.error===r.error});function Dx(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,o=null,n=!1,r=!1,a=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let p=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},d=()=>(o||(o=i()),o),c=()=>{if(n=!1,r||t.size===0)return;let p=d();for(let m of[...t])try{m(p)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},u=()=>{o=null,!(r||n)&&(n=!0,queueMicrotask(c))};return{getState:d,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,u())},setAttachments:p=>{$E(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{Ox(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{Ox(e.activeModeIds,p)||(e.activeModeIds=[...p],u())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,u())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,u())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,u())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,u())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,u())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,u())},flush:()=>{n&&c()},destroy:()=>{r=!0,n=!1,t.clear()}}}var Ho=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},_x=(e,t)=>{let o=I("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function Nx(e,t={}){let o=Ho(e,"[data-persona-composer-form]"),n=Ho(e,"[data-persona-composer-input]");if(!o||!n){let k=`[Persona] composer surface is missing required element(s): ${[!o&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(o||n))throw new Error(k);return typeof console<"u"&&console.warn(k),null}let r={header:Ho(e,"[data-persona-composer-header]"),body:Ho(e,"[data-persona-composer-body]"),actionsStart:Ho(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Ho(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Ho(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Ho(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Ho(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=_x("persona-widget-composer__header","data-persona-composer-header"),o.parentNode?o.parentNode.insertBefore(i,o):e.appendChild(i));let d=r.body??n.parentElement??o,c=(w,k,P,R,b)=>{if(k)return k;a.add(w);let A=_x(P,R);return b.appendChild(A),A},u=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",o),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",o),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],x=(w,k)=>w.target===k.target&&w.type===k.type&&w.handler===k.handler,T=Ho(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:o,input:n,header:i,body:d,actionsStart:u,actionsEnd:p,suggestions:m,status:h,attachmentInput:T,attachmentPreviews:Ho(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Ho(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Ho(e,"[data-persona-composer-submit]")??void 0,micButton:Ho(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(w,k,P,R)=>{w.addEventListener(k,P,R),y.push({target:w,type:k,handler:P,options:R})},removeListener:(w,k,P,R)=>{w.removeEventListener(k,P,R),y=y.filter(b=>!x(b,{target:w,type:k,handler:P}))},destroy:()=>{for(let w of y)w.target.removeEventListener(w.type,w.handler,w.options);y=[]}}}var Ut={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},so=1e5,$a=so+1;var VE=8,jE=8,qm=10,Fx=200,Ux=300,qx=0,$c=e=>Math.max(0,e);function $x(e){e.delayMs!==void 0&&(Fx=$c(e.delayMs)),e.skipDelayMs!==void 0&&(Ux=$c(e.skipDelayMs))}var zE=()=>Date.now()<qx,KE=e=>{qx=e>0?Date.now()+e:0},qc=new WeakMap,Vm="data-persona-tooltip-suppressed",GE=e=>typeof e.closest=="function"&&e.closest(`[${Vm}]`)!==null;function Vx(e){qc.get(e)?.hide()}var jx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,XE=e=>{let t=e.getRootNode?.();return jx(t)?t:e.ownerDocument.body},$m=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),QE=[...["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 eo(e){qc.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=VE,viewportPadding:d=jE}=e,c=()=>t.ownerDocument,u=()=>c().defaultView??window,p=null,m=null,h=null,y=null,x,T=!1,w=!1,k=!1,P=()=>(typeof n=="function"?n():n).trim(),R=()=>(typeof r=="function"?r():r??"").trim(),b=()=>$c(e.delayMs??Fx),A=()=>$c(e.skipDelayMs??Ux),C=()=>{x!==void 0&&(u().clearTimeout(x),x=void 0)},L=()=>{C();let Ce=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,Ce&&KE(A())},F=()=>{if(!p)return;let Ce=c(),Ee=u(),ge=t.getBoundingClientRect(),Ke=p.getBoundingClientRect(),Bt=Ce.documentElement.clientWidth||Ee.innerWidth,Le=Ce.documentElement.clientHeight||Ee.innerHeight,j=Bt-d-Ke.width,qe=ge.left+ge.width/2-Ke.width/2,Ge=$m(qe,d,j),Ae=ge.top-d,De=Le-d-ge.bottom,he=Ke.height+i,gt=Ae>=he||Ae>=De?"top":"bottom",dn=gt==="top"?ge.top-i-Ke.height:ge.bottom+i,Js=Le-d-Ke.height,oo=$m(dn,d,Js),Xo=ge.left+ge.width/2,Sn=Math.max(qm,Ke.width-qm),Rt=$m(Xo-Ge,qm,Sn);p.dataset.placement=gt,p.style.left=`${Ge}px`,p.style.top=`${oo}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${Rt}px`)},X=()=>{if(k||!a||p||!t.isConnected||GE(t))return;let Ce=P(),Ee=XE(t);if(!Ce||!Ee)return;let ge=c(),Ke=u();p=ge.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String($a);let Bt=Ke.getComputedStyle?.(t);if(Bt){for(let he of QE){let gt=Bt.getPropertyValue(he).trim();gt&&p.style.setProperty(he,gt)}Bt.fontFamily&&(p.style.fontFamily=Bt.fontFamily)}m=ge.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=Ce,p.appendChild(m);let Le=R();Le&&(h=ge.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=Le,p.appendChild(h));let j=ge.createElement("span");j.className="persona-control-tooltip__arrow",p.appendChild(j),Ee.appendChild(p),F(),p.dataset.state="open";let qe=()=>{if(!t.isConnected){L();return}m&&(m.textContent=P()),h&&(h.textContent=R()),F()};Ke.addEventListener("scroll",qe,!0),Ke.addEventListener("resize",qe);let Ge=t.getRootNode(),Ae=jx(Ge)?Ge:ge.documentElement,De=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});De?.observe(Ae,{childList:!0,subtree:!0}),y=()=>{Ke.removeEventListener("scroll",qe,!0),Ke.removeEventListener("resize",qe),De?.disconnect()}},G=Ce=>{if(!(k||p)){if(C(),Ce||b()<=0||zE()){X();return}x=u().setTimeout(()=>{x=void 0,X()},b())}},E=()=>{T||w?G(w):L()},O=()=>{let Ce=u();(!Ce.matchMedia||!Ce.matchMedia("(hover: none)").matches)&&(T=!0,E())},D=()=>{T=!1,E()},W=()=>{try{w=t.matches(":focus-visible")}catch{w=!0}E()},te=()=>{w=!1,E()},Q=()=>{T=!1,w=!1,L()},de=Ce=>{Ce.key==="Escape"&&Q()};o.addEventListener("mouseenter",O),o.addEventListener("mouseleave",D),t.addEventListener("focus",W),t.addEventListener("blur",te),t.addEventListener("keydown",de),t.addEventListener("click",Q);let pe={get isOpen(){return p!==null},show:X,hide:L,reposition:F,destroy:()=>{k||(k=!0,L(),o.removeEventListener("mouseenter",O),o.removeEventListener("mouseleave",D),t.removeEventListener("focus",W),t.removeEventListener("blur",te),t.removeEventListener("keydown",de),t.removeEventListener("click",Q),qc.delete(t))}};return qc.set(t,pe),pe}var zx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Va(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];zx(a)&&zx(r)?o[n]=Va(a,r):o[n]=r}return o}var zo="min(440px, calc(100vw - 24px))",Vc="440px",jm="How can I help...",YE={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:zo,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)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:YE,copy:{inputPlaceholder:jm,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Kx(e,t){if(!(!e&&!t))return e?t?Va(e,t):e:t}function ja(e){return e?{...rt,...e,theme:Kx(rt.theme,e.theme),darkTheme:Kx(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...rt.tooltip,...e.tooltip},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,o=e.features?.artifacts,n=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,i=e.features?.scrollBehavior,d=rt.features?.streamAnimation,c=e.features?.streamAnimation,u=rt.features?.askUserQuestion,p=e.features?.askUserQuestion,m=rt.features?.history,h=e.features?.history,y=t===void 0&&o===void 0?void 0:{...t,...o,layout:{...t?.layout,...o?.layout}},x=n===void 0&&r===void 0?void 0:{...n,...r},T=a===void 0&&i===void 0?void 0:{...a,...i},w=d===void 0&&c===void 0?void 0:{...d,...c},k=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},P=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...rt.features,...e.features,...x!==void 0?{scrollToBottom:x}:{},...T!==void 0?{scrollBehavior:T}:{},...y!==void 0?{artifacts:y}:{},...w!==void 0?{streamAnimation:w}:{},...k!==void 0?{askUserQuestion:k}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}function zm(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let o=t.getComputedStyle(e).lineHeight;if(!o||!o.trim().endsWith("px"))return 20;let n=parseFloat(o);return Number.isFinite(n)&&n>0?n:20}function jc(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Gx(e,t){e.style.maxHeight=`${t*zm(e)}px`,e.style.overflowY="auto"}function Cl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Xx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Qx(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let o=e.metaKey===!0||e.ctrlKey===!0,n=t.submitKey??"enter";return n==="none"?!1:n==="mod-enter"?o:o||!Xx(t)}function JE(e){return(e.submitKey??"enter")!=="enter"||Xx(e)?"enter":"send"}function zc(e,t){e.setAttribute("enterkeyhint",JE(t))}function Kc(e,t){let o=t?.autocomplete;e.setAttribute("autocomplete",typeof o=="string"&&o?o:"off");let n=(r,a)=>{a===void 0?e.removeAttribute(r):e.setAttribute(r,a)};n("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),n("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),n("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),n("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Km(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Ko="persona-composer-control",vn="persona-composer-control--glyph",Xm=40,vo=24,Gc=(e,t,o)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let r=n.getComputedStyle(e);for(let a of o){let i=r.getPropertyValue(a).trim();i?t.style.setProperty(a,i):t.style.removeProperty(a)}},Xc=(e,t)=>{let o=I("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??jm,o.dir="auto",zc(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(o)}),Kc(o,e?.composer?.inputAttributes),o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=jc(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${n*20}px`;o.style.maxHeight=r,o.style.overflowY="auto";let a=()=>{let d=o.style.maxHeight;if(d!==r){let u=parseFloat(d);if(Number.isFinite(u)&&u>0)return u}let c=n*zm(o);return r=`${c}px`,o.style.maxHeight=r,c},i=()=>{o.addEventListener("input",()=>{o.style.height="auto";let d=Math.min(o.scrollHeight,a());o.style.height=`${d}px`})};return o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"}),{textarea:o,attachAutoResize:i}},eP="[data-persona-glyph-stack]",Qm=(e,t,o="send")=>{let n=Y("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":o,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Qc=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,n=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",i=t.tooltipText??"Send message",d=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||Xm,y=t.backgroundColor,x=t.textColor,T=I("div","persona-send-button-wrapper"),w=Y("button",{className:bo("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${Ko}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!y&&"persona-bg-persona-primary",!o&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:o?m:void 0,height:o?m:void 0,minWidth:o?m:void 0,minHeight:o?m:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:o&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:o?"0":t.paddingX||void 0,paddingRight:o?"0":t.paddingX||void 0,paddingTop:o?"0":t.paddingY||void 0,paddingBottom:o?"0":t.paddingY||void 0}}),k=null,P=null,R=null;if(o){let C=parseFloat(t.iconSize??"")||Math.round(h*.5),L=t.iconStrokeWidth??2,F=x?.trim()||"currentColor";r&&(k=ce(r,C,F,L)),P=ce(a,C,F,L),k&&P?(R=Qm(k,P),w.appendChild(R)):k?w.appendChild(k):(w.textContent=n,P=null)}else w.textContent=c;w.setAttribute("aria-label",i),T.appendChild(w),eo({anchor:w,trigger:T,text:()=>w.getAttribute("aria-label")??"",enabled:p});let b="send";return{button:w,wrapper:T,setMode:C=>{if(C===b)return;b=C;let L=C==="stop"?d:i;w.setAttribute("aria-label",L),w.setAttribute("data-persona-send-mode",C),o?(w.querySelector(eP)??R)?.setAttribute("data-mode",C):w.textContent=C==="stop"?u:c},glyphStack:R}},za=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let n=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",a=t.provider?.type==="custom";if(!(n||r||a))return null;let d=t.iconName??"mic",c=t.iconSize,u=parseFloat(c??"")||vo,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=I("div","persona-send-button-wrapper"),y=Y("button",{className:bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ko,!c&&vn),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=ce(d,u,m||"currentColor",1.5);T?y.appendChild(T):y.textContent="\u{1F3A4}",h.appendChild(y);let w=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return eo({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??w,enabled:k}),{button:y,wrapper:h}},Yc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=I("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??fr).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ko} ${vn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=ce(r,vo,"currentColor",1.5);d?i.appendChild(d):i.textContent="\u{1F4CE}",i.addEventListener("click",u=>{u.preventDefault(),n.click()}),a.appendChild(i);let c=t.buttonTooltipText??"Attach file";return eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:a,input:n,previewsContainer:o}},Jc=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=I("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let r=t.visible??!0;n.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let i=I("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=a,i.style.color="inherit",i.style.textDecoration="none",n.appendChild(i)}else n.textContent=a;return n},Zc=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function tP(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function eu(e){let{anchor:t,content:o,placement:n="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:i,verticalOffset:d,zIndex:c=2147483e3,onOpen:u,onDismiss:p}=e,m=e.container??tP(t),h=!1,y=null,x=()=>{if(!h)return;let k=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${k.width}px`),i&&(o.style.maxWidth=`${k.width}px`);let P=o.getBoundingClientRect(),R=d?.()??null,b=R!=null?k.top+R:k.top,A=n==="top-start"||n==="top-end"?b-r-P.height:k.bottom+r,L=n==="bottom-end"||n==="top-end"?k.right-P.width:k.left,F=i?.()??null;if(F!=null){let X=Math.max(k.left,k.right-P.width);L=Math.min(Math.max(k.left+F,k.left),X)}o.style.top=`${A}px`,o.style.left=`${L}px`},T=()=>{h&&(h=!1,y&&(y(),y=null),o.remove())},w=()=>{if(h)return;h=!0,c!=null&&(o.style.zIndex=String(c)),m.appendChild(o),x();let k=(t.ownerDocument??document).defaultView??window,P=t.ownerDocument??document,R=()=>{if(!t.isConnected){T(),p?.("anchor-removed");return}x()},b=C=>{let L=typeof C.composedPath=="function"?C.composedPath():[];L.includes(o)||L.includes(t)||(T(),p?.("outside"))},A=k.setTimeout(()=>{P.addEventListener("pointerdown",b,!0)},0);k.addEventListener("scroll",R,!0),k.addEventListener("resize",R),y=()=>{k.clearTimeout(A),P.removeEventListener("pointerdown",b,!0),k.removeEventListener("scroll",R,!0),k.removeEventListener("resize",R)},u?.()};return{get isOpen(){return h},open:w,close:T,toggle:()=>h?T():w(),reposition:x,destroy:T}}var oP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',nP=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Ym="data-persona-menu-focus",rP=new Set(["ArrowDown","ArrowUp","Home","End"]);function Yx(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(oP)??e}var sP=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Jx(e){let t=e.label,o=!1,n=I("div","persona-send-button-wrapper"),r=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Ko} ${vn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(r);let a=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let W=e.getButtonSize?.()??"";r.style.width=W,r.style.height=W,r.style.minWidth=W,r.style.minHeight=W,r.style.lineHeight="1",r.replaceChildren();let te=ce("plus",vo,"currentColor",1.5);te?r.appendChild(te):r.textContent="+"},d=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),a.setAttribute("aria-label",t)};d(),i();let c=[],u=-1,p=!1,m=()=>{let te=a.getRootNode().activeElement;return te instanceof HTMLElement?te:null},h=()=>{let W=m();for(let te of c){let Q=!!W&&Yx(te)===W;te.toggleAttribute(Ym,Q&&p)}},y=()=>c.filter(W=>W.isConnected||a.contains(W)).map(Yx).filter(W=>!sP(W)),x=(W,te)=>{W.forEach((Q,de)=>{Q.setAttribute("tabindex",de===te?"0":"-1")})},T=W=>{let te=y();if(te.length===0)return;let Q=(W%te.length+te.length)%te.length;u=Q,x(te,Q),te[Q].focus(),h()},w=()=>n.ownerDocument??document,k=null,P=null,R=null,b=()=>{k&&(w().removeEventListener("focusin",k,!0),k=null)},A=()=>{P&&(a.removeEventListener("focusin",P),P=null),R&&(a.removeEventListener("pointerdown",R,!0),R=null)},C=null,L=()=>(C||(C=eu({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),C),F=()=>C?.isOpen===!0,X=(W=!1)=>{if(F()){C?.close(),r.setAttribute("aria-expanded","false"),b(),A(),u=-1,p=!1;for(let te of c)te.removeAttribute(Ym);W&&r.focus()}},G=(W=0,te=!1)=>{if(o||F())return;p=te,Gc(r,a,nP),L().open(),r.setAttribute("aria-expanded","true");let Q=y();x(Q,-1),T(W<0?Q.length-1:W),k=de=>{let pe=typeof de.composedPath=="function"?de.composedPath():[];pe.includes(a)||pe.includes(n)||X()},w().addEventListener("focusin",k,!0),P=()=>h(),a.addEventListener("focusin",P),R=()=>{p=!1},a.addEventListener("pointerdown",R,!0)},E=W=>{W.preventDefault(),W.stopPropagation(),F()?X(!0):G(0)},O=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,F()?T(0):G(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,F()?T(-1):G(-1,!0))},D=W=>{switch(rP.has(W.key)&&(p=!0),W.key){case"ArrowDown":W.preventDefault(),T(u+1);return;case"ArrowUp":W.preventDefault(),T(u-1);return;case"Home":W.preventDefault(),T(0);return;case"End":W.preventDefault(),T(y().length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),X(!0);return;case"Tab":X(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",O),a.addEventListener("keydown",D),{trigger:n,triggerButton:r,panel:a,setItems:W=>{for(let Q of c)W.includes(Q)||Q.removeAttribute(Ym);if(c=[...W],!F())return;let te=y();x(te,Math.min(u,te.length-1)),h()},isOpen:F,open:()=>G(0),close:X,setLabel:W=>{W!==t&&(t=W,d())},applyButtonSize:i,destroy:()=>{o=!0,b(),A(),r.removeEventListener("click",E),r.removeEventListener("keydown",O),a.removeEventListener("keydown",D),C?.destroy(),C=null,n.remove(),a.remove(),c=[]}}}var $n={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Zx="data-persona-composer-action",Jm="data-persona-composer-disable-when-streaming",aP="core:overflow",iP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function lP(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let o=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(o))return o;let n=I("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let r=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(o)?o:null}function Zm(e){let t=e.clientWidth;if(!t)return 0;let o=e.ownerDocument?.defaultView;if(!o?.getComputedStyle)return t;let n=o.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-r)}var eC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},dP=(e,t)=>t.includes(":")?t:`${e}:${t}`;function cP(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let c=n.get(d.id);if(c){eC(t,`[Persona] composer action "${d.id}" is already contributed by ${tC(c)}; the ${tC(d)} copy is ignored.`);return}n.set(d.id,d),o.push(d)};for(let d of e.builtIns)a({id:d.id,placement:d.placement,presentation:"bar",order:d.order,sequence:r++,source:"core",builtIn:d});let i=(d,c,u)=>{let p=u?dP(u,d.id):d.id,m=d.order??$n.custom;d.placement==="end"&&m>=$n.send&&(eC(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${$n.send-1}.`),m=$n.send-1),a({id:p,placement:d.placement,presentation:d.presentation??"bar",order:m,sequence:r++,source:c,pluginId:u,action:d})};for(let d of e.configActions??[])i(d,"config");for(let d of e.plugins){if(!d.contributeComposerActions)continue;let c;try{c=d.contributeComposerActions(e.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${d.id}" contributeComposerActions failed:`,u);continue}for(let u of c??[])i(u,"plugin",d.id)}return o.sort((d,c)=>d.order===c.order?d.sequence-c.sequence:d.order-c.order)}var tC=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",oC=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,uP=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function pP(e,t){if(!e||e==="always")return!0;let o=uP(t);return e==="when-text"?o:!o}var zr=e=>e.kind==="custom",eg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,fP=e=>{let t=eg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},mP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function gP(e){let t="",o=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.nodeValue??"";return}if(n.nodeType!==Node.ELEMENT_NODE)return;let r=n;typeof r.matches=="function"&&r.matches(mP)||n.childNodes.forEach(o)};return o(e),t.trim()}var hP=e=>gP(e).length===0;function nC(e){let t=new Map,o=[],n=!1,r=()=>e.getButtonSize?.(),a=(E,O)=>{let D=E.button;if(!D)return;D.setAttribute("role","menuitem"),D.setAttribute("tabindex","-1"),D.className="persona-composer-overflow-menu__item";for(let Q of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])D.style[Q]="";D.style.lineHeight="1",O.tooltipText?D.setAttribute("title",O.tooltipText):D.removeAttribute("title"),D.replaceChildren();let W=I("span","persona-composer-overflow-menu__icon");if(O.iconName){let Q=ce(O.iconName,16,"currentColor",1.5);Q&&W.appendChild(Q)}let te=I("span","persona-composer-overflow-menu__label");te.textContent=O.shortLabel??O.label,D.append(W,te)},i=(E,O)=>{let D=E.button;if(!D)return;if(D.setAttribute("aria-label",O.label),O.pressed===void 0?D.removeAttribute("aria-pressed"):D.setAttribute("aria-pressed",O.pressed?"true":"false"),D.toggleAttribute(Jm,O.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,a(E,O);return}D.removeAttribute("role"),D.removeAttribute("tabindex"),D.removeAttribute("title");let W=r(),te=!!O.shortLabel;if(D.className=bo("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Ko,vn,te&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),D.style.width=W&&!te?W:"",D.style.height=W??"",D.style.minWidth=W&&!te?W:"",D.style.minHeight=W??"",D.style.fontSize=te?"":"18px",D.style.lineHeight="1",D.style.color=O.iconColor??"",D.style.backgroundColor=O.backgroundColor??"",D.replaceChildren(),O.iconName){let Q=ce(O.iconName,vo,"currentColor",1.5);Q&&D.appendChild(Q)}if(te){let Q=I("span","persona-composer-action-button__label");Q.textContent=O.shortLabel,D.appendChild(Q)}else D.firstChild||(D.textContent=O.label);E.tooltip?.destroy(),E.tooltip=eo({anchor:D,trigger:E.element,text:()=>O.tooltipText??O.label,enabled:!!O.tooltipText})},d=(E,O)=>{let D=E.action,W=Y("button",{attrs:{type:"button"}}),te=W;if(O==="bar"){let pe=I("div","persona-send-button-wrapper");pe.appendChild(W),te=pe}te.setAttribute(Zx,E.id);let Q={resolved:E,element:te,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:O},de=pe=>{if(pe.preventDefault(),pe.stopPropagation(),Q.busy||W.disabled)return;let Ce=Q.resolved.action;Q.mode==="menu"&&y?.close(!0);let Ee;try{Ee=Ce.onSelect(e.actionContext,pe)}catch(ge){e.reportError(ge,{actionId:Q.resolved.id});return}!Ee||typeof Ee.then!="function"||(Q.busy=!0,W.setAttribute("aria-busy","true"),Ee.catch(ge=>{e.reportError(ge,{actionId:Q.resolved.id})}).finally(()=>{Q.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",de),Q.detach=()=>W.removeEventListener("click",de),i(Q,D),Q},c=E=>{let O=E.action,D;try{D=O.render({...e.actionContext,id:E.id,action:O})}catch(W){return e.reportError(W,{actionId:E.id}),null}return D?.element?(D.element.setAttribute(Zx,E.id),D.element.toggleAttribute(Jm,O.disableWhenStreaming===!0),{resolved:E,element:D.element,owned:!0,managed:!0,destroy:D.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(E,O)=>{if(E.builtIn){let W=E.builtIn.element;return W?{resolved:E,element:W,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let D=E.action;return D?zr(D)?c(E):d(E,O):null},p=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(O){e.reportError(O,{actionId:E.resolved.id})}E.element.remove()}},m=(E,O)=>{for(let D=0;D<O.length;D++){let W=O[D];if(!W.managed)continue;let te=null;for(let Q=D+1;Q<O.length;Q++){let de=O[Q];if(!de.managed&&de.element.parentElement===E){te=de.element;break}}te?(W.element.parentElement!==E||W.element.nextSibling!==te)&&E.insertBefore(W.element,te):E.lastChild!==W.element&&E.appendChild(W.element)}},h=(E,O)=>{if(E.button){E.button.disabled=O;return}if(!E.owned)return;let D=E.element;D.toggleAttribute("data-disabled",O),D.setAttribute("aria-disabled",O?"true":"false");let W=D instanceof HTMLButtonElement||D instanceof HTMLSelectElement||D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement?D:D.querySelector("button, select, input, textarea");W&&(W.disabled=O)},y=null,x=null,T=null,w=0,k=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},P=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=Jx({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),R=E=>{x!==E&&(T?.disconnect(),x=E,w=Zm(E),!(typeof ResizeObserver>"u")&&(T=new ResizeObserver(O=>{let W=O[O.length-1]?.contentRect?.width??Zm(E);W!==w&&(w=W,X())}),T.observe(E)))},b=(E,O)=>{let D=lP(E.collapseAutoActionsBelow,O);if(D===null)return!1;let W=w||Zm(O);return W>0&&W<D},A=(E,O,D)=>{if(!O)return"bar";if(E.resolved.builtIn){let te=iP(E.resolved.id);return te&&O.includeBuiltIns?.includes(te)?"menu":"bar"}let W=E.resolved.presentation;return W==="overflow"||W==="auto"&&D?"menu":"bar"},C=E=>{let O=E.menuSlot;if(!O)return;if(!hP(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let D=fP(E.element);if(!D){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=I("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==D&&(E.menuLabel.textContent=D),E.menuLabel.parentElement!==O&&O.appendChild(E.menuLabel)},L=(E,O)=>{if(E.mode===O)return E;let D=E.resolved.action;if(D&&!zr(D)){p(E),t.delete(E.resolved.id);let W=d(E.resolved,O);return t.set(E.resolved.id,W),W}if(O==="menu"){let W=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Vm]:""}});W.appendChild(E.element),Vx(eg(E.element)),E.menuSlot=W;let te=Q=>{let de=eg(E.element);if(de.disabled)return;let pe=Q.target===de||de.contains(Q.target);y?.close(!0),pe||de.click()};W.addEventListener("click",te,!0),E.detachMenuSlot=()=>W.removeEventListener("click",te,!0),E.managed=!0,C(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=O,E},F=(E,O)=>{let D=O.map(W=>W.menuSlot??W.element);for(D.forEach((W,te)=>{let Q=E.children[te];Q!==W&&(Q?E.insertBefore(W,Q):E.appendChild(W))});E.children.length>D.length;)E.lastElementChild?.remove()},X=()=>{if(n)return;let E=e.getBindings();if(!E)return;let O=e.getState(),D=O.phase==="streaming",W=k();W&&R(E.footer);let te=W?b(W,E.footer):!1,Q={start:[],end:[]},de=[];for(let pe of o){let Ce=t.get(pe.id);if(!Ce)continue;let Ee=pe.action,ge=Ee?oC(Ee.visible,O,!0)&&pP(Ee.visibility,O):!0;if(Ce.visible!==ge&&(Ce.visible=ge,!ge&&Ce.managed&&(Ce.menuSlot??Ce.element).remove()),!!ge){if(Ce=L(Ce,A(Ce,W,te)),Ee){let Ke=oC(Ee.disabled,O,!1)||Ee.disableWhenStreaming===!0&&D;h(Ce,Ke),!zr(Ee)&&Ee.pressed!==void 0&&Ce.button?.setAttribute("aria-pressed",Ee.pressed?"true":"false")}Ce.mode==="menu"?(C(Ce),de.push(Ce)):Q[pe.placement].push(Ce)}}if(de.length>0){let pe=P();F(pe.panel,de),pe.setItems(de.map(Ke=>Ke.menuSlot??Ke.element)),pe.applyButtonSize();let Ce=Number.isFinite(W?.order)?W?.order:$n.overflow,Ee=Q.start.findIndex(Ke=>Ke.resolved.order>Ce),ge={resolved:{id:aP,placement:"start",presentation:"bar",order:Ce,sequence:-1,source:"core"},element:pe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};Q.start.splice(Ee<0?Q.start.length:Ee,0,ge)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(E.actionsStart,Q.start),m(E.actionsEnd,Q.end)};return{resolve:()=>{if(n)return;let E=cP(e.collect()),O=new Set(E.map(D=>D.id));for(let[D,W]of t)O.has(D)||(p(W),t.delete(D));for(let D of E){let W=t.get(D.id);if(!W){let pe=u(D,"bar");pe&&t.set(D.id,pe);continue}let te=W.resolved.action,Q=D.action;if(!!te!=!!Q||te&&Q&&zr(te)!==zr(Q)||te&&Q&&zr(te)&&zr(Q)&&te.render!==Q.render){p(W),t.delete(D.id);let pe=u(D,W.mode);pe&&t.set(D.id,pe);continue}W.resolved=D,D.builtIn?(W.managed=D.builtIn.managed===!0||W.mode==="menu",D.builtIn.element&&W.mode==="bar"&&(W.element=D.builtIn.element)):Q&&!zr(Q)?i(W,Q):Q&&W.element.toggleAttribute(Jm,Q.disableWhenStreaming===!0)}o=E,X()},sync:X,getResolved:()=>o,getOverflowMenu:()=>y,destroy:()=>{if(!n){n=!0,T?.disconnect(),T=null,x=null;for(let E of t.values())p(E);t.clear(),y?.destroy(),y=null,o=[]}}}}var yP="core:model",bP=700,rC=16,vP=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],sC=()=>{let e=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function aC(e){let t=e.label??"Model",o=e.presentation??"native",n=null,r=c=>{let u=e.getSelectedModelId();return c.find(p=>p.id===u)??c[0]},a=()=>{let c=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),u="",p=()=>{let T=e.getModels(),w=T.map(k=>`${k.id}:${k.label}`).join("|");w!==u&&(u=w,c.replaceChildren(...T.map(k=>{let P=Y("option",{attrs:{value:k.id}});return P.textContent=k.label,P}))),c.value=r(T)?.id??""};p(),n=p;let m=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",m);let h=T=>T.stopPropagation();c.addEventListener("click",h);let{wrapper:y,chevron:x}=sC();return y.append(c,x),{element:y,destroy:()=>{n===p&&(n=null),c.removeEventListener("change",m),c.removeEventListener("click",h)}}},i=()=>{let c=Y("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),u=I("span","persona-composer-model-picker-label"),p=I("span","persona-composer-model-picker-suffix");c.append(u,p);let m=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",x=null,T=()=>x?.isOpen===!0,w=(O=!1)=>{T()&&(x?.close(),c.setAttribute("aria-expanded","false"),O&&c.focus())},k=O=>{let D=[...h.values()];if(D.length===0)return;let W=(O%D.length+D.length)%D.length;D[W].focus()},P=O=>{if(T())return;x||(x=eu({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Gc(c,m,vP),x.open(),c.setAttribute("aria-expanded","true");let W=[...h.keys()].indexOf(r(e.getModels())?.id??"");k(O??(W>=0?W:0))},R=O=>{w(!0),e.onSelect(O)},b=O=>{O.preventDefault(),O.stopPropagation();let D=O.currentTarget.getAttribute("data-persona-model-option");D&&R(D)},A=O=>{let D=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":O.id}});if(O.icon){let pe=ce(O.icon,rC,"currentColor",1.5);if(pe){let Ce=I("span","persona-composer-model-option-icon");Ce.appendChild(pe),D.appendChild(Ce)}}let W=I("span","persona-composer-model-option-body"),te=I("span","persona-composer-model-option-label");if(te.textContent=O.label,W.appendChild(te),O.description){let pe=I("span","persona-composer-model-option-description");pe.textContent=O.description,W.appendChild(pe)}D.appendChild(W);let Q=I("span","persona-composer-model-option-check");Q.setAttribute("aria-hidden","true");let de=ce("check",rC,"currentColor",2);return de&&Q.appendChild(de),D.appendChild(Q),D.addEventListener("click",b),D},C=()=>{let O=e.getModels(),D=O.map(Q=>`${Q.id}:${Q.label}:${Q.icon??""}:${Q.description??""}`).join("|");if(D!==y){y=D;for(let Q of h.values())Q.removeEventListener("click",b);h.clear(),m.replaceChildren(...O.map(Q=>{let de=A(Q);return h.set(Q.id,de),de}))}let W=r(O);for(let[Q,de]of h)de.setAttribute("aria-selected",String(Q===W?.id));u.textContent=W?.label??"";let te=e.getSuffix?.()??"";p.textContent=te,c.setAttribute("aria-label",[t,[W?.label,te].filter(Boolean).join(" ")].filter(Boolean).join(": "))};C(),n=C;let L=O=>{O.preventDefault(),O.stopPropagation(),T()?w(!0):P()},F=O=>{if(O.key==="ArrowDown"){O.preventDefault(),T()?k(0):P(0);return}O.key==="ArrowUp"&&(O.preventDefault(),T()?k(-1):P(-1))},X=O=>{let D=[...h.values()],W=D.indexOf(O.target?.closest?.(".persona-composer-model-option"));switch(O.key){case"ArrowDown":O.preventDefault(),k(W+1);return;case"ArrowUp":O.preventDefault(),k(W-1);return;case"Home":O.preventDefault(),k(0);return;case"End":O.preventDefault(),k(D.length-1);return;case"Escape":O.preventDefault(),O.stopPropagation(),w(!0);return;case"Tab":w(!0);return;default:}};c.addEventListener("click",L),c.addEventListener("keydown",F),m.addEventListener("keydown",X);let{wrapper:G,chevron:E}=sC();return G.append(c,E),{element:G,destroy:()=>{n===C&&(n=null),c.removeEventListener("click",L),c.removeEventListener("keydown",F),m.removeEventListener("keydown",X);for(let O of h.values())O.removeEventListener("click",b);h.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:yP,kind:"custom",placement:"end",order:bP,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var tg="[data-persona-composer-chip-row]";function tu(e){e.style.display=e.childElementCount>0?"flex":"none"}function og(e){let t=e.querySelector(tg);if(t)return t;let o=Y("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});o.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(o,n):e.appendChild(o),o}var xP=":scope > [data-persona-composer-mode]";function iC(e){let t=e.row,o="",n=!1,r=new Set(e.initialIds??[]),a=u=>{let p=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let x=I("span","persona-mention-chip-icon"),T=ce(u.iconName,12,"currentColor",1.5);T&&x.appendChild(T),p.appendChild(x)}let m=I("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,p.appendChild(m);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),y=ce("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),e.onRemove(u.id)}),p.appendChild(h),p},i=()=>Array.from(t.querySelectorAll(xP)),d=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),tu(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!h||h==="none"){p();return}u.addEventListener("animationend",p,{once:!0}),u.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let u of i())u.remove()};return{element:t,render:(u,p)=>{if(n)return;let m=p.filter(T=>u.includes(T.id)),h=m.map(T=>`${T.id}:${T.shortLabel??T.label}`).join("|");if(h===o)return;o=h;let y=new Map;for(let T of i()){let w=T.getAttribute("data-persona-composer-mode");w&&m.some(P=>P.id===w)&&!T.hasAttribute("data-persona-chip-exit")?y.set(w,T):T.hasAttribute("data-persona-chip-exit")||d(T)}let x=t.firstChild;for(let T of m){let w=y.get(T.id);w||(w=a(T),r.has(T.id)||(w.setAttribute("data-persona-chip-enter",""),w.addEventListener("animationend",()=>w?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(T.id),w!==x&&t.insertBefore(w,x),x=w.nextSibling}tu(t)},destroy:()=>{n=!0,c(),tu(t)}}}var lC=e=>`core:mode:${e}`;var ng=e=>Math.min(300+e,499),dC=e=>`core:mode-group:${e}`;function ou(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function CP(e,t){return e?t?.find(o=>o.id===e)?.chipVisibility==="hidden":!1}function cC(e,t){return e?.length?e.filter(o=>!ou(o.groupId,t)&&!CP(o.groupId,t)):[]}var SP=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function uC(e,t,o,n){let r=o.find(d=>d.id===t);if(!r)return[...e];let a=e.includes(t),i=new Set(e);if(a)i.delete(t);else{if(SP(r,n)==="single"){let d=o.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!d.includes(c)))}i.add(t)}return o.filter(d=>i.has(d.id)).map(d=>d.id)}function nu(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function pC(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function fC(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var wP=16;function mC(e){let t=null;return{action:{id:dC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let n=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,a="",i=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},d=u=>{let p=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let h=ce(u.iconName,wP,"currentColor",1.5);h&&p.appendChild(h)}let m=I("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,p.appendChild(m),p.addEventListener("click",i),p},c=()=>{let u=e.getGroup();u?.label?(n.setAttribute("role","group"),n.setAttribute("aria-label",u.label)):(n.removeAttribute("role"),n.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==a){a=m;for(let x of r.values())x.removeEventListener("click",i);r.clear();let y=p.map(x=>{let T=d(x);return r.set(x.id,T),T});n.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,x]of r)x.setAttribute("aria-pressed",String(h.includes(y)))};return c(),t=c,{element:n,destroy:()=>{t===c&&(t=null);for(let u of r.values())u.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}function gC(e){let t=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let o="",n=!1,r=a=>{let i=I("span","persona-composer-quote-bar"),d=I("div","persona-composer-quote-content");if(a.sourceLabel){let m=I("div","persona-composer-quote-source");m.textContent=a.sourceLabel,d.appendChild(m)}let c=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Ic(a.text),d.appendChild(c);let u=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=ce("x",12,"currentColor",2);p?u.appendChild(p):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,d,u)};return{element:t,render:a=>{if(n)return;let i=a?`${a.sourceLabel??""}\0${a.text}`:"";if(i!==o){if(o=i,!a){t.replaceChildren(),t.style.display="none";return}r(a),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function hC(e){let t=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let o,n=!1,r=(i,d,c,u)=>{let p=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":d,[c]:""}}),m=ce(i,12,"currentColor",2);return m?p.appendChild(m):p.textContent=d,p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),p},a=i=>{let d=Ic(i.text??"",90);if(d)return d;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(n||i===o)return;if(o=i,!i){t.replaceChildren(),t.style.display="none";return}let d=I("span","persona-composer-pending-badge");d.textContent=e.label??"Sends next";let c=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=a(i),t.replaceChildren(d,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function yC(e){let t=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),o=Y("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});o.value=e.initialText;let n=()=>{o.style.height="auto",o.style.height=`${o.scrollHeight}px`};o.addEventListener("input",n);let r=I("div","persona-message-edit-actions"),a=(d,c,u,p)=>{let m=Y("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[u]:""},text:d});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),m},i=()=>{let d=o.value.trim();d&&e.onSave(d)};return r.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),o.addEventListener("keydown",d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),e.onCancel();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}),t.append(o,r),{element:t,getValue:()=>o.value,focus:()=>{o.focus();let d=o.value.length;o.setSelectionRange(d,d),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function bC(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 vC(e,t){if(!e||typeof e.text!="string")return;let o=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(c=>o.has(c.sourceId)),r=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>a.has(c)),d=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:n}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...d?{selectedModelId:d}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function xC(e){let t=e.delay??500,o=null,n=!1,r=()=>{o!==null&&(clearTimeout(o),o=null)};return{schedule:()=>{n||(r(),o=setTimeout(()=>{o=null,e.write()},t))},flush:()=>{n||o===null||(r(),e.write())},cancel:r,destroy:()=>{n=!0,r()}}}function CC(e){return e.wrapped||e.text.includes(`
24
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function SC(){let e=!1;return{observe:(t,o)=>o?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function wC(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let o=t.getComputedStyle(e),n=Number.parseFloat(o.lineHeight),r=Number.parseFloat(o.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(r)&&r>0?r*1.4:0;if(!a)return!1;let i=(Number.parseFloat(o.paddingTop)||0)+(Number.parseFloat(o.paddingBottom)||0);return e.scrollHeight-i>a*1.5}function AC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function rg(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 TC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var AP=e=>typeof e?.then=="function";function MC(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function EC(e,t,o){let n;try{n=e(rg(t),{signal:o})}catch(r){return{status:"error",error:r}}return AP(n)?Promise.resolve(n).then(r=>o.aborted?{status:"aborted"}:MC(t,r),r=>o.aborted?{status:"aborted"}:{status:"error",error:r}):MC(t,n)}var PC=/\s/;function MP(e,t,o){if(o==="input-start")return t===0;let n=t>0?e[t-1]:"";return o==="line-start"?n===""||n===`
25
- `:n===""||PC.test(n)}function TP(e,t,o="@",n="anywhere",r=!1){if(!o||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let i=e[a];if(i===o)return MP(e,a,n)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(i===`
26
- `||i==="\uFFFC"||!r&&PC.test(i))return null;a--}return null}function kC(e,t,o){for(let n of o){let r=TP(e,t,n.trigger,n.position??"anywhere",n.allowSpaces??!1);if(r)return{channel:n,match:r}}return null}function LC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function IC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},o=(e.triggers??[]).map(n=>({trigger:n.trigger,position:n.triggerPosition??"anywhere",allowSpaces:n.allowSpaces??!1,sources:Array.isArray(n.sources)?n.sources:[],searchPlaceholder:n.searchPlaceholder,showButton:n.showButton===!0,buttonIconName:n.buttonIconName,buttonTooltipText:n.buttonTooltipText}));return[t,...o]}function RC(e){let{config:t,onOpen:o}=e,n=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Ko} ${vn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),d=ce(n,vo,"currentColor",1.5);return d?i.appendChild(d):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),o()}),a.appendChild(i),eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:a}}var{setLoader:EP,load:PP}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),HC=EP,sg=PP;var{setLoader:kP,load:LP}=mt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),WC=kP,BC=LP;function Sl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let o=Y("span",{className:bo("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&o.style.setProperty("--persona-mention-token-accent",e.color);let n=ce(e.iconName??"at-sign",13,"currentColor",2);if(n){let r=I("span","persona-mention-token-icon");r.appendChild(n),o.appendChild(r)}return o.appendChild(Y("span",{className:"persona-mention-token-label",text:`@${e.label}`})),o}function OC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let o=IC(t).filter(b=>b.sources.length>0);if(o.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let n=o.filter(b=>b.sources.some(A=>typeof A.matchCommand=="function")),r=b=>n.some(A=>A.trigger?A.position==="line-start"?b.split(`
23
+ `),d=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(d){let u=[];a&&u.push(rn(a)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(c){let u=[];i&&u.push(rn(i)),u.push(...r.contentParts),t.contentParts=u}else a&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,o){let n=t.trim(),r=!!o?.replayFields&&(o.replayFields.llmContent!==void 0||o.replayFields.rawContent!==void 0||(o.replayFields.contextMentions?.length??0)>0);if(!n&&(!o?.contentParts||o.contentParts.length===0)&&(!o?.mentions||o.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let a=Wa(),i=Vr();this.activeAssistantMessageId=null;let d=o?.contentParts&&Fa(o.contentParts)?Na:"",c={id:a,role:"user",content:n||d,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:o?.viaVoice||!1,...o?.contentParts&&o.contentParts.length>0&&{contentParts:o.contentParts},...o?.mentions&&o.mentions.refs.length>0&&{contextMentions:o.mentions.refs},...o?.contentSegments&&o.contentSegments.length>0&&{contentSegments:o.contentSegments},...o?.composerOptions&&{composerOptions:o.composerOptions},...o?.replayFields??{}};this.appendMessage(c),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,o?.mentions){let m=this.messages.find(h=>h.id===a)??c;if(await this.applyMentionBundle(m,n,o.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(o?.quote&&!o.replayFields){let m=this.messages.find(y=>y.id===a)??c,h=Cx({quote:o.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...o.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,u,i,a,{composerOptions:o?.composerOptions,interrupt:o?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=om(m,this.config.errorMessage);if(y){let x={id:i,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(x)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,o){let n=Sx(this.messages,t);if(!n)return!1;let r=this.messages[n.start],a=o.replacement,i=a?a.text:r.content,d=a?a.contentParts:r.contentParts;if(!(!!i?.trim()||(d?.length??0)>0||!a&&(r.llmContent?.trim()?.length??0)>0))return!1;let u=a?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},p=a?this.toComposerOptionsPayload(a.options):r.composerOptions,m=a?a.contentSegments:r.contentSegments,h=a?a.options?.quote:void 0,y=a?a.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(i??"",{...d?.length?{contentParts:[...d]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...h?{quote:h}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let o={};return t.selectedModelId&&(o.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(o.activeModeIds=[...t.activeModeIds]),Object.keys(o).length>0?o:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=Vr();this.activeAssistantMessageId=null,this.setStreaming(!0);let o=new AbortController;this.abortController=o;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:o.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let i=om(r,this.config.errorMessage);if(i){let d={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(d)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,o){if(this.streaming&&!o?.allowReentry)return;o?.allowReentry||this.abortController?.abort(),o?.preserveAssistantId&&o.assistantMessageId&&(this.activeAssistantMessageId=o.assistantMessageId);let n=o?.preserveAssistantId?o.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==n&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,o?.assistantMessageId,o?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(o=>this.requestWebMcpApproval(o))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let o={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},n=`approval-${o.id}`;return this.upsertMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o}),new Promise(r=>{this.webMcpApprovalResolvers.set(n,r)})}resolveWebMcpApproval(t,o){let n=this.webMcpApprovalResolvers.get(t);if(!n)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:o,resolvedAt:Date.now()}}),n(o==="approved")}async resolveApproval(t,o,n){let r=`approval-${t.id}`,a={...t,status:o,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),d={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(d),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,u=c&&typeof c=="object"?c.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},o,n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},o),p){let m=null;if(p instanceof Response){if(!p.ok){let h=await p.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m,{allowReentry:!0}):(o==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:o.answers,askUserQuestionIndex:o.currentIndex}})}markAskUserQuestionResolved(t,o){let n=this.messages.find(r=>r.id===t.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...o?{askUserQuestionAnswers:o}:{}}})}async resolveAskUserQuestion(t,o){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof o=="string"?void 0:o;if(i===void 0&&typeof o=="string"){let p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(i={[h]:o})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=t.toolCall.id,c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===0){let p=typeof o=="string"?o:Object.entries(o).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${d}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let x=p[y],T=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";this.appendMessage({id:`ask-user-q-${d}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${d}-${h}`,role:"user",content:T||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[a]:o},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.id;if(!o||!n){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(o);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(o,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let o of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(o)})}flushWebMcpAwaitBatch(t){let o=this.webMcpAwaitBatches.get(t);if(!o)return;this.webMcpAwaitBatches.delete(t);let{snapshots:n}=o;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.resolveWebMcpToolCallBatch(t,n)}resolveWebMcpToolStartedAt(t){let n=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of n)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Un?!1:(this.messages.find(n=>n.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let o=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:o,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),o}markWebMcpToolComplete(t,o,n,r=Date.now(),a){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:o,startedAt:n,completedAt:r,duration:void 0,durationMs:Math.max(0,r-n)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,o){let n=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=async c=>{let u=c.toolCall?.name,p=c.toolCall?.id;if(!u||!p)return null;let m=`${t}:${p}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(c))return null;this.webMcpInflightKeys.add(m),n.push(m);let h=this.markWebMcpToolRunning(c),y=c.agentMetadata?.webMcpToolCallId??u;if(u===Un)return{dedupeKey:m,resumeKey:y,output:Xv(),toolMessage:c,startedAt:h,completedAt:Date.now()};let x=this.client.executeWebMcpToolCall(u,c.toolCall?.args,r.signal),T;if(!x)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await x}catch(w){let k=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));return k||this.callbacks.onError?.(w instanceof Error?w:new Error(String(w))),this.markWebMcpToolComplete(c,nm(k?"Aborted by cancel()":WE(w)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(c,nm("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:T,toolMessage:c,startedAt:h,completedAt:Date.now()}},i;if(this.config.webmcp?.execution==="sequential"){i=[];for(let c of o)i.push(await a(c))}else i=await Promise.all(o.map(a));let d=[];try{if(d=i.filter(p=>p!==null),d.length===0)return;let c={};for(let p of d)c[p.resumeKey]=p.output;let u=await this.client.resumeFlow(t,c,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of d)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===Un?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let p of d)this.markWebMcpToolComplete(p.toolMessage,nm("Aborted by cancel()"),p.startedAt)}finally{for(let c of n)this.webMcpInflightKeys.delete(c);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let o=t.agentMetadata?.executionId,n=t.toolCall?.name,r=t.toolCall?.id;if(!o){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!n)return;if(!r){let i=`${o}:__no_tool_id__:${n}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i))return;this.webMcpInflightKeys.add(i);try{await this.resumeWithToolOutput(o,n,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(i)}catch(d){this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}finally{this.webMcpInflightKeys.delete(i)}return}let a=`${o}:${r}`;if(!(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(o,[t])}async resumeWithToolOutput(t,o,n,r){let a=await this.client.resumeFlow(t,{[o]:n},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!a.ok){let i=await a.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let o=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=t.artifactType==="markdown"?{id:o,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:o,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(o,n),this.selectedArtifactId=o,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(n),n}injectArtifactRefBlock(t){let o=`artifact-ref-${t.id}`,n=Fn(this.config.features?.artifacts,t),r=ol(n,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(i=>i.id===o);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:o,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let o of this.artifacts.values()){let n=this.messages.find(i=>i.id===`artifact-ref-${o.id}`);if(!n)continue;let r=Fn(this.config.features?.artifacts,o),a=ol(r,{artifactId:o.id,title:o.title,artifactType:o.artifactType,status:o.status,...o.file?{file:o.file}:{},...o.presentation?{presentation:o.presentation}:{},...o.component?{component:o.component}:{},...o.props?{componentProps:o.props}:{},...o.markdown!==void 0?{markdown:o.markdown}:{}});n.rawContent!==a&&(n.rawContent=a,n.streaming=o.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);o?.artifactType==="markdown"&&(o.markdown=(o.markdown??"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);o?.artifactType==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>({...o,streaming:!1,sequence:o.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,o=null){this.artifacts.clear();for(let n of t)this.artifacts.set(n.id,{...n,status:"complete"});this.selectedArtifactId=o,this.emitArtifactsState()}trackCursor(t){let o=this.agentExecution?.executionId;if(!o||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let n=this.resumable===null;this.resumable={executionId:o,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(n)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Lx().then(({createReconnectController:t})=>{let o=t(this.buildReconnectHost());return this.reconnectController=o,o}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:o=>t.setStatus(o),setStreaming:o=>t.setStreaming(o),setReconnecting:o=>{t.reconnecting=o},setAbortController:o=>{t.abortController=o},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(o,n,r)=>t.connectStream(o,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:o=>t.appendMessage(o),nextSequence:()=>t.nextSequence(),emitReconnect:o=>t.callbacks.onReconnect?.(o),buildErrorContent:o=>om(new Error(o),t.config.errorMessage),onError:o=>t.callbacks.onError?.(o)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let o=this.reopenTrailingAssistant();o||(o=Vr(),this.appendMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=o,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:o,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let o=this.messages[t];if(o.role==="assistant"&&!o.variant)return o.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),o.id;if(o.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let o=this.config.onExecutionState;if(o){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),o(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let o=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),o&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let n=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Zf(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ul(t)}toggleReadAloud(t){let o=this.messages.find(a=>a.id===t);if(!o||o.role!=="assistant")return;let n=Zf(o.content||"");if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let o=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let o=this.ensureSequence(t),n=this.messages.findIndex(r=>r.id===o.id);if(n===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,a)=>{if(a!==n)return r;let i={...r,...o};if(r.agentMetadata?.askUserQuestionAnswered===!0&&o.agentMetadata&&(i.agentMetadata={...o.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&o.agentMetadata&&(i.agentMetadata={...i.agentMetadata??o.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&o.approval&&r.approval.id===o.approval.id){let p=r.approval,m=o.approval;i.approval={...p,...m,executionId:m.executionId||p.executionId,toolName:m.toolName||p.toolName,description:m.description||p.description,toolType:m.toolType??p.toolType,reason:m.reason??p.reason,parameters:m.parameters??p.parameters}}let d=o.toolCall?.name,c=o.agentMetadata?.executionId,u=o.toolCall?.id;if(d&&Ix(d)&&c&&u&&o.agentMetadata?.awaitingLocalTool===!0){let p=`${c}:${u}`,m=this.webMcpInflightKeys.has(p),h=this.webMcpResolvedKeys.has(p),y=r.toolCall?.name,x=r.agentMetadata?.executionId===c&&r.toolCall?.id===u&&y!==void 0&&Ix(y)&&r.toolCall?.status==="complete";(m||h||x)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((o,n)=>{let r=new Date(o.createdAt).getTime(),a=new Date(n.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let i=o.sequence??0,d=n.sequence??0;return i!==d?i-d:o.id.localeCompare(n.id)})}};var $a=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var rm=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var sm=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var pl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var am=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var im=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var lm=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var dm=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Va=[["path",{d:"M20 6 9 17l-5-5"}]];var fl=[["path",{d:"m6 9 6 6 6-6"}]];var cm=[["path",{d:"m15 18-6-6 6-6"}]];var um=[["path",{d:"m9 18 6-6-6-6"}]];var Fs=[["path",{d:"m18 15-6-6-6 6"}]];var pm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var fm=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Hc=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var ja=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var mm=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Wc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Bc=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var gm=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var hm=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var ml=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var gl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Us=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var hl=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var ym=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var bm=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Oc=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var vm=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var xm=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Cm=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var yl=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Sm=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var wm=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Am=[["path",{d:"M5 12h14"}]];var Dc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M9 3v18"}]];var Mm=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Tm=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Em=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Pm=[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]];var km=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Lm=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Im=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Rm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Hm=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var _c=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Wm=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Bm=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Om=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Dm=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var _m=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Nm=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Fm=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Um=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var bl=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var _t=(e,t=24,o="currentColor",n=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(n)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let i=a[0],d=a[1];if(!d)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(d).forEach(([u,p])=>{u!=="stroke"&&c.setAttribute(u,String(p))}),r.appendChild(c)}),r};var{setLoader:BE,load:OE}=gt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")}),Rx=BE,Nc=OE;var DE={activity:$a,"arrow-down":rm,"arrow-up":im,"arrow-up-right":am,bot:dm,"chevron-down":fl,"chevron-up":Fs,"chevron-right":um,"chevron-left":cm,check:Va,clipboard:fm,"clipboard-copy":pm,"code-xml":Hc,copy:ja,file:hl,"file-code":ml,"file-spreadsheet":gl,"file-text":Us,"image-plus":bm,loader:vm,"loader-circle":Oc,mic:Sm,paperclip:Mm,quote:Pm,"refresh-cw":km,search:Lm,send:Im,"shield-alert":Rm,"shield-check":Hm,"shield-x":_c,square:Wm,"thumbs-down":Om,"thumbs-up":Dm,upload:Fm,"volume-2":Um,x:bl,"at-sign":lm,"arrow-left":sm,"arrow-right":pl,"external-link":gm,ellipsis:Bc,"ellipsis-vertical":Wc,menu:Cm,"panel-left":Dc,plus:Em,minus:Am,pencil:Tm,trash:Nm,"trash-2":_m,download:mm,maximize:xm,minimize:wm,"message-square":yl,star:Bm,eye:hm,history:ym},_E=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],vl=new Map(Object.entries(DE)),za=new Set,Fc=!1,Uc=new Set,Hx=e=>{let t=[...Uc];e&&Uc.clear();for(let o of t)try{o()}catch{}},Wx=e=>Fc?()=>{}:(Uc.add(e),()=>{Uc.delete(e)}),Bx=()=>{let e=0;for(let t of[...za]){let o=vl.get(t.name);if(!o)continue;za.delete(t),e++;let n=_t(o,t.size,t.color,t.strokeWidth);if(n)for(t.el.removeAttribute("data-persona-icon-pending");n.firstChild;)t.el.appendChild(n.firstChild)}return e},Ox=e=>{for(let[t,o]of Object.entries(e))vl.set(t,o);Bx()>0&&!Fc&&Hx(!1)};var qm=!1,NE=()=>{Nc().then(e=>{if(!Fc){for(let[t,o]of Object.entries(e.EXTRA_LUCIDE_ICONS))vl.has(t)||vl.set(t,o);Fc=!0,Bx(),Hx(!0)}}).catch(e=>{qm=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},FE=(e,t,o)=>{let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",t),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("data-persona-icon-pending","true"),n},ue=(e,t=24,o="currentColor",n=2)=>{let r=vl.get(e);if(r)return _t(r,t,o,n);if(_E.includes(e)){qm&&(qm=!1);let a=FE(t,o,n);if(za.size>=500){let i=za.values().next().value;i&&za.delete(i)}return za.add({el:a,name:e,size:t,color:o,strokeWidth:n}),NE(),a}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};var UE={add:e=>ax(e)},qE=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,qc={allowedTypes:hr,maxFileSize:10*1024*1024,maxFiles:4};function $E(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function VE(e){return e==="application/pdf"?Us:e.startsWith("text/")?Us:e.includes("word")?Us:e.includes("excel")||e.includes("spreadsheet")?gl:e==="application/json"?ml:hl}var qs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??qc.allowedTypes,maxFileSize:t.maxFileSize??qc.maxFileSize,maxFiles:t.maxFiles??qc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:UE}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let o of this.attachments)this.renderPreview(o)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:qc.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let o=[];for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let r=ix(n,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,i);continue}let a={id:$E(),file:n,previewUrl:Lc(n)?URL.createObjectURL(n):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(a),this.renderPreview(a),o.push(a)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(o.map(n=>this.runAdd(n)))}async runAdd(t){let o=new AbortController;this.pendingAdds.set(t.id,o);let n=()=>this.destroyed||o.signal.aborted||this.pendingAdds.get(t.id)!==o||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:o.signal,onProgress:a=>{n()||t.status!=="uploading"||(t.progress=qE(a),this.updatePreview(t),this.notify())}});if(n())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(n())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===o&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let o=this.attachments.find(n=>n.id===t);!o||o.status!=="error"||this.destroyed||(o.status=this.hasCustomAdapter()?"uploading":"processing",o.progress=this.hasCustomAdapter()?0:void 0,o.error=void 0,this.updatePreview(o),this.notify(),this.runAdd(o))}abortAdd(t){let o=this.pendingAdds.get(t);o&&(this.pendingAdds.delete(t),o.abort())}removeAttachment(t){let o=this.attachments.findIndex(a=>a.id===t);if(o===-1)return;let n=this.attachments[o];this.abortAdd(t),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(o,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),n.status==="ready"&&n.contentPart&&this.releasePart(n.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let o=this.config.adapter?.remove;if(o)try{let n=o(t,{signal:new AbortController().signal});n&&typeof n.catch=="function"&&n.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(n){console.error("[AttachmentManager] adapter.remove failed:",n)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let o=Lc(t.file),n=I("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",t.id),n.style.width="48px",n.style.height="48px",o&&t.previewUrl){let p=I("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",n.appendChild(p)}else{let p=I("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=VE(t.file.type),h=_t(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=I("span");y.textContent=lx(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",p.appendChild(y),n.appendChild(p)}let r=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),a=I("div","persona-attachment-progress");a.appendChild(I("div","persona-attachment-progress__bar"));let i=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),d=ue("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);d?i.appendChild(d):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(a,i),n.appendChild(r);let c=I("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let u=_t(bl,10,"var(--persona-text-inverse, #ffffff)",2);u?c.appendChild(u):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),n.appendChild(c),this.previewsContainer.appendChild(n),this.applyPreviewState(n,t)}updatePreview(t){let o=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);o&&this.applyPreviewState(o,t)}applyPreviewState(t,o){t.dataset.status=o.status;let n=o.status!=="ready"&&o.status!=="error";t.setAttribute("aria-busy",n?"true":"false"),t.title=o.status==="error"?`${o.file.name}: ${o.error??"Upload failed"}`:o.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let a=o.progress;r.style.width=typeof a=="number"?`${Math.round(a*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,o){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:o,adapter:t?.adapter})}};var Dx=(e,t)=>e.length===t.length&&e.every((o,n)=>o===t[n]),jE=(e,t)=>e.length===t.length&&e.every((o,n)=>{let r=t[n];return o.id===r.id&&o.name===r.name&&o.mimeType===r.mimeType&&o.size===r.size&&o.status===r.status&&o.progress===r.progress&&o.error===r.error});function _x(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,o=null,n=!1,r=!1,a=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let p=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},d=()=>(o||(o=i()),o),c=()=>{if(n=!1,r||t.size===0)return;let p=d();for(let m of[...t])try{m(p)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},u=()=>{o=null,!(r||n)&&(n=!0,queueMicrotask(c))};return{getState:d,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,u())},setAttachments:p=>{jE(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{Dx(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{Dx(e.activeModeIds,p)||(e.activeModeIds=[...p],u())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,u())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,u())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,u())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,u())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,u())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,u())},flush:()=>{n&&c()},destroy:()=>{r=!0,n=!1,t.clear()}}}var Lo=(e,...t)=>{for(let o of t){let n=e.querySelector(o);if(n)return n}return null},Nx=(e,t)=>{let o=I("div",e);return o.setAttribute(t,""),o.setAttribute("data-persona-composer-synthesized",""),o.style.display="contents",o};function Fx(e,t={}){let o=Lo(e,"[data-persona-composer-form]"),n=Lo(e,"[data-persona-composer-input]");if(!o||!n){let k=`[Persona] composer surface is missing required element(s): ${[!o&&"form",!n&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(o||n))throw new Error(k);return typeof console<"u"&&console.warn(k),null}let r={header:Lo(e,"[data-persona-composer-header]"),body:Lo(e,"[data-persona-composer-body]"),actionsStart:Lo(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Lo(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Lo(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Lo(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Lo(e,"[data-persona-composer-status]")},a=new Set,i=r.header;i||(a.add("header"),i=Nx("persona-widget-composer__header","data-persona-composer-header"),o.parentNode?o.parentNode.insertBefore(i,o):e.appendChild(i));let d=r.body??n.parentElement??o,c=(w,k,P,H,b)=>{if(k)return k;a.add(w);let A=Nx(P,H);return b.appendChild(A),A},u=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",o),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",o),m=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],x=(w,k)=>w.target===k.target&&w.type===k.type&&w.handler===k.handler,T=Lo(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:o,input:n,header:i,body:d,actionsStart:u,actionsEnd:p,suggestions:m,status:h,attachmentInput:T,attachmentPreviews:Lo(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Lo(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Lo(e,"[data-persona-composer-submit]")??void 0,micButton:Lo(e,"[data-persona-composer-mic]")??void 0,synthesized:a,found:r,addListener:(w,k,P,H)=>{w.addEventListener(k,P,H),y.push({target:w,type:k,handler:P,options:H})},removeListener:(w,k,P,H)=>{w.removeEventListener(k,P,H),y=y.filter(b=>!x(b,{target:w,type:k,handler:P}))},destroy:()=>{for(let w of y)w.target.removeEventListener(w.type,w.handler,w.options);y=[]}}}var Nt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},ro=1e5,Ka=ro+1;var zE=8,KE=8,$m=10,Ux=200,qx=300,$x=0,Vc=e=>Math.max(0,e);function Vx(e){e.delayMs!==void 0&&(Ux=Vc(e.delayMs)),e.skipDelayMs!==void 0&&(qx=Vc(e.skipDelayMs))}var GE=()=>Date.now()<$x,XE=e=>{$x=e>0?Date.now()+e:0},$c=new WeakMap,jm="data-persona-tooltip-suppressed",QE=e=>typeof e.closest=="function"&&e.closest(`[${jm}]`)!==null;function jx(e){$c.get(e)?.hide()}var zx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,YE=e=>{let t=e.getRootNode?.();return zx(t)?t:e.ownerDocument.body},Vm=(e,t,o)=>Math.min(Math.max(e,t),Math.max(t,o)),JE=[...["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 eo(e){$c.get(e.anchor)?.destroy();let{anchor:t,trigger:o=t,text:n,hint:r,enabled:a=!0,gap:i=zE,viewportPadding:d=KE}=e,c=()=>t.ownerDocument,u=()=>c().defaultView??window,p=null,m=null,h=null,y=null,x,T=!1,w=!1,k=!1,P=()=>(typeof n=="function"?n():n).trim(),H=()=>(typeof r=="function"?r():r??"").trim(),b=()=>Vc(e.delayMs??Ux),A=()=>Vc(e.skipDelayMs??qx),C=()=>{x!==void 0&&(u().clearTimeout(x),x=void 0)},L=()=>{C();let xe=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,xe&&XE(A())},U=()=>{if(!p)return;let xe=c(),Re=u(),He=t.getBoundingClientRect(),we=p.getBoundingClientRect(),pt=xe.documentElement.clientWidth||Re.innerWidth,ke=xe.documentElement.clientHeight||Re.innerHeight,z=pt-d-we.width,Ve=He.left+He.width/2-we.width/2,Xe=Vm(Ve,d,z),At=He.top-d,Ie=ke-d-He.bottom,Pe=we.height+i,be=At>=Pe||At>=Ie?"top":"bottom",xn=be==="top"?He.top-i-we.height:He.bottom+i,Cn=ke-d-we.height,ea=Vm(xn,d,Cn),It=He.left+He.width/2,Sn=Math.max($m,we.width-$m),zo=Vm(It-Xe,$m,Sn);p.dataset.placement=be,p.style.left=`${Xe}px`,p.style.top=`${ea}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${zo}px`)},Q=()=>{if(k||!a||p||!t.isConnected||QE(t))return;let xe=P(),Re=YE(t);if(!xe||!Re)return;let He=c(),we=u();p=He.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(Ka);let pt=we.getComputedStyle?.(t);if(pt){for(let Pe of JE){let be=pt.getPropertyValue(Pe).trim();be&&p.style.setProperty(Pe,be)}pt.fontFamily&&(p.style.fontFamily=pt.fontFamily)}m=He.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=xe,p.appendChild(m);let ke=H();ke&&(h=He.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=ke,p.appendChild(h));let z=He.createElement("span");z.className="persona-control-tooltip__arrow",p.appendChild(z),Re.appendChild(p),U(),p.dataset.state="open";let Ve=()=>{if(!t.isConnected){L();return}m&&(m.textContent=P()),h&&(h.textContent=H()),U()};we.addEventListener("scroll",Ve,!0),we.addEventListener("resize",Ve);let Xe=t.getRootNode(),At=zx(Xe)?Xe:He.documentElement,Ie=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||L()});Ie?.observe(At,{childList:!0,subtree:!0}),y=()=>{we.removeEventListener("scroll",Ve,!0),we.removeEventListener("resize",Ve),Ie?.disconnect()}},$=xe=>{if(!(k||p)){if(C(),xe||b()<=0||GE()){Q();return}x=u().setTimeout(()=>{x=void 0,Q()},b())}},E=()=>{T||w?$(w):L()},B=()=>{let xe=u();(!xe.matchMedia||!xe.matchMedia("(hover: none)").matches)&&(T=!0,E())},D=()=>{T=!1,E()},W=()=>{try{w=t.matches(":focus-visible")}catch{w=!0}E()},te=()=>{w=!1,E()},X=()=>{T=!1,w=!1,L()},fe=xe=>{xe.key==="Escape"&&X()};o.addEventListener("mouseenter",B),o.addEventListener("mouseleave",D),t.addEventListener("focus",W),t.addEventListener("blur",te),t.addEventListener("keydown",fe),t.addEventListener("click",X);let le={get isOpen(){return p!==null},show:Q,hide:L,reposition:U,destroy:()=>{k||(k=!0,L(),o.removeEventListener("mouseenter",B),o.removeEventListener("mouseleave",D),t.removeEventListener("focus",W),t.removeEventListener("blur",te),t.removeEventListener("keydown",fe),t.removeEventListener("click",X),$c.delete(t))}};return $c.set(t,le),le}var Kx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ga(e,t){if(!e)return t;if(!t)return e;let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];Kx(a)&&Kx(r)?o[n]=Ga(a,r):o[n]=r}return o}var $o="min(440px, calc(100vw - 24px))",jc="440px",zm="How can I help...",ZE={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:$o,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)"},st={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:ZE,copy:{inputPlaceholder:zm,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",borderWidth:"0px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Gx(e,t){if(!(!e&&!t))return e?t?Ga(e,t):e:t}function Xa(e){return e?{...st,...e,theme:Gx(st.theme,e.theme),darkTheme:Gx(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...st.tooltip,...e.tooltip},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,o=e.features?.artifacts,n=st.features?.scrollToBottom,r=e.features?.scrollToBottom,a=st.features?.scrollBehavior,i=e.features?.scrollBehavior,d=st.features?.streamAnimation,c=e.features?.streamAnimation,u=st.features?.askUserQuestion,p=e.features?.askUserQuestion,m=st.features?.history,h=e.features?.history,y=t===void 0&&o===void 0?void 0:{...t,...o,layout:{...t?.layout,...o?.layout}},x=n===void 0&&r===void 0?void 0:{...n,...r},T=a===void 0&&i===void 0?void 0:{...a,...i},w=d===void 0&&c===void 0?void 0:{...d,...c},k=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},P=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...st.features,...e.features,...x!==void 0?{scrollToBottom:x}:{},...T!==void 0?{scrollBehavior:T}:{},...y!==void 0?{artifacts:y}:{},...w!==void 0?{streamAnimation:w}:{},...k!==void 0?{askUserQuestion:k}:{},...P!==void 0?{history:P}:{}}})(),suggestionChips:e.suggestionChips??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}function Km(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let o=t.getComputedStyle(e).lineHeight;if(!o||!o.trim().endsWith("px"))return 20;let n=parseFloat(o);return Number.isFinite(n)&&n>0?n:20}function zc(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Xx(e,t){e.style.maxHeight=`${t*Km(e)}px`,e.style.overflowY="auto"}function Sl(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Qx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Yx(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let o=e.metaKey===!0||e.ctrlKey===!0,n=t.submitKey??"enter";return n==="none"?!1:n==="mod-enter"?o:o||!Qx(t)}function eP(e){return(e.submitKey??"enter")!=="enter"||Qx(e)?"enter":"send"}function Kc(e,t){e.setAttribute("enterkeyhint",eP(t))}function Gc(e,t){let o=t?.autocomplete;e.setAttribute("autocomplete",typeof o=="string"&&o?o:"off");let n=(r,a)=>{a===void 0?e.removeAttribute(r):e.setAttribute(r,a)};n("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),n("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),n("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),n("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Gm(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var Vo="persona-composer-control",yn="persona-composer-control--glyph",Qm=40,ho=24,Xc=(e,t,o)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let r=n.getComputedStyle(e);for(let a of o){let i=r.getPropertyValue(a).trim();i?t.style.setProperty(a,i):t.style.removeProperty(a)}},Qc=(e,t)=>{let o=I("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=e?.copy?.inputPlaceholder??zm,o.dir="auto",Kc(o,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Sl(o)}),Gc(o,e?.composer?.inputAttributes),o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=zc(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${n*20}px`;o.style.maxHeight=r,o.style.overflowY="auto";let a=()=>{let d=o.style.maxHeight;if(d!==r){let u=parseFloat(d);if(Number.isFinite(u)&&u>0)return u}let c=n*Km(o);return r=`${c}px`,o.style.maxHeight=r,c},i=()=>{o.addEventListener("input",()=>{o.style.height="auto";let d=Math.min(o.scrollHeight,a());o.style.height=`${d}px`})};return o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"}),{textarea:o,attachAutoResize:i}},oP="[data-persona-glyph-stack]",Ym=(e,t,o="send")=>{let n=Y("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":o,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),n.append(e,t),n},Yc=e=>{let t=e?.sendButton??{},o=t.useIcon??!1,n=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",i=t.tooltipText??"Send message",d=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||Qm,y=t.backgroundColor,x=t.textColor,T=I("div","persona-send-button-wrapper"),w=Y("button",{className:go("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",o?`persona-flex persona-items-center persona-justify-center ${Vo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",o&&!y&&"persona-bg-persona-primary",!o&&!x&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:o?m:void 0,height:o?m:void 0,minWidth:o?m:void 0,minHeight:o?m:void 0,fontSize:o?"18px":void 0,lineHeight:o?"1":void 0,color:o?x||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":x||void 0,backgroundColor:o&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:o?"0":t.paddingX||void 0,paddingRight:o?"0":t.paddingX||void 0,paddingTop:o?"0":t.paddingY||void 0,paddingBottom:o?"0":t.paddingY||void 0}}),k=null,P=null,H=null;if(o){let C=parseFloat(t.iconSize??"")||Math.round(h*.5),L=t.iconStrokeWidth??2,U=x?.trim()||"currentColor";r&&(k=ue(r,C,U,L)),P=ue(a,C,U,L),k&&P?(H=Ym(k,P),w.appendChild(H)):k?w.appendChild(k):(w.textContent=n,P=null)}else w.textContent=c;w.setAttribute("aria-label",i),T.appendChild(w),eo({anchor:w,trigger:T,text:()=>w.getAttribute("aria-label")??"",enabled:p});let b="send";return{button:w,wrapper:T,setMode:C=>{if(C===b)return;b=C;let L=C==="stop"?d:i;w.setAttribute("aria-label",L),w.setAttribute("data-persona-send-mode",C),o?(w.querySelector(oP)??H)?.setAttribute("data-mode",C):w.textContent=C==="stop"?u:c},glyphStack:H}},Qa=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let n=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",a=t.provider?.type==="custom";if(!(n||r||a))return null;let d=t.iconName??"mic",c=t.iconSize,u=parseFloat(c??"")||ho,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=I("div","persona-send-button-wrapper"),y=Y("button",{className:go("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Vo,!c&&yn),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=ue(d,u,m||"currentColor",1.5);T?y.appendChild(T):y.textContent="\u{1F3A4}",h.appendChild(y);let w=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return eo({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??w,enabled:k}),{button:y,wrapper:h}},Jc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let o=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=I("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=(t.allowedTypes??hr).join(","),n.multiple=(t.maxFiles??4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Vo} ${yn}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),d=ue(r,ho,"currentColor",1.5);d?i.appendChild(d):i.textContent="\u{1F4CE}",i.addEventListener("click",u=>{u.preventDefault(),n.click()}),a.appendChild(i);let c=t.buttonTooltipText??"Attach file";return eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:a,input:n,previewsContainer:o}},Zc=e=>{let t=e?.statusIndicator??{},o=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",n=I("div",`persona-mt-2 ${o} persona-text-xs persona-text-persona-muted`);n.setAttribute("data-persona-composer-status","");let r=t.visible??!0;n.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let i=I("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=a,i.style.color="inherit",i.style.textDecoration="none",n.appendChild(i)}else n.textContent=a;return n},eu=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function nP(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function tu(e){let{anchor:t,content:o,placement:n="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:i,verticalOffset:d,zIndex:c=2147483e3,onOpen:u,onDismiss:p}=e,m=e.container??nP(t),h=!1,y=null,x=()=>{if(!h)return;let k=t.getBoundingClientRect();o.style.position="fixed",a&&(o.style.minWidth=`${k.width}px`),i&&(o.style.maxWidth=`${k.width}px`);let P=o.getBoundingClientRect(),H=d?.()??null,b=H!=null?k.top+H:k.top,A=n==="top-start"||n==="top-end"?b-r-P.height:k.bottom+r,L=n==="bottom-end"||n==="top-end"?k.right-P.width:k.left,U=i?.()??null;if(U!=null){let Q=Math.max(k.left,k.right-P.width);L=Math.min(Math.max(k.left+U,k.left),Q)}o.style.top=`${A}px`,o.style.left=`${L}px`},T=()=>{h&&(h=!1,y&&(y(),y=null),o.remove())},w=()=>{if(h)return;h=!0,c!=null&&(o.style.zIndex=String(c)),m.appendChild(o),x();let k=(t.ownerDocument??document).defaultView??window,P=t.ownerDocument??document,H=()=>{if(!t.isConnected){T(),p?.("anchor-removed");return}x()},b=C=>{let L=typeof C.composedPath=="function"?C.composedPath():[];L.includes(o)||L.includes(t)||(T(),p?.("outside"))},A=k.setTimeout(()=>{P.addEventListener("pointerdown",b,!0)},0);k.addEventListener("scroll",H,!0),k.addEventListener("resize",H),y=()=>{k.clearTimeout(A),P.removeEventListener("pointerdown",b,!0),k.removeEventListener("scroll",H,!0),k.removeEventListener("resize",H)},u?.()};return{get isOpen(){return h},open:w,close:T,toggle:()=>h?T():w(),reposition:x,destroy:T}}var rP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',sP=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Jm="data-persona-menu-focus",aP=new Set(["ArrowDown","ArrowUp","Home","End"]);function Jx(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(rP)??e}var iP=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Zx(e){let t=e.label,o=!1,n=I("div","persona-send-button-wrapper"),r=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Vo} ${yn}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});n.appendChild(r);let a=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let W=e.getButtonSize?.()??"";r.style.width=W,r.style.height=W,r.style.minWidth=W,r.style.minHeight=W,r.style.lineHeight="1",r.replaceChildren();let te=ue("plus",ho,"currentColor",1.5);te?r.appendChild(te):r.textContent="+"},d=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),a.setAttribute("aria-label",t)};d(),i();let c=[],u=-1,p=!1,m=()=>{let te=a.getRootNode().activeElement;return te instanceof HTMLElement?te:null},h=()=>{let W=m();for(let te of c){let X=!!W&&Jx(te)===W;te.toggleAttribute(Jm,X&&p)}},y=()=>c.filter(W=>W.isConnected||a.contains(W)).map(Jx).filter(W=>!iP(W)),x=(W,te)=>{W.forEach((X,fe)=>{X.setAttribute("tabindex",fe===te?"0":"-1")})},T=W=>{let te=y();if(te.length===0)return;let X=(W%te.length+te.length)%te.length;u=X,x(te,X),te[X].focus(),h()},w=()=>n.ownerDocument??document,k=null,P=null,H=null,b=()=>{k&&(w().removeEventListener("focusin",k,!0),k=null)},A=()=>{P&&(a.removeEventListener("focusin",P),P=null),H&&(a.removeEventListener("pointerdown",H,!0),H=null)},C=null,L=()=>(C||(C=tu({anchor:r,content:a,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),b()}})),C),U=()=>C?.isOpen===!0,Q=(W=!1)=>{if(U()){C?.close(),r.setAttribute("aria-expanded","false"),b(),A(),u=-1,p=!1;for(let te of c)te.removeAttribute(Jm);W&&r.focus()}},$=(W=0,te=!1)=>{if(o||U())return;p=te,Xc(r,a,sP),L().open(),r.setAttribute("aria-expanded","true");let X=y();x(X,-1),T(W<0?X.length-1:W),k=fe=>{let le=typeof fe.composedPath=="function"?fe.composedPath():[];le.includes(a)||le.includes(n)||Q()},w().addEventListener("focusin",k,!0),P=()=>h(),a.addEventListener("focusin",P),H=()=>{p=!1},a.addEventListener("pointerdown",H,!0)},E=W=>{W.preventDefault(),W.stopPropagation(),U()?Q(!0):$(0)},B=W=>{if(W.key==="ArrowDown"||W.key==="Enter"||W.key===" "){W.preventDefault(),p=!0,U()?T(0):$(0,!0);return}W.key==="ArrowUp"&&(W.preventDefault(),p=!0,U()?T(-1):$(-1,!0))},D=W=>{switch(aP.has(W.key)&&(p=!0),W.key){case"ArrowDown":W.preventDefault(),T(u+1);return;case"ArrowUp":W.preventDefault(),T(u-1);return;case"Home":W.preventDefault(),T(0);return;case"End":W.preventDefault(),T(y().length-1);return;case"Escape":W.preventDefault(),W.stopPropagation(),Q(!0);return;case"Tab":Q(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",B),a.addEventListener("keydown",D),{trigger:n,triggerButton:r,panel:a,setItems:W=>{for(let X of c)W.includes(X)||X.removeAttribute(Jm);if(c=[...W],!U())return;let te=y();x(te,Math.min(u,te.length-1)),h()},isOpen:U,open:()=>$(0),close:Q,setLabel:W=>{W!==t&&(t=W,d())},applyButtonSize:i,destroy:()=>{o=!0,b(),A(),r.removeEventListener("click",E),r.removeEventListener("keydown",B),a.removeEventListener("keydown",D),C?.destroy(),C=null,n.remove(),a.remove(),c=[]}}}var Vn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},eC="data-persona-composer-action",Zm="data-persona-composer-disable-when-streaming",lP="core:overflow",dP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function cP(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let o=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(o))return o;let n=I("div");n.style.position="absolute",n.style.visibility="hidden",n.style.pointerEvents="none",n.style.height="0",n.style.width=e,t.appendChild(n);let r=n.getBoundingClientRect().width;return n.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(o)?o:null}function eg(e){let t=e.clientWidth;if(!t)return 0;let o=e.ownerDocument?.defaultView;if(!o?.getComputedStyle)return t;let n=o.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0);return Math.max(0,t-r)}var tC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},uP=(e,t)=>t.includes(":")?t:`${e}:${t}`;function pP(e){let{debug:t}=e,o=[],n=new Map,r=0,a=d=>{let c=n.get(d.id);if(c){tC(t,`[Persona] composer action "${d.id}" is already contributed by ${oC(c)}; the ${oC(d)} copy is ignored.`);return}n.set(d.id,d),o.push(d)};for(let d of e.builtIns)a({id:d.id,placement:d.placement,presentation:"bar",order:d.order,sequence:r++,source:"core",builtIn:d});let i=(d,c,u)=>{let p=u?uP(u,d.id):d.id,m=d.order??Vn.custom;d.placement==="end"&&m>=Vn.send&&(tC(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${Vn.send-1}.`),m=Vn.send-1),a({id:p,placement:d.placement,presentation:d.presentation??"bar",order:m,sequence:r++,source:c,pluginId:u,action:d})};for(let d of e.configActions??[])i(d,"config");for(let d of e.plugins){if(!d.contributeComposerActions)continue;let c;try{c=d.contributeComposerActions(e.contributionContext)}catch(u){typeof console<"u"&&console.error(`[Persona] plugin "${d.id}" contributeComposerActions failed:`,u);continue}for(let u of c??[])i(u,"plugin",d.id)}return o.sort((d,c)=>d.order===c.order?d.sequence-c.sequence:d.order-c.order)}var oC=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",nC=(e,t,o)=>e===void 0?o:typeof e=="function"?e(t)===!0:e===!0,fP=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function mP(e,t){if(!e||e==="always")return!0;let o=fP(t);return e==="when-text"?o:!o}var Qr=e=>e.kind==="custom",tg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,gP=e=>{let t=tg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},hP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function yP(e){let t="",o=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.nodeValue??"";return}if(n.nodeType!==Node.ELEMENT_NODE)return;let r=n;typeof r.matches=="function"&&r.matches(hP)||n.childNodes.forEach(o)};return o(e),t.trim()}var bP=e=>yP(e).length===0;function rC(e){let t=new Map,o=[],n=!1,r=()=>e.getButtonSize?.(),a=(E,B)=>{let D=E.button;if(!D)return;D.setAttribute("role","menuitem"),D.setAttribute("tabindex","-1"),D.className="persona-composer-overflow-menu__item";for(let X of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])D.style[X]="";D.style.lineHeight="1",B.tooltipText?D.setAttribute("title",B.tooltipText):D.removeAttribute("title"),D.replaceChildren();let W=I("span","persona-composer-overflow-menu__icon");if(B.iconName){let X=ue(B.iconName,16,"currentColor",1.5);X&&W.appendChild(X)}let te=I("span","persona-composer-overflow-menu__label");te.textContent=B.shortLabel??B.label,D.append(W,te)},i=(E,B)=>{let D=E.button;if(!D)return;if(D.setAttribute("aria-label",B.label),B.pressed===void 0?D.removeAttribute("aria-pressed"):D.setAttribute("aria-pressed",B.pressed?"true":"false"),D.toggleAttribute(Zm,B.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,a(E,B);return}D.removeAttribute("role"),D.removeAttribute("tabindex"),D.removeAttribute("title");let W=r(),te=!!B.shortLabel;if(D.className=go("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Vo,yn,te&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),D.style.width=W&&!te?W:"",D.style.height=W??"",D.style.minWidth=W&&!te?W:"",D.style.minHeight=W??"",D.style.fontSize=te?"":"18px",D.style.lineHeight="1",D.style.color=B.iconColor??"",D.style.backgroundColor=B.backgroundColor??"",D.replaceChildren(),B.iconName){let X=ue(B.iconName,ho,"currentColor",1.5);X&&D.appendChild(X)}if(te){let X=I("span","persona-composer-action-button__label");X.textContent=B.shortLabel,D.appendChild(X)}else D.firstChild||(D.textContent=B.label);E.tooltip?.destroy(),E.tooltip=eo({anchor:D,trigger:E.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},d=(E,B)=>{let D=E.action,W=Y("button",{attrs:{type:"button"}}),te=W;if(B==="bar"){let le=I("div","persona-send-button-wrapper");le.appendChild(W),te=le}te.setAttribute(eC,E.id);let X={resolved:E,element:te,button:W,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},fe=le=>{if(le.preventDefault(),le.stopPropagation(),X.busy||W.disabled)return;let xe=X.resolved.action;X.mode==="menu"&&y?.close(!0);let Re;try{Re=xe.onSelect(e.actionContext,le)}catch(He){e.reportError(He,{actionId:X.resolved.id});return}!Re||typeof Re.then!="function"||(X.busy=!0,W.setAttribute("aria-busy","true"),Re.catch(He=>{e.reportError(He,{actionId:X.resolved.id})}).finally(()=>{X.busy=!1,W.removeAttribute("aria-busy")}))};return W.addEventListener("click",fe),X.detach=()=>W.removeEventListener("click",fe),i(X,D),X},c=E=>{let B=E.action,D;try{D=B.render({...e.actionContext,id:E.id,action:B})}catch(W){return e.reportError(W,{actionId:E.id}),null}return D?.element?(D.element.setAttribute(eC,E.id),D.element.toggleAttribute(Zm,B.disableWhenStreaming===!0),{resolved:E,element:D.element,owned:!0,managed:!0,destroy:D.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(E,B)=>{if(E.builtIn){let W=E.builtIn.element;return W?{resolved:E,element:W,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let D=E.action;return D?Qr(D)?c(E):d(E,B):null},p=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(B){e.reportError(B,{actionId:E.resolved.id})}E.element.remove()}},m=(E,B)=>{for(let D=0;D<B.length;D++){let W=B[D];if(!W.managed)continue;let te=null;for(let X=D+1;X<B.length;X++){let fe=B[X];if(!fe.managed&&fe.element.parentElement===E){te=fe.element;break}}te?(W.element.parentElement!==E||W.element.nextSibling!==te)&&E.insertBefore(W.element,te):E.lastChild!==W.element&&E.appendChild(W.element)}},h=(E,B)=>{if(E.button){E.button.disabled=B;return}if(!E.owned)return;let D=E.element;D.toggleAttribute("data-disabled",B),D.setAttribute("aria-disabled",B?"true":"false");let W=D instanceof HTMLButtonElement||D instanceof HTMLSelectElement||D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement?D:D.querySelector("button, select, input, textarea");W&&(W.disabled=B)},y=null,x=null,T=null,w=0,k=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},P=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=Zx({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),H=E=>{x!==E&&(T?.disconnect(),x=E,w=eg(E),!(typeof ResizeObserver>"u")&&(T=new ResizeObserver(B=>{let W=B[B.length-1]?.contentRect?.width??eg(E);W!==w&&(w=W,Q())}),T.observe(E)))},b=(E,B)=>{let D=cP(E.collapseAutoActionsBelow,B);if(D===null)return!1;let W=w||eg(B);return W>0&&W<D},A=(E,B,D)=>{if(!B)return"bar";if(E.resolved.builtIn){let te=dP(E.resolved.id);return te&&B.includeBuiltIns?.includes(te)?"menu":"bar"}let W=E.resolved.presentation;return W==="overflow"||W==="auto"&&D?"menu":"bar"},C=E=>{let B=E.menuSlot;if(!B)return;if(!bP(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let D=gP(E.element);if(!D){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=I("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==D&&(E.menuLabel.textContent=D),E.menuLabel.parentElement!==B&&B.appendChild(E.menuLabel)},L=(E,B)=>{if(E.mode===B)return E;let D=E.resolved.action;if(D&&!Qr(D)){p(E),t.delete(E.resolved.id);let W=d(E.resolved,B);return t.set(E.resolved.id,W),W}if(B==="menu"){let W=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[jm]:""}});W.appendChild(E.element),jx(tg(E.element)),E.menuSlot=W;let te=X=>{let fe=tg(E.element);if(fe.disabled)return;let le=X.target===fe||fe.contains(X.target);y?.close(!0),le||fe.click()};W.addEventListener("click",te,!0),E.detachMenuSlot=()=>W.removeEventListener("click",te,!0),E.managed=!0,C(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=B,E},U=(E,B)=>{let D=B.map(W=>W.menuSlot??W.element);for(D.forEach((W,te)=>{let X=E.children[te];X!==W&&(X?E.insertBefore(W,X):E.appendChild(W))});E.children.length>D.length;)E.lastElementChild?.remove()},Q=()=>{if(n)return;let E=e.getBindings();if(!E)return;let B=e.getState(),D=B.phase==="streaming",W=k();W&&H(E.footer);let te=W?b(W,E.footer):!1,X={start:[],end:[]},fe=[];for(let le of o){let xe=t.get(le.id);if(!xe)continue;let Re=le.action,He=Re?nC(Re.visible,B,!0)&&mP(Re.visibility,B):!0;if(xe.visible!==He&&(xe.visible=He,!He&&xe.managed&&(xe.menuSlot??xe.element).remove()),!!He){if(xe=L(xe,A(xe,W,te)),Re){let we=nC(Re.disabled,B,!1)||Re.disableWhenStreaming===!0&&D;h(xe,we),!Qr(Re)&&Re.pressed!==void 0&&xe.button?.setAttribute("aria-pressed",Re.pressed?"true":"false")}xe.mode==="menu"?(C(xe),fe.push(xe)):X[le.placement].push(xe)}}if(fe.length>0){let le=P();U(le.panel,fe),le.setItems(fe.map(we=>we.menuSlot??we.element)),le.applyButtonSize();let xe=Number.isFinite(W?.order)?W?.order:Vn.overflow,Re=X.start.findIndex(we=>we.resolved.order>xe),He={resolved:{id:lP,placement:"start",presentation:"bar",order:xe,sequence:-1,source:"core"},element:le.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};X.start.splice(Re<0?X.start.length:Re,0,He)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(E.actionsStart,X.start),m(E.actionsEnd,X.end)};return{resolve:()=>{if(n)return;let E=pP(e.collect()),B=new Set(E.map(D=>D.id));for(let[D,W]of t)B.has(D)||(p(W),t.delete(D));for(let D of E){let W=t.get(D.id);if(!W){let le=u(D,"bar");le&&t.set(D.id,le);continue}let te=W.resolved.action,X=D.action;if(!!te!=!!X||te&&X&&Qr(te)!==Qr(X)||te&&X&&Qr(te)&&Qr(X)&&te.render!==X.render){p(W),t.delete(D.id);let le=u(D,W.mode);le&&t.set(D.id,le);continue}W.resolved=D,D.builtIn?(W.managed=D.builtIn.managed===!0||W.mode==="menu",D.builtIn.element&&W.mode==="bar"&&(W.element=D.builtIn.element)):X&&!Qr(X)?i(W,X):X&&W.element.toggleAttribute(Zm,X.disableWhenStreaming===!0)}o=E,Q()},sync:Q,getResolved:()=>o,getOverflowMenu:()=>y,destroy:()=>{if(!n){n=!0,T?.disconnect(),T=null,x=null;for(let E of t.values())p(E);t.clear(),y?.destroy(),y=null,o=[]}}}}var vP="core:model",xP=700,sC=16,CP=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],aC=()=>{let e=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function iC(e){let t=e.label??"Model",o=e.presentation??"native",n=null,r=c=>{let u=e.getSelectedModelId();return c.find(p=>p.id===u)??c[0]},a=()=>{let c=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),u="",p=()=>{let T=e.getModels(),w=T.map(k=>`${k.id}:${k.label}`).join("|");w!==u&&(u=w,c.replaceChildren(...T.map(k=>{let P=Y("option",{attrs:{value:k.id}});return P.textContent=k.label,P}))),c.value=r(T)?.id??""};p(),n=p;let m=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",m);let h=T=>T.stopPropagation();c.addEventListener("click",h);let{wrapper:y,chevron:x}=aC();return y.append(c,x),{element:y,destroy:()=>{n===p&&(n=null),c.removeEventListener("change",m),c.removeEventListener("click",h)}}},i=()=>{let c=Y("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),u=I("span","persona-composer-model-picker-label"),p=I("span","persona-composer-model-picker-suffix");c.append(u,p);let m=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",x=null,T=()=>x?.isOpen===!0,w=(B=!1)=>{T()&&(x?.close(),c.setAttribute("aria-expanded","false"),B&&c.focus())},k=B=>{let D=[...h.values()];if(D.length===0)return;let W=(B%D.length+D.length)%D.length;D[W].focus()},P=B=>{if(T())return;x||(x=tu({anchor:c,content:m,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Xc(c,m,CP),x.open(),c.setAttribute("aria-expanded","true");let W=[...h.keys()].indexOf(r(e.getModels())?.id??"");k(B??(W>=0?W:0))},H=B=>{w(!0),e.onSelect(B)},b=B=>{B.preventDefault(),B.stopPropagation();let D=B.currentTarget.getAttribute("data-persona-model-option");D&&H(D)},A=B=>{let D=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let le=ue(B.icon,sC,"currentColor",1.5);if(le){let xe=I("span","persona-composer-model-option-icon");xe.appendChild(le),D.appendChild(xe)}}let W=I("span","persona-composer-model-option-body"),te=I("span","persona-composer-model-option-label");if(te.textContent=B.label,W.appendChild(te),B.description){let le=I("span","persona-composer-model-option-description");le.textContent=B.description,W.appendChild(le)}D.appendChild(W);let X=I("span","persona-composer-model-option-check");X.setAttribute("aria-hidden","true");let fe=ue("check",sC,"currentColor",2);return fe&&X.appendChild(fe),D.appendChild(X),D.addEventListener("click",b),D},C=()=>{let B=e.getModels(),D=B.map(X=>`${X.id}:${X.label}:${X.icon??""}:${X.description??""}`).join("|");if(D!==y){y=D;for(let X of h.values())X.removeEventListener("click",b);h.clear(),m.replaceChildren(...B.map(X=>{let fe=A(X);return h.set(X.id,fe),fe}))}let W=r(B);for(let[X,fe]of h)fe.setAttribute("aria-selected",String(X===W?.id));u.textContent=W?.label??"";let te=e.getSuffix?.()??"";p.textContent=te,c.setAttribute("aria-label",[t,[W?.label,te].filter(Boolean).join(" ")].filter(Boolean).join(": "))};C(),n=C;let L=B=>{B.preventDefault(),B.stopPropagation(),T()?w(!0):P()},U=B=>{if(B.key==="ArrowDown"){B.preventDefault(),T()?k(0):P(0);return}B.key==="ArrowUp"&&(B.preventDefault(),T()?k(-1):P(-1))},Q=B=>{let D=[...h.values()],W=D.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),k(W+1);return;case"ArrowUp":B.preventDefault(),k(W-1);return;case"Home":B.preventDefault(),k(0);return;case"End":B.preventDefault(),k(D.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),w(!0);return;case"Tab":w(!0);return;default:}};c.addEventListener("click",L),c.addEventListener("keydown",U),m.addEventListener("keydown",Q);let{wrapper:$,chevron:E}=aC();return $.append(c,E),{element:$,destroy:()=>{n===C&&(n=null),c.removeEventListener("click",L),c.removeEventListener("keydown",U),m.removeEventListener("keydown",Q);for(let B of h.values())B.removeEventListener("click",b);h.clear(),x?.destroy(),x=null,m.remove()}}};return{action:{id:vP,kind:"custom",placement:"end",order:xP,presentation:o==="popover"?"bar":"auto",label:t,render:()=>o==="popover"?i():a()},repaint:()=>n?.()}}var og="[data-persona-composer-chip-row]";function ou(e){e.style.display=e.childElementCount>0?"flex":"none"}function ng(e){let t=e.querySelector(og);if(t)return t;let o=Y("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});o.style.display="none";let n=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return n?.parentElement===e?e.insertBefore(o,n):e.appendChild(o),o}var SP=":scope > [data-persona-composer-mode]";function lC(e){let t=e.row,o="",n=!1,r=new Set(e.initialIds??[]),a=u=>{let p=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let x=I("span","persona-mention-chip-icon"),T=ue(u.iconName,12,"currentColor",1.5);T&&x.appendChild(T),p.appendChild(x)}let m=I("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,p.appendChild(m);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),y=ue("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",x=>{x.preventDefault(),x.stopPropagation(),e.onRemove(u.id)}),p.appendChild(h),p},i=()=>Array.from(t.querySelectorAll(SP)),d=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),ou(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!h||h==="none"){p();return}u.addEventListener("animationend",p,{once:!0}),u.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let u of i())u.remove()};return{element:t,render:(u,p)=>{if(n)return;let m=p.filter(T=>u.includes(T.id)),h=m.map(T=>`${T.id}:${T.shortLabel??T.label}`).join("|");if(h===o)return;o=h;let y=new Map;for(let T of i()){let w=T.getAttribute("data-persona-composer-mode");w&&m.some(P=>P.id===w)&&!T.hasAttribute("data-persona-chip-exit")?y.set(w,T):T.hasAttribute("data-persona-chip-exit")||d(T)}let x=t.firstChild;for(let T of m){let w=y.get(T.id);w||(w=a(T),r.has(T.id)||(w.setAttribute("data-persona-chip-enter",""),w.addEventListener("animationend",()=>w?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(T.id),w!==x&&t.insertBefore(w,x),x=w.nextSibling}ou(t)},destroy:()=>{n=!0,c(),ou(t)}}}var dC=e=>`core:mode:${e}`;var rg=e=>Math.min(300+e,499),cC=e=>`core:mode-group:${e}`;function nu(e,t){return e?t?.find(o=>o.id===e)?.presentation==="segmented":!1}function wP(e,t){return e?t?.find(o=>o.id===e)?.chipVisibility==="hidden":!1}function uC(e,t){return e?.length?e.filter(o=>!nu(o.groupId,t)&&!wP(o.groupId,t)):[]}var AP=(e,t)=>e.groupId?t?.find(o=>o.id===e.groupId)?.selection??null:null;function pC(e,t,o,n){let r=o.find(d=>d.id===t);if(!r)return[...e];let a=e.includes(t),i=new Set(e);if(a)i.delete(t);else{if(AP(r,n)==="single"){let d=o.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!d.includes(c)))}i.add(t)}return o.filter(d=>i.has(d.id)).map(d=>d.id)}function ru(e,t){return t?.length?t.filter(o=>e.includes(o.id)).map(o=>o.id):[]}function fC(e,t){return t?.length?t.filter(o=>e.includes(o.id)&&(o.persistence??"sticky")!=="once").map(o=>o.id):[]}function mC(e,t){if(!(!t?.length||e.length===0))return t.find(o=>e.includes(o.id)&&o.placeholder)?.placeholder}var MP=16;function gC(e){let t=null;return{action:{id:cC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let n=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,a="",i=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},d=u=>{let p=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let h=ue(u.iconName,MP,"currentColor",1.5);h&&p.appendChild(h)}let m=I("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,p.appendChild(m),p.addEventListener("click",i),p},c=()=>{let u=e.getGroup();u?.label?(n.setAttribute("role","group"),n.setAttribute("aria-label",u.label)):(n.removeAttribute("role"),n.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==a){a=m;for(let x of r.values())x.removeEventListener("click",i);r.clear();let y=p.map(x=>{let T=d(x);return r.set(x.id,T),T});n.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,x]of r)x.setAttribute("aria-pressed",String(h.includes(y)))};return c(),t=c,{element:n,destroy:()=>{t===c&&(t=null);for(let u of r.values())u.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}function hC(e){let t=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let o="",n=!1,r=a=>{let i=I("span","persona-composer-quote-bar"),d=I("div","persona-composer-quote-content");if(a.sourceLabel){let m=I("div","persona-composer-quote-source");m.textContent=a.sourceLabel,d.appendChild(m)}let c=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Rc(a.text),d.appendChild(c);let u=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=ue("x",12,"currentColor",2);p?u.appendChild(p):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,d,u)};return{element:t,render:a=>{if(n)return;let i=a?`${a.sourceLabel??""}\0${a.text}`:"";if(i!==o){if(o=i,!a){t.replaceChildren(),t.style.display="none";return}r(a),t.style.display="flex"}},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function yC(e){let t=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let o,n=!1,r=(i,d,c,u)=>{let p=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":d,[c]:""}}),m=ue(i,12,"currentColor",2);return m?p.appendChild(m):p.textContent=d,p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),p},a=i=>{let d=Rc(i.text??"",90);if(d)return d;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(p=>p.label).join(", "):"Queued message"};return{element:t,render:i=>{if(n||i===o)return;if(o=i,!i){t.replaceChildren(),t.style.display="none";return}let d=I("span","persona-composer-pending-badge");d.textContent=e.label??"Sends next";let c=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=a(i),t.replaceChildren(d,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{n=!0,t.replaceChildren(),t.remove()}}}function bC(e){let t=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),o=Y("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});o.value=e.initialText;let n=()=>{o.style.height="auto",o.style.height=`${o.scrollHeight}px`};o.addEventListener("input",n);let r=I("div","persona-message-edit-actions"),a=(d,c,u,p)=>{let m=Y("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[u]:""},text:d});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),m},i=()=>{let d=o.value.trim();d&&e.onSave(d)};return r.append(a(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),a(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),o.addEventListener("keydown",d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),e.onCancel();return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}),t.append(o,r),{element:t,getValue:()=>o.value,focus:()=>{o.focus();let d=o.value.length;o.setSelectionRange(d,d),n()},destroy:()=>{t.replaceChildren(),t.remove()}}}function vC(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 xC(e,t){if(!e||typeof e.text!="string")return;let o=new Set(t.mentionSourceIds),n=(e.mentionRefs??[]).filter(c=>o.has(c.sourceId)),r=n.length===(e.mentionRefs?.length??0)&&n.length>0,a=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>a.has(c)),d=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:n}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...d?{selectedModelId:d}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function CC(e){let t=e.delay??500,o=null,n=!1,r=()=>{o!==null&&(clearTimeout(o),o=null)};return{schedule:()=>{n||(r(),o=setTimeout(()=>{o=null,e.write()},t))},flush:()=>{n||o===null||(r(),e.write())},cancel:r,destroy:()=>{n=!0,r()}}}function SC(e){return e.wrapped||e.text.includes(`
24
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function wC(){let e=!1;return{observe:(t,o)=>o?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function AC(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let o=t.getComputedStyle(e),n=Number.parseFloat(o.lineHeight),r=Number.parseFloat(o.fontSize),a=Number.isFinite(n)&&n>0?n:Number.isFinite(r)&&r>0?r*1.4:0;if(!a)return!1;let i=(Number.parseFloat(o.paddingTop)||0)+(Number.parseFloat(o.paddingBottom)||0);return e.scrollHeight-i>a*1.5}function MC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function sg(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 EC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var TP=e=>typeof e?.then=="function";function TC(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function PC(e,t,o){let n;try{n=e(sg(t),{signal:o})}catch(r){return{status:"error",error:r}}return TP(n)?Promise.resolve(n).then(r=>o.aborted?{status:"aborted"}:TC(t,r),r=>o.aborted?{status:"aborted"}:{status:"error",error:r}):TC(t,n)}var kC=/\s/;function EP(e,t,o){if(o==="input-start")return t===0;let n=t>0?e[t-1]:"";return o==="line-start"?n===""||n===`
25
+ `:n===""||kC.test(n)}function PP(e,t,o="@",n="anywhere",r=!1){if(!o||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let i=e[a];if(i===o)return EP(e,a,n)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(i===`
26
+ `||i==="\uFFFC"||!r&&kC.test(i))return null;a--}return null}function LC(e,t,o){for(let n of o){let r=PP(e,t,n.trigger,n.position??"anywhere",n.allowSpaces??!1);if(r)return{channel:n,match:r}}return null}function IC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function RC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},o=(e.triggers??[]).map(n=>({trigger:n.trigger,position:n.triggerPosition??"anywhere",allowSpaces:n.allowSpaces??!1,sources:Array.isArray(n.sources)?n.sources:[],searchPlaceholder:n.searchPlaceholder,showButton:n.showButton===!0,buttonIconName:n.buttonIconName,buttonTooltipText:n.buttonTooltipText}));return[t,...o]}function HC(e){let{config:t,onOpen:o}=e,n=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",a=I("div","persona-send-button-wrapper"),i=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Vo} ${yn}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),d=ue(n,ho,"currentColor",1.5);return d?i.appendChild(d):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),o()}),a.appendChild(i),eo({anchor:i,trigger:a,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:a}}var{setLoader:kP,load:LP}=gt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),WC=kP,ag=LP;var{setLoader:IP,load:RP}=gt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),BC=IP,OC=RP;function wl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let o=Y("span",{className:go("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&o.style.setProperty("--persona-mention-token-accent",e.color);let n=ue(e.iconName??"at-sign",13,"currentColor",2);if(n){let r=I("span","persona-mention-token-icon");r.appendChild(n),o.appendChild(r)}return o.appendChild(Y("span",{className:"persona-mention-token-label",text:`@${e.label}`})),o}function DC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let o=RC(t).filter(b=>b.sources.length>0);if(o.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let n=o.filter(b=>b.sources.some(A=>typeof A.matchCommand=="function")),r=b=>n.some(A=>A.trigger?A.position==="line-start"?b.split(`
27
27
  `).some(L=>L.startsWith(A.trigger)):(A.position==="anywhere"?b:b.split(`
28
- `)[0]).startsWith(A.trigger):!1),a=(b,A)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${b}`,{detail:A}))}catch{}},i=!e.chipRow,d=e.chipRow??Y("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,u=null,p=e.textarea,m=null,h=null,y=null,x=null,T=()=>{if(c)return Promise.resolve(c);if(u)return u;let b=sg().then(A=>(A.setMentionIconRenderer(ce),c=A.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:R,emit:a}),c)).catch(A=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",A),u===b&&(u=null),null));return u=b,b},w=()=>{BC().then(b=>{let A=b.mountInlineComposer({textarea:e.textarea,renderToken:L=>Sl(L,{render:t.renderMentionToken}),onMentionRemoved:L=>c?.untrackMention(L)});m=A.input,h=A.destroy;let C=p;C.replaceWith(A.element),p=A.element,x={next:A.element,prev:C},y?.(A.element,C),c?c.rebindComposer(A.input):u&&u.then(L=>L?.rebindComposer(A.input))}).catch(b=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",b)})};t.display==="inline"&&w();let k=[],P=new Map;for(let b of o){if(!b.showButton)continue;let A=RC({config:{...t,buttonIconName:b.buttonIconName,buttonTooltipText:b.buttonTooltipText},onOpen:()=>{T().then(C=>C?.openMenu(b.trigger))}});k.push(A),P.set(b.trigger,A.button)}let R=(b,A,C)=>{let L=P.get(A);L&&(L.setAttribute("aria-expanded",b?"true":"false"),b?L.setAttribute("aria-controls",C):L.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(b=>b.wrapper),contextRow:d,handleInput:b=>{if(c){c.handleInput();return}if(!LC(b))return;let A=p,C=A.selectionStart??0;kC(A.value,C,o)&&T().then(L=>L?.handleInput())},handleKeydown:b=>{if(c?.isMenuOpen())return c.handleKeydown(b);if(b.key==="Backspace"&&c?.hasMentions()&&!x){let A=p,C=A.selectionStart===0&&A.selectionEnd===0;if((A.value.length===0||C)&&c.removeLastChip())return b.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async b=>r(b)?(c??await T())?.dispatchInlineCommand(b)??null:null,clear:()=>c?.clear(),prefetch:()=>{sg().catch(()=>{})},onComposerSwap:b=>{y=b,x&&b(x.next,x.prev)},destroy:()=>{c?.destroy(),h?.();for(let b of k)b.wrapper.remove();i&&d.remove()}}}var ru="16px",su="transparent",IP=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),ig={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:IP,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"}},lg={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"}},dg={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:zo,maxWidth:Vc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ru,canvasBackground:su},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function xo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?xo(e,n):n}function au(e){let t={};function o(n,r){for(let[a,i]of Object.entries(n)){let d=`${r}.${a}`;if(typeof i=="string"){let c=xo(e,i);c!==void 0&&(t[d]={path:d,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&o(i,d)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function cg(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function _C(e,t){let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?o[n]=_C(a,r):o[n]=r}return o}function RP(e,t){return t?_C(e,t):e}function wl(e,t={}){let o={palette:ig,semantic:lg,components:dg},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:RP(o.components,e?.components)};if(t.validate!==!1){let r=cg(n);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)n=r.transform(n);return n}var ag=e=>e.trim()==="0"?"0px":e,DC="--persona-",HP=e=>{if(!e)return;let t=e.trim().toLowerCase(),o;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?o=[0,1,2].map(d=>parseInt(i[d]+i[d],16)):(i.length===6||i.length===8)&&(o=[0,2,4].map(d=>parseInt(i.slice(d,d+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let d=i[1].split(/[,/\s]+/).filter(Boolean);d.length>=3&&(o=d.slice(0,3).map(c=>{let u=c.endsWith("%"),p=parseFloat(u?c.slice(0,-1):c);return u?p/100*255:p}))}}if(!o||o.some(i=>!Number.isFinite(i)))return;let[n,r,a]=o.map(i=>{let d=Math.max(0,Math.min(255,i))/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*n+.7152*r+.0722*a},WP=.179,to=(e,t)=>{for(let[o,...n]of t){let r;for(let a of n)if(r=a.charCodeAt(0)===61?a.slice(1):e[DC+a],r!==void 0)break;r!==void 0&&(e[DC+o]=r)}};function iu(e){let t=au(e),o={};for(let[j,qe]of Object.entries(t)){let Ge=j.replace(/\./g,"-");o[`--persona-${Ge}`]=qe.value}to(o,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=o["--persona-components-launcher-foreground"];o["--persona-launcher-fg-muted"]=n&&n!==o["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:o["--persona-muted"],to(o,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),to(o,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,to(o,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??ru,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??su,to(o,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),to(o,[["header-bg","components-header-background","surface"]]);let r=o["--persona-header-bg"],a=o["--persona-components-header-foreground"],i=a?`color-mix(in srgb, ${a} 72%, ${r})`:void 0;o["--persona-header-border"]=o["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${r})`:void 0)??o["--persona-divider"],to(o,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),o["--persona-header-title-fg"]=o["--persona-components-header-title-color"]??o["--persona-components-header-titleForeground"]??a??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitle-color"]??o["--persona-components-header-subtitleForeground"]??i??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??i??o["--persona-muted"],to(o,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let d=e.components?.header;d?.shadow&&(o["--persona-header-shadow"]=d.shadow),d?.borderBottom&&(o["--persona-header-border-bottom"]=d.borderBottom),d?.minHeight&&(o["--persona-header-min-height"]=d.minHeight);let c=o["--persona-components-history-railHeader-background"];c&&(o["--persona-history-rail-header-bg"]=c);let u=o["--persona-components-history-railHeader-border"];u&&(o["--persona-history-rail-header-border"]=u);let p=o["--persona-components-history-railHeader-minHeight"];p&&(o["--persona-history-rail-header-min-height"]=p);for(let[j,qe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ge=o[`--persona-components-history-overlay-${j}`];Ge&&(o[`--persona-history-overlay-${qe}`]=Ge)}for(let[j,qe]of[["background","bg"],["borderRadius","radius"]]){let Ge=o[`--persona-components-history-menu-${j}`];Ge&&(o[`--persona-history-menu-${qe}`]=Ge)}let m=e.components?.history?.motion;if(m){let j=Ae=>{if(Ae===void 0)return;let De=String(Ae).trim();return/^\d+(\.\d+)?$/.test(De)?`${De}ms`:De},qe=j(m.enterDurationMs);qe!==void 0&&(o["--persona-history-enter-ms"]=qe);let Ge=j(m.exitDurationMs);Ge!==void 0&&(o["--persona-history-exit-ms"]=Ge),m.enterEasing&&(o["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(o["--persona-history-exit-easing"]=m.exitEasing)}let h=o["--persona-components-history-dangerForeground"];h&&(o["--persona-history-danger-fg"]=h),o["--persona-danger"]=o["--persona-components-history-confirm-dangerBackground"]??o["--persona-palette-colors-error-700"]??"#b42318",o["--persona-danger-fg"]=o["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let j of["scrim","shadow"]){let qe=o[`--persona-components-history-confirm-${j}`];qe&&(o[`--persona-history-confirm-${j}`]=qe)}for(let[j,qe]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ge=o[`--persona-components-tooltip-${j}`];Ge&&(o[`--persona-tooltip-${qe}`]=Ge)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[j,qe]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ge=o[`--persona-components-messageActions-${j}`];Ge&&(o[`--persona-message-action-${qe}`]=Ge)}to(o,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=o["--persona-components-introCard-background"],x=o["--persona-components-introCard-shadow"],T=(!y||y==="transparent"||y==="none")&&(!x||x==="none"),w=o["--persona-components-introCard-padding"]??"1.5rem";o["--persona-intro-card-padding"]=T&&w==="1.5rem"?"1.5rem 0":w,to(o,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["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"]]),to(o,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let k=o["--persona-components-markdown-heading-h1-fontSize"];k&&(o["--persona-md-h1-size"]=k);let P=o["--persona-components-markdown-heading-h1-fontWeight"];P&&(o["--persona-md-h1-weight"]=P);let R=o["--persona-components-markdown-heading-h2-fontSize"];R&&(o["--persona-md-h2-size"]=R);let b=o["--persona-components-markdown-heading-h2-fontWeight"];b&&(o["--persona-md-h2-weight"]=b);let A=o["--persona-components-markdown-prose-fontFamily"];A&&A!=="inherit"&&(o["--persona-md-prose-font-family"]=A),to(o,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),to(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),to(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),to(o,[["md-hr-color","components-markdown-hr-color","divider"]]),to(o,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]),o["--cw-container"]=o["--persona-components-collapsibleWidget-container"]??o["--persona-surface"],o["--cw-surface"]=o["--persona-components-collapsibleWidget-surface"]??o["--persona-surface"],o["--cw-border"]=o["--persona-components-collapsibleWidget-border"]??o["--persona-border"],to(o,[["message-border","components-message-border","border"]]),to(o,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-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 C=e.components,L=C?.iconButton;L&&(L.background&&(o["--persona-icon-btn-bg"]=L.background),L.border&&(o["--persona-icon-btn-border"]=L.border),L.color&&(o["--persona-icon-btn-color"]=L.color),L.padding&&(o["--persona-icon-btn-padding"]=L.padding),L.borderRadius&&(o["--persona-icon-btn-radius"]=L.borderRadius),L.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=L.hoverBackground),L.hoverColor&&(o["--persona-icon-btn-hover-color"]=L.hoverColor),L.activeBackground&&(o["--persona-icon-btn-active-bg"]=L.activeBackground),L.activeBorder&&(o["--persona-icon-btn-active-border"]=L.activeBorder));let F=C?.labelButton;F&&(F.background&&(o["--persona-label-btn-bg"]=F.background),F.border&&(o["--persona-label-btn-border"]=F.border),F.color&&(o["--persona-label-btn-color"]=F.color),F.padding&&(o["--persona-label-btn-padding"]=F.padding),F.borderRadius&&(o["--persona-label-btn-radius"]=F.borderRadius),F.hoverBackground&&(o["--persona-label-btn-hover-bg"]=F.hoverBackground),F.fontSize&&(o["--persona-label-btn-font-size"]=F.fontSize),F.gap&&(o["--persona-label-btn-gap"]=F.gap));let X=C?.toggleGroup;X&&(X.gap&&(o["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(o["--persona-toggle-group-radius"]=X.borderRadius));let G=C?.artifact;if(G?.toolbar){let j=G.toolbar;j.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=j.iconHoverColor),j.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=j.iconHoverBackground),j.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=j.iconPadding),j.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=j.iconBorderRadius),j.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=j.iconBorder),j.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=ag(j.toggleGroupGap)),j.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=j.toggleBorderRadius),j.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=ag(j.toggleGroupPadding)),j.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=j.toggleGroupBorder),j.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=j.toggleGroupBorderRadius),j.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=xo(e,j.toggleGroupBackground)??j.toggleGroupBackground),j.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=j.copyBackground),j.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=j.copyBorder),j.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=j.copyColor),j.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=ag(j.copyBorderRadius)),j.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=j.copyPadding),j.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=j.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??j.copyMenuBackground),j.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=j.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??j.copyMenuBorder),j.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=j.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??j.copyMenuShadow),j.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=j.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??j.copyMenuBorderRadius),j.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=j.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??j.copyMenuItemHoverBackground),j.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=j.iconBackground),j.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=j.toolbarBorder)}if(G?.tab){let j=G.tab;j.background&&(o["--persona-artifact-tab-bg"]=j.background),j.activeBackground&&(o["--persona-artifact-tab-active-bg"]=j.activeBackground),j.activeBorder&&(o["--persona-artifact-tab-active-border"]=j.activeBorder),j.borderRadius&&(o["--persona-artifact-tab-radius"]=j.borderRadius),j.textColor&&(o["--persona-artifact-tab-color"]=j.textColor),j.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=j.hoverBackground),j.listBackground&&(o["--persona-artifact-tab-list-bg"]=j.listBackground),j.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=j.listBorderColor),j.listPadding&&(o["--persona-artifact-tab-list-padding"]=j.listPadding)}if(G?.pane){let j=G.pane;if(j.toolbarBackground){let qe=xo(e,j.toolbarBackground)??j.toolbarBackground;o["--persona-artifact-toolbar-bg"]=qe}}if(G?.card){let j=G.card;j.background&&(o["--persona-artifact-card-bg"]=j.background),j.border&&(o["--persona-artifact-card-border"]=j.border),j.borderRadius&&(o["--persona-artifact-card-radius"]=j.borderRadius),j.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=j.hoverBackground),j.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=j.hoverBorderColor)}if(G?.inline){let j=G.inline;j.background&&(o["--persona-artifact-inline-bg"]=xo(e,j.background)??j.background),j.border&&(o["--persona-artifact-inline-border"]=j.border),j.borderRadius&&(o["--persona-artifact-inline-radius"]=j.borderRadius),j.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=xo(e,j.chromeBackground)??j.chromeBackground),j.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=xo(e,j.chromeBorder)??j.chromeBorder),j.titleColor&&(o["--persona-artifact-inline-title-color"]=xo(e,j.titleColor)??j.titleColor),j.mutedColor&&(o["--persona-artifact-inline-muted-color"]=xo(e,j.mutedColor)??j.mutedColor),j.frameHeight&&(o["--persona-artifact-inline-frame-height"]=j.frameHeight)}let E=C?.code;E&&(E.keywordColor&&(o["--persona-code-keyword-color"]=E.keywordColor),E.stringColor&&(o["--persona-code-string-color"]=E.stringColor),E.commentColor&&(o["--persona-code-comment-color"]=E.commentColor),E.numberColor&&(o["--persona-code-number-color"]=E.numberColor),E.tagColor&&(o["--persona-code-tag-color"]=E.tagColor),E.attrColor&&(o["--persona-code-attr-color"]=E.attrColor),E.propertyColor&&(o["--persona-code-property-color"]=E.propertyColor),E.lineNumberColor&&(o["--persona-code-line-number-color"]=E.lineNumberColor),E.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=E.gutterBorderColor),E.background&&(o["--persona-code-bg"]=xo(e,E.background)??E.background));let O=o["--persona-surface"],D=o["--persona-container"],W=o["--persona-palette-colors-gray-100"]??"#f3f4f6",te=o["--persona-palette-colors-gray-200"]??"#e5e7eb",Q=o["--persona-palette-colors-gray-300"]??"#d1d5db",de=!D||D===O,pe=HP(O??o["--persona-background"]),Ce=de&&pe!==void 0&&pe<WP,Ee=Ce?"rgba(255, 255, 255, 0.08)":W,ge=Ce?"rgba(255, 255, 255, 0.12)":te,Ke=Ce?"rgba(255, 255, 255, 0.16)":Q,Bt=de?Ee:D,Le=de?ge:D;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??Bt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??Le,de&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??Ke),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??Bt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??Bt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??Bt,o}var NC={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var BP={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"}}},OP={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},FC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Al=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",DP=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Al()},lu=e=>DP(e),_P=e=>wl(e),NP=e=>{let t=Va(OP,e??{})??{};return wl({...t,palette:{...t.palette,colors:{...BP.colors,...t.palette?.colors}}},{validate:!1})},Kr=e=>{let t=lu(e),o=FC(e?.theme),n=FC(e?.darkTheme);return t==="dark"?NP(Va(o??{},n??{})):_P(o)},FP=e=>iu(e),Us=(e,t)=>{let o=Kr(t),n=FP(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",lu(t))},Ka=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(Al())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Al());o.addEventListener?(o.addEventListener("change",n),t.push(()=>o.removeEventListener("change",n))):o.addListener&&(o.addListener(n),t.push(()=>o.removeListener(n)))}return()=>{t.forEach(o=>o())}};var Gr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var du="24px",ug=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ml=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let o=Number(t[1])/100;return o>0&&o<1?o:null},UC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var qC=null;var pg=()=>{if(qC!==null)return qC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},UP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",cu=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},uu=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),o=t.pop(),n={key:o,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")n.mod=!0;else if(r==="shift")n.shift=!0;else if(r==="alt"||r==="option")n.alt=!0;else return cu("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(cu("unsupported",e),null):(o==="space"&&(n.key=" "),n)},qP=e=>UP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),$C=(e,t)=>{let o=uu(e);if(!o)return"";let n=pg(),r=qP(o.key);if(!t&&n)return`${o.alt?"\u2325":""}${o.shift?"\u21E7":""}\u2318${r}`;let a=[t?n?"Meta":"Control":"Ctrl"];return o.alt&&a.push("Alt"),o.shift&&a.push("Shift"),a.push(r),a.join("+")},pu=e=>$C(e,!1),Tl=e=>$C(e,!0),$P=(e,t)=>t.key?.toLowerCase()===e.key&&(pg()?t.metaKey:t.ctrlKey)===e.mod&&!(pg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,VP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},VC=e=>{let t=new Map,o=e?.ownerDocument??(typeof document<"u"?document:null),n=(a,i)=>{if((a.scope??"widget")==="page")return!0;if(!e)return!1;let d=i.composedPath?.();return d?.length?d.includes(e):e.contains(i.target)},r=a=>{if(a.isComposing||!t.size)return;let i=a.composedPath?.()[0]??a.target;for(let d of t.values())if($P(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&VP(i))){a.preventDefault();try{d.run(a)}catch(c){cu(`${d.id} threw on`,d.combo),console.warn(c)}return}};return o?.addEventListener("keydown",r),{register(a){let i=uu(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(d);return c?(cu(`${c.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",Tl(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var jC=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:h=>h.getAttribute("im-preserve")==="true",shouldReAppend:h=>h.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(h,y,x={}){h=p(h);let T=m(y),w=u(h,T,x),k=r(w,()=>d(w,h,T,P=>P.morphStyle==="innerHTML"?(a(P,h,T),Array.from(h.childNodes)):n(P,h,T)));return w.pantry.remove(),k}function n(h,y,x){let T=m(y);return a(h,T,x,y,y.nextSibling),Array.from(T.childNodes)}function r(h,y){if(!h.config.restoreFocus)return y();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return y();let{id:T,selectionStart:w,selectionEnd:k}=x,P=y();return T&&T!==document.activeElement?.getAttribute("id")&&(x=h.target.querySelector(`[id="${T}"]`),x?.focus()),x&&!x.selectionEnd&&k&&x.setSelectionRange(w,k),P}let a=(function(){function h(b,A,C,L=null,F=null){A instanceof HTMLTemplateElement&&C instanceof HTMLTemplateElement&&(A=A.content,C=C.content),L||(L=A.firstChild);for(let X of C.childNodes){if(L&&L!=F){let E=x(b,X,L,F);if(E){E!==L&&w(b,L,E),i(E,X,b),L=E.nextSibling;continue}}if(X instanceof Element){let E=X.getAttribute("id");if(b.persistentIds.has(E)){let O=k(A,E,L,b);i(O,X,b),L=O.nextSibling;continue}}let G=y(A,X,L,b);G&&(L=G.nextSibling)}for(;L&&L!=F;){let X=L;L=L.nextSibling,T(b,X)}}function y(b,A,C,L){if(L.callbacks.beforeNodeAdded(A)===!1)return null;if(L.idMap.has(A)){let F=document.createElement(A.tagName);return b.insertBefore(F,C),i(F,A,L),L.callbacks.afterNodeAdded(F),F}else{let F=document.importNode(A,!0);return b.insertBefore(F,C),L.callbacks.afterNodeAdded(F),F}}let x=(function(){function b(L,F,X,G){let E=null,O=F.nextSibling,D=0,W=X;for(;W&&W!=G;){if(C(W,F)){if(A(L,W,F))return W;E===null&&(L.idMap.has(W)||(E=W))}if(E===null&&O&&C(W,O)&&(D++,O=O.nextSibling,D>=2&&(E=void 0)),L.activeElementAndParents.includes(W))break;W=W.nextSibling}return E||null}function A(L,F,X){let G=L.idMap.get(F),E=L.idMap.get(X);if(!E||!G)return!1;for(let O of G)if(E.has(O))return!0;return!1}function C(L,F){let X=L,G=F;return X.nodeType===G.nodeType&&X.tagName===G.tagName&&(!X.getAttribute?.("id")||X.getAttribute?.("id")===G.getAttribute?.("id"))}return b})();function T(b,A){if(b.idMap.has(A))R(b.pantry,A,null);else{if(b.callbacks.beforeNodeRemoved(A)===!1)return;A.parentNode?.removeChild(A),b.callbacks.afterNodeRemoved(A)}}function w(b,A,C){let L=A;for(;L&&L!==C;){let F=L;L=L.nextSibling,T(b,F)}return L}function k(b,A,C,L){let F=L.target.getAttribute?.("id")===A&&L.target||L.target.querySelector(`[id="${A}"]`)||L.pantry.querySelector(`[id="${A}"]`);return P(F,L),R(b,F,C),F}function P(b,A){let C=b.getAttribute("id");for(;b=b.parentNode;){let L=A.idMap.get(b);L&&(L.delete(C),L.size||A.idMap.delete(b))}}function R(b,A,C){if(b.moveBefore)try{b.moveBefore(A,C)}catch{b.insertBefore(A,C)}else b.insertBefore(A,C)}return h})(),i=(function(){function h(P,R,b){return b.ignoreActive&&P===document.activeElement?null:(b.callbacks.beforeNodeMorphed(P,R)===!1||(P instanceof HTMLHeadElement&&b.head.ignore||(P instanceof HTMLHeadElement&&b.head.style!=="morph"?c(P,R,b):(y(P,R,b),k(P,b)||a(b,P,R))),b.callbacks.afterNodeMorphed(P,R)),P)}function y(P,R,b){let A=R.nodeType;if(A===1){let C=P,L=R,F=C.attributes,X=L.attributes;for(let G of X)w(G.name,C,"update",b)||C.getAttribute(G.name)!==G.value&&C.setAttribute(G.name,G.value);for(let G=F.length-1;0<=G;G--){let E=F[G];if(E&&!L.hasAttribute(E.name)){if(w(E.name,C,"remove",b))continue;C.removeAttribute(E.name)}}k(C,b)||x(C,L,b)}(A===8||A===3)&&P.nodeValue!==R.nodeValue&&(P.nodeValue=R.nodeValue)}function x(P,R,b){if(P instanceof HTMLInputElement&&R instanceof HTMLInputElement&&R.type!=="file"){let A=R.value,C=P.value;T(P,R,"checked",b),T(P,R,"disabled",b),R.hasAttribute("value")?C!==A&&(w("value",P,"update",b)||(P.setAttribute("value",A),P.value=A)):w("value",P,"remove",b)||(P.value="",P.removeAttribute("value"))}else if(P instanceof HTMLOptionElement&&R instanceof HTMLOptionElement)T(P,R,"selected",b);else if(P instanceof HTMLTextAreaElement&&R instanceof HTMLTextAreaElement){let A=R.value,C=P.value;if(w("value",P,"update",b))return;A!==C&&(P.value=A),P.firstChild&&P.firstChild.nodeValue!==A&&(P.firstChild.nodeValue=A)}}function T(P,R,b,A){let C=R[b],L=P[b];if(C!==L){let F=w(b,P,"update",A);F||(P[b]=R[b]),C?F||P.setAttribute(b,""):w(b,P,"remove",A)||P.removeAttribute(b)}}function w(P,R,b,A){return P==="value"&&A.ignoreActiveValue&&R===document.activeElement?!0:A.callbacks.beforeAttributeUpdated(P,R,b)===!1}function k(P,R){return!!R.ignoreActiveValue&&P===document.activeElement&&P!==document.body}return h})();function d(h,y,x,T){if(h.head.block){let w=y.querySelector("head"),k=x.querySelector("head");if(w&&k){let P=c(w,k,h);return Promise.all(P).then(()=>{let R=Object.assign(h,{head:{block:!1,ignore:!0}});return T(R)})}}return T(h)}function c(h,y,x){let T=[],w=[],k=[],P=[],R=new Map;for(let A of y.children)R.set(A.outerHTML,A);for(let A of h.children){let C=R.has(A.outerHTML),L=x.head.shouldReAppend(A),F=x.head.shouldPreserve(A);C||F?L?w.push(A):(R.delete(A.outerHTML),k.push(A)):x.head.style==="append"?L&&(w.push(A),P.push(A)):x.head.shouldRemove(A)!==!1&&w.push(A)}P.push(...R.values());let b=[];for(let A of P){let C=document.createRange().createContextualFragment(A.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(C)!==!1){if("href"in C&&C.href||"src"in C&&C.src){let L,F=new Promise(function(X){L=X});C.addEventListener("load",function(){L()}),b.push(F)}h.appendChild(C),x.callbacks.afterNodeAdded(C),T.push(C)}}for(let A of w)x.callbacks.beforeNodeRemoved(A)!==!1&&(h.removeChild(A),x.callbacks.afterNodeRemoved(A));return x.head.afterHeadMorphed(h,{added:T,kept:k,removed:w}),b}let u=(function(){function h(b,A,C){let{persistentIds:L,idMap:F}=P(b,A),X=y(C),G=X.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(G))throw`Do not understand how to morph style ${G}`;return{target:b,newContent:A,config:X,morphStyle:G,ignoreActive:X.ignoreActive,ignoreActiveValue:X.ignoreActiveValue,restoreFocus:X.restoreFocus,idMap:F,persistentIds:L,pantry:x(),activeElementAndParents:T(b),callbacks:X.callbacks,head:X.head}}function y(b){let A=Object.assign({},t);return Object.assign(A,b),A.callbacks=Object.assign({},t.callbacks,b.callbacks),A.head=Object.assign({},t.head,b.head),A}function x(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function T(b){let A=[],C=document.activeElement;if(C?.tagName!=="BODY"&&b.contains(C))for(;C&&(A.push(C),C!==b);)C=C.parentElement;return A}function w(b){let A=Array.from(b.querySelectorAll("[id]"));return b.getAttribute?.("id")&&A.push(b),A}function k(b,A,C,L){for(let F of L){let X=F.getAttribute("id");if(A.has(X)){let G=F;for(;G;){let E=b.get(G);if(E==null&&(E=new Set,b.set(G,E)),E.add(X),G===C)break;G=G.parentElement}}}}function P(b,A){let C=w(b),L=w(A),F=R(C,L),X=new Map;k(X,F,b,C);let G=A.__idiomorphRoot||A;return k(X,F,G,L),{persistentIds:F,idMap:X}}function R(b,A){let C=new Set,L=new Map;for(let{id:X,tagName:G}of b)L.has(X)?C.add(X):L.set(X,G);let F=new Set;for(let{id:X,tagName:G}of A)F.has(X)?C.add(X):L.get(X)===G&&F.add(X);for(let X of C)F.delete(X);return F}return h})(),{normalizeElement:p,normalizeParent:m}=(function(){let h=new WeakSet;function y(k){return k instanceof Document?k.documentElement:k}function x(k){if(k==null)return document.createElement("div");if(typeof k=="string")return x(w(k));if(h.has(k))return k;if(k instanceof Node){if(k.parentNode)return new T(k);{let P=document.createElement("div");return P.append(k),P}}else{let P=document.createElement("div");for(let R of[...k])P.append(R);return P}}class T{constructor(P){this.originalNode=P,this.realParentNode=P.parentNode,this.previousSibling=P.previousSibling,this.nextSibling=P.nextSibling}get childNodes(){let P=[],R=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;R&&R!=this.nextSibling;)P.push(R),R=R.nextSibling;return P}querySelectorAll(P){return this.childNodes.reduce((R,b)=>{if(b instanceof Element){b.matches(P)&&R.push(b);let A=b.querySelectorAll(P);for(let C=0;C<A.length;C++)R.push(A[C])}return R},[])}insertBefore(P,R){return this.realParentNode.insertBefore(P,R)}moveBefore(P,R){return this.realParentNode.moveBefore(P,R)}get __idiomorphRoot(){return this.originalNode}}function w(k){let P=new DOMParser,R=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(R.match(/<\/html>/)||R.match(/<\/head>/)||R.match(/<\/body>/)){let b=P.parseFromString(k,"text/html");if(R.match(/<\/html>/))return h.add(b),b;{let A=b.firstChild;return A&&h.add(A),A}}else{let A=P.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return h.add(A),A}}return{normalizeElement:y,normalizeParent:x}})();return{morph:o,defaults:t}})();var fu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;jC.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&n){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let i=r.textContent??"",d=a.textContent??"";if(i!==d)return}return!1}}}}})};var zC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var fg={index:-1,draft:""};function KC(e){let{direction:t,history:o,currentValue:n,atStart:r,state:a}=e,i=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!i&&!r)return{handled:!1,state:a};if(!i){let d=o.length-1;return{handled:!0,value:o[d],state:{index:d,draft:n}}}if(a.index>0){let d=a.index-1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,state:a}}if(!i)return{handled:!1,state:a};if(a.index<o.length-1){let d=a.index+1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function GC(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function XC(){return new Map}function QC(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function YC(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function JC(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function ZC(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function eS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Vn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function qs(e,t){return Vn(e)-e.scrollTop<=t}function tS(e){let{following:t,currentScrollTop:o,lastScrollTop:n,nearBottom:r,userScrollThreshold:a,isAutoScrolling:i=!1,pauseOnUpwardScroll:d=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:u=!1}=e,p=o-n;return i||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:o}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:o}:t&&d&&p<0?{action:"pause",delta:p,nextLastScrollTop:o}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:o}:{action:"none",delta:p,nextLastScrollTop:o}}function oS(e){let{following:t,deltaY:o,nearBottom:n=!1,resumeWhenNearBottom:r=!1}=e;return t&&o<0?"pause":!t&&r&&o>0&&n?"resume":"none"}function nS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function mg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:o}}function rS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var El={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},jP=["pre","code","a","script","style"],mu=e=>({type:e?.type??El.type,placeholder:e?.placeholder??El.placeholder,speed:e?.speed??El.speed,duration:e?.duration??El.duration,buffer:e?.buffer??El.buffer}),aS=[{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"}],Pl=new Map;for(let e of aS)Pl.set(e.name,e);var iS=["wipe","glyph-cycle"],Ga=e=>{Pl.set(e.name,e)},yg=e=>{aS.some(t=>t.name===e)||Pl.delete(e)},bg=()=>Array.from(Pl.keys()),kl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Pl.get(e)??null,gu=(e,t,o,n,r)=>{if(!r)return e;if(o?.bufferContent)return o.bufferContent(e,n);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
29
- `);return a<0?"":e.slice(0,a)}return e},zP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${o}-${n}`,r.style.setProperty("--char-index",String(n)),r.textContent=t,r},KP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${o}-${n}`,r.style.setProperty("--word-index",String(n)),r.textContent=t,r},gg=/\s/,GP=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let n=o;if(t.has(n.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},XP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=0;for(;d<a.length;)if(gg.test(a[d])){let c=d;for(;c<a.length&&gg.test(a[c]);)c+=1;i.appendChild(n.createTextNode(a.slice(d,c))),d=c}else{let c=n.createElement("span");c.className="persona-stream-word-group";let u=d;for(;u<a.length&&!gg.test(a[u]);)c.appendChild(zP(n,a[u],t,o.value)),o.value+=1,u+=1;i.appendChild(c),d=u}r.replaceChild(i,e)},QP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=a.split(/(\s+)/);for(let c of d)c&&(/^\s+$/.test(c)?i.appendChild(n.createTextNode(c)):(i.appendChild(KP(n,c,t,o.value)),o.value+=1));r.replaceChild(i,e)},Ll=(e,t,o,n)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((n?.skipTags??jP).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],c=i.nextNode();for(;c;)GP(c,a)||d.push(c),c=i.nextNode();let u={value:n?.startIndex??0},p=t==="char"?XP:QP;for(let m of d)p(m,o,u);return r.innerHTML},hu=(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},Il=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},sS=new WeakMap,YP=(e,t)=>{if(!e.styles)return;let o=sS.get(t);if(o||(o=new Set,sS.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},hg=new WeakMap,JP=(e,t)=>{if(!e.onAttach)return;let o=hg.get(t);if(o||(o=new Map,hg.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},lS=e=>{let t=hg.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Rl=(e,t)=>{YP(e,t),JP(e,t)};var{setLoader:ZP,load:ek}=mt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),dS=ZP,cS=ek;function vg(e,t=so){let o=e.style.position,n=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),i=a.position==="static"||a.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=o),e.style.zIndex=n,e.style.isolation=r}}var Hl=0,Xr=null;function xg(e=document){if(Hl++,Hl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Xr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:r},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${r}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Hl=Math.max(0,Hl-1),Hl===0&&Xr)){let o=e.body,n=e.defaultView??window;o.style.overflow=Xr.originalOverflow,o.style.position=Xr.originalPosition,o.style.top=Xr.originalTop,o.style.width=Xr.originalWidth,n.scrollTo(0,Xr.scrollY),Xr=null}}}var Wl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Qr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Wo=e=>{let t=e?.launcher?.dock;return{side:t?.side??Wl.side,width:t?.width??Wl.width,animate:t?.animate??Wl.animate,reveal:t?.reveal??Wl.reveal,maxHeight:t?.maxHeight??Wl.maxHeight}};var Cg=e=>e==="followUp"?"follow-up":e,Sg=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let o=e.label.trim();if(!o)return null;let n=e.prompt?.trim()||o;return{id:e.id?.trim()||n||`suggestion-${t}`,label:o,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},tk=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},uS=new WeakSet,ok=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,nk=e=>{ok()||e.forEach((t,o)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:o*60,easing:"ease-out",fill:"backwards"})})},wg=e=>{var R,b,A;let{item:t,index:o,surface:n,source:r,variant:a,streaming:i,config:d,plugins:c,chipsConfig:u,session:p,getTextarea:m,eventTarget:h,submitPrompt:y}=e,x=n==="followUp",T=t.behavior,w=()=>{if(p.isStreaming())return;let C={suggestion:{...t},surface:n,source:r,behavior:T},L=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:C,bubbles:!0,composed:!0,cancelable:!0}));if(x&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!L)return;for(let X of c)if(X.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let F=m();if(T==="fill"){F.value=t.prompt,F.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),F.focus();return}if(y){y(t.prompt);return}F.value="",p.sendMessage(t.prompt)},k=()=>{let C=I("button",`persona-suggestion persona-suggestion--${a}`);if(C.type="button",C.disabled=i,C.dataset.suggestionId=t.id,C.dataset.emphasis=t.emphasis,C.dataset.behavior=T,a==="chip"&&(u?.fontFamily&&(C.style.fontFamily=tk(u.fontFamily)),u?.fontWeight&&(C.style.fontWeight=u.fontWeight),u?.paddingX&&(C.style.paddingLeft=u.paddingX,C.style.paddingRight=u.paddingX),u?.paddingY&&(C.style.paddingTop=u.paddingY,C.style.paddingBottom=u.paddingY)),t.icon){let F=ce(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);F&&(F.classList.add("persona-suggestion__icon"),t.iconColor&&(F.style.color=t.iconColor),C.appendChild(F))}let L=I("span","persona-suggestion__copy");if(L.appendChild(Y("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&L.appendChild(Y("span",{className:"persona-suggestion__description",text:t.description})),C.appendChild(L),a!=="chip"){let F=Ft(ul,16,"currentColor",1.8);F&&(F.classList.add("persona-suggestion__arrow"),C.appendChild(F))}return C.addEventListener("click",w),C},P=null;for(let C of c)if(C.renderSuggestion&&(P=C.renderSuggestion({suggestion:{...t},index:o,surface:n,source:r,variant:a,streaming:i,config:d,defaultRenderer:k,select:w}),P))break;return P??(P=k()),(R=P.dataset).suggestionId||(R.suggestionId=t.id),(b=P.dataset).behavior||(b.behavior=T),(A=P.dataset).emphasis||(A.emphasis=t.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",i?"true":"false"),P},Bl=e=>{let t=[],o=[],n=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){a();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),y=4,x=h<=y,T=h>=p-y,w=m?!T:!x,k=m?!x:!T;e.toggleAttribute("data-scroll-left",w),e.toggleAttribute("data-scroll-right",k)},d=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",d,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(d):null;return c?.observe(e),{buttons:t,elements:o,destroy:()=>{e.removeEventListener("scroll",d),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,h,y,x,T)=>{e.replaceChildren(),t.length=0,o.length=0;let w=T?.source??"config",k=T?.surface??(w==="config"?"starter":"followUp"),P=k==="followUp",R=T?.variant??"chip",b=T?.behavior??"send",A=T?.overflow??"wrap",C=T?.config??{},L=T?.plugins??[],F=typeof T?.maxItems=="number"?Math.max(0,Math.floor(T.maxItems)):void 0,X=P?"followUps":"starters";!uS.has(C)&&C.debug===!0&&R!=="chip"&&C.suggestions?.[X]?.overflow!==void 0&&(uS.add(C),console.info(`[persona] suggestions.${X}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let G=Q=>Q.map(Sg).filter(de=>de!==null).map(de=>({...de,behavior:de.behavior??b})),E=G(p??[]);L.forEach(Q=>{Q.transformSuggestions&&(E=G(Q.transformSuggestions({suggestions:E.map(de=>({...de})),surface:k,source:w,config:C})))});let O=F===void 0?E:E.slice(0,F);if(!O.length){e.hidden=!0,n=null,a();return}if(!P&&(y??m.getMessages()).some(de=>de.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Cg(k),e.dataset.variant=R,e.dataset.overflow=A;let D=document.createDocumentFragment(),W=m.isStreaming();O.forEach((Q,de)=>{let pe=wg({item:Q,index:de,surface:k,source:w,variant:R,streaming:W,config:C,plugins:L,chipsConfig:x,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:T?.submitPrompt});D.appendChild(pe),o.push(pe),[...pe instanceof HTMLButtonElement?[pe]:[],...Array.from(pe.querySelectorAll("button"))].forEach(Ee=>{t.includes(Ee)||(Ee.disabled=W,t.push(Ee))})}),e.appendChild(D),i(),d();let te=JSON.stringify({normalized:O,surface:k,variant:R,source:w});te!==n&&(n=te,nk(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:O.map(Q=>({...Q})),surface:k,source:w,variant:R},bubbles:!0,composed:!0})),P&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:O.map(Q=>Q.prompt)},bubbles:!0,composed:!0})))}}};var Go={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var rk="persona-header-control",sk="persona-header-control--glyph",ak="persona-header-control--sparse",ik=20,lk={x:[1.4,1.05]},pS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",dk="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yu=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=lk[t]??[1,1.5],d=!n;e.classList.toggle(sk,d),e.classList.toggle(ak,d&&a!==1);let c=parseFloat(n??"")||ik,u=ce(t,`${Math.round(c*a)}px`,"currentColor",i);u?(u.style.display="block",d||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},$s=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=pS,size:d,iconSize:c,color:u,backgroundColor:p,borderWidth:m,borderColor:h,borderRadius:y,paddingX:x,paddingY:T,hidden:w,extraClassName:k,attrs:P}=e,R=I("div",i),b=!!(m||h),A=Y("button",{className:bo(rk,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!b&&"persona-border-none",!y&&"persona-rounded-full",k),attrs:{type:"button","aria-label":t,...P},style:{width:d,height:d,minWidth:d,minHeight:d,display:w?"none":void 0,color:u||Co.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:x,paddingRight:x,paddingTop:T,paddingBottom:T}});return r?yu(A,r,{iconSize:c,iconText:a}):a&&(A.textContent=a),R.appendChild(A),eo({anchor:A,trigger:R,text:()=>A.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:A,wrapper:R}},Xa=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=pS,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=$s({ariaLabel:d,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:n,size:r??i.closeButtonSize,iconSize:a,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!o});return{button:u,wrapper:p}},Qa=(e,t={})=>{let{wrapperClassName:o=dk,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:u,wrapper:p}=$s({ariaLabel:d,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:o,size:n??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var Co={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Ag={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)"},ck={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)"},mr=e=>{let{config:t,showClose:o=!0}=e,n=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:Co.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},a=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",d=r.headerIconHidden??!1,c=r.headerIconName,u=Y("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!d)if(c){let A=parseFloat(a)||24,C=ce(c,A*.6,"currentColor",1);C?u.replaceChildren(C):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let A=I("img");A.src=t.launcher.iconUrl,A.alt="",A.className="persona-rounded-xl persona-object-cover",A.style.height=a,A.style.width=a,u.replaceChildren(A)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=I("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Y("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Co.titleColor,...Ag}}),h=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Co.subtitleColor,...ck}});p.append(m,h),d?n.append(p):n.append(u,p);let y=r.clearChat??{},x=y.enabled??!0,T=y.placement??"inline",w=null,k=null;if(x){let C=Qa(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=C.button,k=C.wrapper,T==="top-right"&&(k.style.right="48px"),T==="inline"&&n.appendChild(k)}let P=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&T==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:b}=Xa(t,{showClose:o,wrapperClassName:P});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:R,closeButtonWrapper:b,clearChatButton:w,clearChatButtonWrapper:k}},Vs=(e,t,o)=>{let n=o?.launcher??{},r=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function js(e){let{items:t,onSelect:o,anchor:n,position:r="bottom-left",portal:a,onOpenChange:i}=e,d=I("div","persona-dropdown-menu persona-hidden");d.setAttribute("role","menu"),d.setAttribute("data-persona-theme-zone","dropdown"),a?(d.style.position="fixed",d.style.zIndex=String($a)):(d.style.position="absolute",d.style.top="100%",d.style.marginTop="4px",r==="bottom-right"?d.style.right="0":d.style.left="0");for(let x of t){if(x.dividerBefore){let k=document.createElement("hr");d.appendChild(k)}let T=document.createElement("button");if(T.type="button",T.setAttribute("role","menuitem"),T.setAttribute("data-dropdown-item-id",x.id),x.destructive&&T.setAttribute("data-destructive",""),x.icon){let k=ce(x.icon,16,"currentColor",1.5);k&&T.appendChild(k)}let w=document.createElement("span");w.textContent=x.label,T.appendChild(w),T.addEventListener("click",k=>{k.stopPropagation(),m(),o(x.id)}),d.appendChild(T)}let c=null;function u(){if(!a)return;let x=n.getBoundingClientRect();d.style.top=`${x.bottom+4}px`,r==="bottom-right"?(d.style.right=`${window.innerWidth-x.right}px`,d.style.left="auto"):(d.style.left=`${x.left}px`,d.style.right="auto")}function p(){let x=d.classList.contains("persona-hidden");u(),d.classList.remove("persona-hidden"),x&&i?.(!0),requestAnimationFrame(()=>{let T=w=>{!d.contains(w.target)&&!n.contains(w.target)&&m()};document.addEventListener("click",T,!0),c=()=>document.removeEventListener("click",T,!0)})}function m(){let x=!d.classList.contains("persona-hidden");d.classList.add("persona-hidden"),c?.(),c=null,x&&i?.(!1)}function h(){d.classList.contains("persona-hidden")?p():m()}function y(){m(),d.remove()}return a&&a.appendChild(d),{element:d,show:p,hide:m,toggle:h,destroy:y}}function zs(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:c}=e,u=I("button",bo(!i&&"persona-icon-btn",a));u.type="button",u.setAttribute("aria-label",o),u.title=o;let p=ce(t,n??16,"currentColor",r??2);if(p&&u.appendChild(p),d&&u.addEventListener("click",d),c)for(let[m,h]of Object.entries(c))u.setAttribute(m,h);return u}function Mg(e){let{icon:t,label:o,variant:n="default",size:r="sm",iconSize:a,className:i,onClick:d,aria:c}=e,u="persona-label-btn";n!=="default"&&(u+=" persona-label-btn--"+n),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=I("button",u);if(p.type="button",p.setAttribute("aria-label",o),t){let h=ce(t,a??14,"currentColor",2);h&&p.appendChild(h)}let m=I("span");if(m.textContent=o,p.appendChild(m),d&&p.addEventListener("click",d),c)for(let[h,y]of Object.entries(c))p.setAttribute(h,y);return p}function fS(e){let{items:t,selectedId:o,onSelect:n,className:r}=e,a=I("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let i=o,d=[];function c(){for(let p of d)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let m;p.icon?m=zs({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),n(p.id)}}):(m=I("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{i=p.id,c(),n(p.id)})),m.setAttribute("aria-pressed",p.id===i?"true":"false"),d.push({id:p.id,btn:m}),a.appendChild(m)}function u(p){i=p,c()}return{element:a,setSelected:u}}function mS(e){let{label:t,icon:o,iconSize:n,iconOnly:r,menuItems:a,onSelect:i,onPrimary:d,position:c="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:x}=e,T=I("div","persona-split-btn"+(h?" "+h:"")),w={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:d},k=r&&o?zs({...w,icon:o,size:n??14}):Mg({...w,icon:o,iconSize:n??14}),P=zs({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(x?" "+x:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});T.append(k,P);let R=null,b=()=>{if(R)return R;let A=(typeof u=="function"?u():u)??void 0;return R=js({items:a,onSelect:i,anchor:T,position:c,portal:A,onOpenChange:C=>{P.setAttribute("aria-expanded",C?"true":"false")}}),A||T.appendChild(R.element),R};return T.isConnected?b():requestAnimationFrame(()=>{R||b()}),P.addEventListener("click",A=>{A.stopPropagation(),b().toggle()}),{element:T,primaryButton:k,chevronButton:P,openMenu:()=>b().show(),closeMenu:()=>R?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{R?.destroy(),T.remove()}}}function bu(e){let{label:t,icon:o="chevron-down",menuItems:n,onSelect:r,position:a="bottom-left",portal:i,className:d,hover:c}=e,u=I("div","persona-combo-btn"+(d?" "+d:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=I("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let m=ce(o,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",u.appendChild(m)),c&&(u.style.borderRadius=c.borderRadius??"10px",u.style.padding=c.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=c.background??"",u.style.borderColor=c.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let h=js({items:n,onSelect:x=>{u.setAttribute("aria-expanded","false"),r(x)},anchor:u,position:a,portal:i});i||u.appendChild(h.element);let y=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",x=>{if(x.stopPropagation(),y())return;let T=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",T?"false":"true"),h.toggle()}),u.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),u.click())}),{element:u,setLabel:x=>{p.textContent=x,u.setAttribute("aria-label",x)},open:()=>{u.setAttribute("aria-expanded","true"),h.show()},close:()=>{u.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let x=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",x?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),u.remove()}}}var Tg=e=>{let t=mr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>o()),n.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),o())}))}return t};function uk(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=$s({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?pu(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",n.id),n.shortcut){let i=Tl(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=js({items:n.menuItems,onSelect:d=>o?.(d),anchor:a,position:"bottom-right"});a.appendChild(i.element),r.addEventListener("click",d=>{d.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>o?.(n.id));e.appendChild(a)}}var Eg=e=>{let{config:t,showClose:o=!0,onClose:n,layoutHeaderConfig:r,onHeaderAction:a}=e,i=t?.launcher??{},d=I("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");d.setAttribute("data-persona-theme-zone","header"),d.style.minHeight=Co.minHeight,d.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",d.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",d.style.boxShadow="var(--persona-header-shadow, none)",d.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,u,p;if(c){let b=bu({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:A=>{let C=F=>{F===!1&&b.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:A}}))},L=c.onSelect(A);L instanceof Promise?L.then(C,()=>{}):C(L)},hover:c.hover,className:""});u=b.element,u.style.color=Co.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=I("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=I("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Co.titleColor,Object.assign(p.style,Ag),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let A=r.onTitleClick;u.addEventListener("click",C=>{C.target.closest("button")||A()}),u.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),A())})}let b=r?.titleRowHover;b&&(u.style.borderRadius=b.borderRadius??"10px",u.style.padding=b.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=b.background??"",u.style.borderColor=b.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}d.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=Xa(t,{showClose:o,wrapperClassName:m});n&&h.addEventListener("click",n);let x=I("div","persona-flex persona-items-center persona-gap-1");c||uk(x,r?.trailingActions,r?.onAction??a);let T=i.clearChat??{},w=null,k=null;if(T.enabled??!0){let b=T.placement??"inline",A=Qa(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});w=A.button,k=A.wrapper,b==="top-right"?k.style.right="48px":x.appendChild(k)}x.appendChild(y),d.appendChild(x);let P=I("div");P.style.display="none";let R=I("span");return R.style.display="none",{header:d,iconHolder:P,headerTitle:p,headerSubtitle:R,closeButton:h,closeButtonWrapper:y,clearChatButton:w,clearChatButtonWrapper:k}},vu={default:Tg,minimal:Eg},Pg=e=>vu[e]??vu.default,Ya=(e,t,o)=>{if(t?.render){let i=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),d=I("div");d.style.display="none";let c=I("span"),u=I("span"),p=I("button");p.style.display="none";let m=I("div");return m.style.display="none",{header:i,iconHolder:d,headerTitle:c,headerSubtitle:u,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let n=t?.layout??"default",a=Pg(n)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ks=e=>{let{config:t}=e,o=Y("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=Zc(),r=Y("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:i}=Xc(t);i();let d=Qc(t),c=za(t),u=Yc(t),p=Jc(t),m=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),r.append(u.input)),r.append(a);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&y.append(u.wrapper),c&&x.append(c.wrapper),x.append(d.wrapper),h.append(y,x),r.append(h),r.addEventListener("click",T=>{T.target!==d.button&&T.target!==d.wrapper&&T.target!==c?.button&&T.target!==c?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&a.focus()}),o.append(n,r,p),{footer:o,suggestions:n,composerForm:r,header:m,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:x,setSendButtonMode:d.setMode}};var gS=()=>{let e=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=I("span","persona-pill-peek__icon"),o=Ft(hl,16,"currentColor",1.5);o&&t.appendChild(o);let n=I("span","persona-pill-peek__text"),r=I("span","persona-pill-peek__caret"),a=Ft(_s,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},xu=e=>{let{config:t}=e,o=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=Zc(),r=Jc(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=Xc(t,{defaultMaxLines:5});i();let d=Qc(t),c=za(t),u=Yc(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&h.append(c.wrapper),h.append(d.wrapper),p.addEventListener("click",T=>{T.target!==d.button&&T.target!==d.wrapper&&T.target!==c?.button&&T.target!==c?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&a.focus()}),u&&p.append(u.input),p.append(m,a,h);let y=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(y),u&&y.append(u.previewsContainer),o.append(n,p,r);let x=p;return{footer:o,suggestions:n,composerForm:p,header:y,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:x,leftActions:m,rightActions:h,setSendButtonMode:d.setMode}};var pk=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},fk=(e,t)=>{if(!e)return null;let o=pk(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},mk=(e,t)=>{let o=I("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},gk=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Lg=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ig=320,xS=320,hk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),yk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),bk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),vk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),xk=e=>{if(!e||e.length===0)return null;let t=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let o of e){let n=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:o.label}}),r=I("span","persona-mention-chip-icon"),a=ce(o.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),n.appendChild(r),n.appendChild(Y("span",{className:"persona-mention-chip-label",text:o.label})),t.appendChild(n)}return t},Ck=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(Sl(n.ref,{readonly:!0,render:t}))}return o},hS="\uE000",yS="\uE001",Sk=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=h=>`${hS}${r}:${h}${yS}`,i=t.map((h,y)=>h.kind==="text"?h.text:a(y)).join(""),d=o(i);if(!t.every((h,y)=>h.kind==="text"||d.includes(a(y)))){e.replaceChildren(Ck(t,n));return}e.innerHTML=d;let u=new RegExp(`${hS}${r}:(\\d+)${yS}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=p.nextNode();h;h=p.nextNode())m.push(h);for(let h of m){let y=h;for(let x=u.exec(y.data);x;x=u.exec(y.data)){let T=t[Number(x[1])],w=y.splitText(x.index);w.data=w.data.slice(x[0].length),T?.kind==="mention"&&w.parentNode?.insertBefore(Sl(T.ref,{readonly:!0,render:n}),w),y=w}}},wk=(e,t,o)=>{if(e.length===0)return null;try{let n=I("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let r=0,a=!1,i=()=>{a||(a=!0,n.remove(),o?.())};return e.forEach((d,c)=>{let u=I("img");u.alt=d.alt?.trim()||`Attached image ${c+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Ig}px`,u.style.maxHeight=`${xS}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),gk(d.image)?(u.src=d.image,n.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):n}catch{return o?.(),null}},Ak=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(n=>{if(!Lg(n.audio))return;let r=I("audio");r.controls=!0,r.preload="metadata",r.src=n.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ig}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Mk=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(n=>{if(!Lg(n.video))return;let r=I("video");r.controls=!0,r.preload="metadata",r.src=n.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Ig}px`,r.style.maxHeight=`${xS}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Tk=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(n=>{if(!Lg(n.data))return;let r=I("a");r.href=n.data,r.download=n.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=n.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Gs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(n),e.appendChild(r),e},Rg=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:Gs};if(t){let r=t(n);if(r!==null)return r}return Gs()},Ek=(e,t)=>{let o=I("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let r=I("img");r.src=n,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(r)}else o.textContent=n,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},bS=(e,t,o="div")=>{let n=I(o,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Ol=(e,t="bubble")=>{let o=["persona-message-bubble"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return o},vS={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"}},Pk=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=vS[o??"bubble"]??vS.bubble;n.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Cu="custom:",kk=e=>`${Cu}${e}`,CS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),Hg=(e,t,o,n)=>{let r=t.showCopy??!0,a=t.showUpvote??!0,i=t.showDownvote??!0,d=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&n?.canRegenerate===!0,u=(t.showEdit??!1)&&n?.canEdit===!0,p=(t.showQuote??!1)&&n?.canQuote!==!1,m=CS(t,e.role);if(!r&&!a&&!i&&!d&&!c&&!u&&!p&&m.length===0){let R=I("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let h=t.visibility??"hover",y=t.align??"right",x=t.layout??"pill-inside",T={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],w={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],k=I("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${T} ${w} ${h==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let P=(R,b,A)=>{let C=zs({icon:R,label:b,size:14,className:"persona-message-action-btn",chromeless:!0});return C.setAttribute("data-action",A),C};r&&k.appendChild(P("copy","Copy message","copy")),d&&k.appendChild(P("volume-2","Read aloud","read-aloud")),a&&k.appendChild(P("thumbs-up","Upvote","upvote")),i&&k.appendChild(P("thumbs-down","Downvote","downvote")),c&&k.appendChild(P("refresh-cw","Regenerate response","regenerate")),u&&k.appendChild(P("pencil","Edit message","edit")),p&&k.appendChild(P("quote","Quote message","quote"));for(let R of m)k.appendChild(P(R.iconName??"ellipsis",R.label,kk(R.id)));return k},Ja=(e,t,o,n,r,a)=>{let i=o??{},d=i.layout??"bubble",c=i.avatar,u=i.timestamp,p=c?.show??!1,m=u?.show??!1,h=c?.position??"left",y=u?.position??"below",x=Ol(e.role,d),T=I("div",x.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let w=a?.widgetConfig?.theme?.components?.message;Pk(T,e.role,d,e.role==="user"?w?.user:w?.assistant),d==="flat"?(T.style.backgroundColor="transparent",T.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=hk(e),P=e.content?.trim()??"",b=k.length>0&&P===Ba,A=mu(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&A.type!=="none"?kl(A.type,C):null,F=e.role==="assistant"&&L?.isAnimating?.(e)===!0,X=e.role==="assistant"&&L!==null&&(!!e.streaming||F);X&&L?.bubbleClass&&T.classList.add(L.bubbleClass);let G=document.createElement("div");G.classList.add("persona-message-content"),e.streaming&&G.classList.add("persona-content-streaming"),X&&L&&(L.containerClass&&G.classList.add(L.containerClass),G.style.setProperty("--persona-stream-step",`${A.speed}ms`),G.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let E=X?gu(e.content??"",A.buffer,L,e,!!e.streaming):e.content??"",O=()=>{let Le=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&L?.wrap==="char"?Ll(Le,"char",e.id,{skipTags:L.skipTags}):X&&L?.wrap==="word"?Ll(Le,"word",e.id,{skipTags:L.skipTags}):Le},D=null;if(b?(D=document.createElement("div"),D.innerHTML=O(),D.style.display="none",G.appendChild(D)):e.contentSegments?.length?Sk(G,e.contentSegments,Le=>t({text:Le,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):G.innerHTML=O(),X&&L?.useCaret&&!b&&P){let Le=hu(),j=G.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=j[j.length-1];if(qe?.parentNode)qe.parentNode.insertBefore(Le,qe.nextSibling);else{let Ge=G.lastElementChild;Ge?Ge.appendChild(Le):G.appendChild(Le)}}if(m&&y==="inline"&&e.createdAt){let Le=bS(e,u,"span");Le.classList.add("persona-timestamp-inline");let j=G.lastElementChild;j?j.appendChild(Le):G.appendChild(Le)}if(k.length>0){let Le=wk(k,!b&&!!P,()=>{b&&D&&(D.style.display="")});Le?T.appendChild(Le):b&&D&&(D.style.display="")}let W=yk(e);if(W.length>0){let Le=Ak(W);Le&&T.appendChild(Le)}let te=bk(e);if(te.length>0){let Le=Mk(te);Le&&T.appendChild(Le)}let Q=vk(e);if(Q.length>0){let Le=Tk(Q);Le&&T.appendChild(Le)}let de=e.contentSegments?.length?null:xk(e.contextMentions);if(de&&T.appendChild(de),T.appendChild(G),m&&y==="below"&&e.createdAt){let Le=bS(e,u);Le.classList.add("persona-mt-1"),T.appendChild(Le)}let pe=e.role==="assistant"?fk(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Le=!!(E&&E.trim()),j=A.placeholder==="skeleton",qe=j&&A.buffer==="line"&&Le;if(Le)qe&&T.appendChild(Il());else if(j)T.appendChild(Il());else{let Ge=Rg("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ge&&T.appendChild(Ge)}}pe&&e.stopReason&&!e.streaming&&(P||(G.style.display="none"),T.appendChild(mk(e.stopReason,pe)));let Ce=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,Ee=a?.actionEligibility,ge=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&Ee?.canEdit===!0||n?.showQuote===!0&&Ee?.canQuote===!0||CS(n,"user").length>0);if((Ce||ge)&&n){let Le=Hg(e,ge?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,Ee);T.appendChild(Le)}if(!p||e.role==="system")return T;let Ke=I("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Bt=Ek(c,e.role);return h==="right"||h==="left"&&e.role==="user"?Ke.append(T,Bt):Ke.append(Bt,T),Ke},SS=(e,t,o,n,r,a)=>{let i=o??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ja(e,t,o,n,r,a)};var Lk=40,Ik=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let o=null;try{o=t()}catch(n){console.warn("[persona] welcome.icon renderer threw",n)}if(!o){e.hidden=!0;return}e.appendChild(o),e.hidden=!1;return}if(t.type==="lucide"){let o=ce(t.name,Lk);if(!o){e.hidden=!0;return}e.appendChild(o)}else t.type==="image"?e.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Y("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},wS=(e,t,o={})=>{let n=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let r=I("p","persona-welcome-kicker");r.hidden=!0;let a=I("h2","persona-welcome-title"),i=I("p","persona-welcome-subtitle"),d=Y("div",{className:"persona-welcome-head-text"},r,a),c=Y("div",{className:"persona-welcome-title-row"},n,d);return{host:Y("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:o.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,i,t),iconHolder:n,kicker:r,title:a,subtitle:i,starterSuggestions:t}},Za=(e,t,o)=>{t.hidden=!o,t.style.display=o?"":"none",e.classList.toggle("persona-gap-6",o),e.classList.toggle("persona-gap-3",!o)},wu=(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==="",Ik(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-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},Rk="data-persona-welcome-plugin",AS="data-persona-welcome-overlay",Su="persona-welcome-overlay-active",Wg=new WeakMap,Bg=(e,t,o)=>{o.setAttribute(Rk,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(AS,""),e.classList.contains(Su)||(Wg.set(e,e.scrollTop),e.classList.add(Su),e.scrollTop=0)},Og=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(AS),e.classList.contains(Su)&&(e.classList.remove(Su),e.scrollTop=Wg.get(e)??e.scrollTop,Wg.delete(e))},MS=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Au=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Y("div",{className:Ol("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:n==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Y("div",{className:"persona-flex"},r)),e.hidden=!1},TS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ES=(e,t)=>{if(TS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let o=e.getBoundingClientRect(),n=e.parentElement,r=0,a=0,i=0;if(n){let x=getComputedStyle(n);r=parseFloat(x.rowGap)||0;let T=e.previousElementSibling,w=e.nextElementSibling,P=n.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-n.scrollTop;a=Math.max(0,T?o.top-T.getBoundingClientRect().bottom-r:o.top-P),i=Math.max(0,w?w.getBoundingClientRect().top-o.bottom-r:0)}let d=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),u=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${o.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${a}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=d,t(m))};return m.finished.then(y).catch(y),m},PS=(e,t,o)=>{if(t<=1||TS()||typeof e.animate!="function"||!e.isConnected)return null;let n=o==="drop"?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var Hk="Hello \u{1F44B}",Wk="I can answer questions and help you get things done here.",kS=new WeakSet,So=(e,t)=>!!e&&e[t]!==void 0,Bk=(e,t)=>{!e||e.debug!==!0||!t.length||kS.has(e)||(kS.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},xn=e=>{let t=e?.welcome,o=e?.copy,n=So(t,"variant")?t.variant:o?.showWelcomeCard===!1?"none":"card",r=n==="hero"?"on-first-message":So(t,"dismiss")?t.dismiss:"never",a=[];So(t,"title")&&So(o,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),So(t,"subtitle")&&So(o,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),So(t,"variant")&&So(o,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),n==="hero"&&So(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),n==="hero"&&So(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let i=t?.anchor==="center"?"center":"bottom",d=Ml(t?.anchorComposerTop)!==null;return So(t,"anchorComposerTop")&&!d&&a.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),i!=="center"&&(So(t,"anchorComposerTop")||So(t,"composerGap"))&&a.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),Bk(e,a),{title:So(t,"title")?t.title:o?.welcomeTitle??Hk,kicker:t?.kicker??"",subtitle:So(t,"subtitle")?t.subtitle:o?.welcomeSubtitle??Wk,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:n,dismiss:r,message:n==="hero"?void 0:t?.message,anchor:i,anchorComposerTop:d?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||du}},LS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Yr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var IS="16px",_g="10px",Ng="14px",RS=e=>{let t=e?.launcher?.enabled??!0,o=St(e);if(Qr(e)){let p=e?.launcher?.composerBar??{},m=I("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??so);let h=I("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");h.style.width="100%",m.appendChild(h);let y=I("div","persona-widget-pill-root");return y.setAttribute("data-persona-composer-bar",""),y.dataset.state="collapsed",y.dataset.expandedSize=p.expandedSize??"anchored",y.style.zIndex=String(e?.launcher?.zIndex??so),{wrapper:m,panel:h,pillRoot:y}}if(o){let p=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(m),{wrapper:p,panel:m}}if(!t){let p=I("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=I("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=e?.launcher?.width??"100%";return p.style.width=h,m.style.width="100%",p.appendChild(m),{wrapper:p,panel:m}}let r=e?.launcher??{},a=r.position&&Go[r.position]?Go[r.position]:Go["bottom-right"],i=I("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??so);let d=I("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??zo;return d.style.width=u,d.style.maxWidth=u,i.appendChild(d),{wrapper:i,panel:d}},Fg=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Cg(e)}});return t.hidden=!0,t},HS=(e,t)=>{let o=Fg("starter"),n=wS(e,o,{flatShadow:St(e)}),r=xn(e);wu(n,r),Za(t,n.host,Yr(r,e?.initialMessages));let a=MS();return Au(a,r.message,e),{welcome:n,greetingHost:a}},Ok=(e,t)=>{let o=I("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:r}=Xa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:IS,iconSize:_g});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,i=null,d=null;if(a){let L=Qa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:IS,iconSize:Ng});i=L.button,d=L.wrapper,d.style.position="absolute",d.style.top="8px",d.style.right="32px",d.style.zIndex="10"}let c=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Y("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=HS(e,u),{host:h,title:y,subtitle:x}=p,T=p.starterSuggestions,w=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=Fg("followUp"),P=Gr(e,!0);P&&(w.style.maxWidth=P,w.style.marginLeft="auto",w.style.marginRight="auto",w.style.width="100%"),u.append(h,m,w,k);let R=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),b=xu({config:e}),{root:A,textNode:C}=gS();return o.append(c,r,u,R),d&&o.appendChild(d),{container:o,body:u,messagesWrapper:w,starterSuggestions:T,transcriptSuggestions:k,composerOverlay:R,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:h,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:y,introSubtitle:x,closeButton:n,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:d,iconHolder:I("span"),headerTitle:I("span"),headerSubtitle:I("span"),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:A,peekTextNode:C}},WS=(e,t=!0)=>{if(Qr(e))return Ok(e,t);let o=Y("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),n=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=n?Ya(e,n,{showClose:t}):mr({config:e,showClose:t}),i=Y("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=HS(e,i),{host:u,title:p,subtitle:m}=d,h=d.starterSuggestions,y=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=Fg("followUp"),T=Gr(e,!1);T&&(y.style.maxWidth=T,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),i.append(u,c,y,x);let w=Ks({config:e}),k=e?.layout?.showFooter!==!1;r?Vs(o,a,e):(a.header.style.display="none",Vs(o,a,e)),o.append(i);let P=Y("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 k||(w.footer.style.display="none"),o.append(w.footer),o.append(P),{container:o,body:i,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:x,composerOverlay:P,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,welcomeHost:u,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:p,introSubtitle:m,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode}};var Ug=(e,t)=>{let o=I("button");o.type="button",o.innerHTML=`
28
+ `)[0]).startsWith(A.trigger):!1),a=(b,A)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${b}`,{detail:A}))}catch{}},i=!e.chipRow,d=e.chipRow??Y("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),c=null,u=null,p=e.textarea,m=null,h=null,y=null,x=null,T=()=>{if(c)return Promise.resolve(c);if(u)return u;let b=ag().then(A=>(A.setMentionIconRenderer(ue),c=A.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:H,emit:a}),c)).catch(A=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",A),u===b&&(u=null),null));return u=b,b},w=()=>{OC().then(b=>{let A=b.mountInlineComposer({textarea:e.textarea,renderToken:L=>wl(L,{render:t.renderMentionToken}),onMentionRemoved:L=>c?.untrackMention(L)});m=A.input,h=A.destroy;let C=p;C.replaceWith(A.element),p=A.element,x={next:A.element,prev:C},y?.(A.element,C),c?c.rebindComposer(A.input):u&&u.then(L=>L?.rebindComposer(A.input))}).catch(b=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",b)})};t.display==="inline"&&w();let k=[],P=new Map;for(let b of o){if(!b.showButton)continue;let A=HC({config:{...t,buttonIconName:b.buttonIconName,buttonTooltipText:b.buttonTooltipText},onOpen:()=>{T().then(C=>C?.openMenu(b.trigger))}});k.push(A),P.set(b.trigger,A.button)}let H=(b,A,C)=>{let L=P.get(A);L&&(L.setAttribute("aria-expanded",b?"true":"false"),b?L.setAttribute("aria-controls",C):L.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(b=>b.wrapper),contextRow:d,handleInput:b=>{if(c){c.handleInput();return}if(!IC(b))return;let A=p,C=A.selectionStart??0;LC(A.value,C,o)&&T().then(L=>L?.handleInput())},handleKeydown:b=>{if(c?.isMenuOpen())return c.handleKeydown(b);if(b.key==="Backspace"&&c?.hasMentions()&&!x){let A=p,C=A.selectionStart===0&&A.selectionEnd===0;if((A.value.length===0||C)&&c.removeLastChip())return b.preventDefault(),!0}return!1},isMenuOpen:()=>c?.isMenuOpen()??!1,hasMentions:()=>c?.hasMentions()??!1,getMentionRefs:()=>c?.getMentionRefs()??[],collectForSubmit:()=>c?.collectForSubmit()??null,takeInlineCommand:async b=>r(b)?(c??await T())?.dispatchInlineCommand(b)??null:null,clear:()=>c?.clear(),prefetch:()=>{ag().catch(()=>{})},onComposerSwap:b=>{y=b,x&&b(x.next,x.prev)},destroy:()=>{c?.destroy(),h?.();for(let b of k)b.wrapper.remove();i&&d.remove()}}}var su="16px",au="transparent",HP=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),lg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:HP,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"}},dg={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"}},cg={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:$o,maxWidth:jc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:su,canvasBackground:au},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function yo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let o=t.split("."),n=e;for(let r of o){if(n==null)return;n=n[r]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?yo(e,n):n}function iu(e){let t={};function o(n,r){for(let[a,i]of Object.entries(n)){let d=`${r}.${a}`;if(typeof i=="string"){let c=yo(e,i);c!==void 0&&(t[d]={path:d,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&o(i,d)}}return o(e.palette,"palette"),o(e.semantic,"semantic"),o(e.components,"components"),t}function ug(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function NC(e,t){let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?o[n]=NC(a,r):o[n]=r}return o}function WP(e,t){return t?NC(e,t):e}function Al(e,t={}){let o={palette:lg,semantic:dg,components:cg},n={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:WP(o.components,e?.components)};if(t.validate!==!1){let r=ug(n);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)n=r.transform(n);return n}var ig=e=>e.trim()==="0"?"0px":e,_C="--persona-",BP=e=>{if(!e)return;let t=e.trim().toLowerCase(),o;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?o=[0,1,2].map(d=>parseInt(i[d]+i[d],16)):(i.length===6||i.length===8)&&(o=[0,2,4].map(d=>parseInt(i.slice(d,d+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let d=i[1].split(/[,/\s]+/).filter(Boolean);d.length>=3&&(o=d.slice(0,3).map(c=>{let u=c.endsWith("%"),p=parseFloat(u?c.slice(0,-1):c);return u?p/100*255:p}))}}if(!o||o.some(i=>!Number.isFinite(i)))return;let[n,r,a]=o.map(i=>{let d=Math.max(0,Math.min(255,i))/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*n+.7152*r+.0722*a},OP=.179,to=(e,t)=>{for(let[o,...n]of t){let r;for(let a of n)if(r=a.charCodeAt(0)===61?a.slice(1):e[_C+a],r!==void 0)break;r!==void 0&&(e[_C+o]=r)}};function lu(e){let t=iu(e),o={};for(let[z,Ve]of Object.entries(t)){let Xe=z.replace(/\./g,"-");o[`--persona-${Xe}`]=Ve.value}to(o,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let n=o["--persona-components-launcher-foreground"];o["--persona-launcher-fg-muted"]=n&&n!==o["--persona-primary"]?`color-mix(in srgb, ${n} 70%, transparent)`:o["--persona-muted"],to(o,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),to(o,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),o["--persona-panel-border"]=o["--persona-components-panel-border"]??`1px solid ${o["--persona-border"]}`,to(o,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),o["--persona-panel-inset"]=o["--persona-components-panel-inset"]??su,o["--persona-panel-canvas-bg"]=o["--persona-components-panel-canvasBackground"]??au,to(o,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),to(o,[["header-bg","components-header-background","surface"]]);let r=o["--persona-header-bg"],a=o["--persona-components-header-foreground"],i=a?`color-mix(in srgb, ${a} 72%, ${r})`:void 0;o["--persona-header-border"]=o["--persona-components-header-border"]??(a?`color-mix(in srgb, ${a} 14%, ${r})`:void 0)??o["--persona-divider"],to(o,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),o["--persona-header-title-fg"]=o["--persona-components-header-title-color"]??o["--persona-components-header-titleForeground"]??a??o["--persona-primary"],o["--persona-header-subtitle-fg"]=o["--persona-components-header-subtitle-color"]??o["--persona-components-header-subtitleForeground"]??i??o["--persona-text-muted"],o["--persona-header-action-icon-fg"]=o["--persona-components-header-actionIconForeground"]??i??o["--persona-muted"],to(o,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let d=e.components?.header;d?.shadow&&(o["--persona-header-shadow"]=d.shadow),d?.borderBottom&&(o["--persona-header-border-bottom"]=d.borderBottom),d?.minHeight&&(o["--persona-header-min-height"]=d.minHeight);let c=o["--persona-components-history-railHeader-background"];c&&(o["--persona-history-rail-header-bg"]=c);let u=o["--persona-components-history-railHeader-border"];u&&(o["--persona-history-rail-header-border"]=u);let p=o["--persona-components-history-railHeader-minHeight"];p&&(o["--persona-history-rail-header-min-height"]=p);for(let[z,Ve]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Xe=o[`--persona-components-history-overlay-${z}`];Xe&&(o[`--persona-history-overlay-${Ve}`]=Xe)}for(let[z,Ve]of[["background","bg"],["borderRadius","radius"]]){let Xe=o[`--persona-components-history-menu-${z}`];Xe&&(o[`--persona-history-menu-${Ve}`]=Xe)}let m=e.components?.history?.motion;if(m){let z=At=>{if(At===void 0)return;let Ie=String(At).trim();return/^\d+(\.\d+)?$/.test(Ie)?`${Ie}ms`:Ie},Ve=z(m.enterDurationMs);Ve!==void 0&&(o["--persona-history-enter-ms"]=Ve);let Xe=z(m.exitDurationMs);Xe!==void 0&&(o["--persona-history-exit-ms"]=Xe),m.enterEasing&&(o["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(o["--persona-history-exit-easing"]=m.exitEasing)}let h=o["--persona-components-history-dangerForeground"];h&&(o["--persona-history-danger-fg"]=h),o["--persona-danger"]=o["--persona-components-history-confirm-dangerBackground"]??o["--persona-palette-colors-error-700"]??"#b42318",o["--persona-danger-fg"]=o["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let z of["scrim","shadow"]){let Ve=o[`--persona-components-history-confirm-${z}`];Ve&&(o[`--persona-history-confirm-${z}`]=Ve)}for(let[z,Ve]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Xe=o[`--persona-components-tooltip-${z}`];Xe&&(o[`--persona-tooltip-${Ve}`]=Xe)}e.components?.tooltip?.arrow===!1&&(o["--persona-tooltip-arrow-display"]="none");for(let[z,Ve]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Xe=o[`--persona-components-messageActions-${z}`];Xe&&(o[`--persona-message-action-${Ve}`]=Xe)}to(o,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=o["--persona-components-introCard-background"],x=o["--persona-components-introCard-shadow"],T=(!y||y==="transparent"||y==="none")&&(!x||x==="none"),w=o["--persona-components-introCard-padding"]??"1.5rem";o["--persona-intro-card-padding"]=T&&w==="1.5rem"?"1.5rem 0":w,to(o,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["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"]]),to(o,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let k=o["--persona-components-markdown-heading-h1-fontSize"];k&&(o["--persona-md-h1-size"]=k);let P=o["--persona-components-markdown-heading-h1-fontWeight"];P&&(o["--persona-md-h1-weight"]=P);let H=o["--persona-components-markdown-heading-h2-fontSize"];H&&(o["--persona-md-h2-size"]=H);let b=o["--persona-components-markdown-heading-h2-fontWeight"];b&&(o["--persona-md-h2-weight"]=b);let A=o["--persona-components-markdown-prose-fontFamily"];A&&A!=="inherit"&&(o["--persona-md-prose-font-family"]=A),to(o,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),to(o,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),to(o,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),to(o,[["md-hr-color","components-markdown-hr-color","divider"]]),to(o,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]),o["--cw-container"]=o["--persona-components-collapsibleWidget-container"]??o["--persona-surface"],o["--cw-surface"]=o["--persona-components-collapsibleWidget-surface"]??o["--persona-surface"],o["--cw-border"]=o["--persona-components-collapsibleWidget-border"]??o["--persona-border"],to(o,[["message-border","components-message-border","border"]]),to(o,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-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 C=e.components,L=C?.iconButton;L&&(L.background&&(o["--persona-icon-btn-bg"]=L.background),L.border&&(o["--persona-icon-btn-border"]=L.border),L.color&&(o["--persona-icon-btn-color"]=L.color),L.padding&&(o["--persona-icon-btn-padding"]=L.padding),L.borderRadius&&(o["--persona-icon-btn-radius"]=L.borderRadius),L.hoverBackground&&(o["--persona-icon-btn-hover-bg"]=L.hoverBackground),L.hoverColor&&(o["--persona-icon-btn-hover-color"]=L.hoverColor),L.activeBackground&&(o["--persona-icon-btn-active-bg"]=L.activeBackground),L.activeBorder&&(o["--persona-icon-btn-active-border"]=L.activeBorder));let U=C?.labelButton;U&&(U.background&&(o["--persona-label-btn-bg"]=U.background),U.border&&(o["--persona-label-btn-border"]=U.border),U.color&&(o["--persona-label-btn-color"]=U.color),U.padding&&(o["--persona-label-btn-padding"]=U.padding),U.borderRadius&&(o["--persona-label-btn-radius"]=U.borderRadius),U.hoverBackground&&(o["--persona-label-btn-hover-bg"]=U.hoverBackground),U.fontSize&&(o["--persona-label-btn-font-size"]=U.fontSize),U.gap&&(o["--persona-label-btn-gap"]=U.gap));let Q=C?.toggleGroup;Q&&(Q.gap&&(o["--persona-toggle-group-gap"]=Q.gap),Q.borderRadius&&(o["--persona-toggle-group-radius"]=Q.borderRadius));let $=C?.artifact;if($?.toolbar){let z=$.toolbar;z.iconHoverColor&&(o["--persona-artifact-toolbar-icon-hover-color"]=z.iconHoverColor),z.iconHoverBackground&&(o["--persona-artifact-toolbar-icon-hover-bg"]=z.iconHoverBackground),z.iconPadding&&(o["--persona-artifact-toolbar-icon-padding"]=z.iconPadding),z.iconBorderRadius&&(o["--persona-artifact-toolbar-icon-radius"]=z.iconBorderRadius),z.iconBorder&&(o["--persona-artifact-toolbar-icon-border"]=z.iconBorder),z.toggleGroupGap&&(o["--persona-artifact-toolbar-toggle-group-gap"]=ig(z.toggleGroupGap)),z.toggleBorderRadius&&(o["--persona-artifact-toolbar-toggle-radius"]=z.toggleBorderRadius),z.toggleGroupPadding&&(o["--persona-artifact-toolbar-toggle-group-padding"]=ig(z.toggleGroupPadding)),z.toggleGroupBorder&&(o["--persona-artifact-toolbar-toggle-group-border"]=z.toggleGroupBorder),z.toggleGroupBorderRadius&&(o["--persona-artifact-toolbar-toggle-group-radius"]=z.toggleGroupBorderRadius),z.toggleGroupBackground&&(o["--persona-artifact-toolbar-toggle-group-bg"]=yo(e,z.toggleGroupBackground)??z.toggleGroupBackground),z.copyBackground&&(o["--persona-artifact-toolbar-copy-bg"]=z.copyBackground),z.copyBorder&&(o["--persona-artifact-toolbar-copy-border"]=z.copyBorder),z.copyColor&&(o["--persona-artifact-toolbar-copy-color"]=z.copyColor),z.copyBorderRadius&&(o["--persona-artifact-toolbar-copy-radius"]=ig(z.copyBorderRadius)),z.copyPadding&&(o["--persona-artifact-toolbar-copy-padding"]=z.copyPadding),z.copyMenuBackground&&(o["--persona-artifact-toolbar-copy-menu-bg"]=z.copyMenuBackground,o["--persona-dropdown-bg"]=o["--persona-dropdown-bg"]??z.copyMenuBackground),z.copyMenuBorder&&(o["--persona-artifact-toolbar-copy-menu-border"]=z.copyMenuBorder,o["--persona-dropdown-border"]=o["--persona-dropdown-border"]??z.copyMenuBorder),z.copyMenuShadow&&(o["--persona-artifact-toolbar-copy-menu-shadow"]=z.copyMenuShadow,o["--persona-dropdown-shadow"]=o["--persona-dropdown-shadow"]??z.copyMenuShadow),z.copyMenuBorderRadius&&(o["--persona-artifact-toolbar-copy-menu-radius"]=z.copyMenuBorderRadius,o["--persona-dropdown-radius"]=o["--persona-dropdown-radius"]??z.copyMenuBorderRadius),z.copyMenuItemHoverBackground&&(o["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=z.copyMenuItemHoverBackground,o["--persona-dropdown-item-hover-bg"]=o["--persona-dropdown-item-hover-bg"]??z.copyMenuItemHoverBackground),z.iconBackground&&(o["--persona-artifact-toolbar-icon-bg"]=z.iconBackground),z.toolbarBorder&&(o["--persona-artifact-toolbar-border"]=z.toolbarBorder)}if($?.tab){let z=$.tab;z.background&&(o["--persona-artifact-tab-bg"]=z.background),z.activeBackground&&(o["--persona-artifact-tab-active-bg"]=z.activeBackground),z.activeBorder&&(o["--persona-artifact-tab-active-border"]=z.activeBorder),z.borderRadius&&(o["--persona-artifact-tab-radius"]=z.borderRadius),z.textColor&&(o["--persona-artifact-tab-color"]=z.textColor),z.hoverBackground&&(o["--persona-artifact-tab-hover-bg"]=z.hoverBackground),z.listBackground&&(o["--persona-artifact-tab-list-bg"]=z.listBackground),z.listBorderColor&&(o["--persona-artifact-tab-list-border-color"]=z.listBorderColor),z.listPadding&&(o["--persona-artifact-tab-list-padding"]=z.listPadding)}if($?.pane){let z=$.pane;if(z.toolbarBackground){let Ve=yo(e,z.toolbarBackground)??z.toolbarBackground;o["--persona-artifact-toolbar-bg"]=Ve}}if($?.card){let z=$.card;z.background&&(o["--persona-artifact-card-bg"]=z.background),z.border&&(o["--persona-artifact-card-border"]=z.border),z.borderRadius&&(o["--persona-artifact-card-radius"]=z.borderRadius),z.hoverBackground&&(o["--persona-artifact-card-hover-bg"]=z.hoverBackground),z.hoverBorderColor&&(o["--persona-artifact-card-hover-border"]=z.hoverBorderColor)}if($?.inline){let z=$.inline;z.background&&(o["--persona-artifact-inline-bg"]=yo(e,z.background)??z.background),z.border&&(o["--persona-artifact-inline-border"]=z.border),z.borderRadius&&(o["--persona-artifact-inline-radius"]=z.borderRadius),z.chromeBackground&&(o["--persona-artifact-inline-chrome-bg"]=yo(e,z.chromeBackground)??z.chromeBackground),z.chromeBorder&&(o["--persona-artifact-inline-chrome-border"]=yo(e,z.chromeBorder)??z.chromeBorder),z.titleColor&&(o["--persona-artifact-inline-title-color"]=yo(e,z.titleColor)??z.titleColor),z.mutedColor&&(o["--persona-artifact-inline-muted-color"]=yo(e,z.mutedColor)??z.mutedColor),z.frameHeight&&(o["--persona-artifact-inline-frame-height"]=z.frameHeight)}let E=C?.code;E&&(E.keywordColor&&(o["--persona-code-keyword-color"]=E.keywordColor),E.stringColor&&(o["--persona-code-string-color"]=E.stringColor),E.commentColor&&(o["--persona-code-comment-color"]=E.commentColor),E.numberColor&&(o["--persona-code-number-color"]=E.numberColor),E.tagColor&&(o["--persona-code-tag-color"]=E.tagColor),E.attrColor&&(o["--persona-code-attr-color"]=E.attrColor),E.propertyColor&&(o["--persona-code-property-color"]=E.propertyColor),E.lineNumberColor&&(o["--persona-code-line-number-color"]=E.lineNumberColor),E.gutterBorderColor&&(o["--persona-code-gutter-border-color"]=E.gutterBorderColor),E.background&&(o["--persona-code-bg"]=yo(e,E.background)??E.background));let B=o["--persona-surface"],D=o["--persona-container"],W=o["--persona-palette-colors-gray-100"]??"#f3f4f6",te=o["--persona-palette-colors-gray-200"]??"#e5e7eb",X=o["--persona-palette-colors-gray-300"]??"#d1d5db",fe=!D||D===B,le=BP(B??o["--persona-background"]),xe=fe&&le!==void 0&&le<OP,Re=xe?"rgba(255, 255, 255, 0.08)":W,He=xe?"rgba(255, 255, 255, 0.12)":te,we=xe?"rgba(255, 255, 255, 0.16)":X,pt=fe?Re:D,ke=fe?He:D;return o["--persona-icon-btn-hover-bg"]=o["--persona-icon-btn-hover-bg"]??pt,o["--persona-icon-btn-active-bg"]=o["--persona-icon-btn-active-bg"]??ke,fe&&(o["--persona-icon-btn-active-border"]=o["--persona-icon-btn-active-border"]??we),o["--persona-label-btn-hover-bg"]=o["--persona-label-btn-hover-bg"]??pt,o["--persona-artifact-tab-hover-bg"]=o["--persona-artifact-tab-hover-bg"]??pt,o["--persona-artifact-card-hover-bg"]=o["--persona-artifact-card-hover-bg"]??pt,o}var FC={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var DP={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"}}},_P={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},UC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ml=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",NP=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ml()},du=e=>NP(e),FP=e=>Al(e),UP=e=>{let t=Ga(_P,e??{})??{};return Al({...t,palette:{...t.palette,colors:{...DP.colors,...t.palette?.colors}}},{validate:!1})},Yr=e=>{let t=du(e),o=UC(e?.theme),n=UC(e?.darkTheme);return t==="dark"?UP(Ga(o??{},n??{})):FP(o)},qP=e=>lu(e),$s=(e,t)=>{let o=Yr(t),n=qP(o);for(let[r,a]of Object.entries(n))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",du(t))},Ya=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let o=new MutationObserver(()=>{e(Ml())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>o.disconnect())}if(typeof window<"u"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Ml());o.addEventListener?(o.addEventListener("change",n),t.push(()=>o.removeEventListener("change",n))):o.addListener&&(o.addListener(n),t.push(()=>o.removeListener(n)))}return()=>{t.forEach(o=>o())}};var Jr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var cu="24px",pg=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Tl=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let o=Number(t[1])/100;return o>0&&o<1?o:null},qC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var $C=null;var fg=()=>{if($C!==null)return $C;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},$P="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",uu=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},pu=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),o=t.pop(),n={key:o,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")n.mod=!0;else if(r==="shift")n.shift=!0;else if(r==="alt"||r==="option")n.alt=!0;else return uu("unknown modifier in",e),null;return!n.mod||n.shift&&n.alt||/^(enter|esc(ape)?)$/.test(o)||!/^([^+\s]|[a-z]{2,12})$/.test(o)?(uu("unsupported",e),null):(o==="space"&&(n.key=" "),n)},VP=e=>$P.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),VC=(e,t)=>{let o=pu(e);if(!o)return"";let n=fg(),r=VP(o.key);if(!t&&n)return`${o.alt?"\u2325":""}${o.shift?"\u21E7":""}\u2318${r}`;let a=[t?n?"Meta":"Control":"Ctrl"];return o.alt&&a.push("Alt"),o.shift&&a.push("Shift"),a.push(r),a.join("+")},fu=e=>VC(e,!1),El=e=>VC(e,!0),jP=(e,t)=>t.key?.toLowerCase()===e.key&&(fg()?t.metaKey:t.ctrlKey)===e.mod&&!(fg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,zP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},jC=e=>{let t=new Map,o=e?.ownerDocument??(typeof document<"u"?document:null),n=(a,i)=>{if((a.scope??"widget")==="page")return!0;if(!e)return!1;let d=i.composedPath?.();return d?.length?d.includes(e):e.contains(i.target)},r=a=>{if(a.isComposing||!t.size)return;let i=a.composedPath?.()[0]??a.target;for(let d of t.values())if(jP(d.parsed,a)&&d.when?.()!==!1&&n(d,a)&&!(!d.allowInInput&&zP(i))){a.preventDefault();try{d.run(a)}catch(c){uu(`${d.id} threw on`,d.combo),console.warn(c)}return}};return o?.addEventListener("keydown",r),{register(a){let i=pu(a.combo);if(!i)return()=>{};let d=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(d);return c?(uu(`${c.id} already owns`,a.combo),()=>{}):(t.set(d,{...a,parsed:i}),a.element?.setAttribute("aria-keyshortcuts",El(a.combo)),()=>{t.get(d)?.id===a.id&&t.delete(d),a.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),o?.removeEventListener("keydown",r)}}};var zC=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:h=>h.getAttribute("im-preserve")==="true",shouldReAppend:h=>h.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function o(h,y,x={}){h=p(h);let T=m(y),w=u(h,T,x),k=r(w,()=>d(w,h,T,P=>P.morphStyle==="innerHTML"?(a(P,h,T),Array.from(h.childNodes)):n(P,h,T)));return w.pantry.remove(),k}function n(h,y,x){let T=m(y);return a(h,T,x,y,y.nextSibling),Array.from(T.childNodes)}function r(h,y){if(!h.config.restoreFocus)return y();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return y();let{id:T,selectionStart:w,selectionEnd:k}=x,P=y();return T&&T!==document.activeElement?.getAttribute("id")&&(x=h.target.querySelector(`[id="${T}"]`),x?.focus()),x&&!x.selectionEnd&&k&&x.setSelectionRange(w,k),P}let a=(function(){function h(b,A,C,L=null,U=null){A instanceof HTMLTemplateElement&&C instanceof HTMLTemplateElement&&(A=A.content,C=C.content),L||(L=A.firstChild);for(let Q of C.childNodes){if(L&&L!=U){let E=x(b,Q,L,U);if(E){E!==L&&w(b,L,E),i(E,Q,b),L=E.nextSibling;continue}}if(Q instanceof Element){let E=Q.getAttribute("id");if(b.persistentIds.has(E)){let B=k(A,E,L,b);i(B,Q,b),L=B.nextSibling;continue}}let $=y(A,Q,L,b);$&&(L=$.nextSibling)}for(;L&&L!=U;){let Q=L;L=L.nextSibling,T(b,Q)}}function y(b,A,C,L){if(L.callbacks.beforeNodeAdded(A)===!1)return null;if(L.idMap.has(A)){let U=document.createElement(A.tagName);return b.insertBefore(U,C),i(U,A,L),L.callbacks.afterNodeAdded(U),U}else{let U=document.importNode(A,!0);return b.insertBefore(U,C),L.callbacks.afterNodeAdded(U),U}}let x=(function(){function b(L,U,Q,$){let E=null,B=U.nextSibling,D=0,W=Q;for(;W&&W!=$;){if(C(W,U)){if(A(L,W,U))return W;E===null&&(L.idMap.has(W)||(E=W))}if(E===null&&B&&C(W,B)&&(D++,B=B.nextSibling,D>=2&&(E=void 0)),L.activeElementAndParents.includes(W))break;W=W.nextSibling}return E||null}function A(L,U,Q){let $=L.idMap.get(U),E=L.idMap.get(Q);if(!E||!$)return!1;for(let B of $)if(E.has(B))return!0;return!1}function C(L,U){let Q=L,$=U;return Q.nodeType===$.nodeType&&Q.tagName===$.tagName&&(!Q.getAttribute?.("id")||Q.getAttribute?.("id")===$.getAttribute?.("id"))}return b})();function T(b,A){if(b.idMap.has(A))H(b.pantry,A,null);else{if(b.callbacks.beforeNodeRemoved(A)===!1)return;A.parentNode?.removeChild(A),b.callbacks.afterNodeRemoved(A)}}function w(b,A,C){let L=A;for(;L&&L!==C;){let U=L;L=L.nextSibling,T(b,U)}return L}function k(b,A,C,L){let U=L.target.getAttribute?.("id")===A&&L.target||L.target.querySelector(`[id="${A}"]`)||L.pantry.querySelector(`[id="${A}"]`);return P(U,L),H(b,U,C),U}function P(b,A){let C=b.getAttribute("id");for(;b=b.parentNode;){let L=A.idMap.get(b);L&&(L.delete(C),L.size||A.idMap.delete(b))}}function H(b,A,C){if(b.moveBefore)try{b.moveBefore(A,C)}catch{b.insertBefore(A,C)}else b.insertBefore(A,C)}return h})(),i=(function(){function h(P,H,b){return b.ignoreActive&&P===document.activeElement?null:(b.callbacks.beforeNodeMorphed(P,H)===!1||(P instanceof HTMLHeadElement&&b.head.ignore||(P instanceof HTMLHeadElement&&b.head.style!=="morph"?c(P,H,b):(y(P,H,b),k(P,b)||a(b,P,H))),b.callbacks.afterNodeMorphed(P,H)),P)}function y(P,H,b){let A=H.nodeType;if(A===1){let C=P,L=H,U=C.attributes,Q=L.attributes;for(let $ of Q)w($.name,C,"update",b)||C.getAttribute($.name)!==$.value&&C.setAttribute($.name,$.value);for(let $=U.length-1;0<=$;$--){let E=U[$];if(E&&!L.hasAttribute(E.name)){if(w(E.name,C,"remove",b))continue;C.removeAttribute(E.name)}}k(C,b)||x(C,L,b)}(A===8||A===3)&&P.nodeValue!==H.nodeValue&&(P.nodeValue=H.nodeValue)}function x(P,H,b){if(P instanceof HTMLInputElement&&H instanceof HTMLInputElement&&H.type!=="file"){let A=H.value,C=P.value;T(P,H,"checked",b),T(P,H,"disabled",b),H.hasAttribute("value")?C!==A&&(w("value",P,"update",b)||(P.setAttribute("value",A),P.value=A)):w("value",P,"remove",b)||(P.value="",P.removeAttribute("value"))}else if(P instanceof HTMLOptionElement&&H instanceof HTMLOptionElement)T(P,H,"selected",b);else if(P instanceof HTMLTextAreaElement&&H instanceof HTMLTextAreaElement){let A=H.value,C=P.value;if(w("value",P,"update",b))return;A!==C&&(P.value=A),P.firstChild&&P.firstChild.nodeValue!==A&&(P.firstChild.nodeValue=A)}}function T(P,H,b,A){let C=H[b],L=P[b];if(C!==L){let U=w(b,P,"update",A);U||(P[b]=H[b]),C?U||P.setAttribute(b,""):w(b,P,"remove",A)||P.removeAttribute(b)}}function w(P,H,b,A){return P==="value"&&A.ignoreActiveValue&&H===document.activeElement?!0:A.callbacks.beforeAttributeUpdated(P,H,b)===!1}function k(P,H){return!!H.ignoreActiveValue&&P===document.activeElement&&P!==document.body}return h})();function d(h,y,x,T){if(h.head.block){let w=y.querySelector("head"),k=x.querySelector("head");if(w&&k){let P=c(w,k,h);return Promise.all(P).then(()=>{let H=Object.assign(h,{head:{block:!1,ignore:!0}});return T(H)})}}return T(h)}function c(h,y,x){let T=[],w=[],k=[],P=[],H=new Map;for(let A of y.children)H.set(A.outerHTML,A);for(let A of h.children){let C=H.has(A.outerHTML),L=x.head.shouldReAppend(A),U=x.head.shouldPreserve(A);C||U?L?w.push(A):(H.delete(A.outerHTML),k.push(A)):x.head.style==="append"?L&&(w.push(A),P.push(A)):x.head.shouldRemove(A)!==!1&&w.push(A)}P.push(...H.values());let b=[];for(let A of P){let C=document.createRange().createContextualFragment(A.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(C)!==!1){if("href"in C&&C.href||"src"in C&&C.src){let L,U=new Promise(function(Q){L=Q});C.addEventListener("load",function(){L()}),b.push(U)}h.appendChild(C),x.callbacks.afterNodeAdded(C),T.push(C)}}for(let A of w)x.callbacks.beforeNodeRemoved(A)!==!1&&(h.removeChild(A),x.callbacks.afterNodeRemoved(A));return x.head.afterHeadMorphed(h,{added:T,kept:k,removed:w}),b}let u=(function(){function h(b,A,C){let{persistentIds:L,idMap:U}=P(b,A),Q=y(C),$=Q.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:b,newContent:A,config:Q,morphStyle:$,ignoreActive:Q.ignoreActive,ignoreActiveValue:Q.ignoreActiveValue,restoreFocus:Q.restoreFocus,idMap:U,persistentIds:L,pantry:x(),activeElementAndParents:T(b),callbacks:Q.callbacks,head:Q.head}}function y(b){let A=Object.assign({},t);return Object.assign(A,b),A.callbacks=Object.assign({},t.callbacks,b.callbacks),A.head=Object.assign({},t.head,b.head),A}function x(){let b=document.createElement("div");return b.hidden=!0,document.body.insertAdjacentElement("afterend",b),b}function T(b){let A=[],C=document.activeElement;if(C?.tagName!=="BODY"&&b.contains(C))for(;C&&(A.push(C),C!==b);)C=C.parentElement;return A}function w(b){let A=Array.from(b.querySelectorAll("[id]"));return b.getAttribute?.("id")&&A.push(b),A}function k(b,A,C,L){for(let U of L){let Q=U.getAttribute("id");if(A.has(Q)){let $=U;for(;$;){let E=b.get($);if(E==null&&(E=new Set,b.set($,E)),E.add(Q),$===C)break;$=$.parentElement}}}}function P(b,A){let C=w(b),L=w(A),U=H(C,L),Q=new Map;k(Q,U,b,C);let $=A.__idiomorphRoot||A;return k(Q,U,$,L),{persistentIds:U,idMap:Q}}function H(b,A){let C=new Set,L=new Map;for(let{id:Q,tagName:$}of b)L.has(Q)?C.add(Q):L.set(Q,$);let U=new Set;for(let{id:Q,tagName:$}of A)U.has(Q)?C.add(Q):L.get(Q)===$&&U.add(Q);for(let Q of C)U.delete(Q);return U}return h})(),{normalizeElement:p,normalizeParent:m}=(function(){let h=new WeakSet;function y(k){return k instanceof Document?k.documentElement:k}function x(k){if(k==null)return document.createElement("div");if(typeof k=="string")return x(w(k));if(h.has(k))return k;if(k instanceof Node){if(k.parentNode)return new T(k);{let P=document.createElement("div");return P.append(k),P}}else{let P=document.createElement("div");for(let H of[...k])P.append(H);return P}}class T{constructor(P){this.originalNode=P,this.realParentNode=P.parentNode,this.previousSibling=P.previousSibling,this.nextSibling=P.nextSibling}get childNodes(){let P=[],H=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;H&&H!=this.nextSibling;)P.push(H),H=H.nextSibling;return P}querySelectorAll(P){return this.childNodes.reduce((H,b)=>{if(b instanceof Element){b.matches(P)&&H.push(b);let A=b.querySelectorAll(P);for(let C=0;C<A.length;C++)H.push(A[C])}return H},[])}insertBefore(P,H){return this.realParentNode.insertBefore(P,H)}moveBefore(P,H){return this.realParentNode.moveBefore(P,H)}get __idiomorphRoot(){return this.originalNode}}function w(k){let P=new DOMParser,H=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(H.match(/<\/html>/)||H.match(/<\/head>/)||H.match(/<\/body>/)){let b=P.parseFromString(k,"text/html");if(H.match(/<\/html>/))return h.add(b),b;{let A=b.firstChild;return A&&h.add(A),A}}else{let A=P.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return h.add(A),A}}return{normalizeElement:y,normalizeParent:x}})();return{morph:o,defaults:t}})();var mu=(e,t,o={})=>{let{preserveTypingAnimation:n=!0}=o;zC.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&n){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let i=r.textContent??"",d=a.textContent??"";if(i!==d)return}return!1}}}}})};var KC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var mg={index:-1,draft:""};function GC(e){let{direction:t,history:o,currentValue:n,atStart:r,state:a}=e,i=a.index!==-1;if(o.length===0)return{handled:!1,state:a};if(t==="up"){if(!i&&!r)return{handled:!1,state:a};if(!i){let d=o.length-1;return{handled:!0,value:o[d],state:{index:d,draft:n}}}if(a.index>0){let d=a.index-1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,state:a}}if(!i)return{handled:!1,state:a};if(a.index<o.length-1){let d=a.index+1;return{handled:!0,value:o[d],state:{index:d,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function XC(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function QC(){return new Map}function YC(e,t,o){let n=e.get(t);return n&&n.fingerprint===o?n.wrapper:null}function JC(e,t,o,n){e.set(t,{fingerprint:o,wrapper:n})}function ZC(e,t){for(let o of e.keys())t.has(o)||e.delete(o)}function eS(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function tS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function jn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Vs(e,t){return jn(e)-e.scrollTop<=t}function oS(e){let{following:t,currentScrollTop:o,lastScrollTop:n,nearBottom:r,userScrollThreshold:a,isAutoScrolling:i=!1,pauseOnUpwardScroll:d=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:u=!1}=e,p=o-n;return i||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:o}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:o}:t&&d&&p<0?{action:"pause",delta:p,nextLastScrollTop:o}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:o}:{action:"none",delta:p,nextLastScrollTop:o}}function nS(e){let{following:t,deltaY:o,nearBottom:n=!1,resumeWhenNearBottom:r=!1}=e;return t&&o<0?"pause":!t&&r&&o>0&&n?"resume":"none"}function rS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function gg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),o=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:o}}function sS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Pl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},KP=["pre","code","a","script","style"],gu=e=>({type:e?.type??Pl.type,placeholder:e?.placeholder??Pl.placeholder,speed:e?.speed??Pl.speed,duration:e?.duration??Pl.duration,buffer:e?.buffer??Pl.buffer}),iS=[{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"}],kl=new Map;for(let e of iS)kl.set(e.name,e);var lS=["wipe","glyph-cycle"],Ja=e=>{kl.set(e.name,e)},bg=e=>{iS.some(t=>t.name===e)||kl.delete(e)},vg=()=>Array.from(kl.keys()),Ll=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:kl.get(e)??null,hu=(e,t,o,n,r)=>{if(!r)return e;if(o?.bufferContent)return o.bufferContent(e,n);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
29
+ `);return a<0?"":e.slice(0,a)}return e},GP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${o}-${n}`,r.style.setProperty("--char-index",String(n)),r.textContent=t,r},XP=(e,t,o,n)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${o}-${n}`,r.style.setProperty("--word-index",String(n)),r.textContent=t,r},hg=/\s/,QP=(e,t)=>{let o=e.parentNode;for(;o;){if(o.nodeType===1){let n=o;if(t.has(n.tagName.toLowerCase()))return!0}o=o.parentNode}return!1},YP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=0;for(;d<a.length;)if(hg.test(a[d])){let c=d;for(;c<a.length&&hg.test(a[c]);)c+=1;i.appendChild(n.createTextNode(a.slice(d,c))),d=c}else{let c=n.createElement("span");c.className="persona-stream-word-group";let u=d;for(;u<a.length&&!hg.test(a[u]);)c.appendChild(GP(n,a[u],t,o.value)),o.value+=1,u+=1;i.appendChild(c),d=u}r.replaceChild(i,e)},JP=(e,t,o)=>{let n=e.ownerDocument,r=e.parentNode;if(!n||!r)return;let a=e.nodeValue??"";if(!a)return;let i=n.createDocumentFragment(),d=a.split(/(\s+)/);for(let c of d)c&&(/^\s+$/.test(c)?i.appendChild(n.createTextNode(c)):(i.appendChild(XP(n,c,t,o.value)),o.value+=1));r.replaceChild(i,e)},Il=(e,t,o,n)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((n?.skipTags??KP).map(m=>m.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),d=[],c=i.nextNode();for(;c;)QP(c,a)||d.push(c),c=i.nextNode();let u={value:n?.startIndex??0},p=t==="char"?YP:JP;for(let m of d)p(m,o,u);return r.innerHTML},yu=(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},Rl=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let o=e.createElement("div");return o.className="persona-stream-skeleton-line",t.appendChild(o),t},aS=new WeakMap,ZP=(e,t)=>{if(!e.styles)return;let o=aS.get(t);if(o||(o=new Set,aS.set(t,o)),o.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;o.delete(e.name)}o.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},yg=new WeakMap,ek=(e,t)=>{if(!e.onAttach)return;let o=yg.get(t);if(o||(o=new Map,yg.set(t,o)),o.has(e.name))return;let n=e.onAttach(t);o.set(e.name,n)},dS=e=>{let t=yg.get(e);if(t){for(let o of t.values())typeof o=="function"&&o();t.clear()}},Hl=(e,t)=>{ZP(e,t),ek(e,t)};var{setLoader:tk,load:ok}=gt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")}),cS=tk,uS=ok;function xg(e,t=ro){let o=e.style.position,n=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),i=a.position==="static"||a.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=o),e.style.zIndex=n,e.style.isolation=r}}var Wl=0,Zr=null;function Cg(e=document){if(Wl++,Wl===1){let o=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Zr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:r},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${r}px`,o.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Wl=Math.max(0,Wl-1),Wl===0&&Zr)){let o=e.body,n=e.defaultView??window;o.style.overflow=Zr.originalOverflow,o.style.position=Zr.originalPosition,o.style.top=Zr.originalTop,o.style.width=Zr.originalWidth,n.scrollTo(0,Zr.scrollY),Zr=null}}}var Bl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ct=e=>(e?.launcher?.mountMode??"floating")==="docked",es=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Io=e=>{let t=e?.launcher?.dock;return{side:t?.side??Bl.side,width:t?.width??Bl.width,animate:t?.animate??Bl.animate,reveal:t?.reveal??Bl.reveal,maxHeight:t?.maxHeight??Bl.maxHeight}};var Sg=e=>e==="followUp"?"follow-up":e,wg=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let o=e.label.trim();if(!o)return null;let n=e.prompt?.trim()||o;return{id:e.id?.trim()||n||`suggestion-${t}`,label:o,prompt:n,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},nk=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},pS=new WeakSet,rk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,sk=e=>{rk()||e.forEach((t,o)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:o*60,easing:"ease-out",fill:"backwards"})})},Ag=e=>{var H,b,A;let{item:t,index:o,surface:n,source:r,variant:a,streaming:i,config:d,plugins:c,chipsConfig:u,session:p,getTextarea:m,eventTarget:h,submitPrompt:y}=e,x=n==="followUp",T=t.behavior,w=()=>{if(p.isStreaming())return;let C={suggestion:{...t},surface:n,source:r,behavior:T},L=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:C,bubbles:!0,composed:!0,cancelable:!0}));if(x&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!L)return;for(let Q of c)if(Q.onSuggestionSelect?.({suggestion:{...t},surface:n,source:r,variant:a,config:d})===!1)return;let U=m();if(T==="fill"){U.value=t.prompt,U.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),U.focus();return}if(y){y(t.prompt);return}U.value="",p.sendMessage(t.prompt)},k=()=>{let C=I("button",`persona-suggestion persona-suggestion--${a}`);if(C.type="button",C.disabled=i,C.dataset.suggestionId=t.id,C.dataset.emphasis=t.emphasis,C.dataset.behavior=T,a==="chip"&&(u?.fontFamily&&(C.style.fontFamily=nk(u.fontFamily)),u?.fontWeight&&(C.style.fontWeight=u.fontWeight),u?.paddingX&&(C.style.paddingLeft=u.paddingX,C.style.paddingRight=u.paddingX),u?.paddingY&&(C.style.paddingTop=u.paddingY,C.style.paddingBottom=u.paddingY)),t.icon){let U=ue(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);U&&(U.classList.add("persona-suggestion__icon"),t.iconColor&&(U.style.color=t.iconColor),C.appendChild(U))}let L=I("span","persona-suggestion__copy");if(L.appendChild(Y("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&L.appendChild(Y("span",{className:"persona-suggestion__description",text:t.description})),C.appendChild(L),a!=="chip"){let U=_t(pl,16,"currentColor",1.8);U&&(U.classList.add("persona-suggestion__arrow"),C.appendChild(U))}return C.addEventListener("click",w),C},P=null;for(let C of c)if(C.renderSuggestion&&(P=C.renderSuggestion({suggestion:{...t},index:o,surface:n,source:r,variant:a,streaming:i,config:d,defaultRenderer:k,select:w}),P))break;return P??(P=k()),(H=P.dataset).suggestionId||(H.suggestionId=t.id),(b=P.dataset).behavior||(b.behavior=T),(A=P.dataset).emphasis||(A.emphasis=t.emphasis),P instanceof HTMLButtonElement||P.setAttribute("aria-disabled",i?"true":"false"),P},Ol=e=>{let t=[],o=[],n=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){a();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),y=4,x=h<=y,T=h>=p-y,w=m?!T:!x,k=m?!x:!T;e.toggleAttribute("data-scroll-left",w),e.toggleAttribute("data-scroll-right",k)},d=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",d,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(d):null;return c?.observe(e),{buttons:t,elements:o,destroy:()=>{e.removeEventListener("scroll",d),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,h,y,x,T)=>{e.replaceChildren(),t.length=0,o.length=0;let w=T?.source??"config",k=T?.surface??(w==="config"?"starter":"followUp"),P=k==="followUp",H=T?.variant??"chip",b=T?.behavior??"send",A=T?.overflow??"wrap",C=T?.config??{},L=T?.plugins??[],U=typeof T?.maxItems=="number"?Math.max(0,Math.floor(T.maxItems)):void 0,Q=P?"followUps":"starters";!pS.has(C)&&C.debug===!0&&H!=="chip"&&C.suggestions?.[Q]?.overflow!==void 0&&(pS.add(C),console.info(`[persona] suggestions.${Q}.overflow applies to the "chip" variant only; the "${H}" variant manages its own stacking.`));let $=X=>X.map(wg).filter(fe=>fe!==null).map(fe=>({...fe,behavior:fe.behavior??b})),E=$(p??[]);L.forEach(X=>{X.transformSuggestions&&(E=$(X.transformSuggestions({suggestions:E.map(fe=>({...fe})),surface:k,source:w,config:C})))});let B=U===void 0?E:E.slice(0,U);if(!B.length){e.hidden=!0,n=null,a();return}if(!P&&(y??m.getMessages()).some(fe=>fe.role==="user")){e.hidden=!0,n=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Sg(k),e.dataset.variant=H,e.dataset.overflow=A;let D=document.createDocumentFragment(),W=m.isStreaming();B.forEach((X,fe)=>{let le=Ag({item:X,index:fe,surface:k,source:w,variant:H,streaming:W,config:C,plugins:L,chipsConfig:x,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:T?.submitPrompt});D.appendChild(le),o.push(le),[...le instanceof HTMLButtonElement?[le]:[],...Array.from(le.querySelectorAll("button"))].forEach(Re=>{t.includes(Re)||(Re.disabled=W,t.push(Re))})}),e.appendChild(D),i(),d();let te=JSON.stringify({normalized:B,surface:k,variant:H,source:w});te!==n&&(n=te,sk(o),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map(X=>({...X})),surface:k,source:w,variant:H},bubbles:!0,composed:!0})),P&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map(X=>X.prompt)},bubbles:!0,composed:!0})))}}};var jo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var ak="persona-header-control",ik="persona-header-control--glyph",lk="persona-header-control--sparse",dk=20,ck={x:[1.4,1.05]},fS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",uk="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bu=(e,t,o={})=>{let{iconSize:n,iconText:r}=o,[a,i]=ck[t]??[1,1.5],d=!n;e.classList.toggle(ik,d),e.classList.toggle(lk,d&&a!==1);let c=parseFloat(n??"")||dk,u=ue(t,`${Math.round(c*a)}px`,"currentColor",i);u?(u.style.display="block",d||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},js=e=>{let{ariaLabel:t,tooltip:o=!0,tooltipHint:n,iconName:r,iconText:a,wrapperClassName:i=fS,size:d,iconSize:c,color:u,backgroundColor:p,borderWidth:m,borderColor:h,borderRadius:y,paddingX:x,paddingY:T,hidden:w,extraClassName:k,attrs:P}=e,H=I("div",i),b=!!(m||h),A=Y("button",{className:go(ak,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!b&&"persona-border-none",!y&&"persona-rounded-full",k),attrs:{type:"button","aria-label":t,...P},style:{width:d,height:d,minWidth:d,minHeight:d,display:w?"none":void 0,color:u||bo.actionIconColor,backgroundColor:p,border:b?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:x,paddingRight:x,paddingTop:T,paddingBottom:T}});return r?bu(A,r,{iconSize:c,iconText:a}):a&&(A.textContent=a),H.appendChild(A),eo({anchor:A,trigger:H,text:()=>A.getAttribute("aria-label")??t,hint:n,enabled:o}),{button:A,wrapper:H}},Za=(e,t={})=>{let{showClose:o=!0,wrapperClassName:n=fS,buttonSize:r,iconSize:a}=t,i=e?.launcher??{},d=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=js({ariaLabel:d,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:n,size:r??i.closeButtonSize,iconSize:a,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!o});return{button:u,wrapper:p}},ei=(e,t={})=>{let{wrapperClassName:o=uk,buttonSize:n,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},d=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:u,wrapper:p}=js({ariaLabel:d,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:o,size:n??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var bo={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Mg={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)"},pk={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)"},yr=e=>{let{config:t,showClose:o=!0}=e,n=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:bo.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},a=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",d=r.headerIconHidden??!1,c=r.headerIconName,u=Y("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!d)if(c){let A=parseFloat(a)||24,C=ue(c,A*.6,"currentColor",1);C?u.replaceChildren(C):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let A=I("img");A.src=t.launcher.iconUrl,A.alt="",A.className="persona-rounded-xl persona-object-cover",A.style.height=a,A.style.width=a,u.replaceChildren(A)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=I("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Y("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:bo.titleColor,...Mg}}),h=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:bo.subtitleColor,...pk}});p.append(m,h),d?n.append(p):n.append(u,p);let y=r.clearChat??{},x=y.enabled??!0,T=y.placement??"inline",w=null,k=null;if(x){let C=ei(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=C.button,k=C.wrapper,T==="top-right"&&(k.style.right="48px"),T==="inline"&&n.appendChild(k)}let P=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&T==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:b}=Za(t,{showClose:o,wrapperClassName:P});return i!=="top-right"&&n.appendChild(b),{header:n,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:H,closeButtonWrapper:b,clearChatButton:w,clearChatButtonWrapper:k}},zs=(e,t,o)=>{let n=o?.launcher??{},r=n.closeButtonPlacement??"inline",a=n.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Ks(e){let{items:t,onSelect:o,anchor:n,position:r="bottom-left",portal:a,onOpenChange:i}=e,d=I("div","persona-dropdown-menu persona-hidden");d.setAttribute("role","menu"),d.setAttribute("data-persona-theme-zone","dropdown"),a?(d.style.position="fixed",d.style.zIndex=String(Ka)):(d.style.position="absolute",d.style.top="100%",d.style.marginTop="4px",r==="bottom-right"?d.style.right="0":d.style.left="0");for(let x of t){if(x.dividerBefore){let k=document.createElement("hr");d.appendChild(k)}let T=document.createElement("button");if(T.type="button",T.setAttribute("role","menuitem"),T.setAttribute("data-dropdown-item-id",x.id),x.destructive&&T.setAttribute("data-destructive",""),x.icon){let k=ue(x.icon,16,"currentColor",1.5);k&&T.appendChild(k)}let w=document.createElement("span");w.textContent=x.label,T.appendChild(w),T.addEventListener("click",k=>{k.stopPropagation(),m(),o(x.id)}),d.appendChild(T)}let c=null;function u(){if(!a)return;let x=n.getBoundingClientRect();d.style.top=`${x.bottom+4}px`,r==="bottom-right"?(d.style.right=`${window.innerWidth-x.right}px`,d.style.left="auto"):(d.style.left=`${x.left}px`,d.style.right="auto")}function p(){let x=d.classList.contains("persona-hidden");u(),d.classList.remove("persona-hidden"),x&&i?.(!0),requestAnimationFrame(()=>{let T=w=>{!d.contains(w.target)&&!n.contains(w.target)&&m()};document.addEventListener("click",T,!0),c=()=>document.removeEventListener("click",T,!0)})}function m(){let x=!d.classList.contains("persona-hidden");d.classList.add("persona-hidden"),c?.(),c=null,x&&i?.(!1)}function h(){d.classList.contains("persona-hidden")?p():m()}function y(){m(),d.remove()}return a&&a.appendChild(d),{element:d,show:p,hide:m,toggle:h,destroy:y}}function Gs(e){let{icon:t,label:o,size:n,strokeWidth:r,className:a,chromeless:i,onClick:d,aria:c}=e,u=I("button",go(!i&&"persona-icon-btn",a));u.type="button",u.setAttribute("aria-label",o),u.title=o;let p=ue(t,n??16,"currentColor",r??2);if(p&&u.appendChild(p),d&&u.addEventListener("click",d),c)for(let[m,h]of Object.entries(c))u.setAttribute(m,h);return u}function Tg(e){let{icon:t,label:o,variant:n="default",size:r="sm",iconSize:a,className:i,onClick:d,aria:c}=e,u="persona-label-btn";n!=="default"&&(u+=" persona-label-btn--"+n),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=I("button",u);if(p.type="button",p.setAttribute("aria-label",o),t){let h=ue(t,a??14,"currentColor",2);h&&p.appendChild(h)}let m=I("span");if(m.textContent=o,p.appendChild(m),d&&p.addEventListener("click",d),c)for(let[h,y]of Object.entries(c))p.setAttribute(h,y);return p}function mS(e){let{items:t,selectedId:o,onSelect:n,className:r}=e,a=I("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let i=o,d=[];function c(){for(let p of d)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let m;p.icon?m=Gs({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),n(p.id)}}):(m=I("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{i=p.id,c(),n(p.id)})),m.setAttribute("aria-pressed",p.id===i?"true":"false"),d.push({id:p.id,btn:m}),a.appendChild(m)}function u(p){i=p,c()}return{element:a,setSelected:u}}function gS(e){let{label:t,icon:o,iconSize:n,iconOnly:r,menuItems:a,onSelect:i,onPrimary:d,position:c="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:x}=e,T=I("div","persona-split-btn"+(h?" "+h:"")),w={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:d},k=r&&o?Gs({...w,icon:o,size:n??14}):Tg({...w,icon:o,iconSize:n??14}),P=Gs({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(x?" "+x:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});T.append(k,P);let H=null,b=()=>{if(H)return H;let A=(typeof u=="function"?u():u)??void 0;return H=Ks({items:a,onSelect:i,anchor:T,position:c,portal:A,onOpenChange:C=>{P.setAttribute("aria-expanded",C?"true":"false")}}),A||T.appendChild(H.element),H};return T.isConnected?b():requestAnimationFrame(()=>{H||b()}),P.addEventListener("click",A=>{A.stopPropagation(),b().toggle()}),{element:T,primaryButton:k,chevronButton:P,openMenu:()=>b().show(),closeMenu:()=>H?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{H?.destroy(),T.remove()}}}function vu(e){let{label:t,icon:o="chevron-down",menuItems:n,onSelect:r,position:a="bottom-left",portal:i,className:d,hover:c}=e,u=I("div","persona-combo-btn"+(d?" "+d:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=I("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let m=ue(o,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",u.appendChild(m)),c&&(u.style.borderRadius=c.borderRadius??"10px",u.style.padding=c.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=c.background??"",u.style.borderColor=c.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let h=Ks({items:n,onSelect:x=>{u.setAttribute("aria-expanded","false"),r(x)},anchor:u,position:a,portal:i});i||u.appendChild(h.element);let y=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",x=>{if(x.stopPropagation(),y())return;let T=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",T?"false":"true"),h.toggle()}),u.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),u.click())}),{element:u,setLabel:x=>{p.textContent=x,u.setAttribute("aria-label",x)},open:()=>{u.setAttribute("aria-expanded","true"),h.show()},close:()=>{u.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let x=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",x?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),u.remove()}}}var Eg=e=>{let t=yr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),o=e.layoutHeaderConfig?.onTitleClick;if(o){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>o()),n.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),o())}))}return t};function fk(e,t,o){if(t?.length)for(let n of t){let{button:r,wrapper:a}=js({ariaLabel:n.ariaLabel??n.label??n.id,iconName:n.icon,iconText:n.icon?void 0:n.label,tooltipHint:n.shortcut?fu(n.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",n.id),n.shortcut){let i=El(n.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(n.menuItems?.length){let i=Ks({items:n.menuItems,onSelect:d=>o?.(d),anchor:a,position:"bottom-right"});a.appendChild(i.element),r.addEventListener("click",d=>{d.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>o?.(n.id));e.appendChild(a)}}var Pg=e=>{let{config:t,showClose:o=!0,onClose:n,layoutHeaderConfig:r,onHeaderAction:a}=e,i=t?.launcher??{},d=I("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");d.setAttribute("data-persona-theme-zone","header"),d.style.minHeight=bo.minHeight,d.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",d.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",d.style.boxShadow="var(--persona-header-shadow, none)",d.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,u,p;if(c){let b=vu({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:A=>{let C=U=>{U===!1&&b.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:A}}))},L=c.onSelect(A);L instanceof Promise?L.then(C,()=>{}):C(L)},hover:c.hover,className:""});u=b.element,u.style.color=bo.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=I("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=I("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=bo.titleColor,Object.assign(p.style,Mg),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let A=r.onTitleClick;u.addEventListener("click",C=>{C.target.closest("button")||A()}),u.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),A())})}let b=r?.titleRowHover;b&&(u.style.borderRadius=b.borderRadius??"10px",u.style.padding=b.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=b.background??"",u.style.borderColor=b.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}d.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=Za(t,{showClose:o,wrapperClassName:m});n&&h.addEventListener("click",n);let x=I("div","persona-flex persona-items-center persona-gap-1");c||fk(x,r?.trailingActions,r?.onAction??a);let T=i.clearChat??{},w=null,k=null;if(T.enabled??!0){let b=T.placement??"inline",A=ei(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});w=A.button,k=A.wrapper,b==="top-right"?k.style.right="48px":x.appendChild(k)}x.appendChild(y),d.appendChild(x);let P=I("div");P.style.display="none";let H=I("span");return H.style.display="none",{header:d,iconHolder:P,headerTitle:p,headerSubtitle:H,closeButton:h,closeButtonWrapper:y,clearChatButton:w,clearChatButtonWrapper:k}},xu={default:Eg,minimal:Pg},kg=e=>xu[e]??xu.default,ti=(e,t,o)=>{if(t?.render){let i=t.render({config:e,onClose:o?.onClose,onClearChat:o?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),d=I("div");d.style.display="none";let c=I("span"),u=I("span"),p=I("button");p.style.display="none";let m=I("div");return m.style.display="none",{header:i,iconHolder:d,headerTitle:c,headerSubtitle:u,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let n=t?.layout??"default",a=kg(n)({config:e,showClose:t?.showCloseButton??o?.showClose??!0,onClose:o?.onClose,onClearChat:o?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Xs=e=>{let{config:t}=e,o=Y("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=eu(),r=Y("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:i}=Qc(t);i();let d=Yc(t),c=Qa(t),u=Jc(t),p=Zc(t),m=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),r.append(u.input)),r.append(a);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),x=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return u&&y.append(u.wrapper),c&&x.append(c.wrapper),x.append(d.wrapper),h.append(y,x),r.append(h),r.addEventListener("click",T=>{T.target!==d.button&&T.target!==d.wrapper&&T.target!==c?.button&&T.target!==c?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&a.focus()}),o.append(n,r,p),{footer:o,suggestions:n,composerForm:r,header:m,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:x,setSendButtonMode:d.setMode}};var hS=()=>{let e=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=I("span","persona-pill-peek__icon"),o=_t(yl,16,"currentColor",1.5);o&&t.appendChild(o);let n=I("span","persona-pill-peek__text"),r=I("span","persona-pill-peek__caret"),a=_t(Fs,16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,n,r),{root:e,textNode:n}},Cu=e=>{let{config:t}=e,o=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),n=eu(),r=Zc(t);r.style.display="none";let{textarea:a,attachAutoResize:i}=Qc(t,{defaultMaxLines:5});i();let d=Yc(t),c=Qa(t),u=Jc(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&h.append(c.wrapper),h.append(d.wrapper),p.addEventListener("click",T=>{T.target!==d.button&&T.target!==d.wrapper&&T.target!==c?.button&&T.target!==c?.wrapper&&T.target!==u?.button&&T.target!==u?.wrapper&&a.focus()}),u&&p.append(u.input),p.append(m,a,h);let y=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});o.append(y),u&&y.append(u.previewsContainer),o.append(n,p,r);let x=p;return{footer:o,suggestions:n,composerForm:p,header:y,textarea:a,sendButton:d.button,sendButtonWrapper:d.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:x,leftActions:m,rightActions:h,setSendButtonMode:d.setMode}};var mk=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},gk=(e,t)=>{if(!e)return null;let o=mk(e);if(o===null)return null;let n=t?.[e],r=n!==void 0?n:o;return r||null},hk=(e,t)=>{let o=I("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return o.setAttribute("data-stop-reason",e),o.setAttribute("role","note"),o.style.opacity="0.75",o.textContent=t,o},yk=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ig=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Rg=320,CS=320,bk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),vk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),xk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ck=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Sk=e=>{if(!e||e.length===0)return null;let t=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let o of e){let n=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:o.label}}),r=I("span","persona-mention-chip-icon"),a=ue(o.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),n.appendChild(r),n.appendChild(Y("span",{className:"persona-mention-chip-label",text:o.label})),t.appendChild(n)}return t},wk=(e,t)=>{let o=document.createDocumentFragment();for(let n of e){if(n.kind==="text"){o.appendChild(document.createTextNode(n.text));continue}o.appendChild(wl(n.ref,{readonly:!0,render:t}))}return o},yS="\uE000",bS="\uE001",Ak=(e,t,o,n)=>{let r=Math.random().toString(36).slice(2,8),a=h=>`${yS}${r}:${h}${bS}`,i=t.map((h,y)=>h.kind==="text"?h.text:a(y)).join(""),d=o(i);if(!t.every((h,y)=>h.kind==="text"||d.includes(a(y)))){e.replaceChildren(wk(t,n));return}e.innerHTML=d;let u=new RegExp(`${yS}${r}:(\\d+)${bS}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=p.nextNode();h;h=p.nextNode())m.push(h);for(let h of m){let y=h;for(let x=u.exec(y.data);x;x=u.exec(y.data)){let T=t[Number(x[1])],w=y.splitText(x.index);w.data=w.data.slice(x[0].length),T?.kind==="mention"&&w.parentNode?.insertBefore(wl(T.ref,{readonly:!0,render:n}),w),y=w}}},Mk=(e,t,o)=>{if(e.length===0)return null;try{let n=I("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),t&&(n.style.marginBottom="8px");let r=0,a=!1,i=()=>{a||(a=!0,n.remove(),o?.())};return e.forEach((d,c)=>{let u=I("img");u.alt=d.alt?.trim()||`Attached image ${c+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Rg}px`,u.style.maxHeight=`${CS}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),yk(d.image)?(u.src=d.image,n.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):n}catch{return o?.(),null}},Tk=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let o=0;return e.forEach(n=>{if(!Ig(n.audio))return;let r=I("audio");r.controls=!0,r.preload="metadata",r.src=n.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Rg}px`,t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Ek=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let o=0;return e.forEach(n=>{if(!Ig(n.video))return;let r=I("video");r.controls=!0,r.preload="metadata",r.src=n.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Rg}px`,r.style.maxHeight=`${CS}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Pk=e=>{if(e.length===0)return null;try{let t=I("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let o=0;return e.forEach(n=>{if(!Ig(n.data))return;let r=I("a");r.href=n.data,r.download=n.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=n.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),o+=1}),o===0?(t.remove(),null):t}catch{return null}},Qs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(o),e.appendChild(n),e.appendChild(r),e},Hg=(e,t,o)=>{let n={config:o??{},streaming:!0,location:e,defaultRenderer:Qs};if(t){let r=t(n);if(r!==null)return r}return Qs()},kk=(e,t)=>{let o=I("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),n=t==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let r=I("img");r.src=n,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",o.appendChild(r)}else o.textContent=n,o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else o.textContent=t==="user"?"U":"A",o.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return o},vS=(e,t,o="div")=>{let n=I(o,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Dl=(e,t="bubble")=>{let o=["persona-message-bubble"];switch(t){case"flat":e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):o.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":o.push("persona-text-sm","persona-leading-relaxed"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:o.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?o.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):o.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return o},xS={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"}},Lk=(e,t,o="bubble",n)=>{if(!n)return;let r=t==="user"?"user":"assistant",a=xS[o??"bubble"]??xS.bubble;n.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${a.padding})`),n.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${a.fontSize})`),n.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${a.lineHeight})`),n.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Su="custom:",Ik=e=>`${Su}${e}`,SS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(o=>(o.roles??["assistant"]).includes(t)),Wg=(e,t,o,n)=>{let r=t.showCopy??!0,a=t.showUpvote??!0,i=t.showDownvote??!0,d=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&n?.canRegenerate===!0,u=(t.showEdit??!1)&&n?.canEdit===!0,p=(t.showQuote??!1)&&n?.canQuote!==!1,m=SS(t,e.role);if(!r&&!a&&!i&&!d&&!c&&!u&&!p&&m.length===0){let H=I("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let h=t.visibility??"hover",y=t.align??"right",x=t.layout??"pill-inside",T={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],w={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[x],k=I("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${T} ${w} ${h==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let P=(H,b,A)=>{let C=Gs({icon:H,label:b,size:14,className:"persona-message-action-btn",chromeless:!0});return C.setAttribute("data-action",A),C};r&&k.appendChild(P("copy","Copy message","copy")),d&&k.appendChild(P("volume-2","Read aloud","read-aloud")),a&&k.appendChild(P("thumbs-up","Upvote","upvote")),i&&k.appendChild(P("thumbs-down","Downvote","downvote")),c&&k.appendChild(P("refresh-cw","Regenerate response","regenerate")),u&&k.appendChild(P("pencil","Edit message","edit")),p&&k.appendChild(P("quote","Quote message","quote"));for(let H of m)k.appendChild(P(H.iconName??"ellipsis",H.label,Ik(H.id)));return k},oi=(e,t,o,n,r,a)=>{let i=o??{},d=i.layout??"bubble",c=i.avatar,u=i.timestamp,p=c?.show??!1,m=u?.show??!1,h=c?.position??"left",y=u?.position??"below",x=Dl(e.role,d),T=I("div",x.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let w=a?.widgetConfig?.theme?.components?.message;Lk(T,e.role,d,e.role==="user"?w?.user:w?.assistant),d==="flat"?(T.style.backgroundColor="transparent",T.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=bk(e),P=e.content?.trim()??"",b=k.length>0&&P===Na,A=gu(a?.widgetConfig?.features?.streamAnimation),C=a?.widgetConfig?.features?.streamAnimation?.plugins,L=e.role==="assistant"&&A.type!=="none"?Ll(A.type,C):null,U=e.role==="assistant"&&L?.isAnimating?.(e)===!0,Q=e.role==="assistant"&&L!==null&&(!!e.streaming||U);Q&&L?.bubbleClass&&T.classList.add(L.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),e.streaming&&$.classList.add("persona-content-streaming"),Q&&L&&(L.containerClass&&$.classList.add(L.containerClass),$.style.setProperty("--persona-stream-step",`${A.speed}ms`),$.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let E=Q?hu(e.content??"",A.buffer,L,e,!!e.streaming):e.content??"",B=()=>{let ke=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return Q&&L?.wrap==="char"?Il(ke,"char",e.id,{skipTags:L.skipTags}):Q&&L?.wrap==="word"?Il(ke,"word",e.id,{skipTags:L.skipTags}):ke},D=null;if(b?(D=document.createElement("div"),D.innerHTML=B(),D.style.display="none",$.appendChild(D)):e.contentSegments?.length?Ak($,e.contentSegments,ke=>t({text:ke,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):$.innerHTML=B(),Q&&L?.useCaret&&!b&&P){let ke=yu(),z=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ve=z[z.length-1];if(Ve?.parentNode)Ve.parentNode.insertBefore(ke,Ve.nextSibling);else{let Xe=$.lastElementChild;Xe?Xe.appendChild(ke):$.appendChild(ke)}}if(m&&y==="inline"&&e.createdAt){let ke=vS(e,u,"span");ke.classList.add("persona-timestamp-inline");let z=$.lastElementChild;z?z.appendChild(ke):$.appendChild(ke)}if(k.length>0){let ke=Mk(k,!b&&!!P,()=>{b&&D&&(D.style.display="")});ke?T.appendChild(ke):b&&D&&(D.style.display="")}let W=vk(e);if(W.length>0){let ke=Tk(W);ke&&T.appendChild(ke)}let te=xk(e);if(te.length>0){let ke=Ek(te);ke&&T.appendChild(ke)}let X=Ck(e);if(X.length>0){let ke=Pk(X);ke&&T.appendChild(ke)}let fe=e.contentSegments?.length?null:Sk(e.contextMentions);if(fe&&T.appendChild(fe),T.appendChild($),m&&y==="below"&&e.createdAt){let ke=vS(e,u);ke.classList.add("persona-mt-1"),T.appendChild(ke)}let le=e.role==="assistant"?gk(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ke=!!(E&&E.trim()),z=A.placeholder==="skeleton",Ve=z&&A.buffer==="line"&&ke;if(ke)Ve&&T.appendChild(Rl());else if(z)T.appendChild(Rl());else{let Xe=Hg("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Xe&&T.appendChild(Xe)}}le&&e.stopReason&&!e.streaming&&(P||($.style.display="none"),T.appendChild(hk(e.stopReason,le)));let xe=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&n?.enabled!==!1,Re=a?.actionEligibility,He=e.role==="user"&&!e.streaming&&n?.enabled!==!1&&(n?.showEdit===!0&&Re?.canEdit===!0||n?.showQuote===!0&&Re?.canQuote===!0||SS(n,"user").length>0);if((xe||He)&&n){let ke=Wg(e,He?{...n,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:n,r,Re);T.appendChild(ke)}if(!p||e.role==="system")return T;let we=I("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),pt=kk(c,e.role);return h==="right"||h==="left"&&e.role==="user"?we.append(T,pt):we.append(pt,T),we},wS=(e,t,o,n,r,a)=>{let i=o??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):oi(e,t,o,n,r,a)};var Rk=40,Hk=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let o=null;try{o=t()}catch(n){console.warn("[persona] welcome.icon renderer threw",n)}if(!o){e.hidden=!0;return}e.appendChild(o),e.hidden=!1;return}if(t.type==="lucide"){let o=ue(t.name,Rk);if(!o){e.hidden=!0;return}e.appendChild(o)}else t.type==="image"?e.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Y("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},AS=(e,t,o={})=>{let n=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});n.hidden=!0;let r=I("p","persona-welcome-kicker");r.hidden=!0;let a=I("h2","persona-welcome-title"),i=I("p","persona-welcome-subtitle"),d=Y("div",{className:"persona-welcome-head-text"},r,a),c=Y("div",{className:"persona-welcome-title-row"},n,d);return{host:Y("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:o.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,i,t),iconHolder:n,kicker:r,title:a,subtitle:i,starterSuggestions:t}},ni=(e,t,o)=>{t.hidden=!o,t.style.display=o?"":"none",e.classList.toggle("persona-gap-6",o),e.classList.toggle("persona-gap-3",!o)},Au=(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==="",Hk(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-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},Wk="data-persona-welcome-plugin",MS="data-persona-welcome-overlay",wu="persona-welcome-overlay-active",Bg=new WeakMap,Og=(e,t,o)=>{o.setAttribute(Wk,""),t.appendChild(o),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(MS,""),e.classList.contains(wu)||(Bg.set(e,e.scrollTop),e.classList.add(wu),e.scrollTop=0)},Dg=(e,t,o)=>{o&&o!==t&&o.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(MS),e.classList.contains(wu)&&(e.classList.remove(wu),e.scrollTop=Bg.get(e)??e.scrollTop,Bg.delete(e))},TS=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Mu=(e,t,o)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let n=o?.layout?.messages?.layout??"bubble",r=Y("div",{className:Dl("assistant",n).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:n==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Y("div",{className:"persona-flex"},r)),e.hidden=!1},ES=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,PS=(e,t)=>{if(ES()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let o=e.getBoundingClientRect(),n=e.parentElement,r=0,a=0,i=0;if(n){let x=getComputedStyle(n);r=parseFloat(x.rowGap)||0;let T=e.previousElementSibling,w=e.nextElementSibling,P=n.getBoundingClientRect().top+(parseFloat(x.borderTopWidth)||0)+(parseFloat(x.paddingTop)||0)-n.scrollTop;a=Math.max(0,T?o.top-T.getBoundingClientRect().bottom-r:o.top-P),i=Math.max(0,w?w.getBoundingClientRect().top-o.bottom-r:0)}let d=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),u=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${o.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${a}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=d,t(m))};return m.finished.then(y).catch(y),m},kS=(e,t,o)=>{if(t<=1||ES()||typeof e.animate!="function"||!e.isConnected)return null;let n=o==="drop"?-t:t;return e.animate([{transform:`translateY(${n}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var Bk="Hello \u{1F44B}",Ok="I can answer questions and help you get things done here.",LS=new WeakSet,vo=(e,t)=>!!e&&e[t]!==void 0,Dk=(e,t)=>{!e||e.debug!==!0||!t.length||LS.has(e)||(LS.add(e),t.forEach(o=>console.warn(`[persona] ${o}`)))},bn=e=>{let t=e?.welcome,o=e?.copy,n=vo(t,"variant")?t.variant:o?.showWelcomeCard===!1?"none":"card",r=n==="hero"?"on-first-message":vo(t,"dismiss")?t.dismiss:"never",a=[];vo(t,"title")&&vo(o,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),vo(t,"subtitle")&&vo(o,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),vo(t,"variant")&&vo(o,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),n==="hero"&&vo(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),n==="hero"&&vo(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let i=t?.anchor==="center"?"center":"bottom",d=Tl(t?.anchorComposerTop)!==null;return vo(t,"anchorComposerTop")&&!d&&a.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),i!=="center"&&(vo(t,"anchorComposerTop")||vo(t,"composerGap"))&&a.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),Dk(e,a),{title:vo(t,"title")?t.title:o?.welcomeTitle??Bk,kicker:t?.kicker??"",subtitle:vo(t,"subtitle")?t.subtitle:o?.welcomeSubtitle??Ok,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:n,dismiss:r,message:n==="hero"?void 0:t?.message,anchor:i,anchorComposerTop:d?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||cu}},IS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",ts=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(o=>o.role==="user");var RS="16px",Ng="10px",Fg="14px",HS=e=>{let t=e?.launcher?.enabled??!0,o=Ct(e);if(es(e)){let p=e?.launcher?.composerBar??{},m=I("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??ro);let h=I("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");h.style.width="100%",m.appendChild(h);let y=I("div","persona-widget-pill-root");return y.setAttribute("data-persona-composer-bar",""),y.dataset.state="collapsed",y.dataset.expandedSize=p.expandedSize??"anchored",y.style.zIndex=String(e?.launcher?.zIndex??ro),{wrapper:m,panel:h,pillRoot:y}}if(o){let p=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=I("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(m),{wrapper:p,panel:m}}if(!t){let p=I("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=I("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=e?.launcher?.width??"100%";return p.style.width=h,m.style.width="100%",p.appendChild(m),{wrapper:p,panel:m}}let r=e?.launcher??{},a=r.position&&jo[r.position]?jo[r.position]:jo["bottom-right"],i=I("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??ro);let d=I("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??$o;return d.style.width=u,d.style.maxWidth=u,i.appendChild(d),{wrapper:i,panel:d}},Ug=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Sg(e)}});return t.hidden=!0,t},WS=(e,t)=>{let o=Ug("starter"),n=AS(e,o,{flatShadow:Ct(e)}),r=bn(e);Au(n,r),ni(t,n.host,ts(r,e?.initialMessages));let a=TS();return Mu(a,r.message,e),{welcome:n,greetingHost:a}},_k=(e,t)=>{let o=I("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");o.setAttribute("data-persona-theme-zone","container");let{button:n,wrapper:r}=Za(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:RS,iconSize:Ng});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,i=null,d=null;if(a){let L=ei(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:RS,iconSize:Fg});i=L.button,d=L.wrapper,d.style.position="absolute",d.style.top="8px",d.style.right="32px",d.style.zIndex="10"}let c=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=Y("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=WS(e,u),{host:h,title:y,subtitle:x}=p,T=p.starterSuggestions,w=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=Ug("followUp"),P=Jr(e,!0);P&&(w.style.maxWidth=P,w.style.marginLeft="auto",w.style.marginRight="auto",w.style.width="100%"),u.append(h,m,w,k);let H=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),b=Cu({config:e}),{root:A,textNode:C}=hS();return o.append(c,r,u,H),d&&o.appendChild(d),{container:o,body:u,messagesWrapper:w,starterSuggestions:T,transcriptSuggestions:k,composerOverlay:H,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:h,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:y,introSubtitle:x,closeButton:n,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:d,iconHolder:I("span"),headerTitle:I("span"),headerSubtitle:I("span"),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:A,peekTextNode:C}},BS=(e,t=!0)=>{if(es(e))return _k(e,t);let o=Y("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),n=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=n?ti(e,n,{showClose:t}):yr({config:e,showClose:t}),i=Y("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:c}=WS(e,i),{host:u,title:p,subtitle:m}=d,h=d.starterSuggestions,y=I("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=Ug("followUp"),T=Jr(e,!1);T&&(y.style.maxWidth=T,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),i.append(u,c,y,x);let w=Xs({config:e}),k=e?.layout?.showFooter!==!1;r?zs(o,a,e):(a.header.style.display="none",zs(o,a,e)),o.append(i);let P=Y("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 k||(w.footer.style.display="none"),o.append(w.footer),o.append(P),{container:o,body:i,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:x,composerOverlay:P,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,welcomeHost:u,welcomeIconHolder:d.iconHolder,greetingHost:c,introKicker:d.kicker,introTitle:p,introSubtitle:m,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode}};var qg=(e,t)=>{let o=I("button");o.type="button",o.innerHTML=`
30
30
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
31
31
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
32
32
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -34,14 +34,14 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
34
34
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
35
35
  </span>
36
36
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
37
- `,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=St(a),c=o.querySelector("[data-role='launcher-title']");if(c){let R=i.title??"Chat Assistant";c.textContent=R,c.setAttribute("title",R)}let u=o.querySelector("[data-role='launcher-subtitle']");if(u){let R=i.subtitle??"Here to help you get answers fast";u.textContent=R,u.setAttribute("title",R)}let p=o.querySelector(".persona-flex-col");p&&(i.textHidden||d?p.style.display="none":p.style.display="");let m=o.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let R=i.agentIconSize??"40px";if(m.style.height=R,m.style.width=R,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let b=parseFloat(R)||24,A=ce(i.agentIconName,b*.6,"var(--persona-text-inverse, #ffffff)",1.5);A?(m.appendChild(A),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let h=o.querySelector("[data-role='launcher-image']");if(h){let R=i.agentIconSize??"40px";h.style.height=R,h.style.width=R,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=o.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let R=i.callToActionIconSize??"32px";y.style.height=R,y.style.width=R,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let b=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,b=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden)y.style.display="none";else if(y.style.display=d?"none":"",y.innerHTML="",i.callToActionIconName){let A=parseFloat(R)||24,C=Math.max(A-b,8),L=ce(i.callToActionIconName,C,"currentColor",1.5);L?y.appendChild(L):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let x=i.position&&Go[i.position]?Go[i.position]:Go["bottom-right"],T="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",w="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";o.className=d?w:`${T} ${x}`,d||(o.style.zIndex=String(i.zIndex??so));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",P="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=i.border??k,o.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:P,d?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=i.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},r=()=>{o.removeEventListener("click",t),o.remove()};return e&&n(e),{element:o,update:n,destroy:r}},Dk="teaser-dismissed",OS=new Set,BS=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${Dk}`},_k=(e,t)=>{if(OS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},Nk=(e,t)=>{if(OS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},Fk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Uk=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||St(e??{})?null:t},DS=(e,t)=>{let o=I("div","persona-launcher-surface");o.setAttribute("data-persona-launcher-surface","true");let n=e??{},r=null,a=null,i=null,d=null,c=null,u=!1,p=!1,m=!1,h=!1,y=()=>(r?.frequency??"once")==="once"&&n.persistState!==!1,x=()=>{c!==null&&(clearTimeout(c),c=null)},T=()=>{!a||!u||(u=!1,a.hidden=!0)},w=te=>{x(),m=!0,T(),Nk(BS(n),te&&y())},k=te=>{!r||m||w(te==="user"&&u)},P=()=>{c=null,!(!a||m||h)&&(p=!0,u=!0,a.hidden=!1,!(Fk()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},R=()=>{!r||!a||m||p||h||_k(BS(n),y())||(x(),c=setTimeout(P,Math.max(0,r.delayMs??0)))},b=()=>{w(y()),t()},A=te=>{te.stopPropagation(),w(y())},L=Ug(e,()=>{k("user"),t()}),F=()=>{x(),d?.removeEventListener("click",b),i?.removeEventListener("click",A),a?.remove(),a=null,d=null,i=null,u=!1},X=()=>{d=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),d.addEventListener("click",b),i=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",A),a=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},d,i),o.insertBefore(a,L.element)},G=()=>{let te=n.launcher?.position??"bottom-right",Q=Go[te]??Go["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",L.element.style.position="";return}o.className=bo("persona-launcher-surface",Q),o.setAttribute("data-teaser",te),o.style.zIndex=String(n.launcher?.zIndex??so),L.element.style.position="static"},E=te=>{let Q=Uk(te);if(r=Q,!Q){F();return}a||X(),d.textContent=Q.text,i.hidden=Q.dismissible===!1,i.setAttribute("aria-label",Q.dismissLabel??"Dismiss message"),R()},O=te=>{n=te,L.update(te),E(te),G()},D=(te,Q="user")=>{h=te,te&&k(Q)},W=()=>{F(),L.destroy(),o.remove()};return o.appendChild(L.element),e&&(E(e),G()),{element:o,launcher:L,get teaser(){return a?{element:a,show:P,dismiss:w}:null},setPanelOpen:D,update:O,destroy:W}};var _S=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=RS(e),a=WS(e,t),i={wrapper:o,panel:n,pillRoot:r},d={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},u={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:i,panelElements:a,transcript:d,header:c,composer:u,replaceHeader:h=>(c.element.replaceWith(h.header),c.element=h.header,c.iconHolder=h.iconHolder,c.headerTitle=h.headerTitle,c.headerSubtitle=h.headerSubtitle,c.closeButton=h.closeButton,c.closeButtonWrapper=h.closeButtonWrapper,c.clearChatButton=h.clearChatButton,c.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{u.footer.replaceWith(h),u.footer=h}}},qg=({config:e,plugins:t,onToggle:o})=>{let n=t.find(a=>a.renderLauncher);if(n?.renderLauncher){let a=n.renderLauncher({config:e,defaultRenderer:()=>Ug(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let r=DS(e,o);return{instance:r,element:r.element}};var qk=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},$k=(e,t,o)=>`${qk(e)}plugin:${t}:${o}`,NS=e=>{let t=new Map,o=!1,n=()=>{if(o||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return o=!0,null}};return r=>{let a=i=>$k(e(),r,i);return{get:i=>{let d=a(i),c=n();if(c)try{return c.getItem(d)}catch{o=!0}return t.get(d)??null},set:(i,d)=>{let c=a(i),u=n();if(u)try{u.setItem(c,d);return}catch{o=!0}t.set(c,d)},remove:i=>{let d=a(i);t.delete(d);let c=n();if(c)try{c.removeItem(d)}catch{o=!0}}}}};var ei=(e,t,o)=>{let n=o;for(let r of t){let a=I("span","persona-tool-char");a.style.setProperty("--char-index",String(n)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),n++}return n};var Vk=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],jk="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",zk="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",Kk=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Mu=(e,t)=>{let o=I("div",["persona-message-bubble",e,...Vk].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Tu=e=>{let t=I("button",e.expandable?jk:zk);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},$g=(e,t,o)=>{e.innerHTML="";let n=Ft(t?_s:pl,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Eu=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=I("div","persona-flex persona-items-center");$g(n,o.expanded,o.iconColor);let r=I("div",o.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(n),e.append(t,r),n},Pu=e=>{let t=I("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let o=e.renderPreview?.();Kk(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},ku=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&$g(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Lu=(e,t,o)=>{let n=o.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${o.previewKind}"]`);if(!r||!a)return;r.setAttribute("aria-expanded",n?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&$g(c,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};var ti=new Set,Gk=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,t).join(`
38
- `):""},FS=(e,t)=>{Lu(e,t,{stateSet:ti,previewKind:"reasoning",iconColor:"currentColor"})},Vg=(e,t)=>{let o=e.reasoning,n=Mu("persona-reasoning-bubble",e.id);if(!o)return n;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,i=a&&ti.has(e.id),d=o.status!=="complete",c=Gk(e,r.previewMaxLines??3),u=Tu({expandable:a,expanded:i,bubbleType:"reasoning"}),p=I("div","persona-flex persona-flex-col persona-text-left"),m=I("span","persona-text-xs persona-text-persona-primary"),h="Thinking...",y=t?.reasoning??{},x=String(o.startedAt??Date.now()),T=()=>{let W=I("span","");return W.setAttribute("data-tool-elapsed",x),W.textContent=Cc(o),W},w=y.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:h,previewText:c,isActive:d,config:t??{},elapsed:Cc(o),createElapsedElement:T});typeof w=="string"&&w.trim()?(m.textContent=w,p.appendChild(m)):w instanceof HTMLElement?p.appendChild(w):(m.textContent=h,p.appendChild(m));let k=I("span","persona-text-xs persona-text-persona-primary");k.textContent=Xv(o),p.appendChild(k);let P=r.loadingAnimation??"none",R=y.activeTextTemplate,b=y.completeTextTemplate,A=d?R:b,C=w instanceof HTMLElement,L=(W,te)=>{m.textContent="";let Q=Sc(W,""),de=0;for(let pe of Q){let Ce=pe.styles.length>0?(()=>{let Ee=I("span",pe.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return m.appendChild(Ee),Ee})():m;if(pe.isDuration&&d)Ce.appendChild(T());else{let Ee=pe.isDuration?Cc(o):pe.text;te?de=ei(Ce,Ee,de):Ce.appendChild(document.createTextNode(Ee))}}};if(!C&&A)if(k.style.display="none",m.style.display="",d&&P!=="none"){let W=y.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),P==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),L(A,!1)):(m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor)),L(A,!0))}else L(A,!1);else if(!C&&d&&P!=="none"){m.style.display="";let W=y.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),P==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor));let te=m.textContent||h;m.textContent="",ei(m,te,0)}o.status==="complete"&&(m.style.display="none")}else C||(o.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!C){let W=I("span","persona-reasoning-header-icon"),te=ce(r.iconName,16,"currentColor",2);te&&(W.appendChild(te),u.appendChild(W))}let F="currentColor",X=Eu(u,p,{expandable:a,expanded:i,iconColor:F,metaGap:!1}),G=Pu({bubble:n,previewKind:"reasoning",expanded:i,isActive:d,previewText:c,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:c,isActive:d,config:t??{}})});if(!a)return n.append(u,G),n;let E=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let O=o.chunks.join(""),D=I("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return D.textContent=O||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),E.appendChild(D),ku({expanded:i,header:u,toggleIcon:X,content:E,collapsedPreview:G,iconColor:F}),n.append(u,G,E),n};var oi=new Set,US=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",Xk=(e,t)=>{let o=e.toolCall;if(!o)return"";let n=(o.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
39
- `);let r=vc(o.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
40
- `):""},jg=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},Qk=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??"tool-call",a=Xk(e,n?.previewMaxLines??3),i=o?Qv(o):"";if(!o)return{summary:i,previewText:a,isActive:!1};let d=o.status!=="complete",c=t?.toolCall??{},u=i;return r==="tool-name"?u=o.name?.trim()||i:r==="tool-preview"&&a&&(u=a),d&&c.activeTextTemplate?u=jf(o,c.activeTextTemplate,u):!d&&c.completeTextTemplate&&(u=jf(o,c.completeTextTemplate,u)),{summary:u,previewText:a,isActive:d}},qS=(e,t,o)=>{Lu(e,t,{stateSet:oi,previewKind:"tool",iconColor:US(o?.toolCall??{})})},zg=(e,t)=>{let o=e.toolCall,n=t?.toolCall??{},r=Mu("persona-tool-bubble",e.id);if(n.backgroundColor&&(r.style.backgroundColor=n.backgroundColor),n.borderColor&&(r.style.borderColor=n.borderColor),n.borderWidth&&(r.style.borderWidth=n.borderWidth),n.borderRadius&&(r.style.borderRadius=n.borderRadius),r.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return r;let a=t?.features?.toolCallDisplay??{},i=a.expandable!==!1,d=i&&oi.has(e.id),{summary:c,previewText:u,isActive:p}=Qk(e,t),m=Tu({expandable:i,expanded:d,bubbleType:"tool"});n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let h=I("div","persona-flex persona-flex-col persona-text-left"),y=I("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(y.style.color=n.headerTextColor);let x=String(o.startedAt??Date.now()),T=()=>{let E=I("span","");return E.setAttribute("data-tool-elapsed",x),E.textContent=al(o),E},w=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:c,previewText:u,collapsedMode:a.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:al(o),createElapsedElement:T});typeof w=="string"&&w.trim()?(y.textContent=w,h.appendChild(y)):w instanceof HTMLElement?h.appendChild(w):(y.textContent=c,h.appendChild(y));let k=a.loadingAnimation??"none",P=n.activeTextTemplate,R=n.completeTextTemplate,b=p?P:R,A=w instanceof HTMLElement,C=(E,O)=>{y.textContent="";let D=o.name?.trim()||"tool",W=Sc(E,D),te=0;for(let Q of W){let de=Q.styles.length>0?(()=>{let pe=I("span",Q.styles.map(Ce=>`persona-tool-text-${Ce}`).join(" "));return y.appendChild(pe),pe})():y;if(Q.isDuration&&p)de.appendChild(T());else{let pe=Q.isDuration?al(o):Q.text;O?te=ei(de,pe,te):de.appendChild(document.createTextNode(pe))}}};if(!A)if(p&&k!=="none"){let E=n.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),k==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${E}ms`),b&&C(b,!1);else if(y.classList.add(`persona-tool-loading-${k}`),y.style.setProperty("--persona-tool-anim-duration",`${E}ms`),k==="shimmer-color"&&(n.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)C(b,!0);else{let O=y.textContent||c;y.textContent="",ei(y,O,0)}}else b&&C(b,!1);let L=US(n),F=Eu(m,h,{expandable:i,expanded:d,iconColor:L,metaGap:!0}),X=Pu({bubble:r,previewKind:"tool",expanded:d,isActive:p,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:u,isActive:p,config:t??{}})});if(!i)return r.append(m,X),r;let G=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=d?"":"none",n.contentBackgroundColor&&(G.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(G.style.color=n.contentTextColor),n.contentPaddingX&&(G.style.paddingLeft=n.contentPaddingX,G.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(G.style.paddingTop=n.contentPaddingY,G.style.paddingBottom=n.contentPaddingY),o.name){let E=I("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?E.style.color=n.contentTextColor:n.headerTextColor&&(E.style.color=n.headerTextColor),E.textContent=o.name,G.appendChild(E)}if(o.args!==void 0){let E=I("div","persona-space-y-1"),O=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Arguments";let D=I("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",jg(D,n),D.textContent=vc(o.args),E.append(O,D),G.appendChild(E)}if(o.chunks&&o.chunks.length){let E=I("div","persona-space-y-1"),O=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Activity";let D=I("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",jg(D,n),D.textContent=o.chunks.join(""),E.append(O,D),G.appendChild(E)}if(o.status==="complete"&&o.result!==void 0){let E=I("div","persona-space-y-1"),O=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(O.style.color=n.labelTextColor),O.textContent="Result";let D=I("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",jg(D,n),D.textContent=vc(o.result),E.append(O,D),G.appendChild(E)}if(o.status==="complete"&&typeof o.duration=="number"){let E=I("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(E.style.color=n.contentTextColor),E.textContent=`Duration: ${o.duration}ms`,G.appendChild(E)}return ku({expanded:d,header:m,toggleIcon:F,content:G,collapsedPreview:X,iconColor:L}),r.append(m,X,G),r};var{setLoader:Yk,load:Jk,provide:fD,getSync:Zk}=mt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),$S=Yk,VS=Jk;var jS=Zk;var{setLoader:eL,load:tL}=mt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),zS=eL,Kg=tL;var Gg=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),n?this.options.set(t,n):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,n])=>{this.register(o,n)})}},Cn=new Gg;var Xg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:oL,load:nL,provide:SD,getSync:rL}=mt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ni=null,Iu=new Set,KS=e=>{if(ni)return ni;ni=e,e.initArtifactsUi({componentRegistry:Cn});for(let n of Xg)Cn.has(n)||Cn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=_n();t?e.__provideMarkdownParsers(t):ka(()=>{let n=_n();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>_c());let o=[...Iu];Iu.clear();for(let n of o)try{n()}catch{}return e},GS=oL,Ru=()=>nL().then(KS);var gr=()=>{if(ni)return ni;let e=rL();return e?KS(e):null},Qg=e=>ni?()=>{}:(Iu.add(e),()=>{Iu.delete(e)});function wo(e){return e?.features?.artifacts?.enabled===!0}function XS(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"),!wo(t))return;let o=t.features?.artifacts?.layout,n=o?.paneBorder?.trim(),r=o?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function sL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var QS=["panel","seamless","detached"];function Yg(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&QS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Jg(e){return!e||!wo(e)?!1:Yg(e)==="detached"}function Dl(e,t){if(!wo(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),sL(e),XS(e,t);return}let o=t.features?.artifacts?.layout,n=Yg(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",o.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=o?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[o?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[o?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[o?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[o?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[d,c]of i){let u=d?.trim();u?e.style.setProperty(c,u):e.style.removeProperty(c)}XS(e,t)}function _l(e,t){for(let d of QS)e.classList.remove(`persona-artifact-appearance-${d}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!wo(t))return;let o=t.features?.artifacts?.layout,n=Yg(t);e.classList.add(`persona-artifact-appearance-${n}`);let r=o?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let i=o?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function YS(e,t){return!t||!wo(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var aL=new Set(["__proto__","prototype","constructor"]),iL=new Set(["collapsed","card","panel","inline"]),JS=new Set(["markdown","component"]),lL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wu=e=>!aL.has(e),Zg=e=>typeof e=="string"&&iL.has(e),Qs=e=>Object.keys(e).length>0;function jn(e,t,o,n){e.push({path:t,code:o,message:n})}var dL="Ignored because this key is not part of the persisted preference schema.",Hu="Ignored an unsupported value.",cL="Expected collapsed, panel, or inline.",uL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',ZS={kind:"mode",message:Hu},ri={kind:"string",message:"Expected a CSS length string."},hr={kind:"boolean"},pL={paneWidth:ri,paneMaxWidth:ri,paneMinWidth:ri,expandedPanelWidth:ri,resizableMinWidth:ri,resizableMaxWidth:ri,expandLauncherPanelWhenOpen:hr,resizable:hr},fL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:hr,showReasoning:hr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Hu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Hu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Hu},expandable:hr,grouped:hr}},reasoningDisplay:{kind:"object",children:{expandable:hr,activePreview:hr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ZS,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ZS,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:JS,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:JS}}},filePreview:{kind:"object",children:{enabled:hr}},layout:{kind:"object",children:pL}}}}};function ew(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:jn(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:jn(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:jn(n,o,"invalid_value",t.message);case"mode":return Zg(e)?Ro(e):jn(n,o,"invalid_value",t.message);case"modeMap":{if(!Xs(e))return jn(n,o,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[i,d]of Object.entries(e)){let c=r?i:Nr(i);Wu(i)&&(r?r.has(i):lL.test(c))?Zg(d)?a[c]=Ro(d):jn(n,`${o}.${i}`,"invalid_value",cL):jn(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":uL)}return Qs(a)?a:void 0}case"object":{if(t.bareMode&&Zg(e))return Ro(e);if(!Xs(e))return jn(n,o,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=d=>o?`${o}.${d}`:d;for(let d of Object.keys(e))(!Wu(d)||!r.includes(d))&&jn(n,a(d),"unknown_key",dL);let i={};for(let d of r){let c=t.children[d],u=ew(e[d],c,a(d),n);if(c.deprecated&&e[d]!==void 0&&jn(n,a(d),"deprecated_key",c.deprecated),u===void 0)continue;let p=c.alias??d,m=i[p];i[p]=Xs(m)&&Xs(u)?{...m,...u}:u}return Qs(i)?i:void 0}}}function eh(e){let t=[];return{preferences:(e===null?void 0:ew(e,fL,"",t))??{},issues:t}}function si(e){if(Array.isArray(e))return e.map(si);if(!Xs(e))return e;let t={};for(let[o,n]of Object.entries(e))Wu(o)&&n!==void 0&&(t[o]=si(n));return t}function tw(e,t){let o=si(e);for(let[n,r]of Object.entries(t)){if(!Wu(n)||r===void 0)continue;let a=o[n];o[n]=Xs(a)&&Xs(r)?tw(a,r):si(r)}return o}function mL(e){let t={},o;for(let r of e){let a=eh(r).preferences;o=ow(o,a.artifacts?.display),t=tw(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function gL(e,t){if(t===void 0)return e===void 0?void 0:si(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Qs(r)?{byMediaType:r}:{}};return Qs(a)?a:void 0}function ow(e,t){if(t===void 0)return e===void 0?void 0:si(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byType,...o.byKind,...t.byType,...t.byKind},a=gL(o.files,t.files),i={...n?{default:n}:{},...Qs(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Qs(i)?i:void 0}function th(e={},t){let o=mL(t),n={...e};if(o.showToolCalls!==void 0&&(n.showToolCalls=o.showToolCalls),o.showReasoning!==void 0&&(n.showReasoning=o.showReasoning),o.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...o.toolCallDisplay}),o.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...o.reasoningDisplay}),o.artifacts){let r=e.artifacts??{},a={...r};if(o.artifacts.display!==void 0){let i=ow(r.display,o.artifacts.display);i!==void 0&&(a.display=i)}o.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:o.artifacts.filePreview.enabled}),o.artifacts.layout&&(a.layout={...r.layout,...o.artifacts.layout}),n.artifacts=a}return n}function Nl(e){let t=e.preferences;return!t||!Qs(t)?e:{...e,features:th(e.features??{},[t])}}function hL(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function yL(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function bL(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function vL(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function oh(e,t){let n=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function nw(e,t,o,n,r,a,i=200){let d=hL(r,200),c=vL(t,o,n,i);c=Math.max(d,c);let u=yL(a);return u!==null&&(c=Math.min(c,u)),bL(e,d,c)}var{setLoader:xL,load:CL,provide:kD,getSync:SL}=mt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),rw=xL,sw=CL;var aw=SL;var nh=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let n=new Set(t.map(a=>a.id));return[...o.filter(a=>!n.has(a.id)),...t].sort((a,i)=>(i.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Fl=new nh;var iw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wL=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),lw=(e,t,o)=>{if(!iw(e)||!iw(t)||wL.has(o))return t;let n={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete n[r];continue}let a=o?`${o}.${r}`:r;n[r]=lw(e[r],t[r],a)}return n};function Bu(e,t){let o=lw(e,t,"");return ja(o)}var dw=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>o(r,a)),o=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:o,emit:(r,a)=>{e.get(r)?.forEach(i=>{try{i(a)}catch(d){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var AL=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ML=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let n=0;for(let r=o;r<t.length;r+=1){let a=t[r];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(o,r+1)}return null},Ul=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=AL(e),o=ML(t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||!n.action)return null;let{action:r,...a}=n;return{type:String(r),payload:a,raw:n}}catch{return null}},rh=e=>typeof e=="string"?e:e==null?"":String(e),Ys={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:rh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=rh(o.element);if(n&&t.document?.querySelector){let r=t.document.querySelector(n);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:rh(o.text)}}},cw=e=>Array.isArray(e)?e.map(t=>String(t)):[],ql=e=>{let t=new Set(cw(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(cw(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let i=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!i&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let d=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:a.message})||null,null):null;if(!d)return null;t.add(a.message.id),n();let c={action:d,message:a.message};e.emit("action:detected",c);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",c)},m=u(d,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:o}};var TL=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},EL=e=>e.map(t=>({...t,streaming:!1})),PL=e=>e.map(t=>({...t,status:"complete"})),Ou=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?TL(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?EL(o.messages):void 0,artifacts:o.artifacts?PL(o.artifacts):void 0};n.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var kL=e=>{let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},uw=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let o=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}catch{}return kL(e)},LL=async(e,t)=>{let o=await uw(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await uw(`${e}\0${t}`)}`}};var pw=(e,t,o)=>{let n="",r="",a="",i=!1,d=!1,c=0,u=null,p=null,m=new Set,h=()=>{if(o||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},y=()=>{let C=h();if(!C)return u;try{return C.getItem(n)}catch{return i=!0,u}},x=(C,L)=>{if(d||C===u)return;let F=u;u=C,c+=1;let X={previousToken:F,token:C,source:L,revision:c};for(let G of m)G(X)},T=C=>{d||C.key!==null&&C.key!==n||x(C.key===null?null:C.newValue??null,"external")},w=(async()=>{let C=await LL(e,t);n=C.storageKey,r=C.leaseKey,a=C.lockName,u=y(),!o&&typeof window<"u"&&window.addEventListener("storage",T)})(),k=C=>new Promise(L=>setTimeout(L,C)),P=()=>{let C=h();if(!C)return null;try{let L=C.getItem(r);if(!L)return null;let F=JSON.parse(L);return typeof F?.expiresAt=="number"&&typeof F?.ownerNonce=="string"?F:null}catch{return null}},R=C=>{let L=h();if(L)try{P()?.ownerNonce===C&&L.removeItem(r)}catch{}},b=C=>new Promise(L=>{let F=setTimeout(X,C);function X(){clearTimeout(F),window.removeEventListener("storage",G),L()}function G(E){(E.key===null||E.key===r)&&X()}window.addEventListener("storage",G)}),A=async C=>{let L=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,F=Date.now()+15e3;for(;Date.now()<F;){let X=h();if(!X)break;let G=Date.now(),E=P();if(E&&E.expiresAt>G&&E.ownerNonce!==L){await b(Math.min(E.expiresAt-G,500));continue}try{X.setItem(r,JSON.stringify({ownerNonce:L,expiresAt:G+1e4}))}catch{i=!0;break}if(await k(20+Math.random()*40),P()?.ownerNonce!==L){await b(500);continue}p=L;try{return await C()}finally{p=null,R(L)}}return C()};return{ready:w,async get(){return await w,x(y(),"external"),u},async set(C){await w;let L=h();if(L)try{L.setItem(n,C)}catch{i=!0}x(C,"local")},async clear(){await w;let C=h();if(C)try{C.removeItem(n)}catch{i=!0}x(null,"local")},revision(){return c},subscribe(C){return m.add(C),()=>{m.delete(C)}},async withFirstInitLock(C){await w;let L=globalThis.navigator?.locks;return L?.request?L.request(a,()=>C()):h()?A(C):C()},matches(C,L,F){return C===e&&L===t&&F===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",T),p&&R(p)}}};var{setLoader:IL,load:RL}=mt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),fw=IL,sh=RL;var ah=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},yr=e=>Object.freeze({...e}),mw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),gw=e=>e?yr(e):null;function hw(e){let{plugins:t,config:o}=e,n=!1,r=!1,a=!1,i=!1,d=null,c=[],u=()=>{for(let b of c.splice(0))try{b()}catch(A){ah("renderHistoryView cleanup",A)}},p=(b,A)=>{for(let C of t){let L=C[b];if(L)try{let F=L(A);if(F)return F}catch(F){ah(b,F)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),h={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:yr(b.identityStatus),pendingAction:gw(b.pendingAction),copy:yr(b.copy),actions:Object.freeze({close:T.close,startNewConversation:T.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:mw(b.conversation),active:b.active,pending:b.pending,open:b.open,requestDelete:b.requestDelete,defaultRenderer:b.defaultRenderer})):null,state:b=>i?p("renderHistoryState",Object.freeze({...m(),state:yr(b.state),identityStatus:yr(b.identityStatus),copy:yr(b.copy),...b.retry?{retry:b.retry}:{},...b.startNewConversation?{startNewConversation:b.startNewConversation}:{},defaultRenderer:b.defaultRenderer})):null},y=t.flatMap(b=>(b.railSections??[]).map(A=>({...A,placement:A.placement??"above-conversations",items:[],render:C=>A.render(Object.freeze({collapsed:C,presentation:e.getPresentation(),actions:T}))}))),x=e.createView({slots:h,renderDom:!1,onModelChange:()=>R(),railSections:y}),T=Object.freeze({...x.operations,close:e.close}),w=()=>(i=!0,x.setDomRenderEnabled(!0),x.element),k=b=>Object.freeze({conversations:Object.freeze(b.conversations.map(mw)),activeConversationId:b.activeConversationId,state:yr(b.state),pendingAction:gw(b.pendingAction),identityStatus:yr(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:yr(x.copy),actions:T,defaultRenderer:w,requestRender:()=>R(),onCleanup:A=>{c.push(A)}}),P=()=>{i=!1;let b=null;for(let C of t)if(C.renderHistoryView){try{b=C.renderHistoryView(k(x.getModel()))}catch(L){ah("renderHistoryView",L),b=null}if(b)break}let A=!b||b.contains(x.element);return i=A,x.setDomRenderEnabled(A),b??x.element};function R(){if(!(!a||n||r)){r=!0;try{u();let b=P();if(b===d)return;let A=d;d=b,e.onElementChanged(b,A)}finally{r=!1}}}return a=!0,R(),{view:x,get element(){return d??x.element},requestRender:R,dispose:()=>{n=!0,u()}}}var HL=null;function yw(){return HL}var WL=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),BL=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),ih=e=>BL.get(e)??"Conversation history is unavailable right now.";function OL(e){if(e instanceof ln)return e;if(e instanceof Fe){let t=WL.get(e.code)??"unavailable";return new ln(t,ih(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ln("unavailable",ih("unavailable"))}function bw(e){let t=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],n={scopes:o},r=d=>{if(!o.includes(d))throw new ln("unsupported_scope",ih("unsupported_scope"))},a=async(d,c)=>{r(d);try{return await c()}catch(u){throw OL(u)}},i=d=>{let c=!1;return{conversationId:d.session.conversationId??"",conversationRevision:d.session.conversationRevision??"",async commit(){c||(c=!0,d.commit(),await e.onActivationCommitted(d.session))},discard(){c||(c=!0,d.discard())}}};return{capabilities:n,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(d){return t().subscribeHistoryIdentityStatus(d)},subscribeAvailability(d){return t().subscribeHistoryAvailability(d)},async list(d){return a(d.context.scope,async()=>{let c=await t().listConversations({...d.cursor?{cursor:d.cursor}:{},...d.limit!==void 0?{limit:d.limit}:{},...d.targetId?{targetId:d.targetId}:{},scope:d.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(d,c){return a(c.context.scope,async()=>{let u=await t().getConversation(d,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),p=dx(u.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:u.summary,messages:dl([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(d,c){return a(c.context.scope,async()=>i(await t().prepareConversationSession(d)))},async prepareStartNew(d){return a(d.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(d,c){await a(c.context.scope,()=>t().deleteConversation(d,{scope:c.context.scope}))},async deleteAll(d){return a(d.context.scope,()=>t().deleteAllConversations({...d.targetId!==void 0?{targetId:d.targetId}:{},scope:d.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var DL=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],vw={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function lh(e){if(!e)return vw;let t={...vw};for(let o of DL){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var _L="button:not([disabled])";function Du(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,o=Math.random().toString(36).slice(2,8),n=`persona-history-confirm-title-${o}`,r=`persona-history-confirm-desc-${o}`,a=Y("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=Y("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),d=Y("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},Y("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:n},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Y("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Y("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},a,i));for(let u of[a,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";a.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",a.style.background="transparent",a.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=Y("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},d);return new Promise(u=>{let p=!1,m=y=>{p||(p=!0,c.removeEventListener("keydown",h,!0),c.remove(),t?.focus(),u(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let x=Array.from(d.querySelectorAll(_L));if(x.length===0)return;let T=x[0],w=x[x.length-1],k=document.activeElement;y.shiftKey&&(k===T||!d.contains(k))?(y.preventDefault(),w.focus()):!y.shiftKey&&k===w&&(y.preventDefault(),T.focus())}c.addEventListener("keydown",h,!0),c.addEventListener("pointerdown",y=>{y.target===c&&m(!1)}),a.addEventListener("click",()=>m(!1)),i.addEventListener("click",()=>m(!0)),e.host.appendChild(c),a.focus()})}var ai=Zt(pc(),1);function NL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function FL(e,t){if(!NL(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function _u(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e;try{let r=(0,ai.parse)(o,ai.STR|ai.OBJ),a=FL(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function xw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Nu(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=Cn.get(e.component);if(!a){if(Xg.includes(e.component)){Ru().catch(()=>{});let d=I("div","persona-w-full");return d.setAttribute("data-persona-artifact-pending","true"),d}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:n,config:o,updateProps:d=>{r&&r(d)}};try{return a(e.props,i)}catch(d){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,d),null}}function Cw(){let e=_u();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Sw(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function $l(e){let t=Sw(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function Fu(e){let t=Sw(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let n=o;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var UL=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Uu(e){let{onSubmit:t,onDismiss:o,title:n="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,ratingLabels:u=UL}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,y.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,y.appendChild(T),h.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let C=1;C<=5;C++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),L.title=u[C-1],L.dataset.rating=String(C),L.innerHTML=`
37
+ `,o.addEventListener("click",t);let n=a=>{let i=a.launcher??{},d=Ct(a),c=o.querySelector("[data-role='launcher-title']");if(c){let H=i.title??"Chat Assistant";c.textContent=H,c.setAttribute("title",H)}let u=o.querySelector("[data-role='launcher-subtitle']");if(u){let H=i.subtitle??"Here to help you get answers fast";u.textContent=H,u.setAttribute("title",H)}let p=o.querySelector(".persona-flex-col");p&&(i.textHidden||d?p.style.display="none":p.style.display="");let m=o.querySelector("[data-role='launcher-icon']");if(m)if(i.agentIconHidden)m.style.display="none";else{let H=i.agentIconSize??"40px";if(m.style.height=H,m.style.width=H,i.agentIconBackgroundColor?(m.style.backgroundColor=i.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",i.agentIconName){let b=parseFloat(H)||24,A=ue(i.agentIconName,b*.6,"var(--persona-text-inverse, #ffffff)",1.5);A?(m.appendChild(A),m.style.display=""):(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}else i.iconUrl?m.style.display="none":(m.textContent=i.agentIconText??"\u{1F4AC}",m.style.display="")}let h=o.querySelector("[data-role='launcher-image']");if(h){let H=i.agentIconSize??"40px";h.style.height=H,h.style.width=H,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=o.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let H=i.callToActionIconSize??"32px";y.style.height=H,y.style.width=H,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let b=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,b=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden)y.style.display="none";else if(y.style.display=d?"none":"",y.innerHTML="",i.callToActionIconName){let A=parseFloat(H)||24,C=Math.max(A-b,8),L=ue(i.callToActionIconName,C,"currentColor",1.5);L?y.appendChild(L):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let x=i.position&&jo[i.position]?jo[i.position]:jo["bottom-right"],T="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",w="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";o.className=d?w:`${T} ${x}`,d||(o.style.zIndex=String(i.zIndex??ro));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",P="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";o.style.border=i.border??k,o.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:P,d?(o.style.width="0",o.style.minWidth="0",o.style.maxWidth="0",o.style.padding="0",o.style.overflow="hidden",o.style.border="none",o.style.boxShadow="none"):(o.style.width="",o.style.minWidth="",o.style.maxWidth=i.collapsedMaxWidth??"",o.style.justifyContent="",o.style.padding="",o.style.overflow="")},r=()=>{o.removeEventListener("click",t),o.remove()};return e&&n(e),{element:o,update:n,destroy:r}},Nk="teaser-dismissed",DS=new Set,OS=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${Nk}`},Fk=(e,t)=>{if(DS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},Uk=(e,t)=>{if(DS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},qk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,$k=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ct(e??{})?null:t},_S=(e,t)=>{let o=I("div","persona-launcher-surface");o.setAttribute("data-persona-launcher-surface","true");let n=e??{},r=null,a=null,i=null,d=null,c=null,u=!1,p=!1,m=!1,h=!1,y=()=>(r?.frequency??"once")==="once"&&n.persistState!==!1,x=()=>{c!==null&&(clearTimeout(c),c=null)},T=()=>{!a||!u||(u=!1,a.hidden=!0)},w=te=>{x(),m=!0,T(),Uk(OS(n),te&&y())},k=te=>{!r||m||w(te==="user"&&u)},P=()=>{c=null,!(!a||m||h)&&(p=!0,u=!0,a.hidden=!1,!(qk()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},H=()=>{!r||!a||m||p||h||Fk(OS(n),y())||(x(),c=setTimeout(P,Math.max(0,r.delayMs??0)))},b=()=>{w(y()),t()},A=te=>{te.stopPropagation(),w(y())},L=qg(e,()=>{k("user"),t()}),U=()=>{x(),d?.removeEventListener("click",b),i?.removeEventListener("click",A),a?.remove(),a=null,d=null,i=null,u=!1},Q=()=>{d=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),d.addEventListener("click",b),i=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",A),a=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},d,i),o.insertBefore(a,L.element)},$=()=>{let te=n.launcher?.position??"bottom-right",X=jo[te]??jo["bottom-right"];if(!a){o.className="persona-launcher-surface",o.removeAttribute("data-teaser"),o.style.zIndex="",L.element.style.position="";return}o.className=go("persona-launcher-surface",X),o.setAttribute("data-teaser",te),o.style.zIndex=String(n.launcher?.zIndex??ro),L.element.style.position="static"},E=te=>{let X=$k(te);if(r=X,!X){U();return}a||Q(),d.textContent=X.text,i.hidden=X.dismissible===!1,i.setAttribute("aria-label",X.dismissLabel??"Dismiss message"),H()},B=te=>{n=te,L.update(te),E(te),$()},D=(te,X="user")=>{h=te,te&&k(X)},W=()=>{U(),L.destroy(),o.remove()};return o.appendChild(L.element),e&&(E(e),$()),{element:o,launcher:L,get teaser(){return a?{element:a,show:P,dismiss:w}:null},setPanelOpen:D,update:B,destroy:W}};var NS=({config:e,showClose:t})=>{let{wrapper:o,panel:n,pillRoot:r}=HS(e),a=BS(e,t),i={wrapper:o,panel:n,pillRoot:r},d={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},u={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:i,panelElements:a,transcript:d,header:c,composer:u,replaceHeader:h=>(c.element.replaceWith(h.header),c.element=h.header,c.iconHolder=h.iconHolder,c.headerTitle=h.headerTitle,c.headerSubtitle=h.headerSubtitle,c.closeButton=h.closeButton,c.closeButtonWrapper=h.closeButtonWrapper,c.clearChatButton=h.clearChatButton,c.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{u.footer.replaceWith(h),u.footer=h}}},$g=({config:e,plugins:t,onToggle:o})=>{let n=t.find(a=>a.renderLauncher);if(n?.renderLauncher){let a=n.renderLauncher({config:e,defaultRenderer:()=>qg(e,o).element,onToggle:o});if(a)return{instance:null,element:a}}let r=_S(e,o);return{instance:r,element:r.element}};var Vk=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},jk=(e,t,o)=>`${Vk(e)}plugin:${t}:${o}`,FS=e=>{let t=new Map,o=!1,n=()=>{if(o||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return o=!0,null}};return r=>{let a=i=>jk(e(),r,i);return{get:i=>{let d=a(i),c=n();if(c)try{return c.getItem(d)}catch{o=!0}return t.get(d)??null},set:(i,d)=>{let c=a(i),u=n();if(u)try{u.setItem(c,d);return}catch{o=!0}t.set(c,d)},remove:i=>{let d=a(i);t.delete(d);let c=n();if(c)try{c.removeItem(d)}catch{o=!0}}}}};var ri=(e,t,o)=>{let n=o;for(let r of t){let a=I("span","persona-tool-char");a.style.setProperty("--char-index",String(n)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),n++}return n};var zk=["persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"],Kk="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none",Gk="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",Xk=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Tu=(e,t)=>{let o=I("div",["persona-message-bubble",e,...zk].join(" "));return o.id=`bubble-${t}`,o.setAttribute("data-message-id",t),o},Eu=e=>{let t=I("button",e.expandable?Kk:Gk);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},Vg=(e,t,o)=>{e.innerHTML="";let n=_t(t?Fs:fl,16,o,2);n?e.appendChild(n):e.textContent=t?"Hide":"Show"},Pu=(e,t,o)=>{if(!o.expandable)return e.append(t),null;let n=I("div","persona-flex persona-items-center");Vg(n,o.expanded,o.iconColor);let r=I("div",o.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(n),e.append(t,r),n},ku=e=>{let t=I("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let o=e.renderPreview?.();Xk(t,o)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Lu=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Vg(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Iu=(e,t,o)=>{let n=o.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${o.previewKind}"]`);if(!r||!a)return;r.setAttribute("aria-expanded",n?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&Vg(c,n,o.iconColor),a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")};var si=new Set,Qk=(e,t)=>{let o=e.reasoning?.chunks.join("").trim()??"";return o?o.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).slice(0,t).join(`
38
+ `):""},US=(e,t)=>{Iu(e,t,{stateSet:si,previewKind:"reasoning",iconColor:"currentColor"})},jg=(e,t)=>{let o=e.reasoning,n=Tu("persona-reasoning-bubble",e.id);if(!o)return n;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,i=a&&si.has(e.id),d=o.status!=="complete",c=Qk(e,r.previewMaxLines??3),u=Eu({expandable:a,expanded:i,bubbleType:"reasoning"}),p=I("div","persona-flex persona-flex-col persona-text-left"),m=I("span","persona-text-xs persona-text-persona-primary"),h="Thinking...",y=t?.reasoning??{},x=String(o.startedAt??Date.now()),T=()=>{let W=I("span","");return W.setAttribute("data-tool-elapsed",x),W.textContent=Sc(o),W},w=y.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:h,previewText:c,isActive:d,config:t??{},elapsed:Sc(o),createElapsedElement:T});typeof w=="string"&&w.trim()?(m.textContent=w,p.appendChild(m)):w instanceof HTMLElement?p.appendChild(w):(m.textContent=h,p.appendChild(m));let k=I("span","persona-text-xs persona-text-persona-primary");k.textContent=Qv(o),p.appendChild(k);let P=r.loadingAnimation??"none",H=y.activeTextTemplate,b=y.completeTextTemplate,A=d?H:b,C=w instanceof HTMLElement,L=(W,te)=>{m.textContent="";let X=wc(W,""),fe=0;for(let le of X){let xe=le.styles.length>0?(()=>{let Re=I("span",le.styles.map(He=>`persona-tool-text-${He}`).join(" "));return m.appendChild(Re),Re})():m;if(le.isDuration&&d)xe.appendChild(T());else{let Re=le.isDuration?Sc(o):le.text;te?fe=ri(xe,Re,fe):xe.appendChild(document.createTextNode(Re))}}};if(!C&&A)if(k.style.display="none",m.style.display="",d&&P!=="none"){let W=y.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),P==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),L(A,!1)):(m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor)),L(A,!0))}else L(A,!1);else if(!C&&d&&P!=="none"){m.style.display="";let W=y.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),P==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${W}ms`),P==="shimmer-color"&&(y.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",y.loadingAnimationColor),y.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",y.loadingAnimationSecondaryColor));let te=m.textContent||h;m.textContent="",ri(m,te,0)}o.status==="complete"&&(m.style.display="none")}else C||(o.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!C){let W=I("span","persona-reasoning-header-icon"),te=ue(r.iconName,16,"currentColor",2);te&&(W.appendChild(te),u.appendChild(W))}let U="currentColor",Q=Pu(u,p,{expandable:a,expanded:i,iconColor:U,metaGap:!1}),$=ku({bubble:n,previewKind:"reasoning",expanded:i,isActive:d,previewText:c,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:c,isActive:d,config:t??{}})});if(!a)return n.append(u,$),n;let E=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=i?"":"none";let B=o.chunks.join(""),D=I("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return D.textContent=B||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),E.appendChild(D),Lu({expanded:i,header:u,toggleIcon:Q,content:E,collapsedPreview:$,iconColor:U}),n.append(u,$,E),n};var ai=new Set,qS=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",Yk=(e,t)=>{let o=e.toolCall;if(!o)return"";let n=(o.chunks??[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
39
+ `);let r=xc(o.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
40
+ `):""},zg=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},Jk=(e,t)=>{let o=e.toolCall,n=t?.features?.toolCallDisplay,r=n?.collapsedMode??"tool-call",a=Yk(e,n?.previewMaxLines??3),i=o?Yv(o):"";if(!o)return{summary:i,previewText:a,isActive:!1};let d=o.status!=="complete",c=t?.toolCall??{},u=i;return r==="tool-name"?u=o.name?.trim()||i:r==="tool-preview"&&a&&(u=a),d&&c.activeTextTemplate?u=zf(o,c.activeTextTemplate,u):!d&&c.completeTextTemplate&&(u=zf(o,c.completeTextTemplate,u)),{summary:u,previewText:a,isActive:d}},$S=(e,t,o)=>{Iu(e,t,{stateSet:ai,previewKind:"tool",iconColor:qS(o?.toolCall??{})})},Kg=(e,t)=>{let o=e.toolCall,n=t?.toolCall??{},r=Tu("persona-tool-bubble",e.id);if(n.backgroundColor&&(r.style.backgroundColor=n.backgroundColor),n.borderColor&&(r.style.borderColor=n.borderColor),n.borderWidth&&(r.style.borderWidth=n.borderWidth),n.borderRadius&&(r.style.borderRadius=n.borderRadius),r.style.boxShadow=n.shadow!==void 0?n.shadow.trim()===""?"none":n.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!o)return r;let a=t?.features?.toolCallDisplay??{},i=a.expandable!==!1,d=i&&ai.has(e.id),{summary:c,previewText:u,isActive:p}=Jk(e,t),m=Eu({expandable:i,expanded:d,bubbleType:"tool"});n.headerBackgroundColor&&(m.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(m.style.paddingLeft=n.headerPaddingX,m.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(m.style.paddingTop=n.headerPaddingY,m.style.paddingBottom=n.headerPaddingY);let h=I("div","persona-flex persona-flex-col persona-text-left"),y=I("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(y.style.color=n.headerTextColor);let x=String(o.startedAt??Date.now()),T=()=>{let E=I("span","");return E.setAttribute("data-tool-elapsed",x),E.textContent=il(o),E},w=n.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:c,previewText:u,collapsedMode:a.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:il(o),createElapsedElement:T});typeof w=="string"&&w.trim()?(y.textContent=w,h.appendChild(y)):w instanceof HTMLElement?h.appendChild(w):(y.textContent=c,h.appendChild(y));let k=a.loadingAnimation??"none",P=n.activeTextTemplate,H=n.completeTextTemplate,b=p?P:H,A=w instanceof HTMLElement,C=(E,B)=>{y.textContent="";let D=o.name?.trim()||"tool",W=wc(E,D),te=0;for(let X of W){let fe=X.styles.length>0?(()=>{let le=I("span",X.styles.map(xe=>`persona-tool-text-${xe}`).join(" "));return y.appendChild(le),le})():y;if(X.isDuration&&p)fe.appendChild(T());else{let le=X.isDuration?il(o):X.text;B?te=ri(fe,le,te):fe.appendChild(document.createTextNode(le))}}};if(!A)if(p&&k!=="none"){let E=n.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),k==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${E}ms`),b&&C(b,!1);else if(y.classList.add(`persona-tool-loading-${k}`),y.style.setProperty("--persona-tool-anim-duration",`${E}ms`),k==="shimmer-color"&&(n.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),b)C(b,!0);else{let B=y.textContent||c;y.textContent="",ri(y,B,0)}}else b&&C(b,!1);let L=qS(n),U=Pu(m,h,{expandable:i,expanded:d,iconColor:L,metaGap:!0}),Q=ku({bubble:r,previewKind:"tool",expanded:d,isActive:p,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>n.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:u,isActive:p,config:t??{}})});if(!i)return r.append(m,Q),r;let $=I("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if($.style.display=d?"":"none",n.contentBackgroundColor&&($.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&($.style.color=n.contentTextColor),n.contentPaddingX&&($.style.paddingLeft=n.contentPaddingX,$.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&($.style.paddingTop=n.contentPaddingY,$.style.paddingBottom=n.contentPaddingY),o.name){let E=I("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?E.style.color=n.contentTextColor:n.headerTextColor&&(E.style.color=n.headerTextColor),E.textContent=o.name,$.appendChild(E)}if(o.args!==void 0){let E=I("div","persona-space-y-1"),B=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(B.style.color=n.labelTextColor),B.textContent="Arguments";let D=I("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",zg(D,n),D.textContent=xc(o.args),E.append(B,D),$.appendChild(E)}if(o.chunks&&o.chunks.length){let E=I("div","persona-space-y-1"),B=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(B.style.color=n.labelTextColor),B.textContent="Activity";let D=I("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",zg(D,n),D.textContent=o.chunks.join(""),E.append(B,D),$.appendChild(E)}if(o.status==="complete"&&o.result!==void 0){let E=I("div","persona-space-y-1"),B=I("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(B.style.color=n.labelTextColor),B.textContent="Result";let D=I("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");D.style.fontSize="0.75rem",D.style.lineHeight="1rem",zg(D,n),D.textContent=xc(o.result),E.append(B,D),$.appendChild(E)}if(o.status==="complete"&&typeof o.duration=="number"){let E=I("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(E.style.color=n.contentTextColor),E.textContent=`Duration: ${o.duration}ms`,$.appendChild(E)}return Lu({expanded:d,header:m,toggleIcon:U,content:$,collapsedPreview:Q,iconColor:L}),r.append(m,Q,$),r};var{setLoader:Zk,load:eL,provide:gD,getSync:tL}=gt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")}),VS=Zk,jS=eL;var zS=tL;var{setLoader:oL,load:nL}=gt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")}),KS=oL,Gg=nL;var Xg=class{constructor(){this.components=new Map;this.options=new Map}register(t,o,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,o),n?this.options.set(t,n):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([o,n])=>{this.register(o,n)})}},vn=new Xg;var Qg=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:rL,load:sL,provide:AD,getSync:aL}=gt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ii=null,Ru=new Set,GS=e=>{if(ii)return ii;ii=e,e.initArtifactsUi({componentRegistry:vn});for(let n of Qg)vn.has(n)||vn.register(n,n==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Nn();t?e.__provideMarkdownParsers(t):Ha(()=>{let n=Nn();n&&e.__provideMarkdownParsers(n)}),e.__setIconsExtraLoader(()=>Nc());let o=[...Ru];Ru.clear();for(let n of o)try{n()}catch{}return e},XS=rL,Hu=()=>sL().then(GS);var br=()=>{if(ii)return ii;let e=aL();return e?GS(e):null},Yg=e=>ii?()=>{}:(Ru.add(e),()=>{Ru.delete(e)});function xo(e){return e?.features?.artifacts?.enabled===!0}function QS(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"),!xo(t))return;let o=t.features?.artifacts?.layout,n=o?.paneBorder?.trim(),r=o?.paneBorderLeft?.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function iL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var YS=["panel","seamless","detached"];function Jg(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&YS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Zg(e){return!e||!xo(e)?!1:Jg(e)==="detached"}function _l(e,t){if(!xo(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),iL(e),QS(e,t);return}let o=t.features?.artifacts?.layout,n=Jg(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",o?.splitGap??n),e.style.setProperty("--persona-artifact-pane-width",o?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",o?.paneMaxWidth??"28rem"),o?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",o.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),o?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",o.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=o?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=o?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[o?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[o?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[o?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[o?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[d,c]of i){let u=d?.trim();u?e.style.setProperty(c,u):e.style.removeProperty(c)}QS(e,t)}function Nl(e,t){for(let d of YS)e.classList.remove(`persona-artifact-appearance-${d}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!xo(t))return;let o=t.features?.artifacts?.layout,n=Jg(t);e.classList.add(`persona-artifact-appearance-${n}`);let r=o?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=o?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let i=o?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function JS(e,t){return!t||!xo(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var lL=new Set(["__proto__","prototype","constructor"]),dL=new Set(["collapsed","card","panel","inline"]),ZS=new Set(["markdown","component"]),cL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ys=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bu=e=>!lL.has(e),eh=e=>typeof e=="string"&&dL.has(e),Js=e=>Object.keys(e).length>0;function zn(e,t,o,n){e.push({path:t,code:o,message:n})}var uL="Ignored because this key is not part of the persisted preference schema.",Wu="Ignored an unsupported value.",pL="Expected collapsed, panel, or inline.",fL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',ew={kind:"mode",message:Wu},li={kind:"string",message:"Expected a CSS length string."},vr={kind:"boolean"},mL={paneWidth:li,paneMaxWidth:li,paneMinWidth:li,expandedPanelWidth:li,resizableMinWidth:li,resizableMaxWidth:li,expandLauncherPanelWhenOpen:vr,resizable:vr},gL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:vr,showReasoning:vr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Wu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Wu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Wu},expandable:vr,grouped:vr}},reasoningDisplay:{kind:"object",children:{expandable:vr,activePreview:vr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ew,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ew,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:ZS,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:ZS}}},filePreview:{kind:"object",children:{enabled:vr}},layout:{kind:"object",children:mL}}}}};function tw(e,t,o,n){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:zn(n,o,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:zn(n,o,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:zn(n,o,"invalid_value",t.message);case"mode":return eh(e)?ko(e):zn(n,o,"invalid_value",t.message);case"modeMap":{if(!Ys(e))return zn(n,o,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[i,d]of Object.entries(e)){let c=r?i:$r(i);Bu(i)&&(r?r.has(i):cL.test(c))?eh(d)?a[c]=ko(d):zn(n,`${o}.${i}`,"invalid_value",pL):zn(n,`${o}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":fL)}return Js(a)?a:void 0}case"object":{if(t.bareMode&&eh(e))return ko(e);if(!Ys(e))return zn(n,o,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=d=>o?`${o}.${d}`:d;for(let d of Object.keys(e))(!Bu(d)||!r.includes(d))&&zn(n,a(d),"unknown_key",uL);let i={};for(let d of r){let c=t.children[d],u=tw(e[d],c,a(d),n);if(c.deprecated&&e[d]!==void 0&&zn(n,a(d),"deprecated_key",c.deprecated),u===void 0)continue;let p=c.alias??d,m=i[p];i[p]=Ys(m)&&Ys(u)?{...m,...u}:u}return Js(i)?i:void 0}}}function th(e){let t=[];return{preferences:(e===null?void 0:tw(e,gL,"",t))??{},issues:t}}function di(e){if(Array.isArray(e))return e.map(di);if(!Ys(e))return e;let t={};for(let[o,n]of Object.entries(e))Bu(o)&&n!==void 0&&(t[o]=di(n));return t}function ow(e,t){let o=di(e);for(let[n,r]of Object.entries(t)){if(!Bu(n)||r===void 0)continue;let a=o[n];o[n]=Ys(a)&&Ys(r)?ow(a,r):di(r)}return o}function hL(e){let t={},o;for(let r of e){let a=th(r).preferences;o=nw(o,a.artifacts?.display),t=ow(t,a)}let n=t;return n.artifacts&&(o!==void 0?n.artifacts.display=o:delete n.artifacts.display),n}function yL(e,t){if(t===void 0)return e===void 0?void 0:di(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byMediaType,...t.byMediaType},a={...n?{default:n}:{},...Js(r)?{byMediaType:r}:{}};return Js(a)?a:void 0}function nw(e,t){if(t===void 0)return e===void 0?void 0:di(e);if(typeof t=="string")return t;let o=typeof e=="string"?{default:e}:e??{},n=t.default??o.default,r={...o.byType,...o.byKind,...t.byType,...t.byKind},a=yL(o.files,t.files),i={...n?{default:n}:{},...Js(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Js(i)?i:void 0}function oh(e={},t){let o=hL(t),n={...e};if(o.showToolCalls!==void 0&&(n.showToolCalls=o.showToolCalls),o.showReasoning!==void 0&&(n.showReasoning=o.showReasoning),o.toolCallDisplay&&(n.toolCallDisplay={...e.toolCallDisplay,...o.toolCallDisplay}),o.reasoningDisplay&&(n.reasoningDisplay={...e.reasoningDisplay,...o.reasoningDisplay}),o.artifacts){let r=e.artifacts??{},a={...r};if(o.artifacts.display!==void 0){let i=nw(r.display,o.artifacts.display);i!==void 0&&(a.display=i)}o.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:o.artifacts.filePreview.enabled}),o.artifacts.layout&&(a.layout={...r.layout,...o.artifacts.layout}),n.artifacts=a}return n}function Fl(e){let t=e.preferences;return!t||!Js(t)?e:{...e,features:oh(e.features??{},[t])}}function bL(e,t){if(!e?.trim())return t;let o=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return o?Math.max(0,Number(o[1])):t}function vL(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function xL(e,t,o){return o<t?t:Math.min(o,Math.max(t,e))}function CL(e,t,o,n){let r=e-n-2*t-o;return Math.max(0,r)}function nh(e,t){let n=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(n);return a?Number(a[1]):8}function rw(e,t,o,n,r,a,i=200){let d=bL(r,200),c=CL(t,o,n,i);c=Math.max(d,c);let u=vL(a);return u!==null&&(c=Math.min(c,u)),xL(e,d,c)}var{setLoader:SL,load:wL,provide:ID,getSync:AL}=gt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")}),sw=SL,aw=wL;var iw=AL;var rh=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let o=this.plugins.get(t);o&&(o.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,o)=>(o.priority??0)-(t.priority??0))}getForInstance(t){let o=this.getAll();if(!t||t.length===0)return o;let n=new Set(t.map(a=>a.id));return[...o.filter(a=>!n.has(a.id)),...t].sort((a,i)=>(i.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Ul=new rh;var lw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ML=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),dw=(e,t,o)=>{if(!lw(e)||!lw(t)||ML.has(o))return t;let n={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete n[r];continue}let a=o?`${o}.${r}`:r;n[r]=dw(e[r],t[r],a)}return n};function Ou(e,t){let o=dw(e,t,"");return Xa(o)}var cw=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>o(r,a)),o=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:o,emit:(r,a)=>{e.get(r)?.forEach(i=>{try{i(a)}catch(d){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var TL=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},EL=e=>{let t=e.trim(),o=t.indexOf("{");if(o===-1)return null;let n=0;for(let r=o;r<t.length;r+=1){let a=t[r];if(a==="{"&&(n+=1),a==="}"&&(n-=1,n===0))return t.slice(o,r+1)}return null},ql=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=TL(e),o=EL(t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||!n.action)return null;let{action:r,...a}=n;return{type:String(r),payload:a,raw:n}}catch{return null}},sh=e=>typeof e=="string"?e:e==null?"":String(e),Zs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:sh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let o=e.payload,n=sh(o.element);if(n&&t.document?.querySelector){let r=t.document.querySelector(n);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:sh(o.text)}}},uw=e=>Array.isArray(e)?e.map(t=>String(t)):[],$l=e=>{let t=new Set(uw(e.getSessionMetadata().processedActionMessageIds)),o=()=>{t=new Set(uw(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let a=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let i=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!i&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let d=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:a.message})||null,null):null;if(!d)return null;t.add(a.message.id),n();let c={action:d,message:a.message};e.emit("action:detected",c);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",c)},m=u(d,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:o}};var PL=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},kL=e=>e.map(t=>({...t,streaming:!1})),LL=e=>e.map(t=>({...t,status:"complete"})),Du=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=t();return o?PL(o.getItem(e)):null},save:o=>{let n=t();if(n)try{let r={...o,messages:o.messages?kL(o.messages):void 0,artifacts:o.artifacts?LL(o.artifacts):void 0};n.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=t();if(o)try{o.removeItem(e)}catch(n){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var IL=e=>{let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},pw=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let o=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("")}catch{}return IL(e)},RL=async(e,t)=>{let o=await pw(e);return{storageKey:`${t}visitor:${o}`,leaseKey:`${t}visitor-init-lock:${o}`,lockName:`persona-visitor-init:${await pw(`${e}\0${t}`)}`}};var fw=(e,t,o)=>{let n="",r="",a="",i=!1,d=!1,c=0,u=null,p=null,m=new Set,h=()=>{if(o||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},y=()=>{let C=h();if(!C)return u;try{return C.getItem(n)}catch{return i=!0,u}},x=(C,L)=>{if(d||C===u)return;let U=u;u=C,c+=1;let Q={previousToken:U,token:C,source:L,revision:c};for(let $ of m)$(Q)},T=C=>{d||C.key!==null&&C.key!==n||x(C.key===null?null:C.newValue??null,"external")},w=(async()=>{let C=await RL(e,t);n=C.storageKey,r=C.leaseKey,a=C.lockName,u=y(),!o&&typeof window<"u"&&window.addEventListener("storage",T)})(),k=C=>new Promise(L=>setTimeout(L,C)),P=()=>{let C=h();if(!C)return null;try{let L=C.getItem(r);if(!L)return null;let U=JSON.parse(L);return typeof U?.expiresAt=="number"&&typeof U?.ownerNonce=="string"?U:null}catch{return null}},H=C=>{let L=h();if(L)try{P()?.ownerNonce===C&&L.removeItem(r)}catch{}},b=C=>new Promise(L=>{let U=setTimeout(Q,C);function Q(){clearTimeout(U),window.removeEventListener("storage",$),L()}function $(E){(E.key===null||E.key===r)&&Q()}window.addEventListener("storage",$)}),A=async C=>{let L=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U=Date.now()+15e3;for(;Date.now()<U;){let Q=h();if(!Q)break;let $=Date.now(),E=P();if(E&&E.expiresAt>$&&E.ownerNonce!==L){await b(Math.min(E.expiresAt-$,500));continue}try{Q.setItem(r,JSON.stringify({ownerNonce:L,expiresAt:$+1e4}))}catch{i=!0;break}if(await k(20+Math.random()*40),P()?.ownerNonce!==L){await b(500);continue}p=L;try{return await C()}finally{p=null,H(L)}}return C()};return{ready:w,async get(){return await w,x(y(),"external"),u},async set(C){await w;let L=h();if(L)try{L.setItem(n,C)}catch{i=!0}x(C,"local")},async clear(){await w;let C=h();if(C)try{C.removeItem(n)}catch{i=!0}x(null,"local")},revision(){return c},subscribe(C){return m.add(C),()=>{m.delete(C)}},async withFirstInitLock(C){await w;let L=globalThis.navigator?.locks;return L?.request?L.request(a,()=>C()):h()?A(C):C()},matches(C,L,U){return C===e&&L===t&&U===o},destroy(){d=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",T),p&&H(p)}}};var{setLoader:HL,load:WL}=gt({fallbackImport:()=>import("@runtypelabs/persona/history-view")}),mw=HL,ah=WL;var ih=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},xr=e=>Object.freeze({...e}),gw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),hw=e=>e?xr(e):null;function yw(e){let{plugins:t,config:o}=e,n=!1,r=!1,a=!1,i=!1,d=null,c=[],u=()=>{for(let b of c.splice(0))try{b()}catch(A){ih("renderHistoryView cleanup",A)}},p=(b,A)=>{for(let C of t){let L=C[b];if(L)try{let U=L(A);if(U)return U}catch(U){ih(b,U)}}return null},m=()=>({presentation:e.getPresentation(),config:o}),h={header:b=>i?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:xr(b.identityStatus),pendingAction:hw(b.pendingAction),copy:xr(b.copy),actions:Object.freeze({close:T.close,startNewConversation:T.startNewConversation}),defaultRenderer:b.defaultRenderer})):null,conversation:b=>i?p("renderHistoryConversation",Object.freeze({...m(),conversation:gw(b.conversation),active:b.active,pending:b.pending,open:b.open,requestDelete:b.requestDelete,defaultRenderer:b.defaultRenderer})):null,state:b=>i?p("renderHistoryState",Object.freeze({...m(),state:xr(b.state),identityStatus:xr(b.identityStatus),copy:xr(b.copy),...b.retry?{retry:b.retry}:{},...b.startNewConversation?{startNewConversation:b.startNewConversation}:{},defaultRenderer:b.defaultRenderer})):null},y=t.flatMap(b=>(b.railSections??[]).map(A=>({...A,placement:A.placement??"above-conversations",items:[],render:C=>A.render(Object.freeze({collapsed:C,presentation:e.getPresentation(),actions:T}))}))),x=e.createView({slots:h,renderDom:!1,onModelChange:()=>H(),railSections:y}),T=Object.freeze({...x.operations,close:e.close}),w=()=>(i=!0,x.setDomRenderEnabled(!0),x.element),k=b=>Object.freeze({conversations:Object.freeze(b.conversations.map(gw)),activeConversationId:b.activeConversationId,state:xr(b.state),pendingAction:hw(b.pendingAction),identityStatus:xr(b.identityStatus),nextCursor:b.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:o,copy:xr(x.copy),actions:T,defaultRenderer:w,requestRender:()=>H(),onCleanup:A=>{c.push(A)}}),P=()=>{i=!1;let b=null;for(let C of t)if(C.renderHistoryView){try{b=C.renderHistoryView(k(x.getModel()))}catch(L){ih("renderHistoryView",L),b=null}if(b)break}let A=!b||b.contains(x.element);return i=A,x.setDomRenderEnabled(A),b??x.element};function H(){if(!(!a||n||r)){r=!0;try{u();let b=P();if(b===d)return;let A=d;d=b,e.onElementChanged(b,A)}finally{r=!1}}}return a=!0,H(),{view:x,get element(){return d??x.element},requestRender:H,dispose:()=>{n=!0,u()}}}var BL=null;function bw(){return BL}var OL=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),DL=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),lh=e=>DL.get(e)??"Conversation history is unavailable right now.";function _L(e){if(e instanceof sn)return e;if(e instanceof qe){let t=OL.get(e.code)??"unavailable";return new sn(t,lh(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new sn("unavailable",lh("unavailable"))}function vw(e){let t=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],n={scopes:o},r=d=>{if(!o.includes(d))throw new sn("unsupported_scope",lh("unsupported_scope"))},a=async(d,c)=>{r(d);try{return await c()}catch(u){throw _L(u)}},i=d=>{let c=!1;return{conversationId:d.session.conversationId??"",conversationRevision:d.session.conversationRevision??"",async commit(){c||(c=!0,d.commit(),await e.onActivationCommitted(d.session))},discard(){c||(c=!0,d.discard())}}};return{capabilities:n,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(d){return t().subscribeHistoryIdentityStatus(d)},subscribeAvailability(d){return t().subscribeHistoryAvailability(d)},async list(d){return a(d.context.scope,async()=>{let c=await t().listConversations({...d.cursor?{cursor:d.cursor}:{},...d.limit!==void 0?{limit:d.limit}:{},...d.targetId?{targetId:d.targetId}:{},scope:d.context.scope});return{items:c.data,nextCursor:c.nextCursor}})},async getPage(d,c){return a(c.context.scope,async()=>{let u=await t().getConversation(d,{...c.cursor?{messageCursor:c.cursor}:{},scope:c.context.scope}),p=cx(u.messages,{...c.beforeCreatedAt?{beforeCreatedAt:c.beforeCreatedAt}:{}});return{summary:u.summary,messages:cl([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(d,c){return a(c.context.scope,async()=>i(await t().prepareConversationSession(d)))},async prepareStartNew(d){return a(d.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(d,c){await a(c.context.scope,()=>t().deleteConversation(d,{scope:c.context.scope}))},async deleteAll(d){return a(d.context.scope,()=>t().deleteAllConversations({...d.targetId!==void 0?{targetId:d.targetId}:{},scope:d.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var NL=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],xw={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function dh(e){if(!e)return xw;let t={...xw};for(let o of NL){let n=e[o];typeof n=="string"&&n.length>0&&(t[o]=n)}return t}var FL="button:not([disabled])";function _u(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,o=Math.random().toString(36).slice(2,8),n=`persona-history-confirm-title-${o}`,r=`persona-history-confirm-desc-${o}`,a=Y("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=Y("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),d=Y("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},Y("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:n},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Y("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Y("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},a,i));for(let u of[a,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";a.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",a.style.background="transparent",a.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let c=Y("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},d);return new Promise(u=>{let p=!1,m=y=>{p||(p=!0,c.removeEventListener("keydown",h,!0),c.remove(),t?.focus(),u(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let x=Array.from(d.querySelectorAll(FL));if(x.length===0)return;let T=x[0],w=x[x.length-1],k=document.activeElement;y.shiftKey&&(k===T||!d.contains(k))?(y.preventDefault(),w.focus()):!y.shiftKey&&k===w&&(y.preventDefault(),T.focus())}c.addEventListener("keydown",h,!0),c.addEventListener("pointerdown",y=>{y.target===c&&m(!1)}),a.addEventListener("click",()=>m(!1)),i.addEventListener("click",()=>m(!0)),e.host.appendChild(c),a.focus()})}var ci=Zt(fc(),1);function UL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function qL(e,t){if(!UL(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:t}}function Nu(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:o=>{let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(o.length<=t)return e;try{let r=(0,ci.parse)(o,ci.STR|ci.OBJ),a=qL(r,o);a&&(e=a)}catch{}return t=o.length,e},reset:()=>{e=null,t=0}}}function Cw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Fu(e,t){let{config:o,message:n,onPropsUpdate:r}=t,a=vn.get(e.component);if(!a){if(Qg.includes(e.component)){Hu().catch(()=>{});let d=I("div","persona-w-full");return d.setAttribute("data-persona-artifact-pending","true"),d}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:n,config:o,updateProps:d=>{r&&r(d)}};try{return a(e.props,i)}catch(d){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,d),null}}function Sw(){let e=Nu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ww(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Vl(e){let t=ww(e);if(!t)return!1;try{let o=JSON.parse(t);return typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"}catch{return!1}}function Uu(e){let t=ww(e);if(!t)return null;try{let o=JSON.parse(t);if(typeof o=="object"&&o!==null&&"component"in o&&typeof o.component=="string"){let n=o;return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t}}}catch{}return null}var $L=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qu(e){let{onSubmit:t,onDismiss:o,title:n="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,ratingLabels:u=$L}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,y.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,y.appendChild(T),h.appendChild(y);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let C=1;C<=5;C++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),L.title=u[C-1],L.dataset.rating=String(C),L.innerHTML=`
41
41
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
42
42
  <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>
43
43
  </svg>
44
- `,L.addEventListener("click",()=>{m=C,k.forEach((F,X)=>{let G=X<C;F.classList.toggle("selected",G),F.setAttribute("aria-checked",X===C-1?"true":"false")})}),k.push(L),w.appendChild(L)}h.appendChild(w);let P=null;if(c){let C=document.createElement("div");C.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=a,P.rows=3,P.setAttribute("aria-label","Additional comments"),C.appendChild(P),h.appendChild(C)}let R=document.createElement("div");R.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=d,b.addEventListener("click",()=>{o?.(),p.remove()});let A=document.createElement("button");return A.type="button",A.className="persona-feedback-btn persona-feedback-btn-submit",A.textContent=i,A.addEventListener("click",async()=>{if(m===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}A.disabled=!0,A.textContent="Submitting...";try{let C=P?.value.trim()||void 0;await t(m,C),p.remove()}catch(C){A.disabled=!1,A.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),R.appendChild(b),R.appendChild(A),h.appendChild(R),p.appendChild(h),p}function qu(e){let{onSubmit:t,onDismiss:o,title:n="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let h=null,y=document.createElement("div");y.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,x.appendChild(T);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,x.appendChild(w),y.appendChild(x);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=u;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,P.appendChild(R),P.appendChild(b);let A=document.createElement("div");A.className="persona-feedback-numbers";let C=[];for(let E=0;E<=10;E++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${E} out of 10`),O.textContent=String(E),O.dataset.rating=String(E),E<=6?O.classList.add("persona-feedback-detractor"):E<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{h=E,C.forEach((D,W)=>{D.classList.toggle("selected",W===E),D.setAttribute("aria-checked",W===E?"true":"false")})}),C.push(O),A.appendChild(O)}k.appendChild(P),k.appendChild(A),y.appendChild(k);let L=null;if(c){let E=document.createElement("div");E.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),E.appendChild(L),y.appendChild(E)}let F=document.createElement("div");F.className="persona-feedback-actions";let X=document.createElement("button");X.type="button",X.className="persona-feedback-btn persona-feedback-btn-skip",X.textContent=d,X.addEventListener("click",()=>{o?.(),m.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=i,G.addEventListener("click",async()=>{if(h===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let E=L?.value.trim()||void 0;await t(h,E),m.remove()}catch(E){G.disabled=!1,G.textContent=i,console.error("[NPS Feedback] Failed to submit:",E)}}),F.appendChild(X),F.appendChild(G),y.appendChild(F),m.appendChild(y),m}var ii="persona-chat-history",VL=30*1e3,jL=641,li="data-persona-composer-reason",zL={"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 KL(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let n of o){if(n.kind!=="file"||!n.type.startsWith("image/"))continue;let r=n.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=zL[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith("image/")&&t.push(n);return t}function $u(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function GL(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function XL(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var dh=e=>!e||typeof e!="object"?{}:{...e},ww=e=>e.map(t=>({...t,streaming:!1})),Aw=(e,t,o)=>{let n=e?.markdown?Zi(e.markdown):null,r=lc(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,i=d=>{let c=d.text??"",u=d.message.rawContent??null;if(t){let h=t.process({text:c,raw:u??c,message:d.message,streaming:d.streaming});h!==null&&(c=h.text,h.persist||(d.message.__skipPersist=!0),h.resubmit&&!d.streaming&&o&&o())}let p=_n()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...d,text:c,raw:u??d.text??""});m=r?r(h):h}else if(n){let h=d.streaming?yv(c):c,y=n(h);m=r&&p?r(y):y}else m=dr(c);return m};return d=>{try{return i(d)}catch(c){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),dr(d.text??"")}}};function Mw(e){let t=I("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",n=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,i=ce(o,n,r,a);if(i&&t.appendChild(i),e?.label){let d=I("span","persona-drop-overlay-label");d.textContent=e.label,t.appendChild(d)}return t}var QL=(e,t)=>{let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];o[n]=a?{...a,...r}:r}return o},YL=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:QL(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),Vu=(e,t,o)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=ja(t),r=()=>{$x({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};r();let a=n.features;n=Nl(n);let i=Fl.getForInstance(n.plugins),d=VC(e),c=[],u=!1,p=NS(()=>n),m=null,h=null,y=null,x=!1,T=null,w=s=>{m=s,s.initApprovalUi({webMcpToolTitle:dc});let l=s.createBuiltInApprovalPlugin();h=l.plugin,y=l.teardown},k=()=>{if(m)return m;let s=jS();return s?(w(s),s):(VS().then(l=>{x||m||(w(l),T?.())}).catch(()=>{}),null)},P=!1,R=!1,b=null,A=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=aw();if(v){v.enhanceWithForms(s,l,f,g);return}sw().then(()=>{P||R||!b||(R=!0,b())}).catch(()=>{})};n.components&&Cn.registerAll(n.components);let C=dw(),F=n.persistState===!1?null:n.storageAdapter??Ou(),X={},G=null,E,O=new Promise(s=>{E=s}),D,W=!1,te=s=>{if(n.onStateLoaded)try{let l=n.onStateLoaded(s);if(l&&typeof l=="object"&&"state"in l){let{state:f,open:g}=l;return g&&(W=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(F?.load)try{let s=F.load();if(s&&typeof s.then=="function")G=s.then(l=>te(l??{messages:[],metadata:{}}));else{let f=te(s??{messages:[],metadata:{}});f.metadata&&(X=dh(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),D=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=te({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}G||E();let Q=()=>X,de=s=>{X=s({...X})??{},wi()},pe=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ul],Ce=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ys.message,Ys.messageAndClick],Ee=ql({parsers:pe,handlers:Ce,getSessionMetadata:Q,updateSessionMetadata:de,emit:C.emit,documentRef:typeof document<"u"?document:null});Ee.syncFromMetadata();let ge=n.launcher?.enabled??!0,Ke=n.launcher?.autoExpand??!1,Bt=n.autoFocusInput??!1,Le=Ke,j=ge,qe=n.layout?.header?.layout,Ge=!1,Ae=()=>Qr(n),De=()=>ge||Ae(),he=Ae()?!1:ge?Ke:!0,gt=!1,dn=null,Js=()=>{gt=!0,dn&&clearTimeout(dn),dn=setTimeout(()=>{gt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),gt=!1)},1e4)},oo=Aw(n,Ee,Js),Xo=n.features?.showReasoning??!0,Sn=n.features?.showToolCalls??!0,Rt=n.features?.showEventStreamToggle??!1,Jr=n.features?.scrollToBottom??{},Ao=n.features?.scrollBehavior??{},wn=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",Zr=`${wn()}event-stream`,po=null,ci=n.features?.eventStream?.maxEvents??2e3,Tt=null,ut=null,cn=null,jl=!1,B=null,ee=!1,S=null,U=0,q=(s,l)=>{Tt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},$=(s,l)=>{ut?.processEvent(s,l),Tt?q(s,l):cn&&(cn.length>=ci&&cn.shift(),cn.push({type:s,payload:l}))},oe=()=>{Tt||!Rt||(cn??(cn=[]),Kg().then(s=>{if(jl||Tt||!Rt)return;po=new s.EventStreamStore(Zr),Tt=new s.EventStreamBuffer(ci,po),ut=ut??new s.ThroughputTracker,po.open().then(()=>Tt?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=cn??[];cn=null;for(let f of l)ut?.processEvent(f.type,f.payload),q(f.type,f.payload)}).catch(()=>{}))};Rt&&oe();let ne=!1,ie=null,xe=()=>{},ht=()=>{},$e=()=>{},Ht=()=>{},wt=()=>{},es=()=>ee||ne&&ie==="panel",Bo={onCopy:s=>{C.emit("message:copy",s),H?.isClientTokenMode()&&H.submitMessageFeedback(s.id,"copy").catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",l)}),n.messageActions?.onCopy?.(s)},onFeedback:s=>{C.emit("message:feedback",s),H?.isClientTokenMode()&&H.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},qt=n.statusIndicator??{},fo=s=>s==="idle"?qt.idleText??Ut.idle:s==="connecting"?qt.connectingText??Ut.connecting:s==="connected"?qt.connectedText??Ut.connected:s==="error"?qt.errorText??Ut.error:s==="paused"?qt.pausedText??Ut.paused:s==="resuming"?qt.resumingText??Ut.resuming:Ut[s];function ao(s,l,f,g){if(!s.hasAttribute(li))if(g==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=l,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=l}let Oo=_S({config:n,showClose:De()}),{wrapper:Xe,panel:we,pillRoot:Xt}=Oo.shell,_e=Oo.panelElements,{container:ue,body:re,messagesWrapper:ke,starterSuggestions:Ku,transcriptSuggestions:ui,suggestions:br,textarea:le,sendButton:Me,composerForm:un,statusText:st,welcomeHost:Mo,welcomeIconHolder:zw,greetingHost:Do,introKicker:Kw,introTitle:Gw,introSubtitle:Xw,closeButton:Ue,iconHolder:Et,headerTitle:vr,headerSubtitle:ts,header:Te,footer:Ie,actionsRow:Qw}=_e,Gu=_e.leftActions,zl=_e.rightActions,An=_e.sendButtonWrapper,wh=_e.setSendButtonMode,se=_e.micButton,_o=_e.micButtonWrapper,At=_e.attachmentButton,To=_e.attachmentButtonWrapper,yt=_e.attachmentInput,Eo=_e.attachmentPreviewsContainer;ue.classList.add("persona-relative"),re.classList.add("persona-relative");let Yw=12,pi=()=>Jr.label??"",Jw=()=>Jr.iconName??"arrow-down",Zw=()=>Jr.enabled!==!1,No=()=>Ao.mode??"anchor-top",xr=()=>No()==="follow"||No()==="anchor-top"&&Si,fi=()=>Ao.anchorTopOffset??16,eA=()=>Ao.restorePosition??"bottom",Ah=()=>Ao.pauseOnInteraction===!0,Mh=()=>Ao.showActivityWhilePinned!==!1,Th=()=>Ao.announce===!0,Xu=()=>Ao.scrollbar??"on-scroll",Ot=I("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Ot.type="button",Ot.style.display="none",Ot.setAttribute("data-persona-scroll-to-bottom","true");let mi=I("span","persona-flex persona-items-center"),Qu=I("span",""),os=I("span","");os.setAttribute("data-persona-scroll-to-bottom-count",""),os.style.display="none",Ot.append(mi,Qu,os),ue.appendChild(Ot);let Qo=I("div","persona-stream-anchor-spacer");Qo.setAttribute("aria-hidden","true"),Qo.setAttribute("data-persona-anchor-spacer",""),Qo.style.flexShrink="0",Qo.style.pointerEvents="none",Qo.style.height="0px",Qo.style.display="none",re.appendChild(Qo);let zn=I("div","persona-sr-only");zn.setAttribute("aria-live","polite"),zn.setAttribute("aria-atomic","true"),zn.setAttribute("role","status"),zn.setAttribute("data-persona-live-region",""),Object.assign(zn.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"}),ue.appendChild(zn);let gi=null,Kl=null,Gl=s=>{!Th()||!s||(Kl=s,gi===null&&(gi=setTimeout(()=>{gi=null,Kl&&Th()&&(zn.textContent=Kl),Kl=null},400)))},Xl="empty",Ql=0,Yu=()=>Ql||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ns=()=>{let l=Ie.style.display==="none"?0:Ie.offsetHeight;Ot.style.bottom=`${l+Yu()+Yw}px`};ns();let Ju=()=>{na||(Ie.style.marginBottom=Ql>0?`${Ql}px`:"")},Yl=()=>{let s=ug(n,Ae()),l=xn(n),g=Ie.style.display==="none"?0:Ie.offsetHeight,v=l.anchor==="center"&&Xl==="empty"?Ml(l.anchorComposerTop)??Ml("44%"):null,M=v===null||Ae()?0:UC({columnHeight:ue.clientHeight,footerHeight:g,fraction:v});e.style.setProperty("--persona-composer-overlay-height",`${g}px`),e.style.setProperty("--persona-composer-lift",`${s==="overlay"?M:0}px`),Ql=s==="block"?M:0,Ju(),ns()},Eh=()=>{let s=!!pi();Ot.setAttribute("aria-label",pi()||"Jump to latest"),Ot.title=pi(),Ot.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),mi.innerHTML="";let l=ce(Jw(),"14px","currentColor",2);l?(mi.appendChild(l),mi.style.display=""):mi.style.display="none",Qu.textContent=pi(),Qu.style.display=s?"":"none"};Eh();let Ze=null,Wt=null,Se=Dx(),tA=s=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};Se.subscribe(tA);let Mn=()=>{Se.setText(le?.value??"")},rs=()=>{Se.setMentionRefs(Wt?.getMentionRefs()??[])},oA=s=>({id:s.id,name:s.file.name,mimeType:s.file.type,size:s.file.size,status:s.status,progress:s.progress,error:s.error}),Ph=s=>{let l=Object.freeze(s.map(oA));Se.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Ap()};Se.setSelectedModelId(n.composer?.selectedModelId);let hi=()=>n.composer?.modes??[],Zs=()=>cC(hi(),n.composer?.modeGroups);{let s=nu(n.composer?.defaultActiveModeIds??[],hi());s.length&&Se.setActiveModeIds(s)}function kh(s){if(Se.getState().selectedModelId!==s){Se.setSelectedModelId(s),Cr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function Jl(s){Se.setActiveModeIds(s),Kn?.render(s,Zs()),ea.forEach(l=>l.repaint()),En?.resolve(),wd(),pn()}function Zu(s){Jl(uC(Se.getState().activeModeIds,s,hi(),n.composer?.modeGroups))}let Cr=null,ep=null,Kn=null,ea=new Map,Sr=null;function Tn(s){Se.setQuote(s),Sr?.render(Se.getState().quote),pn(),Cy()}let Lh=!1;function tp(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Lh&&n.debug===!0&&(Lh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let wr=null;function ta(s){Se.setPendingSubmission(s),wr?.render(Se.getState().pendingSubmission),pn()}let nA=s=>{let l=ea.get(s);if(l)return l;let f=mC({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>hi().filter(g=>g.groupId===s),getActiveIds:()=>Se.getState().activeModeIds,onSelect:g=>Zu(g)});return ea.set(s,f),f},rA=()=>{let s=[],l=Se.getState().activeModeIds,f=new Set;if(hi().forEach((g,v)=>{if(ou(g.groupId,n.composer?.modeGroups)){let M=g.groupId;if(f.has(M))return;f.add(M);let N=nA(M);N.action.order=ng(v),N.action.label=n.composer?.modeGroups?.find(z=>z.id===M)?.label??M,s.push(N.action);return}s.push({id:lC(g.id),kind:"button",placement:"start",order:ng(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>Zu(g.id)})}),n.composer?.models?.length&&!i.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!Cr||ep!==g)&&(ep=g,Cr=aC({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>Se.getState().selectedModelId,onSelect:v=>kh(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(Cr.action)}return s},op=null,Ih=i.find(s=>s.renderHeader);if(Ih?.renderHeader){let s=Ih.renderHeader({config:n,defaultRenderer:()=>{let l=mr({config:n,showClose:De()});return Vs(ue,l,n),l.header},onClose:()=>dt(!1,"user")});if(s){let l=Te;l&&(l.replaceWith(s),Te=s,Oo.header.element=s)}}let Rh=()=>{B&&(re.style.display="none",Ie.parentNode?.insertBefore(B.element,Ie),B.update())},np=()=>{if(!Tt){oe();return}if(ee=!0,B?Rh():Kg().then(l=>{B||!ee||!Tt||(B=l.createEventStreamView({buffer:Tt,getFullHistory:()=>Tt.getAllFromStore(),onClose:()=>oa(),config:n,plugins:i,getThroughput:()=>ut?.getMetric()??{status:"idle"},renderIconByName:ce}),Rh())}).catch(()=>{oa()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Co.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.add(f))}let s=()=>{if(!ee)return;let l=Date.now();l-U>=200&&(B?.update(),U=l),S=requestAnimationFrame(s)};U=0,S=requestAnimationFrame(s),Vt(),C.emit("eventStream:opened",{timestamp:Date.now()})},oa=()=>{if(ee){if(ee=!1,B&&B.element.remove(),re.style.display="",tt){tt.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&tt.classList.remove(l))}S!==null&&(cancelAnimationFrame(S),S=null),Vt(),C.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(Rt){let s=n.features?.eventStream?.classNames,l="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(s?.toggleButton?" "+s.toggleButton:"");tt=I("button",l),tt.style.width="28px",tt.style.height="28px",tt.style.color=Co.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let f=Ft(Na,"18px","currentColor",1.5);f&&tt.appendChild(f);let g=_e.clearChatButtonWrapper,v=_e.closeButtonWrapper,M=g||v;M&&M.parentNode===Te?Te.insertBefore(tt,M):Te.appendChild(tt),tt.addEventListener("click",()=>{ee?oa():np()})}let Hh=s=>{let l=n.attachments;if(!l?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=I("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(l.allowedTypes??fr).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},na=!1,Wh=s=>{let l=i.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=u?H.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>Kb(),storage:p(l.id),onSubmit:v=>{!H||H.isStreaming()||Qd(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Lr()||yt?.click()},models:f?.models,selectedModelId:Se.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>kh(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{op?.()}:void 0})},Bh=Wh(()=>Ks({config:n}).footer);Bh&&(Oo.replaceComposer(Bh),Ie=Oo.composer.footer,na=!0);let ot=null,sA=s=>{un=s.form,le=s.input,An=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(Me=s.sendButton),s.micButton&&(se=s.micButton,_o=s.micButton.parentElement),s.found.status&&(st=s.found.status),s.found.suggestions&&(br=s.found.suggestions),s.attachmentButton&&(At=s.attachmentButton,To=s.attachmentButton.parentElement),yt=s.attachmentInput??null,Eo=s.attachmentPreviews??null,s.found.actionsRow&&(Qw=s.found.actionsRow),Gu=s.found.actionsStart,zl=s.found.actionsEnd};function rp(){let s=le;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;Kc(s,l),f&&s.setAttribute("aria-label",f),zc(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(s)}),Gx(s,jc(n.composer?.maxLines,Ae()?5:3))}let Oh=s=>{ot=Nx(s,{debug:n.debug===!0}),ot&&sA(ot),rp()};Hh(Ie),Oh(Ie),Mn();let yi=Gr(n,Ae());yi&&(ke.style.maxWidth=yi,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",Do.style.maxWidth=yi,Do.style.marginLeft="auto",Do.style.marginRight="auto",Do.style.width="100%",Ku.style.maxWidth=yi,ui.style.maxWidth=yi,ui.style.marginLeft="auto",ui.style.marginRight="auto",ui.style.width="100%");let Dh=()=>{let s=Gr(n,Ae());if(!(!s||Ae()))for(let l of[un,br,Eo,st])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};Dh();let _h=()=>{!n.attachments?.enabled||!yt||!Eo||(Ze?Ze.remountPreviews(Eo):(Ze=Fs.fromConfig(n.attachments,Ph),Ze.setPreviewsContainer(Eo)),ot?.addListener(yt,"change",s=>{let l=s.target;Ze?.handleFileSelect(l.files),l.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(Mw(n.attachments.dropOverlay)))};_h();let aA=()=>Wt?.prefetch(),Nh=()=>{if(!n.contextMentions?.enabled||!le)return;let s=ot?.header??null,l=s?og(s):void 0;if(Wt=OC({config:n,textarea:le,anchor:un??le,getMessages:()=>H.getMessages(),liveRegionHost:ue,chipRow:l}),Wt&&!l){let f=le;f.parentElement?.insertBefore(Wt.contextRow,f)}};Nh();let En=null,iA={getState:()=>Se.getState(),getValue:()=>le?.value??"",setValue:s=>{le&&(le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),Mn())},submit:()=>{AC(ot?.form??null)},openAttachmentPicker:()=>{Lr()||yt?.click()},toggleVoice:()=>{op?.()},requestRender:()=>En?.resolve()},lA=()=>{let s=[];return(Wt?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:$n.mention+g,element:f,managed:!0})}),To&&s.push({id:"core:attachment",placement:"start",order:$n.attachment,element:To}),_o&&s.push({id:"core:mic",placement:"end",order:$n.mic,element:_o}),An&&s.push({id:"core:send",placement:"end",order:$n.send,element:An}),s},Fh=()=>{En?.destroy(),En=nC({getBindings:()=>ot,collect:()=>({builtIns:lA(),configActions:[...rA(),...n.composer?.actions??[]],plugins:i,contributionContext:{config:n,getState:()=>Se.getState(),requestRender:()=>En?.resolve()},debug:n.debug===!0}),actionContext:iA,getState:()=>Se.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),En.resolve()};Fh();let sp=()=>{if(Kn?.destroy(),Kn=null,!Zs().length)return;let s=ot?.header;s&&(Kn=iC({row:og(s),onRemove:l=>Zu(l),initialIds:Se.getState().activeModeIds}),Kn.render(Se.getState().activeModeIds,Zs()))};sp();let Uh=()=>{Sr?.destroy(),Sr=null,wr?.destroy(),wr=null;let s=ot?.header;s&&(Sr=gC({onDismiss:()=>Tn(void 0)}),s.appendChild(Sr.element),Sr.render(Se.getState().quote),tp()==="defer-one"&&(wr=hC({onEdit:()=>BM(),onRemove:()=>ta(void 0)}),s.appendChild(wr.element),wr.render(Se.getState().pendingSubmission)))};Uh();let ap=SC(),dA=()=>{let s=ot?.header?.querySelector(tg);if(s)return s.childElementCount>0;let l=Se.getState();return l.mentionRefs.length>0||nu(l.activeModeIds,Zs()).length>0},qh=()=>!1;function pn(){let s=Se.getState(),l=ap.observe(wC(le),s.text);Ie.toggleAttribute("data-persona-composer-compact",CC({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:dA(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0,dictationActive:qh()}))}function $h(){n.composer?.layout==="single-row"&&!Ae()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}$h(),Se.subscribe(()=>{En?.sync(),Ap(),Cd(),pn(),Cy()}),Cd();let Vh=!1,cA=s=>{if(Vh||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(Vh=!0,console.warn(`[persona] layout.slots.${l.join(" and layout.slots.")} ${l.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let s=n.layout?.slots??{};cA(s);let l=g=>{switch(g){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return ke;case"footer-top":return br;case"composer":return un;case"footer-bottom":return st;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")Te.insertBefore(v,Te.firstChild);else if(g==="header-right")Te.appendChild(v);else{let M=Te.querySelector(".persona-flex-col");M?M.parentNode?.insertBefore(v,M.nextSibling):Te.appendChild(v)}break;case"body-top":{let M=re.querySelector("[data-persona-intro-card]");M?M.replaceWith(v):re.insertBefore(v,re.firstChild);break}case"body-bottom":re.appendChild(v);break;case"footer-top":br.replaceWith(v);break;case"footer-bottom":st.replaceWith(v);break;default:break}};for(let[g,v]of Object.entries(s))if(v)try{let M=v({config:n,defaultContent:()=>l(g)});M&&f(g,M)}catch(M){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${g}":`,M)}})();let jh=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let g=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-bubble-type");if(M==="reasoning")ti.has(v)?ti.delete(v):ti.add(v),FS(v,g);else if(M==="tool")oi.has(v)?oi.delete(v):oi.add(v),qS(v,g,n);else if(M==="approval"&&m){let z=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",V=m.approvalDetailsExpansionState.get(v)??z;m.approvalDetailsExpansionState.set(v,!V),m.updateApprovalDetailsUI(v,g,n)}Dt.delete(v)};ke.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),jh(s))}),ke.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),jh(s))}),ke.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=ke.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),M=zC(v);!M||M===v||(l.setData("text/plain",M),s.preventDefault())});let ip=new Map,zh=null,Kh="idle",uA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},pA=(s,l)=>{let{icon:f,label:g}=uA[l];s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",l==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",l!=="idle"),s.classList.toggle("persona-message-action-loading",l==="loading");let v=ce(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},Gh=()=>{ke.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;pA(l,g&&g===zh?Kh:"idle")})};ke.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest("[data-actions-for]");if(!g)return;let v=g.getAttribute("data-actions-for");if(!v)return;let M=f.getAttribute("data-action");if(M==="copy"){let z=H.getMessages().find(V=>V.id===v);if(z&&Bo.onCopy){let V=z.content||"";navigator.clipboard.writeText(V).then(()=>{f.classList.add("persona-message-action-success");let K=Ft(Fa,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let J=Ft(Ua,14,"currentColor",2);J&&(f.innerHTML="",f.appendChild(J))},2e3)}).catch(K=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",K)}),Bo.onCopy(z)}}else if(M==="read-aloud")H.toggleReadAloud(v);else if(M==="upvote"||M==="downvote"){let z=(ip.get(v)??null)===M,V=M==="upvote"?"thumbs-up":"thumbs-down";if(z){ip.delete(v),f.classList.remove("persona-message-action-active");let K=ce(V,14,"currentColor",2);K&&(f.innerHTML="",f.appendChild(K))}else{let K=M==="upvote"?"downvote":"upvote",J=g.querySelector(`[data-action="${K}"]`);if(J){J.classList.remove("persona-message-action-active");let ct=ce(K==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(J.innerHTML="",J.appendChild(ct))}ip.set(v,M),f.classList.add("persona-message-action-active");let ae=ce(V,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ae)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Je=H.getMessages().find(lt=>lt.id===v);Je&&Bo.onFeedback&&Bo.onFeedback({type:M,messageId:Je.id,message:Je})}}else if(M==="regenerate")Zl?.regenerate(v);else if(M==="edit")Zl?.edit(v);else if(M==="quote")Zl?.quote(v);else if(M?.startsWith(Cu)){let N=M.slice(Cu.length),z=n.messageActions?.custom?.find(K=>K.id===N),V=H.getMessages().find(K=>K.id===v);if(!z||!V)return;try{z.onSelect(V)}catch(K){console.error(`[AgentWidget] messageActions.custom "${N}" onSelect failed:`,K)}}});let Zl=null;ke.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest(".persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-approval-action");if(!M)return;let N=M==="approve"?"approved":"denied",V=H.getMessages().find(J=>J.id===v);if(!V?.approval)return;let K=g.querySelector("[data-approval-buttons]");K&&K.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),V.approval.toolType==="webmcp"?H.resolveWebMcpApproval(v,N):H.resolveApproval(V.approval,N)});let Ve=null,Xh=!1,bi=null,ss=()=>{},vi="none",ed=null,Yo={artifacts:[],selectedId:null},Gn=!1,fn=!1,xi=!1,ra=!1,Qh=()=>ra||Yo.artifacts.some(s=>Nn(n.features?.artifacts,s)==="panel"),td=()=>Yo.artifacts.length>0&&!Gn&&Qh(),it={current:null},lp=(s,l)=>{let f=H.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",M=f?.file,N=f?.artifactType??"markdown";if(!g){let K=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(K){let ae=H.getMessages().find(fe=>fe.id===K);if(ae?.rawContent)try{let fe=JSON.parse(ae.rawContent);g=fe?.props?.markdown,v=fe?.props?.title||v,fe?.props?.file&&typeof fe.props.file=="object"&&(M=fe.props.file),!f&&typeof fe?.props?.artifactType=="string"&&(N=fe.props.artifactType)}catch{}}}return{markdown:g,title:v,file:M,artifactType:N}};ke.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-download-artifact");if(!g||n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:g})===!0)return;let{markdown:M,title:N,file:z}=lp(f,g);if(!M)return;let V=gr();V&&V.triggerArtifactDownload(V.downloadInfoFor({title:N,markdown:M,file:z}))}),ke.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-artifact-custom-action");if(!g)return;let v=f.closest("[data-artifact-inline]"),M=v?null:f.closest("[data-open-artifact]"),N=v?v.getAttribute("data-artifact-inline"):M?.getAttribute("data-open-artifact")??null,V=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(lt=>lt.id===g);if(!V)return;let{markdown:K,title:J,file:ae,artifactType:fe}=lp(f,N??""),Je={artifactId:N,title:J,artifactType:fe,markdown:K,file:ae};try{Promise.resolve(V.onClick(Je)).catch(()=>{})}catch{}}),ke.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-copy-artifact");if(!g)return;let v=H.getArtifactById(g),M=gr();if(!M)return;let N="";if(v)N=M.artifactCopyText(v);else{let{markdown:z,file:V,artifactType:K}=lp(f,g);K==="markdown"&&(N=M.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:z??"",...V?{file:V}:{}}))}N&&navigator.clipboard.writeText(N).then(()=>{let z=Ft(Fa,16,"currentColor",2);z&&(f.replaceChildren(z),setTimeout(()=>{let V=Ft(Ua,16,"currentColor",2);V&&f.replaceChildren(V)},1500))}).catch(()=>{})}),ke.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-expand-artifact-inline");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(Gn=!1,ra=!0,fn=!0,xi=!0,H.selectArtifact(g),mn())}),ke.addEventListener("click",s=>{let l=s.target;if(l.closest("[data-download-artifact]")||l.closest("[data-artifact-custom-action]"))return;let f=l.closest("[data-open-artifact]");if(!f)return;let g=f.getAttribute("data-open-artifact");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(s.preventDefault(),s.stopPropagation(),Gn=!1,ra=!0,H.selectArtifact(g),mn())}),ke.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let l=s.target;!l.hasAttribute("data-open-artifact")&&!l.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),l.click())});let sa=_e.composerOverlay,aa=(s,l,f)=>{let g=l.trim();if(!g||!it.current)return;let v=s.getAttribute("data-tool-call-id")??"",M=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:g,answers:f.structured,values:f.values??(f.source==="multi"?g.split(", "):[g]),isFreeText:M,source:f.source},bubbles:!0,composed:!0})),$r(sa,v);let N=it.current.getMessages().find(z=>z.toolCall?.id===v);N?.agentMetadata?.awaitingLocalTool?it.current.resolveAskUserQuestion(N,f.structured??g):it.current.sendMessage(g)},as=s=>{let l=it.current;if(!l)return;let f=s.getAttribute("data-tool-call-id")??"",g=l.getMessages().find(v=>v.toolCall?.id===f);g&&l.persistAskUserQuestionProgress(g,{answers:mc(s,g),currentIndex:sn(s)})},Yh=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),dp=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=sn(s),f=Ra(s);if(l>=f-1)return;let g=it.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(gc(s,g,n,l+1),as(s))};sa.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let M=g.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),$r(sa,M);let N=it.current?.getMessages().find(z=>z.toolCall?.id===M);N?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(N),it.current?.resolveAskUserQuestion(N,"(dismissed)"));return}if(v==="pick"){let M=f.getAttribute("data-option-label");if(!M)return;let N=g.getAttribute("data-multi-select")==="true",z=qr(g);if(z&&N){let V=Ws(g)[sn(g)],K=new Set(Array.isArray(V)?V:[]);K.has(M)?K.delete(M):K.add(M),Vr(g,Array.from(K)),as(g);return}if(z){Vr(g,M),as(g),dp(g);return}if(N){let V=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",V?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!V);let K=g.querySelector('[data-ask-user-action="submit-multi"]');K&&(K.disabled=Ff(g).length===0);return}aa(g,M,{source:"pick",values:[M]});return}if(v==="submit-multi"){let M=Ff(g);if(M.length===0)return;aa(g,M.join(", "),{source:"multi",values:M});return}if(v==="open-free-text"){let M=g.querySelector('[data-ask-free-text-row="true"]');M&&(M.classList.remove("persona-hidden"),M.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let N=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!N.trim())return;if(qr(g)){Vr(g,N.trim()),as(g),dp(g);return}aa(g,N,{source:"free-text"});return}if(v==="next"||v==="back"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!N)return;let V=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(V){let ae=Ws(g)[sn(g)];(typeof ae!="string"||ae!==V)&&Vr(g,V)}let K=v==="next"?1:-1,J=sn(g)+K;gc(g,N,n,J),as(g);return}if(v==="submit-all"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!N)return;let V=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";V&&Vr(g,V);let K=mc(g,N);it.current.persistAskUserQuestionProgress(N,{answers:K,currentIndex:sn(g)});let J=Yh(K);aa(g,J||"(submitted)",{source:"submit-all",structured:K});return}if(v==="skip"){if(!it.current)return;let M=g.getAttribute("data-tool-call-id")??"",N=it.current.getMessages().find(fe=>fe.toolCall?.id===M);if(!N)return;let z=qr(g),V=sn(g),K=Ra(g),J=V>=K-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),$r(sa,M),N.agentMetadata?.awaitingLocalTool&&(it.current.markAskUserQuestionResolved(N),it.current.resolveAskUserQuestion(N,"(dismissed)"));return}Vr(g,"");let ae=g.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),J){let fe=mc(g,N),Je=Yh(fe);aa(g,Je||"(skipped)",{source:"submit-all",structured:fe});return}gc(g,N,n,V+1),as(g);return}}),sa.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;s.preventDefault();let v=f.value;if(v.trim()){if(qr(g)){Vr(g,v.trim()),as(g),dp(g);return}aa(g,v,{source:"free-text"})}});let Jh=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let l=s.target;if(l?.tagName==="INPUT"||l?.tagName==="TEXTAREA"||l?.isContentEditable)return;let f=sa.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let g=Number(s.key),M=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[g-1];M&&(s.preventDefault(),M.click())};document.addEventListener("keydown",Jh);let Pn=null,bt=null,Ci=null,od=null,nd=()=>{},Zh=!1,rd="",sd="";function cp(){od?.(),od=null}let fA=()=>{let s=ba&&Ts?.isConnected?Ts:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},ey=()=>{if(!Pn||!bt)return;let s=e.classList.contains("persona-artifact-welded-split"),l=e.ownerDocument.defaultView??window,f=l.innerWidth<=640;if(!s||e.classList.contains("persona-artifact-narrow-host")||f){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let g=Pn.firstElementChild;if(!g||g===bt)return;let v=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${v}px`,bt.style.zIndex="5";let M=oh(Pn,l),N=g.offsetWidth+M/2-v/2;bt.style.left=`${Math.max(0,N)}px`},ad=()=>{},mA=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:ge||St(n)},id=()=>!wo(n)||!td()||e.classList.contains("persona-artifact-narrow-host")||mA()||(e.ownerDocument.defaultView??window).innerWidth<jL?"none":Jg(n)?"detached":"welded",mn=()=>{if(!Ve||!wo(n))return;Dl(e,n),_l(e,n),ad();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=we.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=td();Ve.setVisible(f),Ve.update(Yo),Gn?(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),fn=!1,xi=!1):Yo.artifacts.length>0&&Qh()?(Ve.element.classList.remove("persona-hidden"),Ve.setMobileOpen(!0)):(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),fn=!1,xi=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if(Ve.setExpandToggleVisible(g),Ve.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),Ve.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ve.setCustomActions(n.features?.artifacts?.toolbarActions??[]),Ve.setTabFade(n.features?.artifacts?.layout?.tabFade),Ve.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!xi&&(fn=!1),fn!==Zh){let M=Ve.element;fn?(rd=M.style.width,sd=M.style.maxWidth,M.style.removeProperty("width"),M.style.removeProperty("max-width")):(rd&&(M.style.width=rd),sd&&(M.style.maxWidth=sd),rd="",sd=""),Zh=fn}e.classList.toggle("persona-artifact-expanded",fn),Ve.setExpanded(fn);let v=id();v!==vi&&(vi=v,ss()),nd()};if(wo(n)){we.style.position="relative";let s=I("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),l=I("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(ue),Pn=l,l.appendChild(s),we.appendChild(l);let f=v=>{Xh||Ve||(Ve=v.createArtifactPane(n,{onSelect:M=>it.current?.selectArtifact(M),onDismiss:()=>{Gn=!0,mn()},onToggleExpand:()=>{let M=!fn,N=Yo.selectedId??Yo.artifacts[Yo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:N,expanded:M})!==!0&&(fn=M,M||(xi=!1),mn())}}),Ve.element.classList.add("persona-hidden"),l.appendChild(Ve.element),Ve.backdrop&&we.appendChild(Ve.backdrop),nd(),mn())},g=gr();g?f(g):(Qg(()=>{let v=gr();v&&f(v)}),Ru().catch(()=>{})),nd=()=>{if(!Pn||!Ve)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){Ci?.(),Ci=null,cp(),bt&&(bt.remove(),bt=null),Ve.element.style.removeProperty("width"),Ve.element.style.removeProperty("maxWidth");return}if(!bt){let M=I("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");M.setAttribute("role","separator"),M.setAttribute("aria-orientation","vertical"),M.setAttribute("aria-label","Resize artifacts panel"),M.tabIndex=0;let N=e.ownerDocument,z=N.defaultView??window,V=K=>{if(!Ve||K.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;K.preventDefault(),cp();let J=K.clientX,ae=Ve.element.getBoundingClientRect().width,fe=n.features?.artifacts?.layout,Je=ct=>{let Qt=Pn.getBoundingClientRect().width,Nt=e.classList.contains("persona-artifact-welded-split"),Lt=oh(Pn,z),io=Nt?0:M.getBoundingClientRect().width||6,et=ae-(ct.clientX-J),lo=nw(et,Qt,Lt,io,fe?.resizableMinWidth,fe?.resizableMaxWidth,fA());Ve.element.style.width=`${lo}px`,Ve.element.style.maxWidth="none",ey()},lt=()=>{N.removeEventListener("pointermove",Je),N.removeEventListener("pointerup",lt),N.removeEventListener("pointercancel",lt),od=null;try{M.releasePointerCapture(K.pointerId)}catch{}};od=lt,N.addEventListener("pointermove",Je),N.addEventListener("pointerup",lt),N.addEventListener("pointercancel",lt);try{M.setPointerCapture(K.pointerId)}catch{}};M.addEventListener("pointerdown",V),bt=M,Pn.insertBefore(M,Ve.element),Ci=()=>{M.removeEventListener("pointerdown",V)}}if(bt){let M=td();bt.classList.toggle("persona-hidden",!M),ey()}},ad=()=>{if(!ge||!Ve||(n.launcher?.sidebarMode??!1)||St(n)&&Wo(n).reveal==="emerge")return;let M=e.ownerDocument.defaultView??window,N=n.launcher?.mobileFullscreen??!0,z=n.launcher?.mobileBreakpoint??640;if(N&&M.innerWidth<=z||!YS(n,ge))return;let V=n.launcher?.width??n.launcherWidth??zo,K=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";td()?(we.style.width=K,we.style.maxWidth=K):(we.style.width=V,we.style.maxWidth=V)},typeof ResizeObserver<"u"&&(bi=new ResizeObserver(()=>{mn()}),bi.observe(we))}else we.appendChild(ue);Ae()&&Xt&&(_e.peekBanner&&Xt.appendChild(_e.peekBanner),Xt.appendChild(Ie)),e.appendChild(Xe),Xt&&e.appendChild(Xt);let up=()=>{if(Ae()){we.style.width="100%",we.style.maxWidth="100%";let ve=n.launcher?.composerBar??{},Ne=Xe.dataset.state==="expanded",ft=ve.expandedSize??"anchored";if(!(Ne&&ft!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Gt=n.theme?.components?.panel,jo=Kr(n),Rs=(Hs,oc)=>Hs==null||Hs===""?oc:xo(jo,Hs)??Hs,nv="1px solid var(--persona-border)",Mt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Tf="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Rs(Gt?.border,nv),ue.style.borderRadius=Rs(Gt?.borderRadius,Tf),ue.style.boxShadow=Rs(Gt?.shadow,Mt),ue.style.overflow="hidden";return}let s=St(n),l=n.launcher?.sidebarMode??!1,f=s||l||(n.launcher?.fullHeight??!1),g=n.launcher?.enabled===!1,v=n.launcher?.detachedPanel===!0,M=n.theme?.components?.panel,N=Kr(n),z=(ve,Ne)=>ve==null||ve===""?Ne:xo(N,ve)??ve,V=e.ownerDocument.defaultView??window,K=n.launcher?.mobileFullscreen??!0,J=n.launcher?.mobileBreakpoint??640,ae=V.innerWidth<=J,fe=K&&ae&&ge,Je=s&&K&&ae,lt=n.launcher?.position??"bottom-left",ct=lt==="bottom-left"||lt==="top-left",Qt=n.launcher?.zIndex??so,Nt="var(--persona-panel-border, 1px solid var(--persona-border))",Lt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=v&&!fe&&!Je;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let lo=et?Nt:l||fe?"none":Nt,lr=et?Lt:fe?"none":l?ct?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":g?"none":Lt;s&&!fe&&!et&&(lr="none",lo="none");let Wn=et?io:l||fe?"0":io,Bn=z(M?.border,lo),_=z(M?.shadow,lr),We=z(M?.borderRadius,Wn),Oe=id(),me=Oe==="detached",pt=Oe==="welded";e.classList.toggle("persona-artifact-detached-split",me),e.classList.toggle("persona-artifact-welded-split",pt);let jt="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)))))",It=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&wo(n)&&Jg(n)&&g&&!s;e.classList.toggle("persona-artifact-chat-flush",It);let Pe=me||It?"none":_,zt=me?Nt:pt?"none":Bn,Kt=me?io:We;It&&(zt="none",Kt="0");let rn=M?.borderRadius!=null&&M.borderRadius!=="",Re=It&&!rn?"0":We,xt=re.scrollTop;e.style.cssText="",Xe.style.cssText="",we.style.cssText="",ue.style.cssText="",re.style.cssText="",na||(Ie.style.cssText=""),ee&&(re.style.display="none"),(f||g)&&(e.style.minWidth="0");let On=()=>{if(xt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===xt)return;let Ne=re.scrollHeight-re.clientHeight;Ne<=0||(re.scrollTop=Math.min(xt,Ne))})};if(fe){Xe.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"),Xe.style.cssText=`
44
+ `,L.addEventListener("click",()=>{m=C,k.forEach((U,Q)=>{let $=Q<C;U.classList.toggle("selected",$),U.setAttribute("aria-checked",Q===C-1?"true":"false")})}),k.push(L),w.appendChild(L)}h.appendChild(w);let P=null;if(c){let C=document.createElement("div");C.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=a,P.rows=3,P.setAttribute("aria-label","Additional comments"),C.appendChild(P),h.appendChild(C)}let H=document.createElement("div");H.className="persona-feedback-actions";let b=document.createElement("button");b.type="button",b.className="persona-feedback-btn persona-feedback-btn-skip",b.textContent=d,b.addEventListener("click",()=>{o?.(),p.remove()});let A=document.createElement("button");return A.type="button",A.className="persona-feedback-btn persona-feedback-btn-submit",A.textContent=i,A.addEventListener("click",async()=>{if(m===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}A.disabled=!0,A.textContent="Submitting...";try{let C=P?.value.trim()||void 0;await t(m,C),p.remove()}catch(C){A.disabled=!1,A.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),H.appendChild(b),H.appendChild(A),h.appendChild(H),p.appendChild(h),p}function $u(e){let{onSubmit:t,onDismiss:o,title:n="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:i="Submit",skipText:d="Skip",showComment:c=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let h=null,y=document.createElement("div");y.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,x.appendChild(T);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,x.appendChild(w),y.appendChild(x);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=u;let b=document.createElement("span");b.className="persona-feedback-label-high",b.textContent=p,P.appendChild(H),P.appendChild(b);let A=document.createElement("div");A.className="persona-feedback-numbers";let C=[];for(let E=0;E<=10;E++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${E} out of 10`),B.textContent=String(E),B.dataset.rating=String(E),E<=6?B.classList.add("persona-feedback-detractor"):E<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{h=E,C.forEach((D,W)=>{D.classList.toggle("selected",W===E),D.setAttribute("aria-checked",W===E?"true":"false")})}),C.push(B),A.appendChild(B)}k.appendChild(P),k.appendChild(A),y.appendChild(k);let L=null;if(c){let E=document.createElement("div");E.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=a,L.rows=3,L.setAttribute("aria-label","Additional comments"),E.appendChild(L),y.appendChild(E)}let U=document.createElement("div");U.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=d,Q.addEventListener("click",()=>{o?.(),m.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=i,$.addEventListener("click",async()=>{if(h===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let E=L?.value.trim()||void 0;await t(h,E),m.remove()}catch(E){$.disabled=!1,$.textContent=i,console.error("[NPS Feedback] Failed to submit:",E)}}),U.appendChild(Q),U.appendChild($),y.appendChild(U),m.appendChild(y),m}var ui="persona-chat-history",zL=30*1e3,KL=641,pi="data-persona-composer-reason",GL={"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 XL(e){if(!e)return[];let t=[],o=Array.from(e.items??[]);for(let n of o){if(n.kind!=="file"||!n.type.startsWith("image/"))continue;let r=n.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=GL[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith("image/")&&t.push(n);return t}function Vu(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function QL(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function YL(e){try{let t=e==="local"?localStorage:sessionStorage,o="__persist_test__";return t.setItem(o,"1"),t.removeItem(o),t}catch{return null}}var ch=e=>!e||typeof e!="object"?{}:{...e},Aw=e=>e.map(t=>({...t,streaming:!1})),Mw=(e,t,o)=>{let n=e?.markdown?el(e.markdown):null,r=dc(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,i=d=>{let c=d.text??"",u=d.message.rawContent??null;if(t){let h=t.process({text:c,raw:u??c,message:d.message,streaming:d.streaming});h!==null&&(c=h.text,h.persist||(d.message.__skipPersist=!0),h.resubmit&&!d.streaming&&o&&o())}let p=Nn()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...d,text:c,raw:u??d.text??""});m=r?r(h):h}else if(n){let h=d.streaming?bv(c):c,y=n(h);m=r&&p?r(y):y}else m=pr(c);return m};return d=>{try{return i(d)}catch(c){return a||(a=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),pr(d.text??"")}}};function Tw(e){let t=I("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let o=e?.iconName??"upload",n=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,i=ue(o,n,r,a);if(i&&t.appendChild(i),e?.label){let d=I("span","persona-drop-overlay-label");d.textContent=e.label,t.appendChild(d)}return t}var JL=(e,t)=>{let o={...e};for(let[n,r]of Object.entries(t)){let a=o[n];o[n]=a?{...a,...r}:r}return o},ZL=e=>e.reduce((t,o)=>({blocks:[...t.blocks,...o.blocks],contentParts:[...t.contentParts,...o.contentParts],context:JL(t.context,o.context)}),{blocks:[],contentParts:[],context:{}}),ju=(e,t,o)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=Xa(t),r=()=>{Vx({delayMs:n.tooltip?.delayMs??200,skipDelayMs:n.tooltip?.skipDelayMs??300})};r();let a=n.features;n=Fl(n);let i=Ul.getForInstance(n.plugins),d=jC(e),c=[],u=!1,p=FS(()=>n),m=null,h=null,y=null,x=!1,T=null,w=s=>{m=s,s.initApprovalUi({webMcpToolTitle:cc});let l=s.createBuiltInApprovalPlugin();h=l.plugin,y=l.teardown},k=()=>{if(m)return m;let s=zS();return s?(w(s),s):(jS().then(l=>{x||m||(w(l),T?.())}).catch(()=>{}),null)},P=!1,H=!1,b=null,A=(s,l,f,g)=>{if(!s.querySelector("[data-tv-form]"))return;let v=iw();if(v){v.enhanceWithForms(s,l,f,g);return}aw().then(()=>{P||H||!b||(H=!0,b())}).catch(()=>{})};n.components&&vn.registerAll(n.components);let C=cw(),U=n.persistState===!1?null:n.storageAdapter??Du(),Q=!!n.clientToken&&typeof n.reconnectStream!="function",$={},E=null,B,D=new Promise(s=>{B=s}),W,te=!1,X=s=>{if(n.onStateLoaded)try{let l=n.onStateLoaded(s);if(l&&typeof l=="object"&&"state"in l){let{state:f,open:g}=l;return g&&(te=!0),f}return l}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}return s};if(U?.load)try{let s=U.load();if(s&&typeof s.then=="function")E=s.then(l=>X(l??{messages:[],metadata:{}}));else{let f=X(s??{messages:[],metadata:{}});f.metadata&&($=ch(f.metadata)),f.messages?.length&&(n={...n,initialMessages:f.messages}),f.artifacts?.length&&(n={...n,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),W=f.draft}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(n.onStateLoaded)try{let s=X({messages:[],metadata:{}});s.messages?.length&&(n={...n,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}E||B();let fe=()=>$,le=s=>{$=s({...$})??{},ma()},xe=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ql],Re=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Zs.message,Zs.messageAndClick],He=$l({parsers:xe,handlers:Re,getSessionMetadata:fe,updateSessionMetadata:le,emit:C.emit,documentRef:typeof document<"u"?document:null});He.syncFromMetadata();let we=n.launcher?.enabled??!0,pt=n.launcher?.autoExpand??!1,ke=n.autoFocusInput??!1,z=pt,Ve=we,Xe=n.layout?.header?.layout,At=!1,Ie=()=>es(n),Pe=()=>we||Ie(),be=Ie()?!1:we?pt:!0,xn=!1,Cn=null,ea=()=>{xn=!0,Cn&&clearTimeout(Cn),Cn=setTimeout(()=>{xn&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),xn=!1)},1e4)},It=Mw(n,He,ea),Sn=n.features?.showReasoning??!0,zo=n.features?.showToolCalls??!0,so=n.features?.showEventStreamToggle??!1,wn=n.features?.scrollToBottom??{},Ko=n.features?.scrollBehavior??{},an=()=>(typeof n.persistState=="object"?n.persistState?.keyPrefix:void 0)??"persona-",An=`${an()}event-stream`,Kn=null,os=n.features?.eventStream?.maxEvents??2e3,tt=null,Ro=null,ln=null,F=!1,J=null,S=!1,N=null,q=0,V=(s,l)=>{tt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(l)})},oe=(s,l)=>{Ro?.processEvent(s,l),tt?V(s,l):ln&&(ln.length>=os&&ln.shift(),ln.push({type:s,payload:l}))},se=()=>{tt||!so||(ln??(ln=[]),Gg().then(s=>{if(F||tt||!so)return;Kn=new s.EventStreamStore(An),tt=new s.EventStreamBuffer(os,Kn),Ro=Ro??new s.ThroughputTracker,Kn.open().then(()=>tt?.restore()).catch(f=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let l=ln??[];ln=null;for(let f of l)Ro?.processEvent(f.type,f.payload),V(f.type,f.payload)}).catch(()=>{}))};so&&se();let ie=!1,de=null,Ft=()=>{},Be=()=>{},Rt=()=>{},Mt=()=>{},Gn=()=>{},Cr=()=>S||ie&&de==="panel",Ut={onCopy:s=>{C.emit("message:copy",s),R?.isClientTokenMode()&&R.submitMessageFeedback(s.id,"copy").catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",l)}),n.messageActions?.onCopy?.(s)},onFeedback:s=>{C.emit("message:feedback",s),R?.isClientTokenMode()&&R.submitMessageFeedback(s.messageId,s.type).catch(l=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",l)}),n.messageActions?.onFeedback?.(s)}},qt=n.statusIndicator??{},Co=s=>s==="idle"?qt.idleText??Nt.idle:s==="connecting"?qt.connectingText??Nt.connecting:s==="connected"?qt.connectedText??Nt.connected:s==="error"?qt.errorText??Nt.error:s==="paused"?qt.pausedText??Nt.paused:s==="resuming"?qt.resumingText??Nt.resuming:Nt[s];function zl(s,l,f,g){if(!s.hasAttribute(pi))if(g==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=l,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=l}let Ho=NS({config:n,showClose:Pe()}),{wrapper:Ge,panel:Se,pillRoot:Xt}=Ho.shell,Fe=Ho.panelElements,{container:pe,body:ne,messagesWrapper:Ee,starterSuggestions:Gu,transcriptSuggestions:fi,suggestions:Sr,textarea:ce,sendButton:Ae,composerForm:dn,statusText:at,welcomeHost:So,welcomeIconHolder:Kw,greetingHost:Wo,introKicker:Gw,introTitle:Xw,introSubtitle:Qw,closeButton:$e,iconHolder:Tt,headerTitle:wr,headerSubtitle:ns,header:Me,footer:Le,actionsRow:Yw}=Fe,Xu=Fe.leftActions,Kl=Fe.rightActions,Mn=Fe.sendButtonWrapper,Ah=Fe.setSendButtonMode,re=Fe.micButton,Bo=Fe.micButtonWrapper,St=Fe.attachmentButton,wo=Fe.attachmentButtonWrapper,ht=Fe.attachmentInput,Ao=Fe.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ne.classList.add("persona-relative");let Jw=12,mi=()=>wn.label??"",Zw=()=>wn.iconName??"arrow-down",eA=()=>wn.enabled!==!1,Oo=()=>Ko.mode??"anchor-top",Ar=()=>Oo()==="follow"||Oo()==="anchor-top"&&Ai,gi=()=>Ko.anchorTopOffset??16,tA=()=>Ko.restorePosition??"bottom",Mh=()=>Ko.pauseOnInteraction===!0,Th=()=>Ko.showActivityWhilePinned!==!1,Eh=()=>Ko.announce===!0,Qu=()=>Ko.scrollbar??"on-scroll",Wt=I("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let hi=I("span","persona-flex persona-items-center"),Yu=I("span",""),rs=I("span","");rs.setAttribute("data-persona-scroll-to-bottom-count",""),rs.style.display="none",Wt.append(hi,Yu,rs),pe.appendChild(Wt);let Go=I("div","persona-stream-anchor-spacer");Go.setAttribute("aria-hidden","true"),Go.setAttribute("data-persona-anchor-spacer",""),Go.style.flexShrink="0",Go.style.pointerEvents="none",Go.style.height="0px",Go.style.display="none",ne.appendChild(Go);let Xn=I("div","persona-sr-only");Xn.setAttribute("aria-live","polite"),Xn.setAttribute("aria-atomic","true"),Xn.setAttribute("role","status"),Xn.setAttribute("data-persona-live-region",""),Object.assign(Xn.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"}),pe.appendChild(Xn);let yi=null,Gl=null,Xl=s=>{!Eh()||!s||(Gl=s,yi===null&&(yi=setTimeout(()=>{yi=null,Gl&&Eh()&&(Xn.textContent=Gl),Gl=null},400)))},Ql="empty",Yl=0,Ju=()=>Yl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ss=()=>{let l=Le.style.display==="none"?0:Le.offsetHeight;Wt.style.bottom=`${l+Ju()+Jw}px`};ss();let Zu=()=>{aa||(Le.style.marginBottom=Yl>0?`${Yl}px`:"")},Jl=()=>{let s=pg(n,Ie()),l=bn(n),g=Le.style.display==="none"?0:Le.offsetHeight,v=l.anchor==="center"&&Ql==="empty"?Tl(l.anchorComposerTop)??Tl("44%"):null,M=v===null||Ie()?0:qC({columnHeight:pe.clientHeight,footerHeight:g,fraction:v});e.style.setProperty("--persona-composer-overlay-height",`${g}px`),e.style.setProperty("--persona-composer-lift",`${s==="overlay"?M:0}px`),Yl=s==="block"?M:0,Zu(),ss()},Ph=()=>{let s=!!mi();Wt.setAttribute("aria-label",mi()||"Jump to latest"),Wt.title=mi(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),hi.innerHTML="";let l=ue(Zw(),"14px","currentColor",2);l?(hi.appendChild(l),hi.style.display=""):hi.style.display="none",Yu.textContent=mi(),Yu.style.display=s?"":"none"};Ph();let Ze=null,Ht=null,Ce=_x(),oA=s=>{try{pe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:s,bubbles:!0,composed:!0}))}catch{}};Ce.subscribe(oA);let Tn=()=>{Ce.setText(ce?.value??"")},as=()=>{Ce.setMentionRefs(Ht?.getMentionRefs()??[])},nA=s=>({id:s.id,name:s.file.name,mimeType:s.file.type,size:s.file.size,status:s.status,progress:s.progress,error:s.error}),kh=s=>{let l=Object.freeze(s.map(nA));Ce.setAttachments(l);try{n.attachments?.onChange?.(l)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Mp()};Ce.setSelectedModelId(n.composer?.selectedModelId);let bi=()=>n.composer?.modes??[],oa=()=>uC(bi(),n.composer?.modeGroups);{let s=ru(n.composer?.defaultActiveModeIds??[],bi());s.length&&Ce.setActiveModeIds(s)}function Lh(s){if(Ce.getState().selectedModelId!==s){Ce.setSelectedModelId(s),Mr?.repaint();try{n.composer?.onModelChange?.(s)}catch(l){console.error("[AgentWidget] composer.onModelChange failed:",l)}}}function Zl(s){Ce.setActiveModeIds(s),Qn?.render(s,oa()),na.forEach(l=>l.repaint()),Pn?.resolve(),Ad(),cn()}function ep(s){Zl(pC(Ce.getState().activeModeIds,s,bi(),n.composer?.modeGroups))}let Mr=null,tp=null,Qn=null,na=new Map,Tr=null;function En(s){Ce.setQuote(s),Tr?.render(Ce.getState().quote),cn(),Sy()}let Ih=!1;function op(){let s=n.composer?.streamingSubmitBehavior??"block";return s!=="interrupt"?s:n.clientToken?"interrupt":(!Ih&&n.debug===!0&&(Ih=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Er=null;function ra(s){Ce.setPendingSubmission(s),Er?.render(Ce.getState().pendingSubmission),cn()}let rA=s=>{let l=na.get(s);if(l)return l;let f=gC({groupId:s,getGroup:()=>n.composer?.modeGroups?.find(g=>g.id===s),getModes:()=>bi().filter(g=>g.groupId===s),getActiveIds:()=>Ce.getState().activeModeIds,onSelect:g=>ep(g)});return na.set(s,f),f},sA=()=>{let s=[],l=Ce.getState().activeModeIds,f=new Set;if(bi().forEach((g,v)=>{if(nu(g.groupId,n.composer?.modeGroups)){let M=g.groupId;if(f.has(M))return;f.add(M);let _=rA(M);_.action.order=rg(v),_.action.label=n.composer?.modeGroups?.find(K=>K.id===M)?.label??M,s.push(_.action);return}s.push({id:dC(g.id),kind:"button",placement:"start",order:rg(v),presentation:g.presentation??"auto",label:g.label,shortLabel:g.shortLabel,iconName:g.iconName,pressed:l.includes(g.id),onSelect:()=>ep(g.id)})}),n.composer?.models?.length&&!i.some(g=>g.renderComposer)){let g=n.composer?.modelPicker?.presentation??"native";(!Mr||tp!==g)&&(tp=g,Mr=iC({getModels:()=>n.composer?.models??[],getSelectedModelId:()=>Ce.getState().selectedModelId,onSelect:v=>Lh(v),presentation:g,getSuffix:()=>n.composer?.modelPicker?.suffix})),s.push(Mr.action)}return s},np=null,Rh=i.find(s=>s.renderHeader);if(Rh?.renderHeader){let s=Rh.renderHeader({config:n,defaultRenderer:()=>{let l=yr({config:n,showClose:Pe()});return zs(pe,l,n),l.header},onClose:()=>ct(!1,"user")});if(s){let l=Me;l&&(l.replaceWith(s),Me=s,Ho.header.element=s)}}let Hh=()=>{J&&(ne.style.display="none",Le.parentNode?.insertBefore(J.element,Le),J.update())},rp=()=>{if(!tt){se();return}if(S=!0,J?Hh():Gg().then(l=>{J||!S||!tt||(J=l.createEventStreamView({buffer:tt,getFullHistory:()=>tt.getAllFromStore(),onClose:()=>sa(),config:n,plugins:i,getThroughput:()=>Ro?.getMetric()??{status:"idle"},renderIconByName:ue}),Hh())}).catch(()=>{sa()}),ot){ot.style.boxShadow=`inset 0 0 0 1.5px ${bo.actionIconColor}`;let l=n.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&ot.classList.add(f))}let s=()=>{if(!S)return;let l=Date.now();l-q>=200&&(J?.update(),q=l),N=requestAnimationFrame(s)};q=0,N=requestAnimationFrame(s),Vt(),C.emit("eventStream:opened",{timestamp:Date.now()})},sa=()=>{if(S){if(S=!1,J&&J.element.remove(),ne.style.display="",ot){ot.style.boxShadow="";let s=n.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(l=>l&&ot.classList.remove(l))}N!==null&&(cancelAnimationFrame(N),N=null),Vt(),C.emit("eventStream:closed",{timestamp:Date.now()})}},ot=null;if(so){let s=n.features?.eventStream?.classNames,l="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(s?.toggleButton?" "+s.toggleButton:"");ot=I("button",l),ot.style.width="28px",ot.style.height="28px",ot.style.color=bo.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let f=_t($a,"18px","currentColor",1.5);f&&ot.appendChild(f);let g=Fe.clearChatButtonWrapper,v=Fe.closeButtonWrapper,M=g||v;M&&M.parentNode===Me?Me.insertBefore(ot,M):Me.appendChild(ot),ot.addEventListener("click",()=>{S?sa():rp()})}let Wh=s=>{let l=n.attachments;if(!l?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=I("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(l.allowedTypes??hr).join(","),v.multiple=(l.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",l.buttonTooltipText??"Attach files"),s.appendChild(v)}},aa=!1,Bh=s=>{let l=i.find(v=>v.renderComposer);if(!l?.renderComposer)return null;let f=n.composer,g=u?R.isStreaming():!1;return l.renderComposer({config:n,defaultRenderer:s,requestRender:()=>Gb(),storage:p(l.id),onSubmit:v=>{!R||R.isStreaming()||Yd(v.trim(),{consumeDraft:!1})},streaming:g,disabled:g,openAttachmentPicker:()=>{Wr()||ht?.click()},models:f?.models,selectedModelId:Ce.getState().selectedModelId??f?.selectedModelId,onModelChange:v=>Lh(v),onVoiceToggle:n.voiceRecognition?.enabled===!0?()=>{np?.()}:void 0})},Oh=Bh(()=>Xs({config:n}).footer);Oh&&(Ho.replaceComposer(Oh),Le=Ho.composer.footer,aa=!0);let nt=null,aA=s=>{dn=s.form,ce=s.input,Mn=s.sendButton?s.sendButton.parentElement:null,s.sendButton&&(Ae=s.sendButton),s.micButton&&(re=s.micButton,Bo=s.micButton.parentElement),s.found.status&&(at=s.found.status),s.found.suggestions&&(Sr=s.found.suggestions),s.attachmentButton&&(St=s.attachmentButton,wo=s.attachmentButton.parentElement),ht=s.attachmentInput??null,Ao=s.attachmentPreviews??null,s.found.actionsRow&&(Yw=s.found.actionsRow),Xu=s.found.actionsStart,Kl=s.found.actionsEnd};function sp(){let s=ce;if(!s)return;let l=n.composer?.inputAttributes,f=!l?.ariaLabel&&!(s instanceof HTMLTextAreaElement)?s.getAttribute("aria-label"):null;Gc(s,l),f&&s.setAttribute("aria-label",f),Kc(s,{submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Sl(s)}),Xx(s,zc(n.composer?.maxLines,Ie()?5:3))}let Dh=s=>{nt=Fx(s,{debug:n.debug===!0}),nt&&aA(nt),sp()};Wh(Le),Dh(Le),Tn();let vi=Jr(n,Ie());vi&&(Ee.style.maxWidth=vi,Ee.style.marginLeft="auto",Ee.style.marginRight="auto",Ee.style.width="100%",Wo.style.maxWidth=vi,Wo.style.marginLeft="auto",Wo.style.marginRight="auto",Wo.style.width="100%",Gu.style.maxWidth=vi,fi.style.maxWidth=vi,fi.style.marginLeft="auto",fi.style.marginRight="auto",fi.style.width="100%");let _h=()=>{let s=Jr(n,Ie());if(!(!s||Ie()))for(let l of[dn,Sr,Ao,at])l&&(l.style.maxWidth=s,l.style.marginLeft="auto",l.style.marginRight="auto",l.style.width="100%")};_h();let Nh=()=>{!n.attachments?.enabled||!ht||!Ao||(Ze?Ze.remountPreviews(Ao):(Ze=qs.fromConfig(n.attachments,kh),Ze.setPreviewsContainer(Ao)),nt?.addListener(ht,"change",s=>{let l=s.target;Ze?.handleFileSelect(l.files),l.value=""}),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(Tw(n.attachments.dropOverlay)))};Nh();let iA=()=>Ht?.prefetch(),Fh=()=>{if(!n.contextMentions?.enabled||!ce)return;let s=nt?.header??null,l=s?ng(s):void 0;if(Ht=DC({config:n,textarea:ce,anchor:dn??ce,getMessages:()=>R.getMessages(),liveRegionHost:pe,chipRow:l}),Ht&&!l){let f=ce;f.parentElement?.insertBefore(Ht.contextRow,f)}};Fh();let Pn=null,lA={getState:()=>Ce.getState(),getValue:()=>ce?.value??"",setValue:s=>{ce&&(ce.value=s,ce.dispatchEvent(new Event("input",{bubbles:!0})),Tn())},submit:()=>{MC(nt?.form??null)},openAttachmentPicker:()=>{Wr()||ht?.click()},toggleVoice:()=>{np?.()},requestRender:()=>Pn?.resolve()},dA=()=>{let s=[];return(Ht?.affordanceButtons??[]).forEach((f,g)=>{s.push({id:`core:mention-${g}`,placement:"start",order:Vn.mention+g,element:f,managed:!0})}),wo&&s.push({id:"core:attachment",placement:"start",order:Vn.attachment,element:wo}),Bo&&s.push({id:"core:mic",placement:"end",order:Vn.mic,element:Bo}),Mn&&s.push({id:"core:send",placement:"end",order:Vn.send,element:Mn}),s},Uh=()=>{Pn?.destroy(),Pn=rC({getBindings:()=>nt,collect:()=>({builtIns:dA(),configActions:[...sA(),...n.composer?.actions??[]],plugins:i,contributionContext:{config:n,getState:()=>Ce.getState(),requestRender:()=>Pn?.resolve()},debug:n.debug===!0}),actionContext:lA,getState:()=>Ce.getState(),getOverflow:()=>n.composer?.actionOverflow,reportError:(s,l)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${l.actionId}" failed:`,s)}}),Pn.resolve()};Uh();let ap=()=>{if(Qn?.destroy(),Qn=null,!oa().length)return;let s=nt?.header;s&&(Qn=lC({row:ng(s),onRemove:l=>ep(l),initialIds:Ce.getState().activeModeIds}),Qn.render(Ce.getState().activeModeIds,oa()))};ap();let qh=()=>{Tr?.destroy(),Tr=null,Er?.destroy(),Er=null;let s=nt?.header;s&&(Tr=hC({onDismiss:()=>En(void 0)}),s.appendChild(Tr.element),Tr.render(Ce.getState().quote),op()==="defer-one"&&(Er=yC({onEdit:()=>DM(),onRemove:()=>ra(void 0)}),s.appendChild(Er.element),Er.render(Ce.getState().pendingSubmission)))};qh();let ip=wC(),cA=()=>{let s=nt?.header?.querySelector(og);if(s)return s.childElementCount>0;let l=Ce.getState();return l.mentionRefs.length>0||ru(l.activeModeIds,oa()).length>0},$h=()=>!1;function cn(){let s=Ce.getState(),l=ip.observe(AC(ce),s.text);Le.toggleAttribute("data-persona-composer-compact",SC({text:s.text,wrapped:l,hasAttachments:s.attachments.length>0,hasChips:cA(),hasQuote:s.quote!==void 0,hasPendingSubmission:s.pendingSubmission!==void 0,dictationActive:$h()}))}function Vh(){n.composer?.layout==="single-row"&&!Ie()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}Vh(),Ce.subscribe(()=>{Pn?.sync(),Mp(),Sd(),cn(),Sy()}),Sd();let jh=!1,uA=s=>{if(jh||n.debug!==!0)return;let l=["messages","composer"].filter(f=>s[f]);l.length&&(jh=!0,console.warn(`[persona] layout.slots.${l.join(" and layout.slots.")} ${l.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let s=n.layout?.slots??{};uA(s);let l=g=>{switch(g){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return Ee;case"footer-top":return Sr;case"composer":return dn;case"footer-bottom":return at;default:return null}},f=(g,v)=>{switch(g){case"header-left":case"header-center":case"header-right":if(g==="header-left")Me.insertBefore(v,Me.firstChild);else if(g==="header-right")Me.appendChild(v);else{let M=Me.querySelector(".persona-flex-col");M?M.parentNode?.insertBefore(v,M.nextSibling):Me.appendChild(v)}break;case"body-top":{let M=ne.querySelector("[data-persona-intro-card]");M?M.replaceWith(v):ne.insertBefore(v,ne.firstChild);break}case"body-bottom":ne.appendChild(v);break;case"footer-top":Sr.replaceWith(v);break;case"footer-bottom":at.replaceWith(v);break;default:break}};for(let[g,v]of Object.entries(s))if(v)try{let M=v({config:n,defaultContent:()=>l(g)});M&&f(g,M)}catch(M){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${g}":`,M)}})();let zh=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let g=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-bubble-type");if(M==="reasoning")si.has(v)?si.delete(v):si.add(v),US(v,g);else if(M==="tool")ai.has(v)?ai.delete(v):ai.add(v),$S(v,g,n);else if(M==="approval"&&m){let K=((n.approval!==!1?n.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",j=m.approvalDetailsExpansionState.get(v)??K;m.approvalDetailsExpansionState.set(v,!j),m.updateApprovalDetailsUI(v,g,n)}Bt.delete(v)};Ee.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),zh(s))}),Ee.addEventListener("keydown",s=>{let l=s.target;(s.key==="Enter"||s.key===" ")&&l.closest('button[data-expand-header="true"]')&&(s.preventDefault(),zh(s))}),Ee.addEventListener("copy",s=>{let{clipboardData:l}=s;if(!l)return;let f=Ee.getRootNode(),g=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!g||g.isCollapsed)return;let v=g.toString(),M=KC(v);!M||M===v||(l.setData("text/plain",M),s.preventDefault())});let lp=new Map,Kh=null,Gh="idle",pA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},fA=(s,l)=>{let{icon:f,label:g}=pA[l];s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",l==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",l!=="idle"),s.classList.toggle("persona-message-action-loading",l==="loading");let v=ue(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},Xh=()=>{Ee.querySelectorAll('[data-action="read-aloud"]').forEach(l=>{let g=l.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;fA(l,g&&g===Kh?Gh:"idle")})};Ee.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest("[data-actions-for]");if(!g)return;let v=g.getAttribute("data-actions-for");if(!v)return;let M=f.getAttribute("data-action");if(M==="copy"){let K=R.getMessages().find(j=>j.id===v);if(K&&Ut.onCopy){let j=K.content||"";navigator.clipboard.writeText(j).then(()=>{f.classList.add("persona-message-action-success");let G=_t(Va,14,"currentColor",2);G&&(f.innerHTML="",f.appendChild(G)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let Z=_t(ja,14,"currentColor",2);Z&&(f.innerHTML="",f.appendChild(Z))},2e3)}).catch(G=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",G)}),Ut.onCopy(K)}}else if(M==="read-aloud")R.toggleReadAloud(v);else if(M==="upvote"||M==="downvote"){let K=(lp.get(v)??null)===M,j=M==="upvote"?"thumbs-up":"thumbs-down";if(K){lp.delete(v),f.classList.remove("persona-message-action-active");let G=ue(j,14,"currentColor",2);G&&(f.innerHTML="",f.appendChild(G))}else{let G=M==="upvote"?"downvote":"upvote",Z=g.querySelector(`[data-action="${G}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ut=ue(G==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ut&&(Z.innerHTML="",Z.appendChild(ut))}lp.set(v,M),f.classList.add("persona-message-action-active");let ae=ue(j,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ae)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Je=R.getMessages().find(dt=>dt.id===v);Je&&Ut.onFeedback&&Ut.onFeedback({type:M,messageId:Je.id,message:Je})}}else if(M==="regenerate")ed?.regenerate(v);else if(M==="edit")ed?.edit(v);else if(M==="quote")ed?.quote(v);else if(M?.startsWith(Su)){let _=M.slice(Su.length),K=n.messageActions?.custom?.find(G=>G.id===_),j=R.getMessages().find(G=>G.id===v);if(!K||!j)return;try{K.onSelect(j)}catch(G){console.error(`[AgentWidget] messageActions.custom "${_}" onSelect failed:`,G)}}});let ed=null;Ee.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.closest(".persona-approval-bubble");if(!g)return;let v=g.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-approval-action");if(!M)return;let _=M==="approve"?"approved":"denied",j=R.getMessages().find(Z=>Z.id===v);if(!j?.approval)return;let G=g.querySelector("[data-approval-buttons]");G&&G.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),j.approval.toolType==="webmcp"?R.resolveWebMcpApproval(v,_):R.resolveApproval(j.approval,_)});let je=null,Qh=!1,xi=null,is=()=>{},Ci="none",td=null,Xo={artifacts:[],selectedId:null},Yn=!1,un=!1,Si=!1,ia=!1,Yh=()=>ia||Xo.artifacts.some(s=>Fn(n.features?.artifacts,s)==="panel"),od=()=>Xo.artifacts.length>0&&!Yn&&Yh(),lt={current:null},dp=(s,l)=>{let f=R.getArtifactById(l),g=f?.markdown,v=f?.title||"artifact",M=f?.file,_=f?.artifactType??"markdown";if(!g){let G=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(G){let ae=R.getMessages().find(me=>me.id===G);if(ae?.rawContent)try{let me=JSON.parse(ae.rawContent);g=me?.props?.markdown,v=me?.props?.title||v,me?.props?.file&&typeof me.props.file=="object"&&(M=me.props.file),!f&&typeof me?.props?.artifactType=="string"&&(_=me.props.artifactType)}catch{}}}return{markdown:g,title:v,file:M,artifactType:_}};Ee.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-download-artifact");if(!g||n.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:g})===!0)return;let{markdown:M,title:_,file:K}=dp(f,g);if(!M)return;let j=br();j&&j.triggerArtifactDownload(j.downloadInfoFor({title:_,markdown:M,file:K}))}),Ee.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-artifact-custom-action");if(!g)return;let v=f.closest("[data-artifact-inline]"),M=v?null:f.closest("[data-open-artifact]"),_=v?v.getAttribute("data-artifact-inline"):M?.getAttribute("data-open-artifact")??null,j=(v?n.features?.artifacts?.inlineActions:n.features?.artifacts?.cardActions)?.find(dt=>dt.id===g);if(!j)return;let{markdown:G,title:Z,file:ae,artifactType:me}=dp(f,_??""),Je={artifactId:_,title:Z,artifactType:me,markdown:G,file:ae};try{Promise.resolve(j.onClick(Je)).catch(()=>{})}catch{}}),Ee.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-copy-artifact");if(!g)return;let v=R.getArtifactById(g),M=br();if(!M)return;let _="";if(v)_=M.artifactCopyText(v);else{let{markdown:K,file:j,artifactType:G}=dp(f,g);G==="markdown"&&(_=M.artifactCopyText({id:g,artifactType:"markdown",status:"complete",markdown:K??"",...j?{file:j}:{}}))}_&&navigator.clipboard.writeText(_).then(()=>{let K=_t(Va,16,"currentColor",2);K&&(f.replaceChildren(K),setTimeout(()=>{let j=_t(ja,16,"currentColor",2);j&&f.replaceChildren(j)},1500))}).catch(()=>{})}),Ee.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let g=f.getAttribute("data-expand-artifact-inline");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(Yn=!1,ia=!0,un=!0,Si=!0,R.selectArtifact(g),pn())}),Ee.addEventListener("click",s=>{let l=s.target;if(l.closest("[data-download-artifact]")||l.closest("[data-artifact-custom-action]"))return;let f=l.closest("[data-open-artifact]");if(!f)return;let g=f.getAttribute("data-open-artifact");!g||n.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:g})===!0||(s.preventDefault(),s.stopPropagation(),Yn=!1,ia=!0,R.selectArtifact(g),pn())}),Ee.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let l=s.target;!l.hasAttribute("data-open-artifact")&&!l.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),l.click())});let la=Fe.composerOverlay,da=(s,l,f)=>{let g=l.trim();if(!g||!lt.current)return;let v=s.getAttribute("data-tool-call-id")??"",M=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:g,answers:f.structured,values:f.values??(f.source==="multi"?g.split(", "):[g]),isFreeText:M,source:f.source},bubbles:!0,composed:!0})),Kr(la,v);let _=lt.current.getMessages().find(K=>K.toolCall?.id===v);_?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(_,f.structured??g):lt.current.sendMessage(g)},ls=s=>{let l=lt.current;if(!l)return;let f=s.getAttribute("data-tool-call-id")??"",g=l.getMessages().find(v=>v.toolCall?.id===f);g&&l.persistAskUserQuestionProgress(g,{answers:gc(s,g),currentIndex:nn(s)})},Jh=s=>Object.entries(s).map(([l,f])=>`${l}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),cp=s=>{if(n.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let l=nn(s),f=Oa(s);if(l>=f-1)return;let g=lt.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));g&&(hc(s,g,n,l+1),ls(s))};la.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let M=g.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),Kr(la,M);let _=lt.current?.getMessages().find(K=>K.toolCall?.id===M);_?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(_),lt.current?.resolveAskUserQuestion(_,"(dismissed)"));return}if(v==="pick"){let M=f.getAttribute("data-option-label");if(!M)return;let _=g.getAttribute("data-multi-select")==="true",K=zr(g);if(K&&_){let j=Os(g)[nn(g)],G=new Set(Array.isArray(j)?j:[]);G.has(M)?G.delete(M):G.add(M),Gr(g,Array.from(G)),ls(g);return}if(K){Gr(g,M),ls(g),cp(g);return}if(_){let j=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",j?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!j);let G=g.querySelector('[data-ask-user-action="submit-multi"]');G&&(G.disabled=Uf(g).length===0);return}da(g,M,{source:"pick",values:[M]});return}if(v==="submit-multi"){let M=Uf(g);if(M.length===0)return;da(g,M.join(", "),{source:"multi",values:M});return}if(v==="open-free-text"){let M=g.querySelector('[data-ask-free-text-row="true"]');M&&(M.classList.remove("persona-hidden"),M.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let _=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!_.trim())return;if(zr(g)){Gr(g,_.trim()),ls(g),cp(g);return}da(g,_,{source:"free-text"});return}if(v==="next"||v==="back"){if(!lt.current)return;let M=g.getAttribute("data-tool-call-id")??"",_=lt.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!_)return;let j=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(j){let ae=Os(g)[nn(g)];(typeof ae!="string"||ae!==j)&&Gr(g,j)}let G=v==="next"?1:-1,Z=nn(g)+G;hc(g,_,n,Z),ls(g);return}if(v==="submit-all"){if(!lt.current)return;let M=g.getAttribute("data-tool-call-id")??"",_=lt.current.getMessages().find(ae=>ae.toolCall?.id===M);if(!_)return;let j=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";j&&Gr(g,j);let G=gc(g,_);lt.current.persistAskUserQuestionProgress(_,{answers:G,currentIndex:nn(g)});let Z=Jh(G);da(g,Z||"(submitted)",{source:"submit-all",structured:G});return}if(v==="skip"){if(!lt.current)return;let M=g.getAttribute("data-tool-call-id")??"",_=lt.current.getMessages().find(me=>me.toolCall?.id===M);if(!_)return;let K=zr(g),j=nn(g),G=Oa(g),Z=j>=G-1;if(!K){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),Kr(la,M),_.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(_),lt.current.resolveAskUserQuestion(_,"(dismissed)"));return}Gr(g,"");let ae=g.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),Z){let me=gc(g,_),Je=Jh(me);da(g,Je||"(skipped)",{source:"submit-all",structured:me});return}hc(g,_,n,j+1),ls(g);return}}),la.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let g=f.closest("[data-persona-ask-sheet-for]");if(!g)return;s.preventDefault();let v=f.value;if(v.trim()){if(zr(g)){Gr(g,v.trim()),ls(g),cp(g);return}da(g,v,{source:"free-text"})}});let Zh=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let l=s.target;if(l?.tagName==="INPUT"||l?.tagName==="TEXTAREA"||l?.isContentEditable)return;let f=la.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let g=Number(s.key),M=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[g-1];M&&(s.preventDefault(),M.click())};document.addEventListener("keydown",Zh);let kn=null,yt=null,wi=null,nd=null,rd=()=>{},ey=!1,sd="",ad="";function up(){nd?.(),nd=null}let mA=()=>{let s=Sa&&Ps?.isConnected?Ps:null,l=s?s.getBoundingClientRect().width:0;return l<=0?200:l+360},ty=()=>{if(!kn||!yt)return;let s=e.classList.contains("persona-artifact-welded-split"),l=e.ownerDocument.defaultView??window,f=l.innerWidth<=640;if(!s||e.classList.contains("persona-artifact-narrow-host")||f){yt.style.removeProperty("position"),yt.style.removeProperty("left"),yt.style.removeProperty("top"),yt.style.removeProperty("bottom"),yt.style.removeProperty("width"),yt.style.removeProperty("z-index");return}let g=kn.firstElementChild;if(!g||g===yt)return;let v=10;yt.style.position="absolute",yt.style.top="0",yt.style.bottom="0",yt.style.width=`${v}px`,yt.style.zIndex="5";let M=nh(kn,l),_=g.offsetWidth+M/2-v/2;yt.style.left=`${Math.max(0,_)}px`},id=()=>{},gA=()=>{let s=e.ownerDocument.defaultView??window,l=n.launcher?.mobileFullscreen??!0,f=n.launcher?.mobileBreakpoint??640;return!l||s.innerWidth>f?!1:we||Ct(n)},ld=()=>!xo(n)||!od()||e.classList.contains("persona-artifact-narrow-host")||gA()||(e.ownerDocument.defaultView??window).innerWidth<KL?"none":Zg(n)?"detached":"welded",pn=()=>{if(!je||!xo(n))return;_l(e,n),Nl(e,n),id();let s=n.features?.artifacts?.layout?.narrowHostMaxWidth??520,l=Se.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",l>0&&l<=s);let f=od();je.setVisible(f),je.update(Xo),Yn?(je.setMobileOpen(!1),je.element.classList.add("persona-hidden"),je.backdrop?.classList.add("persona-hidden"),un=!1,Si=!1):Xo.artifacts.length>0&&Yh()?(je.element.classList.remove("persona-hidden"),je.setMobileOpen(!0)):(je.setMobileOpen(!1),je.element.classList.add("persona-hidden"),je.backdrop?.classList.add("persona-hidden"),un=!1,Si=!1);let g=n.features?.artifacts?.layout?.showExpandToggle===!0;if(je.setExpandToggleVisible(g),je.setCopyButtonVisible(n.features?.artifacts?.layout?.showCopyButton===!0),je.setRefreshButtonVisible(typeof n.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),je.setCustomActions(n.features?.artifacts?.toolbarActions??[]),je.setTabFade(n.features?.artifacts?.layout?.tabFade),je.setRenderTabBar(n.features?.artifacts?.renderTabBar),!g&&!Si&&(un=!1),un!==ey){let M=je.element;un?(sd=M.style.width,ad=M.style.maxWidth,M.style.removeProperty("width"),M.style.removeProperty("max-width")):(sd&&(M.style.width=sd),ad&&(M.style.maxWidth=ad),sd="",ad=""),ey=un}e.classList.toggle("persona-artifact-expanded",un),je.setExpanded(un);let v=ld();v!==Ci&&(Ci=v,is()),rd()};if(xo(n)){Se.style.position="relative";let s=I("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),l=I("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(pe),kn=l,l.appendChild(s),Se.appendChild(l);let f=v=>{Qh||je||(je=v.createArtifactPane(n,{onSelect:M=>lt.current?.selectArtifact(M),onDismiss:()=>{Yn=!0,pn()},onToggleExpand:()=>{let M=!un,_=Xo.selectedId??Xo.artifacts[Xo.artifacts.length-1]?.id??null;n.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:_,expanded:M})!==!0&&(un=M,M||(Si=!1),pn())}}),je.element.classList.add("persona-hidden"),l.appendChild(je.element),je.backdrop&&Se.appendChild(je.backdrop),rd(),pn())},g=br();g?f(g):(Yg(()=>{let v=br();v&&f(v)}),Hu().catch(()=>{})),rd=()=>{if(!kn||!je)return;if(!(n.features?.artifacts?.layout?.resizable===!0)){wi?.(),wi=null,up(),yt&&(yt.remove(),yt=null),je.element.style.removeProperty("width"),je.element.style.removeProperty("maxWidth");return}if(!yt){let M=I("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");M.setAttribute("role","separator"),M.setAttribute("aria-orientation","vertical"),M.setAttribute("aria-label","Resize artifacts panel"),M.tabIndex=0;let _=e.ownerDocument,K=_.defaultView??window,j=G=>{if(!je||G.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||K.innerWidth<=640)return;G.preventDefault(),up();let Z=G.clientX,ae=je.element.getBoundingClientRect().width,me=n.features?.artifacts?.layout,Je=ut=>{let Qt=kn.getBoundingClientRect().width,Dt=e.classList.contains("persona-artifact-welded-split"),kt=nh(kn,K),ao=Dt?0:M.getBoundingClientRect().width||6,et=ae-(ut.clientX-Z),io=rw(et,Qt,kt,ao,me?.resizableMinWidth,me?.resizableMaxWidth,mA());je.element.style.width=`${io}px`,je.element.style.maxWidth="none",ty()},dt=()=>{_.removeEventListener("pointermove",Je),_.removeEventListener("pointerup",dt),_.removeEventListener("pointercancel",dt),nd=null;try{M.releasePointerCapture(G.pointerId)}catch{}};nd=dt,_.addEventListener("pointermove",Je),_.addEventListener("pointerup",dt),_.addEventListener("pointercancel",dt);try{M.setPointerCapture(G.pointerId)}catch{}};M.addEventListener("pointerdown",j),yt=M,kn.insertBefore(M,je.element),wi=()=>{M.removeEventListener("pointerdown",j)}}if(yt){let M=od();yt.classList.toggle("persona-hidden",!M),ty()}},id=()=>{if(!we||!je||(n.launcher?.sidebarMode??!1)||Ct(n)&&Io(n).reveal==="emerge")return;let M=e.ownerDocument.defaultView??window,_=n.launcher?.mobileFullscreen??!0,K=n.launcher?.mobileBreakpoint??640;if(_&&M.innerWidth<=K||!JS(n,we))return;let j=n.launcher?.width??n.launcherWidth??$o,G=n.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";od()?(Se.style.width=G,Se.style.maxWidth=G):(Se.style.width=j,Se.style.maxWidth=j)},typeof ResizeObserver<"u"&&(xi=new ResizeObserver(()=>{pn()}),xi.observe(Se))}else Se.appendChild(pe);Ie()&&Xt&&(Fe.peekBanner&&Xt.appendChild(Fe.peekBanner),Xt.appendChild(Le)),e.appendChild(Ge),Xt&&e.appendChild(Xt);let pp=()=>{if(Ie()){Se.style.width="100%",Se.style.maxWidth="100%";let ve=n.launcher?.composerBar??{},Ue=Ge.dataset.state==="expanded",mt=ve.expandedSize??"anchored";if(!(Ue&&mt!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let Gt=n.theme?.components?.panel,qo=Yr(n),Ws=(Bs,nc)=>Bs==null||Bs===""?nc:yo(qo,Bs)??Bs,rv="1px solid var(--persona-border)",wt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ef="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Ws(Gt?.border,rv),pe.style.borderRadius=Ws(Gt?.borderRadius,Ef),pe.style.boxShadow=Ws(Gt?.shadow,wt),pe.style.overflow="hidden";return}let s=Ct(n),l=n.launcher?.sidebarMode??!1,f=s||l||(n.launcher?.fullHeight??!1),g=n.launcher?.enabled===!1,v=n.launcher?.detachedPanel===!0,M=n.theme?.components?.panel,_=Yr(n),K=(ve,Ue)=>ve==null||ve===""?Ue:yo(_,ve)??ve,j=e.ownerDocument.defaultView??window,G=n.launcher?.mobileFullscreen??!0,Z=n.launcher?.mobileBreakpoint??640,ae=j.innerWidth<=Z,me=G&&ae&&we,Je=s&&G&&ae,dt=n.launcher?.position??"bottom-left",ut=dt==="bottom-left"||dt==="top-left",Qt=n.launcher?.zIndex??ro,Dt="var(--persona-panel-border, 1px solid var(--persona-border))",kt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",ao="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=v&&!me&&!Je;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let io=et?Dt:l||me?"none":Dt,ur=et?kt:me?"none":l?ut?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":g?"none":kt;s&&!me&&!et&&(ur="none",io="none");let Bn=et?ao:l||me?"0":ao,On=K(M?.border,io),O=K(M?.shadow,ur),De=K(M?.borderRadius,Bn),Ne=ld(),ge=Ne==="detached",ft=Ne==="welded";e.classList.toggle("persona-artifact-detached-split",ge),e.classList.toggle("persona-artifact-welded-split",ft);let jt="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)))))",Lt=(n.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&xo(n)&&Zg(n)&&g&&!s;e.classList.toggle("persona-artifact-chat-flush",Lt);let Te=ge||Lt?"none":O,zt=ge?Dt:ft?"none":On,Kt=ge?ao:De;Lt&&(zt="none",Kt="0");let on=M?.borderRadius!=null&&M.borderRadius!=="",We=Lt&&!on?"0":De,vt=ne.scrollTop;e.style.cssText="",Ge.style.cssText="",Se.style.cssText="",pe.style.cssText="",ne.style.cssText="",aa||(Le.style.cssText=""),S&&(ne.style.display="none"),(f||g)&&(e.style.minWidth="0");let Dn=()=>{if(vt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===vt)return;let Ue=ne.scrollHeight-ne.clientHeight;Ue<=0||(ne.scrollTop=Math.min(vt,Ue))})};if(me){Ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ge.style.cssText=`
45
45
  position: fixed !important;
46
46
  inset: 0 !important;
47
47
  width: 100% !important;
@@ -53,7 +53,7 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
53
53
  flex-direction: column !important;
54
54
  z-index: ${Qt} !important;
55
55
  background-color: var(--persona-surface, #ffffff) !important;
56
- `,we.style.cssText=`
56
+ `,Se.style.cssText=`
57
57
  position: relative !important;
58
58
  display: flex !important;
59
59
  flex-direction: column !important;
@@ -66,7 +66,7 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
66
66
  padding: 0 !important;
67
67
  box-shadow: none !important;
68
68
  border-radius: 0 !important;
69
- `,ue.style.cssText=`
69
+ `,pe.style.cssText=`
70
70
  display: flex !important;
71
71
  flex-direction: column !important;
72
72
  flex: 1 1 0% !important;
@@ -77,7 +77,7 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
77
77
  overflow: hidden !important;
78
78
  border-radius: 0 !important;
79
79
  border: none !important;
80
- `,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ie.style.flexShrink="0",Ju(),Ge=!0,On();return}let Be=n?.launcher?.width??n?.launcherWidth??zo;if(!l&&!s)g&&f?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=Be,we.style.maxWidth=Be);else if(s)if(Wo(n).reveal==="emerge"&&!v){let Ne=Wo(n).width;we.style.width=Ne,we.style.maxWidth=Ne}else we.style.width="100%",we.style.maxWidth="100%";if(ad(),we.style.boxShadow=Pe,we.style.borderRadius=Re,me?we.style.border="none":pt&&(we.style.border=Bn),ue.style.border=zt,ue.style.borderRadius=Kt,ue.style.boxShadow=me&&!It?jt:"",It&&(ue.style.background="transparent",re.style.background="transparent",Ie.style.background="transparent",Ie.style.borderTop="none"),pt){let ve=n.features?.artifacts?.layout;ed=ve?.unifiedSplitOuterRadius?.trim()||ve?.paneBorderRadius?.trim()||We}else ed=null;if(s&&!fe&&!et&&!me&&!pt&&M?.border===void 0&&(ue.style.border="none",Wo(n).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),s&&!fe&&pt&&M?.border===void 0&&(Wo(n).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",g&&(e.style.width="100%"),Xe.style.display="flex",Xe.style.flexDirection="column",Xe.style.flex="1 1 0%",Xe.style.minHeight="0",Xe.style.maxHeight="100%",Xe.style.height="100%",g&&(Xe.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",me||(we.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ie.style.flexShrink="0"),g&&(et||me||It)&&!s&&(It||(Xe.style.padding="var(--persona-panel-inset)"),Xe.style.background="var(--persona-panel-canvas-bg)"),Xe.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"),!l&&!g&&!s&&(Go[lt]??Go["bottom-right"]).split(" ").forEach(Ne=>Xe.classList.add(Ne)),l){let ve=n.launcher?.sidebarWidth??"420px";v?Xe.style.cssText=`
80
+ `,ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Le.style.flexShrink="0",Zu(),At=!0,Dn();return}let _e=n?.launcher?.width??n?.launcherWidth??$o;if(!l&&!s)g&&f?(Se.style.width="100%",Se.style.maxWidth="100%"):(Se.style.width=_e,Se.style.maxWidth=_e);else if(s)if(Io(n).reveal==="emerge"&&!v){let Ue=Io(n).width;Se.style.width=Ue,Se.style.maxWidth=Ue}else Se.style.width="100%",Se.style.maxWidth="100%";if(id(),Se.style.boxShadow=Te,Se.style.borderRadius=We,ge?Se.style.border="none":ft&&(Se.style.border=On),pe.style.border=zt,pe.style.borderRadius=Kt,pe.style.boxShadow=ge&&!Lt?jt:"",Lt&&(pe.style.background="transparent",ne.style.background="transparent",Le.style.background="transparent",Le.style.borderTop="none"),ft){let ve=n.features?.artifacts?.layout;td=ve?.unifiedSplitOuterRadius?.trim()||ve?.paneBorderRadius?.trim()||De}else td=null;if(s&&!me&&!et&&!ge&&!ft&&M?.border===void 0&&(pe.style.border="none",Io(n).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),s&&!me&&ft&&M?.border===void 0&&(Io(n).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",g&&(e.style.width="100%"),Ge.style.display="flex",Ge.style.flexDirection="column",Ge.style.flex="1 1 0%",Ge.style.minHeight="0",Ge.style.maxHeight="100%",Ge.style.height="100%",g&&(Ge.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",ge||(Se.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Le.style.flexShrink="0"),g&&(et||ge||Lt)&&!s&&(Lt||(Ge.style.padding="var(--persona-panel-inset)"),Ge.style.background="var(--persona-panel-canvas-bg)"),Ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!l&&!g&&!s&&(jo[dt]??jo["bottom-right"]).split(" ").forEach(Ue=>Ge.classList.add(Ue)),l){let ve=n.launcher?.sidebarWidth??"420px";v?Ge.style.cssText=`
81
81
  position: fixed !important;
82
82
  top: var(--persona-panel-inset) !important;
83
83
  bottom: var(--persona-panel-inset) !important;
@@ -89,8 +89,8 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
89
89
  display: flex !important;
90
90
  flex-direction: column !important;
91
91
  z-index: ${Qt} !important;
92
- ${ct?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
93
- `:Xe.style.cssText=`
92
+ ${ut?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
93
+ `:Ge.style.cssText=`
94
94
  position: fixed !important;
95
95
  top: 0 !important;
96
96
  bottom: 0 !important;
@@ -102,8 +102,8 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
102
102
  display: flex !important;
103
103
  flex-direction: column !important;
104
104
  z-index: ${Qt} !important;
105
- ${ct?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
106
- `,we.style.cssText=`
105
+ ${ut?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
106
+ `,Se.style.cssText=`
107
107
  position: relative !important;
108
108
  display: flex !important;
109
109
  flex-direction: column !important;
@@ -114,10 +114,10 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
114
114
  min-height: 0 !important;
115
115
  margin: 0 !important;
116
116
  padding: 0 !important;
117
- box-shadow: ${Pe} !important;
118
- border-radius: ${Re} !important;
119
- ${me?"border: none !important;":pt?`border: ${Bn} !important;`:""}
120
- `,we.style.setProperty("width","100%","important"),we.style.setProperty("max-width","100%","important"),ue.style.cssText=`
117
+ box-shadow: ${Te} !important;
118
+ border-radius: ${We} !important;
119
+ ${ge?"border: none !important;":ft?`border: ${On} !important;`:""}
120
+ `,Se.style.setProperty("width","100%","important"),Se.style.setProperty("max-width","100%","important"),pe.style.cssText=`
121
121
  display: flex !important;
122
122
  flex-direction: column !important;
123
123
  flex: 1 1 0% !important;
@@ -128,30 +128,30 @@ _Details: ${o.message}_`:n}var om=e=>({isError:!0,content:[{type:"text",text:e}]
128
128
  overflow: hidden !important;
129
129
  border-radius: ${Kt} !important;
130
130
  border: ${zt} !important;
131
- ${me&&!It?`box-shadow: ${jt} !important;`:""}
132
- ${It?"background: transparent !important;":""}
133
- `,na||(Ie.style.cssText=`
131
+ ${ge&&!Lt?`box-shadow: ${jt} !important;`:""}
132
+ ${Lt?"background: transparent !important;":""}
133
+ `,aa||(Le.style.cssText=`
134
134
  flex-shrink: 0 !important;
135
135
  border-top: none !important;
136
136
  padding: 8px 16px 12px 16px !important;
137
- ${It?"background: transparent !important;":""}
138
- `)}if(!g&&!s){let ve="max-height: -moz-available !important; max-height: stretch !important;",Ne=l?"":"padding-top: 1.25em !important;",ft=l?"":`z-index: ${n.launcher?.zIndex??so} !important;`;Xe.style.cssText+=ve+Ne+ft}Ju(),On()},pp=()=>{e.style.setProperty("--persona-content-max-width",Gr(n,Ae()))},ty=!1,oy=()=>{let s=ug(n,Ae());Ae()&&n.composer?.placement&&n.debug===!0&&!ty&&(ty=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=xn(n);e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",Xl),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??du),Yl()},ny=()=>{if(Ae())return;let s=St(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!ge)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,M=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=M)return;let N=g.innerHeight,z=64,V=n.launcher?.heightOffset??0,K=Math.max(200,N-z),J=Math.min(640,K);we.style.height=`${Math.max(200,J-V)}px`};up(),Us(e,n),Dl(e,n),_l(e,n),pp(),oy(),ss=()=>{up(),ny(),Us(e,n),Dl(e,n),_l(e,n),pp(),oy(),ed?e.style.setProperty("--persona-artifact-welded-outer-radius",ed):e.style.removeProperty("--persona-artifact-welded-outer-radius"),ht(),xe()};let ye=[];ye.push(()=>{Xh=!0}),ye.push(()=>{c.forEach(s=>s()),d.destroy()}),ye.push(()=>{document.removeEventListener("keydown",Jh)}),ye.push(()=>{gi!==null&&clearTimeout(gi)});let kn=null,Ln=null;ye.push(()=>{kn?.(),kn=null,Ln?.(),Ln=null}),bi&&ye.push(()=>{bi?.disconnect(),bi=null}),ye.push(()=>{Ci?.(),Ci=null,cp(),bt&&(bt.remove(),bt=null),Ve?.element.style.removeProperty("width"),Ve?.element.style.removeProperty("maxWidth"),Ve?.destroy()}),Rt&&ye.push(()=>{jl=!0,cn=null,S!==null&&(cancelAnimationFrame(S),S=null),B?.destroy(),B=null,Tt?.destroy(),Tt=null,po=null});let is=null,ry=()=>{is&&(is(),is=null),n.colorScheme==="auto"&&(is=Ka(()=>{Us(e,n)}))};ry(),ye.push(()=>{is&&(is(),is=null)}),ye.push(()=>{x=!0,y?.()}),ye.push(()=>{P=!0});let sy=!1;ye.push(()=>{sy=!0});let fp=(s,l)=>{let f=kl(s,l);return f||!iS.includes(s)?f:(cS().then(g=>{if(sy)return;Ga(g.wipe),Ga(g.glyphCycle);let v=kl(s,l);v&&Rl(v,e)}).catch(()=>{}),null)},ld=n.features?.streamAnimation;if(ld?.type&&ld.type!=="none"){let s=fp(ld.type,ld.plugins);s&&Rl(s,e),ye.push(()=>lS(e))}let Xn=Bl(br),ay=Bl(Ku),iy=Bl(ui),ls=[Xn,ay,iy];ye.push(()=>{ls.forEach(s=>s.destroy())});let ds=null,H,cs=null,ly=!1,dy=0,cy=null,uy=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),py=s=>{for(let l=s.length-1;l>=0;l--)if(Bs(s[l]))return s[l].id??null;return null},fy=!1,gA=()=>{fy||n.debug!==!0||(fy=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},my=!1,gy=!1,hy=(s,l)=>{my||n.debug!==!0||!l.enabled||l.expose||ly||gy&&(H.isStreaming()||s.some(Bs)||(my=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},ia=s=>{if(!H)return;let l=s??H.getMessages(),f=K=>{K.render([],H,le,l)},g=K=>{ls.forEach(J=>{J!==K&&f(J)})};cs&&(uy(l)>dy||py(l)!==cy)&&(cs=null);let v=jr(n);hy(l,v);let M=v.enabled?yc(l):null,N=cs??M,z=cs?"host":"agent";if(N){let K=n.suggestions?.followUps,J=K?.placement??(K?"auto":"composer"),fe=(J==="auto"?Ae()?"composer":"after-message":J)==="after-message"?iy:Xn;g(fe),fe.render(N,H,le,l,n.suggestionChipsConfig,{source:z,surface:"followUp",variant:K?.variant??"chip",behavior:K?.behavior??"send",overflow:K?.overflow??"wrap",maxItems:K?.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}if(l.some(K=>K.role==="user")){ls.forEach(f);return}let V=n.suggestions?.starters;if(V){let K=Yr(xn(n),l),J=V.placement??"auto",ae=J==="auto"?K?"welcome":"composer":J;if(ae==="welcome"&&!K){gA(),ls.forEach(f);return}let fe=ae==="welcome"?ay:Xn;g(fe),fe.render(V.items??n.suggestionChips,H,le,l,n.suggestionChipsConfig,{surface:"starter",variant:V.variant??"card",behavior:V.behavior??"send",overflow:V.overflow??"wrap",maxItems:V.maxItems??4,config:n,plugins:i,submitPrompt:Xd});return}g(Xn),Xn.render(n.suggestionChips,H,le,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:n,plugins:i,submitPrompt:Xd})},yy=()=>{cs&&(cs=null,ia())},hA=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){yy();return}let f=H?H.getMessages():[];cs=l,ly=!0,dy=uy(f),cy=py(f),ia(f)},Fo=!1,Dt=XC(),la=new Map,us=new Map,Ar=new Map,ps=null,Mr=null;function fs(){if(!ps)return;let s=ps;ps=null,Mr?.destroy(),Mr=null,Dt.delete(s),ue.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),H&&Jo(ke,H.getMessages(),oo)}let ms=0,yA=_n()!==null,Uo=eS(),qo=0,Tr=null,Po=!1,dd=!1,Er=0,$t=null,gs=null,mp=!1,da=!1,hs=null,Si=!0,cd=!1,ca=null,ud=!1,ys=()=>{ud=!0,CA()},gp=null,bA=4,Qn=24,vA=80,xA=1e3,Yn=null,by=()=>{e.setAttribute("data-persona-scrollbar",Xu()),Xu()!=="on-scroll"&&(Yn!==null&&clearTimeout(Yn),Yn=null,re.removeAttribute("data-persona-scrollbar-visible"))},CA=()=>{Xu()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Yn!==null&&clearTimeout(Yn),Yn=setTimeout(()=>{Yn=null,qs(re,Qn)&&re.removeAttribute("data-persona-scrollbar-visible")},xA))};by(),ye.push(()=>{Yn!==null&&clearTimeout(Yn)});let hp=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};qh=()=>je.active,pn();let vy=n.voiceRecognition?.autoResume??!1,Jn=s=>{C.emit("voice:state",{active:je.active,source:s,timestamp:Date.now()})},gn=()=>{de(s=>({...s,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},SA=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=dh(X.voiceState),l=!!s.active,f=Number(s.timestamp??0);je.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<VL&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,n.voiceRecognition?.provider?.type==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),Jn("restore"),H.isVoiceActive()&&Ea()}):Jd("restore"))},1e3)},wA=()=>H?ww(H.getMessages()).filter(s=>!s.__skipPersist):[],pd=null,xy=(s,l)=>{typeof console<"u"&&console.error(s,l)},fd=(s,l)=>{let f=()=>{try{let N=s();return!N||typeof N.then!="function"?null:Promise.resolve(N).catch(z=>{xy(l,z)})}catch(N){return xy(l,N),null}},g=pd,v=g?g.then(()=>f()??void 0):f();if(!v)return;let M=v.finally(()=>{pd===M&&(pd=null)});pd=M};function wi(s){if(!F?.save)return;let f={messages:s?ww(s):H?wA():[],metadata:X,artifacts:Yo.artifacts,selectedArtifactId:Yo.selectedId,...bs?{draft:bs}:{}};fd(()=>F.save(f),"[AgentWidget] Failed to persist state:")}let bs,md=()=>!F?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,Ai=xC({write:()=>{if(!md())return;let s=Se.getState(),l=bC({text:s.text,mentionRefs:s.mentionRefs,contentSegments:pf(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(bs)&&(bs=l,wi())}});function Cy(){md()&&Ai.schedule()}function yp(){Ai.flush()}function Sy(s){if(!md())return;let l=vC(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(bs=s,le&&!le.value&&(le.value=l.text,le.dispatchEvent(new Event("input",{bubbles:!0})),Mn()),l.selectedModelId&&(Se.setSelectedModelId(l.selectedModelId),Cr?.repaint()),Jl(l.activeModeIds??[]),l.quote&&Tn(l.quote),Ai.cancel())}function gd(){Ai.cancel(),bs&&(bs=void 0,md()&&wi())}let ua=null,wy=()=>Xe.querySelector("#persona-scroll-container")||re,pa=()=>{ua!==null&&(cancelAnimationFrame(ua),ua=null),Po=!1},Ay=()=>{Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),dd=!1,pa()},AA=()=>Fo&&vp()&&(No()!=="anchor-top"||Mh()),bp=()=>{let s=pi()||"Jump to latest",l=AA();Ot.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Er>0?(os.textContent=String(Er),os.style.display="",Ot.setAttribute("aria-label",`${s} (${Er} new)`)):(os.textContent="",os.style.display="none",Ot.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},My=()=>{Er!==0&&(Er=0,bp())},MA=()=>{let s=$t?.spacerHeight??0;return s<=0?qs(re,Qn):vd(s)-re.scrollTop-re.clientHeight<=Qn},vp=()=>xr()?!Uo.isFollowing():!MA(),xp=()=>!!H&&H.getMessages().length>0,Vt=()=>{if(!Zw()||es()){Ot.parentNode&&Ot.remove(),Ot.style.display="none";return}Ot.parentNode!==ue&&ue.appendChild(Ot),ns();let l=Vn(re)>0&&vp()&&xp();l?bp():My(),Ot.style.display=l?"":"none"},Mi=()=>{Uo.pause()&&(Ay(),Vt())},ko=()=>{Uo.resume(),My(),Vt()},Pr=(s=!1)=>{xr()&&xp()&&Uo.isFollowing()&&(!s&&!Fo||(Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),dd=!0,Tr=requestAnimationFrame(()=>{Tr=null,dd=!1,Uo.isFollowing()&&TA(wy(),s?220:140)})))},Ty=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,M=l(),N=M-v;if(pa(),Math.abs(N)<1){Po=!0,s.scrollTop=M,qo=s.scrollTop,Po=!1;return}let z=performance.now();Po=!0;let V=J=>1-Math.pow(1-J,3),K=J=>{if(!g()){pa();return}let ae=l();ae!==M&&(M=ae,N=M-v);let fe=J-z,Je=Math.min(fe/f,1),lt=V(Je),ct=v+N*lt;s.scrollTop=ct,qo=s.scrollTop,Je<1?ua=requestAnimationFrame(K):(s.scrollTop=M,qo=s.scrollTop,ua=null,Po=!1)};ua=requestAnimationFrame(K)},TA=(s,l=500)=>{let f=Vn(s)-s.scrollTop;if(Math.abs(f)<1){qo=s.scrollTop;return}if(Math.abs(f)>=vA){pa(),Po=!0,s.scrollTop=Vn(s),qo=s.scrollTop,Po=!1;return}Ty(s,()=>Vn(s),l,()=>Uo.isFollowing())},hd=()=>{if(!xp()){Vt();return}let s=wy();Po=!0,s.scrollTop=Vn(s),qo=s.scrollTop,Po=!1,Vt()},vs=s=>{let l=0,f=s;for(;f&&f!==re;)l+=f.offsetTop,f=f.offsetParent;return l},EA=()=>{let s=re.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??re.ownerDocument.getSelection()},yd=()=>nS(EA(),re),Cp=()=>{if(eA()!=="last-user-turn")return!1;let s=H?.getMessages()??[];if(s.length<2)return!1;let l=[...s].reverse().find(M=>M.role==="user");if(!l)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l.id):l.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),g=re.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,vs(g)-fi()),Vn(re));return Po=!0,re.scrollTop=v,qo=re.scrollTop,Po=!1,No()==="follow"&&!qs(re,Qn)&&Uo.pause(),Vt(),!0},bd=s=>{let l=Math.max(0,Math.round(s));Qo.style.height=`${l}px`,Qo.style.display=l>0?"":"none",$t&&($t.spacerHeight=Math.max(0,s))},vd=s=>{let l=parseFloat(getComputedStyle(re).paddingBottom)||0,f=0;for(let v of Array.from(re.children)){if(v===Qo||v.offsetHeight===0)continue;let M=vs(v)+v.offsetHeight;M>f&&(f=M)}let g=re.scrollHeight-s;return f>0?Math.min(f+l,g):g},PA=()=>{if(!$t||$t.spacerHeight<=0)return;let s=vd($t.spacerHeight),l=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-s+Qn);l<$t.spacerHeight&&(bd(l),Vt())},hn=()=>{gs!==null&&(cancelAnimationFrame(gs),gs=null),pa(),$t=null,Qo.style.height="0px",Qo.style.display="none"},Ey=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Sp=s=>re.querySelector(`[data-message-id="${Ey(s)}"]`),Py=s=>{gs!==null&&cancelAnimationFrame(gs),gs=requestAnimationFrame(()=>{gs=null;let l=Ey(s),f=re.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=vs(f),v=$t?.spacerHeight??0,M=vd(v),{targetScrollTop:N,spacerHeight:z}=mg({anchorOffsetTop:g,topOffset:fi(),viewportHeight:re.clientHeight,contentHeight:M,slack:Qn});$t={initialSpacerHeight:z,contentHeightAtAnchor:M,spacerHeight:z},bd(z),Ty(re,()=>f.isConnected?Math.max(0,vs(f)-fi()):N,220)})},Lo=()=>{if(No()!=="anchor-top"||!$t||!ca)return;let s=Sp(ca);if(!s)return;pa();let l=$t.spacerHeight,f=vd(l),{targetScrollTop:g,spacerHeight:v}=mg({anchorOffsetTop:vs(s),topOffset:fi(),viewportHeight:re.clientHeight,contentHeight:f,slack:Qn});$t={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},bd(v),Po=!0,re.scrollTop=g,qo=re.scrollTop,Po=!1,Vt()},kA=()=>{if(xr()){if(!Uo.isFollowing()||qs(re,1))return;Pr(!Fo);return}if($t&&$t.initialSpacerHeight>0){let s=re.scrollHeight-$t.spacerHeight,l=rS({initialSpacerHeight:$t.initialSpacerHeight,contentHeightAtAnchor:$t.contentHeightAtAnchor,currentContentHeight:s});l!==$t.spacerHeight&&bd(l)}Vt()},LA=s=>{let l=No();l==="follow"?(ko(),Pr(!0)):l==="anchor-top"&&(Si=!1,cd=!0,ud=!1,ca=s,Py(s))},IA=()=>{if(No()==="anchor-top"){if(cd){Si=!1;return}Si=!0,hn(),ko(),Pr(!0)}},RA=96,HA=s=>{if(hs===null)return!0;let l=Sp(hs),f=Sp(s);if(!l||!f)return!0;let g=vs(f)-vs(l);return fi()+g>re.clientHeight-RA},WA=s=>{if(No()!=="anchor-top"||!cd||ud||yd())return;let l=hs===null;for(let f of s){if(!l){f.id===hs&&(l=!0);continue}if(ZC(f)){if(f.id===ca||!HA(f.id))return;ca=f.id,Py(f.id);return}}},BA=s=>{let l=new Map;s.forEach(f=>{let g=hp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&(C.emit("assistant:message",f),!da&&(No()!=="anchor-top"||Mh())&&vp()&&(Er+=1,bp(),Vt(),Gl(Er===1?"1 new message below.":`${Er} new messages below.`))),f.role==="assistant"&&g?.streaming&&f.streaming===!1&&C.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(g?f.approval.status!=="pending"&&C.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):C.emit("approval:requested",{approval:f.approval,message:f}))}),hp.clear(),l.forEach((f,g)=>{hp.set(g,f)})},Ti=(s,l)=>{let f=l==="user"?"user":"assistant",g=n.layout?.messages?.[f],v=g?.width??"content",M=g?.maxWidth??(v==="full"?"100%":void 0);s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${l}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",l==="user"),s.setAttribute("data-message-role",l),s.setAttribute("data-message-width",v),M?s.style.setProperty("--persona-message-row-max-width",M):s.style.removeProperty("--persona-message-row-max-width")},Zn=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Ti(f,l),f},OA=(s,l,f)=>{let g=document.createElement("div"),M=(()=>{let _=i.find(We=>We.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),N=(_,We)=>We==null?!1:typeof We=="string"?(_.textContent=We,!0):(_.appendChild(We),!0),z=new Set,V=new Map,K=new Set,J=i.some(_=>_.renderAskUserQuestion),ae=[],fe=[],Je=n.enableComponentStreaming!==!1,lt=n.approval!==!1,ct=[],Qt=n.messageActions,Nt=Qt?.showRegenerate===!0&&Qt.enabled!==!1&&it.current?.isStreaming()!==!0?Sx(l):null,Lt=Qt?.showEdit===!0&&Qt.enabled!==!1,io=Qt?.showQuote===!0&&Qt.enabled!==!1,et=null,lo=n.features?.reasoningDisplay?.completedVisibility==="removed";if(l.forEach(_=>{if(lo&&_.variant==="reasoning"&&_.reasoning?.status==="complete")return;if(z.add(_.id),V.set(_.id,_.role),ps===_.id&&Mr){let Re=Zn(_.id,_.role);Re.setAttribute("data-persona-message-edit-stub","true"),Re.setAttribute("data-preserve-runtime","true"),g.appendChild(Re),et={messageId:_.id,element:Mr.element};return}let We=J&&cr(_),Oe=lt&&_.variant==="approval"&&!!_.approval,me=!We&&_.role==="assistant"&&!_.variant&&Je&&$l(_);!Oe&&Ar.has(_.id)&&(s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Ar.delete(_.id)),!me&&us.has(_.id)&&(s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),us.delete(_.id));let pt=cr(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",jt={canRegenerate:Nt===_.id,canEdit:Lt&&Qf(_),canQuote:io&&!_.variant&&(_.content?.trim().length??0)>0},co=`${jt.canRegenerate?"r":""}${jt.canEdit?"e":""}${jt.canQuote?"q":""}`,uo=GC(_,ms)+pt+`:${co}`,It=We||Oe||me?null:QC(Dt,_.id,uo);if(It){g.appendChild(It.cloneNode(!0)),cr(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(K.add(_.toolCall.id),Ha(_,n,_e.composerOverlay));return}let Pe=null,zt=i.find(Re=>!!(_.variant==="reasoning"&&Re.renderReasoning||_.variant==="tool"&&Re.renderToolCall||!_.variant&&Re.renderMessage)),Kt=n.layout?.messages;if(cr(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){la.delete(_.id),s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(Bs(_)&&jr(n).enabled)return;if(cr(_)&&n.features?.askUserQuestion?.enabled!==!1){let Re=i.find(xt=>typeof xt.renderAskUserQuestion=="function");if(Re&&it.current){let xt=la.get(_.id),On=xt!==uo,yn=null;if(On){let{payload:Ne,complete:ft}=ur(_),Or=_.id,Gt=()=>it.current?.getMessages().find(jo=>jo.id===Or);yn=Re.renderAskUserQuestion({message:_,payload:Ne,complete:ft,resolve:jo=>{let Rs=Gt();Rs&&it.current?.resolveAskUserQuestion(Rs,jo)},dismiss:()=>{let jo=Gt();jo?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(jo),it.current?.resolveAskUserQuestion(jo,"(dismissed)"))},config:n})}let Be=xt!=null;if(On&&yn===null&&!Be){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(K.add(_.toolCall.id),Ha(_,n,_e.composerOverlay));return}let ve=Zn(_.id,_.role);ve.setAttribute("data-ask-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ae.push({messageId:_.id,fingerprint:uo,bubble:yn});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(K.add(_.toolCall.id),Ha(_,n,_e.composerOverlay));return}}else if(Oe){let Re=k();if(!Re){g.appendChild(Zn(_.id,_.role));return}let xt=i.find(ve=>typeof ve.renderApproval=="function")??h,yn=Ar.get(_.id)!==uo,Be=null;if(yn&&xt?.renderApproval){let ve=_.id,Ne=(ft,Or)=>{let Gt=it.current?.getMessages().find(jo=>jo.id===ve);Gt?.approval&&(Gt.approval.toolType==="webmcp"?it.current?.resolveWebMcpApproval(Gt.id,ft):it.current?.resolveApproval(Gt.approval,ft,Or))};Be=xt.renderApproval({message:_,defaultRenderer:()=>Re.createApprovalBubble(_,n),config:n,approve:ft=>Ne("approved",ft),deny:ft=>Ne("denied",ft)})}if(yn&&Be===null)s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Ar.delete(_.id),Pe=Re.createApprovalBubble(_,n);else{let ve=Zn(_.id,_.role);ve.setAttribute("data-approval-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ct.push({messageId:_.id,fingerprint:uo,bubble:Be});return}}else if(zt)if(_.variant==="reasoning"&&_.reasoning&&zt.renderReasoning){if(!Xo)return;Pe=zt.renderReasoning({message:_,defaultRenderer:()=>Vg(_,n),config:n})}else if(_.variant==="tool"&&_.toolCall&&zt.renderToolCall){if(!Sn)return;Pe=zt.renderToolCall({message:_,defaultRenderer:()=>zg(_,n),config:n})}else zt.renderMessage&&(Pe=zt.renderMessage({message:_,defaultRenderer:()=>{let Re=Ja(_,f,Kt,n.messageActions,Bo,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:jt});return _.role!=="user"&&A(Re,_,n,H),Re},config:n}));if(!Pe&&me){let Re=Fu(_);if(Re){let xt=us.get(_.id),On=xt!==uo,yn=n.wrapComponentDirectiveInBubble!==!1&&Cn.getOptions(Re.component)?.bubbleChrome!==!1,Be=null;if(On){let ve=Nu(Re,{config:n,message:_,transform:f});if(ve&&Re.component==="PersonaArtifactInline"){let Ne=ve.hasAttribute("data-artifact-inline")?ve:ve.querySelector("[data-artifact-inline]"),ft=Ne?.getAttribute("data-artifact-inline")??"",Or=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ft):ft,Gt=ft?s.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${Or}"]`)??null:null;Ne&&Gt&&Gt!==Ne&&gr()?.hasLiveInlineArtifactBlock(Gt)&&(Ne===ve?ve=Gt:Ne.replaceWith(Gt))}if(ve)if(yn){let Ne=document.createElement("div");if(Ne.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ne.id=`bubble-${_.id}`,Ne.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let ft=document.createElement("div");ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ft.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Ne.appendChild(ft)}Ne.appendChild(ve),Be=Ne}else{let Ne=document.createElement("div");if(Ne.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ne.id=`bubble-${_.id}`,Ne.setAttribute("data-message-id",_.id),Ne.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let ft=document.createElement("div");ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ft.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Ne.appendChild(ft)}Ne.appendChild(ve),Be=Ne}}if(Be||xt!=null){let ve=Zn(_.id,_.role);ve.setAttribute("data-component-directive-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),fe.push({messageId:_.id,fingerprint:uo,bubble:Be});return}}}if(!Pe)if(_.variant==="reasoning"&&_.reasoning){if(!Xo)return;Pe=Vg(_,n)}else if(_.variant==="tool"&&_.toolCall){if(!Sn)return;Pe=zg(_,n)}else if(_.variant==="approval"&&_.approval){if(n.approval===!1)return;let Re=k();if(!Re)return;Pe=Re.createApprovalBubble(_,n)}else{let Re=n.layout?.messages;Re?.renderUserMessage&&_.role==="user"?Pe=Re.renderUserMessage({message:_,config:n,streaming:!!_.streaming}):Re?.renderAssistantMessage&&_.role==="assistant"?Pe=Re.renderAssistantMessage({message:_,config:n,streaming:!!_.streaming}):Pe=Ja(_,f,Re,n.messageActions,Bo,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:jt}),_.role!=="user"&&Pe&&A(Pe,_,n,H)}let rn=Zn(_.id,_.role);rn.appendChild(Pe),YC(Dt,_.id,uo,rn),g.appendChild(rn)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Oe=We.getAttribute("data-persona-ask-sheet-for");Oe&&!K.has(Oe)&&$r(_e.composerOverlay,Oe)}),n.features?.toolCallDisplay?.grouped){let _=[],We=[],Oe=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(me=>{if(me.variant==="tool"&&me.toolCall&&Sn){We.push(me);return}me.variant==="reasoning"&&(!Xo||lo&&me.reasoning?.status==="complete")||((We.length>1||Oe&&We.length>0)&&_.push(We),We=[])}),(We.length>1||Oe&&We.length>0)&&_.push(We),_.forEach(me=>{let pt=me.map(Kt=>Array.from(g.children).find(rn=>rn instanceof HTMLElement&&rn.getAttribute("data-wrapper-id")===Kt.id)).filter(Kt=>!!Kt);if(pt.length<(Oe?1:2))return;let jt=Zn(`tool-group-${me[0].id}`,"assistant");jt.setAttribute("data-persona-tool-group-row","true");let co=document.createElement("div");co.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",co.setAttribute("data-persona-tool-group","true");let uo=document.createElement("div");uo.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",uo.id=`tool-group-summary-${me[0].id}`;let It=`Called ${me.length} ${me.length===1?"tool":"tools"}`,Pe=n.toolCall?.renderGroupedSummary?.({messages:me,toolCalls:me.map(Kt=>Kt.toolCall).filter(Kt=>!!Kt),defaultSummary:It,config:n});N(uo,Pe)||(uo.textContent=It);let zt=document.createElement("div");zt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.id=`tool-group-stack-${me[0].id}`,zt.setAttribute("data-persona-tool-group-stack","true"),co.appendChild(uo),Oe||co.appendChild(zt),jt.appendChild(co),pt[0].before(jt),pt.forEach((Kt,rn)=>{if(Oe){Kt.remove();return}Kt.style.setProperty("--persona-message-row-max-width","100%");let Re=document.createElement("div");Re.className="persona-tool-group-item persona-relative",Re.setAttribute("data-persona-tool-group-item","true"),rn<pt.length-1&&Re.setAttribute("data-persona-tool-group-connector","true"),Re.appendChild(Kt),zt.appendChild(Re)})})}JC(Dt,z);let lr=l.some(_=>_.role==="assistant"&&_.streaming),Wn=l[l.length-1],Bn=Wn?.role==="assistant"&&!Wn.streaming&&Wn.variant!=="approval";if(Fo&&l.some(_=>_.role==="user")&&!lr&&!Bn){let _={config:n,streaming:!0,location:"standalone",defaultRenderer:Gs},We=i.find(me=>me.renderLoadingIndicator),Oe=null;if(We?.renderLoadingIndicator&&(Oe=We.renderLoadingIndicator(_)),Oe===null&&n.loadingIndicator?.render&&(Oe=n.loadingIndicator.render(_)),Oe===null&&(Oe=Gs()),Oe){let me=document.createElement("div"),pt=n.loadingIndicator?.showBubble!==!1,jt=n.layout?.messages?.layout??"bubble";me.className=pt?Ol("assistant",jt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),me.setAttribute("data-typing-indicator","true"),pt&&(me.style.color="var(--persona-message-assistant-text, var(--persona-text))",jt!=="flat"&&(me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),me.appendChild(Oe);let co=Zn("typing-indicator","assistant");co.appendChild(me),g.appendChild(co)}}if(!Fo&&l.length>0){let _=l[l.length-1],We={config:n,lastMessage:_,messageCount:l.length},Oe=i.find(pt=>pt.renderIdleIndicator),me=null;if(Oe?.renderIdleIndicator&&(me=Oe.renderIdleIndicator(We)),me===null&&n.loadingIndicator?.renderIdle&&(me=n.loadingIndicator.renderIdle(We)),me){let pt=document.createElement("div"),jt=n.loadingIndicator?.showBubble!==!1;pt.className=jt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),pt.setAttribute("data-idle-indicator","true"),pt.appendChild(me);let co=Zn("idle-indicator","assistant");co.appendChild(pt),g.appendChild(co)}}if(Cv(g),fu(s,g),Lf(s),et){let{messageId:_,element:We}=et,Oe=s.querySelector(`#wrapper-${_}`);Oe&&We.parentElement!==Oe&&(Ti(Oe,V.get(_)??"user"),Oe.replaceChildren(We))}if(ae.length>0)for(let{messageId:_,fingerprint:We,bubble:Oe}of ae){let me=s.querySelector(`#wrapper-${_}`);me&&(Ti(me,V.get(_)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),la.set(_,We)))}if(la.size>0)for(let _ of la.keys())z.has(_)||la.delete(_);if(fe.length>0)for(let{messageId:_,fingerprint:We,bubble:Oe}of fe){let me=s.querySelector(`#wrapper-${_}`);me&&(Ti(me,V.get(_)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),us.set(_,We)))}if(us.size>0)for(let _ of us.keys())z.has(_)||us.delete(_);if(ct.length>0)for(let{messageId:_,fingerprint:We,bubble:Oe}of ct){let me=s.querySelector(`#wrapper-${_}`);me&&(Ti(me,V.get(_)??"assistant"),Oe!==null&&(me.replaceChildren(Oe),me.setAttribute("data-bubble-fp",We),Ar.set(_,We)))}if(Ar.size>0)for(let _ of Ar.keys())z.has(_)||Ar.delete(_)},wp=!1,xd=()=>{wp||(wp=!0,ic().catch(()=>{wp=!1}))},Jo=(s,l,f)=>{l.length>0&&xd(),OA(s,l,f),Gh()},Ei=null,DA=()=>{if(Ei)return;let s=f=>{let g=f.composedPath();g.includes(Xe)||Xt&&g.includes(Xt)||dt(!1,"user")};Ei=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},ky=()=>{if(!Ei)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ei,!0),Ei=null};ye.push(()=>ky());let Pi=null,_A=()=>{if(Pi)return;let s=f=>{f.key==="Escape"&&(f.isComposing||dt(!1,"user"))};Pi=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Ly=()=>{if(!Pi)return;(e.ownerDocument??document).removeEventListener("keydown",Pi,!0),Pi=null};ye.push(()=>Ly());let ki=!1,Iy=new Set,NA=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},fa=()=>{if(!Ae())return;let s=_e.peekBanner,l=_e.peekTextNode;if(!s||!l)return;if(he){s.classList.remove("persona-pill-peek--visible");return}let f=H?.getMessages()??[],g;for(let Nt=f.length-1;Nt>=0;Nt--){let Lt=f[Nt];if(Lt.role==="assistant"&&Lt.content){g=Lt;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,M=!!g.streaming,N=NA(),z=mu(N),V=z.type!=="none"?fp(z.type,N?.plugins):null,K=V?.isAnimating?.(g)===!0,J=V!==null&&(M||K);J&&V&&!Iy.has(V.name)&&(Rl(V,e),Iy.add(V.name));let ae=J&&V?.containerClass?V.containerClass:null,fe=l.dataset.personaPeekStreamClass??null;fe&&fe!==ae&&(l.classList.remove(fe),delete l.dataset.personaPeekStreamClass),ae&&fe!==ae&&(l.classList.add(ae),l.dataset.personaPeekStreamClass=ae),J?(l.style.setProperty("--persona-stream-step",`${z.speed}ms`),l.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Je=J?gu(v,z.buffer,V,g,M):v;if(J&&z.placeholder==="skeleton"&&M&&(!Je||!Je.trim())){let Nt=document.createElement("div"),Lt=Il();Lt.classList.add("persona-pill-peek__skeleton"),Nt.appendChild(Lt),fu(l,Nt)}else{let Nt=Math.max(0,Je.length-100),Lt=Je.length>100?Je.slice(-100):Je,io=dr(Lt);if(!J||!V){let et=Je.length>100?`\u2026${Lt}`:Lt;l.textContent!==et&&(l.textContent=et)}else{let et=io;(V.wrap==="char"||V.wrap==="word")&&(et=Ll(io,V.wrap,`peek-${g.id}`,{skipTags:V.skipTags,startIndex:Nt}));let lo=document.createElement("div");if(lo.innerHTML=et,V.useCaret&&Lt.length>0){let lr=hu(),Wn=lo.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bn=Wn[Wn.length-1];Bn?.parentNode?Bn.parentNode.insertBefore(lr,Bn.nextSibling):lo.appendChild(lr)}fu(l,lo),V.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:z.speed,duration:z.duration})}}let Qt=Fo||ki;s.classList.toggle("persona-pill-peek--visible",Qt)};if(Ae()){let s=_e.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),dt(!0,"user")};s.addEventListener("pointerdown",g),ye.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{ki||(ki=!0,fa())},f=()=>{ki&&(ki=!1,fa())};we.addEventListener("pointerenter",l),we.addEventListener("pointerleave",f),ye.push(()=>{we.removeEventListener("pointerenter",l),we.removeEventListener("pointerleave",f)}),Xt&&(Xt.addEventListener("pointerenter",l),Xt.addEventListener("pointerleave",f),ye.push(()=>{Xt.removeEventListener("pointerenter",l),Xt.removeEventListener("pointerleave",f)}))}let FA=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,M=l.expandedMaxWidth??"880px",N=l.expandedTopOffset??"5vh",z=l.modalMaxWidth??"880px",V=l.modalMaxHeight??"min(90vh, 800px)",K="calc(100vw - 32px)",J="var(--persona-pill-area-height, 80px)",ae=Xe.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Xt){let fe=Xt.style;fe.bottom=g,fe.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=z,ae.maxWidth=K,ae.maxHeight=V,ae.height=V;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${g} + ${J})`,ae.top=N,ae.width=M,ae.maxWidth=K}},Li=()=>{if(he&&xd(),!De())return;if(Ae()){let K=(n.launcher?.composerBar??{}).expandedSize??"anchored",J=he?"expanded":"collapsed";Xe.dataset.state=J,Xe.dataset.expandedSize=K,Xt&&(Xt.dataset.state=J,Xt.dataset.expandedSize=K),Xe.style.removeProperty("display"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),FA(he),ue.style.display=he?"flex":"none",ss(),he?(DA(),_A()):(ky(),Ly()),fa();return}let s=St(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,M=g&&v&&ge,N=Wo(n).reveal;he?(Xe.style.removeProperty("display"),Xe.style.display=s?"flex":"",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),Pt?(Pt.setPanelOpen(!0),Pt.element.style.display="none"):go&&(go.style.display="none")):(s?s&&(N==="overlay"||N==="push")&&!M?(Xe.style.removeProperty("display"),Xe.style.display="flex",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.setProperty("display","none","important"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.display="",Xe.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),Pt?(Pt.setPanelOpen(!1),Pt.element.style.display=s?"none":""):go&&(go.style.display=s?"none":""))},dt=(s,l="user")=>{if(!De()||he===s)return;let f=he;he=s,Li();let g=(()=>{let M=n.launcher?.sidebarMode??!1,N=e.ownerDocument.defaultView??window,z=n.launcher?.mobileFullscreen??!0,V=n.launcher?.mobileBreakpoint??640,K=N.innerWidth<=V,J=St(n)&&z&&K,ae=Ae()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return M||z&&K&&ge||J||ae})();if(he&&g){if(!kn){let M=e.getRootNode(),N=M instanceof ShadowRoot?M.host:e.closest(".persona-host");N&&(kn=vg(N,n.launcher?.zIndex??so))}Ln||(Ln=xg(e.ownerDocument))}else he||(kn?.(),kn=null,Ln?.(),Ln=null);he&&(Ki(),Cp()||(No()==="follow"?Pr(!0):hd()));let v={open:he,source:l,timestamp:Date.now()};he&&!f?C.emit("widget:opened",v):!he&&f&&C.emit("widget:closed",v),C.emit("widget:state",{open:he,launcherEnabled:ge,voiceActive:je.active,streaming:H.isStreaming()})},kr={inputDisabled:!1,sendDisabled:!1},Lr=()=>kr.inputDisabled,xs=()=>kr.inputDisabled||kr.sendDisabled,UA=()=>(kr.inputDisabled?kr.inputReason:void 0)??(kr.sendDisabled?kr.sendReason:void 0);function Ap(){if(!Me)return;if(Se.getState().phase==="streaming"){Me.disabled=!1;return}let s=Ze?!Ze.isReady():!1;Me.disabled=xs()||s}function Cd(){if(!An)return;let s=Se.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;An.toggleAttribute("data-persona-send-hidden",l)}function qA(){let s=UA();if(Ae()){let l=un??Ie;s?l.setAttribute("title",s):l.removeAttribute("title"),Ie.toggleAttribute(li,!!s);return}if(s){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(li,""),st.textContent=s;return}if(st.hasAttribute(li)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(li),u)){let l=H.getStatus();ao(st,fo(l),n.statusIndicator??{},l)}}function Mp(){let s=Km(n.composer?.inputDisabled),l=Km(n.composer?.sendDisabled);kr={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},Se.setInputDisabled(s.disabled),Se.setSendDisabled(l.disabled);let f=Se.getState().phase==="streaming",g=s.disabled,v=f||g;le&&(le instanceof HTMLTextAreaElement?le.disabled=g:le.setAttribute("contenteditable",g?"false":"true"),le.setAttribute("aria-disabled",g?"true":"false")),At&&(At.disabled=g),yt&&(yt.disabled=g);for(let M of Wt?.affordanceButtons??[])M.querySelectorAll("button").forEach(N=>{N.disabled=g});se&&(se.disabled=v),ls.forEach(M=>{M.elements.forEach(N=>{N.toggleAttribute("data-disabled",v),N instanceof HTMLButtonElement||N.setAttribute("aria-disabled",v?"true":"false")}),M.buttons.forEach(N=>{N.disabled=v})}),Lp.forEach(M=>{M.toggleAttribute("data-disabled",v),M instanceof HTMLButtonElement?M.disabled=v:M.setAttribute("aria-disabled",v?"true":"false"),M.querySelectorAll("button").forEach(N=>{N.disabled=v})}),Ie.dataset.personaComposerStreaming=f?"true":"false",Ie.dataset.personaComposerInputDisabled=g?"true":"false",Ie.dataset.personaComposerSendDisabled=xs()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(M=>{(M instanceof HTMLButtonElement||M instanceof HTMLInputElement||M instanceof HTMLTextAreaElement||M instanceof HTMLSelectElement)&&(M.disabled=f)}),Ap(),qA()}let Ii=s=>{Se.setStreaming(s),wh(s?"stop":"send"),Mp()},Cs=()=>{je.active||le&&le.focus()};C.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Cs(),200)});let Ss=null,Ri=!1,Tp=!Mo.hidden,Ir=null,Ep=!G,Sd=null;ye.push(()=>{Sd?.cancel(),Sd=null});let $A=s=>{let l=LS(s);if(l===Xl)return;Xl=l,e.setAttribute("data-persona-conversation-state",l);let f=Yu();Yl(),Ep&&(Sd?.cancel(),Sd=PS(Ie,l==="active"?f:Yu(),l==="active"?"drop":"rise")),Lo()},Ry=null,Hy,Wy=null,ma=null,Pp=!1,Hi=s=>{let l=xn(n),f=`${l.variant}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==Ry||l.icon!==Hy)&&(Ry=f,Hy=l.icon,wu({host:Mo,iconHolder:zw,kicker:Kw,title:Gw,subtitle:Xw,starterSuggestions:Ku},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==Wy&&(Wy=g,Au(Do,l.message,n));let v=s??(H?H.getMessages():n.initialMessages);$A(v);let M=Ri,N=!M&&Yr(l,v),z=N!==Tp;if(Tp=N,ma){Ir?.cancel(),Ir=null,M!==Pp&&(Pp=M,M?Og(re,Mo,null):Bg(re,Mo,ma)),Za(re,Mo,!M);return}if(z&&!N&&!M&&l.dismiss==="on-first-message"&&Ep){Ir=ES(Mo,K=>{Ir===K&&(Ir=null),!Tp&&!ma&&(Za(re,Mo,!1),Lo()),K?.cancel()});return}if(Ir){if(!N&&!M)return;Ir.cancel(),Ir=null}let V=!Mo.hidden;Za(re,Mo,N),!N&&V&&Lo()},kp=[],Lp=[],Ip=!1,By=null,Oy,Dy=()=>{Lp.length=0;let s=kp.splice(0,kp.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};ye.push(Dy);let VA=(s,l)=>{let f=Sg(s,l);if(!f)return n.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),I("span");let g=n.suggestions?.starters,v=wg({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:u?H.isStreaming():!1,config:n,plugins:i,chipsConfig:n.suggestionChipsConfig,session:H,getTextarea:()=>le,eventTarget:Mo,submitPrompt:Xd});return Lp.push(v),v},Rp=()=>{if(Ip)return;Ip=!0;let s=xn(n);By=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,Oy=s.icon;try{Dy(),Og(re,Mo,ma),ma=null,Pp=!1;let l=H?H.getMessages():n.initialMessages,f=Yr(s,l),g=0,v=null;for(let M of i)if(M.renderWelcome&&(v=M.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>Mo,sendMessage:N=>{if(!H||H.isStreaming())return;let z=N.trim();z&&H.sendMessage(z)},requestRender:()=>Rp(),renderStarter:N=>VA(N,g++),storage:p(M.id),onCleanup:N=>{kp.push(N)}}),v))break;v&&v!==Mo&&(ma=v,Bg(re,Mo,v))}finally{Ip=!1}Hi()},jA=()=>{let s=xn(n);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===By&&s.icon===Oy||Rp()},wd=()=>{Hi(),na||(le.placeholder=fC(Se.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!H?.isStreaming()&&(Me.textContent=n.copy?.sendButtonLabel??"Send")),le.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',le.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},zA=!!n.setStoredConversationId,ga=s=>de(l=>{let f={...l};return delete f[s],f}),Ad=s=>{let l=X[s];return typeof l=="string"?l:null},_y=()=>{let s=X.durableResume;if(!s||typeof s!="object")return null;let l=s;return typeof l.executionId=="string"&&l.executionId.length>0&&typeof l.after=="string"&&l.after.length>0?{executionId:l.executionId,after:l.after}:null},Hp=!!n.clientToken&&typeof n.reconnectStream!="function";n.clientToken&&(n={...n,getStoredSessionId:()=>Ad("sessionId"),setStoredSessionId:s=>{de(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>ga("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Ad("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{de(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>ga("conversationId"))});let Ny=()=>n.clientToken??null,Fy=s=>pw(s,wn(),n.persistState===!1),Uy=Ny(),er=Uy?Fy(Uy):null,tr={...er?{visitorStore:er}:{},historyBootstrapReady:O,getStoredMessageCursor:()=>Ad("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){ga("historyMessageCursor");return}de(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=X.pendingDisplayProjections;if(!s||typeof s!="object")return null;let l=s;return typeof l.conversationId!="string"||!Array.isArray(l.messageIds)?null:{conversationId:l.conversationId,messageIds:l.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){ga("pendingDisplayProjections");return}de(l=>({...l,pendingDisplayProjections:s}))},getStoredResumableHandle:_y,setStoredResumableHandle:s=>{if(!s){ga("durableResume");return}de(l=>({...l,durableResume:s}))},shouldResumeDurableConversation:()=>Hp&&_y()!==null,...zA?{}:{getStoredConversationRevision:()=>Ad("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){ga("conversationRevision");return}de(l=>({...l,conversationRevision:s}))}}};if(Hp){let s=n.onExecutionState,l=e.ownerDocument.defaultView,f=!1,g=()=>{f=!0},v=()=>{f=!1};l?.addEventListener("beforeunload",g),l?.addEventListener("pagehide",g),l?.addEventListener("pageshow",v),ye.push(()=>{l?.removeEventListener("beforeunload",g),l?.removeEventListener("pagehide",g),l?.removeEventListener("pageshow",v)}),n={...n,reconnectStream:n.reconnectStream??(M=>H.getClient().reconnectClientTokenStream(M)),onExecutionState:M=>{(M||!f)&&tr.setStoredResumableHandle?.(M?{executionId:M.executionId,after:M.lastEventId}:null),s?.(M)}}}let KA=()=>{let s=Ny();if(s&&er?.matches(s,wn(),n.persistState===!1)||!s&&!er)return;er?.destroy(),er=s?Fy(s):null;let l={...tr};er?l.visitorStore=er:delete l.visitorStore,tr=l,H.setHistoryInternals(tr)},ws=null,GA=()=>{ws==null&&(ws=setInterval(()=>{let s=ke.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(ws),ws=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=xc(l-g))})},100))},Wp=(s,l)=>{if(Object.is(s,l))return!0;if(s===null||l===null||typeof s!="object"||typeof l!="object")return!1;if(Array.isArray(s)||Array.isArray(l))return!Array.isArray(s)||!Array.isArray(l)||s.length!==l.length?!1:s.every((N,z)=>Wp(N,l[z]));let f=s,g=l,v=Object.keys(f),M=Object.keys(g);return v.length===M.length&&v.every(N=>Object.prototype.hasOwnProperty.call(g,N)&&Wp(f[N],g[N]))},qy=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},Bp=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!$l(s),XA=(s,l,f)=>{if(s.length!==l.length)return!1;let g=s[f.index],v=l[f.index];return!g||!v||g.id!==f.id||v.id!==f.id?!1:(!Object.is(g.content,v.content)||!Object.is(g.rawContent,v.rawContent)||!Object.is(g.llmContent,v.llmContent))&&Bp(g)&&Bp(v)&&Wp(qy(g),qy(v))},Op=null,ha=null,As=null,or=null,Md=s=>{Op=s;let l,f;ha=null;for(let v=s.length-1;v>=0;v-=1){let M=s[v];if(!l&&M.role==="user"&&(l=M),!f&&M.role==="assistant"&&(f=M),!ha&&Bp(M)&&(ha={index:v,id:M.id}),l&&f&&ha)break}Jo(ke,s,oo),gr()?.updateInlineArtifactBlocks(ke,Yo.artifacts,{suppressTransition:Fo}),GA(),Hi(s),ia(s),Pr(!Fo),BA(s),s.length===0&&(hn(),Si=!0,cd=!1,ca=null,ud=!1),!mp||da?(mp=!0,hs=l?.id??null,gp=f?.id??null):l&&l.id!==hs?(hs=l.id,LA(l.id)):f&&f.id!==gp&&IA(),f&&(gp=f.id),WA(s);let g=je.lastUserMessageId;l&&l.id!==g&&(je.lastUserMessageId=l.id,C.emit("user:message",l)),je.lastUserMessageWasVoice=!!l?.viaVoice,wi(s),fa()},Dp=()=>{or!==null&&(cancelAnimationFrame(or),or=null);let s=As;As=null,s&&Md(s)},$y=()=>{or!==null&&cancelAnimationFrame(or),or=null,As=null},QA=s=>{let l=As??Op;if(Fo&&l&&ha&&XA(l,s,ha)){As=s,or===null&&(or=requestAnimationFrame(()=>{or=null;let f=As;As=null,f&&Md(f)}));return}if(s.length===0){$y(),Md(s);return}Dp(),Md(s)};H=new _a(n,{onMessagesChanged(s){QA(s)},onStatusChanged(s){let l=n.statusIndicator??{};ao(st,(g=>g==="idle"?l.idleText??Ut.idle:g==="connecting"?l.connectingText??Ut.connecting:g==="connected"?l.connectedText??Ut.connected:g==="error"?l.errorText??Ut.error:g==="paused"?l.pausedText??Ut.paused:g==="resuming"?l.resumingText??Ut.resuming:Ut[g])(s),l,s),wt()},onStreamingChanged(s){s||(H?.getMessages().length===0?$y():Dp()),Fo=s,Ii(s),wt(),H&&Jo(ke,H.getMessages(),oo),s||(Pr(!0),PA(),gy=!0,H&&hy(H.getMessages(),jr(n))),Vt(),Gl(s?"Responding\u2026":"Response complete."),fa()},onVoiceStatusChanged(s){if(C.emit("voice:status",{status:s,timestamp:Date.now()}),n.voiceRecognition?.provider?.type==="runtype")switch(s){case"listening":ir(),Ea();break;case"processing":ir(),JM();break;case"speaking":ir(),ZM();break;default:s==="idle"&&H.isBargeInActive()?(ir(),Ea(),se?.setAttribute("aria-label","End voice session")):(je.active=!1,ir(),Jn("system"),gn());break}},onArtifactsState(s){Yo=s,s.artifacts.length===0&&(ra=!1),gr()?.updateInlineArtifactBlocks(ke,s.artifacts,{suppressTransition:Fo}),mn(),wi()},onHistoryStateChanged(s){$e(s)},onHistoryNotice(s){Ht(s)},onReconnect(s){let{executionId:l,lastEventId:f}=s.handle;s.phase==="paused"?C.emit("stream:paused",{executionId:l,after:f}):s.phase==="resuming"?C.emit("stream:resuming",{executionId:l,after:f,attempt:s.attempt??1}):C.emit("stream:resumed",{executionId:l,after:f})}},tr),it.current=H,ye.push(()=>H.cancel()),ye.push(()=>{H.destroy(),er?.destroy()});let _p=null;if(H.onReadAloudChange((s,l)=>{zh=s,Kh=l,Gh();let f=s??_p;s&&(_p=s);let g=f?H.getMessages().find(v=>v.id===f)??null:null;C.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(_p=null)}),u=!0,mp=!0,n.voiceRecognition?.provider?.type==="runtype")try{H.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let YA=720,JA=250,Ye=lh(n.features?.history?.copy),$o=null,Np=!1,at=null,Td=null,Ed="conversation",Fp=null,mo=null,In=null,Pd=H.getHistoryState(),Up=null,Wi=0,qp=null,kd=null,Ld=null,$p=`persona-history-${Math.random().toString(36).slice(2,8)}`,Vp=()=>n.features?.history?.enabled===!0,Rn=()=>Vp()&&!!$o&&!Np,Vy=()=>{let s=H.getStatus();return Fo||s==="paused"||s==="resuming"},jp=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=$o?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},ya=()=>Td?.scope??jp(),jy=()=>H.getClientSession()?.targetId??null,zy=s=>`${s.state}:${"reason"in s?s.reason:""}`,ZA=s=>{let l=zy(s);l!==Up&&(Up=l,C.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Id=s=>{s&&(zn.textContent="",zn.textContent=s)},Ky=null,Gy=null,eM=()=>{if(!Vp())return null;let s=yw();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:(Ky!==l&&(Ky=l,Gy=l()),Gy):H.isClientTokenMode()?bw({client:H.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>H.bindActivatedSession(f),getClient:()=>H.getClient()}):null},Xy=()=>{kd?.(),kd=null,Ld?.(),Ld=null,Np=!1,$o=eM();let s={...tr};$o?s.historyProvider=$o:delete s.historyProvider,tr=s,H.setHistoryInternals(tr),$o&&(kd=$o.subscribeAvailability?.(l=>{Np=!l,l||Io({restoreFocus:!1}),Hr()})??null,Ld=$o.subscribeIdentityStatus(l=>ZA(l)),Up=zy($o.getIdentityStatus()))},zp=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!ge||St(n)))return"panel";let l=Pn??ue;return(l.getBoundingClientRect().width||l.clientWidth)>=YA?"rail":"panel"},Zo=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Rd="data-persona-history-suppressed",Vo=null,Rr=null,Ms=null,Bi=null,Kp=null,Qy="",Yy=()=>Te===Kp?Qy:n.layout?.showHeader===!1?"none":"",tM=()=>ie==="panel"&&!!Ms&&Bi===Ms.element&&n.layout?.showHeader!==!1&&Yy()!=="none",oM=()=>{for(let s of Array.from(Te.children))s!==Vo&&s.setAttribute(Rd,"")},nM=()=>{for(let s of Array.from(ue.querySelectorAll(`[${Rd}]`)))s.removeAttribute(Rd)},rM=()=>{let s=Ms;if(!s)return;if(Array.from(Te.children).some(g=>g!==Vo&&!g.hasAttribute(Rd))){Rr&&Rr!==Te&&(Rr.style.removeProperty("min-height"),Rr=null);let g=Te.offsetHeight;g>0&&(Te.style.minHeight=`${g}px`,Rr=Te)}Vo||(Vo=I("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==Vo&&Vo.replaceChildren(f),Vo.parentNode!==Te&&Te.appendChild(Vo),oM()},Jy=()=>{Rr&&(Rr.style.removeProperty("min-height"),Rr=null),Vo&&(Ms?.setHeaderPlacement("inline"),Vo.remove(),Vo=null,nM())},Hd=null,Gp=()=>{if(Hd){if(re.style.display="none",Zo(re,!0),Ie.hidden=!0,Zo(Ie,!0),tM()){rM(),Te.style.display=Yy(),Zo(Te,!1);return}Jy(),Te.style.display="none",Zo(Te,!0)}};xe=Gp;let sM=s=>{let l=re.style.display,f=Ie.hidden,g=Ie,v=Te,M=Te.style.display;Kp=v,Qy=M,Hd=()=>{Hd=null,Jy(),Kp=null,re.style.display=l,Zo(re,!1),g.hidden=f,Zo(g,!1),Ie!==g&&(Ie.hidden=!1,Zo(Ie,!1)),v.style.display=M,Zo(v,!1),Te!==v&&(Te.style.display=n.layout?.showHeader===!1?"none":"",Zo(Te,!1))},Ie.parentNode?.insertBefore(s,Ie),Gp()},ba=null,Ts=null,Oi=null,va=null,Zy=()=>[Te,_e.closeButtonWrapper,_e.clearChatButtonWrapper,re,Ie],aM=52,Wd=()=>n.features?.history?.rail?.collapsible!==!1,xa=()=>n.features?.history?.rail?.side==="right"?"right":"left",Xp=200,Qp=400,Yp=s=>Math.min(Qp,Math.max(Xp,Math.round(s))),iM=()=>n.features?.history?.rail?.resizable===!0,Di,lM=()=>{if(Di===void 0&&(Di=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${wn()}rail-width`));s&&(Di=s)}catch{}return Di},_i=()=>Yp(lM()??n.features?.history?.rail?.width??260),dM=s=>{if(Di=s,n.persistState!==!1)try{window.localStorage.setItem(`${wn()}rail-width`,String(s))}catch{}},Bd=()=>Wd()&&n.features?.history?.rail?.collapsedBehavior==="overlay",_t=!1,eb=s=>{let l=I("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},cM=()=>{let s=n.features?.history?.rail?.brand;if(!s)return;let l=!1,f;return g=>{if(s.render)try{return s.render({collapsed:g})??null}catch(v){return l||(l=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=eb(s.iconUrl):f=s.icon?ce(s.icon,20):null),f?f.cloneNode(!0):null}},uM=()=>n.features?.history?.rail?.sections?.map(s=>{let l=!1,f=g=>{l||(l=!0,console.warn("[persona] history rail section threw",s.id,g))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(g=>{let v;return{id:g.id,label:g.label,badge:g.badge,iconNode:()=>{if(v!==void 0)return v;try{g.renderIcon?v=g.renderIcon()??null:g.iconUrl?v=eb(g.iconUrl):v=g.icon?ce(g.icon,20):null}catch(M){f(M),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(M){f(M)}}}})}})??[],pM=s=>{let l=uM();for(let f of s)l.some(g=>g.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):l.push(f);return l.length?l:void 0},Ni=null,tb=()=>`${wn()}rail-collapsed`,Jp=()=>{if(Ni===null&&(Ni=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(tb());s&&(Ni=s==="1")}catch{}return Ni},Zp=s=>{if(Ni=s,n.persistState!==!1)try{window.localStorage.setItem(tb(),s?"1":"0")}catch{}},Fi=()=>ie==="rail"&&Wd()&&!Bd()&&Jp(),ef=()=>{},ob=()=>{if(Bd()){ef();return}Zp(!Jp()),at?.view.setCollapsed(Fi()),ht(),Lo()},tf=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!uu(s)?null:{combo:s,hint:pu(s),aria:Tl(s)}},nb=()=>{c.forEach(l=>l()),c=[];let s=tf();s&&c.push(d.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ne&&ie==="rail"&&Wd()||Sa(),run:()=>Bd()?ef():ob()}));for(let l of n.layout?.header?.trailingActions??[])l.shortcut&&c.push(d.register({id:`header-action-${l.id}`,combo:l.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${l.id}"]`);f?f.click():n.layout?.header?.onAction?.(l.id)}}));for(let l of i)for(let f of l.shortcuts??[])c.push(d.register({...f,id:`${l.id}:${f.id}`}))};nb();let fM=300,Od="var(--persona-history-overlay-margin,8px)",en=null,nr=null,Dd=0,rr=null,Ca=null,Es=!1,of=0,rb=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Sa=()=>Rn()&&Bd()&&(ie??zp())==="rail",mM=()=>ne&&!_t,Ui=()=>{Ca!==null&&clearTimeout(Ca),Ca=null},gM=()=>{sh().catch(()=>{})},sb=()=>{Ui(),_t&&(Ca=setTimeout(()=>{Ca=null,!(Es||!_t)&&(rr?.contains(document.activeElement)||Io({restoreFocus:!1}))},fM))},hM=(s,l)=>{let f=rr?.getBoundingClientRect();if(!f)return!1;let g=en?.getBoundingClientRect(),v=g?Math.min(g.top,f.top):f.top;return s>=f.left&&s<=f.right&&l>=v&&l<=f.bottom||!!g&&s>=g.left&&s<=g.right&&l>=g.top&&l<=g.bottom},nf=s=>{_t&&(Es=hM(s.clientX,s.clientY),Es?Ui():Ca===null&&sb())},ab=s=>{ne||!Sa()||(_t=!0,$i({invoker:en,keyboard:s?.keyboard===!0}).then(()=>{ne?!Es&&document.activeElement!==en&&Io():_t=!1}))},ib=()=>{let s=Bi?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",_t?Ye.expandLabel:Ye.collapseLabel),s.setAttribute("aria-expanded",_t?"false":"true"))},lb=()=>{Zp(!1);let s=at;if(!_t||!s){$i({invoker:en});return}let l=document.activeElement===en;_t=!1,_d(),s.element.remove(),sf(s.element),ib(),l&&Fd(),Lo(),Hr()},yM=()=>{Zp(!0),Io()};ef=()=>{!ne||_t?lb():yM()};let bM=()=>{let s=tf(),l=$s({ariaLabel:Ye.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":$p,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{Es=!0,Ui(),!(rb()||Date.now()<of)&&ab()}),f.addEventListener("mouseleave",()=>{Es=!1,of=0,sb()}),f.addEventListener("focus",()=>{ne||gM()}),f.addEventListener("click",g=>{Rn()&&(g.detail!==0&&rb()&&!ne?ab():lb())}),en=f,nr=l.wrapper},qi=()=>{if(nr&&!nr.isConnected&&(nr=null,en=null),!Sa()){nr?.remove(),nr=null,en=null;return}en||bM();let s=nr,l=en;if(!s||!l)return;let f=xa()!=="right"?Te.firstChild:null;(f??Te.lastChild)!==s&&Te.insertBefore(s,f),s.style.display=mM()||Dd>0?"none":"",l.setAttribute("aria-label",Ye.expandLabel),l.setAttribute("aria-expanded",ne?"true":"false"),rr&&ht()},db=s=>{if(!_t)return;let l=s.target;l instanceof Node&&(rr?.contains(l)||nr?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||Io({restoreFocus:!1}))};document.addEventListener("pointerdown",db,!0),ye.push(()=>{document.removeEventListener("pointerdown",db,!0),document.removeEventListener("pointermove",nf),wa?.(),Ui()});let rf=null,wa=null,cb=16,ub=s=>{dM(Yp(s)),ht(),Lo()},vM=()=>{let s=I("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(Xp)),s.setAttribute("aria-valuemax",String(Qp)),s.addEventListener("pointerdown",l=>{let f=Ts;if(!f||l.button!==0)return;l.preventDefault(),wa?.();let g=l.clientX,v=f.getBoundingClientRect().width||_i(),M=xa()==="right"?-1:1,N=v,z=e.ownerDocument;f.style.transition="none";let V=J=>{N=Yp(v+M*(J.clientX-g)),f.style.flex=`0 0 ${N}px`,s.setAttribute("aria-valuenow",String(N))},K=()=>{wa=null,z.removeEventListener("pointermove",V),z.removeEventListener("pointerup",K),z.removeEventListener("pointercancel",K),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}ub(N)};wa=K,z.addEventListener("pointermove",V),z.addEventListener("pointerup",K),z.addEventListener("pointercancel",K);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=xa()==="right"?-cb:cb,g=_i(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Xp:l.key==="End"?Qp:null;v!==null&&(l.preventDefault(),ub(v))}),s},xM=(s,l)=>{if(!iM()||Fi()){wa?.(),rf?.remove();return}let f=rf??vM();rf=f,f.setAttribute("aria-label",Ye.resizeLabel),f.setAttribute("aria-valuenow",String(_i())),f.nextElementSibling!==l&&s.insertBefore(f,l)};ht=()=>{at?.view.setRailSide(xa());let s=xa()==="right",l=rr;if(l){let z=en?en.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round(z))}px + ${Od})`,l.style.width=`${_i()}px`,l.style.left=s?"":Od,l.style.right=s?Od:""}let f=Ts,g=ba,v=Oi;if(!f||!g||!v)return;f.style.flex=`0 0 ${Fi()?aM:_i()}px`;let M="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":M,f.style.borderLeft=s?M:"";let N=s?v:f;g.firstElementChild!==N&&g.append(N,s?f:v),xM(g,s?f:v)};let pb=s=>{if(va&&Ts){va.replaceWith(s),va=null,ht();return}let l=I("div","persona-history-rail-shell");l.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=I("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let g=I("div","persona-history-rail-host");g.style.cssText="display:flex;min-height:0;overflow:hidden",ue.insertBefore(l,Te.parentNode===ue?Te:re);for(let v of Zy())v?.parentNode===ue&&f.appendChild(v);l.append(g,f),g.appendChild(s),ba=l,Ts=g,Oi=f,ht()},CM=()=>{if(ba)return;let s=I("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",va=s,pb(s),Lo()},fb=()=>{va&&(_d(),Lo())},SM=s=>{let l=I("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${Od};display:flex;overflow:hidden;z-index:${$a-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,ue.style.position="relative",ue.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",nf),rr=l,ht(),ib()},_d=()=>{Hd?.(),rr&&(Es&&(of=Date.now()+150),document.removeEventListener("pointermove",nf),rr.remove(),rr=null);let s=ba;if(s){wa?.();for(let l of Zy())l&&s.contains(l)&&ue.insertBefore(l,s);s.remove(),ba=null,Ts=null,Oi=null,va=null}},mb=s=>{Bi=s,s.id=$p,s.style.flex="1 1 auto",s.style.minHeight="0"},sf=s=>{mb(s),(ie!=="rail"||_t)&&fb(),ie!=="rail"?sM(s):_t?SM(s):pb(s)},Nd=()=>{if(qi(),Mb(),!ne||!at)return;let s=zp();if(s===ie)return;let l=document.activeElement,f=l instanceof HTMLElement&&(at.element.contains(l)||Vo?.contains(l)===!0)?l:null;_d(),at.element.remove(),at.view.setHeaderPlacement("inline"),ie=s,at.view.setPresentation(s),at.view.setCollapsed(Fi()),at.requestRender(),at.element.isConnected||sf(at.element),f?.isConnected?f.focus():Fd(),Vt(),Lo(),Hr()},gb=(s,l)=>Vo?.querySelector(l)??s.querySelector(l),Fd=()=>{let s=at?.element??Bi;if(!s)return;let l=gb(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=gb(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},$i=async s=>{if(!Rn()||ne)return;let l=$o;if(!l)return;if(!_t&&Sa()&&Jp()){qi();return}Ud();let f=++Wi;Ed=s?.returnSurface??"conversation",Fp=s?.invoker??mo;let g=Sa()&&!_t;g&&(Dd+=1,qi(),CM());let v;try{v=await sh()}catch{Id(Ye.openHistoryLabel),g&&(Dd-=1,f===Wi&&(fb(),qi()));return}if(g&&(Dd-=1),f!==Wi||ne)return;Td={scope:jp()},ie=zp(),ne=!0;let M=ie==="panel"&&n.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",N=n.features?.history?.rowAvatar,z=tf(),V=z?{hint:z.hint,aria:z.aria}:null,K={provider:l,context:Td,targetId:jy(),presentation:ie,collapsible:Wd(),collapsed:Fi(),railSide:xa(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:cM(),onToggleCollapse:ob,...V?{collapseShortcut:V}:{},headerPlacement:M,showScopeStatus:n.features?.history?.showScopeStatus!==!1,showDelete:n.features?.history?.showDelete!==!1,showDeleteAll:n.features?.history?.showDeleteAll!==!1,...n.features?.history?.listActions?.length?{listActions:n.features.history.listActions}:{},rowAvatar:N===!1?!1:typeof N=="string"?N:n.launcher?.iconUrl,activeConversationId:H.getActiveConversationId(),...n.features?.history?.grouping?{grouping:n.features.history.grouping}:{},...n.features?.history?.copy?{copy:n.features.history.copy}:{},...n.features?.history?.pageSize!==void 0?{pageSize:n.features.history.pageSize}:{},onSelect:J=>lf(J,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:J=>Ps(J),attachTooltip:eo,onStartNew:()=>df({focusComposer:!0}),onClose:()=>Io(),onRequestDeleteConversation:J=>Ab(J),onRequestClearHistory:()=>PM(),...l.resetDevice?{onRequestResetIdentity:()=>kM()}:{}};at=hw({plugins:i,config:n,getPresentation:()=>ie??"panel",getReturnSurface:()=>Ed,close:()=>Io(),createView:({slots:J,renderDom:ae,onModelChange:fe,railSections:Je})=>(Ms=v.createHistoryView({...K,railSections:pM(Je),slots:J,renderDom:ae,onModelChange:fe,onAnnounce:Id}),Ms),onElementChanged:(J,ae)=>{if(!ae?.isConnected)return sf(J);mb(J),ae.replaceWith(J),Gp()}}),at.view.setNewConversationRequired(Pd.recovery==="new_conversation_required"),s?.focus!==!1&&(ie!=="rail"||s?.keyboard===!0)&&Fd(),Vt(),Lo(),Hr(),C.emit("history:opened",{presentation:ie,returnSurface:Ed,timestamp:Date.now()})},Ud=()=>{},Io=s=>{if(!ne)return;Wi+=1;let l=Ed,f=Fp,g=at,v=s?.restoreFocus!==!1;ne=!1;let M=!1,N=null,z=()=>{if(!M){if(M=!0,Ud=()=>{},N!==null&&clearTimeout(N),_t=!1,Ui(),_d(),g?.dispose(),g?.view.destroy(),g?.element.remove(),at===g&&(at=null,Ms=null,Bi=null,ie=null,Td=null,Fp=null),Vt(),Lo(),Hr(),v){let K=f??mo;K?.isConnected?K.focus():Cs()}C.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},V=g&&g.element===g.view.element?g.view.playExit():null;if(!V){z();return}Ud=z,N=setTimeout(z,JA),V.then(z)},hb=s=>{if(!(s.key!=="Escape"||!ne||!at)){if(ie==="rail"){let l=s.target;if(!(l instanceof Node)||!(at.element.contains(l)||_t&&nr?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),Io()}};ue.addEventListener("keydown",hb),ye.push(()=>ue.removeEventListener("keydown",hb));let qd=null,yb=!1,Vi=()=>{if(!vr)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&qd?.trim()||null;vr.textContent=l??n.launcher?.title??"Chat Assistant";let f=vr.closest(".persona-combo-btn");if(!f)return;let g=!s||H.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",g?"false":"true"),f.setAttribute("aria-haspopup",g?"true":"false"),g||f.setAttribute("aria-expanded","false"),f.style.cursor=g?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=g?"":"none")},wM=s=>{s!==qd&&(qd=s,Vi())},Ps=s=>{yb=s?.starred===!0,wM(s&&s.title.trim()||null),Vi()};Vi(),ue.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=H.getActiveConversationId();f&&(l==="delete"?Ab(f):l==="star"&&H.canUpdateConversations()&&cf(f,{starred:!yb}).catch(()=>{}))});let $d=0,AM=250,Vd=null,jd=()=>{Vd&&clearTimeout(Vd),Vd=null};ye.push(jd);let bb=()=>{jd();let s=Ss;s&&(Ri=!0,s.hidden=!1,ke.style.display="none",Hi())},zd=()=>{$d+=1,jd(),Ss&&(Ss.remove(),Ss=null,Ri=!1,ke.style.removeProperty("display"),Zo(Ie,!1),Hi())},MM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ke.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},af=(s,l)=>Y("div",{className:bo("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),vb=()=>Y("div",{className:"persona-conversation-loading-body"},af("58%",!1),af("72%",!0),af("44%",!1)),xb=s=>{Ss?.remove(),Ss=s,s.hidden=!Ri,re.insertBefore(s,ke),jd(),Ri||(Vd=setTimeout(bb,AM)),Zo(Ie,!0)},TM=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:vb},l=null,f=i.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),xb(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ye.openConversationLoadingLabel}},l??vb()))},EM=s=>{let l=()=>{lf(s,{focusComposer:!0}).catch(()=>{})},f=Rn()?()=>{zd(),$i()}:void 0,g=(z,V)=>{let K=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return K.addEventListener("click",V),K},v=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Ye.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},g(Ye.openConversationRetryLabel,l),f?g(Ye.openConversationBackLabel,f):null)),M=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Ye.openConversationErrorTitle,retryLabel:Ye.openConversationRetryLabel,backLabel:Ye.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),N=null;for(let z of i)if(z.renderHistoryOpenError){try{N=z.renderHistoryOpenError(M)}catch(V){console.warn("[persona] renderHistoryOpenError threw",V),N=null}if(N)break}xb(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},N??v())),bb()};C.on("history:closed",()=>{Ss&&Zo(Ie,!0)});let lf=async(s,{focusComposer:l=!1}={})=>{let f=ya(),g=!!at;at?.view.setActiveConversationId(s),zd();let v=$d;TM(),ne&&(ie==="panel"||_t)&&Io({restoreFocus:!1}),da=!0;try{await H.openConversation(s,{scope:f})}catch(M){throw v===$d&&EM(s),M}finally{da=!1}v===$d&&(zd(),Dt.clear(),hn(),ko(),Cp()||hd(),MM(),sr(),g||Ps(null),C.emit("history:conversationOpened",{conversationId:s,title:qd,scope:f,timestamp:Date.now()}),l&&Cs())},df=async({focusComposer:s=!1}={})=>{zd(),await H.startNewConversation({scope:ya()}),Ps(null),Dt.clear(),hn(),ko(),hd(),sr();let l=H.getActiveConversationId();at?.view.setActiveConversationId(l),C.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),ne&&(ie==="panel"||_t)&&Io({restoreFocus:!1}),s&&Cs()},cf=async(s,l)=>{let f=await H.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return at?.view.applyConversationSummary(f),!at&&s===H.getActiveConversationId()&&Ps(f),f},Cb=async s=>{let l=ya(),f=H.getActiveConversationId()===s;await H.deleteConversation(s,{scope:l}),at?.view.removeConversationSummary(s),f&&(Ps(null),Dt.clear(),hn(),ko(),sr()),C.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},Sb=async s=>{let l=s?.scope??ya(),f=s?.allTargets?null:s?.targetId??jy(),g=await H.clearConversationHistory({...f?{targetId:f}:{},scope:l});return Ps(null),Dt.clear(),hn(),ko(),sr(),C.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},wb=async()=>{if(!$o?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await H.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ps(null),H.clearArtifacts(),Dt.clear(),Op=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),X={},Ee.syncFromMetadata(),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),hn(),ko(),sr(),Io({restoreFocus:!1}),Cs(),he||Pt?.launcher.element.focus()}return Id(s?Ye.identityResetNotice:Ye.identityResetUnconfirmedNotice),C.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},uf=()=>Pn?we:ue,Ab=async s=>await Du({host:uf(),title:Ye.deleteConversationConfirmTitle,description:Ye.deleteConversationConfirm,confirmLabel:Ye.deleteConversationConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await Cb(s),"deleted"):"cancelled",PM=async()=>{let s=ya()==="verified-user";return await Du({host:uf(),title:Ye.clearHistoryConfirmTitle,description:s?Ye.clearHistoryVerifiedConfirm:Ye.clearHistoryConfirm,confirmLabel:Ye.clearHistoryConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await Sb(),"cleared"):"cancelled"},kM=async()=>{if(!await Du({host:uf(),title:Ye.resetIdentityConfirmTitle,description:Ye.resetIdentityConfirm,confirmLabel:Ye.resetIdentityConfirmLabel,cancelLabel:Ye.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await wb();return{outcome:"reset",remoteRevocationConfirmed:l}},tn=I("button","persona-history-earlier");tn.type="button",tn.textContent=Ye.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let sr=()=>{if(!(Rn()&&!!Pd.nextMessageCursor&&!!H.getActiveConversationId())){tn.remove();return}tn.textContent=Ye.showEarlierMessagesLabel,tn.parentNode!==re&&re.insertBefore(tn,re.firstChild)};tn.addEventListener("click",()=>{let s=H.getActiveConversationId(),l=Pd.nextMessageCursor;if(!s||!l||tn.disabled)return;tn.disabled=!0;let f=re.scrollHeight,g=re.scrollTop;H.loadOlderMessages(s,l,{scope:ya()}).then(()=>{re.scrollTop=g+(re.scrollHeight-f),Lo()}).catch(()=>{}).finally(()=>{tn.disabled=!1,sr()})});let LM=()=>{let s=$s({ariaLabel:Ye.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return s.button.addEventListener("click",l=>{if(!(!Rn()||Vy())){if(ne){Io();return}$i({invoker:s.button,keyboard:l.detail===0})}}),s},Mb=()=>{if(!Rn()){In?.remove(),mo=null,In=null;return}if(In&&!In.isConnected&&(mo=null,In=null),!mo&&Te){let g=LM();mo=g.button,In=g.wrapper;let v=_e.clearChatButtonWrapper||_e.closeButtonWrapper;v?.parentNode&&Te.contains(v)?v.parentNode.insertBefore(In,v):Te.appendChild(In)}if(!mo||!In)return;let s=Sa()||ne&&ie==="rail";if(In.style.display=s?"none":"",s){document.activeElement===mo&&Fd();return}let l=Vy();mo.disabled=l,mo.setAttribute("aria-disabled",l?"true":"false");let f=l?Ye.openHistoryBusyLabel:Ye.openHistoryLabel;mo.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(mo.removeAttribute("aria-expanded"),mo.removeAttribute("aria-controls")):(mo.setAttribute("aria-expanded",ne?"true":"false"),mo.setAttribute("aria-controls",$p))},Kd=!1,IM=()=>{let s=_e.clearChatButton;if(s){if(Rn()){Kd||(qp=s.getAttribute("aria-label")??"",Kd=!0),s.setAttribute("aria-label",Ye.newConversationLabel),s.removeAttribute("title");return}Kd&&(Kd=!1,qp&&s.setAttribute("aria-label",qp))}},Hr=()=>{Ye=lh(n.features?.history?.copy),Mb(),qi(),IM(),sr()};wt=Hr,$e=s=>{Pd=s,at?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),Ii(s.sendBlocked||Fo),sr()},Ht=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Dt.clear(),hn(),ko()),Id(s.message),at?.view.refresh()},Xy(),Hr(),ye.push(()=>{kd?.(),Ld?.(),Wi+=1,Ud(),at?.dispose(),at?.view.destroy(),at=null}),n.clientToken&&H.initClientSession().then(()=>{if(Rn())return H.reconcileBootConversation({scope:jp()})}).then(()=>{sr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(Rt||n.onSSEEvent)&&H.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),$(s,l)});let Tb=()=>{let s=n.resume??(Hp?tr.getStoredResumableHandle?.():null);s&&typeof n.reconnectStream=="function"&&H.resumeFromHandle(s)};G?G.then(s=>{if(s){if(s.metadata&&(X=dh(s.metadata),Ee.syncFromMetadata()),s.messages?.length){da=!0;try{H.hydrateMessages(s.messages)}finally{da=!1}xd()}s.artifacts?.length&&H.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),Sy(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{Ep=!0,E(),Tb()}):(Sy(D),Tb());let RM=()=>{!Ae()||he||!(n.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},HM=(s,l)=>s?l?{refs:[...s.refs,...l.refs],finalize:async()=>{let[f,g]=await Promise.allSettled([s.finalize(),l.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),g.status==="fulfilled"?v.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),YL(v)}}:s:l,pf=()=>{let l=le.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},ar=!1,ks=null,Gd=()=>{le.value="",le.style.height="auto",Mn(),zi()},ff="data-persona-composer-notice",Aa=null;function WM(s){Gl(s),!(Ae()||!st)&&(st.hasAttribute(li)||(st.setAttribute(ff,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=s,Aa&&clearTimeout(Aa),Aa=setTimeout(()=>{if(Aa=null,!!st?.hasAttribute(ff)&&(st.removeAttribute(ff),st.removeAttribute("role"),st.removeAttribute("aria-live"),u)){let l=H.getStatus();ao(st,fo(l),n.statusIndicator??{},l)}},4e3)))}function BM(){let s=Se.getState().pendingSubmission;s&&(ta(void 0),le&&(le.value=s.text,le.dispatchEvent(new Event("input",{bubbles:!0})),Mn()),s.options.selectedModelId&&(Se.setSelectedModelId(s.options.selectedModelId),Cr?.repaint()),s.options.activeModeIds?.length&&Jl(s.options.activeModeIds),s.options.quote&&Tn(s.options.quote),le?.focus())}let OM=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},Eb=(s={})=>{let l=(s.overrideText??le?.value??"").trim();return s.resolveInlineCommand&&l?(Wt?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>Pb(s,l,f)):Pb(s,l,null)},Pb=(s,l,f)=>{if(f?.kind==="action"){Gd(),Wt?.clear(),rs();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,M=s.pending?.contentParts,N=(Ze?.hasAttachments()??!1)||(M?.length??0)>0;if(!TC({text:v,hasAttachments:N,attachmentsReady:Ze?.isReady()??!0,hasMentions:Wt?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Lr(),sendDisabled:xs()}))return;let z=H.isStreaming()?tp():"block";if(z==="defer-one"&&!s.pending){if(Se.getState().pendingSubmission){WM("One message is already queued. Edit or remove it first.");return}DM({intent:s,sendText:v,serverMentions:g});return}let V={text:v,mentionRefs:[...Wt?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:pf(),options:{...Se.getState().selectedModelId&&{selectedModelId:Se.getState().selectedModelId},...Se.getState().activeModeIds.length>0&&{activeModeIds:[...Se.getState().activeModeIds]},...Se.getState().quote&&{quote:{...Se.getState().quote}}},viaVoice:s.viaVoice};s.pending&&(V.options={...s.pending.options},V.contentSegments=s.pending.contentSegments,V.mentionRefs=[...s.pending.mentionRefs],V.viaVoice=s.pending.viaVoice);let K=()=>{if(M?.length)return[...M];if(!Ze?.hasAttachments())return;let ct=[...Ze.getContentParts()];return V.text&&ct.push(an(V.text)),ct};V.contentParts=K();let J=()=>{fs(),RM();let ct=Wt?.collectForSubmit()??null,Qt=HM(ct,g),Nt=K();s.consumeDraft!==!1&&Gd();let Lt={selectedModelId:V.options.selectedModelId,activeModeIds:V.options.activeModeIds},io=z==="interrupt";io&&H.cancel(),H.sendMessage(V.text,{contentParts:Nt,mentions:Qt??void 0,contentSegments:V.contentSegments,viaVoice:V.viaVoice,composerOptions:Lt,...V.options.quote&&{quote:V.options.quote},...io&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),ct&&Wt?.clear(),rs();let et=Se.getState().activeModeIds,lo=pC(et,n.composer?.modes);lo.length!==et.length&&Jl(lo),Se.getState().quote&&Tn(void 0),gd(),ap.release(),pn()},ae=n.composer?.onBeforeSend;if(!ae){J();return}let fe=new AbortController;ks=fe;let Je=ct=>{if(ks=null,ct.status==="error"){OM(ct.error);return}ct.status==="proceed"&&J()},lt=EC(ae,V,fe.signal);if(!(lt instanceof Promise)){Je(lt);return}return Se.setPreparing(!0),lt.then(Je).finally(()=>Se.setPreparing(!1))};function DM(s){let l=Se.getState(),f=Ze?.hasAttachments()??!1,g=f?[...Ze.getContentParts()]:[];f&&s.sendText&&g.push(an(s.sendText));let v=rg({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Wt?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:pf(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});ta(v),s.intent.consumeDraft!==!1&&Gd(),f&&Ze.clearAttachments(),Wt?.clear(),rs(),l.quote&&Tn(void 0),gd(),ap.release(),pn(),Gl("Message queued. It sends when the response finishes.")}function _M(){let s=Se.getState().pendingSubmission;s&&(ta(void 0),Qd(s.text,{consumeDraft:!1,pending:s}))}function NM(s){if(n.messageActions?.showEdit!==!0)return;let l=H.getMessages().find(f=>f.id===s);!l||!Qf(l)||ps!==s&&(fs(),ps=s,Mr=yC({messageId:s,initialText:l.content,onSave:f=>FM(s,f),onCancel:()=>fs()}),Dt.delete(s),Jo(ke,H.getMessages(),oo),Mr.focus())}function FM(s,l){let f=Mr;if(ps=null,Mr=null,f?.destroy(),Dt.delete(s),!H.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Jo(ke,H.getMessages(),oo);return}Lo()}function UM(s){if(H.isStreaming())return;let l=Xf(H.getMessages(),s);l&&(fs(),H.resubmitFrom(l,{reason:"retry"})&&Lo())}Zl={regenerate:UM,edit:NM,quote:s=>{let f=H.getMessages().find(g=>g.id===s)?.content?.trim();f&&(Tn({text:f,messageId:s}),le?.focus())}};let ji=async s=>{if(!ar){ar=!0;try{await Eb({resolveInlineCommand:!0,...s})}finally{ar=!1}}};function Xd(s){xs()||(Gd(),Qd(s,{consumeDraft:!1}))}let Qd=(s,l)=>{if(ar)return;ar=!0;let f=()=>{ar=!1};try{let g=Eb({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},qM=s=>{if(s.preventDefault(),H.isStreaming()){H.cancel(),ut?.reset(),B?.update();return}ar||ji()},$M=()=>n.features?.composerHistory!==!1,mf={...fg},gf=!1,zi=()=>{mf={...fg}},VM=()=>H.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),jM=s=>{if(!le)return;gf=!0,le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),gf=!1;let l=le.value.length;le.setSelectionRange(l,l)},zM=s=>{gf||(s.isComposing||Wt?.handleInput(s.inputType??void 0),zi())},KM=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Cl(le)}),GM=s=>{if(le&&!Lr()&&!(!s.isComposing&&Wt?.handleKeydown(s))){if($M()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=le.selectionStart===0&&le.selectionEnd===0,f=KC({direction:s.key==="ArrowUp"?"up":"down",history:VM(),currentValue:le.value,atStart:l,state:mf});if(mf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&jM(f.value);return}}if(Qx(s,KM())){if(H.isStreaming()){if(s.preventDefault(),tp()==="block"||ar||xs())return;zi(),ji();return}if(ar){s.preventDefault();return}if(xs()){s.preventDefault();return}zi(),s.preventDefault(),Me.click()}}},kb=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(ue)){if(ks){ks.abort(),ks=null,s.preventDefault(),s.stopImmediatePropagation();return}H.isStreaming()&&(H.cancel(),ut?.reset(),B?.update(),zi(),s.preventDefault(),s.stopImmediatePropagation())}},XM=async s=>{if(n.attachments?.enabled!==!0||!Ze||Lr())return;let l=KL(s.clipboardData);l.length!==0&&(s.preventDefault(),await Ze.handleFiles(l))},on=null,Hn=!1,Ma=null,vt=null,hf=()=>n.voiceRecognition?.completionBehavior==="review";function Ls(s){se?.setAttribute("data-state",s),s==="recording"?YM():xf()}let Lb="--persona-voice-level",yf=.5,Ta=null,bf=-1,Yd=0,Ib=()=>{let s=[],l=_o??se?.parentElement??null;return l&&s.push(l),Ie&&s.push(Ie),s},vf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==bf){bf=l;for(let f of Ib())f.style.setProperty(Lb,String(l))}},QM=()=>{bf=-1,Yd=0;for(let s of Ib())s.style.removeProperty(Lb)};function YM(){if(Ta!==null)return;if(typeof requestAnimationFrame!="function"){vf(u?H.getVoiceLevel()??yf:yf);return}let s=()=>{Ta=requestAnimationFrame(s);let l=u?H.getVoiceLevel():null;if(l===null){vf(yf);return}Yd+=(l-Yd)*.3,vf(Yd)};Ta=requestAnimationFrame(s)}function xf(){Ta!==null&&(cancelAnimationFrame(Ta),Ta=null),QM()}let Rb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jd=(s="user")=>{if(Hn||H.isStreaming())return;let l=Rb();if(!l)return;on=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;on.continuous=f.provider?.browser?.continuous??!0,on.interimResults=!0,on.lang=f.provider?.browser?.language??"en-US";let v=le.value;on.onresult=M=>{let N="",z="";for(let K=0;K<M.results.length;K++){let J=M.results[K],ae=J[0].transcript;J.isFinal?N+=ae+" ":z=ae}let V=v+N+z;le.value=V,Mn(),Ma&&clearTimeout(Ma),(N||z)&&(Ma=window.setTimeout(()=>{if(le.value.trim()&&on&&Hn){if(Wr(),hf())return;ji({viaVoice:!0})}},g))},on.onerror=M=>{M.error!=="no-speech"&&Wr()},on.onend=()=>{if(Hn){let M=le.value.trim();!hf()&&M&&M!==v.trim()&&ji({viaVoice:!0}),Wr()}};try{if(on.start(),Hn=!0,je.active=!0,s!=="system"&&(je.manuallyDeactivated=!1),Jn(s),gn(),pn(),se){let M=n.voiceRecognition??{};vt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:M.iconName??"mic",iconSize:parseFloat(M.iconSize??"")||vo};let N=M.recordingBackgroundColor,z=M.recordingIconColor,V=M.recordingBorderColor;if(se.classList.add("persona-voice-recording"),Ls("recording"),se.style.backgroundColor=N??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let K=se.querySelector("svg");K&&K.setAttribute("stroke",z)}V&&(se.style.borderColor=V),se.setAttribute("aria-label","Stop voice recognition")}}catch{Wr("system")}},Wr=(s="user")=>{if(Hn){if(Hn=!1,Ma&&(clearTimeout(Ma),Ma=null),on){try{on.stop()}catch{}on=null}if(je.active=!1,Jn(s),gn(),pn(),se){if(se.classList.remove("persona-voice-recording"),Ls("idle"),vt){se.style.backgroundColor=vt.backgroundColor,se.style.color=vt.color,se.style.borderColor=vt.borderColor;let l=se.querySelector("svg");l&&l.setAttribute("stroke",vt.color||"currentColor"),vt=null}se.setAttribute("aria-label","Start voice recognition")}}},Cf=()=>{if(!se||vt)return;let s=n.voiceRecognition??{};vt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||vo}},Sf=(s,l)=>{if(!se)return;let f=se.querySelector("svg");f&&f.remove();let g=vt?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||vo),v=ce(s,g,l,1.5);v&&se.appendChild(v)},Zd=()=>{se&&se.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ea=()=>{if(!se)return;Cf();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(Zd(),se.classList.add("persona-voice-recording"),Ls("recording"),se.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=se.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(se.style.borderColor=g),se.setAttribute("aria-label","Stop voice recognition")},JM=()=>{if(!se)return;Cf();let s=n.voiceRecognition??{},l=H.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??vt?.color??"",v=s.processingBackgroundColor??vt?.backgroundColor??"",M=s.processingBorderColor??vt?.borderColor??"";Zd(),se.classList.add("persona-voice-processing"),Ls("processing"),se.style.backgroundColor=v,se.style.borderColor=M;let N=g||"currentColor";se.style.color=N,Sf(f,N),se.setAttribute("aria-label","Processing voice input"),l==="none"&&(se.style.cursor="default")},ZM=()=>{if(!se)return;Cf();let s=n.voiceRecognition??{},l=H.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??vt?.color??"":vt?.color??""),M=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),N=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":vt?.borderColor??"");Zd(),se.classList.add("persona-voice-speaking"),Ls("speaking"),se.style.backgroundColor=M,se.style.borderColor=N;let z=v||"currentColor";se.style.color=z,Sf(g,z);let V=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";se.setAttribute("aria-label",V),l==="none"&&(se.style.cursor="default"),l==="barge-in"&&se.classList.add("persona-voice-recording")},ir=()=>{se&&(Zd(),Ls("idle"),vt&&(se.style.backgroundColor=vt.backgroundColor??"",se.style.color=vt.color??"",se.style.borderColor=vt.borderColor??"",Sf(vt.iconName,vt.color||"currentColor"),vt=null),se.style.cursor="",se.setAttribute("aria-label","Start voice recognition"))},wf=()=>{if(!Lr()){if(n.voiceRecognition?.provider?.type==="runtype"){let s=H.getVoiceStatus(),l=H.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,gn(),Jn("user"),ir()});return}H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),je.manuallyDeactivated=!H.isVoiceActive(),gn(),Jn("user"),H.isVoiceActive()?Ea():ir()});return}if(Hn){let s=le.value.trim();je.manuallyDeactivated=!0,gn(),Wr("user"),s&&!hf()&&ji()}else je.manuallyDeactivated=!1,gn(),Jd("user")}};op=wf,se&&ye.push(()=>{n.voiceRecognition?.provider?.type==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),ir()):Wr("system")});let eT=C.on("assistant:complete",()=>{Se.getState().pendingSubmission&&setTimeout(()=>{H.isStreaming()||_M()},0)});ye.push(eT);let tT=C.on("assistant:complete",()=>{vy&&(je.active||je.manuallyDeactivated||vy==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(n.voiceRecognition?.provider?.type==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),Jn("auto"),H.isVoiceActive()&&Ea()}):Jd("auto"))},600))});ye.push(tT);let oT=C.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});ye.push(oT);let Hb=()=>{dt(!he,"user")},Pt=null,go=null;if(ge&&!Ae()){let{instance:s,element:l}=qg({config:n,plugins:i,onToggle:Hb});Pt=s,s||(go=l)}Pt?e.appendChild(Pt.element):go&&e.appendChild(go),Li(),ia(),wd(),Rp(),Ii(H.isStreaming()),Cp()||(No()==="follow"?Pr(!0):hd()),SA(),Bt&&(!ge||Ae()?setTimeout(()=>Cs(),0):he&&setTimeout(()=>Cs(),200));let Is=null,Wb=()=>{Is&&(Is.disconnect(),Is.observe(Ie),Is.observe(ue))},Ki=()=>{if(Ae()){ns(),Li();return}let s=St(n),l=n.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,g=n.launcher?.mobileFullscreen??!0,v=n.launcher?.mobileBreakpoint??640,M=f.innerWidth<=v,N=g&&M&&ge;try{if(N){ss(),vi=id();return}let z=!1;Ge&&(Ge=!1,ss(),z=!0);let V=id();if(!z&&V!==vi&&(ss(),z=!0),vi=V,z&&nd(),!ge&&!s){we.style.height="",we.style.width="";return}if(!l&&!s){let J=n?.launcher?.width??n?.launcherWidth??zo;we.style.width=J,we.style.maxWidth=J}ad(),ny()}finally{if(ns(),Yl(),Li(),he&&ge){let V=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),K=n.launcher?.sidebarMode??!1,J=n.launcher?.mobileFullscreen??!0,ae=St(n)&&J&&V,fe=K||J&&V&&ge||ae;if(fe&&!Ln){let Je=e.getRootNode(),lt=Je instanceof ShadowRoot?Je.host:e.closest(".persona-host");lt&&!kn&&(kn=vg(lt,n.launcher?.zIndex??so)),Ln=xg(e.ownerDocument)}else fe||(kn?.(),kn=null,Ln?.(),Ln=null)}}};Ki();let ec=e.ownerDocument.defaultView??window;if(ec.addEventListener("resize",Ki),ye.push(()=>ec.removeEventListener("resize",Ki)),typeof ResizeObserver<"u"){Is=new ResizeObserver(()=>{Yl()}),Wb(),ye.push(()=>{Is?.disconnect(),Is=null});let s=new ResizeObserver(()=>{Nd()});s.observe(ue),ye.push(()=>s.disconnect())}ec.addEventListener("resize",Nd),ye.push(()=>ec.removeEventListener("resize",Nd)),qo=re.scrollTop;let Bb=Vn(re),Ob=()=>{let s=re.scrollTop,l=Vn(re),f=l<Bb;if(Bb=l,!xr()){qo=s,Vt();return}let{action:g,nextLastScrollTop:v}=tS({following:Uo.isFollowing(),currentScrollTop:s,lastScrollTop:qo,nearBottom:qs(re,Qn),userScrollThreshold:bA,isAutoScrolling:Po||dd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qo=v,g==="resume"){yd()||ko();return}g==="pause"&&Mi()};if(re.addEventListener("scroll",Ob,{passive:!0}),ye.push(()=>re.removeEventListener("scroll",Ob)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{kA(),Lf(ke)});s.observe(ke),s.observe(re),ye.push(()=>s.disconnect())}let Db=()=>{xr()&&Uo.isFollowing()&&yd()&&Mi()},_b=re.ownerDocument;_b.addEventListener("selectionchange",Db),ye.push(()=>{_b.removeEventListener("selectionchange",Db)});let nT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Nb=s=>{nT.has(s.key)&&(ys(),Ah()&&xr()&&Uo.isFollowing()&&Mi())},Fb=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(ys(),Ah()&&xr()&&Uo.isFollowing()&&Mi())};re.addEventListener("keydown",Nb),re.addEventListener("focusin",Fb),ye.push(()=>{re.removeEventListener("keydown",Nb),re.removeEventListener("focusin",Fb)});let Ub=s=>{if(s.deltaY!==0&&ys(),!xr())return;let l=oS({following:Uo.isFollowing(),deltaY:s.deltaY,nearBottom:qs(re,Qn),resumeWhenNearBottom:!0});l==="pause"?Mi():l==="resume"&&!yd()&&ko()};re.addEventListener("wheel",Ub,{passive:!0}),re.addEventListener("touchmove",ys,{passive:!0}),re.addEventListener("pointerdown",ys,{passive:!0}),ye.push(()=>{re.removeEventListener("touchmove",ys),re.removeEventListener("pointerdown",ys)}),ye.push(()=>re.removeEventListener("wheel",Ub)),Ot.addEventListener("click",()=>{hn(),re.scrollTop=re.scrollHeight,qo=re.scrollTop,ko(),Pr(!0),Vt()}),ye.push(()=>Ot.remove()),ye.push(()=>{Ay(),hn()});let qb=()=>{Ue&&(ds&&(Ue.removeEventListener("click",ds),ds=null),De()?(Ue.style.display="",ds=()=>{dt(!1,"user")},Ue.addEventListener("click",ds)):Ue.style.display="none")};qb(),(()=>{let{clearChatButton:s}=_e;s&&s.addEventListener("click",()=>{if(Rn()){df({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}H.clearMessages(),Dt.clear(),ko(),$r(_e.composerOverlay);try{localStorage.removeItem(ii),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ii}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ii)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),X={},Ee.syncFromMetadata(),Ze?.clearAttachments(),gd(),ta(void 0),Tn(void 0),fs(),Tt?.clear(),ut?.reset(),B?.update()})})();let $b=[["keydown",GM],["input",zM],["input",Mn],["input",rs],["keyup",rs],["paste",XM],["focus",aA]],Vb=s=>{if(s)for(let[l,f]of $b)ot?.addListener(s,l,f)},rT=s=>{if(s)for(let[l,f]of $b)ot?.removeListener(s,l,f)},jb=()=>{ot&&(ot.addListener(ot.form,"submit",qM),ot.addListener(ot.footer,"click",rs),Vb(le),se&&ot.addListener(se,"click",wf))};jb();let zb=()=>{Wt?.onComposerSwap((s,l)=>{rT(l),le=s,ot&&(ot.input=s),Vb(s),rp(),Mp(),Mn()})};zb();let Af=!1;function Kb(){if(!Af){Af=!0;try{let s=le?.value??"",l=Ie.ownerDocument??document,f=le?l.activeElement===le:!1;xf(),ot?.destroy(),ot=null,Wt?.destroy(),Wt=null;let g=null,v=()=>(g=Ae()?xu({config:n}):Ks({config:n}),g.footer),M=Wh(v)??v();Oo.replaceComposer(M),Ie=Oo.composer.footer;let N=g!==null&&M===g.footer;na=!N,wh=N?g.setSendButtonMode:()=>{},Hh(Ie),Oh(Ie),Dh(),_h(),Nh(),zb(),Fh(),sp(),Uh(),jb();let z=ls.indexOf(Xn);Xn.destroy(),Xn=Bl(br),z>=0&&(ls[z]=Xn),le&&(le.value=s),Mn(),rs(),wd(),ia(),Ii(H.isStreaming()),je.active&&Ls("recording"),ss(),Wb(),ns(),pn(),Cd(),f&&le?.focus()}finally{Af=!1}}}let Gi=e.ownerDocument??document;Gi.addEventListener("keydown",kb,!0);let Gb=()=>{yp()},Xb=()=>{Gi.visibilityState==="hidden"&&yp()};typeof window<"u"&&(window.addEventListener("pagehide",Gb),Gi.addEventListener("visibilitychange",Xb),ye.push(()=>{window.removeEventListener("pagehide",Gb),Gi.removeEventListener("visibilitychange",Xb)}));let Qb="persona-attachment-drop-active",Xi=0,Mf=()=>{Xi=0,ue.classList.remove(Qb)},Pa=()=>n.attachments?.enabled===!0&&Ze!==null&&!Lr(),Yb=s=>{!$u(s.dataTransfer)||!Pa()||(Xi++,Xi===1&&ue.classList.add(Qb))},Jb=s=>{!$u(s.dataTransfer)||!Pa()||(Xi--,Xi<=0&&Mf())},Zb=s=>{!$u(s.dataTransfer)||!Pa()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},ev=s=>{if(!$u(s.dataTransfer)||!Pa())return;s.preventDefault(),s.stopPropagation(),Mf();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&Ze.handleFiles(l)},Br=!0;ue.addEventListener("dragenter",Yb,Br),ue.addEventListener("dragleave",Jb,Br),e.addEventListener("dragover",Zb,Br),e.addEventListener("drop",ev,Br);let tc=e.ownerDocument,tv=s=>{Pa()&&s.preventDefault()},ov=s=>{Pa()&&s.preventDefault()};tc.addEventListener("dragover",tv),tc.addEventListener("drop",ov),ye.push(()=>{ot?.destroy(),ot=null,xf(),En?.destroy(),En=null,Kn?.destroy(),Kn=null,Sr?.destroy(),Sr=null,wr?.destroy(),wr=null,Cr=null,ep=null,yp(),Ai.destroy(),Aa&&clearTimeout(Aa),fs(),ks?.abort(),ks=null,Ze?.destroy(),Ze=null,Se.destroy(),Gi.removeEventListener("keydown",kb,!0),Wt?.destroy()}),ye.push(()=>{ue.removeEventListener("dragenter",Yb,Br),ue.removeEventListener("dragleave",Jb,Br),e.removeEventListener("dragover",Zb,Br),e.removeEventListener("drop",ev,Br),tc.removeEventListener("dragover",tv),tc.removeEventListener("drop",ov),Mf()}),ye.push(()=>{H.cancel()}),Pt?ye.push(()=>{Pt?.destroy()}):go&&ye.push(()=>{go?.remove()});let kt={update(s){let l=n.toolCall,f=n.messageActions,g=n.layout?.messages,v=n.colorScheme,M=n.loadingIndicator,N=n.iterationDisplay,z=n.features?.showReasoning,V=n.features?.showToolCalls,K=n.features?.toolCallDisplay,J=n.features?.reasoningDisplay,ae=n.features?.streamAnimation?.type,fe=n.features?.history?.enabled===!0,Je=n.features?.history?.provider,lt=n.getIdentityProof,ct=n.clientToken,Qt=n.contextMentions;n=Bu({...n,features:a},s),a=n.features,n=Nl(n),r(),up(),Us(e,n),Dl(e,n),_l(e,n),ht(),mn(),n.colorScheme!==v&&ry();let Nt=Fl.getForInstance(n.plugins);i.length=0,i.push(...Nt),nb(),ge=n.launcher?.enabled??!0,Ke=n.launcher?.autoExpand??!1,Xo=n.features?.showReasoning??!0,Sn=n.features?.showToolCalls??!0,Jr=n.features?.scrollToBottom??{};let Lt=No();Ao=n.features?.scrollBehavior??{},Lt!==No()&&(hn(),ko()),by(),Eh(),Vt();let io=Rt;if(Rt=n.features?.showEventStreamToggle??!1,Rt&&!io){if(Tt||(oe(),H.setSSEEventCallback((Z,ze)=>{n.onSSEEvent?.(Z,ze),$(Z,ze)})),!tt&&Te){let Z=n.features?.eventStream?.classNames,ze="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Z?.toggleButton?" "+Z.toggleButton:"");tt=I("button",ze),tt.style.width="28px",tt.style.height="28px",tt.style.color=Co.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Qe=Ft(Na,"18px","currentColor",1.5);Qe&&tt.appendChild(Qe);let nt=_e.clearChatButtonWrapper,Ct=_e.closeButtonWrapper,no=nt||Ct;no&&no.parentNode===Te?Te.insertBefore(tt,no):Te.appendChild(tt),tt.addEventListener("click",()=>{ee?oa():np()})}}else!Rt&&io&&(oa(),tt&&(tt.remove(),tt=null),Tt?.clear(),po?.destroy(),Tt=null,po=null,ut?.reset(),ut=null,cn=null);if(n.launcher?.enabled===!1&&Pt&&(Pt.destroy(),Pt=null),n.launcher?.enabled===!1&&go&&(go.remove(),go=null),n.launcher?.enabled!==!1&&!Pt&&!go){let{instance:Z,element:ze}=qg({config:n,plugins:i,onToggle:Hb});Pt=Z,Z||(go=ze),e.appendChild(ze)}Pt&&Pt.update(n),Vi(),ts&&n.launcher?.subtitle!==void 0&&(ts.textContent=n.launcher.subtitle);let et=n.layout?.header;if(et?.layout!==qe&&Te){let Z=et?Ya(n,et,{showClose:De(),onClose:()=>dt(!1,"user")}):mr({config:n,showClose:De(),onClose:()=>dt(!1,"user")});Oo.replaceHeader(Z),Te=Oo.header.element,Et=Oo.header.iconHolder,vr=Oo.header.headerTitle,ts=Oo.header.headerSubtitle,Ue=Oo.header.closeButton,qe=et?.layout,Vi()}else if(et){if(Et&&(Et.style.display=et.showIcon===!1?"none":""),vr&&(vr.style.display=et.showTitle===!1?"none":""),ts&&(ts.style.display=et.showSubtitle===!1?"none":""),Ue){let Z=De()&&et.showCloseButton!==!1;Ue.style.display=Z?"":"none"}if(_e.clearChatButtonWrapper){let Z=et.showClearChat;if(Z!==void 0){_e.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ze}=_e;ze&&!ze.classList.contains("persona-absolute")&&(Z?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let lr=n.layout?.showHeader!==!1;Te&&(Te.style.display=lr?"":"none");let Wn=n.layout?.showFooter!==!1;Ie&&(Ie.style.display=Wn?"":"none"),ns(),Vt(),ge!==j?ge?dt(Ke,"auto"):(he=!0,Li()):Ke!==Le&&dt(Ke,"auto"),Le=Ke,j=ge,Ki(),qb();let We=JSON.stringify(n.toolCall)!==JSON.stringify(l),Oe=JSON.stringify(n.messageActions)!==JSON.stringify(f),me=JSON.stringify(n.layout?.messages)!==JSON.stringify(g),pt=n.loadingIndicator?.render!==M?.render||n.loadingIndicator?.renderIdle!==M?.renderIdle||n.loadingIndicator?.showBubble!==M?.showBubble,jt=n.iterationDisplay!==N,co=(n.features?.showReasoning??!0)!==(z??!0)||(n.features?.showToolCalls??!0)!==(V??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(K)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(J);(We||Oe||me||pt||jt||co)&&H&&(ms++,Jo(ke,H.getMessages(),oo));let It=n.features?.streamAnimation?.type;if(It!==ae&&It&&It!=="none"){let Z=fp(It,n.features?.streamAnimation?.plugins);Z&&Rl(Z,e)}let Pe=n.launcher??{},zt=Pe.headerIconHidden??!1,Kt=n.layout?.header?.showIcon,rn=zt||Kt===!1,Re=Pe.headerIconName,xt=Pe.headerIconSize??"48px";if(Et){let Z=Te,ze=Z?.querySelector(".persona-flex-col");if(rn)Et.style.display="none",Z&&ze&&!Z.contains(ze)&&Z.insertBefore(ze,Z.firstChild);else{if(Et.style.display="",Et.style.height=xt,Et.style.width=xt,Z&&ze&&(Z.contains(Et)?Et.nextSibling!==ze&&(Et.remove(),Z.insertBefore(Et,ze)):Z.insertBefore(Et,ze)),Re){let nt=parseFloat(xt)||24,Ct=ce(Re,nt*.6,"currentColor",1);Ct?Et.replaceChildren(Ct):Et.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let nt=Et.querySelector("img");if(nt)nt.src=Pe.iconUrl,nt.style.height=xt,nt.style.width=xt;else{let Ct=document.createElement("img");Ct.src=Pe.iconUrl,Ct.alt="",Ct.className="persona-rounded-xl persona-object-cover",Ct.style.height=xt,Ct.style.width=xt,Et.replaceChildren(Ct)}}else{let nt=Et.querySelector("svg"),Ct=Et.querySelector("img");(nt||Ct)&&Et.replaceChildren(),Et.textContent=Pe.agentIconText??"\u{1F4AC}"}let Qe=Et.querySelector("img");Qe&&(Qe.style.height=xt,Qe.style.width=xt)}}let On=n.layout?.header?.showTitle,yn=n.layout?.header?.showSubtitle;if(vr&&(vr.style.display=On===!1?"none":""),ts&&(ts.style.display=yn===!1?"none":""),Ue){let Z=De()&&n.layout?.header?.showCloseButton!==!1;if(Ue.style.display=Z?"":"none",!Ae()){let Yt=Pe.closeButtonSize??"";Ue.style.height=Yt,Ue.style.width=Yt,Ue.style.minWidth=Yt,Ue.style.minHeight=Yt}let ze=Pe.closeButtonPlacement??"inline",{closeButtonWrapper:Qe}=_e,nt=ze==="top-right",Ct=Qe?.classList.contains("persona-absolute");if(Qe&&nt!==Ct)if(Qe.remove(),nt){Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Yt=Oi??ue;Yt.style.position="relative",Yt.appendChild(Qe)}else{let Yt=Pe.clearChat?.placement??"inline",Jt=Pe.clearChat?.enabled??!0;Qe.className=Jt&&Yt==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Qe)}if(Ue.style.color=Pe.closeButtonColor||Co.actionIconColor,Pe.closeButtonBackgroundColor?(Ue.style.backgroundColor=Pe.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Yt=Pe.closeButtonBorderWidth||"0px",Jt=Pe.closeButtonBorderColor||"transparent";Ue.style.border=`${Yt} solid ${Jt}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(Ue.style.borderRadius=Pe.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(Ue.style.paddingLeft=Pe.closeButtonPaddingX,Ue.style.paddingRight=Pe.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Pe.closeButtonPaddingY?(Ue.style.paddingTop=Pe.closeButtonPaddingY,Ue.style.paddingBottom=Pe.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),yu(Ue,Pe.closeButtonIconName??"x",{iconSize:Ae()?_g:void 0,iconText:Pe.closeButtonIconText??"\xD7"});let no=Pe.closeButtonTooltipText??"Close chat",bn=Pe.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",no),Qe&&eo({anchor:Ue,trigger:Qe,text:()=>Ue?.getAttribute("aria-label")??no,enabled:bn})}let{clearChatButton:Be,clearChatButtonWrapper:ve}=_e;if(Be){let Z=Pe.clearChat??{},ze=Z.enabled??!0,Qe=n.layout?.header?.showClearChat,nt=Qe!==void 0?Qe:ze,Ct=Z.placement??"inline";if(ve){ve.style.display=nt?"":"none";let{closeButtonWrapper:no}=_e;!Ae()&&no&&!no.classList.contains("persona-absolute")&&(nt?no.classList.remove("persona-ml-auto"):no.classList.add("persona-ml-auto"));let bn=Ct==="top-right",Yt=ve.classList.contains("persona-absolute");if(!Ae()&&bn!==Yt&&nt){if(ve.remove(),bn){ve.className="persona-absolute persona-top-4 persona-z-50",ve.style.right="48px";let Dn=Oi??ue;Dn.style.position="relative",Dn.appendChild(ve)}else{ve.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ve.style.right="";let Dn=_e.closeButtonWrapper;Te&&Dn&&Dn.parentElement===Te?Te.insertBefore(ve,Dn):Te&&Te.appendChild(ve)}let Jt=_e.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(bn?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(nt){if(!Ae()){let Jt=Z.size??"";Be.style.height=Jt,Be.style.width=Jt,Be.style.minWidth=Jt,Be.style.minHeight=Jt}let no=Z.iconColor??"";if(Be.style.color=no||Co.actionIconColor,yu(Be,Z.iconName??"refresh-cw",{iconSize:Ae()?Ng:void 0}),Z.backgroundColor?(Be.style.backgroundColor=Z.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let Jt=Z.borderWidth||"0px",Dn=Z.borderColor||"transparent";Be.style.border=`${Jt} solid ${Dn}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");Z.borderRadius?(Be.style.borderRadius=Z.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),Z.paddingX?(Be.style.paddingLeft=Z.paddingX,Be.style.paddingRight=Z.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),Z.paddingY?(Be.style.paddingTop=Z.paddingY,Be.style.paddingBottom=Z.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let bn=Z.tooltipText??"Clear chat",Yt=Z.showTooltip??!0;Be.setAttribute("aria-label",bn),ve&&eo({anchor:Be,trigger:ve,text:()=>Be?.getAttribute("aria-label")??bn,enabled:Yt})}}let Ne=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Ul],ft=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Ys.message,Ys.messageAndClick];Ee=ql({parsers:Ne,handlers:ft,getSessionMetadata:Q,updateSessionMetadata:de,emit:C.emit,documentRef:typeof document<"u"?document:null}),oo=Aw(n,Ee,Js),KA(),H.updateConfig(n),(n.features?.history?.enabled===!0!==fe||n.features?.history?.provider!==Je||n.getIdentityProof!==lt||n.clientToken!==ct)&&(Io({restoreFocus:!1}),Xy()),Hr(),Nd(),Jo(ke,H.getMessages(),oo),ia(),wd(),jA(),Ii(H.isStreaming()),Qt!==n.contextMentions&&Kb();let Or=n.voiceRecognition?.enabled===!0,Gt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),jo=n.voiceRecognition?.provider?.type==="runtype";if(Or&&(Gt||jo))if(!se||!_o){let Z=za(n);if(Z){se=Z.button,_o=Z.wrapper;let ze=An&&An.parentElement===zl?An:null;zl?zl.insertBefore(_o,ze):un?.appendChild(_o),ot&&(ot.micButton=se),ot?.addListener(se,"click",wf),se.disabled=H.isStreaming()}}else{let Z=n.voiceRecognition??{},ze=n.sendButton??{},Qe=Z.iconName??"mic",nt=Z.iconSize,Ct=parseFloat(nt??"")||vo;se.classList.add(Ko),se.classList.toggle(vn,!nt),se.style.width=nt??"",se.style.height=nt??"",se.style.minWidth=nt??"",se.style.minHeight=nt??"";let no=Z.iconColor??ze.textColor;se.innerHTML="";let bn=ce(Qe,Ct,no||"currentColor",1.5);bn?se.appendChild(bn):se.textContent="\u{1F3A4}";let Yt=Z.backgroundColor??ze.backgroundColor;Yt?se.style.backgroundColor=Yt:se.style.backgroundColor="",no?se.style.color=no:se.style.color="var(--persona-text, #111827)",Z.borderWidth?(se.style.borderWidth=Z.borderWidth,se.style.borderStyle="solid"):(se.style.borderWidth="",se.style.borderStyle=""),Z.borderColor?se.style.borderColor=Z.borderColor:se.style.borderColor="",Z.paddingX?(se.style.paddingLeft=Z.paddingX,se.style.paddingRight=Z.paddingX):(se.style.paddingLeft="",se.style.paddingRight=""),Z.paddingY?(se.style.paddingTop=Z.paddingY,se.style.paddingBottom=Z.paddingY):(se.style.paddingTop="",se.style.paddingBottom="");let Jt=Z.tooltipText??"Start voice recognition",Dn=Z.showTooltip??!1;se.setAttribute("aria-label",Jt),_o&&eo({anchor:se,trigger:_o,text:()=>se?.getAttribute("aria-label")??Jt,enabled:Dn}),_o.style.display="",se.disabled=H.isStreaming()}else se&&_o&&(_o.style.display="none",n.voiceRecognition?.provider?.type==="runtype"?H.isVoiceActive()&&H.toggleVoice():Hn&&Wr());if(n.attachments?.enabled===!0){if(!To||!At){let Z=n.attachments??{};Eo||(Eo=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Eo.style.display="none",(le.parentElement??un).insertBefore(Eo,le)),yt||(yt=document.createElement("input"),yt.type="file",yt.accept=(Z.allowedTypes??fr).join(","),yt.multiple=(Z.maxFiles??4)>1,yt.style.display="none",yt.setAttribute("aria-label","Attach files"),(le.parentElement??un).insertBefore(yt,le)),To=I("div","persona-send-button-wrapper"),At=I("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ko} ${vn}`),At.type="button",At.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ze=Z.buttonIconName??"paperclip";At.style.fontSize="18px",At.style.lineHeight="1";let Qe=ce(ze,vo,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",At.addEventListener("click",Ct=>{Ct.preventDefault(),yt?.click()}),To.appendChild(At);let nt=Z.buttonTooltipText??"Attach file";eo({anchor:At,trigger:To,text:()=>At?.getAttribute("aria-label")??nt}),Gu?Gu.append(To):un.appendChild(To),ot&&(ot.attachmentButton=At,ot.attachmentInput=yt??void 0,ot.attachmentPreviews=Eo??void 0),!Ze&&yt&&Eo&&(Ze=Fs.fromConfig(Z,Ph),Ze.setPreviewsContainer(Eo),ot?.addListener(yt,"change",async()=>{Ze&&yt?.files&&(await Ze.handleFileSelect(yt.files),yt.value="")}))}else{To.style.display="";let Z=n.attachments??{};yt&&(yt.accept=(Z.allowedTypes??fr).join(","),yt.multiple=(Z.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Mw(n.attachments?.dropOverlay)),At){let Z=n.attachments??{},ze=Z.buttonTooltipText??"Attach file";At.setAttribute("aria-label",ze),At.textContent="";let Qe=ce(Z.buttonIconName??"paperclip",vo,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",To&&eo({anchor:At,trigger:To,text:()=>At?.getAttribute("aria-label")??ze})}}else To&&(To.style.display="none"),Ze&&Ze.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Mt=n.sendButton??{},Tf=Mt.useIcon??!1,Hs=Mt.iconText??"\u2191",oc=Mt.iconName,rv=Mt.tooltipText??"Send message",iT=Mt.showTooltip??!1,Qi=Mt.size,lT=parseFloat(Qi??"")||Xm,nc=Mt.backgroundColor,Yi=Mt.textColor;if(Tf){if(Me.style.width=Qi??"",Me.style.height=Qi??"",Me.style.minWidth=Qi??"",Me.style.minHeight=Qi??"",Me.style.fontSize="18px",Me.style.lineHeight="1",Yi?Me.style.color=Yi:Me.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!H.isStreaming())if(Me.innerHTML="",oc){let Z=parseFloat(Mt.iconSize??"")||Math.round(lT*.5),ze=Yi?.trim()||"currentColor",Qe=Mt.iconStrokeWidth??2,nt=ce(oc,Z,ze,Qe),Ct=ce(Mt.stopIconName??"square",Z,ze,Qe);nt&&Ct?Me.appendChild(Qm(nt,Ct)):nt?Me.appendChild(nt):Me.textContent=Hs}else Me.textContent=Hs;Me.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Ko}`,nc?(Me.style.backgroundColor=nc,Me.classList.remove("persona-bg-persona-primary")):(Me.style.backgroundColor="",Me.classList.add("persona-bg-persona-primary"))}else Me.textContent=n.copy?.sendButtonLabel??"Send",Me.style.width="",Me.style.height="",Me.style.minWidth="",Me.style.minHeight="",Me.style.fontSize="",Me.style.lineHeight="",Me.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",nc?(Me.style.backgroundColor=nc,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Yi?Me.style.color=Yi:Me.classList.add("persona-text-white");Mt.borderWidth?(Me.style.borderWidth=Mt.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),Mt.borderColor?Me.style.borderColor=Mt.borderColor:Me.style.borderColor="",Mt.paddingX?(Me.style.paddingLeft=Mt.paddingX,Me.style.paddingRight=Mt.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),Mt.paddingY?(Me.style.paddingTop=Mt.paddingY,Me.style.paddingBottom=Mt.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),H.isStreaming()||Me.setAttribute("aria-label",rv),Cd(),An&&eo({anchor:Me,trigger:An,text:()=>Me.getAttribute("aria-label")??rv,enabled:iT}),$h();let sv=nu(Se.getState().activeModeIds,n.composer?.modes);Se.setActiveModeIds(sv),Zs().length>0!==!!Kn&&sp(),Kn?.render(sv,Zs());for(let Z of[...ea.keys()])ou(Z,n.composer?.modeGroups)||ea.delete(Z);ea.forEach(Z=>Z.repaint()),Cr?.repaint(),En?.resolve();let rc=Gr(n,Ae());if(pp(),rc){ke.style.maxWidth=rc,ke.style.marginLeft="auto",ke.style.marginRight="auto",ke.style.width="100%",Do.style.maxWidth=rc,Do.style.marginLeft="auto",Do.style.marginRight="auto",Do.style.width="100%";for(let Z of[un,br,Eo,st])Z&&(Z.style.maxWidth=rc,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{ke.style.maxWidth="",ke.style.marginLeft="",ke.style.marginRight="",ke.style.width="",Do.style.maxWidth="",Do.style.marginLeft="",Do.style.marginRight="",Do.style.width="";for(let Z of[un,br,Eo,st])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Dr=n.statusIndicator??{},dT=Dr.visible??!0;if(st.style.display=dT?"":"none",H){let Z=H.getStatus();ao(st,(Qe=>Qe==="idle"?Dr.idleText??Ut.idle:Qe==="connecting"?Dr.connectingText??Ut.connecting:Qe==="connected"?Dr.connectedText??Ut.connected:Qe==="error"?Dr.errorText??Ut.error:Ut[Qe])(Z),Dr,Z)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let cT=Dr.align==="left"?"persona-text-left":Dr.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(cT),rp(),Mp(),pn(),xe()},open(){De()&&dt(!0,"api")},close(){De()&&dt(!1,"api")},toggle(){De()&&dt(!he,"api")},reconnect(){H.reconnectNow()},clearChat(){Gn=!1,H.clearMessages(),Dt.clear(),ko();try{localStorage.removeItem(ii),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ii}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ii)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),F?.clear&&fd(()=>F.clear(),"[AgentWidget] Failed to clear storage adapter:"),X={},Ee.syncFromMetadata(),Ze?.clearAttachments(),gd(),ta(void 0),Tn(void 0),fs(),Tt?.clear(),ut?.reset(),B?.update()},setMessage(s){return!le||H.isStreaming()||Lr()?!1:(!he&&De()&&dt(!0,"system"),le.value=s,le.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(H.isStreaming()||xs())return!1;let l=s?.trim()||le.value.trim();return l?(!he&&De()&&dt(!0,"system"),le.value="",le.style.height="auto",Mn(),Qd(l,{consumeDraft:!1}),!0):!1},getComposerState(){return Se.getState()},setQuote(s){let l=s?.text?.trim();l&&Tn({...s,text:l})},clearQuote(){Tn(void 0)},startVoiceRecognition(){return H.isStreaming()?!1:n.voiceRecognition?.provider?.type==="runtype"?(H.isVoiceActive()||(!he&&De()&&dt(!0,"system"),je.manuallyDeactivated=!1,gn(),H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),Jn("user"),H.isVoiceActive()&&Ea()})),!0):Hn?!0:Rb()?(!he&&De()&&dt(!0,"system"),je.manuallyDeactivated=!1,gn(),Jd("user"),!0):!1},stopVoiceRecognition(){return n.voiceRecognition?.provider?.type==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,gn(),Jn("user"),ir()}),!0):!1:Hn?(je.manuallyDeactivated=!0,gn(),Wr("user"),!0):!1},injectMessage(s){return!he&&De()&&dt(!0,"system"),H.injectMessage(s)},injectAssistantMessage(s){!he&&De()&&dt(!0,"system");let l=H.injectAssistantMessage(s);return gt&&(gt=!1,dn&&(clearTimeout(dn),dn=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),l},injectUserMessage(s){return!he&&De()&&dt(!0,"system"),H.injectUserMessage(s)},injectSystemMessage(s){return!he&&De()&&dt(!0,"system"),H.injectSystemMessage(s)},injectMessageBatch(s){return!he&&De()&&dt(!0,"system"),H.injectMessageBatch(s)},injectComponentDirective(s){return!he&&De()&&dt(!0,"system"),H.injectComponentDirective(s)},injectTestMessage(s){!he&&De()&&dt(!0,"system"),H.injectTestEvent(s)},async connectStream(s,l){return H.connectStream(s,l)},__pushEventStreamEvent(s){Rt&&(oe(),$(s.type,s.payload))},showEventStream(){Rt&&np()},hideEventStream(){ee&&oa()},isEventStreamVisible(){return ee},listConversations(s){return H.listConversations(s)},getActiveConversationId(){return H.getActiveConversationId()},openConversation(s,l){return lf(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return df({focusComposer:s?.focus===!0})},deleteConversation(s){return Cb(s)},renameConversation(s,l){return cf(s,{title:l})},setConversationStarred(s,l){return cf(s,{starred:l})},clearConversationHistory(s){return Sb(s)},resetHistoryIdentity(){return wb()},getHistoryIdentityStatus(){return $o?$o.getIdentityStatus():Vp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return $i({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){Io(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return ne},showArtifacts(){wo(n)&&(Gn=!1,ra=!0,mn(),Ve?.setMobileOpen(!0))},hideArtifacts(){wo(n)&&(Gn=!0,mn())},upsertArtifact(s){return wo(n)?(Nn(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Gn=!1,ra=!0),H.upsertArtifact(s)):null},selectArtifact(s){wo(n)&&H.selectArtifact(s)},clearArtifacts(){wo(n)&&H.clearArtifacts()},getArtifacts(){return H?.getArtifacts()??[]},getSelectedArtifactId(){return H?.getSelectedArtifactId()??null},focusInput(){return ge&&!he&&!Ae()||!le?!1:(le.focus(),!0)},async resolveApproval(s,l,f){let v=H.getMessages().find(M=>M.variant==="approval"&&M.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){H.resolveWebMcpApproval(v.id,l);return}return H.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){hA(s)},clearFollowUpSuggestions(){yy()},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...X}},updatePersistentMetadata(s){de(s)},on(s,l){return C.on(s,l)},off(s,l){C.off(s,l)},isOpen(){return De()&&he},isVoiceActive(){return je.active},toggleReadAloud(s){H.toggleReadAloud(s)},stopReadAloud(){H.stopSpeaking()},getReadAloudState(s){return H.getReadAloudState(s)},onReadAloudChange(s){return H.onReadAloudChange(s)},getState(){return{open:De()&&he,launcherEnabled:ge,voiceActive:je.active,streaming:H.isStreaming()}},showCSATFeedback(s){!he&&De()&&dt(!0,"system");let l=ke.querySelector(".persona-feedback-container");l&&l.remove();let f=Uu({onSubmit:async(g,v)=>{H.isClientTokenMode()&&await H.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});ke.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!he&&De()&&dt(!0,"system");let l=ke.querySelector(".persona-feedback-container");l&&l.remove();let f=qu({onSubmit:async(g,v)=>{H.isClientTokenMode()&&await H.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});ke.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return H.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return H.submitNPSFeedback(s,l)},destroy(){Dp(),ws!=null&&(clearInterval(ws),ws=null),ye.forEach(s=>s()),Xe.remove(),Xt?.remove(),Pt?.destroy(),go?.remove(),ds&&Ue.removeEventListener("click",ds)}};if(((o?.debugTools??!1)||!!n.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,l={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:f=>f?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=l,ye.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),l=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",l),ye.push(()=>{window.removeEventListener("persona:focusInput",l)}),Rt){let K=ae=>{let fe=ae.detail;(!fe?.instanceId||fe.instanceId===s)&&kt.showEventStream()},J=ae=>{let fe=ae.detail;(!fe?.instanceId||fe.instanceId===s)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",K),window.addEventListener("persona:hideEventStream",J),ye.push(()=>{window.removeEventListener("persona:showEventStream",K),window.removeEventListener("persona:hideEventStream",J)})}let f=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.showHistory()},g=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),ye.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.showArtifacts()},M=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.hideArtifacts()},N=K=>{let J=K.detail;J?.instanceId&&J.instanceId!==s||J?.artifact&&kt.upsertArtifact(J.artifact)},z=K=>{let J=K.detail;J?.instanceId&&J.instanceId!==s||typeof J?.id=="string"&&kt.selectArtifact(J.id)},V=K=>{let J=K.detail;(!J?.instanceId||J.instanceId===s)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",M),window.addEventListener("persona:upsertArtifact",N),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",V),ye.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",M),window.removeEventListener("persona:upsertArtifact",N),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",V)})}let nn=GL(n.persistState);if(nn&&De()){let s=XL(nn.storage),l=`${nn.keyPrefix}widget-open`,f=`${nn.keyPrefix}widget-voice`,g=`${nn.keyPrefix}widget-voice-mode`;if(s){let v=nn.persist?.openState&&s.getItem(l)==="true",M=nn.persist?.voiceState&&s.getItem(f)==="true",N=nn.persist?.voiceState&&s.getItem(g)==="true";if(v&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open(),setTimeout(()=>{if(M||N)kt.startVoiceRecognition();else if(nn.persist?.focusInput){let z=e.querySelector("textarea");z&&z.focus()}},100)},0)),nn.persist?.openState&&(C.on("widget:opened",()=>{s.setItem(l,"true")}),C.on("widget:closed",()=>{s.setItem(l,"false")})),nn.persist?.voiceState&&(C.on("voice:state",z=>{s.setItem(f,z.active?"true":"false")}),C.on("user:message",z=>{s.setItem(g,z.viaVoice?"true":"false")})),nn.clearOnChatClear){let z=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},V=()=>z();window.addEventListener("persona:clear-chat",V),ye.push(()=>{window.removeEventListener("persona:clear-chat",V)})}}}if(W&&De()&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open()},0)),fa(),!yA){let s=ka(()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))});ye.push(s)}T=()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))},H.getMessages().length>0&&xd(),b=()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))};let sT=Hx(()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo))});ye.push(sT);let aT=Qg(()=>{H&&(ms++,Dt.clear(),Jo(ke,H.getMessages(),oo),gr()?.updateInlineArtifactBlocks(ke,Yo.artifacts,{suppressTransition:!0}),mn())});return ye.push(aT),kt};var Tw=(e,t)=>{let o=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(n)return Math.max(0,parseFloat(n[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(o);return r?Math.max(0,t*parseFloat(r[1])/100):420},JL=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},ZL=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},e0=(e,t)=>{let o=e.parentElement;if(!o)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(n);let r=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!r||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Ew=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0",e.style.minWidth=o?"":"0"},fh=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=""},Pw=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",fh(e)},ch=e=>{e.style.transition=""},uh=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=""},ph=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ju=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},t0=(e,t,o,n,r)=>{r?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,n),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(n))},o0=(e,t,o,n,r,a)=>{let i=a?t:e;r==="left"?i.firstElementChild!==n&&i.replaceChildren(n,o):i.lastElementChild!==n&&i.replaceChildren(o,n)},n0=e=>{let t=Kr(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:xo(t,r)??r;return{inset:n(o?.inset,ru),canvasBackground:n(o?.canvasBackground,su)}},kw=(e,t,o,n)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=n},r0=(e,t,o,n,r,a,i,d)=>{let c=Wo(a),u=c.reveal==="push",p=d!=null,m=d?.inset??"",h=d?.canvasBackground??"";t0(e,t,o,n,u),o0(e,t,o,n,c.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let y=e.ownerDocument.defaultView,x=a?.launcher?.mobileFullscreen??!0,T=a?.launcher?.mobileBreakpoint??640,w=y!=null?y.innerWidth<=T:!1;if(x&&w&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),uh(t),ch(n),Pw(n),ph(o),ju(r,n),kw(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??so),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Pw(n),JL(n,c.maxHeight),kw(n,p&&i,m,h),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",uh(t),ch(n),ph(o),ju(r,n);let P=c.animate?"transform 180ms ease":"none",R=c.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":R;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=c.width,n.style.maxWidth=c.width,n.style.minWidth=c.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=P,n.style.transform=b,n.style.pointerEvents=i?"auto":"none",n.style.zIndex="2",c.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ch(n),fh(n),ju(r,n);let P=Tw(c.width,e.clientWidth),R=Math.max(0,e.clientWidth),b=c.animate?"margin-left 180ms ease":"none",A=c.side==="right"?i?-P:0:i?0:-P;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=`${R+P}px`,t.style.transition=b,t.style.marginLeft=`${A}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${R}px`,o.style.maxWidth=`${R}px`,o.style.minWidth=`${R}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=c.width,n.style.minWidth=c.width,n.style.maxWidth=c.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",uh(t),fh(n),ph(o),ju(r,n);let P=c.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=i?c.width:"0px",b=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",A=!i;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${R}`,n.style.width=R,n.style.maxWidth=R,n.style.minWidth=R,n.style.minHeight="0",ZL(n,c.maxHeight),n.style.overflow=P||A?"hidden":"visible",n.style.transition=b,P){n.style.alignItems=c.side==="right"?"flex-start":"flex-end";let C=p?`calc(${Tw(c.width,e.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=C,r.style.minWidth=C,r.style.maxWidth=C,r.style.boxSizing="border-box"}}},s0=(e,t)=>{let o=e.ownerDocument.createElement("div");return Ew(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){Ew(o,n)},destroy(){o.remove()}}},a0=(e,t)=>{let{ownerDocument:o}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,i=o.createElement("div"),d=o.createElement("div"),c=o.createElement("div"),u=o.createElement("aside"),p=o.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;d.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),n.insertBefore(i,e),c.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},x=null,T=()=>{x=t?.launcher?.detachedPanel===!0?n0(t):null};T();let w=()=>{r0(i,d,c,u,p,t,m,x)},k=null,P=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Ka(()=>{T(),w()}))},R=()=>{y(),Wo(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{w()}),h.observe(i)))},b=!1,A=()=>{w(),R(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,e0(i,Wo(t)))},C=i.ownerDocument.defaultView,L=()=>{A()};return C?.addEventListener("resize",L),Wo(t).reveal==="push"?(d.appendChild(c),d.appendChild(u),i.appendChild(d)):(i.appendChild(c),i.appendChild(u)),A(),P(),{mode:"docked",host:p,shell:i,syncWidgetState(F){let X=F.launcherEnabled?F.open:!0;m!==X&&(m=X,A())},updateConfig(F){t=F,(t?.launcher?.enabled??!0)===!1&&(m=!0),T(),A(),P()},destroy(){C?.removeEventListener("resize",L),k?.(),k=null,y(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),i.remove()}}},Vl=(e,t)=>St(t)?a0(e,t):s0(e,t);var i0=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Lw=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let n=o.cloneNode(!0);e.insertBefore(n,e.firstChild)},Iw=e=>{let t=i0(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=Vl(t,r),i,d=[],c=(w,k)=>{let R=!(k?.launcher?.enabled??!0)||St(k),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),R&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0",b.style.minWidth="0"),o){let A=w.attachShadow({mode:"open"});A.appendChild(b),Lw(A,n)}else w.appendChild(b),Lw(w,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},u=()=>{a.syncWidgetState(i.getState())},p=()=>{d.forEach(w=>w()),d=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},m=()=>{let w=c(a.host,r);i=Vu(w,r,{debugTools:e.debugTools}),p()},h=()=>{d.forEach(w=>w()),d=[],i.destroy()};m(),e.onChatReady?.();let y=w=>{h(),a.destroy(),a=Vl(t,w),r=w,m()},x={update(w){let k=Bu(r??{},w),P=St(r),R=St(k),b=Qr(r),A=Qr(k);if(P!==R||b!==A){y(k);return}r=k,a.updateConfig(r),i.update(w),u()},destroy(){h(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},T=new Proxy(x,{get(w,k,P){if(k==="host")return a.host;if(k in w)return Reflect.get(w,k,P);let R=i[k];return typeof R=="function"?R.bind(i):R}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=T),T};var Ow=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),l0=new Set(["button","a","input","select","textarea","details","summary"]),d0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),mh=/\b(product|card|item|listing|result)\b/i,hh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,c0=3e3,u0=100;function Dw(e){let t=typeof e.className=="string"?e.className:"";if(mh.test(t)||e.id&&mh.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&mh.test(n.value))return!0}return!1}function _w(e){return hh.test((e.textContent??"").trim())}function Nw(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=t[o].getAttribute("href")??"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function p0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Rw(e){let t=e.match(hh);return t?t[0]:null}function Hw(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let n=t.getAttribute("href");return{title:t.textContent.trim(),href:n&&n!=="#"?n:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function f0(e){let t=[],o=n=>{let r=n.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(n=>o(n.textContent??"")),e.querySelectorAll('[role="button"]').forEach(n=>o(n.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{o(n.value??"")}),t.slice(0,6)}var m0="commerce-card",g0="result-card";function Ww(e){return!Dw(e)||!_w(e)||!Nw(e)&&!p0(e)?0:5200}function Bw(e){return!Dw(e)||_w(e)||!Nw(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var yh=[{id:m0,scoreElement(e){return Ww(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let n=o.text.trim();return!!(n.length===0||hh.test(n)&&n.length<32)}return!0},formatSummary(e,t){if(Ww(e)===0)return null;let{title:o,href:n}=Hw(e),r=Rw((e.textContent??"").trim())??Rw(t.text)??"",a=f0(e);return[n&&o?`[${o}](${n})${r?`: ${r}`:""}`:o?`${o}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
139
- `)}},{id:g0,scoreElement(e){return Bw(e)},formatSummary(e,t){if(Bw(e)===0)return null;let{title:o,href:n}=Hw(e);return[n&&o?`[${o}](${n})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
140
- `)}}];function h0(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function y0(e){let t=e.options??{},o=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,d=t.mode??"structured",c=t.maxCandidates??Math.max(500,o*10),u=e.rules??yh;return d==="simple"&&e.rules&&e.rules.length>0?(h0(),u=[]):d==="simple"&&(u=[]),{mode:d,maxElements:o,maxCandidates:c,excludeSelector:n,maxTextLength:r,visibleOnly:a,root:i,rules:u}}function gh(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var b0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function v0(e){let t=e.tagName.toLowerCase(),o=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||o==="textbox"||o==="combobox"||o==="listbox"||o==="spinbutton"?"input":t==="button"||o==="button"||l0.has(t)||o&&d0.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Fw(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function x0(e){let t={},o=e.id;o&&(t.id=o);let n=e.getAttribute("href");n&&(t.href=n);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let i=e.getAttribute("value");i&&(t.value=i);let d=e.getAttribute("name");d&&(t.name=d);let c=e.getAttribute("role");c&&(t.role=c);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function bh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${gh(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of b0){let a=e.getAttribute(r);if(a){let i=`${t}[${r}="${gh(a)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let o=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(o.length>0){let r=`${t}.${o.map(i=>gh(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let d=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(d>=0){let c=`${r}:nth-of-type(${d+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function C0(e){return e==="static"?u0:c0}function Uw(e,t){let o=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:bh(e),tagName:o,text:n,role:e.getAttribute("role"),interactivity:v0(e),attributes:x0(e)}}function S0(e,t,o,n){let r=C0(t.interactivity),a=null;for(let i of o){let d=i.scoreElement(e,t,n);d>0&&(r+=d,i.formatSummary&&!a&&(a=i))}return{score:r,formattingRule:a}}function w0(e,t){for(let o of e)if(t.el!==o.el&&o.formattingRule?.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function A0(e,t){let o={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,r=[],a=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),d=i.currentNode;for(;d&&r.length<e.maxCandidates;){if(d.nodeType===Node.ELEMENT_NODE){let u=d,p=u.tagName.toLowerCase();if(Ow.has(p)){d=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){d=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Fw(u)){d=i.nextNode();continue}let m=Uw(u,e.maxTextLength),h=m.text.length>0,y=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(w=>w==="role");if(!h&&!y){d=i.nextNode();continue}if(n.has(m.selector)){d=i.nextNode();continue}n.add(m.selector);let{score:x,formattingRule:T}=S0(u,m,e.rules,o);r.push({el:u,domIndex:a,enriched:m,score:x,formattingRule:T}),a+=1}d=i.nextNode()}r.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let c=[];for(let u of r){if(c.length>=e.maxElements)break;w0(c,u)||c.push(u)}return c.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:m===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),c.map(u=>{let p;if(u.formattingRule?.formatSummary){let h=u.formattingRule.formatSummary(u.el,u.enriched,o);h&&(p=h)}let m={...u.enriched};return p&&(m.formattedSummary=p),m})}function M0(e,t){let o=[],n=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&o.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,u=c.tagName.toLowerCase();if(Ow.has(u)){a=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Fw(c)){a=r.nextNode();continue}let p=Uw(c,e.maxTextLength),m=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(y=>y==="role");if(!m&&!h){a=r.nextNode();continue}n.has(p.selector)||(n.add(p.selector),o.push(p))}a=r.nextNode()}let i=[],d=[];for(let c of o)c.interactivity!=="static"?i.push(c):d.push(c);return[...i,...d].slice(0,e.maxElements)}function qw(e={}){let t=y0(e),o=t.root??document.body;return o?t.mode==="simple"?M0(t,o):A0(t,o):[]}var zu=100;function $w(e,t={}){if(e.length===0)return"No page elements found.";let o=t.mode??"structured",n=[];if(o==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
137
+ ${Lt?"background: transparent !important;":""}
138
+ `)}if(!g&&!s){let ve="max-height: -moz-available !important; max-height: stretch !important;",Ue=l?"":"padding-top: 1.25em !important;",mt=l?"":`z-index: ${n.launcher?.zIndex??ro} !important;`;Ge.style.cssText+=ve+Ue+mt}Zu(),Dn()},fp=()=>{e.style.setProperty("--persona-content-max-width",Jr(n,Ie()))},oy=!1,ny=()=>{let s=pg(n,Ie());Ie()&&n.composer?.placement&&n.debug===!0&&!oy&&(oy=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let l=bn(n);e.setAttribute("data-persona-composer-placement",s),e.setAttribute("data-persona-conversation-state",Ql),e.setAttribute("data-persona-welcome-anchor",l.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",l.composerGap??cu),Jl()},ry=()=>{if(Ie())return;let s=Ct(n),l=n.launcher?.sidebarMode??!1;if(s||l||(n.launcher?.fullHeight??!1)||!we)return;let g=e.ownerDocument.defaultView??window,v=n.launcher?.mobileFullscreen??!0,M=n.launcher?.mobileBreakpoint??640;if(v&&g.innerWidth<=M)return;let _=g.innerHeight,K=64,j=n.launcher?.heightOffset??0,G=Math.max(200,_-K),Z=Math.min(640,G);Se.style.height=`${Math.max(200,Z-j)}px`};pp(),$s(e,n),_l(e,n),Nl(e,n),fp(),ny(),is=()=>{pp(),ry(),$s(e,n),_l(e,n),Nl(e,n),fp(),ny(),td?e.style.setProperty("--persona-artifact-welded-outer-radius",td):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Be(),Ft()};let he=[];he.push(()=>{Qh=!0}),he.push(()=>{c.forEach(s=>s()),d.destroy()}),he.push(()=>{document.removeEventListener("keydown",Zh)}),he.push(()=>{yi!==null&&clearTimeout(yi)});let Ln=null,In=null;he.push(()=>{Ln?.(),Ln=null,In?.(),In=null}),xi&&he.push(()=>{xi?.disconnect(),xi=null}),he.push(()=>{wi?.(),wi=null,up(),yt&&(yt.remove(),yt=null),je?.element.style.removeProperty("width"),je?.element.style.removeProperty("maxWidth"),je?.destroy()}),so&&he.push(()=>{F=!0,ln=null,N!==null&&(cancelAnimationFrame(N),N=null),J?.destroy(),J=null,tt?.destroy(),tt=null,Kn=null});let ds=null,sy=()=>{ds&&(ds(),ds=null),n.colorScheme==="auto"&&(ds=Ya(()=>{$s(e,n)}))};sy(),he.push(()=>{ds&&(ds(),ds=null)}),he.push(()=>{x=!0,y?.()}),he.push(()=>{P=!0});let ay=!1;he.push(()=>{ay=!0});let mp=(s,l)=>{let f=Ll(s,l);return f||!lS.includes(s)?f:(uS().then(g=>{if(ay)return;Ja(g.wipe),Ja(g.glyphCycle);let v=Ll(s,l);v&&Hl(v,e)}).catch(()=>{}),null)},dd=n.features?.streamAnimation;if(dd?.type&&dd.type!=="none"){let s=mp(dd.type,dd.plugins);s&&Hl(s,e),he.push(()=>dS(e))}let Jn=Ol(Sr),iy=Ol(Gu),ly=Ol(fi),cs=[Jn,iy,ly];he.push(()=>{cs.forEach(s=>s.destroy())});let us=null,R,ps=null,dy=!1,cy=0,uy=null,py=s=>s.reduce((l,f)=>f.role==="user"?l+1:l,0),fy=s=>{for(let l=s.length-1;l>=0;l--)if(Ds(s[l]))return s[l].id??null;return null},my=!1,hA=()=>{my||n.debug!==!0||(my=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},gy=!1,hy=!1,yy=(s,l)=>{gy||n.debug!==!0||!l.enabled||l.expose||dy||hy&&(R.isStreaming()||s.some(Ds)||(gy=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},ca=s=>{if(!R)return;let l=s??R.getMessages(),f=G=>{G.render([],R,ce,l)},g=G=>{cs.forEach(Z=>{Z!==G&&f(Z)})};ps&&(py(l)>cy||fy(l)!==uy)&&(ps=null);let v=Xr(n);yy(l,v);let M=v.enabled?bc(l):null,_=ps??M,K=ps?"host":"agent";if(_){let G=n.suggestions?.followUps,Z=G?.placement??(G?"auto":"composer"),me=(Z==="auto"?Ie()?"composer":"after-message":Z)==="after-message"?ly:Jn;g(me),me.render(_,R,ce,l,n.suggestionChipsConfig,{source:K,surface:"followUp",variant:G?.variant??"chip",behavior:G?.behavior??"send",overflow:G?.overflow??"wrap",maxItems:G?.maxItems??4,config:n,plugins:i,submitPrompt:Qd});return}if(l.some(G=>G.role==="user")){cs.forEach(f);return}let j=n.suggestions?.starters;if(j){let G=ts(bn(n),l),Z=j.placement??"auto",ae=Z==="auto"?G?"welcome":"composer":Z;if(ae==="welcome"&&!G){hA(),cs.forEach(f);return}let me=ae==="welcome"?iy:Jn;g(me),me.render(j.items??n.suggestionChips,R,ce,l,n.suggestionChipsConfig,{surface:"starter",variant:j.variant??"card",behavior:j.behavior??"send",overflow:j.overflow??"wrap",maxItems:j.maxItems??4,config:n,plugins:i,submitPrompt:Qd});return}g(Jn),Jn.render(n.suggestionChips,R,ce,l,n.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:n,plugins:i,submitPrompt:Qd})},by=()=>{ps&&(ps=null,ca())},yA=s=>{let l=Array.isArray(s)?[...s]:[];if(!l.length){by();return}let f=R?R.getMessages():[];ps=l,dy=!0,cy=py(f),uy=fy(f),ca(f)},Do=!1,Bt=QC(),ua=new Map,fs=new Map,Pr=new Map,ms=null,kr=null;function gs(){if(!ms)return;let s=ms;ms=null,kr?.destroy(),kr=null,Bt.delete(s),pe.querySelector(`#wrapper-${s}`)?.removeAttribute("data-preserve-runtime"),R&&Qo(Ee,R.getMessages(),It)}let hs=0,bA=Nn()!==null,_o=tS(),No=0,Lr=null,Mo=!1,cd=!1,Ir=0,$t=null,ys=null,gp=!1,pa=!1,bs=null,Ai=!0,ud=!1,fa=null,pd=!1,vs=()=>{pd=!0,SA()},hp=null,vA=4,Zn=24,xA=80,CA=1e3,er=null,vy=()=>{e.setAttribute("data-persona-scrollbar",Qu()),Qu()!=="on-scroll"&&(er!==null&&clearTimeout(er),er=null,ne.removeAttribute("data-persona-scrollbar-visible"))},SA=()=>{Qu()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),er!==null&&clearTimeout(er),er=setTimeout(()=>{er=null,Vs(ne,Zn)&&ne.removeAttribute("data-persona-scrollbar-visible")},CA))};vy(),he.push(()=>{er!==null&&clearTimeout(er)});let yp=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};$h=()=>ze.active,cn();let xy=n.voiceRecognition?.autoResume??!1,tr=s=>{C.emit("voice:state",{active:ze.active,source:s,timestamp:Date.now()})},fn=()=>{le(s=>({...s,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},wA=()=>{if(n.voiceRecognition?.enabled===!1)return;let s=ch($.voiceState),l=!!s.active,f=Number(s.timestamp??0);ze.manuallyDeactivated=!!s.manuallyDeactivated,l&&Date.now()-f<zL&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,n.voiceRecognition?.provider?.type==="runtype"?R.toggleVoice().then(()=>{ze.active=R.isVoiceActive(),tr("restore"),R.isVoiceActive()&&Ia()}):Zd("restore"))},1e3)},AA=()=>R?Aw(R.getMessages()).filter(s=>!s.__skipPersist):[],fd=null,Cy=(s,l)=>{typeof console<"u"&&console.error(s,l)},md=(s,l)=>{let f=()=>{try{let _=s();return!_||typeof _.then!="function"?null:Promise.resolve(_).catch(K=>{Cy(l,K)})}catch(_){return Cy(l,_),null}},g=fd,v=g?g.then(()=>f()??void 0):f();if(!v)return;let M=v.finally(()=>{fd===M&&(fd=null)});fd=M};function ma(s){if(!U?.save)return;let l=s?Aw(s):R?AA():[],f=Q&&R?.getResumableHandle();f&&($={...$,durableResume:{executionId:f.executionId,after:f.lastEventId}});let g={messages:l,metadata:$,artifacts:Xo.artifacts,selectedArtifactId:Xo.selectedId,...xs?{draft:xs}:{}};md(()=>U.save(g),"[AgentWidget] Failed to persist state:")}let xs,gd=()=>!U?.save||n.persistState===!1?!1:typeof n.persistState=="object"?n.persistState.persist?.draft!==!1:!0,Mi=CC({write:()=>{if(!gd())return;let s=Ce.getState(),l=vC({text:s.text,mentionRefs:s.mentionRefs,contentSegments:ff(),selectedModelId:s.selectedModelId,activeModeIds:s.activeModeIds,quote:s.quote});JSON.stringify(l)!==JSON.stringify(xs)&&(xs=l,ma())}});function Sy(){gd()&&Mi.schedule()}function bp(){Mi.flush()}function wy(s){if(!gd())return;let l=xC(s,{mentionSourceIds:(n.contextMentions?.sources??[]).map(f=>f.id),modelIds:(n.composer?.models??[]).map(f=>f.id),modes:n.composer?.modes??[]});l&&(xs=s,ce&&!ce.value&&(ce.value=l.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),Tn()),l.selectedModelId&&(Ce.setSelectedModelId(l.selectedModelId),Mr?.repaint()),Zl(l.activeModeIds??[]),l.quote&&En(l.quote),Mi.cancel())}function hd(){Mi.cancel(),xs&&(xs=void 0,gd()&&ma())}let ga=null,Ay=()=>Ge.querySelector("#persona-scroll-container")||ne,ha=()=>{ga!==null&&(cancelAnimationFrame(ga),ga=null),Mo=!1},My=()=>{Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),cd=!1,ha()},MA=()=>Do&&xp()&&(Oo()!=="anchor-top"||Th()),vp=()=>{let s=mi()||"Jump to latest",l=MA();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",l),Ir>0?(rs.textContent=String(Ir),rs.style.display="",Wt.setAttribute("aria-label",`${s} (${Ir} new)`)):(rs.textContent="",rs.style.display="none",Wt.setAttribute("aria-label",l?`${s} (response streaming below)`:s))},Ty=()=>{Ir!==0&&(Ir=0,vp())},TA=()=>{let s=$t?.spacerHeight??0;return s<=0?Vs(ne,Zn):xd(s)-ne.scrollTop-ne.clientHeight<=Zn},xp=()=>Ar()?!_o.isFollowing():!TA(),Cp=()=>!!R&&R.getMessages().length>0,Vt=()=>{if(!eA()||Cr()){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==pe&&pe.appendChild(Wt),ss();let l=jn(ne)>0&&xp()&&Cp();l?vp():Ty(),Wt.style.display=l?"":"none"},Ti=()=>{_o.pause()&&(My(),Vt())},To=()=>{_o.resume(),Ty(),Vt()},Rr=(s=!1)=>{Ar()&&Cp()&&_o.isFollowing()&&(!s&&!Do||(Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),cd=!0,Lr=requestAnimationFrame(()=>{Lr=null,cd=!1,_o.isFollowing()&&EA(Ay(),s?220:140)})))},Ey=(s,l,f,g=()=>!0)=>{let v=s.scrollTop,M=l(),_=M-v;if(ha(),Math.abs(_)<1){Mo=!0,s.scrollTop=M,No=s.scrollTop,Mo=!1;return}let K=performance.now();Mo=!0;let j=Z=>1-Math.pow(1-Z,3),G=Z=>{if(!g()){ha();return}let ae=l();ae!==M&&(M=ae,_=M-v);let me=Z-K,Je=Math.min(me/f,1),dt=j(Je),ut=v+_*dt;s.scrollTop=ut,No=s.scrollTop,Je<1?ga=requestAnimationFrame(G):(s.scrollTop=M,No=s.scrollTop,ga=null,Mo=!1)};ga=requestAnimationFrame(G)},EA=(s,l=500)=>{let f=jn(s)-s.scrollTop;if(Math.abs(f)<1){No=s.scrollTop;return}if(Math.abs(f)>=xA){ha(),Mo=!0,s.scrollTop=jn(s),No=s.scrollTop,Mo=!1;return}Ey(s,()=>jn(s),l,()=>_o.isFollowing())},yd=()=>{if(!Cp()){Vt();return}let s=Ay();Mo=!0,s.scrollTop=jn(s),No=s.scrollTop,Mo=!1,Vt()},Cs=s=>{let l=0,f=s;for(;f&&f!==ne;)l+=f.offsetTop,f=f.offsetParent;return l},PA=()=>{let s=ne.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??ne.ownerDocument.getSelection()},bd=()=>rS(PA(),ne),Sp=()=>{if(tA()!=="last-user-turn")return!1;let s=R?.getMessages()??[];if(s.length<2)return!1;let l=[...s].reverse().find(M=>M.role==="user");if(!l)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l.id):l.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),g=ne.querySelector(`[data-message-id="${f}"]`);if(!g)return!1;let v=Math.min(Math.max(0,Cs(g)-gi()),jn(ne));return Mo=!0,ne.scrollTop=v,No=ne.scrollTop,Mo=!1,Oo()==="follow"&&!Vs(ne,Zn)&&_o.pause(),Vt(),!0},vd=s=>{let l=Math.max(0,Math.round(s));Go.style.height=`${l}px`,Go.style.display=l>0?"":"none",$t&&($t.spacerHeight=Math.max(0,s))},xd=s=>{let l=parseFloat(getComputedStyle(ne).paddingBottom)||0,f=0;for(let v of Array.from(ne.children)){if(v===Go||v.offsetHeight===0)continue;let M=Cs(v)+v.offsetHeight;M>f&&(f=M)}let g=ne.scrollHeight-s;return f>0?Math.min(f+l,g):g},kA=()=>{if(!$t||$t.spacerHeight<=0)return;let s=xd($t.spacerHeight),l=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-s+Zn);l<$t.spacerHeight&&(vd(l),Vt())},mn=()=>{ys!==null&&(cancelAnimationFrame(ys),ys=null),ha(),$t=null,Go.style.height="0px",Go.style.display="none"},Py=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),wp=s=>ne.querySelector(`[data-message-id="${Py(s)}"]`),ky=s=>{ys!==null&&cancelAnimationFrame(ys),ys=requestAnimationFrame(()=>{ys=null;let l=Py(s),f=ne.querySelector(`[data-message-id="${l}"]`);if(!f)return;let g=Cs(f),v=$t?.spacerHeight??0,M=xd(v),{targetScrollTop:_,spacerHeight:K}=gg({anchorOffsetTop:g,topOffset:gi(),viewportHeight:ne.clientHeight,contentHeight:M,slack:Zn});$t={initialSpacerHeight:K,contentHeightAtAnchor:M,spacerHeight:K},vd(K),Ey(ne,()=>f.isConnected?Math.max(0,Cs(f)-gi()):_,220)})},Eo=()=>{if(Oo()!=="anchor-top"||!$t||!fa)return;let s=wp(fa);if(!s)return;ha();let l=$t.spacerHeight,f=xd(l),{targetScrollTop:g,spacerHeight:v}=gg({anchorOffsetTop:Cs(s),topOffset:gi(),viewportHeight:ne.clientHeight,contentHeight:f,slack:Zn});$t={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},vd(v),Mo=!0,ne.scrollTop=g,No=ne.scrollTop,Mo=!1,Vt()},LA=()=>{if(Ar()){if(!_o.isFollowing()||Vs(ne,1))return;Rr(!Do);return}if($t&&$t.initialSpacerHeight>0){let s=ne.scrollHeight-$t.spacerHeight,l=sS({initialSpacerHeight:$t.initialSpacerHeight,contentHeightAtAnchor:$t.contentHeightAtAnchor,currentContentHeight:s});l!==$t.spacerHeight&&vd(l)}Vt()},IA=s=>{let l=Oo();l==="follow"?(To(),Rr(!0)):l==="anchor-top"&&(Ai=!1,ud=!0,pd=!1,fa=s,ky(s))},RA=()=>{if(Oo()==="anchor-top"){if(ud){Ai=!1;return}Ai=!0,mn(),To(),Rr(!0)}},HA=96,WA=s=>{if(bs===null)return!0;let l=wp(bs),f=wp(s);if(!l||!f)return!0;let g=Cs(f)-Cs(l);return gi()+g>ne.clientHeight-HA},BA=s=>{if(Oo()!=="anchor-top"||!ud||pd||bd())return;let l=bs===null;for(let f of s){if(!l){f.id===bs&&(l=!0);continue}if(eS(f)){if(f.id===fa||!WA(f.id))return;fa=f.id,ky(f.id);return}}},OA=s=>{let l=new Map;s.forEach(f=>{let g=yp.get(f.id);l.set(f.id,{streaming:f.streaming,role:f.role}),!g&&f.role==="assistant"&&(C.emit("assistant:message",f),!pa&&(Oo()!=="anchor-top"||Th())&&xp()&&(Ir+=1,vp(),Vt(),Xl(Ir===1?"1 new message below.":`${Ir} new messages below.`))),f.role==="assistant"&&g?.streaming&&f.streaming===!1&&C.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(g?f.approval.status!=="pending"&&C.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):C.emit("approval:requested",{approval:f.approval,message:f}))}),yp.clear(),l.forEach((f,g)=>{yp.set(g,f)})},Ei=(s,l)=>{let f=l==="user"?"user":"assistant",g=n.layout?.messages?.[f],v=g?.width??"content",M=g?.maxWidth??(v==="full"?"100%":void 0);s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${l}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",l==="user"),s.setAttribute("data-message-role",l),s.setAttribute("data-message-width",v),M?s.style.setProperty("--persona-message-row-max-width",M):s.style.removeProperty("--persona-message-row-max-width")},or=(s,l)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Ei(f,l),f},DA=(s,l,f)=>{let g=document.createElement("div"),M=(()=>{let O=i.find(De=>De.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(n.loadingIndicator?.render)return n.loadingIndicator.render})(),_=(O,De)=>De==null?!1:typeof De=="string"?(O.textContent=De,!0):(O.appendChild(De),!0),K=new Set,j=new Map,G=new Set,Z=i.some(O=>O.renderAskUserQuestion),ae=[],me=[],Je=n.enableComponentStreaming!==!1,dt=n.approval!==!1,ut=[],Qt=n.messageActions,Dt=Qt?.showRegenerate===!0&&Qt.enabled!==!1&&lt.current?.isStreaming()!==!0?wx(l):null,kt=Qt?.showEdit===!0&&Qt.enabled!==!1,ao=Qt?.showQuote===!0&&Qt.enabled!==!1,et=null,io=n.features?.reasoningDisplay?.completedVisibility==="removed";if(l.forEach(O=>{if(io&&O.variant==="reasoning"&&O.reasoning?.status==="complete")return;if(K.add(O.id),j.set(O.id,O.role),ms===O.id&&kr){let We=or(O.id,O.role);We.setAttribute("data-persona-message-edit-stub","true"),We.setAttribute("data-preserve-runtime","true"),g.appendChild(We),et={messageId:O.id,element:kr.element};return}let De=Z&&fr(O),Ne=dt&&O.variant==="approval"&&!!O.approval,ge=!De&&O.role==="assistant"&&!O.variant&&Je&&Vl(O);!Ne&&Pr.has(O.id)&&(s.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Pr.delete(O.id)),!ge&&fs.has(O.id)&&(s.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),fs.delete(O.id));let ft=fr(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",jt={canRegenerate:Dt===O.id,canEdit:kt&&Yf(O),canQuote:ao&&!O.variant&&(O.content?.trim().length??0)>0},lo=`${jt.canRegenerate?"r":""}${jt.canEdit?"e":""}${jt.canQuote?"q":""}`,co=XC(O,hs)+ft+`:${lo}`,Lt=De||Ne||ge?null:YC(Bt,O.id,co);if(Lt){g.appendChild(Lt.cloneNode(!0)),fr(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(G.add(O.toolCall.id),Da(O,n,Fe.composerOverlay));return}let Te=null,zt=i.find(We=>!!(O.variant==="reasoning"&&We.renderReasoning||O.variant==="tool"&&We.renderToolCall||!O.variant&&We.renderMessage)),Kt=n.layout?.messages;if(fr(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){ua.delete(O.id),s.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ds(O)&&Xr(n).enabled)return;if(fr(O)&&n.features?.askUserQuestion?.enabled!==!1){let We=i.find(vt=>typeof vt.renderAskUserQuestion=="function");if(We&&lt.current){let vt=ua.get(O.id),Dn=vt!==co,gn=null;if(Dn){let{payload:Ue,complete:mt}=mr(O),Fr=O.id,Gt=()=>lt.current?.getMessages().find(qo=>qo.id===Fr);gn=We.renderAskUserQuestion({message:O,payload:Ue,complete:mt,resolve:qo=>{let Ws=Gt();Ws&&lt.current?.resolveAskUserQuestion(Ws,qo)},dismiss:()=>{let qo=Gt();qo?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(qo),lt.current?.resolveAskUserQuestion(qo,"(dismissed)"))},config:n})}let _e=vt!=null;if(Dn&&gn===null&&!_e){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(G.add(O.toolCall.id),Da(O,n,Fe.composerOverlay));return}let ve=or(O.id,O.role);ve.setAttribute("data-ask-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ae.push({messageId:O.id,fingerprint:co,bubble:gn});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(G.add(O.toolCall.id),Da(O,n,Fe.composerOverlay));return}}else if(Ne){let We=k();if(!We){g.appendChild(or(O.id,O.role));return}let vt=i.find(ve=>typeof ve.renderApproval=="function")??h,gn=Pr.get(O.id)!==co,_e=null;if(gn&&vt?.renderApproval){let ve=O.id,Ue=(mt,Fr)=>{let Gt=lt.current?.getMessages().find(qo=>qo.id===ve);Gt?.approval&&(Gt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(Gt.id,mt):lt.current?.resolveApproval(Gt.approval,mt,Fr))};_e=vt.renderApproval({message:O,defaultRenderer:()=>We.createApprovalBubble(O,n),config:n,approve:mt=>Ue("approved",mt),deny:mt=>Ue("denied",mt)})}if(gn&&_e===null)s.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Pr.delete(O.id),Te=We.createApprovalBubble(O,n);else{let ve=or(O.id,O.role);ve.setAttribute("data-approval-plugin-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),ut.push({messageId:O.id,fingerprint:co,bubble:_e});return}}else if(zt)if(O.variant==="reasoning"&&O.reasoning&&zt.renderReasoning){if(!Sn)return;Te=zt.renderReasoning({message:O,defaultRenderer:()=>jg(O,n),config:n})}else if(O.variant==="tool"&&O.toolCall&&zt.renderToolCall){if(!zo)return;Te=zt.renderToolCall({message:O,defaultRenderer:()=>Kg(O,n),config:n})}else zt.renderMessage&&(Te=zt.renderMessage({message:O,defaultRenderer:()=>{let We=oi(O,f,Kt,n.messageActions,Ut,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:jt});return O.role!=="user"&&A(We,O,n,R),We},config:n}));if(!Te&&ge){let We=Uu(O);if(We){let vt=fs.get(O.id),Dn=vt!==co,gn=n.wrapComponentDirectiveInBubble!==!1&&vn.getOptions(We.component)?.bubbleChrome!==!1,_e=null;if(Dn){let ve=Fu(We,{config:n,message:O,transform:f});if(ve&&We.component==="PersonaArtifactInline"){let Ue=ve.hasAttribute("data-artifact-inline")?ve:ve.querySelector("[data-artifact-inline]"),mt=Ue?.getAttribute("data-artifact-inline")??"",Fr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(mt):mt,Gt=mt?s.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${Fr}"]`)??null:null;Ue&&Gt&&Gt!==Ue&&br()?.hasLiveInlineArtifactBlock(Gt)&&(Ue===ve?ve=Gt:Ue.replaceWith(Gt))}if(ve)if(gn){let Ue=document.createElement("div");if(Ue.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ue.id=`bubble-${O.id}`,Ue.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let mt=document.createElement("div");mt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",mt.innerHTML=f({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ue.appendChild(mt)}Ue.appendChild(ve),_e=Ue}else{let Ue=document.createElement("div");if(Ue.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ue.id=`bubble-${O.id}`,Ue.setAttribute("data-message-id",O.id),Ue.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let mt=document.createElement("div");mt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",mt.innerHTML=f({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ue.appendChild(mt)}Ue.appendChild(ve),_e=Ue}}if(_e||vt!=null){let ve=or(O.id,O.role);ve.setAttribute("data-component-directive-stub","true"),ve.setAttribute("data-preserve-runtime","true"),g.appendChild(ve),me.push({messageId:O.id,fingerprint:co,bubble:_e});return}}}if(!Te)if(O.variant==="reasoning"&&O.reasoning){if(!Sn)return;Te=jg(O,n)}else if(O.variant==="tool"&&O.toolCall){if(!zo)return;Te=Kg(O,n)}else if(O.variant==="approval"&&O.approval){if(n.approval===!1)return;let We=k();if(!We)return;Te=We.createApprovalBubble(O,n)}else{let We=n.layout?.messages;We?.renderUserMessage&&O.role==="user"?Te=We.renderUserMessage({message:O,config:n,streaming:!!O.streaming}):We?.renderAssistantMessage&&O.role==="assistant"?Te=We.renderAssistantMessage({message:O,config:n,streaming:!!O.streaming}):Te=oi(O,f,We,n.messageActions,Ut,{loadingIndicatorRenderer:M,widgetConfig:n,actionEligibility:jt}),O.role!=="user"&&Te&&A(Te,O,n,R)}let on=or(O.id,O.role);on.appendChild(Te),JC(Bt,O.id,co,on),g.appendChild(on)}),Fe.composerOverlay&&Fe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let Ne=De.getAttribute("data-persona-ask-sheet-for");Ne&&!G.has(Ne)&&Kr(Fe.composerOverlay,Ne)}),n.features?.toolCallDisplay?.grouped){let O=[],De=[],Ne=n.features.toolCallDisplay.groupedMode==="summary";l.forEach(ge=>{if(ge.variant==="tool"&&ge.toolCall&&zo){De.push(ge);return}ge.variant==="reasoning"&&(!Sn||io&&ge.reasoning?.status==="complete")||((De.length>1||Ne&&De.length>0)&&O.push(De),De=[])}),(De.length>1||Ne&&De.length>0)&&O.push(De),O.forEach(ge=>{let ft=ge.map(Kt=>Array.from(g.children).find(on=>on instanceof HTMLElement&&on.getAttribute("data-wrapper-id")===Kt.id)).filter(Kt=>!!Kt);if(ft.length<(Ne?1:2))return;let jt=or(`tool-group-${ge[0].id}`,"assistant");jt.setAttribute("data-persona-tool-group-row","true");let lo=document.createElement("div");lo.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",lo.setAttribute("data-persona-tool-group","true");let co=document.createElement("div");co.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",co.id=`tool-group-summary-${ge[0].id}`;let Lt=`Called ${ge.length} ${ge.length===1?"tool":"tools"}`,Te=n.toolCall?.renderGroupedSummary?.({messages:ge,toolCalls:ge.map(Kt=>Kt.toolCall).filter(Kt=>!!Kt),defaultSummary:Lt,config:n});_(co,Te)||(co.textContent=Lt);let zt=document.createElement("div");zt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.id=`tool-group-stack-${ge[0].id}`,zt.setAttribute("data-persona-tool-group-stack","true"),lo.appendChild(co),Ne||lo.appendChild(zt),jt.appendChild(lo),ft[0].before(jt),ft.forEach((Kt,on)=>{if(Ne){Kt.remove();return}Kt.style.setProperty("--persona-message-row-max-width","100%");let We=document.createElement("div");We.className="persona-tool-group-item persona-relative",We.setAttribute("data-persona-tool-group-item","true"),on<ft.length-1&&We.setAttribute("data-persona-tool-group-connector","true"),We.appendChild(Kt),zt.appendChild(We)})})}ZC(Bt,K);let ur=l.some(O=>O.role==="assistant"&&O.streaming),Bn=l[l.length-1],On=Bn?.role==="assistant"&&!Bn.streaming&&Bn.variant!=="approval";if(Do&&l.some(O=>O.role==="user")&&!ur&&!On){let O={config:n,streaming:!0,location:"standalone",defaultRenderer:Qs},De=i.find(ge=>ge.renderLoadingIndicator),Ne=null;if(De?.renderLoadingIndicator&&(Ne=De.renderLoadingIndicator(O)),Ne===null&&n.loadingIndicator?.render&&(Ne=n.loadingIndicator.render(O)),Ne===null&&(Ne=Qs()),Ne){let ge=document.createElement("div"),ft=n.loadingIndicator?.showBubble!==!1,jt=n.layout?.messages?.layout??"bubble";ge.className=ft?Dl("assistant",jt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),ge.setAttribute("data-typing-indicator","true"),ft&&(ge.style.color="var(--persona-message-assistant-text, var(--persona-text))",jt!=="flat"&&(ge.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),ge.appendChild(Ne);let lo=or("typing-indicator","assistant");lo.appendChild(ge),g.appendChild(lo)}}if(!Do&&l.length>0){let O=l[l.length-1],De={config:n,lastMessage:O,messageCount:l.length},Ne=i.find(ft=>ft.renderIdleIndicator),ge=null;if(Ne?.renderIdleIndicator&&(ge=Ne.renderIdleIndicator(De)),ge===null&&n.loadingIndicator?.renderIdle&&(ge=n.loadingIndicator.renderIdle(De)),ge){let ft=document.createElement("div"),jt=n.loadingIndicator?.showBubble!==!1;ft.className=jt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ft.setAttribute("data-idle-indicator","true"),ft.appendChild(ge);let lo=or("idle-indicator","assistant");lo.appendChild(ft),g.appendChild(lo)}}if(Sv(g),mu(s,g),If(s),et){let{messageId:O,element:De}=et,Ne=s.querySelector(`#wrapper-${O}`);Ne&&De.parentElement!==Ne&&(Ei(Ne,j.get(O)??"user"),Ne.replaceChildren(De))}if(ae.length>0)for(let{messageId:O,fingerprint:De,bubble:Ne}of ae){let ge=s.querySelector(`#wrapper-${O}`);ge&&(Ei(ge,j.get(O)??"assistant"),Ne!==null&&(ge.replaceChildren(Ne),ge.setAttribute("data-bubble-fp",De),ua.set(O,De)))}if(ua.size>0)for(let O of ua.keys())K.has(O)||ua.delete(O);if(me.length>0)for(let{messageId:O,fingerprint:De,bubble:Ne}of me){let ge=s.querySelector(`#wrapper-${O}`);ge&&(Ei(ge,j.get(O)??"assistant"),Ne!==null&&(ge.replaceChildren(Ne),ge.setAttribute("data-bubble-fp",De),fs.set(O,De)))}if(fs.size>0)for(let O of fs.keys())K.has(O)||fs.delete(O);if(ut.length>0)for(let{messageId:O,fingerprint:De,bubble:Ne}of ut){let ge=s.querySelector(`#wrapper-${O}`);ge&&(Ei(ge,j.get(O)??"assistant"),Ne!==null&&(ge.replaceChildren(Ne),ge.setAttribute("data-bubble-fp",De),Pr.set(O,De)))}if(Pr.size>0)for(let O of Pr.keys())K.has(O)||Pr.delete(O)},Ap=!1,Cd=()=>{Ap||(Ap=!0,lc().catch(()=>{Ap=!1}))},Qo=(s,l,f)=>{l.length>0&&Cd(),DA(s,l,f),Xh()},Pi=null,_A=()=>{if(Pi)return;let s=f=>{let g=f.composedPath();g.includes(Ge)||Xt&&g.includes(Xt)||ct(!1,"user")};Pi=s,(e.ownerDocument??document).addEventListener("pointerdown",s,!0)},Ly=()=>{if(!Pi)return;(e.ownerDocument??document).removeEventListener("pointerdown",Pi,!0),Pi=null};he.push(()=>Ly());let ki=null,NA=()=>{if(ki)return;let s=f=>{f.key==="Escape"&&(f.isComposing||ct(!1,"user"))};ki=s,(e.ownerDocument??document).addEventListener("keydown",s,!0)},Iy=()=>{if(!ki)return;(e.ownerDocument??document).removeEventListener("keydown",ki,!0),ki=null};he.push(()=>Iy());let Li=!1,Ry=new Set,FA=()=>{let s=n.launcher?.composerBar?.peek?.streamAnimation;return s||n.features?.streamAnimation},ya=()=>{if(!Ie())return;let s=Fe.peekBanner,l=Fe.peekTextNode;if(!s||!l)return;if(be){s.classList.remove("persona-pill-peek--visible");return}let f=R?.getMessages()??[],g;for(let Dt=f.length-1;Dt>=0;Dt--){let kt=f[Dt];if(kt.role==="assistant"&&kt.content){g=kt;break}}if(!g){s.classList.remove("persona-pill-peek--visible");return}let v=g.content,M=!!g.streaming,_=FA(),K=gu(_),j=K.type!=="none"?mp(K.type,_?.plugins):null,G=j?.isAnimating?.(g)===!0,Z=j!==null&&(M||G);Z&&j&&!Ry.has(j.name)&&(Hl(j,e),Ry.add(j.name));let ae=Z&&j?.containerClass?j.containerClass:null,me=l.dataset.personaPeekStreamClass??null;me&&me!==ae&&(l.classList.remove(me),delete l.dataset.personaPeekStreamClass),ae&&me!==ae&&(l.classList.add(ae),l.dataset.personaPeekStreamClass=ae),Z?(l.style.setProperty("--persona-stream-step",`${K.speed}ms`),l.style.setProperty("--persona-stream-duration",`${K.duration}ms`)):(l.style.removeProperty("--persona-stream-step"),l.style.removeProperty("--persona-stream-duration"));let Je=Z?hu(v,K.buffer,j,g,M):v;if(Z&&K.placeholder==="skeleton"&&M&&(!Je||!Je.trim())){let Dt=document.createElement("div"),kt=Rl();kt.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(kt),mu(l,Dt)}else{let Dt=Math.max(0,Je.length-100),kt=Je.length>100?Je.slice(-100):Je,ao=pr(kt);if(!Z||!j){let et=Je.length>100?`\u2026${kt}`:kt;l.textContent!==et&&(l.textContent=et)}else{let et=ao;(j.wrap==="char"||j.wrap==="word")&&(et=Il(ao,j.wrap,`peek-${g.id}`,{skipTags:j.skipTags,startIndex:Dt}));let io=document.createElement("div");if(io.innerHTML=et,j.useCaret&&kt.length>0){let ur=yu(),Bn=io.querySelectorAll(".persona-stream-char, .persona-stream-word"),On=Bn[Bn.length-1];On?.parentNode?On.parentNode.insertBefore(ur,On.nextSibling):io.appendChild(ur)}mu(l,io),j.onAfterRender?.({container:l,bubble:s,messageId:g.id,message:g,speed:K.speed,duration:K.duration})}}let Qt=Do||Li;s.classList.toggle("persona-pill-peek--visible",Qt)};if(Ie()){let s=Fe.peekBanner;if(s){let g=v=>{v.preventDefault(),v.stopPropagation(),ct(!0,"user")};s.addEventListener("pointerdown",g),he.push(()=>{s.removeEventListener("pointerdown",g)})}let l=()=>{Li||(Li=!0,ya())},f=()=>{Li&&(Li=!1,ya())};Se.addEventListener("pointerenter",l),Se.addEventListener("pointerleave",f),he.push(()=>{Se.removeEventListener("pointerenter",l),Se.removeEventListener("pointerleave",f)}),Xt&&(Xt.addEventListener("pointerenter",l),Xt.addEventListener("pointerleave",f),he.push(()=>{Xt.removeEventListener("pointerenter",l),Xt.removeEventListener("pointerleave",f)}))}let UA=s=>{let l=n.launcher?.composerBar??{},f=l.expandedSize??"anchored",g=l.bottomOffset??"16px",v=l.collapsedMaxWidth,M=l.expandedMaxWidth??"880px",_=l.expandedTopOffset??"5vh",K=l.modalMaxWidth??"880px",j=l.modalMaxHeight??"min(90vh, 800px)",G="calc(100vw - 32px)",Z="var(--persona-pill-area-height, 80px)",ae=Ge.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Xt){let me=Xt.style;me.bottom=g,me.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=K,ae.maxWidth=G,ae.maxHeight=j,ae.height=j;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${g} + ${Z})`,ae.top=_,ae.width=M,ae.maxWidth=G}},Ii=()=>{if(be&&Cd(),!Pe())return;if(Ie()){let G=(n.launcher?.composerBar??{}).expandedSize??"anchored",Z=be?"expanded":"collapsed";Ge.dataset.state=Z,Ge.dataset.expandedSize=G,Xt&&(Xt.dataset.state=Z,Xt.dataset.expandedSize=G),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),UA(be),pe.style.display=be?"flex":"none",is(),be?(_A(),NA()):(Ly(),Iy()),ya();return}let s=Ct(n),l=e.ownerDocument.defaultView??window,f=n.launcher?.mobileBreakpoint??640,g=n.launcher?.mobileFullscreen??!0,v=l.innerWidth<=f,M=g&&v&&we,_=Io(n).reveal;be?(Ge.style.removeProperty("display"),Ge.style.display=s?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),Et?(Et.setPanelOpen(!0),Et.element.style.display="none"):po&&(po.style.display="none")):(s?s&&(_==="overlay"||_==="push")&&!M?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.setProperty("display","none","important"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.display="",Ge.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),Et?(Et.setPanelOpen(!1),Et.element.style.display=s?"none":""):po&&(po.style.display=s?"none":""))},ct=(s,l="user")=>{if(!Pe()||be===s)return;let f=be;be=s,Ii();let g=(()=>{let M=n.launcher?.sidebarMode??!1,_=e.ownerDocument.defaultView??window,K=n.launcher?.mobileFullscreen??!0,j=n.launcher?.mobileBreakpoint??640,G=_.innerWidth<=j,Z=Ct(n)&&K&&G,ae=Ie()&&(n.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return M||K&&G&&we||Z||ae})();if(be&&g){if(!Ln){let M=e.getRootNode(),_=M instanceof ShadowRoot?M.host:e.closest(".persona-host");_&&(Ln=xg(_,n.launcher?.zIndex??ro))}In||(In=Cg(e.ownerDocument))}else be||(Ln?.(),Ln=null,In?.(),In=null);be&&(Gi(),Sp()||(Oo()==="follow"?Rr(!0):yd()));let v={open:be,source:l,timestamp:Date.now()};be&&!f?C.emit("widget:opened",v):!be&&f&&C.emit("widget:closed",v),C.emit("widget:state",{open:be,launcherEnabled:we,voiceActive:ze.active,streaming:R.isStreaming()})},Hr={inputDisabled:!1,sendDisabled:!1},Wr=()=>Hr.inputDisabled,Ss=()=>Hr.inputDisabled||Hr.sendDisabled,qA=()=>(Hr.inputDisabled?Hr.inputReason:void 0)??(Hr.sendDisabled?Hr.sendReason:void 0);function Mp(){if(!Ae)return;if(Ce.getState().phase==="streaming"){Ae.disabled=!1;return}let s=Ze?!Ze.isReady():!1;Ae.disabled=Ss()||s}function Sd(){if(!Mn)return;let s=Ce.getState(),l=n.sendButton?.visibility==="when-text"&&s.phase!=="streaming"&&s.text.trim().length===0&&s.attachments.length===0;Mn.toggleAttribute("data-persona-send-hidden",l)}function $A(){let s=qA();if(Ie()){let l=dn??Le;s?l.setAttribute("title",s):l.removeAttribute("title"),Le.toggleAttribute(pi,!!s);return}if(s){at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.setAttribute(pi,""),at.textContent=s;return}if(at.hasAttribute(pi)&&(at.removeAttribute("role"),at.removeAttribute("aria-live"),at.removeAttribute(pi),u)){let l=R.getStatus();zl(at,Co(l),n.statusIndicator??{},l)}}function Tp(){let s=Gm(n.composer?.inputDisabled),l=Gm(n.composer?.sendDisabled);Hr={inputDisabled:s.disabled,inputReason:s.reason,sendDisabled:l.disabled,sendReason:l.reason},Ce.setInputDisabled(s.disabled),Ce.setSendDisabled(l.disabled);let f=Ce.getState().phase==="streaming",g=s.disabled,v=f||g;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=g:ce.setAttribute("contenteditable",g?"false":"true"),ce.setAttribute("aria-disabled",g?"true":"false")),St&&(St.disabled=g),ht&&(ht.disabled=g);for(let M of Ht?.affordanceButtons??[])M.querySelectorAll("button").forEach(_=>{_.disabled=g});re&&(re.disabled=v),cs.forEach(M=>{M.elements.forEach(_=>{_.toggleAttribute("data-disabled",v),_ instanceof HTMLButtonElement||_.setAttribute("aria-disabled",v?"true":"false")}),M.buttons.forEach(_=>{_.disabled=v})}),Ip.forEach(M=>{M.toggleAttribute("data-disabled",v),M instanceof HTMLButtonElement?M.disabled=v:M.setAttribute("aria-disabled",v?"true":"false"),M.querySelectorAll("button").forEach(_=>{_.disabled=v})}),Le.dataset.personaComposerStreaming=f?"true":"false",Le.dataset.personaComposerInputDisabled=g?"true":"false",Le.dataset.personaComposerSendDisabled=Ss()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(M=>{(M instanceof HTMLButtonElement||M instanceof HTMLInputElement||M instanceof HTMLTextAreaElement||M instanceof HTMLSelectElement)&&(M.disabled=f)}),Mp(),$A()}let Ri=s=>{Ce.setStreaming(s),Ah(s?"stop":"send"),Tp()},ws=()=>{ze.active||ce&&ce.focus()};C.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>ws(),200)});let As=null,Hi=!1,Ep=!So.hidden,Br=null,Pp=!E,wd=null;he.push(()=>{wd?.cancel(),wd=null});let VA=s=>{let l=IS(s);if(l===Ql)return;Ql=l,e.setAttribute("data-persona-conversation-state",l);let f=Ju();Jl(),Pp&&(wd?.cancel(),wd=kS(Le,l==="active"?f:Ju(),l==="active"?"drop":"rise")),Eo()},Hy=null,Wy,By=null,ba=null,kp=!1,Wi=s=>{let l=bn(n),f=`${l.variant}|${l.dismiss}|${l.anchor??"bottom"}|${l.align??""}|${l.iconPlacement}|${l.kicker??""}|${l.title}|${l.subtitle}`;(f!==Hy||l.icon!==Wy)&&(Hy=f,Wy=l.icon,Au({host:So,iconHolder:Kw,kicker:Gw,title:Xw,subtitle:Qw,starterSuggestions:Gu},l));let g=l.message===void 0?null:`${n.layout?.messages?.layout??"bubble"}|${l.message}`;g!==By&&(By=g,Mu(Wo,l.message,n));let v=s??(R?R.getMessages():n.initialMessages);VA(v);let M=Hi,_=!M&&ts(l,v),K=_!==Ep;if(Ep=_,ba){Br?.cancel(),Br=null,M!==kp&&(kp=M,M?Dg(ne,So,null):Og(ne,So,ba)),ni(ne,So,!M);return}if(K&&!_&&!M&&l.dismiss==="on-first-message"&&Pp){Br=PS(So,G=>{Br===G&&(Br=null),!Ep&&!ba&&(ni(ne,So,!1),Eo()),G?.cancel()});return}if(Br){if(!_&&!M)return;Br.cancel(),Br=null}let j=!So.hidden;ni(ne,So,_),!_&&j&&Eo()},Lp=[],Ip=[],Rp=!1,Oy=null,Dy,_y=()=>{Ip.length=0;let s=Lp.splice(0,Lp.length);for(let l of s)try{l()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};he.push(_y);let jA=(s,l)=>{let f=wg(s,l);if(!f)return n.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),I("span");let g=n.suggestions?.starters,v=Ag({item:{...f,behavior:f.behavior??g?.behavior??"send"},index:l,surface:"starter",source:"config",variant:g?.variant??"card",streaming:u?R.isStreaming():!1,config:n,plugins:i,chipsConfig:n.suggestionChipsConfig,session:R,getTextarea:()=>ce,eventTarget:So,submitPrompt:Qd});return Ip.push(v),v},Hp=()=>{if(Rp)return;Rp=!0;let s=bn(n);Oy=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,Dy=s.icon;try{_y(),Dg(ne,So,ba),ba=null,kp=!1;let l=R?R.getMessages():n.initialMessages,f=ts(s,l),g=0,v=null;for(let M of i)if(M.renderWelcome&&(v=M.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>So,sendMessage:_=>{if(!R||R.isStreaming())return;let K=_.trim();K&&R.sendMessage(K)},requestRender:()=>Hp(),renderStarter:_=>jA(_,g++),storage:p(M.id),onCleanup:_=>{Lp.push(_)}}),v))break;v&&v!==So&&(ba=v,Og(ne,So,v))}finally{Rp=!1}Wi()},zA=()=>{let s=bn(n);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===Oy&&s.icon===Dy||Hp()},Ad=()=>{Wi(),aa||(ce.placeholder=mC(Ce.getState().activeModeIds,n.composer?.modes)??n.copy?.inputPlaceholder??"How can I help...",!(n.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(Ae.textContent=n.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},KA=!!n.setStoredConversationId,va=s=>le(l=>{let f={...l};return delete f[s],f}),Md=s=>{let l=$[s];return typeof l=="string"?l:null},Ny=()=>{let s=$.durableResume;if(!s||typeof s!="object")return null;let l=s;return typeof l.executionId=="string"&&l.executionId.length>0&&typeof l.after=="string"&&l.after.length>0?{executionId:l.executionId,after:l.after}:null};n.clientToken&&(n={...n,getStoredSessionId:()=>Md("sessionId"),setStoredSessionId:s=>{le(l=>({...l,sessionId:s}))},clearStoredSessionId:n.clearStoredSessionId??(()=>va("sessionId")),getStoredConversationId:n.getStoredConversationId??(()=>Md("conversationId")),setStoredConversationId:n.setStoredConversationId??(s=>{le(l=>({...l,conversationId:s}))}),clearStoredConversationId:n.clearStoredConversationId??(()=>va("conversationId"))});let Fy=()=>n.clientToken??null,Uy=s=>fw(s,an(),n.persistState===!1),qy=Fy(),nr=qy?Uy(qy):null,rr={...nr?{visitorStore:nr}:{},historyBootstrapReady:D,getStoredMessageCursor:()=>Md("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){va("historyMessageCursor");return}le(l=>({...l,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=$.pendingDisplayProjections;if(!s||typeof s!="object")return null;let l=s;return typeof l.conversationId!="string"||!Array.isArray(l.messageIds)?null:{conversationId:l.conversationId,messageIds:l.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){va("pendingDisplayProjections");return}le(l=>({...l,pendingDisplayProjections:s}))},getStoredResumableHandle:Ny,setStoredResumableHandle:s=>{if(!s){va("durableResume");return}le(l=>({...l,durableResume:s}))},shouldResumeDurableConversation:()=>Q&&Ny()!==null,...KA?{}:{getStoredConversationRevision:()=>Md("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){va("conversationRevision");return}le(l=>({...l,conversationRevision:s}))}}};if(Q){let s=n.onExecutionState,l=e.ownerDocument.defaultView,f=!1,g=()=>f=!0,v=()=>f=!1;l?.addEventListener("pagehide",g),l?.addEventListener("pageshow",v),he.push(()=>{l?.removeEventListener("pagehide",g),l?.removeEventListener("pageshow",v)}),n={...n,reconnectStream:n.reconnectStream??(M=>R.getClient().reconnectClientTokenStream(M)),onExecutionState:M=>{(M||!f)&&rr.setStoredResumableHandle?.(M?{executionId:M.executionId,after:M.lastEventId}:null),s?.(M)}}}let GA=()=>{let s=Fy();if(s&&nr?.matches(s,an(),n.persistState===!1)||!s&&!nr)return;nr?.destroy(),nr=s?Uy(s):null;let l={...rr};nr?l.visitorStore=nr:delete l.visitorStore,rr=l,R.setHistoryInternals(rr)},Ms=null,XA=()=>{Ms==null&&(Ms=setInterval(()=>{let s=Ee.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(Ms),Ms=null;return}let l=Date.now();s.forEach(f=>{let g=Number(f.getAttribute("data-tool-elapsed"));g&&(f.textContent=Cc(l-g))})},100))},Wp=(s,l)=>{if(Object.is(s,l))return!0;if(s===null||l===null||typeof s!="object"||typeof l!="object")return!1;if(Array.isArray(s)||Array.isArray(l))return!Array.isArray(s)||!Array.isArray(l)||s.length!==l.length?!1:s.every((_,K)=>Wp(_,l[K]));let f=s,g=l,v=Object.keys(f),M=Object.keys(g);return v.length===M.length&&v.every(_=>Object.prototype.hasOwnProperty.call(g,_)&&Wp(f[_],g[_]))},$y=s=>{let{content:l,rawContent:f,llmContent:g,...v}=s;return v},Bp=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!Vl(s),QA=(s,l,f)=>{if(s.length!==l.length)return!1;let g=s[f.index],v=l[f.index];return!g||!v||g.id!==f.id||v.id!==f.id?!1:(!Object.is(g.content,v.content)||!Object.is(g.rawContent,v.rawContent)||!Object.is(g.llmContent,v.llmContent))&&Bp(g)&&Bp(v)&&Wp($y(g),$y(v))},Op=null,xa=null,Ts=null,sr=null,Dp=null,YA=s=>{if(!Q)return ma(s);Dp=s,queueMicrotask(()=>{Dp===s&&(Dp=null,ma(s))})},Td=s=>{Op=s;let l,f;xa=null;for(let v=s.length-1;v>=0;v-=1){let M=s[v];if(!l&&M.role==="user"&&(l=M),!f&&M.role==="assistant"&&(f=M),!xa&&Bp(M)&&(xa={index:v,id:M.id}),l&&f&&xa)break}Qo(Ee,s,It),br()?.updateInlineArtifactBlocks(Ee,Xo.artifacts,{suppressTransition:Do}),XA(),Wi(s),ca(s),Rr(!Do),OA(s),s.length===0&&(mn(),Ai=!0,ud=!1,fa=null,pd=!1),!gp||pa?(gp=!0,bs=l?.id??null,hp=f?.id??null):l&&l.id!==bs?(bs=l.id,IA(l.id)):f&&f.id!==hp&&RA(),f&&(hp=f.id),BA(s);let g=ze.lastUserMessageId;l&&l.id!==g&&(ze.lastUserMessageId=l.id,C.emit("user:message",l)),ze.lastUserMessageWasVoice=!!l?.viaVoice,YA(s),ya()},_p=()=>{sr!==null&&(cancelAnimationFrame(sr),sr=null);let s=Ts;Ts=null,s&&Td(s)},Vy=()=>{sr!==null&&cancelAnimationFrame(sr),sr=null,Ts=null},JA=s=>{let l=Ts??Op;if(Do&&l&&xa&&QA(l,s,xa)){Ts=s,sr===null&&(sr=requestAnimationFrame(()=>{sr=null;let f=Ts;Ts=null,f&&Td(f)}));return}if(s.length===0){Vy(),Td(s);return}_p(),Td(s)};R=new qa(n,{onMessagesChanged(s){JA(s)},onStatusChanged(s){let l=n.statusIndicator??{};zl(at,(g=>g==="idle"?l.idleText??Nt.idle:g==="connecting"?l.connectingText??Nt.connecting:g==="connected"?l.connectedText??Nt.connected:g==="error"?l.errorText??Nt.error:g==="paused"?l.pausedText??Nt.paused:g==="resuming"?l.resumingText??Nt.resuming:Nt[g])(s),l,s),Gn()},onStreamingChanged(s){s||(R?.getMessages().length===0?Vy():_p()),Do=s,Ri(s),Gn(),R&&Qo(Ee,R.getMessages(),It),s||(Rr(!0),kA(),hy=!0,R&&yy(R.getMessages(),Xr(n))),Vt(),Xl(s?"Responding\u2026":"Response complete."),ya()},onVoiceStatusChanged(s){if(C.emit("voice:status",{status:s,timestamp:Date.now()}),n.voiceRecognition?.provider?.type==="runtype")switch(s){case"listening":cr(),Ia();break;case"processing":cr(),eT();break;case"speaking":cr(),tT();break;default:s==="idle"&&R.isBargeInActive()?(cr(),Ia(),re?.setAttribute("aria-label","End voice session")):(ze.active=!1,cr(),tr("system"),fn());break}},onArtifactsState(s){Xo=s,s.artifacts.length===0&&(ia=!1),br()?.updateInlineArtifactBlocks(Ee,s.artifacts,{suppressTransition:Do}),pn(),ma()},onHistoryStateChanged(s){Rt(s)},onHistoryNotice(s){Mt(s)},onReconnect(s){let{executionId:l,lastEventId:f}=s.handle;s.phase==="paused"?C.emit("stream:paused",{executionId:l,after:f}):s.phase==="resuming"?C.emit("stream:resuming",{executionId:l,after:f,attempt:s.attempt??1}):C.emit("stream:resumed",{executionId:l,after:f})}},rr),lt.current=R,he.push(()=>R.cancel()),he.push(()=>{R.destroy(),nr?.destroy()});let Np=null;if(R.onReadAloudChange((s,l)=>{Kh=s,Gh=l,Xh();let f=s??Np;s&&(Np=s);let g=f?R.getMessages().find(v=>v.id===f)??null:null;C.emit("message:read-aloud",{messageId:f,message:g,state:l,timestamp:Date.now()}),l==="idle"&&(Np=null)}),u=!0,gp=!0,n.voiceRecognition?.provider?.type==="runtype")try{R.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let ZA=720,eM=250,Ye=dh(n.features?.history?.copy),Fo=null,Fp=!1,it=null,Ed=null,Pd="conversation",Up=null,uo=null,Rn=null,kd=R.getHistoryState(),qp=null,Bi=0,$p=null,Ld=null,Id=null,Vp=`persona-history-${Math.random().toString(36).slice(2,8)}`,jp=()=>n.features?.history?.enabled===!0,Hn=()=>jp()&&!!Fo&&!Fp,jy=()=>{let s=R.getStatus();return Do||s==="paused"||s==="resuming"},zp=()=>{let s=n.features?.history?.scope;if(s)return s;let l=n.getIdentityProof?"verified-user":"browser",f=Fo?.capabilities.scopes;return!f||f.includes(l)?l:f[0]??l},Ca=()=>Ed?.scope??zp(),zy=()=>R.getClientSession()?.targetId??null,Ky=s=>`${s.state}:${"reason"in s?s.reason:""}`,tM=s=>{let l=Ky(s);l!==qp&&(qp=l,C.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Rd=s=>{s&&(Xn.textContent="",Xn.textContent=s)},Gy=null,Xy=null,oM=()=>{if(!jp())return null;let s=bw();if(s)return s();let l=n.features?.history?.provider;return l?typeof l!="function"?l:(Gy!==l&&(Gy=l,Xy=l()),Xy):R.isClientTokenMode()?vw({client:R.getClient(),getIdentityProofConfigured:()=>typeof n.getIdentityProof=="function",onActivationCommitted:f=>R.bindActivatedSession(f),getClient:()=>R.getClient()}):null},Qy=()=>{Ld?.(),Ld=null,Id?.(),Id=null,Fp=!1,Fo=oM();let s={...rr};Fo?s.historyProvider=Fo:delete s.historyProvider,rr=s,R.setHistoryInternals(rr),Fo&&(Ld=Fo.subscribeAvailability?.(l=>{Fp=!l,l||Po({restoreFocus:!1}),Dr()})??null,Id=Fo.subscribeIdentityStatus(l=>tM(l)),qp=Ky(Fo.getIdentityStatus()))},Kp=()=>{let s=n.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!we||Ct(n)))return"panel";let l=kn??pe;return(l.getBoundingClientRect().width||l.clientWidth)>=ZA?"rail":"panel"},Yo=(s,l)=>{l?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Hd="data-persona-history-suppressed",Uo=null,Or=null,Es=null,Oi=null,Gp=null,Yy="",Jy=()=>Me===Gp?Yy:n.layout?.showHeader===!1?"none":"",nM=()=>de==="panel"&&!!Es&&Oi===Es.element&&n.layout?.showHeader!==!1&&Jy()!=="none",rM=()=>{for(let s of Array.from(Me.children))s!==Uo&&s.setAttribute(Hd,"")},sM=()=>{for(let s of Array.from(pe.querySelectorAll(`[${Hd}]`)))s.removeAttribute(Hd)},aM=()=>{let s=Es;if(!s)return;if(Array.from(Me.children).some(g=>g!==Uo&&!g.hasAttribute(Hd))){Or&&Or!==Me&&(Or.style.removeProperty("min-height"),Or=null);let g=Me.offsetHeight;g>0&&(Me.style.minHeight=`${g}px`,Or=Me)}Uo||(Uo=I("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==Uo&&Uo.replaceChildren(f),Uo.parentNode!==Me&&Me.appendChild(Uo),rM()},Zy=()=>{Or&&(Or.style.removeProperty("min-height"),Or=null),Uo&&(Es?.setHeaderPlacement("inline"),Uo.remove(),Uo=null,sM())},Wd=null,Xp=()=>{if(Wd){if(ne.style.display="none",Yo(ne,!0),Le.hidden=!0,Yo(Le,!0),nM()){aM(),Me.style.display=Jy(),Yo(Me,!1);return}Zy(),Me.style.display="none",Yo(Me,!0)}};Ft=Xp;let iM=s=>{let l=ne.style.display,f=Le.hidden,g=Le,v=Me,M=Me.style.display;Gp=v,Yy=M,Wd=()=>{Wd=null,Zy(),Gp=null,ne.style.display=l,Yo(ne,!1),g.hidden=f,Yo(g,!1),Le!==g&&(Le.hidden=!1,Yo(Le,!1)),v.style.display=M,Yo(v,!1),Me!==v&&(Me.style.display=n.layout?.showHeader===!1?"none":"",Yo(Me,!1))},Le.parentNode?.insertBefore(s,Le),Xp()},Sa=null,Ps=null,Di=null,wa=null,eb=()=>[Me,Fe.closeButtonWrapper,Fe.clearChatButtonWrapper,ne,Le],lM=52,Bd=()=>n.features?.history?.rail?.collapsible!==!1,Aa=()=>n.features?.history?.rail?.side==="right"?"right":"left",Qp=200,Yp=400,Jp=s=>Math.min(Yp,Math.max(Qp,Math.round(s))),dM=()=>n.features?.history?.rail?.resizable===!0,_i,cM=()=>{if(_i===void 0&&(_i=null,n.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${an()}rail-width`));s&&(_i=s)}catch{}return _i},Ni=()=>Jp(cM()??n.features?.history?.rail?.width??260),uM=s=>{if(_i=s,n.persistState!==!1)try{window.localStorage.setItem(`${an()}rail-width`,String(s))}catch{}},Od=()=>Bd()&&n.features?.history?.rail?.collapsedBehavior==="overlay",Ot=!1,tb=s=>{let l=I("img");return l.src=s,l.alt="",l.setAttribute("aria-hidden","true"),l},pM=()=>{let s=n.features?.history?.rail?.brand;if(!s)return;let l=!1,f;return g=>{if(s.render)try{return s.render({collapsed:g})??null}catch(v){return l||(l=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=tb(s.iconUrl):f=s.icon?ue(s.icon,20):null),f?f.cloneNode(!0):null}},fM=()=>n.features?.history?.rail?.sections?.map(s=>{let l=!1,f=g=>{l||(l=!0,console.warn("[persona] history rail section threw",s.id,g))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(g=>{let v;return{id:g.id,label:g.label,badge:g.badge,iconNode:()=>{if(v!==void 0)return v;try{g.renderIcon?v=g.renderIcon()??null:g.iconUrl?v=tb(g.iconUrl):v=g.icon?ue(g.icon,20):null}catch(M){f(M),v=null}return v},onSelect:()=>{try{g.onSelect()}catch(M){f(M)}}}})}})??[],mM=s=>{let l=fM();for(let f of s)l.some(g=>g.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):l.push(f);return l.length?l:void 0},Fi=null,ob=()=>`${an()}rail-collapsed`,Zp=()=>{if(Fi===null&&(Fi=n.features?.history?.rail?.defaultCollapsed===!0,n.persistState!==!1))try{let s=window.localStorage.getItem(ob());s&&(Fi=s==="1")}catch{}return Fi},ef=s=>{if(Fi=s,n.persistState!==!1)try{window.localStorage.setItem(ob(),s?"1":"0")}catch{}},Ui=()=>de==="rail"&&Bd()&&!Od()&&Zp(),tf=()=>{},nb=()=>{if(Od()){tf();return}ef(!Zp()),it?.view.setCollapsed(Ui()),Be(),Eo()},of=()=>{let s=n.features?.history?.rail?.collapseShortcut;return!s||!pu(s)?null:{combo:s,hint:fu(s),aria:El(s)}},rb=()=>{c.forEach(l=>l()),c=[];let s=of();s&&c.push(d.register({id:"history-rail-collapse",combo:s.combo,scope:n.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ie&&de==="rail"&&Bd()||Ta(),run:()=>Od()?tf():nb()}));for(let l of n.layout?.header?.trailingActions??[])l.shortcut&&c.push(d.register({id:`header-action-${l.id}`,combo:l.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${l.id}"]`);f?f.click():n.layout?.header?.onAction?.(l.id)}}));for(let l of i)for(let f of l.shortcuts??[])c.push(d.register({...f,id:`${l.id}:${f.id}`}))};rb();let gM=300,Dd="var(--persona-history-overlay-margin,8px)",Jo=null,ar=null,_d=0,ir=null,Ma=null,ks=!1,nf=0,sb=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ta=()=>Hn()&&Od()&&(de??Kp())==="rail",hM=()=>ie&&!Ot,qi=()=>{Ma!==null&&clearTimeout(Ma),Ma=null},yM=()=>{ah().catch(()=>{})},ab=()=>{qi(),Ot&&(Ma=setTimeout(()=>{Ma=null,!(ks||!Ot)&&(ir?.contains(document.activeElement)||Po({restoreFocus:!1}))},gM))},bM=(s,l)=>{let f=ir?.getBoundingClientRect();if(!f)return!1;let g=Jo?.getBoundingClientRect(),v=g?Math.min(g.top,f.top):f.top;return s>=f.left&&s<=f.right&&l>=v&&l<=f.bottom||!!g&&s>=g.left&&s<=g.right&&l>=g.top&&l<=g.bottom},rf=s=>{Ot&&(ks=bM(s.clientX,s.clientY),ks?qi():Ma===null&&ab())},ib=s=>{ie||!Ta()||(Ot=!0,Vi({invoker:Jo,keyboard:s?.keyboard===!0}).then(()=>{ie?!ks&&document.activeElement!==Jo&&Po():Ot=!1}))},lb=()=>{let s=Oi?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",Ot?Ye.expandLabel:Ye.collapseLabel),s.setAttribute("aria-expanded",Ot?"false":"true"))},db=()=>{ef(!1);let s=it;if(!Ot||!s){Vi({invoker:Jo});return}let l=document.activeElement===Jo;Ot=!1,Nd(),s.element.remove(),af(s.element),lb(),l&&Ud(),Eo(),Dr()},vM=()=>{ef(!0),Po()};tf=()=>{!ie||Ot?db():vM()};let xM=()=>{let s=of(),l=js({ariaLabel:Ye.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":Vp,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=l.button;f.addEventListener("mouseenter",()=>{ks=!0,qi(),!(sb()||Date.now()<nf)&&ib()}),f.addEventListener("mouseleave",()=>{ks=!1,nf=0,ab()}),f.addEventListener("focus",()=>{ie||yM()}),f.addEventListener("click",g=>{Hn()&&(g.detail!==0&&sb()&&!ie?ib():db())}),Jo=f,ar=l.wrapper},$i=()=>{if(ar&&!ar.isConnected&&(ar=null,Jo=null),!Ta()){ar?.remove(),ar=null,Jo=null;return}Jo||xM();let s=ar,l=Jo;if(!s||!l)return;let f=Aa()!=="right"?Me.firstChild:null;(f??Me.lastChild)!==s&&Me.insertBefore(s,f),s.style.display=hM()||_d>0?"none":"",l.setAttribute("aria-label",Ye.expandLabel),l.setAttribute("aria-expanded",ie?"true":"false"),ir&&Be()},cb=s=>{if(!Ot)return;let l=s.target;l instanceof Node&&(ir?.contains(l)||ar?.contains(l)||l instanceof Element&&l.closest('.persona-dropdown-menu,[role="alertdialog"]')||Po({restoreFocus:!1}))};document.addEventListener("pointerdown",cb,!0),he.push(()=>{document.removeEventListener("pointerdown",cb,!0),document.removeEventListener("pointermove",rf),Ea?.(),qi()});let sf=null,Ea=null,ub=16,pb=s=>{uM(Jp(s)),Be(),Eo()},CM=()=>{let s=I("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(Qp)),s.setAttribute("aria-valuemax",String(Yp)),s.addEventListener("pointerdown",l=>{let f=Ps;if(!f||l.button!==0)return;l.preventDefault(),Ea?.();let g=l.clientX,v=f.getBoundingClientRect().width||Ni(),M=Aa()==="right"?-1:1,_=v,K=e.ownerDocument;f.style.transition="none";let j=Z=>{_=Jp(v+M*(Z.clientX-g)),f.style.flex=`0 0 ${_}px`,s.setAttribute("aria-valuenow",String(_))},G=()=>{Ea=null,K.removeEventListener("pointermove",j),K.removeEventListener("pointerup",G),K.removeEventListener("pointercancel",G),f.style.removeProperty("transition");try{s.releasePointerCapture(l.pointerId)}catch{}pb(_)};Ea=G,K.addEventListener("pointermove",j),K.addEventListener("pointerup",G),K.addEventListener("pointercancel",G);try{s.setPointerCapture(l.pointerId)}catch{}}),s.addEventListener("keydown",l=>{let f=Aa()==="right"?-ub:ub,g=Ni(),v=l.key==="ArrowRight"?g+f:l.key==="ArrowLeft"?g-f:l.key==="Home"?Qp:l.key==="End"?Yp:null;v!==null&&(l.preventDefault(),pb(v))}),s},SM=(s,l)=>{if(!dM()||Ui()){Ea?.(),sf?.remove();return}let f=sf??CM();sf=f,f.setAttribute("aria-label",Ye.resizeLabel),f.setAttribute("aria-valuenow",String(Ni())),f.nextElementSibling!==l&&s.insertBefore(f,l)};Be=()=>{it?.view.setRailSide(Aa());let s=Aa()==="right",l=ir;if(l){let K=Jo?Jo.getBoundingClientRect().bottom-pe.getBoundingClientRect().top:0;l.style.top=`calc(${Math.max(0,Math.round(K))}px + ${Dd})`,l.style.width=`${Ni()}px`,l.style.left=s?"":Dd,l.style.right=s?Dd:""}let f=Ps,g=Sa,v=Di;if(!f||!g||!v)return;f.style.flex=`0 0 ${Ui()?lM:Ni()}px`;let M="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":M,f.style.borderLeft=s?M:"";let _=s?v:f;g.firstElementChild!==_&&g.append(_,s?f:v),SM(g,s?f:v)};let fb=s=>{if(wa&&Ps){wa.replaceWith(s),wa=null,Be();return}let l=I("div","persona-history-rail-shell");l.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=I("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let g=I("div","persona-history-rail-host");g.style.cssText="display:flex;min-height:0;overflow:hidden",pe.insertBefore(l,Me.parentNode===pe?Me:ne);for(let v of eb())v?.parentNode===pe&&f.appendChild(v);l.append(g,f),g.appendChild(s),Sa=l,Ps=g,Di=f,Be()},wM=()=>{if(Sa)return;let s=I("div","persona-history-rail-placeholder");s.style.cssText="flex:1 1 auto;min-height:0",wa=s,fb(s),Eo()},mb=()=>{wa&&(Nd(),Eo())},AM=s=>{let l=I("div","persona-history-rail-overlay");l.style.cssText=`position:absolute;bottom:${Dd};display:flex;overflow:hidden;z-index:${Ka-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,pe.style.position="relative",pe.appendChild(l),l.appendChild(s),document.addEventListener("pointermove",rf),ir=l,Be(),lb()},Nd=()=>{Wd?.(),ir&&(ks&&(nf=Date.now()+150),document.removeEventListener("pointermove",rf),ir.remove(),ir=null);let s=Sa;if(s){Ea?.();for(let l of eb())l&&s.contains(l)&&pe.insertBefore(l,s);s.remove(),Sa=null,Ps=null,Di=null,wa=null}},gb=s=>{Oi=s,s.id=Vp,s.style.flex="1 1 auto",s.style.minHeight="0"},af=s=>{gb(s),(de!=="rail"||Ot)&&mb(),de!=="rail"?iM(s):Ot?AM(s):fb(s)},Fd=()=>{if($i(),Tb(),!ie||!it)return;let s=Kp();if(s===de)return;let l=document.activeElement,f=l instanceof HTMLElement&&(it.element.contains(l)||Uo?.contains(l)===!0)?l:null;Nd(),it.element.remove(),it.view.setHeaderPlacement("inline"),de=s,it.view.setPresentation(s),it.view.setCollapsed(Ui()),it.requestRender(),it.element.isConnected||af(it.element),f?.isConnected?f.focus():Ud(),Vt(),Eo(),Dr()},hb=(s,l)=>Uo?.querySelector(l)??s.querySelector(l),Ud=()=>{let s=it?.element??Oi;if(!s)return;let l=hb(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(l){l.focus();return}let f=hb(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},Vi=async s=>{if(!Hn()||ie)return;let l=Fo;if(!l)return;if(!Ot&&Ta()&&Zp()){$i();return}qd();let f=++Bi;Pd=s?.returnSurface??"conversation",Up=s?.invoker??uo;let g=Ta()&&!Ot;g&&(_d+=1,$i(),wM());let v;try{v=await ah()}catch{Rd(Ye.openHistoryLabel),g&&(_d-=1,f===Bi&&(mb(),$i()));return}if(g&&(_d-=1),f!==Bi||ie)return;Ed={scope:zp()},de=Kp(),ie=!0;let M=de==="panel"&&n.layout?.showHeader!==!1&&Me.style.display!=="none"?"external":"inline",_=n.features?.history?.rowAvatar,K=of(),j=K?{hint:K.hint,aria:K.aria}:null,G={provider:l,context:Ed,targetId:zy(),presentation:de,collapsible:Bd(),collapsed:Ui(),railSide:Aa(),renderRailHeader:n.features?.history?.rail?.renderHeader,railBrand:pM(),onToggleCollapse:nb,...j?{collapseShortcut:j}:{},headerPlacement:M,showScopeStatus:n.features?.history?.showScopeStatus!==!1,showDelete:n.features?.history?.showDelete!==!1,showDeleteAll:n.features?.history?.showDeleteAll!==!1,...n.features?.history?.listActions?.length?{listActions:n.features.history.listActions}:{},rowAvatar:_===!1?!1:typeof _=="string"?_:n.launcher?.iconUrl,activeConversationId:R.getActiveConversationId(),...n.features?.history?.grouping?{grouping:n.features.history.grouping}:{},...n.features?.history?.copy?{copy:n.features.history.copy}:{},...n.features?.history?.pageSize!==void 0?{pageSize:n.features.history.pageSize}:{},onSelect:Z=>df(Z,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Z=>Ls(Z),attachTooltip:eo,onStartNew:()=>cf({focusComposer:!0}),onClose:()=>Po(),onRequestDeleteConversation:Z=>Mb(Z),onRequestClearHistory:()=>LM(),...l.resetDevice?{onRequestResetIdentity:()=>IM()}:{}};it=yw({plugins:i,config:n,getPresentation:()=>de??"panel",getReturnSurface:()=>Pd,close:()=>Po(),createView:({slots:Z,renderDom:ae,onModelChange:me,railSections:Je})=>(Es=v.createHistoryView({...G,railSections:mM(Je),slots:Z,renderDom:ae,onModelChange:me,onAnnounce:Rd}),Es),onElementChanged:(Z,ae)=>{if(!ae?.isConnected)return af(Z);gb(Z),ae.replaceWith(Z),Xp()}}),it.view.setNewConversationRequired(kd.recovery==="new_conversation_required"),s?.focus!==!1&&(de!=="rail"||s?.keyboard===!0)&&Ud(),Vt(),Eo(),Dr(),C.emit("history:opened",{presentation:de,returnSurface:Pd,timestamp:Date.now()})},qd=()=>{},Po=s=>{if(!ie)return;Bi+=1;let l=Pd,f=Up,g=it,v=s?.restoreFocus!==!1;ie=!1;let M=!1,_=null,K=()=>{if(!M){if(M=!0,qd=()=>{},_!==null&&clearTimeout(_),Ot=!1,qi(),Nd(),g?.dispose(),g?.view.destroy(),g?.element.remove(),it===g&&(it=null,Es=null,Oi=null,de=null,Ed=null,Up=null),Vt(),Eo(),Dr(),v){let G=f??uo;G?.isConnected?G.focus():ws()}C.emit("history:closed",{returnSurface:l,timestamp:Date.now()})}},j=g&&g.element===g.view.element?g.view.playExit():null;if(!j){K();return}qd=K,_=setTimeout(K,eM),j.then(K)},yb=s=>{if(!(s.key!=="Escape"||!ie||!it)){if(de==="rail"){let l=s.target;if(!(l instanceof Node)||!(it.element.contains(l)||Ot&&ar?.contains(l)===!0))return}s.preventDefault(),s.stopPropagation(),Po()}};pe.addEventListener("keydown",yb),he.push(()=>pe.removeEventListener("keydown",yb));let $d=null,bb=!1,ji=()=>{if(!wr)return;let s=n.layout?.header?.titleSource==="conversation",l=s&&$d?.trim()||null;wr.textContent=l??n.launcher?.title??"Chat Assistant";let f=wr.closest(".persona-combo-btn");if(!f)return;let g=!s||R.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",g?"false":"true"),f.setAttribute("aria-haspopup",g?"true":"false"),g||f.setAttribute("aria-expanded","false"),f.style.cursor=g?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=g?"":"none")},MM=s=>{s!==$d&&($d=s,ji())},Ls=s=>{bb=s?.starred===!0,MM(s&&s.title.trim()||null),ji()};ji(),pe.addEventListener("persona:title-menu-builtin",s=>{let l=s.detail?.actionId,f=R.getActiveConversationId();f&&(l==="delete"?Mb(f):l==="star"&&R.canUpdateConversations()&&uf(f,{starred:!bb}).catch(()=>{}))});let Vd=0,TM=250,jd=null,zd=()=>{jd&&clearTimeout(jd),jd=null};he.push(zd);let vb=()=>{zd();let s=As;s&&(Hi=!0,s.hidden=!1,Ee.style.display="none",Wi())},Kd=()=>{Vd+=1,zd(),As&&(As.remove(),As=null,Hi=!1,Ee.style.removeProperty("display"),Yo(Le,!1),Wi())},EM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Ee.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},lf=(s,l)=>Y("div",{className:go("persona-conversation-loading-bubble",l&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),xb=()=>Y("div",{className:"persona-conversation-loading-body"},lf("58%",!1),lf("72%",!0),lf("44%",!1)),Cb=s=>{As?.remove(),As=s,s.hidden=!Hi,ne.insertBefore(s,Ee),zd(),Hi||(jd=setTimeout(vb,TM)),Yo(Le,!0)},PM=()=>{let s={config:n,streaming:!1,location:"conversation-open",defaultRenderer:xb},l=null,f=i.find(g=>g.renderLoadingIndicator);f?.renderLoadingIndicator&&(l=f.renderLoadingIndicator(s)),l===null&&n.loadingIndicator?.render&&(l=n.loadingIndicator.render(s)),Cb(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ye.openConversationLoadingLabel}},l??xb()))},kM=s=>{let l=()=>{df(s,{focusComposer:!0}).catch(()=>{})},f=Hn()?()=>{Kd(),Vi()}:void 0,g=(K,j)=>{let G=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:K});return G.addEventListener("click",j),G},v=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Ye.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},g(Ye.openConversationRetryLabel,l),f?g(Ye.openConversationBackLabel,f):null)),M=Object.freeze({conversationId:s,config:n,copy:Object.freeze({title:Ye.openConversationErrorTitle,retryLabel:Ye.openConversationRetryLabel,backLabel:Ye.openConversationBackLabel}),retry:l,...f?{back:f}:{},defaultRenderer:v}),_=null;for(let K of i)if(K.renderHistoryOpenError){try{_=K.renderHistoryOpenError(M)}catch(j){console.warn("[persona] renderHistoryOpenError threw",j),_=null}if(_)break}Cb(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},_??v())),vb()};C.on("history:closed",()=>{As&&Yo(Le,!0)});let df=async(s,{focusComposer:l=!1}={})=>{let f=Ca(),g=!!it;it?.view.setActiveConversationId(s),Kd();let v=Vd;PM(),ie&&(de==="panel"||Ot)&&Po({restoreFocus:!1}),pa=!0;try{await R.openConversation(s,{scope:f})}catch(M){throw v===Vd&&kM(s),M}finally{pa=!1}v===Vd&&(Kd(),Bt.clear(),mn(),To(),Sp()||yd(),EM(),lr(),g||Ls(null),C.emit("history:conversationOpened",{conversationId:s,title:$d,scope:f,timestamp:Date.now()}),l&&ws())},cf=async({focusComposer:s=!1}={})=>{Kd(),await R.startNewConversation({scope:Ca()}),Ls(null),Bt.clear(),mn(),To(),yd(),lr();let l=R.getActiveConversationId();it?.view.setActiveConversationId(l),C.emit("history:conversationStarted",{conversationId:l,timestamp:Date.now()}),ie&&(de==="panel"||Ot)&&Po({restoreFocus:!1}),s&&ws()},uf=async(s,l)=>{let f=await R.updateConversation(s,{...l,...l.title!==void 0?{title:l.title.trim()}:{}});return it?.view.applyConversationSummary(f),!it&&s===R.getActiveConversationId()&&Ls(f),f},Sb=async s=>{let l=Ca(),f=R.getActiveConversationId()===s;await R.deleteConversation(s,{scope:l}),it?.view.removeConversationSummary(s),f&&(Ls(null),Bt.clear(),mn(),To(),lr()),C.emit("history:conversationDeleted",{conversationId:s,scope:l,wasActive:f,timestamp:Date.now()})},wb=async s=>{let l=s?.scope??Ca(),f=s?.allTargets?null:s?.targetId??zy(),g=await R.clearConversationHistory({...f?{targetId:f}:{},scope:l});return Ls(null),Bt.clear(),mn(),To(),lr(),C.emit("history:cleared",{deleted:g.deleted,scope:l,targetId:f,timestamp:Date.now()}),g},Ab=async()=>{if(!Fo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await R.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ls(null),R.clearArtifacts(),Bt.clear(),Op=null,n.clearStoredSessionId?.(),n.clearStoredConversationId?.(),$={},He.syncFromMetadata(),U?.clear&&md(()=>U.clear(),"[AgentWidget] Failed to clear storage adapter:"),mn(),To(),lr(),Po({restoreFocus:!1}),ws(),be||Et?.launcher.element.focus()}return Rd(s?Ye.identityResetNotice:Ye.identityResetUnconfirmedNotice),C.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},pf=()=>kn?Se:pe,Mb=async s=>await _u({host:pf(),title:Ye.deleteConversationConfirmTitle,description:Ye.deleteConversationConfirm,confirmLabel:Ye.deleteConversationConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await Sb(s),"deleted"):"cancelled",LM=async()=>{let s=Ca()==="verified-user";return await _u({host:pf(),title:Ye.clearHistoryConfirmTitle,description:s?Ye.clearHistoryVerifiedConfirm:Ye.clearHistoryConfirm,confirmLabel:Ye.clearHistoryConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await wb(),"cleared"):"cancelled"},IM=async()=>{if(!await _u({host:pf(),title:Ye.resetIdentityConfirmTitle,description:Ye.resetIdentityConfirm,confirmLabel:Ye.resetIdentityConfirmLabel,cancelLabel:Ye.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:l}=await Ab();return{outcome:"reset",remoteRevocationConfirmed:l}},Zo=I("button","persona-history-earlier");Zo.type="button",Zo.textContent=Ye.showEarlierMessagesLabel,Zo.setAttribute("data-persona-history-earlier",""),Object.assign(Zo.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let lr=()=>{if(!(Hn()&&!!kd.nextMessageCursor&&!!R.getActiveConversationId())){Zo.remove();return}Zo.textContent=Ye.showEarlierMessagesLabel,Zo.parentNode!==ne&&ne.insertBefore(Zo,ne.firstChild)};Zo.addEventListener("click",()=>{let s=R.getActiveConversationId(),l=kd.nextMessageCursor;if(!s||!l||Zo.disabled)return;Zo.disabled=!0;let f=ne.scrollHeight,g=ne.scrollTop;R.loadOlderMessages(s,l,{scope:Ca()}).then(()=>{ne.scrollTop=g+(ne.scrollHeight-f),Eo()}).catch(()=>{}).finally(()=>{Zo.disabled=!1,lr()})});let RM=()=>{let s=js({ariaLabel:Ye.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return s.button.addEventListener("click",l=>{if(!(!Hn()||jy())){if(ie){Po();return}Vi({invoker:s.button,keyboard:l.detail===0})}}),s},Tb=()=>{if(!Hn()){Rn?.remove(),uo=null,Rn=null;return}if(Rn&&!Rn.isConnected&&(uo=null,Rn=null),!uo&&Me){let g=RM();uo=g.button,Rn=g.wrapper;let v=Fe.clearChatButtonWrapper||Fe.closeButtonWrapper;v?.parentNode&&Me.contains(v)?v.parentNode.insertBefore(Rn,v):Me.appendChild(Rn)}if(!uo||!Rn)return;let s=Ta()||ie&&de==="rail";if(Rn.style.display=s?"none":"",s){document.activeElement===uo&&Ud();return}let l=jy();uo.disabled=l,uo.setAttribute("aria-disabled",l?"true":"false");let f=l?Ye.openHistoryBusyLabel:Ye.openHistoryLabel;uo.setAttribute("aria-label",f),(n.features?.history?.presentation??"panel")==="panel"?(uo.removeAttribute("aria-expanded"),uo.removeAttribute("aria-controls")):(uo.setAttribute("aria-expanded",ie?"true":"false"),uo.setAttribute("aria-controls",Vp))},Gd=!1,HM=()=>{let s=Fe.clearChatButton;if(s){if(Hn()){Gd||($p=s.getAttribute("aria-label")??"",Gd=!0),s.setAttribute("aria-label",Ye.newConversationLabel),s.removeAttribute("title");return}Gd&&(Gd=!1,$p&&s.setAttribute("aria-label",$p))}},Dr=()=>{Ye=dh(n.features?.history?.copy),Tb(),$i(),HM(),lr()};Gn=Dr,Rt=s=>{kd=s,it?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),Ri(s.sendBlocked||Do),lr()},Mt=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Bt.clear(),mn(),To()),Rd(s.message),it?.view.refresh()},Qy(),Dr(),he.push(()=>{Ld?.(),Id?.(),Bi+=1,qd(),it?.dispose(),it?.view.destroy(),it=null}),n.clientToken&&R.initClientSession().then(()=>{if(Hn())return R.reconcileBootConversation({scope:zp()})}).then(()=>{lr()}).catch(s=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(so||n.onSSEEvent)&&R.setSSEEventCallback((s,l)=>{n.onSSEEvent?.(s,l),oe(s,l)});let Eb=()=>{let s=n.resume??(Q?rr.getStoredResumableHandle?.():null);s&&typeof n.reconnectStream=="function"&&R.resumeFromHandle(s)};E?E.then(s=>{if(s){if(s.metadata&&($=ch(s.metadata),He.syncFromMetadata()),s.messages?.length){pa=!0;try{R.hydrateMessages(s.messages)}finally{pa=!1}Cd()}s.artifacts?.length&&R.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null),wy(s.draft)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{Pp=!0,B(),Eb()}):(wy(W),Eb());let WM=()=>{!Ie()||be||!(n.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},BM=(s,l)=>s?l?{refs:[...s.refs,...l.refs],finalize:async()=>{let[f,g]=await Promise.allSettled([s.finalize(),l.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),g.status==="fulfilled"?v.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),ZL(v)}}:s:l,ff=()=>{let l=ce.getInlineMessageFields?.();return l&&l.contentSegments.some(g=>g.kind==="mention")?l.contentSegments:void 0},dr=!1,Is=null,Xd=()=>{ce.value="",ce.style.height="auto",Tn(),Ki()},mf="data-persona-composer-notice",Pa=null;function OM(s){Xl(s),!(Ie()||!at)&&(at.hasAttribute(pi)||(at.setAttribute(mf,""),at.setAttribute("role","status"),at.setAttribute("aria-live","polite"),at.textContent=s,Pa&&clearTimeout(Pa),Pa=setTimeout(()=>{if(Pa=null,!!at?.hasAttribute(mf)&&(at.removeAttribute(mf),at.removeAttribute("role"),at.removeAttribute("aria-live"),u)){let l=R.getStatus();zl(at,Co(l),n.statusIndicator??{},l)}},4e3)))}function DM(){let s=Ce.getState().pendingSubmission;s&&(ra(void 0),ce&&(ce.value=s.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),Tn()),s.options.selectedModelId&&(Ce.setSelectedModelId(s.options.selectedModelId),Mr?.repaint()),s.options.activeModeIds?.length&&Zl(s.options.activeModeIds),s.options.quote&&En(s.options.quote),ce?.focus())}let _M=s=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",s)},Pb=(s={})=>{let l=(s.overrideText??ce?.value??"").trim();return s.resolveInlineCommand&&l?(Ht?.takeInlineCommand(l)??Promise.resolve(null)).then(f=>kb(s,l,f)):kb(s,l,null)},kb=(s,l,f)=>{if(f?.kind==="action"){Xd(),Ht?.clear(),as();return}let g=f?.kind==="server"?f.mentions:null,v=f?.kind==="prompt"?f.sendText:l,M=s.pending?.contentParts,_=(Ze?.hasAttachments()??!1)||(M?.length??0)>0;if(!EC({text:v,hasAttachments:_,attachmentsReady:Ze?.isReady()??!0,hasMentions:Ht?.hasMentions()??!1,hasServerMentions:!!g,inputDisabled:Wr(),sendDisabled:Ss()}))return;let K=R.isStreaming()?op():"block";if(K==="defer-one"&&!s.pending){if(Ce.getState().pendingSubmission){OM("One message is already queued. Edit or remove it first.");return}NM({intent:s,sendText:v,serverMentions:g});return}let j={text:v,mentionRefs:[...Ht?.getMentionRefs()??[],...g?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:ff(),options:{...Ce.getState().selectedModelId&&{selectedModelId:Ce.getState().selectedModelId},...Ce.getState().activeModeIds.length>0&&{activeModeIds:[...Ce.getState().activeModeIds]},...Ce.getState().quote&&{quote:{...Ce.getState().quote}}},viaVoice:s.viaVoice};s.pending&&(j.options={...s.pending.options},j.contentSegments=s.pending.contentSegments,j.mentionRefs=[...s.pending.mentionRefs],j.viaVoice=s.pending.viaVoice);let G=()=>{if(M?.length)return[...M];if(!Ze?.hasAttachments())return;let ut=[...Ze.getContentParts()];return j.text&&ut.push(rn(j.text)),ut};j.contentParts=G();let Z=()=>{gs(),WM();let ut=Ht?.collectForSubmit()??null,Qt=BM(ut,g),Dt=G();s.consumeDraft!==!1&&Xd();let kt={selectedModelId:j.options.selectedModelId,activeModeIds:j.options.activeModeIds},ao=K==="interrupt";ao&&R.cancel(),R.sendMessage(j.text,{contentParts:Dt,mentions:Qt??void 0,contentSegments:j.contentSegments,viaVoice:j.viaVoice,composerOptions:kt,...j.options.quote&&{quote:j.options.quote},...ao&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),ut&&Ht?.clear(),as();let et=Ce.getState().activeModeIds,io=fC(et,n.composer?.modes);io.length!==et.length&&Zl(io),Ce.getState().quote&&En(void 0),hd(),ip.release(),cn()},ae=n.composer?.onBeforeSend;if(!ae){Z();return}let me=new AbortController;Is=me;let Je=ut=>{if(Is=null,ut.status==="error"){_M(ut.error);return}ut.status==="proceed"&&Z()},dt=PC(ae,j,me.signal);if(!(dt instanceof Promise)){Je(dt);return}return Ce.setPreparing(!0),dt.then(Je).finally(()=>Ce.setPreparing(!1))};function NM(s){let l=Ce.getState(),f=Ze?.hasAttachments()??!1,g=f?[...Ze.getContentParts()]:[];f&&s.sendText&&g.push(rn(s.sendText));let v=sg({text:s.sendText,contentParts:g.length?g:void 0,mentionRefs:[...Ht?.getMentionRefs()??[],...s.serverMentions?.refs??[]],contentSegments:ff(),options:{...l.selectedModelId&&{selectedModelId:l.selectedModelId},...l.activeModeIds.length>0&&{activeModeIds:[...l.activeModeIds]},...l.quote&&{quote:{...l.quote}}},viaVoice:s.intent.viaVoice});ra(v),s.intent.consumeDraft!==!1&&Xd(),f&&Ze.clearAttachments(),Ht?.clear(),as(),l.quote&&En(void 0),hd(),ip.release(),cn(),Xl("Message queued. It sends when the response finishes.")}function FM(){let s=Ce.getState().pendingSubmission;s&&(ra(void 0),Yd(s.text,{consumeDraft:!1,pending:s}))}function UM(s){if(n.messageActions?.showEdit!==!0)return;let l=R.getMessages().find(f=>f.id===s);!l||!Yf(l)||ms!==s&&(gs(),ms=s,kr=bC({messageId:s,initialText:l.content,onSave:f=>qM(s,f),onCancel:()=>gs()}),Bt.delete(s),Qo(Ee,R.getMessages(),It),kr.focus())}function qM(s,l){let f=kr;if(ms=null,kr=null,f?.destroy(),Bt.delete(s),!R.resubmitFrom(s,{reason:"edit",replacement:{text:l,mentionRefs:[],options:{}}})){Qo(Ee,R.getMessages(),It);return}Eo()}function $M(s){if(R.isStreaming())return;let l=Qf(R.getMessages(),s);l&&(gs(),R.resubmitFrom(l,{reason:"retry"})&&Eo())}ed={regenerate:$M,edit:UM,quote:s=>{let f=R.getMessages().find(g=>g.id===s)?.content?.trim();f&&(En({text:f,messageId:s}),ce?.focus())}};let zi=async s=>{if(!dr){dr=!0;try{await Pb({resolveInlineCommand:!0,...s})}finally{dr=!1}}};function Qd(s){Ss()||(Xd(),Yd(s,{consumeDraft:!1}))}let Yd=(s,l)=>{if(dr)return;dr=!0;let f=()=>{dr=!1};try{let g=Pb({...l,overrideText:s});g instanceof Promise?g.finally(f):f()}catch(g){throw f(),g}},VM=s=>{if(s.preventDefault(),R.isStreaming()){R.cancel(),Ro?.reset(),J?.update();return}dr||zi()},jM=()=>n.features?.composerHistory!==!1,gf={...mg},hf=!1,Ki=()=>{gf={...mg}},zM=()=>R.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),KM=s=>{if(!ce)return;hf=!0,ce.value=s,ce.dispatchEvent(new Event("input",{bubbles:!0})),hf=!1;let l=ce.value.length;ce.setSelectionRange(l,l)},GM=s=>{hf||(s.isComposing||Ht?.handleInput(s.inputType??void 0),Ki())},XM=()=>({submitKey:n.composer?.submitKey,insertNewlineOnTouchEnter:n.composer?.insertNewlineOnTouchEnter,coarsePointer:Sl(ce)}),QM=s=>{if(ce&&!Wr()&&!(!s.isComposing&&Ht?.handleKeydown(s))){if(jM()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let l=ce.selectionStart===0&&ce.selectionEnd===0,f=GC({direction:s.key==="ArrowUp"?"up":"down",history:zM(),currentValue:ce.value,atStart:l,state:gf});if(gf=f.state,f.handled){s.preventDefault(),f.value!==void 0&&KM(f.value);return}}if(Yx(s,XM())){if(R.isStreaming()){if(s.preventDefault(),op()==="block"||dr||Ss())return;Ki(),zi();return}if(dr){s.preventDefault();return}if(Ss()){s.preventDefault();return}Ki(),s.preventDefault(),Ae.click()}}},Lb=s=>{if(!(s.key!=="Escape"||s.isComposing)&&s.composedPath().includes(pe)){if(Is){Is.abort(),Is=null,s.preventDefault(),s.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),Ro?.reset(),J?.update(),Ki(),s.preventDefault(),s.stopImmediatePropagation())}},YM=async s=>{if(n.attachments?.enabled!==!0||!Ze||Wr())return;let l=XL(s.clipboardData);l.length!==0&&(s.preventDefault(),await Ze.handleFiles(l))},en=null,Wn=!1,ka=null,bt=null,yf=()=>n.voiceRecognition?.completionBehavior==="review";function Rs(s){re?.setAttribute("data-state",s),s==="recording"?ZM():Cf()}let Ib="--persona-voice-level",bf=.5,La=null,vf=-1,Jd=0,Rb=()=>{let s=[],l=Bo??re?.parentElement??null;return l&&s.push(l),Le&&s.push(Le),s},xf=s=>{let l=Math.round(Math.max(0,Math.min(1,s))*100)/100;if(l!==vf){vf=l;for(let f of Rb())f.style.setProperty(Ib,String(l))}},JM=()=>{vf=-1,Jd=0;for(let s of Rb())s.style.removeProperty(Ib)};function ZM(){if(La!==null)return;if(typeof requestAnimationFrame!="function"){xf(u?R.getVoiceLevel()??bf:bf);return}let s=()=>{La=requestAnimationFrame(s);let l=u?R.getVoiceLevel():null;if(l===null){xf(bf);return}Jd+=(l-Jd)*.3,xf(Jd)};La=requestAnimationFrame(s)}function Cf(){La!==null&&(cancelAnimationFrame(La),La=null),JM()}let Hb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zd=(s="user")=>{if(Wn||R.isStreaming())return;let l=Hb();if(!l)return;en=new l;let f=n.voiceRecognition??{},g=f.pauseDuration??2e3;en.continuous=f.provider?.browser?.continuous??!0,en.interimResults=!0,en.lang=f.provider?.browser?.language??"en-US";let v=ce.value;en.onresult=M=>{let _="",K="";for(let G=0;G<M.results.length;G++){let Z=M.results[G],ae=Z[0].transcript;Z.isFinal?_+=ae+" ":K=ae}let j=v+_+K;ce.value=j,Tn(),ka&&clearTimeout(ka),(_||K)&&(ka=window.setTimeout(()=>{if(ce.value.trim()&&en&&Wn){if(_r(),yf())return;zi({viaVoice:!0})}},g))},en.onerror=M=>{M.error!=="no-speech"&&_r()},en.onend=()=>{if(Wn){let M=ce.value.trim();!yf()&&M&&M!==v.trim()&&zi({viaVoice:!0}),_r()}};try{if(en.start(),Wn=!0,ze.active=!0,s!=="system"&&(ze.manuallyDeactivated=!1),tr(s),fn(),cn(),re){let M=n.voiceRecognition??{};bt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:M.iconName??"mic",iconSize:parseFloat(M.iconSize??"")||ho};let _=M.recordingBackgroundColor,K=M.recordingIconColor,j=M.recordingBorderColor;if(re.classList.add("persona-voice-recording"),Rs("recording"),re.style.backgroundColor=_??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=K??"var(--persona-voice-recording-indicator, #ffffff)",K){let G=re.querySelector("svg");G&&G.setAttribute("stroke",K)}j&&(re.style.borderColor=j),re.setAttribute("aria-label","Stop voice recognition")}}catch{_r("system")}},_r=(s="user")=>{if(Wn){if(Wn=!1,ka&&(clearTimeout(ka),ka=null),en){try{en.stop()}catch{}en=null}if(ze.active=!1,tr(s),fn(),cn(),re){if(re.classList.remove("persona-voice-recording"),Rs("idle"),bt){re.style.backgroundColor=bt.backgroundColor,re.style.color=bt.color,re.style.borderColor=bt.borderColor;let l=re.querySelector("svg");l&&l.setAttribute("stroke",bt.color||"currentColor"),bt=null}re.setAttribute("aria-label","Start voice recognition")}}},Sf=()=>{if(!re||bt)return;let s=n.voiceRecognition??{};bt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??"")||ho}},wf=(s,l)=>{if(!re)return;let f=re.querySelector("svg");f&&f.remove();let g=bt?.iconSize??(parseFloat(n.voiceRecognition?.iconSize??"")||ho),v=ue(s,g,l,1.5);v&&re.appendChild(v)},ec=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ia=()=>{if(!re)return;Sf();let s=n.voiceRecognition??{},l=s.recordingBackgroundColor,f=s.recordingIconColor,g=s.recordingBorderColor;if(ec(),re.classList.add("persona-voice-recording"),Rs("recording"),re.style.backgroundColor=l??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=re.querySelector("svg");v&&v.setAttribute("stroke",f)}g&&(re.style.borderColor=g),re.setAttribute("aria-label","Stop voice recognition")},eT=()=>{if(!re)return;Sf();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=s.processingIconName??"loader",g=s.processingIconColor??bt?.color??"",v=s.processingBackgroundColor??bt?.backgroundColor??"",M=s.processingBorderColor??bt?.borderColor??"";ec(),re.classList.add("persona-voice-processing"),Rs("processing"),re.style.backgroundColor=v,re.style.borderColor=M;let _=g||"currentColor";re.style.color=_,wf(f,_),re.setAttribute("aria-label","Processing voice input"),l==="none"&&(re.style.cursor="default")},tT=()=>{if(!re)return;Sf();let s=n.voiceRecognition??{},l=R.getVoiceInterruptionMode(),f=l==="cancel"?"square":l==="barge-in"?"mic":"volume-2",g=s.speakingIconName??f,v=s.speakingIconColor??(l==="barge-in"?s.recordingIconColor??bt?.color??"":bt?.color??""),M=s.speakingBackgroundColor??(l==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":bt?.backgroundColor??""),_=s.speakingBorderColor??(l==="barge-in"?s.recordingBorderColor??"":bt?.borderColor??"");ec(),re.classList.add("persona-voice-speaking"),Rs("speaking"),re.style.backgroundColor=M,re.style.borderColor=_;let K=v||"currentColor";re.style.color=K,wf(g,K);let j=l==="cancel"?"Stop playback and re-record":l==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",j),l==="none"&&(re.style.cursor="default"),l==="barge-in"&&re.classList.add("persona-voice-recording")},cr=()=>{re&&(ec(),Rs("idle"),bt&&(re.style.backgroundColor=bt.backgroundColor??"",re.style.color=bt.color??"",re.style.borderColor=bt.borderColor??"",wf(bt.iconName,bt.color||"currentColor"),bt=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},Af=()=>{if(!Wr()){if(n.voiceRecognition?.provider?.type==="runtype"){let s=R.getVoiceStatus(),l=R.getVoiceInterruptionMode();if(l==="none"&&(s==="processing"||s==="speaking"))return;if(l==="cancel"&&(s==="processing"||s==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,fn(),tr("user"),cr()});return}R.toggleVoice().then(()=>{ze.active=R.isVoiceActive(),ze.manuallyDeactivated=!R.isVoiceActive(),fn(),tr("user"),R.isVoiceActive()?Ia():cr()});return}if(Wn){let s=ce.value.trim();ze.manuallyDeactivated=!0,fn(),_r("user"),s&&!yf()&&zi()}else ze.manuallyDeactivated=!1,fn(),Zd("user")}};np=Af,re&&he.push(()=>{n.voiceRecognition?.provider?.type==="runtype"?(R.isVoiceActive()&&R.toggleVoice(),cr()):_r("system")});let oT=C.on("assistant:complete",()=>{Ce.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||FM()},0)});he.push(oT);let nT=C.on("assistant:complete",()=>{xy&&(ze.active||ze.manuallyDeactivated||xy==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(n.voiceRecognition?.provider?.type==="runtype"?R.toggleVoice().then(()=>{ze.active=R.isVoiceActive(),tr("auto"),R.isVoiceActive()&&Ia()}):Zd("auto"))},600))});he.push(nT);let rT=C.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});he.push(rT);let Wb=()=>{ct(!be,"user")},Et=null,po=null;if(we&&!Ie()){let{instance:s,element:l}=$g({config:n,plugins:i,onToggle:Wb});Et=s,s||(po=l)}Et?e.appendChild(Et.element):po&&e.appendChild(po),Ii(),ca(),Ad(),Hp(),Ri(R.isStreaming()),Sp()||(Oo()==="follow"?Rr(!0):yd()),wA(),ke&&(!we||Ie()?setTimeout(()=>ws(),0):be&&setTimeout(()=>ws(),200));let Hs=null,Bb=()=>{Hs&&(Hs.disconnect(),Hs.observe(Le),Hs.observe(pe))},Gi=()=>{if(Ie()){ss(),Ii();return}let s=Ct(n),l=n.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,g=n.launcher?.mobileFullscreen??!0,v=n.launcher?.mobileBreakpoint??640,M=f.innerWidth<=v,_=g&&M&&we;try{if(_){is(),Ci=ld();return}let K=!1;At&&(At=!1,is(),K=!0);let j=ld();if(!K&&j!==Ci&&(is(),K=!0),Ci=j,K&&rd(),!we&&!s){Se.style.height="",Se.style.width="";return}if(!l&&!s){let Z=n?.launcher?.width??n?.launcherWidth??$o;Se.style.width=Z,Se.style.maxWidth=Z}id(),ry()}finally{if(ss(),Jl(),Ii(),be&&we){let j=(e.ownerDocument.defaultView??window).innerWidth<=(n.launcher?.mobileBreakpoint??640),G=n.launcher?.sidebarMode??!1,Z=n.launcher?.mobileFullscreen??!0,ae=Ct(n)&&Z&&j,me=G||Z&&j&&we||ae;if(me&&!In){let Je=e.getRootNode(),dt=Je instanceof ShadowRoot?Je.host:e.closest(".persona-host");dt&&!Ln&&(Ln=xg(dt,n.launcher?.zIndex??ro)),In=Cg(e.ownerDocument)}else me||(Ln?.(),Ln=null,In?.(),In=null)}}};Gi();let tc=e.ownerDocument.defaultView??window;if(tc.addEventListener("resize",Gi),he.push(()=>tc.removeEventListener("resize",Gi)),typeof ResizeObserver<"u"){Hs=new ResizeObserver(()=>{Jl()}),Bb(),he.push(()=>{Hs?.disconnect(),Hs=null});let s=new ResizeObserver(()=>{Fd()});s.observe(pe),he.push(()=>s.disconnect())}tc.addEventListener("resize",Fd),he.push(()=>tc.removeEventListener("resize",Fd)),No=ne.scrollTop;let Ob=jn(ne),Db=()=>{let s=ne.scrollTop,l=jn(ne),f=l<Ob;if(Ob=l,!Ar()){No=s,Vt();return}let{action:g,nextLastScrollTop:v}=oS({following:_o.isFollowing(),currentScrollTop:s,lastScrollTop:No,nearBottom:Vs(ne,Zn),userScrollThreshold:vA,isAutoScrolling:Mo||cd||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(No=v,g==="resume"){bd()||To();return}g==="pause"&&Ti()};if(ne.addEventListener("scroll",Db,{passive:!0}),he.push(()=>ne.removeEventListener("scroll",Db)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{LA(),If(Ee)});s.observe(Ee),s.observe(ne),he.push(()=>s.disconnect())}let _b=()=>{Ar()&&_o.isFollowing()&&bd()&&Ti()},Nb=ne.ownerDocument;Nb.addEventListener("selectionchange",_b),he.push(()=>{Nb.removeEventListener("selectionchange",_b)});let sT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Fb=s=>{sT.has(s.key)&&(vs(),Mh()&&Ar()&&_o.isFollowing()&&Ti())},Ub=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(vs(),Mh()&&Ar()&&_o.isFollowing()&&Ti())};ne.addEventListener("keydown",Fb),ne.addEventListener("focusin",Ub),he.push(()=>{ne.removeEventListener("keydown",Fb),ne.removeEventListener("focusin",Ub)});let qb=s=>{if(s.deltaY!==0&&vs(),!Ar())return;let l=nS({following:_o.isFollowing(),deltaY:s.deltaY,nearBottom:Vs(ne,Zn),resumeWhenNearBottom:!0});l==="pause"?Ti():l==="resume"&&!bd()&&To()};ne.addEventListener("wheel",qb,{passive:!0}),ne.addEventListener("touchmove",vs,{passive:!0}),ne.addEventListener("pointerdown",vs,{passive:!0}),he.push(()=>{ne.removeEventListener("touchmove",vs),ne.removeEventListener("pointerdown",vs)}),he.push(()=>ne.removeEventListener("wheel",qb)),Wt.addEventListener("click",()=>{mn(),ne.scrollTop=ne.scrollHeight,No=ne.scrollTop,To(),Rr(!0),Vt()}),he.push(()=>Wt.remove()),he.push(()=>{My(),mn()});let $b=()=>{$e&&(us&&($e.removeEventListener("click",us),us=null),Pe()?($e.style.display="",us=()=>{ct(!1,"user")},$e.addEventListener("click",us)):$e.style.display="none")};$b(),(()=>{let{clearChatButton:s}=Fe;s&&s.addEventListener("click",()=>{if(Hn()){cf({focusComposer:!0}).catch(f=>{n.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}R.clearMessages(),Bt.clear(),To(),Kr(Fe.composerOverlay);try{localStorage.removeItem(ui),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ui}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ui)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),U?.clear&&md(()=>U.clear(),"[AgentWidget] Failed to clear storage adapter:"),$={},He.syncFromMetadata(),Ze?.clearAttachments(),hd(),ra(void 0),En(void 0),gs(),tt?.clear(),Ro?.reset(),J?.update()})})();let Vb=[["keydown",QM],["input",GM],["input",Tn],["input",as],["keyup",as],["paste",YM],["focus",iA]],jb=s=>{if(s)for(let[l,f]of Vb)nt?.addListener(s,l,f)},aT=s=>{if(s)for(let[l,f]of Vb)nt?.removeListener(s,l,f)},zb=()=>{nt&&(nt.addListener(nt.form,"submit",VM),nt.addListener(nt.footer,"click",as),jb(ce),re&&nt.addListener(re,"click",Af))};zb();let Kb=()=>{Ht?.onComposerSwap((s,l)=>{aT(l),ce=s,nt&&(nt.input=s),jb(s),sp(),Tp(),Tn()})};Kb();let Mf=!1;function Gb(){if(!Mf){Mf=!0;try{let s=ce?.value??"",l=Le.ownerDocument??document,f=ce?l.activeElement===ce:!1;Cf(),nt?.destroy(),nt=null,Ht?.destroy(),Ht=null;let g=null,v=()=>(g=Ie()?Cu({config:n}):Xs({config:n}),g.footer),M=Bh(v)??v();Ho.replaceComposer(M),Le=Ho.composer.footer;let _=g!==null&&M===g.footer;aa=!_,Ah=_?g.setSendButtonMode:()=>{},Wh(Le),Dh(Le),_h(),Nh(),Fh(),Kb(),Uh(),ap(),qh(),zb();let K=cs.indexOf(Jn);Jn.destroy(),Jn=Ol(Sr),K>=0&&(cs[K]=Jn),ce&&(ce.value=s),Tn(),as(),Ad(),ca(),Ri(R.isStreaming()),ze.active&&Rs("recording"),is(),Bb(),ss(),cn(),Sd(),f&&ce?.focus()}finally{Mf=!1}}}let Xi=e.ownerDocument??document;Xi.addEventListener("keydown",Lb,!0);let Xb=()=>{bp()},Qb=()=>{Xi.visibilityState==="hidden"&&bp()};typeof window<"u"&&(window.addEventListener("pagehide",Xb),Xi.addEventListener("visibilitychange",Qb),he.push(()=>{window.removeEventListener("pagehide",Xb),Xi.removeEventListener("visibilitychange",Qb)}));let Yb="persona-attachment-drop-active",Qi=0,Tf=()=>{Qi=0,pe.classList.remove(Yb)},Ra=()=>n.attachments?.enabled===!0&&Ze!==null&&!Wr(),Jb=s=>{!Vu(s.dataTransfer)||!Ra()||(Qi++,Qi===1&&pe.classList.add(Yb))},Zb=s=>{!Vu(s.dataTransfer)||!Ra()||(Qi--,Qi<=0&&Tf())},ev=s=>{!Vu(s.dataTransfer)||!Ra()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},tv=s=>{if(!Vu(s.dataTransfer)||!Ra())return;s.preventDefault(),s.stopPropagation(),Tf();let l=Array.from(s.dataTransfer.files??[]);l.length!==0&&Ze.handleFiles(l)},Nr=!0;pe.addEventListener("dragenter",Jb,Nr),pe.addEventListener("dragleave",Zb,Nr),e.addEventListener("dragover",ev,Nr),e.addEventListener("drop",tv,Nr);let oc=e.ownerDocument,ov=s=>{Ra()&&s.preventDefault()},nv=s=>{Ra()&&s.preventDefault()};oc.addEventListener("dragover",ov),oc.addEventListener("drop",nv),he.push(()=>{nt?.destroy(),nt=null,Cf(),Pn?.destroy(),Pn=null,Qn?.destroy(),Qn=null,Tr?.destroy(),Tr=null,Er?.destroy(),Er=null,Mr=null,tp=null,bp(),Mi.destroy(),Pa&&clearTimeout(Pa),gs(),Is?.abort(),Is=null,Ze?.destroy(),Ze=null,Ce.destroy(),Xi.removeEventListener("keydown",Lb,!0),Ht?.destroy()}),he.push(()=>{pe.removeEventListener("dragenter",Jb,Nr),pe.removeEventListener("dragleave",Zb,Nr),e.removeEventListener("dragover",ev,Nr),e.removeEventListener("drop",tv,Nr),oc.removeEventListener("dragover",ov),oc.removeEventListener("drop",nv),Tf()}),he.push(()=>{R.cancel()}),Et?he.push(()=>{Et?.destroy()}):po&&he.push(()=>{po?.remove()});let Pt={update(s){let l=n.toolCall,f=n.messageActions,g=n.layout?.messages,v=n.colorScheme,M=n.loadingIndicator,_=n.iterationDisplay,K=n.features?.showReasoning,j=n.features?.showToolCalls,G=n.features?.toolCallDisplay,Z=n.features?.reasoningDisplay,ae=n.features?.streamAnimation?.type,me=n.features?.history?.enabled===!0,Je=n.features?.history?.provider,dt=n.getIdentityProof,ut=n.clientToken,Qt=n.contextMentions;n=Ou({...n,features:a},s),a=n.features,n=Fl(n),r(),pp(),$s(e,n),_l(e,n),Nl(e,n),Be(),pn(),n.colorScheme!==v&&sy();let Dt=Ul.getForInstance(n.plugins);i.length=0,i.push(...Dt),rb(),we=n.launcher?.enabled??!0,pt=n.launcher?.autoExpand??!1,Sn=n.features?.showReasoning??!0,zo=n.features?.showToolCalls??!0,wn=n.features?.scrollToBottom??{};let kt=Oo();Ko=n.features?.scrollBehavior??{},kt!==Oo()&&(mn(),To()),vy(),Ph(),Vt();let ao=so;if(so=n.features?.showEventStreamToggle??!1,so&&!ao){if(tt||(se(),R.setSSEEventCallback((ee,Ke)=>{n.onSSEEvent?.(ee,Ke),oe(ee,Ke)})),!ot&&Me){let ee=n.features?.eventStream?.classNames,Ke="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");ot=I("button",Ke),ot.style.width="28px",ot.style.height="28px",ot.style.color=bo.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let Qe=_t($a,"18px","currentColor",1.5);Qe&&ot.appendChild(Qe);let rt=Fe.clearChatButtonWrapper,xt=Fe.closeButtonWrapper,oo=rt||xt;oo&&oo.parentNode===Me?Me.insertBefore(ot,oo):Me.appendChild(ot),ot.addEventListener("click",()=>{S?sa():rp()})}}else!so&&ao&&(sa(),ot&&(ot.remove(),ot=null),tt?.clear(),Kn?.destroy(),tt=null,Kn=null,Ro?.reset(),Ro=null,ln=null);if(n.launcher?.enabled===!1&&Et&&(Et.destroy(),Et=null),n.launcher?.enabled===!1&&po&&(po.remove(),po=null),n.launcher?.enabled!==!1&&!Et&&!po){let{instance:ee,element:Ke}=$g({config:n,plugins:i,onToggle:Wb});Et=ee,ee||(po=Ke),e.appendChild(Ke)}Et&&Et.update(n),ji(),ns&&n.launcher?.subtitle!==void 0&&(ns.textContent=n.launcher.subtitle);let et=n.layout?.header;if(et?.layout!==Xe&&Me){let ee=et?ti(n,et,{showClose:Pe(),onClose:()=>ct(!1,"user")}):yr({config:n,showClose:Pe(),onClose:()=>ct(!1,"user")});Ho.replaceHeader(ee),Me=Ho.header.element,Tt=Ho.header.iconHolder,wr=Ho.header.headerTitle,ns=Ho.header.headerSubtitle,$e=Ho.header.closeButton,Xe=et?.layout,ji()}else if(et){if(Tt&&(Tt.style.display=et.showIcon===!1?"none":""),wr&&(wr.style.display=et.showTitle===!1?"none":""),ns&&(ns.style.display=et.showSubtitle===!1?"none":""),$e){let ee=Pe()&&et.showCloseButton!==!1;$e.style.display=ee?"":"none"}if(Fe.clearChatButtonWrapper){let ee=et.showClearChat;if(ee!==void 0){Fe.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ke}=Fe;Ke&&!Ke.classList.contains("persona-absolute")&&(ee?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let ur=n.layout?.showHeader!==!1;Me&&(Me.style.display=ur?"":"none");let Bn=n.layout?.showFooter!==!1;Le&&(Le.style.display=Bn?"":"none"),ss(),Vt(),we!==Ve?we?ct(pt,"auto"):(be=!0,Ii()):pt!==z&&ct(pt,"auto"),z=pt,Ve=we,Gi(),$b();let De=JSON.stringify(n.toolCall)!==JSON.stringify(l),Ne=JSON.stringify(n.messageActions)!==JSON.stringify(f),ge=JSON.stringify(n.layout?.messages)!==JSON.stringify(g),ft=n.loadingIndicator?.render!==M?.render||n.loadingIndicator?.renderIdle!==M?.renderIdle||n.loadingIndicator?.showBubble!==M?.showBubble,jt=n.iterationDisplay!==_,lo=(n.features?.showReasoning??!0)!==(K??!0)||(n.features?.showToolCalls??!0)!==(j??!0)||JSON.stringify(n.features?.toolCallDisplay)!==JSON.stringify(G)||JSON.stringify(n.features?.reasoningDisplay)!==JSON.stringify(Z);(De||Ne||ge||ft||jt||lo)&&R&&(hs++,Qo(Ee,R.getMessages(),It));let Lt=n.features?.streamAnimation?.type;if(Lt!==ae&&Lt&&Lt!=="none"){let ee=mp(Lt,n.features?.streamAnimation?.plugins);ee&&Hl(ee,e)}let Te=n.launcher??{},zt=Te.headerIconHidden??!1,Kt=n.layout?.header?.showIcon,on=zt||Kt===!1,We=Te.headerIconName,vt=Te.headerIconSize??"48px";if(Tt){let ee=Me,Ke=ee?.querySelector(".persona-flex-col");if(on)Tt.style.display="none",ee&&Ke&&!ee.contains(Ke)&&ee.insertBefore(Ke,ee.firstChild);else{if(Tt.style.display="",Tt.style.height=vt,Tt.style.width=vt,ee&&Ke&&(ee.contains(Tt)?Tt.nextSibling!==Ke&&(Tt.remove(),ee.insertBefore(Tt,Ke)):ee.insertBefore(Tt,Ke)),We){let rt=parseFloat(vt)||24,xt=ue(We,rt*.6,"currentColor",1);xt?Tt.replaceChildren(xt):Tt.textContent=Te.agentIconText??"\u{1F4AC}"}else if(Te.iconUrl){let rt=Tt.querySelector("img");if(rt)rt.src=Te.iconUrl,rt.style.height=vt,rt.style.width=vt;else{let xt=document.createElement("img");xt.src=Te.iconUrl,xt.alt="",xt.className="persona-rounded-xl persona-object-cover",xt.style.height=vt,xt.style.width=vt,Tt.replaceChildren(xt)}}else{let rt=Tt.querySelector("svg"),xt=Tt.querySelector("img");(rt||xt)&&Tt.replaceChildren(),Tt.textContent=Te.agentIconText??"\u{1F4AC}"}let Qe=Tt.querySelector("img");Qe&&(Qe.style.height=vt,Qe.style.width=vt)}}let Dn=n.layout?.header?.showTitle,gn=n.layout?.header?.showSubtitle;if(wr&&(wr.style.display=Dn===!1?"none":""),ns&&(ns.style.display=gn===!1?"none":""),$e){let ee=Pe()&&n.layout?.header?.showCloseButton!==!1;if($e.style.display=ee?"":"none",!Ie()){let Yt=Te.closeButtonSize??"";$e.style.height=Yt,$e.style.width=Yt,$e.style.minWidth=Yt,$e.style.minHeight=Yt}let Ke=Te.closeButtonPlacement??"inline",{closeButtonWrapper:Qe}=Fe,rt=Ke==="top-right",xt=Qe?.classList.contains("persona-absolute");if(Qe&&rt!==xt)if(Qe.remove(),rt){Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Yt=Di??pe;Yt.style.position="relative",Yt.appendChild(Qe)}else{let Yt=Te.clearChat?.placement??"inline",Jt=Te.clearChat?.enabled??!0;Qe.className=Jt&&Yt==="inline"?"":"persona-ml-auto",Me&&Me.appendChild(Qe)}if($e.style.color=Te.closeButtonColor||bo.actionIconColor,Te.closeButtonBackgroundColor?($e.style.backgroundColor=Te.closeButtonBackgroundColor,$e.classList.remove("hover:persona-bg-gray-100")):($e.style.backgroundColor="",$e.classList.add("hover:persona-bg-gray-100")),Te.closeButtonBorderWidth||Te.closeButtonBorderColor){let Yt=Te.closeButtonBorderWidth||"0px",Jt=Te.closeButtonBorderColor||"transparent";$e.style.border=`${Yt} solid ${Jt}`,$e.classList.remove("persona-border-none")}else $e.style.border="",$e.classList.add("persona-border-none");Te.closeButtonBorderRadius?($e.style.borderRadius=Te.closeButtonBorderRadius,$e.classList.remove("persona-rounded-full")):($e.style.borderRadius="",$e.classList.add("persona-rounded-full")),Te.closeButtonPaddingX?($e.style.paddingLeft=Te.closeButtonPaddingX,$e.style.paddingRight=Te.closeButtonPaddingX):($e.style.paddingLeft="",$e.style.paddingRight=""),Te.closeButtonPaddingY?($e.style.paddingTop=Te.closeButtonPaddingY,$e.style.paddingBottom=Te.closeButtonPaddingY):($e.style.paddingTop="",$e.style.paddingBottom=""),bu($e,Te.closeButtonIconName??"x",{iconSize:Ie()?Ng:void 0,iconText:Te.closeButtonIconText??"\xD7"});let oo=Te.closeButtonTooltipText??"Close chat",hn=Te.closeButtonShowTooltip??!0;$e.setAttribute("aria-label",oo),Qe&&eo({anchor:$e,trigger:Qe,text:()=>$e?.getAttribute("aria-label")??oo,enabled:hn})}let{clearChatButton:_e,clearChatButtonWrapper:ve}=Fe;if(_e){let ee=Te.clearChat??{},Ke=ee.enabled??!0,Qe=n.layout?.header?.showClearChat,rt=Qe!==void 0?Qe:Ke,xt=ee.placement??"inline";if(ve){ve.style.display=rt?"":"none";let{closeButtonWrapper:oo}=Fe;!Ie()&&oo&&!oo.classList.contains("persona-absolute")&&(rt?oo.classList.remove("persona-ml-auto"):oo.classList.add("persona-ml-auto"));let hn=xt==="top-right",Yt=ve.classList.contains("persona-absolute");if(!Ie()&&hn!==Yt&&rt){if(ve.remove(),hn){ve.className="persona-absolute persona-top-4 persona-z-50",ve.style.right="48px";let _n=Di??pe;_n.style.position="relative",_n.appendChild(ve)}else{ve.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ve.style.right="";let _n=Fe.closeButtonWrapper;Me&&_n&&_n.parentElement===Me?Me.insertBefore(ve,_n):Me&&Me.appendChild(ve)}let Jt=Fe.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(hn?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(rt){if(!Ie()){let Jt=ee.size??"";_e.style.height=Jt,_e.style.width=Jt,_e.style.minWidth=Jt,_e.style.minHeight=Jt}let oo=ee.iconColor??"";if(_e.style.color=oo||bo.actionIconColor,bu(_e,ee.iconName??"refresh-cw",{iconSize:Ie()?Fg:void 0}),ee.backgroundColor?(_e.style.backgroundColor=ee.backgroundColor,_e.classList.remove("hover:persona-bg-gray-100")):(_e.style.backgroundColor="",_e.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let Jt=ee.borderWidth||"0px",_n=ee.borderColor||"transparent";_e.style.border=`${Jt} solid ${_n}`,_e.classList.remove("persona-border-none")}else _e.style.border="",_e.classList.add("persona-border-none");ee.borderRadius?(_e.style.borderRadius=ee.borderRadius,_e.classList.remove("persona-rounded-full")):(_e.style.borderRadius="",_e.classList.add("persona-rounded-full")),ee.paddingX?(_e.style.paddingLeft=ee.paddingX,_e.style.paddingRight=ee.paddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),ee.paddingY?(_e.style.paddingTop=ee.paddingY,_e.style.paddingBottom=ee.paddingY):(_e.style.paddingTop="",_e.style.paddingBottom="");let hn=ee.tooltipText??"Clear chat",Yt=ee.showTooltip??!0;_e.setAttribute("aria-label",hn),ve&&eo({anchor:_e,trigger:ve,text:()=>_e?.getAttribute("aria-label")??hn,enabled:Yt})}}let Ue=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ql],mt=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Zs.message,Zs.messageAndClick];He=$l({parsers:Ue,handlers:mt,getSessionMetadata:fe,updateSessionMetadata:le,emit:C.emit,documentRef:typeof document<"u"?document:null}),It=Mw(n,He,ea),GA(),R.updateConfig(n),(n.features?.history?.enabled===!0!==me||n.features?.history?.provider!==Je||n.getIdentityProof!==dt||n.clientToken!==ut)&&(Po({restoreFocus:!1}),Qy()),Dr(),Fd(),Qo(Ee,R.getMessages(),It),ca(),Ad(),zA(),Ri(R.isStreaming()),Qt!==n.contextMentions&&Gb();let Fr=n.voiceRecognition?.enabled===!0,Gt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),qo=n.voiceRecognition?.provider?.type==="runtype";if(Fr&&(Gt||qo))if(!re||!Bo){let ee=Qa(n);if(ee){re=ee.button,Bo=ee.wrapper;let Ke=Mn&&Mn.parentElement===Kl?Mn:null;Kl?Kl.insertBefore(Bo,Ke):dn?.appendChild(Bo),nt&&(nt.micButton=re),nt?.addListener(re,"click",Af),re.disabled=R.isStreaming()}}else{let ee=n.voiceRecognition??{},Ke=n.sendButton??{},Qe=ee.iconName??"mic",rt=ee.iconSize,xt=parseFloat(rt??"")||ho;re.classList.add(Vo),re.classList.toggle(yn,!rt),re.style.width=rt??"",re.style.height=rt??"",re.style.minWidth=rt??"",re.style.minHeight=rt??"";let oo=ee.iconColor??Ke.textColor;re.innerHTML="";let hn=ue(Qe,xt,oo||"currentColor",1.5);hn?re.appendChild(hn):re.textContent="\u{1F3A4}";let Yt=ee.backgroundColor??Ke.backgroundColor;Yt?re.style.backgroundColor=Yt:re.style.backgroundColor="",oo?re.style.color=oo:re.style.color="var(--persona-text, #111827)",ee.borderWidth?(re.style.borderWidth=ee.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),ee.borderColor?re.style.borderColor=ee.borderColor:re.style.borderColor="",ee.paddingX?(re.style.paddingLeft=ee.paddingX,re.style.paddingRight=ee.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),ee.paddingY?(re.style.paddingTop=ee.paddingY,re.style.paddingBottom=ee.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Jt=ee.tooltipText??"Start voice recognition",_n=ee.showTooltip??!1;re.setAttribute("aria-label",Jt),Bo&&eo({anchor:re,trigger:Bo,text:()=>re?.getAttribute("aria-label")??Jt,enabled:_n}),Bo.style.display="",re.disabled=R.isStreaming()}else re&&Bo&&(Bo.style.display="none",n.voiceRecognition?.provider?.type==="runtype"?R.isVoiceActive()&&R.toggleVoice():Wn&&_r());if(n.attachments?.enabled===!0){if(!wo||!St){let ee=n.attachments??{};Ao||(Ao=I("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ao.style.display="none",(ce.parentElement??dn).insertBefore(Ao,ce)),ht||(ht=document.createElement("input"),ht.type="file",ht.accept=(ee.allowedTypes??hr).join(","),ht.multiple=(ee.maxFiles??4)>1,ht.style.display="none",ht.setAttribute("aria-label","Attach files"),(ce.parentElement??dn).insertBefore(ht,ce)),wo=I("div","persona-send-button-wrapper"),St=I("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Vo} ${yn}`),St.type="button",St.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Ke=ee.buttonIconName??"paperclip";St.style.fontSize="18px",St.style.lineHeight="1";let Qe=ue(Ke,ho,"currentColor",1.5);Qe?St.appendChild(Qe):St.textContent="\u{1F4CE}",St.addEventListener("click",xt=>{xt.preventDefault(),ht?.click()}),wo.appendChild(St);let rt=ee.buttonTooltipText??"Attach file";eo({anchor:St,trigger:wo,text:()=>St?.getAttribute("aria-label")??rt}),Xu?Xu.append(wo):dn.appendChild(wo),nt&&(nt.attachmentButton=St,nt.attachmentInput=ht??void 0,nt.attachmentPreviews=Ao??void 0),!Ze&&ht&&Ao&&(Ze=qs.fromConfig(ee,kh),Ze.setPreviewsContainer(Ao),nt?.addListener(ht,"change",async()=>{Ze&&ht?.files&&(await Ze.handleFileSelect(ht.files),ht.value="")}))}else{wo.style.display="";let ee=n.attachments??{};ht&&(ht.accept=(ee.allowedTypes??hr).join(","),ht.multiple=(ee.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles,adapter:ee.adapter})}if(pe.querySelector(".persona-attachment-drop-overlay")?.remove(),pe.appendChild(Tw(n.attachments?.dropOverlay)),St){let ee=n.attachments??{},Ke=ee.buttonTooltipText??"Attach file";St.setAttribute("aria-label",Ke),St.textContent="";let Qe=ue(ee.buttonIconName??"paperclip",ho,"currentColor",1.5);Qe?St.appendChild(Qe):St.textContent="\u{1F4CE}",wo&&eo({anchor:St,trigger:wo,text:()=>St?.getAttribute("aria-label")??Ke})}}else wo&&(wo.style.display="none"),Ze&&Ze.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let wt=n.sendButton??{},Ef=wt.useIcon??!1,Bs=wt.iconText??"\u2191",nc=wt.iconName,sv=wt.tooltipText??"Send message",dT=wt.showTooltip??!1,Yi=wt.size,cT=parseFloat(Yi??"")||Qm,rc=wt.backgroundColor,Ji=wt.textColor;if(Ef){if(Ae.style.width=Yi??"",Ae.style.height=Yi??"",Ae.style.minWidth=Yi??"",Ae.style.minHeight=Yi??"",Ae.style.fontSize="18px",Ae.style.lineHeight="1",Ji?Ae.style.color=Ji:Ae.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(Ae.innerHTML="",nc){let ee=parseFloat(wt.iconSize??"")||Math.round(cT*.5),Ke=Ji?.trim()||"currentColor",Qe=wt.iconStrokeWidth??2,rt=ue(nc,ee,Ke,Qe),xt=ue(wt.stopIconName??"square",ee,Ke,Qe);rt&&xt?Ae.appendChild(Ym(rt,xt)):rt?Ae.appendChild(rt):Ae.textContent=Bs}else Ae.textContent=Bs;Ae.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Vo}`,rc?(Ae.style.backgroundColor=rc,Ae.classList.remove("persona-bg-persona-primary")):(Ae.style.backgroundColor="",Ae.classList.add("persona-bg-persona-primary"))}else Ae.textContent=n.copy?.sendButtonLabel??"Send",Ae.style.width="",Ae.style.height="",Ae.style.minWidth="",Ae.style.minHeight="",Ae.style.fontSize="",Ae.style.lineHeight="",Ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",rc?(Ae.style.backgroundColor=rc,Ae.classList.remove("persona-bg-persona-accent")):Ae.classList.add("persona-bg-persona-accent"),Ji?Ae.style.color=Ji:Ae.classList.add("persona-text-white");wt.borderWidth?(Ae.style.borderWidth=wt.borderWidth,Ae.style.borderStyle="solid"):(Ae.style.borderWidth="",Ae.style.borderStyle=""),wt.borderColor?Ae.style.borderColor=wt.borderColor:Ae.style.borderColor="",wt.paddingX?(Ae.style.paddingLeft=wt.paddingX,Ae.style.paddingRight=wt.paddingX):(Ae.style.paddingLeft="",Ae.style.paddingRight=""),wt.paddingY?(Ae.style.paddingTop=wt.paddingY,Ae.style.paddingBottom=wt.paddingY):(Ae.style.paddingTop="",Ae.style.paddingBottom=""),R.isStreaming()||Ae.setAttribute("aria-label",sv),Sd(),Mn&&eo({anchor:Ae,trigger:Mn,text:()=>Ae.getAttribute("aria-label")??sv,enabled:dT}),Vh();let av=ru(Ce.getState().activeModeIds,n.composer?.modes);Ce.setActiveModeIds(av),oa().length>0!==!!Qn&&ap(),Qn?.render(av,oa());for(let ee of[...na.keys()])nu(ee,n.composer?.modeGroups)||na.delete(ee);na.forEach(ee=>ee.repaint()),Mr?.repaint(),Pn?.resolve();let sc=Jr(n,Ie());if(fp(),sc){Ee.style.maxWidth=sc,Ee.style.marginLeft="auto",Ee.style.marginRight="auto",Ee.style.width="100%",Wo.style.maxWidth=sc,Wo.style.marginLeft="auto",Wo.style.marginRight="auto",Wo.style.width="100%";for(let ee of[dn,Sr,Ao,at])ee&&(ee.style.maxWidth=sc,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%")}else{Ee.style.maxWidth="",Ee.style.marginLeft="",Ee.style.marginRight="",Ee.style.width="",Wo.style.maxWidth="",Wo.style.marginLeft="",Wo.style.marginRight="",Wo.style.width="";for(let ee of[dn,Sr,Ao,at])ee&&(ee.style.maxWidth="",ee.style.marginLeft="",ee.style.marginRight="",ee.style.width="")}let Ur=n.statusIndicator??{},uT=Ur.visible??!0;if(at.style.display=uT?"":"none",R){let ee=R.getStatus();zl(at,(Qe=>Qe==="idle"?Ur.idleText??Nt.idle:Qe==="connecting"?Ur.connectingText??Nt.connecting:Qe==="connected"?Ur.connectedText??Nt.connected:Qe==="error"?Ur.errorText??Nt.error:Nt[Qe])(ee),Ur,ee)}at.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pT=Ur.align==="left"?"persona-text-left":Ur.align==="center"?"persona-text-center":"persona-text-right";at.classList.add(pT),sp(),Tp(),cn(),Ft()},open(){Pe()&&ct(!0,"api")},close(){Pe()&&ct(!1,"api")},toggle(){Pe()&&ct(!be,"api")},reconnect(){R.reconnectNow()},clearChat(){Yn=!1,R.clearMessages(),Bt.clear(),To();try{localStorage.removeItem(ui),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ui}`)}catch(l){console.error("[AgentWidget] Failed to clear default localStorage:",l)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ui)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(l){console.error("[AgentWidget] Failed to clear custom localStorage:",l)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),U?.clear&&md(()=>U.clear(),"[AgentWidget] Failed to clear storage adapter:"),$={},He.syncFromMetadata(),Ze?.clearAttachments(),hd(),ra(void 0),En(void 0),gs(),tt?.clear(),Ro?.reset(),J?.update()},setMessage(s){return!ce||R.isStreaming()||Wr()?!1:(!be&&Pe()&&ct(!0,"system"),ce.value=s,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(R.isStreaming()||Ss())return!1;let l=s?.trim()||ce.value.trim();return l?(!be&&Pe()&&ct(!0,"system"),ce.value="",ce.style.height="auto",Tn(),Yd(l,{consumeDraft:!1}),!0):!1},getComposerState(){return Ce.getState()},setQuote(s){let l=s?.text?.trim();l&&En({...s,text:l})},clearQuote(){En(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:n.voiceRecognition?.provider?.type==="runtype"?(R.isVoiceActive()||(!be&&Pe()&&ct(!0,"system"),ze.manuallyDeactivated=!1,fn(),R.toggleVoice().then(()=>{ze.active=R.isVoiceActive(),tr("user"),R.isVoiceActive()&&Ia()})),!0):Wn?!0:Hb()?(!be&&Pe()&&ct(!0,"system"),ze.manuallyDeactivated=!1,fn(),Zd("user"),!0):!1},stopVoiceRecognition(){return n.voiceRecognition?.provider?.type==="runtype"?R.isVoiceActive()?(R.toggleVoice().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,fn(),tr("user"),cr()}),!0):!1:Wn?(ze.manuallyDeactivated=!0,fn(),_r("user"),!0):!1},injectMessage(s){return!be&&Pe()&&ct(!0,"system"),R.injectMessage(s)},injectAssistantMessage(s){!be&&Pe()&&ct(!0,"system");let l=R.injectAssistantMessage(s);return xn&&(xn=!1,Cn&&(clearTimeout(Cn),Cn=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),l},injectUserMessage(s){return!be&&Pe()&&ct(!0,"system"),R.injectUserMessage(s)},injectSystemMessage(s){return!be&&Pe()&&ct(!0,"system"),R.injectSystemMessage(s)},injectMessageBatch(s){return!be&&Pe()&&ct(!0,"system"),R.injectMessageBatch(s)},injectComponentDirective(s){return!be&&Pe()&&ct(!0,"system"),R.injectComponentDirective(s)},injectTestMessage(s){!be&&Pe()&&ct(!0,"system"),R.injectTestEvent(s)},async connectStream(s,l){return R.connectStream(s,l)},__pushEventStreamEvent(s){so&&(se(),oe(s.type,s.payload))},showEventStream(){so&&rp()},hideEventStream(){S&&sa()},isEventStreamVisible(){return S},listConversations(s){return R.listConversations(s)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(s,l){return df(s,{focusComposer:l?.focus===!0})},startNewConversation(s){return cf({focusComposer:s?.focus===!0})},deleteConversation(s){return Sb(s)},renameConversation(s,l){return uf(s,{title:l})},setConversationStarred(s,l){return uf(s,{starred:l})},clearConversationHistory(s){return wb(s)},resetHistoryIdentity(){return Ab()},getHistoryIdentityStatus(){return Fo?Fo.getIdentityStatus():jp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return Vi({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){Po(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return ie},showArtifacts(){xo(n)&&(Yn=!1,ia=!0,pn(),je?.setMobileOpen(!0))},hideArtifacts(){xo(n)&&(Yn=!0,pn())},upsertArtifact(s){return xo(n)?(Fn(n.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(Yn=!1,ia=!0),R.upsertArtifact(s)):null},selectArtifact(s){xo(n)&&R.selectArtifact(s)},clearArtifacts(){xo(n)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return we&&!be&&!Ie()||!ce?!1:(ce.focus(),!0)},async resolveApproval(s,l,f){let v=R.getMessages().find(M=>M.variant==="approval"&&M.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){R.resolveWebMcpApproval(v.id,l);return}return R.resolveApproval(v.approval,l,f)},setFollowUpSuggestions(s){yA(s)},clearFollowUpSuggestions(){by()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...$}},updatePersistentMetadata(s){le(s)},on(s,l){return C.on(s,l)},off(s,l){C.off(s,l)},isOpen(){return Pe()&&be},isVoiceActive(){return ze.active},toggleReadAloud(s){R.toggleReadAloud(s)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(s){return R.getReadAloudState(s)},onReadAloudChange(s){return R.onReadAloudChange(s)},getState(){return{open:Pe()&&be,launcherEnabled:we,voiceActive:ze.active,streaming:R.isStreaming()}},showCSATFeedback(s){!be&&Pe()&&ct(!0,"system");let l=Ee.querySelector(".persona-feedback-container");l&&l.remove();let f=qu({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Ee.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!be&&Pe()&&ct(!0,"system");let l=Ee.querySelector(".persona-feedback-container");l&&l.remove();let f=$u({onSubmit:async(g,v)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(g,v),s?.onSubmit?.(g,v)},onDismiss:s?.onDismiss,...s});Ee.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,l){return R.submitCSATFeedback(s,l)},async submitNPSFeedback(s,l){return R.submitNPSFeedback(s,l)},destroy(){_p(),Ms!=null&&(clearInterval(Ms),Ms=null),he.forEach(s=>s()),Ge.remove(),Xt?.remove(),Et?.destroy(),po?.remove(),us&&$e.removeEventListener("click",us)}};if(((o?.debugTools??!1)||!!n.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,l={controller:Pt,getMessages:Pt.getMessages,getStatus:Pt.getStatus,getMetadata:Pt.getPersistentMetadata,updateMetadata:Pt.updatePersistentMetadata,clearHistory:()=>Pt.clearChat(),setVoiceActive:f=>f?Pt.startVoiceRecognition():Pt.stopVoiceRecognition()};window.AgentWidgetBrowser=l,he.push(()=>{window.AgentWidgetBrowser===l&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),l=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Pt.focusInput()};if(window.addEventListener("persona:focusInput",l),he.push(()=>{window.removeEventListener("persona:focusInput",l)}),so){let G=ae=>{let me=ae.detail;(!me?.instanceId||me.instanceId===s)&&Pt.showEventStream()},Z=ae=>{let me=ae.detail;(!me?.instanceId||me.instanceId===s)&&Pt.hideEventStream()};window.addEventListener("persona:showEventStream",G),window.addEventListener("persona:hideEventStream",Z),he.push(()=>{window.removeEventListener("persona:showEventStream",G),window.removeEventListener("persona:hideEventStream",Z)})}let f=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Pt.showHistory()},g=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Pt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",g),he.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",g)});let v=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Pt.showArtifacts()},M=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Pt.hideArtifacts()},_=G=>{let Z=G.detail;Z?.instanceId&&Z.instanceId!==s||Z?.artifact&&Pt.upsertArtifact(Z.artifact)},K=G=>{let Z=G.detail;Z?.instanceId&&Z.instanceId!==s||typeof Z?.id=="string"&&Pt.selectArtifact(Z.id)},j=G=>{let Z=G.detail;(!Z?.instanceId||Z.instanceId===s)&&Pt.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",M),window.addEventListener("persona:upsertArtifact",_),window.addEventListener("persona:selectArtifact",K),window.addEventListener("persona:clearArtifacts",j),he.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",M),window.removeEventListener("persona:upsertArtifact",_),window.removeEventListener("persona:selectArtifact",K),window.removeEventListener("persona:clearArtifacts",j)})}let tn=QL(n.persistState);if(tn&&Pe()){let s=YL(tn.storage),l=`${tn.keyPrefix}widget-open`,f=`${tn.keyPrefix}widget-voice`,g=`${tn.keyPrefix}widget-voice-mode`;if(s){let v=tn.persist?.openState&&s.getItem(l)==="true",M=tn.persist?.voiceState&&s.getItem(f)==="true",_=tn.persist?.voiceState&&s.getItem(g)==="true";if(v&&(Et?.setPanelOpen(!0,"auto"),setTimeout(()=>{Pt.open(),setTimeout(()=>{if(M||_)Pt.startVoiceRecognition();else if(tn.persist?.focusInput){let K=e.querySelector("textarea");K&&K.focus()}},100)},0)),tn.persist?.openState&&(C.on("widget:opened",()=>{s.setItem(l,"true")}),C.on("widget:closed",()=>{s.setItem(l,"false")})),tn.persist?.voiceState&&(C.on("voice:state",K=>{s.setItem(f,K.active?"true":"false")}),C.on("user:message",K=>{s.setItem(g,K.viaVoice?"true":"false")})),tn.clearOnChatClear){let K=()=>{s.removeItem(l),s.removeItem(f),s.removeItem(g)},j=()=>K();window.addEventListener("persona:clear-chat",j),he.push(()=>{window.removeEventListener("persona:clear-chat",j)})}}}if(te&&Pe()&&(Et?.setPanelOpen(!0,"auto"),setTimeout(()=>{Pt.open()},0)),ya(),!bA){let s=Ha(()=>{R&&(hs++,Bt.clear(),Qo(Ee,R.getMessages(),It))});he.push(s)}T=()=>{R&&(hs++,Bt.clear(),Qo(Ee,R.getMessages(),It))},R.getMessages().length>0&&Cd(),b=()=>{R&&(hs++,Bt.clear(),Qo(Ee,R.getMessages(),It))};let iT=Wx(()=>{R&&(hs++,Bt.clear(),Qo(Ee,R.getMessages(),It))});he.push(iT);let lT=Yg(()=>{R&&(hs++,Bt.clear(),Qo(Ee,R.getMessages(),It),br()?.updateInlineArtifactBlocks(Ee,Xo.artifacts,{suppressTransition:!0}),pn())});return he.push(lT),Pt};var Ew=(e,t)=>{let o=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(o);if(n)return Math.max(0,parseFloat(n[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(o);return r?Math.max(0,t*parseFloat(r[1])/100):420},e0=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},t0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},o0=(e,t)=>{let o=e.parentElement;if(!o)return;let n=e.ownerDocument.createElement("div");n.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",o.appendChild(n);let r=n.offsetHeight>0;n.style.height="100%";let a=n.offsetHeight>0;n.remove(),!(!r||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Pw=(e,t)=>{let o=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=o?"":"100%",e.style.display=o?"":"flex",e.style.flexDirection=o?"":"column",e.style.flex=o?"":"1 1 auto",e.style.minHeight=o?"":"0",e.style.minWidth=o?"":"0"},mh=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=""},kw=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",mh(e)},uh=e=>{e.style.transition=""},ph=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=""},fh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},zu=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},n0=(e,t,o,n,r)=>{r?o.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(o,n),e.appendChild(t)):o.parentElement===t&&(t.replaceChildren(),e.appendChild(o),e.appendChild(n))},r0=(e,t,o,n,r,a)=>{let i=a?t:e;r==="left"?i.firstElementChild!==n&&i.replaceChildren(n,o):i.lastElementChild!==n&&i.replaceChildren(o,n)},s0=e=>{let t=Yr(e),o=t.components?.panel,n=(r,a)=>r==null||r===""?a:yo(t,r)??r;return{inset:n(o?.inset,su),canvasBackground:n(o?.canvasBackground,au)}},Lw=(e,t,o,n)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=o,e.style.background=n},a0=(e,t,o,n,r,a,i,d)=>{let c=Io(a),u=c.reveal==="push",p=d!=null,m=d?.inset??"",h=d?.canvasBackground??"";n0(e,t,o,n,u),r0(e,t,o,n,c.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",o.style.display="flex",o.style.flexDirection="column",o.style.minHeight="0",o.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let y=e.ownerDocument.defaultView,x=a?.launcher?.mobileFullscreen??!0,T=a?.launcher?.mobileBreakpoint??640,w=y!=null?y.innerWidth<=T:!1;if(x&&w&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ph(t),uh(n),kw(n),fh(o),zu(r,n),Lw(n,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",o.style.flex="1 1 auto",o.style.width="100%",o.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String(a?.launcher?.zIndex??ro),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",o.style.flex="1 1 auto",o.style.width="100%",o.style.maxWidth="100%",o.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),kw(n),e0(n,c.maxHeight),Lw(n,p&&i,m,h),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ph(t),uh(n),fh(o),zu(r,n);let P=c.animate?"transform 180ms ease":"none",H=c.side==="right"?"translateX(100%)":"translateX(-100%)",b=i?"translateX(0)":H;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=c.width,n.style.maxWidth=c.width,n.style.minWidth=c.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=P,n.style.transform=b,n.style.pointerEvents=i?"auto":"none",n.style.zIndex="2",c.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(c.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",uh(n),mh(n),zu(r,n);let P=Ew(c.width,e.clientWidth),H=Math.max(0,e.clientWidth),b=c.animate?"margin-left 180ms ease":"none",A=c.side==="right"?i?-P:0:i?0:-P;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=`${H+P}px`,t.style.transition=b,t.style.marginLeft=`${A}px`,t.style.transform="",o.style.flex="0 0 auto",o.style.flexGrow="0",o.style.flexShrink="0",o.style.width=`${H}px`,o.style.maxWidth=`${H}px`,o.style.minWidth=`${H}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=c.width,n.style.minWidth=c.width,n.style.maxWidth=c.width,n.style.position="relative",n.style.top="",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ph(t),mh(n),fh(o),zu(r,n);let P=c.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let H=i?c.width:"0px",b=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",A=!i;if(n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${H}`,n.style.width=H,n.style.maxWidth=H,n.style.minWidth=H,n.style.minHeight="0",t0(n,c.maxHeight),n.style.overflow=P||A?"hidden":"visible",n.style.transition=b,P){n.style.alignItems=c.side==="right"?"flex-start":"flex-end";let C=p?`calc(${Ew(c.width,e.clientWidth)}px - (2 * ${m}))`:c.width;r.style.width=C,r.style.minWidth=C,r.style.maxWidth=C,r.style.boxSizing="border-box"}}},i0=(e,t)=>{let o=e.ownerDocument.createElement("div");return Pw(o,t),e.appendChild(o),{mode:"direct",host:o,shell:null,syncWidgetState:()=>{},updateConfig(n){Pw(o,n)},destroy(){o.remove()}}},l0=(e,t)=>{let{ownerDocument:o}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,i=o.createElement("div"),d=o.createElement("div"),c=o.createElement("div"),u=o.createElement("aside"),p=o.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;d.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),n.insertBefore(i,e),c.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},x=null,T=()=>{x=t?.launcher?.detachedPanel===!0?s0(t):null};T();let w=()=>{a0(i,d,c,u,p,t,m,x)},k=null,P=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Ya(()=>{T(),w()}))},H=()=>{y(),Io(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{w()}),h.observe(i)))},b=!1,A=()=>{w(),H(),m&&!b&&i.dataset.personaDockMobileFullscreen!=="true"&&(b=!0,o0(i,Io(t)))},C=i.ownerDocument.defaultView,L=()=>{A()};return C?.addEventListener("resize",L),Io(t).reveal==="push"?(d.appendChild(c),d.appendChild(u),i.appendChild(d)):(i.appendChild(c),i.appendChild(u)),A(),P(),{mode:"docked",host:p,shell:i,syncWidgetState(U){let Q=U.launcherEnabled?U.open:!0;m!==Q&&(m=Q,A())},updateConfig(U){t=U,(t?.launcher?.enabled??!0)===!1&&(m=!0),T(),A(),P()},destroy(){C?.removeEventListener("resize",L),k?.(),k=null,y(),n.isConnected&&(a&&a.parentNode===n?n.insertBefore(e,a):n.appendChild(e)),i.remove()}}},jl=(e,t)=>Ct(t)?l0(e,t):i0(e,t);var d0=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Iw=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let n=o.cloneNode(!0);e.insertBefore(n,e.firstChild)},Rw=e=>{let t=d0(e.target),o=e.useShadowDom===!0,n=t.ownerDocument,r=e.config,a=jl(t,r),i,d=[],c=(w,k)=>{let H=!(k?.launcher?.enabled??!0)||Ct(k),b=n.createElement("div");if(b.setAttribute("data-persona-root","true"),H&&(b.style.height="100%",b.style.display="flex",b.style.flexDirection="column",b.style.flex="1",b.style.minHeight="0",b.style.minWidth="0"),o){let A=w.attachShadow({mode:"open"});A.appendChild(b),Iw(A,n)}else w.appendChild(b),Iw(w,n);return t.id&&b.setAttribute("data-persona-instance",t.id),b},u=()=>{a.syncWidgetState(i.getState())},p=()=>{d.forEach(w=>w()),d=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},m=()=>{let w=c(a.host,r);i=ju(w,r,{debugTools:e.debugTools}),p()},h=()=>{d.forEach(w=>w()),d=[],i.destroy()};m(),e.onChatReady?.();let y=w=>{h(),a.destroy(),a=jl(t,w),r=w,m()},x={update(w){let k=Ou(r??{},w),P=Ct(r),H=Ct(k),b=es(r),A=es(k);if(P!==H||b!==A){y(k);return}r=k,a.updateConfig(r),i.update(w),u()},destroy(){h(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},T=new Proxy(x,{get(w,k,P){if(k==="host")return a.host;if(k in w)return Reflect.get(w,k,P);let H=i[k];return typeof H=="function"?H.bind(i):H}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=T),T};var Dw=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),c0=new Set(["button","a","input","select","textarea","details","summary"]),u0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),gh=/\b(product|card|item|listing|result)\b/i,yh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,p0=3e3,f0=100;function _w(e){let t=typeof e.className=="string"?e.className:"";if(gh.test(t)||e.id&&gh.test(e.id))return!0;for(let o=0;o<e.attributes.length;o++){let n=e.attributes[o];if(n.name.startsWith("data-")&&gh.test(n.value))return!0}return!1}function Nw(e){return yh.test((e.textContent??"").trim())}function Fw(e){let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=t[o].getAttribute("href")??"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function m0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Hw(e){let t=e.match(yh);return t?t[0]:null}function Ww(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let n=t.getAttribute("href");return{title:t.textContent.trim(),href:n&&n!=="#"?n:null}}let o=e.querySelector("h1, h2, h3, h4, h5, h6");return o?.textContent?.trim()?{title:o.textContent.trim(),href:null}:{title:"",href:null}}function g0(e){let t=[],o=n=>{let r=n.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(n=>o(n.textContent??"")),e.querySelectorAll('[role="button"]').forEach(n=>o(n.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{o(n.value??"")}),t.slice(0,6)}var h0="commerce-card",y0="result-card";function Bw(e){return!_w(e)||!Nw(e)||!Fw(e)&&!m0(e)?0:5200}function Ow(e){return!_w(e)||Nw(e)||!Fw(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var bh=[{id:h0,scoreElement(e){return Bw(e)},shouldSuppressDescendant(e,t,o){if(t===e||!e.contains(t))return!1;if(o.interactivity==="static"){let n=o.text.trim();return!!(n.length===0||yh.test(n)&&n.length<32)}return!0},formatSummary(e,t){if(Bw(e)===0)return null;let{title:o,href:n}=Ww(e),r=Hw((e.textContent??"").trim())??Hw(t.text)??"",a=g0(e);return[n&&o?`[${o}](${n})${r?`: ${r}`:""}`:o?`${o}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
139
+ `)}},{id:y0,scoreElement(e){return Ow(e)},formatSummary(e,t){if(Ow(e)===0)return null;let{title:o,href:n}=Ww(e);return[n&&o?`[${o}](${n})`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
140
+ `)}}];function b0(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function v0(e){let t=e.options??{},o=t.maxElements??e.maxElements??80,n=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,d=t.mode??"structured",c=t.maxCandidates??Math.max(500,o*10),u=e.rules??bh;return d==="simple"&&e.rules&&e.rules.length>0?(b0(),u=[]):d==="simple"&&(u=[]),{mode:d,maxElements:o,maxCandidates:c,excludeSelector:n,maxTextLength:r,visibleOnly:a,root:i,rules:u}}function hh(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var x0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function C0(e){let t=e.tagName.toLowerCase(),o=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||o==="textbox"||o==="combobox"||o==="listbox"||o==="spinbutton"?"input":t==="button"||o==="button"||c0.has(t)||o&&u0.has(o)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Uw(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function S0(e){let t={},o=e.id;o&&(t.id=o);let n=e.getAttribute("href");n&&(t.href=n);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let i=e.getAttribute("value");i&&(t.value=i);let d=e.getAttribute("name");d&&(t.name=d);let c=e.getAttribute("role");c&&(t.role=c);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function vh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${hh(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of x0){let a=e.getAttribute(r);if(a){let i=`${t}[${r}="${hh(a)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let o=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(o.length>0){let r=`${t}.${o.map(i=>hh(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let d=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(d>=0){let c=`${r}:nth-of-type(${d+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let n=e.parentElement;if(n){let a=Array.from(n.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function w0(e){return e==="static"?f0:p0}function qw(e,t){let o=e.tagName.toLowerCase(),n=(e.textContent??"").trim().substring(0,t);return{selector:vh(e),tagName:o,text:n,role:e.getAttribute("role"),interactivity:C0(e),attributes:S0(e)}}function A0(e,t,o,n){let r=w0(t.interactivity),a=null;for(let i of o){let d=i.scoreElement(e,t,n);d>0&&(r+=d,i.formatSummary&&!a&&(a=i))}return{score:r,formattingRule:a}}function M0(e,t){for(let o of e)if(t.el!==o.el&&o.formattingRule?.shouldSuppressDescendant&&o.el.contains(t.el)&&o.formattingRule.shouldSuppressDescendant(o.el,t.el,t.enriched))return!0;return!1}function T0(e,t){let o={doc:t.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,r=[],a=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),d=i.currentNode;for(;d&&r.length<e.maxCandidates;){if(d.nodeType===Node.ELEMENT_NODE){let u=d,p=u.tagName.toLowerCase();if(Dw.has(p)){d=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){d=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Uw(u)){d=i.nextNode();continue}let m=qw(u,e.maxTextLength),h=m.text.length>0,y=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(w=>w==="role");if(!h&&!y){d=i.nextNode();continue}if(n.has(m.selector)){d=i.nextNode();continue}n.add(m.selector);let{score:x,formattingRule:T}=A0(u,m,e.rules,o);r.push({el:u,domIndex:a,enriched:m,score:x,formattingRule:T}),a+=1}d=i.nextNode()}r.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let c=[];for(let u of r){if(c.length>=e.maxElements)break;M0(c,u)||c.push(u)}return c.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:m===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),c.map(u=>{let p;if(u.formattingRule?.formatSummary){let h=u.formattingRule.formatSummary(u.el,u.enriched,o);h&&(p=h)}let m={...u.enriched};return p&&(m.formattedSummary=p),m})}function E0(e,t){let o=[],n=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&o.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let c=a,u=c.tagName.toLowerCase();if(Dw.has(u)){a=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Uw(c)){a=r.nextNode();continue}let p=qw(c,e.maxTextLength),m=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(y=>y==="role");if(!m&&!h){a=r.nextNode();continue}n.has(p.selector)||(n.add(p.selector),o.push(p))}a=r.nextNode()}let i=[],d=[];for(let c of o)c.interactivity!=="static"?i.push(c):d.push(c);return[...i,...d].slice(0,e.maxElements)}function $w(e={}){let t=v0(e),o=t.root??document.body;return o?t.mode==="simple"?E0(t,o):T0(t,o):[]}var Ku=100;function Vw(e,t={}){if(e.length===0)return"No page elements found.";let o=t.mode??"structured",n=[];if(o==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
141
141
  ${a.map(i=>`- ${i.split(`
142
142
  `).join(`
143
143
  `)}`).join(`
144
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)o==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,zu)}" (clickable)`);n.push(`Interactive elements:
144
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)o==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Ku)}" (clickable)`);n.push(`Interactive elements:
145
145
  ${a.join(`
146
- `)}`)}if(r.navigable.length>0){let a=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,zu)}" (navigable)`);n.push(`Navigation links:
146
+ `)}`)}if(r.navigable.length>0){let a=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Ku)}" (navigable)`);n.push(`Navigation links:
147
147
  ${a.join(`
148
- `)}`)}if(r.input.length>0){let a=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,zu)}" (input)`);n.push(`Form inputs:
148
+ `)}`)}if(r.input.length>0){let a=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Ku)}" (input)`);n.push(`Form inputs:
149
149
  ${a.join(`
150
- `)}`)}if(r.static.length>0){let a=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,zu)}"`);n.push(`Content:
150
+ `)}`)}if(r.static.length>0){let a=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Ku)}"`);n.push(`Content:
151
151
  ${a.join(`
152
152
  `)}`)}return n.join(`
153
153
 
154
- `)}var T0={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"}}},Vw={components:{panel:{borderRadius:"0",shadow:"none"}}},vh={id:"shop",label:"Shopping Assistant",config:{theme:T0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:zo},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},xh={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Vw}},Ch={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Vw}},Sh={shop:vh,minimal:xh,fullscreen:Ch};function jw(e){return Sh[e]}var He=typeof document<"u"?document.currentScript?.src??null:null;Av(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});lv(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Ex(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});HC(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});WC(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});fw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});dS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"animations-extra.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the animations-extra.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin.`)):import(e)});$S(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"approval-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the approval-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host approval-ui.js alongside it.`)):import(e)});Mx(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"voice-runtime.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the voice-runtime.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host voice-runtime.js alongside it.`)):import(e)});GS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"artifacts-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the artifacts-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host artifacts-ui.js alongside it.`)):import(e)});rw(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"forms-ui.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the forms-ui.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host forms-ui.js alongside it.`)):import(e)});Ix(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"icons-extra.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the icons-extra.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host icons-extra.js alongside it, or register the icons they use via registerIcons().`)):import(e)});Ev(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"webmcp-runtime.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the webmcp-runtime.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host webmcp-runtime.js alongside it.`)):import(e)});Px(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"session-reconnect.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the session-reconnect.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host session-reconnect.js alongside it.`)):import(e)});zS(()=>{let e=He?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===He?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${He??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return yT(E0);})();
154
+ `)}var P0={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"}}},jw={components:{panel:{borderRadius:"0",shadow:"none"}}},xh={id:"shop",label:"Shopping Assistant",config:{theme:P0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:$o},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Ch={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:jw}},Sh={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:jw}},wh={shop:xh,minimal:Ch,fullscreen:Sh};function zw(e){return wh[e]}var Oe=typeof document<"u"?document.currentScript?.src??null:null;Mv(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});dv(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Px(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});WC(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});BC(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});mw(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"history-view.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the history-view.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host history-view.js alongside it.`)):import(e)});cS(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"animations-extra.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the animations-extra.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host animations-extra.js alongside it, or register the animation plugins themselves via registerStreamAnimationPlugin.`)):import(e)});VS(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"approval-ui.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the approval-ui.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host approval-ui.js alongside it.`)):import(e)});Tx(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"voice-runtime.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the voice-runtime.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host voice-runtime.js alongside it.`)):import(e)});XS(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"artifacts-ui.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the artifacts-ui.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host artifacts-ui.js alongside it.`)):import(e)});sw(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"forms-ui.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the forms-ui.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host forms-ui.js alongside it.`)):import(e)});Rx(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"icons-extra.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the icons-extra.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host icons-extra.js alongside it, or register the icons they use via registerIcons().`)):import(e)});Pv(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"webmcp-runtime.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the webmcp-runtime.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host webmcp-runtime.js alongside it.`)):import(e)});kx(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"session-reconnect.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the session-reconnect.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host session-reconnect.js alongside it.`)):import(e)});KS(()=>{let e=Oe?.replace(/index\.global\.js($|\?)/,"event-stream-view.js$1");return!e||e===Oe?Promise.reject(new Error(`Could not derive the event-stream-view.js URL from the widget script URL (${Oe??"unavailable"}). Self-hosted deployments that rename index.global.js should host event-stream-view.js alongside it.`)):import(e)});return vT(k0);})();
155
155
  /*! Bundled license information:
156
156
 
157
157
  lucide/dist/esm/icons/activity.mjs: