@runtypelabs/persona 4.22.1 → 4.23.0

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,4 +1,4 @@
1
- "use strict";var S0=Object.create;var Gd=Object.defineProperty;var A0=Object.getOwnPropertyDescriptor;var M0=Object.getOwnPropertyNames;var T0=Object.getPrototypeOf,E0=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Vn=(t,e)=>{for(var n in e)Gd(t,n,{get:e[n],enumerable:!0})},pC=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of M0(e))!E0.call(t,r)&&r!==n&&Gd(t,r,{get:()=>e[r],enumerable:!(o=A0(e,r))||o.enumerable});return t};var uC=(t,e,n)=>(n=t!=null?S0(T0(t)):{},pC(e||!t||!t.__esModule?Gd(n,"default",{value:t,enumerable:!0}):n,t)),k0=t=>pC(Gd({},"__esModule",{value:!0}),t);var $t,oo=be(()=>{"use strict";$t=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}}});var yC={};Vn(yC,{DOMPurify:()=>hC.default,Marked:()=>gC.Marked});var gC,hC,bC=be(()=>{"use strict";gC=require("marked"),hC=uC(require("dompurify"),1)});var m1,P0,I0,Df,Yd,vC,CC,ea,_f,Ao,ti=be(()=>{"use strict";oo();({setLoader:m1,load:P0,provide:I0,getSync:Df}=$t({fallbackImport:()=>Promise.resolve().then(()=>(bC(),yC))})),Yd=new Set,vC=()=>{let t=[...Yd];Yd.clear();for(let e of t)try{e()}catch{}},CC=()=>{let t=Df();return t?Promise.resolve(t):P0().then(e=>(vC(),e))},ea=t=>Df()?()=>{}:(Yd.add(t),()=>{Yd.delete(t)}),_f=t=>{I0(t),vC()},Ao=Df});var H0,Nf,Qd,h1,Pr,Xd=be(()=>{"use strict";ti();H0=t=>{if(!t)return;let e={},n=t;if(n.heading){let o=n.heading;e.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;e.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;e.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;e.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;e.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;e.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;e.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;e.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;e.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;e.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;e.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;e.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;e.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;e.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;e.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;e.checkbox=r=>o({checked:r})}return n.hr&&(e.hr=n.hr),n.br&&(e.br=n.br),e},Nf=t=>{let e=null;return n=>{let o=Ao();if(!o)return Pr(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=H0(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Qd=t=>t?Nf({markedOptions:t.options,renderer:t.renderer}):Nf(),h1=Nf(),Pr=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")});var R0,W0,B0,Jd,Ff=be(()=>{"use strict";Xd();ti();R0={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"]},W0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,B0=()=>{let t=null;return e=>{let n=Ao();if(!n)return Pr(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!W0.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,R0)}},Jd=t=>t===!1?null:typeof t=="function"?t:B0()});function HC(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${N0(e.join(""))}`}function PC(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function N0(t){let e=PC(t,0).toString(36),n=PC(t,2654435761).toString(36);return`${e}.${n}`}var Ir,$f,IC,Zd,LC,F0,ta,RC,na=be(()=>{"use strict";Ir="webmcp:",$f=new Map,IC=t=>{$f.clear();for(let e of t){let n=e.title?.trim();n&&$f.set(e.name,n)}},Zd=t=>$f.get(F0(t)),LC=null;F0=t=>t.startsWith(Ir)?t.slice(Ir.length):t,ta=t=>t.startsWith(Ir),RC=()=>LC?LC():import("@mcp-b/webmcp-polyfill")});var WC,V0,ep,np,$0,tp,z0,U0,q0,Fo,j0,K0,G0,Y0,BC=be(()=>{"use strict";WC="webmcp:",V0=t=>t.startsWith(WC)?t.slice(WC.length):t,ep={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},np=class{constructor(e,n){this.config=e;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return ep.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=z0(r.annotations);return{name:r.name,description:r.description,parametersSchema:U0(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Fo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Fo(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=V0(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Fo(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return Fo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Fo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Fo("Aborted by cancel()");let d=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(p))return Fo("User declined the tool call.");if(o?.aborted)return Fo("Aborted by cancel()");let u=new AbortController,m=!1,h=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),g=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",g,{once:!0}));try{let b=await r.executeTool(l,G0(n),{signal:u.signal});return q0(b)}catch(b){if(m)return Fo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Fo("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Fo(C)}finally{clearTimeout(h),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ep.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ep.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??j0;try{return await n(e)}catch(o){return ep.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>$0(e,o))}},$0=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},tp={type:"object",properties:{}},z0=t=>{if(!t||typeof t!="object")return;let e={...typeof t.readOnlyHint=="boolean"?{readOnlyHint:t.readOnlyHint}:{},...typeof t.untrustedContentHint=="boolean"?{untrustedContentHint:t.untrustedContentHint}:{}};return Object.keys(e).length>0?e:void 0},U0=t=>{if(t===void 0||t==="")return{...tp};if(typeof t=="object")return t!==null&&!Array.isArray(t)?t:{...tp};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{...tp}}catch{return{...tp}}},q0=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Y0(e)}]}},Fo=t=>({isError:!0,content:[{type:"text",text:t}]}),j0=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=K0(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
1
+ "use strict";var S0=Object.create;var Gd=Object.defineProperty;var A0=Object.getOwnPropertyDescriptor;var M0=Object.getOwnPropertyNames;var T0=Object.getPrototypeOf,E0=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Vn=(t,e)=>{for(var n in e)Gd(t,n,{get:e[n],enumerable:!0})},pC=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of M0(e))!E0.call(t,r)&&r!==n&&Gd(t,r,{get:()=>e[r],enumerable:!(o=A0(e,r))||o.enumerable});return t};var uC=(t,e,n)=>(n=t!=null?S0(T0(t)):{},pC(e||!t||!t.__esModule?Gd(n,"default",{value:t,enumerable:!0}):n,t)),k0=t=>pC(Gd({},"__esModule",{value:!0}),t);var $t,oo=be(()=>{"use strict";$t=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}}});var yC={};Vn(yC,{DOMPurify:()=>hC.default,Marked:()=>gC.Marked});var gC,hC,bC=be(()=>{"use strict";gC=require("marked"),hC=uC(require("dompurify"),1)});var m1,P0,I0,Df,Yd,vC,CC,ea,_f,Mo,ti=be(()=>{"use strict";oo();({setLoader:m1,load:P0,provide:I0,getSync:Df}=$t({fallbackImport:()=>Promise.resolve().then(()=>(bC(),yC))})),Yd=new Set,vC=()=>{let t=[...Yd];Yd.clear();for(let e of t)try{e()}catch{}},CC=()=>{let t=Df();return t?Promise.resolve(t):P0().then(e=>(vC(),e))},ea=t=>Df()?()=>{}:(Yd.add(t),()=>{Yd.delete(t)}),_f=t=>{I0(t),vC()},Mo=Df});var H0,Nf,Qd,h1,Pr,Xd=be(()=>{"use strict";ti();H0=t=>{if(!t)return;let e={},n=t;if(n.heading){let o=n.heading;e.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;e.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;e.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;e.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;e.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;e.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;e.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;e.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;e.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;e.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;e.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;e.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;e.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;e.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;e.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;e.checkbox=r=>o({checked:r})}return n.hr&&(e.hr=n.hr),n.br&&(e.br=n.br),e},Nf=t=>{let e=null;return n=>{let o=Mo();if(!o)return Pr(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=H0(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Qd=t=>t?Nf({markedOptions:t.options,renderer:t.renderer}):Nf(),h1=Nf(),Pr=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")});var R0,W0,B0,Jd,Ff=be(()=>{"use strict";Xd();ti();R0={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"]},W0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,B0=()=>{let t=null;return e=>{let n=Mo();if(!n)return Pr(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!W0.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,R0)}},Jd=t=>t===!1?null:typeof t=="function"?t:B0()});function HC(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${N0(e.join(""))}`}function PC(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function N0(t){let e=PC(t,0).toString(36),n=PC(t,2654435761).toString(36);return`${e}.${n}`}var Ir,$f,IC,Zd,LC,F0,ta,RC,na=be(()=>{"use strict";Ir="webmcp:",$f=new Map,IC=t=>{$f.clear();for(let e of t){let n=e.title?.trim();n&&$f.set(e.name,n)}},Zd=t=>$f.get(F0(t)),LC=null;F0=t=>t.startsWith(Ir)?t.slice(Ir.length):t,ta=t=>t.startsWith(Ir),RC=()=>LC?LC():import("@mcp-b/webmcp-polyfill")});var WC,V0,ep,np,$0,tp,z0,U0,q0,Vo,j0,K0,G0,Y0,BC=be(()=>{"use strict";WC="webmcp:",V0=t=>t.startsWith(WC)?t.slice(WC.length):t,ep={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},np=class{constructor(e,n){this.config=e;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return ep.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=z0(r.annotations);return{name:r.name,description:r.description,parametersSchema:U0(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Vo(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=V0(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return Vo(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(b=>b.name===s);if(!l)return Vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Vo("Aborted by cancel()");let d=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(p))return Vo("User declined the tool call.");if(o?.aborted)return Vo("Aborted by cancel()");let u=new AbortController,m=!1,h=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),g=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",g,{once:!0}));try{let b=await r.executeTool(l,G0(n),{signal:u.signal});return q0(b)}catch(b){if(m)return Vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Vo("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return Vo(C)}finally{clearTimeout(h),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ep.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ep.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??j0;try{return await n(e)}catch(o){return ep.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>$0(e,o))}},$0=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},tp={type:"object",properties:{}},z0=t=>{if(!t||typeof t!="object")return;let e={...typeof t.readOnlyHint=="boolean"?{readOnlyHint:t.readOnlyHint}:{},...typeof t.untrustedContentHint=="boolean"?{untrustedContentHint:t.untrustedContentHint}:{}};return Object.keys(e).length>0?e:void 0},U0=t=>{if(t===void 0||t==="")return{...tp};if(typeof t=="object")return t!==null&&!Array.isArray(t)?t:{...tp};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{...tp}}catch{return{...tp}}},q0=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Y0(e)}]}},Vo=t=>({isError:!0,content:[{type:"text",text:t}]}),j0=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=K0(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
2
2
 
3
3
  Arguments:
4
4
  ${e}`:"")+(t.description?`
@@ -14,7 +14,7 @@ ${n}`}function jL(t,e,n){return e.includes("</document_content>")?Dl(t,e):`<docu
14
14
  <document_content>
15
15
  ${e}
16
16
  </document_content>
17
- </document>`}function Iw(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Dl(t.label,t.text)}return n==="document"?jL(t.label,t.text,e):Dl(t.label,t.text)}var eg=be(()=>{"use strict"});function gp(t){return t instanceof sr}var sr,_l=be(()=>{"use strict";sr=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var pa,rg=be(()=>{"use strict";pa=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function ZL(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===JL?new Uint8Array(t,44):new Uint8Array(t)}function eP(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Bw,YL,QL,XL,JL,ua,sg=be(()=>{"use strict";rg();Bw=16e3,YL=24e3,QL=4096,XL=4,JL=1380533830;ua=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Bw,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Bw});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new pa(YL);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${eP(o)}/ws/agents/${encodeURIComponent(e)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let h=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${h}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}onLevel(e){this.levelCallbacks.push(e)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(QL,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),p=new Int16Array(d.length),u=0;for(let m=0;m<d.length;m++){let h=Math.max(-1,Math.min(1,d[m]));u+=h*h,p[m]=h<0?h*32768:h*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/d.length),h=Math.max(0,Math.min(1,m*XL));for(let g of this.levelCallbacks)g(h)}},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=ZL(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}}});var ms,ig=be(()=>{"use strict";ms=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function Vl(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new ua(t.runtype);case"browser":if(!ms.isSupported())throw new Error("Browser speech recognition not supported");return new ms(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function ag(t){if(t?.type==="custom"&&t.custom)return Vl({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return Vl({type:"runtype",runtype:t.runtype});if(ms.isSupported())return Vl({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ow(t){try{return ag(t),!0}catch{return!1}}var Dw=be(()=>{"use strict";sg();ig()});var _w={};Vn(_w,{BrowserVoiceProvider:()=>ms,RuntypeVoiceProvider:()=>ua,createBestAvailableVoiceProvider:()=>ag,createVoiceProvider:()=>Vl,isVoiceSupported:()=>Ow});var Nw=be(()=>{"use strict";Dw();sg();ig()});function oP(t){return t.replace(/\/+$/,"")}async function rP(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var yp,Vw=be(()=>{"use strict";rg();yp=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new pa(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${oP(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await rP(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var bp,$w=be(()=>{"use strict";bp=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var zw={};Vn(zw,{FallbackSpeechEngine:()=>bp,RuntypeSpeechEngine:()=>yp});var Uw=be(()=>{"use strict";Vw();$w()});var jw={};Vn(jw,{createReconnectController:()=>iP});function iP(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=t.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},d=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",d),r=!0)},u=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},m=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),h=()=>{let b=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,u(),t.setAbortController(null);let C=!1;for(let P of t.getMessages())P.streaming&&(P.streaming=!1,C=!0);let S=t.buildErrorContent("Connection lost and the response could not be resumed.");S?t.appendMessage({id:`reconnect-failed-${b?.executionId??t.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},g=async()=>{let b=t.config.reconnect?.backoffMs??sP,C=t.config.reconnect?.maxAttempts??b.length,S=t.config.reconnectStream;if(!S){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let P=t.getResumable(),M=P.lastEventId,B=new AbortController;t.setAbortController(B),t.emitReconnect({phase:"resuming",handle:P,attempt:e});let A=null;try{let O=await S({executionId:P.executionId,after:P.lastEventId,signal:B.signal});O&&O.ok&&O.body&&(A=O.body)}catch{A=null}if(B.signal.aborted)return;if(A){let O=t.getMessages().find(W=>W.id===P.assistantMessageId)?.content,E=typeof O=="string"?O:"";try{await t.resumeConnect(A,P.assistantMessageId,E)}catch{}if(B.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:P});return}t.getResumable().lastEventId!==M&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),B.signal.aborted))return}t.getResumable()&&h()};return{begin(){e=0,p(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,u()},wake:s}}var sP,Kw=be(()=>{"use strict";sP=[1e3,2e3,4e3,8e3,8e3]});var Qe,ro=be(()=>{"use strict";Qe=(t,e=24,n="currentColor",o=2)=>{if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r}});var Qw={};Vn(Qw,{EXTRA_LUCIDE_ICONS:()=>pP});var ae,pP,Xw=be(()=>{"use strict";ae=require("lucide"),pP={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var uP,mP,mg,Cp,wp=be(()=>{"use strict";oo();({setLoader:uP,load:mP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Xw(),Qw))})),mg=uP,Cp=mP});var me,fP,gP,xp,ma,fg,Sp,hP,Jw,yP,gg,bP,vP,Ie,Yt=be(()=>{"use strict";ro();wp();me=require("lucide"),fP={activity:me.Activity,"arrow-down":me.ArrowDown,"arrow-up":me.ArrowUp,"arrow-up-right":me.ArrowUpRight,bot:me.Bot,"chevron-down":me.ChevronDown,"chevron-up":me.ChevronUp,"chevron-right":me.ChevronRight,"chevron-left":me.ChevronLeft,check:me.Check,clipboard:me.Clipboard,"clipboard-copy":me.ClipboardCopy,"code-xml":me.CodeXml,copy:me.Copy,file:me.File,"file-code":me.FileCode,"file-spreadsheet":me.FileSpreadsheet,"file-text":me.FileText,"image-plus":me.ImagePlus,loader:me.Loader,"loader-circle":me.LoaderCircle,mic:me.Mic,paperclip:me.Paperclip,quote:me.Quote,"refresh-cw":me.RefreshCw,search:me.Search,send:me.Send,"shield-alert":me.ShieldAlert,"shield-check":me.ShieldCheck,"shield-x":me.ShieldX,square:me.Square,"thumbs-down":me.ThumbsDown,"thumbs-up":me.ThumbsUp,upload:me.Upload,"volume-2":me.Volume2,x:me.X,"at-sign":me.AtSign,"arrow-left":me.ArrowLeft,"arrow-right":me.ArrowRight,"external-link":me.ExternalLink,ellipsis:me.Ellipsis,"ellipsis-vertical":me.EllipsisVertical,menu:me.Menu,"panel-left":me.PanelLeft,plus:me.Plus,minus:me.Minus,pencil:me.Pencil,trash:me.Trash,"trash-2":me.Trash2,download:me.Download,maximize:me.Maximize,minimize:me.Minimize,"message-square":me.MessageSquare,star:me.Star,eye:me.Eye,history:me.History},gP=["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"],xp=new Map(Object.entries(fP)),ma=new Set,fg=!1,Sp=new Set,hP=t=>{let e=[...Sp];t&&Sp.clear();for(let n of e)try{n()}catch{}},Jw=t=>fg?()=>{}:(Sp.add(t),()=>{Sp.delete(t)}),yP=()=>{let t=0;for(let e of[...ma]){let n=xp.get(e.name);if(!n)continue;ma.delete(e),t++;let o=Qe(n,e.size,e.color,e.strokeWidth);if(o)for(e.el.removeAttribute("data-persona-icon-pending");o.firstChild;)e.el.appendChild(o.firstChild)}return t},gg=!1,bP=()=>{Cp().then(t=>{if(!fg){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))xp.has(e)||xp.set(e,n);fg=!0,yP(),hP(!0)}}).catch(t=>{gg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},vP=(t,e,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},Ie=(t,e=24,n="currentColor",o=2)=>{let r=xp.get(t);if(r)return Qe(r,e,n,o);if(gP.includes(t)){gg&&(gg=!1);let s=vP(e,n,o);if(ma.size>=500){let a=ma.values().next().value;a&&ma.delete(a)}return ma.add({el:s,name:t,size:e,color:n,strokeWidth:o}),bP(),s}return console.warn(`Lucide icon "${t}" 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 fn,Hn,fa,fs=be(()=>{"use strict";fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Hn=1e5,fa=Hn+1});function gx(t){let e=t.getRootNode?.();return e&&hx(e)||e&&_p(e)?e:t.ownerDocument??document}function Dp(t,e,n){let o=_p(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(_p(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function Np(t,e,n){if(_p(t)||hx(t)){Dp(t,e,n);return}let o=t;if(o.isConnected){Dp(gx(o),e,n);return}let r=o.ownerDocument??document;Dp(r,e,n),queueMicrotask(()=>{let s=gx(o);s!==r&&Dp(s,e,n)})}function OP(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function gs(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=t,m=t.container??OP(e),h=!1,g=null,b=()=>{if(!h)return;let P=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let M=n.getBoundingClientRect(),B=l?.()??null,A=B!=null?P.top+B:P.top,O=o==="top-start"||o==="top-end"?A-r-M.height:P.bottom+r,W=o==="bottom-end"||o==="top-end"?P.right-M.width:P.left,R=a?.()??null;if(R!=null){let V=Math.max(P.left,P.right-M.width);W=Math.min(Math.max(P.left+R,P.left),V)}n.style.top=`${O}px`,n.style.left=`${W}px`},C=()=>{h&&(h=!1,g&&(g(),g=null),n.remove())},S=()=>{if(h)return;h=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),b();let P=(e.ownerDocument??document).defaultView??window,M=e.ownerDocument??document,B=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},A=E=>{let W=typeof E.composedPath=="function"?E.composedPath():[];W.includes(n)||W.includes(e)||(C(),u?.("outside"))},O=P.setTimeout(()=>{M.addEventListener("pointerdown",A,!0)},0);P.addEventListener("scroll",B,!0),P.addEventListener("resize",B),g=()=>{P.clearTimeout(O),M.removeEventListener("pointerdown",A,!0),P.removeEventListener("scroll",B,!0),P.removeEventListener("resize",B)},p?.()};return{get isOpen(){return h},open:S,close:C,toggle:()=>h?C():S(),reposition:b,destroy:C}}function yx(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var _p,hx,ya=be(()=>{"use strict";_p=t=>t.nodeType===Node.DOCUMENT_NODE,hx=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function ba(t){t.style.display=t.childElementCount>0?"flex":"none"}function Pg(t){let e=t.querySelector(Lg);if(e)return e;let n=$("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=t.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===t?t.insertBefore(n,o):t.appendChild(n),n}var Lg,Fp=be(()=>{"use strict";Ye();Lg="[data-persona-composer-chip-row]"});function jl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function qx(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>jl(t.form),dispatchInput:e,focus:()=>t.focus()}}var zp=be(()=>{"use strict"});function iI(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
17
+ </document>`}function Iw(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Dl(t.label,t.text)}return n==="document"?jL(t.label,t.text,e):Dl(t.label,t.text)}var eg=be(()=>{"use strict"});function gp(t){return t instanceof ir}var ir,_l=be(()=>{"use strict";ir=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var pa,rg=be(()=>{"use strict";pa=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function ZL(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===JL?new Uint8Array(t,44):new Uint8Array(t)}function eP(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Bw,YL,QL,XL,JL,ua,sg=be(()=>{"use strict";rg();Bw=16e3,YL=24e3,QL=4096,XL=4,JL=1380533830;ua=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Bw,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Bw});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new pa(YL);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${eP(o)}/ws/agents/${encodeURIComponent(e)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let h=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${h}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}onLevel(e){this.levelCallbacks.push(e)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(QL,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),p=new Int16Array(d.length),u=0;for(let m=0;m<d.length;m++){let h=Math.max(-1,Math.min(1,d[m]));u+=h*h,p[m]=h<0?h*32768:h*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/d.length),h=Math.max(0,Math.min(1,m*XL));for(let g of this.levelCallbacks)g(h)}},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=ZL(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}}});var ms,ig=be(()=>{"use strict";ms=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function Vl(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new ua(t.runtype);case"browser":if(!ms.isSupported())throw new Error("Browser speech recognition not supported");return new ms(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function ag(t){if(t?.type==="custom"&&t.custom)return Vl({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return Vl({type:"runtype",runtype:t.runtype});if(ms.isSupported())return Vl({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ow(t){try{return ag(t),!0}catch{return!1}}var Dw=be(()=>{"use strict";sg();ig()});var _w={};Vn(_w,{BrowserVoiceProvider:()=>ms,RuntypeVoiceProvider:()=>ua,createBestAvailableVoiceProvider:()=>ag,createVoiceProvider:()=>Vl,isVoiceSupported:()=>Ow});var Nw=be(()=>{"use strict";Dw();sg();ig()});function oP(t){return t.replace(/\/+$/,"")}async function rP(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var yp,Vw=be(()=>{"use strict";rg();yp=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new pa(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${oP(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await rP(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var bp,$w=be(()=>{"use strict";bp=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var zw={};Vn(zw,{FallbackSpeechEngine:()=>bp,RuntypeSpeechEngine:()=>yp});var Uw=be(()=>{"use strict";Vw();$w()});var jw={};Vn(jw,{createReconnectController:()=>iP});function iP(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=t.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},d=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",d),r=!0)},u=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},m=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),h=()=>{let b=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,u(),t.setAbortController(null);let C=!1;for(let P of t.getMessages())P.streaming&&(P.streaming=!1,C=!0);let S=t.buildErrorContent("Connection lost and the response could not be resumed.");S?t.appendMessage({id:`reconnect-failed-${b?.executionId??t.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},g=async()=>{let b=t.config.reconnect?.backoffMs??sP,C=t.config.reconnect?.maxAttempts??b.length,S=t.config.reconnectStream;if(!S){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let P=t.getResumable(),M=P.lastEventId,B=new AbortController;t.setAbortController(B),t.emitReconnect({phase:"resuming",handle:P,attempt:e});let A=null;try{let O=await S({executionId:P.executionId,after:P.lastEventId,signal:B.signal});O&&O.ok&&O.body&&(A=O.body)}catch{A=null}if(B.signal.aborted)return;if(A){let O=t.getMessages().find(W=>W.id===P.assistantMessageId)?.content,E=typeof O=="string"?O:"";try{await t.resumeConnect(A,P.assistantMessageId,E)}catch{}if(B.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:P});return}t.getResumable().lastEventId!==M&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await m(b[Math.min(e-1,b.length-1)]??1e3),B.signal.aborted))return}t.getResumable()&&h()};return{begin(){e=0,p(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,u()},wake:s}}var sP,Kw=be(()=>{"use strict";sP=[1e3,2e3,4e3,8e3,8e3]});var Qe,ro=be(()=>{"use strict";Qe=(t,e=24,n="currentColor",o=2)=>{if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r}});var Qw={};Vn(Qw,{EXTRA_LUCIDE_ICONS:()=>pP});var ae,pP,Xw=be(()=>{"use strict";ae=require("lucide"),pP={user:ae.User,mail:ae.Mail,phone:ae.Phone,calendar:ae.Calendar,clock:ae.Clock,building:ae.Building,"map-pin":ae.MapPin,lock:ae.Lock,key:ae.Key,"credit-card":ae.CreditCard,hash:ae.Hash,globe:ae.Globe,link:ae.Link,"circle-check":ae.CircleCheck,"circle-x":ae.CircleX,"triangle-alert":ae.TriangleAlert,info:ae.Info,ban:ae.Ban,shield:ae.Shield,house:ae.House,"pen-line":ae.PenLine,save:ae.Save,share:ae.Share,funnel:ae.Funnel,settings:ae.Settings,"rotate-cw":ae.RotateCw,"shopping-cart":ae.ShoppingCart,"shopping-bag":ae.ShoppingBag,package:ae.Package,truck:ae.Truck,tag:ae.Tag,gift:ae.Gift,receipt:ae.Receipt,wallet:ae.Wallet,store:ae.Store,"dollar-sign":ae.DollarSign,percent:ae.Percent,play:ae.Play,pause:ae.Pause,"volume-x":ae.VolumeX,camera:ae.Camera,image:ae.Image,film:ae.Film,headphones:ae.Headphones,"message-circle":ae.MessageCircle,bell:ae.Bell,heart:ae.Heart,"eye-off":ae.EyeOff,bookmark:ae.Bookmark,"calendar-days":ae.CalendarDays,timer:ae.Timer,folder:ae.Folder,"folder-open":ae.FolderOpen,files:ae.Files,"chart-column":ae.ChartColumn,sparkles:ae.Sparkles,zap:ae.Zap,sun:ae.Sun,moon:ae.Moon,flag:ae.Flag,lightbulb:ae.Lightbulb,monitor:ae.Monitor,smartphone:ae.Smartphone}});var uP,mP,mg,Cp,wp=be(()=>{"use strict";oo();({setLoader:uP,load:mP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Xw(),Qw))})),mg=uP,Cp=mP});var me,fP,gP,xp,ma,fg,Sp,hP,Jw,yP,gg,bP,vP,Ie,Yt=be(()=>{"use strict";ro();wp();me=require("lucide"),fP={activity:me.Activity,"arrow-down":me.ArrowDown,"arrow-up":me.ArrowUp,"arrow-up-right":me.ArrowUpRight,bot:me.Bot,"chevron-down":me.ChevronDown,"chevron-up":me.ChevronUp,"chevron-right":me.ChevronRight,"chevron-left":me.ChevronLeft,check:me.Check,clipboard:me.Clipboard,"clipboard-copy":me.ClipboardCopy,"code-xml":me.CodeXml,copy:me.Copy,file:me.File,"file-code":me.FileCode,"file-spreadsheet":me.FileSpreadsheet,"file-text":me.FileText,"image-plus":me.ImagePlus,loader:me.Loader,"loader-circle":me.LoaderCircle,mic:me.Mic,paperclip:me.Paperclip,quote:me.Quote,"refresh-cw":me.RefreshCw,search:me.Search,send:me.Send,"shield-alert":me.ShieldAlert,"shield-check":me.ShieldCheck,"shield-x":me.ShieldX,square:me.Square,"thumbs-down":me.ThumbsDown,"thumbs-up":me.ThumbsUp,upload:me.Upload,"volume-2":me.Volume2,x:me.X,"at-sign":me.AtSign,"arrow-left":me.ArrowLeft,"arrow-right":me.ArrowRight,"external-link":me.ExternalLink,ellipsis:me.Ellipsis,"ellipsis-vertical":me.EllipsisVertical,menu:me.Menu,"panel-left":me.PanelLeft,plus:me.Plus,minus:me.Minus,pencil:me.Pencil,trash:me.Trash,"trash-2":me.Trash2,download:me.Download,maximize:me.Maximize,minimize:me.Minimize,"message-square":me.MessageSquare,star:me.Star,eye:me.Eye,history:me.History},gP=["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"],xp=new Map(Object.entries(fP)),ma=new Set,fg=!1,Sp=new Set,hP=t=>{let e=[...Sp];t&&Sp.clear();for(let n of e)try{n()}catch{}},Jw=t=>fg?()=>{}:(Sp.add(t),()=>{Sp.delete(t)}),yP=()=>{let t=0;for(let e of[...ma]){let n=xp.get(e.name);if(!n)continue;ma.delete(e),t++;let o=Qe(n,e.size,e.color,e.strokeWidth);if(o)for(e.el.removeAttribute("data-persona-icon-pending");o.firstChild;)e.el.appendChild(o.firstChild)}return t},gg=!1,bP=()=>{Cp().then(t=>{if(!fg){for(let[e,n]of Object.entries(t.EXTRA_LUCIDE_ICONS))xp.has(e)||xp.set(e,n);fg=!0,yP(),hP(!0)}}).catch(t=>{gg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",t)})},vP=(t,e,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},Ie=(t,e=24,n="currentColor",o=2)=>{let r=xp.get(t);if(r)return Qe(r,e,n,o);if(gP.includes(t)){gg&&(gg=!1);let s=vP(e,n,o);if(ma.size>=500){let a=ma.values().next().value;a&&ma.delete(a)}return ma.add({el:s,name:t,size:e,color:n,strokeWidth:o}),bP(),s}return console.warn(`Lucide icon "${t}" 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 fn,Hn,fa,fs=be(()=>{"use strict";fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Hn=1e5,fa=Hn+1});function gx(t){let e=t.getRootNode?.();return e&&hx(e)||e&&_p(e)?e:t.ownerDocument??document}function Dp(t,e,n){let o=_p(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(_p(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function Np(t,e,n){if(_p(t)||hx(t)){Dp(t,e,n);return}let o=t;if(o.isConnected){Dp(gx(o),e,n);return}let r=o.ownerDocument??document;Dp(r,e,n),queueMicrotask(()=>{let s=gx(o);s!==r&&Dp(s,e,n)})}function OP(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function gs(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=t,m=t.container??OP(e),h=!1,g=null,b=()=>{if(!h)return;let P=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let M=n.getBoundingClientRect(),B=l?.()??null,A=B!=null?P.top+B:P.top,O=o==="top-start"||o==="top-end"?A-r-M.height:P.bottom+r,W=o==="bottom-end"||o==="top-end"?P.right-M.width:P.left,R=a?.()??null;if(R!=null){let V=Math.max(P.left,P.right-M.width);W=Math.min(Math.max(P.left+R,P.left),V)}n.style.top=`${O}px`,n.style.left=`${W}px`},C=()=>{h&&(h=!1,g&&(g(),g=null),n.remove())},S=()=>{if(h)return;h=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),b();let P=(e.ownerDocument??document).defaultView??window,M=e.ownerDocument??document,B=()=>{if(!e.isConnected){C(),u?.("anchor-removed");return}b()},A=E=>{let W=typeof E.composedPath=="function"?E.composedPath():[];W.includes(n)||W.includes(e)||(C(),u?.("outside"))},O=P.setTimeout(()=>{M.addEventListener("pointerdown",A,!0)},0);P.addEventListener("scroll",B,!0),P.addEventListener("resize",B),g=()=>{P.clearTimeout(O),M.removeEventListener("pointerdown",A,!0),P.removeEventListener("scroll",B,!0),P.removeEventListener("resize",B)},p?.()};return{get isOpen(){return h},open:S,close:C,toggle:()=>h?C():S(),reposition:b,destroy:C}}function yx(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var _p,hx,ya=be(()=>{"use strict";_p=t=>t.nodeType===Node.DOCUMENT_NODE,hx=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});function ba(t){t.style.display=t.childElementCount>0?"flex":"none"}function Pg(t){let e=t.querySelector(Lg);if(e)return e;let n=$("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=t.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===t?t.insertBefore(n,o):t.appendChild(n),n}var Lg,Fp=be(()=>{"use strict";Ye();Lg="[data-persona-composer-chip-row]"});function jl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function qx(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>jl(t.form),dispatchInput:e,focus:()=>t.focus()}}var zp=be(()=>{"use strict"});function iI(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
18
18
  `:o===""||Yx.test(o)}function aI(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let a=t[s];if(a===n)return iI(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(a===`
19
19
  `||a==="\uFFFC"||!r&&Yx.test(a))return null;s--}return null}function Kl(t,e,n){for(let o of n){let r=aI(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Qx(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function Xx(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var Yx,Up=be(()=>{"use strict";Yx=/\s/});function qp(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var Rg=be(()=>{"use strict"});var Zx,Wg,jp,Kp=be(()=>{"use strict";Zx=null,Wg=t=>{Zx=t},jp=(t,e,n,o)=>Zx?.(t,e,n,o)??null});function tS(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let g="resolving",b,C=n.renderMentionChip({ref:e,status:g,payload:b,remove:o});return{get el(){return C},setStatus:(P,M)=>{if(P===g&&M===b)return;g=P,b=M;let B=n.renderMentionChip({ref:e,status:g,payload:b,remove:o});C.replaceWith(B),C=B}}}let r=e.iconName??n.chipIconName??"at-sign",s=$("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),a=v("span","persona-mention-chip-icon"),l=g=>{a.replaceChildren();let b=jp(g,13,"currentColor",2);b&&a.appendChild(b)};l(r);let d=v("span","persona-mention-chip-spinner"),p=$("span",{className:"persona-mention-chip-label",text:e.label}),u=$("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),m=Qe(eS.X,11,"currentColor",2.5);return m?u.appendChild(m):u.textContent="\xD7",u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(d),s.appendChild(p),s.appendChild(u),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="resolving"?(d.parentNode!==s&&s.insertBefore(d,p),a.parentNode===s&&a.remove(),s.setAttribute("title",e.label)):(d.parentNode===s&&d.remove(),a.parentNode!==s&&s.insertBefore(a,p),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var eS,nS=be(()=>{"use strict";Ye();eS=require("lucide");ro();Kp()});function Gp(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var oS,Yp,Bg=be(()=>{"use strict";nS();Fp();eg();oS=(t,e)=>`${t}\0${e}`,Yp=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=oS(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=Gp(e,n),a={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return a.chip=tS({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),a.chip.el.setAttribute("data-persona-chip-enter",""),a.chip.el.addEventListener("animationend",()=>a.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.opts.contextRow.appendChild(a.chip.el),this.startPending(a),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let a={key:e,source:n,item:o,ref:Gp(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(a)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.ref.label} from context`)}getRefs(){return this.mentions.map(e=>e.ref)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var u;let s=await Promise.all(e.map(async m=>{try{return m.source.resolveOn==="submit"?await m.source.resolve(m.item,this.buildResolveContext(new AbortController().signal,m.args,o)):(m.resolvePromise&&await m.resolvePromise,m.payload??null)}catch(h){try{this.opts.mentionConfig.onMentionResolveError?.(m.item,h)}catch(g){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",g)}return this.opts.emit?.("resolve-error",{sourceId:m.source.id,itemId:m.item.id}),null}})),a=[],l=[],d={},p=new Set;for(let m=0;m<e.length;m++){let h=e[m],g=s[m];if(!g)continue;let b=oS(h.source.id,h.item.id);if(!p.has(b)){if(p.add(b),g.llmAppend&&g.llmAppend.trim())try{a.push(Iw({label:h.ref.label,text:g.llmAppend,ref:h.ref,item:h.item},a.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}g.contentParts?.length&&l.push(...g.contentParts),g.context&&((d[u=h.source.id]??(d[u]={}))[h.item.id]=g.context)}}return{blocks:a,contentParts:l,context:d}}}}updateRowVisibility(){ba(this.opts.contextRow)}}});var rS,sS=be(()=>{"use strict";rS=`
20
20
  .persona-mention-menu {
@@ -179,7 +179,7 @@ ${e}
179
179
  `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=Qp(r.slice(n.trigger.length));if(s)for(let l of n.sources){let d=l.matchCommand?.(s);if(d&&this.isInlineCommand(d))return{source:l,item:d,args:a}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,a=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:a,args:s}),a==="action")return this.runAction(r,s),{kind:"action"};if(a==="prompt"){let d;try{d=await o.resolve(r,this.resolveContext(s,e))}catch(p){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",p),null}return{kind:"prompt",sendText:d.insertText??d.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let d=await o.resolve(r,this.resolveContext(s,e)),p={};return d.context&&(p[o.id]={[r.id]:d.context}),{blocks:[],contentParts:d.contentParts??[],context:p}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,a;try{a=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(d){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",d);return}let l=a.insertText??a.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=Xx(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function Og(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,pI),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:a=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=a},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var pI,uS=be(()=>{"use strict";pI={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"}});function mS(t){let e=t.composerInput??qx(t.textarea),n=Og("polite",t.liveRegionHost),o=Og("assertive",t.liveRegionHost),r=p=>n.announce(p),s=p=>o.announce(p),a=new Yp({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Xp({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(p,u,m)=>a.add(p,u,m),onInsertMention:(p,u,m,h)=>a.track(p,u,m,h,g=>e.setMentionStatus?.(p,g)),admitMention:(p,u)=>a.admit(p,u),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),d=l();return{openMenu:p=>d.openFromButton(p),isMenuOpen:()=>d.isOpen(),handleInput:()=>d.onInput(),handleKeydown:p=>d.handleKeydown(p),hasMentions:()=>a.hasMentions(),getMentionRefs:()=>a.getRefs(),removeLastChip:()=>a.removeLast(),dispatchInlineCommand:p=>d.dispatchInlineCommand(p),collectForSubmit:()=>a.hasMentions()?a.collectForSubmit():null,untrackMention:p=>a.remove(p),rebindComposer:p=>{p!==e&&(d.destroy(),e=p,d=l())},clear:()=>a.clear(),destroy:()=>{d.destroy(),a.clear(),n.destroy(),o.destroy()}}}var fS=be(()=>{"use strict";Bg();pS();zp();uS();Kp()});var gS={};Vn(gS,{mountContextMentions:()=>mS,setMentionIconRenderer:()=>Wg});var hS=be(()=>{"use strict";fS()});function Ng(t){return t.kind==="text"?t.value.length:1}function Fg(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function yS(){return{blocks:[{kind:"text",value:""}]}}function Vg(t){return{blocks:[{kind:"text",value:t}]}}function $g(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${mI}${e.ref.label}`).join("")}function Zp(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function eu(t){return t.blocks.reduce((e,n)=>e+Ng(n),0)}function fI(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Jp(t,e){let n=[],o=[],r=0;for(let s of t){let a=Ng(s),l=r+a;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let d=e-r;d>0&&n.push({kind:"text",value:s.value.slice(0,d)}),d<a&&o.push({kind:"text",value:s.value.slice(d)})}else o.push(s);r=l}return{left:n,right:o}}function zg(t,e,n,o){let r=Jp(t.blocks,e.start).left,s=Jp(t.blocks,e.end).right,a=s[0],l=a?.kind==="text"?a.value.charAt(0):"",d=l!==" "&&l!==" "&&l!==`
180
180
  `,p=Fg([...r,{kind:"mention",id:o,ref:n},...d?[{kind:"text",value:" "}]:[],...s]),u=e.start+1+(l===`
181
181
  `?0:1);return{doc:{blocks:p},caret:u}}function bS(t,e){let n=0,o=0,r=!1;for(let a of t.blocks)a.kind==="mention"&&a.id===e&&(n=o,r=!0),o+=Ng(a);return r?{doc:{blocks:Fg(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===e)))},caret:n}:{doc:t,caret:o}}function tu(t,e,n,o){let r=eu(t),s=Math.max(0,Math.min(e,n,r)),a=Math.min(r,Math.max(e,n,0)),l=Jp(t.blocks,s).left,d=Jp(t.blocks,a).right;return{doc:{blocks:Fg([...l,{kind:"text",value:o},...d])},caret:s+o.length}}function vS(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:$g(t),contextMentions:fI(t).map(n=>n.ref),contentSegments:e}}var mI,Ug=be(()=>{"use strict";Up();mI="@"});function Xl(t){return t.nodeType===1&&t.hasAttribute(Ql)}function xS(t){return t.nodeType===1&&t.tagName==="BR"}function nu(t){return t.nodeType===3?t.data.length:Xl(t)||xS(t)?1:t.textContent?.length??0}function CS(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?nu(r):0);if(r.contains(e))return Xl(r)?o+1:o+hI(r,e,n);o+=nu(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let a=0;a<Math.min(n,s.length);a++)r+=nu(s[a]);return r}return o}function hI(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let a of Array.from(s.childNodes))if(r(a))return!0;return!1};return r(t),o}function Yl(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],a=nu(s);if(e<=n+a)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=a}return{node:t,offset:o.length}}function yI(t,e){let n=[];for(let o of Array.from(t.childNodes))if(Xl(o)){let r=o.getAttribute(Ql),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(xS(o))n.push({kind:"text",value:wS});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function SS(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.setAttribute("dir","auto"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,a=()=>yI(o,n),l=R=>{o.replaceChildren();for(let V of R.blocks)if(V.kind==="text")V.value.length>0&&o.appendChild(document.createTextNode(V.value));else{n.set(V.id,V.ref);let H=e(V.ref);H.setAttribute("contenteditable","false"),H.setAttribute(Ql,V.id),o.appendChild(H)}},d=()=>{let V=o.getRootNode().activeElement;return V===o||V!=null&&o.contains(V)},p=(R,V)=>{if(s=R,!V?.focus&&!d())return;let H=typeof window<"u"?window.getSelection():null;if(!H)return;let w=Yl(o,R);try{let T=document.createRange();T.setStart(w.node,w.offset),T.collapse(!0),H.removeAllRanges(),H.addRange(T)}catch{}},u=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},m=()=>{let R={start:s,end:s},V=typeof window<"u"?window.getSelection():null;if(!V||V.rangeCount===0)return R;let H=V.getRangeAt(0);if(!o.contains(H.startContainer))return R;let w=CS(o,H.startContainer,H.startOffset),T=H.collapsed?w:CS(o,H.endContainer,H.endOffset);return{start:Math.min(w,T),end:Math.max(w,T)}},h=()=>{let R=new Set;for(let V of Array.from(o.childNodes))Xl(V)&&R.add(V.getAttribute(Ql));for(let V of Array.from(n.keys()))R.has(V)||(n.delete(V),t.onMentionRemoved?.(V))},g=()=>{r||n.size!==0&&h()},b=()=>{r=!0},C=()=>{r=!1,h()},S=R=>{R.preventDefault();let V=R.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,V);else{let{start:H,end:w}=m(),T=tu(a(),H,w,V);l(T.doc),p(T.caret,{focus:!0}),h()}u()},P=R=>{if(r)return;let V=R.inputType;if(V==="insertParagraph"){R.preventDefault();let{start:Y,end:re}=m(),oe=tu(a(),Y,re,wS);l(oe.doc),p(oe.caret,{focus:!0}),n.size>0&&h(),u();return}if(V!=="deleteContentBackward"&&V!=="deleteContentForward"||n.size===0)return;let{start:H,end:w}=m();if(H!==w)return;let T=a(),I=Zp(T),D=V==="deleteContentBackward"?H-1:H;if(D<0||D>=I.length||I[D]!=="\uFFFC")return;let G=0,z=null;for(let Y of T.blocks){let re=Y.kind==="text"?Y.value.length:1;if(Y.kind==="mention"&&D>=G&&D<G+re){z=Y.id;break}G+=re}if(!z)return;R.preventDefault();let K=bS(T,z);l(K.doc),p(K.caret,{focus:!0}),h(),u()},M=(R,V)=>{l(Vg(R)),p(V)},B=(R,V)=>{if(!Number.isFinite(R)||!Number.isFinite(V)||V<=R)return null;try{let H=Yl(o,R),w=Yl(o,V),T=document.createRange();T.setStart(H.node,H.offset),T.setEnd(w.node,w.offset);let I=T.getBoundingClientRect();return I.width===0&&I.height===0?null:I}catch{return null}},A=(R,V,H)=>{let w=tu(a(),R,V,H);l(w.doc),p(w.caret,{focus:!0})},O=(R,V)=>{let H=a(),w=Zp(H),T=V.triggerIndex,I=V.triggerIndex+1+V.query.length;if(T<0||I>w.length||w.slice(T+1,I)!==V.query)return null;let D=t.generateId(),G=zg(H,{start:T,end:I},R,D);return l(G.doc),p(G.caret,{focus:!0}),t.onMentionInserted?.(D,R),u(),D},E=R=>{let V=a(),H=m(),T=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:H.start,end:H.end}:{start:eu(V),end:eu(V)},I=t.generateId(),D=zg(V,T,R,I);return l(D.doc),p(D.caret,{focus:!0}),t.onMentionInserted?.(I,R),u(),I},W=(R,V)=>{for(let H of Array.from(o.childNodes))if(Xl(H)&&H.getAttribute(Ql)===R){let w=V==="error";if(H.classList.toggle(gI,w),w){H.hasAttribute(Gl)||(H.setAttribute(Gl,H.getAttribute("aria-label")??""),H.setAttribute(qg,H.getAttribute("title")??""));let T=n.get(R)?.label??"";H.setAttribute("title",`${T}: failed to attach context`),H.setAttribute("aria-label",`${T}, failed to attach context`)}else if(H.hasAttribute(Gl)){let T=H.getAttribute(Gl),I=H.getAttribute(qg);T?H.setAttribute("aria-label",T):H.removeAttribute("aria-label"),I?H.setAttribute("title",I):H.removeAttribute("title"),H.removeAttribute(Gl),H.removeAttribute(qg)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",b),o.addEventListener("compositionend",C),o.addEventListener("paste",S),o.addEventListener("beforeinput",P),l(yS()),{element:o,getValue:()=>$g(a()),getLogicalText:()=>Zp(a()),getDocument:a,getSelection:m,setSelection:(R,V=R)=>{let H=typeof window<"u"?window.getSelection():null;if(H)try{let w=Yl(o,R),T=Yl(o,V),I=document.createRange();I.setStart(w.node,w.offset),I.setEnd(T.node,T.offset),H.removeAllRanges(),H.addRange(I)}catch{}},setValueWithCaret:M,getLogicalRangeRect:B,setValue:R=>{l(Vg(R)),o.focus(),p(R.length,{focus:!0}),u()},replaceLogicalRange:A,insertMentionAtTrigger:O,insertMentionAtSelection:E,setMentionStatus:W,submit:()=>jl(o.closest("form")),dispatchInput:u,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",b),o.removeEventListener("compositionend",C),o.removeEventListener("paste",S),o.removeEventListener("beforeinput",P)}}}var gI,Ql,Gl,qg,wS,AS=be(()=>{"use strict";Ug();zp();gI="persona-mention-token-error",Ql="data-mention-id",Gl="data-mention-prev-label",qg="data-mention-prev-title",wS=`
182
- `});function CI(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function wI(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function MS(t){let{textarea:e}=t,n={generateId:vI,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=SS(n),r=o.element,s=e.getAttribute("aria-label")!=null;CI(e,r),wI(r,o,s),r.getInlineMessageFields=()=>vS(o.getDocument?.()??{blocks:[]});let a=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,a),{input:o,element:r,destroy:o.destroy}}var bI,vI,TS=be(()=>{"use strict";AS();Ug();bI=0,vI=()=>`pmention-${++bI}`});var ES={};Vn(ES,{mountInlineComposer:()=>MS});var kS=be(()=>{"use strict";TS()});function YS(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function pu(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function lr(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Wr(t,e){return lr(t)-t.scrollTop<=e}function uu(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=t,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function mu(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function QS(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Xg(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight+(t.slack??0));return{targetScrollTop:e,spacerHeight:n}}function XS(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Jg=be(()=>{"use strict"});var nc,VI,fu,$I,th,ZS,ii,oc,gu,zI,UI,Zg,qI,jI,KI,rc,hu,sc,JS,GI,eh,YI,eA,ic,ac=be(()=>{"use strict";nc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},VI=["pre","code","a","script","style"],fu=t=>({type:t?.type??nc.type,placeholder:t?.placeholder??nc.placeholder,speed:t?.speed??nc.speed,duration:t?.duration??nc.duration,buffer:t?.buffer??nc.buffer}),$I=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],th=new Map;for(let t of $I)th.set(t.name,t);ZS=["wipe","glyph-cycle"],ii=t=>{th.set(t.name,t)},oc=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:th.get(t)??null,gu=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
182
+ `});function CI(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function wI(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function MS(t){let{textarea:e}=t,n={generateId:vI,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=SS(n),r=o.element,s=e.getAttribute("aria-label")!=null;CI(e,r),wI(r,o,s),r.getInlineMessageFields=()=>vS(o.getDocument?.()??{blocks:[]});let a=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,a),{input:o,element:r,destroy:o.destroy}}var bI,vI,TS=be(()=>{"use strict";AS();Ug();bI=0,vI=()=>`pmention-${++bI}`});var ES={};Vn(ES,{mountInlineComposer:()=>MS});var kS=be(()=>{"use strict";TS()});function YS(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function pu(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function cr(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Wr(t,e){return cr(t)-t.scrollTop<=e}function uu(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=t,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function mu(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function QS(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Xg(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight+(t.slack??0));return{targetScrollTop:e,spacerHeight:n}}function XS(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Jg=be(()=>{"use strict"});var nc,VI,fu,$I,th,ZS,ii,oc,gu,zI,UI,Zg,qI,jI,KI,rc,hu,sc,JS,GI,eh,YI,eA,ic,ac=be(()=>{"use strict";nc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},VI=["pre","code","a","script","style"],fu=t=>({type:t?.type??nc.type,placeholder:t?.placeholder??nc.placeholder,speed:t?.speed??nc.speed,duration:t?.duration??nc.duration,buffer:t?.buffer??nc.buffer}),$I=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],th=new Map;for(let t of $I)th.set(t.name,t);ZS=["wipe","glyph-cycle"],ii=t=>{th.set(t.name,t)},oc=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:th.get(t)??null,gu=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
183
183
  `);return s<0?"":t.slice(0,s)}return t},zI=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},UI=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},Zg=/\s/,qI=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},jI=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Zg.test(s[l])){let d=l;for(;d<s.length&&Zg.test(s[d]);)d+=1;a.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=l;for(;p<s.length&&!Zg.test(s[p]);)d.appendChild(zI(o,s[p],e,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,t)},KI=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(UI(o,d,e,n.value)),n.value+=1));r.replaceChild(a,t)},rc=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??VI).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)qI(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=e==="char"?jI:KI;for(let m of l)u(m,n,p);return r.innerHTML},hu=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},sc=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},JS=new WeakMap,GI=(t,e)=>{if(!t.styles)return;let n=JS.get(e);if(n||(n=new Set,JS.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},eh=new WeakMap,YI=(t,e)=>{if(!t.onAttach)return;let n=eh.get(e);if(n||(n=new Map,eh.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},eA=t=>{let e=eh.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},ic=(t,e)=>{GI(t,e),YI(t,e)}});var QI,tA,nA,oA=be(()=>{"use strict";ac();QI=`
184
184
  @keyframes persona-stream-wipe {
185
185
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
@@ -234,13 +234,13 @@ ${e}
234
234
  opacity: 1 !important;
235
235
  }
236
236
  }
237
- `.trim(),lc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",JI=10,ZI=120,nh=120,eH=.4,tH=50,nH=t=>{if(!t)return nh;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):nh},pA=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=nH(e);return ZI*n/nh},oh=t=>{let e=lc[Math.floor(Math.random()*lc.length)];return t&&e===t&&(e=lc[(lc.indexOf(e)+1)%lc.length]),e},oH=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let n=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===t){o=!0;continue}o&&Math.random()<eH&&(r.textContent=oh())}},rA=new WeakMap,sA=25,iA=.5,rH=6,aA=.25,lA=new WeakMap,cA=new WeakMap,sH=(t,e)=>{if(!t)return sA*iA;let n=lA.get(t);lA.set(t,e);let o=cA.get(t)??sA;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-aA)+r*aA,cA.set(t,o))}return Math.max(rH,o*iA)},wa=new Map,iH=t=>t.closest("[data-message-id]")?.dataset.messageId??null,aH=t=>{t&&wa.set(t,(wa.get(t)??0)+1)},lH=t=>{if(!t)return;let e=wa.get(t)??0;e<=1?wa.delete(t):wa.set(t,e-1)},uA=t=>{if(t.dataset.glyphCycleScheduled==="true")return;let e=t.textContent??"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=oh();let n=iH(t);n&&(t.dataset.glyphCycleMessageId=n),aH(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=sH(o,r),a=pA(t),l=JI*a,d=r+l;if(o){let p=rA.get(o);p!==void 0&&(d=Math.max(d,p)),rA.set(o,d+s)}cH(t,e,d)},cH=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=pA(t),r=t.textContent??void 0,s=()=>{if(!t.isConnected)return;if(Date.now()>=n){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,lH(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=oh(r);t.textContent=a,r=a,oH(t),setTimeout(s,o)};setTimeout(s,o)},dA=t=>{let e=t.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))uA(n)},dH=t=>t.nodeType===1,mA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:XI,bufferContent(t){if(t.length<tH)return"";let e=0,n=-1,o=0;for(;o<t.length;){if(t[o]==="*"&&t[o+1]==="*"){e+=1,o+=2;continue}/\s/.test(t[o])&&e%2===0&&(n=o),o+=1}return n<0?"":t.slice(0,n)},isAnimating(t){return(wa.get(t.id)??0)>0},onAttach(t){dA(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))dH(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?uA(r):dA(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};ii(mA);fA=mA});var hA={};Vn(hA,{glyphCycle:()=>fA,wipe:()=>nA});var yA=be(()=>{"use strict";oA();gA()});function fc(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=t,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(fa)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of e){if(b.dividerBefore){let P=document.createElement("hr");l.appendChild(P)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",b.id),b.destructive&&C.setAttribute("data-destructive",""),b.icon){let P=Ie(b.icon,16,"currentColor",1.5);P&&C.appendChild(P)}let S=document.createElement("span");S.textContent=b.label,C.appendChild(S),C.addEventListener("click",P=>{P.stopPropagation(),m(),n(b.id)}),l.appendChild(C)}let d=null;function p(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function u(){let b=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),b&&a?.(!0),requestAnimationFrame(()=>{let C=S=>{!l.contains(S.target)&&!o.contains(S.target)&&m()};document.addEventListener("click",C,!0),d=()=>document.removeEventListener("click",C,!0)})}function m(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,b&&a?.(!1)}function h(){l.classList.contains("persona-hidden")?u():m()}function g(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:h,destroy:g}}var dh=be(()=>{"use strict";Ye();Yt();fs()});function gn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=t,p=v("button",Vt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=Ie(e,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,h]of Object.entries(d))p.setAttribute(m,h);return p}function ci(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=t,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=v("button",p);if(u.type="button",u.setAttribute("aria-label",n),e){let h=Ie(e,s??14,"currentColor",2);h&&u.appendChild(h)}let m=v("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[h,g]of Object.entries(d))u.setAttribute(h,g);return u}function bu(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of e){let m;u.icon?m=gn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=v("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function xA(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:h,primaryClassName:g,chevronClassName:b}=t,C=v("div","persona-split-btn"+(h?" "+h:"")),S={label:e,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},P=r&&n?gn({...S,icon:n,size:o??14}):ci({...S,icon:n,iconSize:o??14}),M=gn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(P,M);let B=null,A=()=>{if(B)return B;let O=(typeof p=="function"?p():p)??void 0;return B=fc({items:s,onSelect:a,anchor:C,position:d,portal:O,onOpenChange:E=>{M.setAttribute("aria-expanded",E?"true":"false")}}),O||C.appendChild(B.element),B};return C.isConnected?A():requestAnimationFrame(()=>{B||A()}),M.addEventListener("click",O=>{O.stopPropagation(),A().toggle()}),{element:C,primaryButton:P,chevronButton:M,openMenu:()=>A().show(),closeMenu:()=>B?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{B?.destroy(),C.remove()}}}function SA(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=t,p=v("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,p.appendChild(u);let m=Ie(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let h=fc({items:o,onSelect:b=>{p.setAttribute("aria-expanded","false"),r(b)},anchor:p,position:s,portal:a});a||p.appendChild(h.element);let g=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",b=>{if(b.stopPropagation(),g())return;let C=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),h.toggle()}),p.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p.click())}),{element:p,setLabel:b=>{u.textContent=b,p.setAttribute("aria-label",b)},open:()=>{p.setAttribute("aria-expanded","true"),h.show()},close:()=>{p.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let b=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),p.remove()}}}var di=be(()=>{"use strict";Ye();Yt();dh()});var vs,Tu=be(()=>{"use strict";Ye();vs=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o}});var JA,kh,Wu,Bu=be(()=>{"use strict";JA=()=>{},kh=t=>{JA=t.webMcpToolTitle},Wu=t=>JA(t)});var Lo,pi,ui,ZA,eM,tM,Lh,Ph,Ih=be(()=>{"use strict";Ye();ri();Bu();Lo=require("lucide");ro();na();pi=new Map,ui=t=>{let n=(t.startsWith(Ir)?t.slice(Ir.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},ZA=t=>t?.approval!==!1?t?.approval:void 0,eM=(t,e)=>{let n=ZA(e)?.detailsDisplay??"collapsed";return pi.get(t)??n==="expanded"},tM=(t,e,n)=>{let o=ZA(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=Qe(e?Lo.ChevronUp:Lo.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},Lh=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=eM(t,n);tM(o,s,n),r.style.display=s?"":"none"},Ph=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?Lo.ShieldX:n.status==="timeout"?Lo.ShieldAlert:Lo.ShieldCheck,p=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",u=Qe(d,20,p,2);u&&l.appendChild(u);let m=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),g=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",h.appendChild(g),!r){let W=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");W.setAttribute("data-approval-status",n.status),n.status==="approved"?(W.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",W.style.color="var(--persona-palette-colors-success-700, #15803d)",W.textContent="Approved"):n.status==="denied"?(W.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",W.style.color="var(--persona-palette-colors-error-700, #b91c1c)",W.textContent="Denied"):n.status==="timeout"&&(W.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",W.style.color="var(--persona-palette-colors-warning-700, #b45309)",W.textContent="Timeout"),h.appendChild(W)}m.appendChild(h);let C=n.toolType==="webmcp"||n.toolName.startsWith(Ir)?Wu(n.toolName):void 0,S=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),P=!n.toolName,M=S||(P?n.description:`The assistant wants to use \u201C${C??ui(n.toolName)}\u201D.`),B=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(B.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(B.style.color=o.descriptionColor),B.textContent=M,m.appendChild(B),n.reason){let W=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");W.setAttribute("data-approval-reason","true"),o?.reasonColor?W.style.color=o.reasonColor:o?.descriptionColor&&(W.style.color=o.descriptionColor);let R=v("span","persona-font-medium");R.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,W.appendChild(R),W.appendChild(document.createTextNode(n.reason)),m.appendChild(W)}let A=o?.detailsDisplay??"collapsed",O=!!n.description&&!P,E=O||!!n.parameters;if(A!=="hidden"&&E){let W=eM(t.id,e),R=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");R.type="button",R.setAttribute("data-expand-header","true"),R.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(R.style.color=o.descriptionColor);let V=v("span");V.setAttribute("data-approval-details-label","true");let H=v("span","persona-inline-flex persona-items-center");H.setAttribute("data-approval-details-chevron","true"),R.append(V,H),tM(R,W,e),m.appendChild(R);let w=v("div");if(w.setAttribute("data-approval-details","true"),w.style.display=W?"":"none",O){let T=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=n.description,w.appendChild(T)}if(n.parameters){let T=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(T.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(T.style.color=o.parameterTextColor),T.style.fontSize="0.75rem",T.style.lineHeight="1rem",T.textContent=us(n.parameters),w.appendChild(T)}m.appendChild(w)}if(r){let W=v("div","persona-flex persona-gap-2 persona-mt-2");W.setAttribute("data-approval-buttons","true");let R=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");R.type="button",R.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",R.style.color=o?.approveButtonTextColor??"#ffffff",R.setAttribute("data-approval-action","approve");let V=Qe(Lo.ShieldCheck,14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",R.appendChild(V));let H=document.createTextNode(o?.approveLabel??"Approve");R.appendChild(H);let w=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");w.type="button",w.style.backgroundColor=o?.denyButtonColor??"transparent",w.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",w.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,w.setAttribute("data-approval-action","deny");let T=Qe(Lo.ShieldX,14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);T&&(T.style.marginRight="4px",w.appendChild(T));let I=document.createTextNode(o?.denyLabel??"Deny");w.appendChild(I),W.append(R,w),m.appendChild(W)}return a.append(l,m),s.appendChild(a),s}});var fi,mR,nM,mi,fR,gR,Hh,hR,yR,bR,Rh,oM=be(()=>{"use strict";Ye();Bu();fi=require("lucide");ro();ri();na();ya();Ih();mR=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),nM=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},mi=(t,e)=>{nM(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},fR=t=>t?.approval!==!1?t?.approval:void 0,gR=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return pi.get(t)??n==="expanded"},Hh=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},hR=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Ir)?Wu(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??ui(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),l){n.append(" from ");let p=document.createElement("strong");p.textContent=l,n.appendChild(p)}return n},yR=t=>{let e=v("div","persona-approval-resolved"),n=Qe(fi.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?ui(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},bR=(t,e,n,o,r,s,a)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",p=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",m=p||u,h=m&&gR(e.id,o),g=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",C=v("button","persona-approval-head");C.type="button",m?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",h?"true":"false"),C.setAttribute("aria-label",h?b:g)):C.setAttribute("data-static","true");let S=v("span","persona-approval-logo"),P=Qe(fi.ShieldCheck,16,"currentColor",2);P&&S.appendChild(P),C.appendChild(S);let M=hR(n,o);if(m){let R=v("span","persona-approval-toggle");R.setAttribute("aria-hidden","true");let V=Qe(fi.ChevronDown,14,"currentColor",2);V&&R.appendChild(V),M.append(" "),M.appendChild(R)}C.appendChild(M),l.appendChild(C);let B=v("div","persona-approval-body");if(m){let R=v("div","persona-approval-details");if(R.setAttribute("data-role","params"),R.hidden=!h,p){let V=v("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,R.appendChild(V)}if(u){let V=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=us(n.parameters),R.appendChild(V)}B.appendChild(R)}if(n.reason){let R=v("p","persona-approval-reason");o?.reasonColor?R.style.color=o.reasonColor:o?.descriptionColor&&(R.style.color=o.descriptionColor);let V=v("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,R.append(V,document.createTextNode(n.reason)),B.appendChild(R)}let A=v("div","persona-approval-actions"),O=null,E=R=>{o?.approveButtonColor&&(R.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(R.style.color=o.approveButtonTextColor)},W=v("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),o?.denyButtonColor&&(W.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(W.style.color=o.denyButtonTextColor),W.append(o?.denyLabel??"Deny"),a){let R=v("div","persona-approval-split"),V=v("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),E(V),V.append(o?.approveLabel??"Always allow",Hh("\u23CE"));let H=v("button","persona-approval-caret");H.type="button",H.setAttribute("data-action","toggle-menu"),H.setAttribute("aria-label","More options"),E(H);let w=Qe(fi.ChevronDown,15,"currentColor",2);w&&H.appendChild(w),R.append(V,H),A.append(R,W),W.append(Hh("Esc"));let T=v("div","persona-approval-menu"),I=v("button","persona-approval-menu-item");I.type="button",I.append("Allow once",Hh("\u2318\u23CE")),T.appendChild(I),O=gs({anchor:R,content:T,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,O),I.addEventListener("click",()=>{mi(t,e.id),r()})}else{let R=v("button","persona-approval-primary persona-approval-primary--solo");R.type="button",R.setAttribute("data-action","allow"),E(R),R.append(o?.approveLabel??"Allow"),A.append(R,W)}return B.appendChild(A),l.appendChild(B),l.addEventListener("click",R=>{let V=R.target instanceof Element?R.target.closest("[data-action]"):null;if(!V)return;let H=V.getAttribute("data-action");if(H==="toggle-params"){let w=l.querySelector('[data-role="params"]');if(w){let T=w.hidden;w.hidden=!T,C.setAttribute("aria-expanded",T?"true":"false"),C.setAttribute("aria-label",T?b:g),pi.set(e.id,T)}return}if(H==="toggle-menu"){O?.toggle();return}if(H==="always"){mi(t,e.id),r({remember:!0});return}if(H==="allow"){mi(t,e.id),r();return}if(H==="deny"){mi(t,e.id),s();return}}),l},Rh=()=>{let t=mR();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let d=fR(a);if(l.status!=="pending"){if(mi(t,o.id),l.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return yR(l)}nM(t,o.id);let p=d?.enableAlwaysAllow===!0,u=bR(t,o,l,d,r,s,p);if(p){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let m=h=>{yx(h)||o.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),mi(t,o.id),h.key==="Escape"?s():h.metaKey||h.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,m),document.addEventListener("keydown",m)}return u}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])mi(t,o);t.latestPendingApprovalId=null}}}});var rM=be(()=>{"use strict";Ih();oM();Bu()});var sM={};Vn(sM,{approvalDetailsExpansionState:()=>pi,createApprovalBubble:()=>Ph,createBuiltInApprovalPlugin:()=>Rh,humanizeToolName:()=>ui,initApprovalUi:()=>kh,updateApprovalDetailsUI:()=>Lh});var iM=be(()=>{"use strict";rM()});function ka(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function cM(t,e){if(e[t])return e[t];for(let n of Object.keys(e))if(n.endsWith("_")&&t.startsWith(n))return e[n]}function AR(t,e){return(e&&cM(t,e))??cM(t,Or)??wR}function MR(t){return/^#[0-9a-fA-F]{6}$/.test(t)?`${t}50`:`color-mix(in srgb, ${t} 31%, transparent)`}function TR(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function ER(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function kR(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function LR(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function PR(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function IR(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function HR(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function RR(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,l.appendChild(d),l}}function Wh(t,e,n,o,r,s,a,l){let d=r.has(t.id),p=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ka(p,o.classNames?.eventRow);let u=a.find(h=>h.renderEventStreamRow);if(u?.renderEventStreamRow&&l){let h=u.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(h)return p.appendChild(h),p}return p.appendChild(m()),p;function m(){let h=v("div",""),g=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",t.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=Qe(d?En.ChevronDown:En.ChevronRight,"14px","currentColor",2);C&&b.appendChild(C);let S=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=o.timestampFormat??"relative";S.textContent=P==="relative"?TR(t.timestamp,n):ER(t.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let B=AR(t.type,o.badgeColors),A=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");A.style.backgroundColor=B.bg,A.style.color=B.text,A.style.borderColor=MR(B.text),A.textContent=t.type;let O=o.descriptionFields??xR,E=kR(t.payload,O),W=null;E&&(W=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=E);let R=v("div","persona-flex-1 persona-min-w-0"),V=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),H=Qe(En.Clipboard,"12px","currentColor",1.5);return H&&V.appendChild(H),V.addEventListener("click",async w=>{w.stopPropagation(),await LR(PR(t)),V.innerHTML="";let T=Qe(En.Check,"12px","currentColor",1.5);T&&V.appendChild(T),setTimeout(()=>{V.innerHTML="";let I=Qe(En.Clipboard,"12px","currentColor",1.5);I&&V.appendChild(I)},1500)}),g.appendChild(b),g.appendChild(S),M&&g.appendChild(M),g.appendChild(A),W&&g.appendChild(W),g.appendChild(R),g.appendChild(V),h.appendChild(g),d&&h.appendChild(RR(t,a,l)),h}}function Bh(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=t.renderIconByName??(()=>null),d=r?.features?.scrollToBottom,p=d?.enabled!==!1,u=d?.iconName??"arrow-down",m=d?.label??"",h=r?.features?.eventStream??{},g=s.find(C=>C.renderEventStreamView);if(g?.renderEventStreamView&&r){let C=g.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>b().element,onClose:o});if(C)return{element:C,update:()=>{},destroy:()=>{}}}return b();function b(){let C=h.classNames,S=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ka(S,C?.panel);let P=[],M="",B="",A=null,O=[],E={},W=0,R=pu(),V=0,H=0,w=!1,T=null,I=!1,D=0,G=new Set,z=new Map,K="",Y="",re=null,oe,se,ce,we,ge=null,N=null,ye=null;function ke(){let ve=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Se=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(ka(Se,C?.headerBar),a){N=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),N.style.cursor="help",ge=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ge.textContent="-- tok/s",ye=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ye.style.display="none",ye.style.pointerEvents="none";let Rn=N,tn=ye,it=()=>{if(!tn.textContent)return;let Kt=Rn.getBoundingClientRect(),Ze=ve.getBoundingClientRect();tn.style.left=`${Kt.left-Ze.left}px`,tn.style.top=`${Kt.bottom-Ze.top+4}px`,tn.style.display="block"},_e=()=>{tn.style.display="none"};N.addEventListener("mouseenter",it),N.addEventListener("mouseleave",_e),N.appendChild(ge)}let Ke=v("div","persona-flex-1");oe=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ut=v("option","");ut.value="",ut.textContent="All events (0)",oe.appendChild(ut),se=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),se.type="button",se.title="Copy All";let Cn=Qe(En.ClipboardCopy,"12px","currentColor",1.5);Cn&&se.appendChild(Cn);let wn=v("span","persona-event-copy-all persona-text-xs");wn.textContent="Copy All",se.appendChild(wn),N&&Se.appendChild(N),Se.appendChild(Ke),Se.appendChild(oe),Se.appendChild(se);let Wt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ka(Wt,C?.searchBar);let St=Qe(En.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Et=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");St&&Et.appendChild(St),ce=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ka(ce,C?.searchInput),ce.type="text",ce.placeholder="Search event payloads...",we=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),we.type="button",we.style.display="none";let sn=Qe(En.X,"12px","currentColor",2);return sn&&we.appendChild(sn),Wt.appendChild(Et),Wt.appendChild(ce),Wt.appendChild(we),ve.appendChild(Se),ve.appendChild(Wt),ye&&ve.appendChild(ye),ve}let nt,Ee=s.find(ve=>ve.renderEventStreamToolbar);Ee?.renderEventStreamToolbar&&r?nt=Ee.renderEventStreamToolbar({config:r,defaultRenderer:()=>ke(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Se=>{M=Se,Q(),Te()},onSearchChange:Se=>{B=Se,Q(),Te()}})??ke():nt=ke();let Ne=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ne.style.display="none";function Pe(){if(!a||!ge||!N)return;let ve=a(),Se=IR(ve);ge.textContent=Se;let Ke=HR(ve);ye&&(ye.textContent=Ke,Ke||(ye.style.display="none")),N.setAttribute("aria-label",Ke?`Throughput: ${Se}, ${Ke}`:`Throughput: ${Se}`)}let dt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Xe=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Xe.style.height="100%";let xt=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ka(xt,C?.scrollIndicator),xt.style.display="none",xt.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ge=l(u,"14px","currentColor",2);Ge&&xt.appendChild(Ge);let yt=v("span","");yt.textContent=m,xt.appendChild(yt);let X=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");X.style.display="none",dt.appendChild(Xe),dt.appendChild(X),dt.appendChild(xt),S.setAttribute("tabindex","0"),S.appendChild(nt),S.appendChild(Ne),S.appendChild(dt);function L(){let ve=e.getAll(),Se={};for(let Wt of ve)Se[Wt.type]=(Se[Wt.type]||0)+1;let Ke=Object.keys(Se).sort(),ut=Ke.length!==O.length||!Ke.every((Wt,St)=>Wt===O[St]),vn=!ut&&Ke.some(Wt=>Se[Wt]!==E[Wt]),Cn=ve.length!==Object.values(E).reduce((Wt,St)=>Wt+St,0);if(!ut&&!vn&&!Cn||(O=Ke,E=Se,!oe))return;let wn=oe.value;if(oe.options[0].textContent=`All events (${ve.length})`,ut){for(;oe.options.length>1;)oe.remove(1);for(let Wt of Ke){let St=v("option","");St.value=Wt,St.textContent=`${Wt} (${Se[Wt]||0})`,oe.appendChild(St)}wn&&Ke.includes(wn)?oe.value=wn:wn&&(oe.value="",M="")}else for(let Wt=1;Wt<oe.options.length;Wt++){let St=oe.options[Wt];St.textContent=`${St.value} (${Se[St.value]||0})`}}function j(){let ve=e.getAll();if(M&&(ve=ve.filter(Se=>Se.type===M)),B){let Se=B.toLowerCase();ve=ve.filter(Ke=>Ke.type.toLowerCase().includes(Se)||Ke.payload.toLowerCase().includes(Se))}return ve}function J(){return M!==""||B!==""}function Q(){W=0,V=0,R.resume(),xt.style.display="none"}function de(ve){G.has(ve)?G.delete(ve):G.add(ve),re=ve;let Se=Xe.scrollTop,Ke=R.isFollowing();I=!0,R.pause(),Te(),Xe.scrollTop=Se,Ke&&R.resume(),I=!1}function Me(){return Wr(Xe,50)}function Te(){H=Date.now(),w=!1,Pe(),L();let ve=e.getEvictedCount();ve>0?(Ne.textContent=`${ve.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",P=j();let Se=P.length,Ke=e.getSize()>0;Se===0&&Ke&&J()?(X.textContent=B?`No events matching '${B}'`:"No events matching filter",X.style.display="",Xe.style.display="none"):(X.style.display="none",Xe.style.display=""),se&&(se.title=J()?`Copy Filtered (${Se})`:"Copy All"),p&&!R.isFollowing()&&Se>W&&(V+=Se-W,yt.textContent=m?`${m}${V>0?` (${V})`:""}`:"",xt.style.display=""),W=Se;let ut=e.getAll(),vn=ut.length>0?ut[0].timestamp:0,Cn=new Set(P.map(St=>St.id));for(let St of G)Cn.has(St)||G.delete(St);let wn=M!==K||B!==Y,Wt=z.size===0&&P.length>0;if(wn||Wt||P.length===0){Xe.innerHTML="",z.clear();let St=document.createDocumentFragment();for(let Et=0;Et<P.length;Et++){let sn=Wh(P[Et],Et,vn,h,G,de,s,r);z.set(P[Et].id,sn),St.appendChild(sn)}Xe.appendChild(St),K=M,Y=B,re=null}else{if(re!==null){let Et=z.get(re);if(Et&&Et.parentNode===Xe){let sn=P.findIndex(Rn=>Rn.id===re);if(sn>=0){let Rn=Wh(P[sn],sn,vn,h,G,de,s,r);Xe.insertBefore(Rn,Et),Et.remove(),z.set(re,Rn)}}re=null}let St=new Set(P.map(Et=>Et.id));for(let[Et,sn]of z)St.has(Et)||(sn.remove(),z.delete(Et));for(let Et=0;Et<P.length;Et++){let sn=P[Et];if(!z.has(sn.id)){let Rn=Wh(sn,Et,vn,h,G,de,s,r);z.set(sn.id,Rn),Xe.appendChild(Rn)}}}R.isFollowing()&&(Xe.scrollTop=Xe.scrollHeight)}function Fe(){if(Date.now()-H>=SR){T!==null&&(cancelAnimationFrame(T),T=null),Te();return}w||(w=!0,T=requestAnimationFrame(()=>{T=null,Te()}))}let je=(ve,Se)=>{if(!se)return;se.innerHTML="";let Ke=Qe(ve,"12px","currentColor",1.5);Ke&&se.appendChild(Ke);let ut=v("span","persona-text-xs");ut.textContent="Copy All",se.appendChild(ut),setTimeout(()=>{se.innerHTML="";let vn=Qe(En.ClipboardCopy,"12px","currentColor",1.5);vn&&se.appendChild(vn);let Cn=v("span","persona-text-xs");Cn.textContent="Copy All",se.appendChild(Cn),se.disabled=!1},Se)},lt=async()=>{if(se){se.disabled=!0;try{let ve;J()?ve=P:n?(ve=await n(),ve.length===0&&(ve=e.getAll())):ve=e.getAll();let Se=ve.map(Ke=>{try{return JSON.parse(Ke.payload)}catch{return Ke.payload}});await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),je(En.Check,1500)}catch{je(En.X,1500)}}},ot=()=>{oe&&(M=oe.value,Q(),Te())},Je=()=>{!ce||!we||(we.style.display=ce.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{B=ce.value,Q(),Te()},150))},mt=()=>{!ce||!we||(ce.value="",B="",we.style.display="none",A&&clearTimeout(A),Q(),Te())},Tt=()=>{if(I)return;let ve=Xe.scrollTop,{action:Se,nextLastScrollTop:Ke}=uu({following:R.isFollowing(),currentScrollTop:ve,lastScrollTop:D,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});D=Ke,Se==="resume"?(R.resume(),V=0,xt.style.display="none"):Se==="pause"&&(R.pause(),p&&(yt.textContent=m,xt.style.display=""))},ee=ve=>{let Se=mu({following:R.isFollowing(),deltaY:ve.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Se==="pause"?(R.pause(),p&&(yt.textContent=m,xt.style.display="")):Se==="resume"&&(R.resume(),V=0,xt.style.display="none")},Oe=()=>{p&&(Xe.scrollTop=Xe.scrollHeight,R.resume(),V=0,xt.style.display="none")},$e=ve=>{let Se=ve.target;if(!Se||Se.closest("button"))return;let Ke=Se.closest("[data-event-id]");if(!Ke)return;let ut=Ke.getAttribute("data-event-id");ut&&de(ut)},pt=ve=>{if((ve.metaKey||ve.ctrlKey)&&ve.key==="f"){ve.preventDefault(),ce?.focus(),ce?.select();return}ve.key==="Escape"&&(ce&&document.activeElement===ce?(mt(),ce.blur(),S.focus()):o&&o())};se&&se.addEventListener("click",lt),oe&&oe.addEventListener("change",ot),ce&&ce.addEventListener("input",Je),we&&we.addEventListener("click",mt),Xe.addEventListener("scroll",Tt),Xe.addEventListener("wheel",ee,{passive:!0}),Xe.addEventListener("click",$e),xt.addEventListener("click",Oe),S.addEventListener("keydown",pt);function _t(){A&&clearTimeout(A),T!==null&&(cancelAnimationFrame(T),T=null),w=!1,z.clear(),se&&se.removeEventListener("click",lt),oe&&oe.removeEventListener("change",ot),ce&&ce.removeEventListener("input",Je),we&&we.removeEventListener("click",mt),Xe.removeEventListener("scroll",Tt),Xe.removeEventListener("wheel",ee),Xe.removeEventListener("click",$e),xt.removeEventListener("click",Oe),S.removeEventListener("keydown",pt)}return{element:S,update:Fe,destroy:_t}}}var En,Or,wR,xR,SR,dM=be(()=>{"use strict";Ye();En=require("lucide");ro();Jg();Or={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};Or.execution_error=Or.error;Or.execution_=Or.flow_;Or.turn_=Or.agent_;Or.text_=Or.agent_;wR={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},xR=["flowName","stepName","reasoningText","text","name","tool","toolName"],SR=100});var bc,pM=be(()=>{"use strict";bc=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}}});var vc,uM=be(()=>{"use strict";vc=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}}});function Oh(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ou(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function OR(t,e){return typeof e.type=="string"?e.type:t}function fM(t){let e=mM(t,"tokens")??mM(t,"totalTokens");return e?hM(e.output):void 0}function DR(t){return hM(t.durationMs)}function _R(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var WR,BR,gM,hM,mM,Cc,yM=be(()=>{"use strict";WR=new Set(["step_start","turn_start"]),BR=new Set(["step_complete","turn_complete"]),gM=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hM=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,mM=(t,e)=>{let n=t[e];return gM(n)?n:void 0};Cc=class{constructor(e=_R){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ou(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!gM(n)){e==="execution_error"&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=OR(e,n),r=this.now();if(o==="execution_start"){this.startRun(r);return}if(WR.has(o)){this.run||this.startRun(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Oh(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ou(l,d),outputTokens:l,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(BR.has(o)){if(!this.run)return;let s=this.run,a=fM(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+Oh(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ou(d,p),outputTokens:d,durationMs:p,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.run)return;let s=this.run,a=fM(n),l=a??s.exactOutputTokens+Oh(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ou(l,p),outputTokens:l,durationMs:p,source:d},this.run=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:DR(n)??o-e.startedAt}}});var bM=be(()=>{"use strict";dM();pM();uM();yM()});var vM={};Vn(vM,{EventStreamBuffer:()=>bc,EventStreamStore:()=>vc,ThroughputTracker:()=>Cc,createEventStreamView:()=>Bh});var CM=be(()=>{"use strict";bM()});var _h,$o,wc=be(()=>{"use strict";_h=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},$o=new _h});function cr(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function wM(t){let e=cr(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Du(t){if(typeof t!="string")return"";let e=t.indexOf(`
237
+ `.trim(),lc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",JI=10,ZI=120,nh=120,eH=.4,tH=50,nH=t=>{if(!t)return nh;let n=(t.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):nh},pA=t=>{let e=t.closest(".persona-stream-glyph-cycle"),n=nH(e);return ZI*n/nh},oh=t=>{let e=lc[Math.floor(Math.random()*lc.length)];return t&&e===t&&(e=lc[(lc.indexOf(e)+1)%lc.length]),e},oH=t=>{let e=t.closest(".persona-stream-glyph-cycle");if(!e)return;let n=e.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===t){o=!0;continue}o&&Math.random()<eH&&(r.textContent=oh())}},rA=new WeakMap,sA=25,iA=.5,rH=6,aA=.25,lA=new WeakMap,cA=new WeakMap,sH=(t,e)=>{if(!t)return sA*iA;let n=lA.get(t);lA.set(t,e);let o=cA.get(t)??sA;if(n!==void 0){let r=e-n;r>1&&(o=o*(1-aA)+r*aA,cA.set(t,o))}return Math.max(rH,o*iA)},wa=new Map,iH=t=>t.closest("[data-message-id]")?.dataset.messageId??null,aH=t=>{t&&wa.set(t,(wa.get(t)??0)+1)},lH=t=>{if(!t)return;let e=wa.get(t)??0;e<=1?wa.delete(t):wa.set(t,e-1)},uA=t=>{if(t.dataset.glyphCycleScheduled==="true")return;let e=t.textContent??"";if(!e||/\s/.test(e))return;t.dataset.glyphCycleScheduled="true",t.dataset.glyphCycleFinal=e,t.setAttribute("data-preserve-runtime","stream-glyph-cycle"),t.textContent=oh();let n=iH(t);n&&(t.dataset.glyphCycleMessageId=n),aH(n);let o=t.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=sH(o,r),a=pA(t),l=JI*a,d=r+l;if(o){let p=rA.get(o);p!==void 0&&(d=Math.max(d,p)),rA.set(o,d+s)}cH(t,e,d)},cH=(t,e,n)=>{if(t.dataset.glyphCycleStarted==="true")return;t.dataset.glyphCycleStarted="true";let o=pA(t),r=t.textContent??void 0,s=()=>{if(!t.isConnected)return;if(Date.now()>=n){t.textContent=e,t.removeAttribute("data-preserve-runtime"),delete t.dataset.glyphCycleStarted,delete t.dataset.glyphCycleFinal,lH(t.dataset.glyphCycleMessageId??null),delete t.dataset.glyphCycleMessageId;return}let a=oh(r);t.textContent=a,r=a,oH(t),setTimeout(s,o)};setTimeout(s,o)},dA=t=>{let e=t.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(e)for(let n of Array.from(e))uA(n)},dH=t=>t.nodeType===1,mA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:XI,bufferContent(t){if(t.length<tH)return"";let e=0,n=-1,o=0;for(;o<t.length;){if(t[o]==="*"&&t[o+1]==="*"){e+=1,o+=2;continue}/\s/.test(t[o])&&e%2===0&&(n=o),o+=1}return n<0?"":t.slice(0,n)},isAnimating(t){return(wa.get(t.id)??0)>0},onAttach(t){dA(t);let e=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))dH(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?uA(r):dA(r))});return e.observe(t,{childList:!0,subtree:!0}),()=>e.disconnect()}};ii(mA);fA=mA});var hA={};Vn(hA,{glyphCycle:()=>fA,wipe:()=>nA});var yA=be(()=>{"use strict";oA();gA()});function fc(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=t,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(fa)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of e){if(b.dividerBefore){let P=document.createElement("hr");l.appendChild(P)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",b.id),b.destructive&&C.setAttribute("data-destructive",""),b.icon){let P=Ie(b.icon,16,"currentColor",1.5);P&&C.appendChild(P)}let S=document.createElement("span");S.textContent=b.label,C.appendChild(S),C.addEventListener("click",P=>{P.stopPropagation(),m(),n(b.id)}),l.appendChild(C)}let d=null;function p(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function u(){let b=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),b&&a?.(!0),requestAnimationFrame(()=>{let C=S=>{!l.contains(S.target)&&!o.contains(S.target)&&m()};document.addEventListener("click",C,!0),d=()=>document.removeEventListener("click",C,!0)})}function m(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,b&&a?.(!1)}function h(){l.classList.contains("persona-hidden")?u():m()}function g(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:h,destroy:g}}var dh=be(()=>{"use strict";Ye();Yt();fs()});function gn(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=t,p=v("button",Vt(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=Ie(e,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,h]of Object.entries(d))p.setAttribute(m,h);return p}function ci(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=t,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=v("button",p);if(u.type="button",u.setAttribute("aria-label",n),e){let h=Ie(e,s??14,"currentColor",2);h&&u.appendChild(h)}let m=v("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[h,g]of Object.entries(d))u.setAttribute(h,g);return u}function bu(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of e){let m;u.icon?m=gn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=v("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function xA(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:h,primaryClassName:g,chevronClassName:b}=t,C=v("div","persona-split-btn"+(h?" "+h:"")),S={label:e,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},P=r&&n?gn({...S,icon:n,size:o??14}):ci({...S,icon:n,iconSize:o??14}),M=gn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(P,M);let B=null,A=()=>{if(B)return B;let O=(typeof p=="function"?p():p)??void 0;return B=fc({items:s,onSelect:a,anchor:C,position:d,portal:O,onOpenChange:E=>{M.setAttribute("aria-expanded",E?"true":"false")}}),O||C.appendChild(B.element),B};return C.isConnected?A():requestAnimationFrame(()=>{B||A()}),M.addEventListener("click",O=>{O.stopPropagation(),A().toggle()}),{element:C,primaryButton:P,chevronButton:M,openMenu:()=>A().show(),closeMenu:()=>B?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{B?.destroy(),C.remove()}}}function SA(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=t,p=v("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,p.appendChild(u);let m=Ie(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let h=fc({items:o,onSelect:b=>{p.setAttribute("aria-expanded","false"),r(b)},anchor:p,position:s,portal:a});a||p.appendChild(h.element);let g=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",b=>{if(b.stopPropagation(),g())return;let C=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),h.toggle()}),p.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p.click())}),{element:p,setLabel:b=>{u.textContent=b,p.setAttribute("aria-label",b)},open:()=>{p.setAttribute("aria-expanded","true"),h.show()},close:()=>{p.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let b=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),p.remove()}}}var di=be(()=>{"use strict";Ye();Yt();dh()});var vs,Tu=be(()=>{"use strict";Ye();vs=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o}});var JA,kh,Wu,Bu=be(()=>{"use strict";JA=()=>{},kh=t=>{JA=t.webMcpToolTitle},Wu=t=>JA(t)});var Po,pi,ui,ZA,eM,tM,Lh,Ph,Ih=be(()=>{"use strict";Ye();ri();Bu();Po=require("lucide");ro();na();pi=new Map,ui=t=>{let n=(t.startsWith(Ir)?t.slice(Ir.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},ZA=t=>t?.approval!==!1?t?.approval:void 0,eM=(t,e)=>{let n=ZA(e)?.detailsDisplay??"collapsed";return pi.get(t)??n==="expanded"},tM=(t,e,n)=>{let o=ZA(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=Qe(e?Po.ChevronUp:Po.ChevronDown,14,"currentColor",2);a&&s.appendChild(a)}},Lh=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=eM(t,n);tM(o,s,n),r.style.display=s?"":"none"},Ph=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?Po.ShieldX:n.status==="timeout"?Po.ShieldAlert:Po.ShieldCheck,p=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",u=Qe(d,20,p,2);u&&l.appendChild(u);let m=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),g=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",h.appendChild(g),!r){let W=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");W.setAttribute("data-approval-status",n.status),n.status==="approved"?(W.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",W.style.color="var(--persona-palette-colors-success-700, #15803d)",W.textContent="Approved"):n.status==="denied"?(W.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",W.style.color="var(--persona-palette-colors-error-700, #b91c1c)",W.textContent="Denied"):n.status==="timeout"&&(W.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",W.style.color="var(--persona-palette-colors-warning-700, #b45309)",W.textContent="Timeout"),h.appendChild(W)}m.appendChild(h);let C=n.toolType==="webmcp"||n.toolName.startsWith(Ir)?Wu(n.toolName):void 0,S=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),P=!n.toolName,M=S||(P?n.description:`The assistant wants to use \u201C${C??ui(n.toolName)}\u201D.`),B=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(B.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(B.style.color=o.descriptionColor),B.textContent=M,m.appendChild(B),n.reason){let W=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");W.setAttribute("data-approval-reason","true"),o?.reasonColor?W.style.color=o.reasonColor:o?.descriptionColor&&(W.style.color=o.descriptionColor);let R=v("span","persona-font-medium");R.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,W.appendChild(R),W.appendChild(document.createTextNode(n.reason)),m.appendChild(W)}let A=o?.detailsDisplay??"collapsed",O=!!n.description&&!P,E=O||!!n.parameters;if(A!=="hidden"&&E){let W=eM(t.id,e),R=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");R.type="button",R.setAttribute("data-expand-header","true"),R.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(R.style.color=o.descriptionColor);let V=v("span");V.setAttribute("data-approval-details-label","true");let H=v("span","persona-inline-flex persona-items-center");H.setAttribute("data-approval-details-chevron","true"),R.append(V,H),tM(R,W,e),m.appendChild(R);let w=v("div");if(w.setAttribute("data-approval-details","true"),w.style.display=W?"":"none",O){let T=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=n.description,w.appendChild(T)}if(n.parameters){let T=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(T.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(T.style.color=o.parameterTextColor),T.style.fontSize="0.75rem",T.style.lineHeight="1rem",T.textContent=us(n.parameters),w.appendChild(T)}m.appendChild(w)}if(r){let W=v("div","persona-flex persona-gap-2 persona-mt-2");W.setAttribute("data-approval-buttons","true");let R=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");R.type="button",R.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",R.style.color=o?.approveButtonTextColor??"#ffffff",R.setAttribute("data-approval-action","approve");let V=Qe(Po.ShieldCheck,14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",R.appendChild(V));let H=document.createTextNode(o?.approveLabel??"Approve");R.appendChild(H);let w=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");w.type="button",w.style.backgroundColor=o?.denyButtonColor??"transparent",w.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",w.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,w.setAttribute("data-approval-action","deny");let T=Qe(Po.ShieldX,14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);T&&(T.style.marginRight="4px",w.appendChild(T));let I=document.createTextNode(o?.denyLabel??"Deny");w.appendChild(I),W.append(R,w),m.appendChild(W)}return a.append(l,m),s.appendChild(a),s}});var fi,mR,nM,mi,fR,gR,Hh,hR,yR,bR,Rh,oM=be(()=>{"use strict";Ye();Bu();fi=require("lucide");ro();ri();na();ya();Ih();mR=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),nM=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},mi=(t,e)=>{nM(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},fR=t=>t?.approval!==!1?t?.approval:void 0,gR=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return pi.get(t)??n==="expanded"},Hh=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},hR=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Ir)?Wu(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??ui(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),l){n.append(" from ");let p=document.createElement("strong");p.textContent=l,n.appendChild(p)}return n},yR=t=>{let e=v("div","persona-approval-resolved"),n=Qe(fi.Ban,15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?ui(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},bR=(t,e,n,o,r,s,a)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",p=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",m=p||u,h=m&&gR(e.id,o),g=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",C=v("button","persona-approval-head");C.type="button",m?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",h?"true":"false"),C.setAttribute("aria-label",h?b:g)):C.setAttribute("data-static","true");let S=v("span","persona-approval-logo"),P=Qe(fi.ShieldCheck,16,"currentColor",2);P&&S.appendChild(P),C.appendChild(S);let M=hR(n,o);if(m){let R=v("span","persona-approval-toggle");R.setAttribute("aria-hidden","true");let V=Qe(fi.ChevronDown,14,"currentColor",2);V&&R.appendChild(V),M.append(" "),M.appendChild(R)}C.appendChild(M),l.appendChild(C);let B=v("div","persona-approval-body");if(m){let R=v("div","persona-approval-details");if(R.setAttribute("data-role","params"),R.hidden=!h,p){let V=v("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,R.appendChild(V)}if(u){let V=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=us(n.parameters),R.appendChild(V)}B.appendChild(R)}if(n.reason){let R=v("p","persona-approval-reason");o?.reasonColor?R.style.color=o.reasonColor:o?.descriptionColor&&(R.style.color=o.descriptionColor);let V=v("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,R.append(V,document.createTextNode(n.reason)),B.appendChild(R)}let A=v("div","persona-approval-actions"),O=null,E=R=>{o?.approveButtonColor&&(R.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(R.style.color=o.approveButtonTextColor)},W=v("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),o?.denyButtonColor&&(W.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(W.style.color=o.denyButtonTextColor),W.append(o?.denyLabel??"Deny"),a){let R=v("div","persona-approval-split"),V=v("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),E(V),V.append(o?.approveLabel??"Always allow",Hh("\u23CE"));let H=v("button","persona-approval-caret");H.type="button",H.setAttribute("data-action","toggle-menu"),H.setAttribute("aria-label","More options"),E(H);let w=Qe(fi.ChevronDown,15,"currentColor",2);w&&H.appendChild(w),R.append(V,H),A.append(R,W),W.append(Hh("Esc"));let T=v("div","persona-approval-menu"),I=v("button","persona-approval-menu-item");I.type="button",I.append("Allow once",Hh("\u2318\u23CE")),T.appendChild(I),O=gs({anchor:R,content:T,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,O),I.addEventListener("click",()=>{mi(t,e.id),r()})}else{let R=v("button","persona-approval-primary persona-approval-primary--solo");R.type="button",R.setAttribute("data-action","allow"),E(R),R.append(o?.approveLabel??"Allow"),A.append(R,W)}return B.appendChild(A),l.appendChild(B),l.addEventListener("click",R=>{let V=R.target instanceof Element?R.target.closest("[data-action]"):null;if(!V)return;let H=V.getAttribute("data-action");if(H==="toggle-params"){let w=l.querySelector('[data-role="params"]');if(w){let T=w.hidden;w.hidden=!T,C.setAttribute("aria-expanded",T?"true":"false"),C.setAttribute("aria-label",T?b:g),pi.set(e.id,T)}return}if(H==="toggle-menu"){O?.toggle();return}if(H==="always"){mi(t,e.id),r({remember:!0});return}if(H==="allow"){mi(t,e.id),r();return}if(H==="deny"){mi(t,e.id),s();return}}),l},Rh=()=>{let t=mR();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let d=fR(a);if(l.status!=="pending"){if(mi(t,o.id),l.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return yR(l)}nM(t,o.id);let p=d?.enableAlwaysAllow===!0,u=bR(t,o,l,d,r,s,p);if(p){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let m=h=>{yx(h)||o.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),mi(t,o.id),h.key==="Escape"?s():h.metaKey||h.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,m),document.addEventListener("keydown",m)}return u}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])mi(t,o);t.latestPendingApprovalId=null}}}});var rM=be(()=>{"use strict";Ih();oM();Bu()});var sM={};Vn(sM,{approvalDetailsExpansionState:()=>pi,createApprovalBubble:()=>Ph,createBuiltInApprovalPlugin:()=>Rh,humanizeToolName:()=>ui,initApprovalUi:()=>kh,updateApprovalDetailsUI:()=>Lh});var iM=be(()=>{"use strict";rM()});function ka(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function cM(t,e){if(e[t])return e[t];for(let n of Object.keys(e))if(n.endsWith("_")&&t.startsWith(n))return e[n]}function AR(t,e){return(e&&cM(t,e))??cM(t,Or)??wR}function MR(t){return/^#[0-9a-fA-F]{6}$/.test(t)?`${t}50`:`color-mix(in srgb, ${t} 31%, transparent)`}function TR(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function ER(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function kR(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function LR(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function PR(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function IR(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function HR(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function RR(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,l.appendChild(d),l}}function Wh(t,e,n,o,r,s,a,l){let d=r.has(t.id),p=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ka(p,o.classNames?.eventRow);let u=a.find(h=>h.renderEventStreamRow);if(u?.renderEventStreamRow&&l){let h=u.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(h)return p.appendChild(h),p}return p.appendChild(m()),p;function m(){let h=v("div",""),g=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",t.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=Qe(d?En.ChevronDown:En.ChevronRight,"14px","currentColor",2);C&&b.appendChild(C);let S=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),P=o.timestampFormat??"relative";S.textContent=P==="relative"?TR(t.timestamp,n):ER(t.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let B=AR(t.type,o.badgeColors),A=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");A.style.backgroundColor=B.bg,A.style.color=B.text,A.style.borderColor=MR(B.text),A.textContent=t.type;let O=o.descriptionFields??xR,E=kR(t.payload,O),W=null;E&&(W=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=E);let R=v("div","persona-flex-1 persona-min-w-0"),V=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),H=Qe(En.Clipboard,"12px","currentColor",1.5);return H&&V.appendChild(H),V.addEventListener("click",async w=>{w.stopPropagation(),await LR(PR(t)),V.innerHTML="";let T=Qe(En.Check,"12px","currentColor",1.5);T&&V.appendChild(T),setTimeout(()=>{V.innerHTML="";let I=Qe(En.Clipboard,"12px","currentColor",1.5);I&&V.appendChild(I)},1500)}),g.appendChild(b),g.appendChild(S),M&&g.appendChild(M),g.appendChild(A),W&&g.appendChild(W),g.appendChild(R),g.appendChild(V),h.appendChild(g),d&&h.appendChild(RR(t,a,l)),h}}function Bh(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=t.renderIconByName??(()=>null),d=r?.features?.scrollToBottom,p=d?.enabled!==!1,u=d?.iconName??"arrow-down",m=d?.label??"",h=r?.features?.eventStream??{},g=s.find(C=>C.renderEventStreamView);if(g?.renderEventStreamView&&r){let C=g.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>b().element,onClose:o});if(C)return{element:C,update:()=>{},destroy:()=>{}}}return b();function b(){let C=h.classNames,S=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ka(S,C?.panel);let P=[],M="",B="",A=null,O=[],E={},W=0,R=pu(),V=0,H=0,w=!1,T=null,I=!1,D=0,G=new Set,z=new Map,K="",Y="",re=null,oe,se,ce,we,ge=null,N=null,ye=null;function ke(){let ve=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Se=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(ka(Se,C?.headerBar),a){N=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),N.style.cursor="help",ge=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ge.textContent="-- tok/s",ye=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ye.style.display="none",ye.style.pointerEvents="none";let Rn=N,tn=ye,it=()=>{if(!tn.textContent)return;let Kt=Rn.getBoundingClientRect(),Ze=ve.getBoundingClientRect();tn.style.left=`${Kt.left-Ze.left}px`,tn.style.top=`${Kt.bottom-Ze.top+4}px`,tn.style.display="block"},_e=()=>{tn.style.display="none"};N.addEventListener("mouseenter",it),N.addEventListener("mouseleave",_e),N.appendChild(ge)}let Ke=v("div","persona-flex-1");oe=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ut=v("option","");ut.value="",ut.textContent="All events (0)",oe.appendChild(ut),se=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),se.type="button",se.title="Copy All";let Cn=Qe(En.ClipboardCopy,"12px","currentColor",1.5);Cn&&se.appendChild(Cn);let wn=v("span","persona-event-copy-all persona-text-xs");wn.textContent="Copy All",se.appendChild(wn),N&&Se.appendChild(N),Se.appendChild(Ke),Se.appendChild(oe),Se.appendChild(se);let Wt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ka(Wt,C?.searchBar);let St=Qe(En.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Et=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");St&&Et.appendChild(St),ce=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ka(ce,C?.searchInput),ce.type="text",ce.placeholder="Search event payloads...",we=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),we.type="button",we.style.display="none";let sn=Qe(En.X,"12px","currentColor",2);return sn&&we.appendChild(sn),Wt.appendChild(Et),Wt.appendChild(ce),Wt.appendChild(we),ve.appendChild(Se),ve.appendChild(Wt),ye&&ve.appendChild(ye),ve}let nt,Ee=s.find(ve=>ve.renderEventStreamToolbar);Ee?.renderEventStreamToolbar&&r?nt=Ee.renderEventStreamToolbar({config:r,defaultRenderer:()=>ke(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Se=>{M=Se,Q(),Te()},onSearchChange:Se=>{B=Se,Q(),Te()}})??ke():nt=ke();let Ne=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ne.style.display="none";function Pe(){if(!a||!ge||!N)return;let ve=a(),Se=IR(ve);ge.textContent=Se;let Ke=HR(ve);ye&&(ye.textContent=Ke,Ke||(ye.style.display="none")),N.setAttribute("aria-label",Ke?`Throughput: ${Se}, ${Ke}`:`Throughput: ${Se}`)}let dt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Xe=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Xe.style.height="100%";let xt=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ka(xt,C?.scrollIndicator),xt.style.display="none",xt.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ge=l(u,"14px","currentColor",2);Ge&&xt.appendChild(Ge);let yt=v("span","");yt.textContent=m,xt.appendChild(yt);let X=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");X.style.display="none",dt.appendChild(Xe),dt.appendChild(X),dt.appendChild(xt),S.setAttribute("tabindex","0"),S.appendChild(nt),S.appendChild(Ne),S.appendChild(dt);function L(){let ve=e.getAll(),Se={};for(let Wt of ve)Se[Wt.type]=(Se[Wt.type]||0)+1;let Ke=Object.keys(Se).sort(),ut=Ke.length!==O.length||!Ke.every((Wt,St)=>Wt===O[St]),vn=!ut&&Ke.some(Wt=>Se[Wt]!==E[Wt]),Cn=ve.length!==Object.values(E).reduce((Wt,St)=>Wt+St,0);if(!ut&&!vn&&!Cn||(O=Ke,E=Se,!oe))return;let wn=oe.value;if(oe.options[0].textContent=`All events (${ve.length})`,ut){for(;oe.options.length>1;)oe.remove(1);for(let Wt of Ke){let St=v("option","");St.value=Wt,St.textContent=`${Wt} (${Se[Wt]||0})`,oe.appendChild(St)}wn&&Ke.includes(wn)?oe.value=wn:wn&&(oe.value="",M="")}else for(let Wt=1;Wt<oe.options.length;Wt++){let St=oe.options[Wt];St.textContent=`${St.value} (${Se[St.value]||0})`}}function j(){let ve=e.getAll();if(M&&(ve=ve.filter(Se=>Se.type===M)),B){let Se=B.toLowerCase();ve=ve.filter(Ke=>Ke.type.toLowerCase().includes(Se)||Ke.payload.toLowerCase().includes(Se))}return ve}function J(){return M!==""||B!==""}function Q(){W=0,V=0,R.resume(),xt.style.display="none"}function de(ve){G.has(ve)?G.delete(ve):G.add(ve),re=ve;let Se=Xe.scrollTop,Ke=R.isFollowing();I=!0,R.pause(),Te(),Xe.scrollTop=Se,Ke&&R.resume(),I=!1}function Me(){return Wr(Xe,50)}function Te(){H=Date.now(),w=!1,Pe(),L();let ve=e.getEvictedCount();ve>0?(Ne.textContent=`${ve.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",P=j();let Se=P.length,Ke=e.getSize()>0;Se===0&&Ke&&J()?(X.textContent=B?`No events matching '${B}'`:"No events matching filter",X.style.display="",Xe.style.display="none"):(X.style.display="none",Xe.style.display=""),se&&(se.title=J()?`Copy Filtered (${Se})`:"Copy All"),p&&!R.isFollowing()&&Se>W&&(V+=Se-W,yt.textContent=m?`${m}${V>0?` (${V})`:""}`:"",xt.style.display=""),W=Se;let ut=e.getAll(),vn=ut.length>0?ut[0].timestamp:0,Cn=new Set(P.map(St=>St.id));for(let St of G)Cn.has(St)||G.delete(St);let wn=M!==K||B!==Y,Wt=z.size===0&&P.length>0;if(wn||Wt||P.length===0){Xe.innerHTML="",z.clear();let St=document.createDocumentFragment();for(let Et=0;Et<P.length;Et++){let sn=Wh(P[Et],Et,vn,h,G,de,s,r);z.set(P[Et].id,sn),St.appendChild(sn)}Xe.appendChild(St),K=M,Y=B,re=null}else{if(re!==null){let Et=z.get(re);if(Et&&Et.parentNode===Xe){let sn=P.findIndex(Rn=>Rn.id===re);if(sn>=0){let Rn=Wh(P[sn],sn,vn,h,G,de,s,r);Xe.insertBefore(Rn,Et),Et.remove(),z.set(re,Rn)}}re=null}let St=new Set(P.map(Et=>Et.id));for(let[Et,sn]of z)St.has(Et)||(sn.remove(),z.delete(Et));for(let Et=0;Et<P.length;Et++){let sn=P[Et];if(!z.has(sn.id)){let Rn=Wh(sn,Et,vn,h,G,de,s,r);z.set(sn.id,Rn),Xe.appendChild(Rn)}}}R.isFollowing()&&(Xe.scrollTop=Xe.scrollHeight)}function Fe(){if(Date.now()-H>=SR){T!==null&&(cancelAnimationFrame(T),T=null),Te();return}w||(w=!0,T=requestAnimationFrame(()=>{T=null,Te()}))}let je=(ve,Se)=>{if(!se)return;se.innerHTML="";let Ke=Qe(ve,"12px","currentColor",1.5);Ke&&se.appendChild(Ke);let ut=v("span","persona-text-xs");ut.textContent="Copy All",se.appendChild(ut),setTimeout(()=>{se.innerHTML="";let vn=Qe(En.ClipboardCopy,"12px","currentColor",1.5);vn&&se.appendChild(vn);let Cn=v("span","persona-text-xs");Cn.textContent="Copy All",se.appendChild(Cn),se.disabled=!1},Se)},lt=async()=>{if(se){se.disabled=!0;try{let ve;J()?ve=P:n?(ve=await n(),ve.length===0&&(ve=e.getAll())):ve=e.getAll();let Se=ve.map(Ke=>{try{return JSON.parse(Ke.payload)}catch{return Ke.payload}});await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),je(En.Check,1500)}catch{je(En.X,1500)}}},ot=()=>{oe&&(M=oe.value,Q(),Te())},Je=()=>{!ce||!we||(we.style.display=ce.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{B=ce.value,Q(),Te()},150))},mt=()=>{!ce||!we||(ce.value="",B="",we.style.display="none",A&&clearTimeout(A),Q(),Te())},Tt=()=>{if(I)return;let ve=Xe.scrollTop,{action:Se,nextLastScrollTop:Ke}=uu({following:R.isFollowing(),currentScrollTop:ve,lastScrollTop:D,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});D=Ke,Se==="resume"?(R.resume(),V=0,xt.style.display="none"):Se==="pause"&&(R.pause(),p&&(yt.textContent=m,xt.style.display=""))},ee=ve=>{let Se=mu({following:R.isFollowing(),deltaY:ve.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Se==="pause"?(R.pause(),p&&(yt.textContent=m,xt.style.display="")):Se==="resume"&&(R.resume(),V=0,xt.style.display="none")},Oe=()=>{p&&(Xe.scrollTop=Xe.scrollHeight,R.resume(),V=0,xt.style.display="none")},$e=ve=>{let Se=ve.target;if(!Se||Se.closest("button"))return;let Ke=Se.closest("[data-event-id]");if(!Ke)return;let ut=Ke.getAttribute("data-event-id");ut&&de(ut)},pt=ve=>{if((ve.metaKey||ve.ctrlKey)&&ve.key==="f"){ve.preventDefault(),ce?.focus(),ce?.select();return}ve.key==="Escape"&&(ce&&document.activeElement===ce?(mt(),ce.blur(),S.focus()):o&&o())};se&&se.addEventListener("click",lt),oe&&oe.addEventListener("change",ot),ce&&ce.addEventListener("input",Je),we&&we.addEventListener("click",mt),Xe.addEventListener("scroll",Tt),Xe.addEventListener("wheel",ee,{passive:!0}),Xe.addEventListener("click",$e),xt.addEventListener("click",Oe),S.addEventListener("keydown",pt);function _t(){A&&clearTimeout(A),T!==null&&(cancelAnimationFrame(T),T=null),w=!1,z.clear(),se&&se.removeEventListener("click",lt),oe&&oe.removeEventListener("change",ot),ce&&ce.removeEventListener("input",Je),we&&we.removeEventListener("click",mt),Xe.removeEventListener("scroll",Tt),Xe.removeEventListener("wheel",ee),Xe.removeEventListener("click",$e),xt.removeEventListener("click",Oe),S.removeEventListener("keydown",pt)}return{element:S,update:Fe,destroy:_t}}}var En,Or,wR,xR,SR,dM=be(()=>{"use strict";Ye();En=require("lucide");ro();Jg();Or={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};Or.execution_error=Or.error;Or.execution_=Or.flow_;Or.turn_=Or.agent_;Or.text_=Or.agent_;wR={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},xR=["flowName","stepName","reasoningText","text","name","tool","toolName"],SR=100});var bc,pM=be(()=>{"use strict";bc=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}}});var vc,uM=be(()=>{"use strict";vc=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}}});function Oh(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ou(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function OR(t,e){return typeof e.type=="string"?e.type:t}function fM(t){let e=mM(t,"tokens")??mM(t,"totalTokens");return e?hM(e.output):void 0}function DR(t){return hM(t.durationMs)}function _R(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var WR,BR,gM,hM,mM,Cc,yM=be(()=>{"use strict";WR=new Set(["step_start","turn_start"]),BR=new Set(["step_complete","turn_complete"]),gM=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),hM=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,mM=(t,e)=>{let n=t[e];return gM(n)?n:void 0};Cc=class{constructor(e=_R){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ou(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!gM(n)){e==="execution_error"&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=OR(e,n),r=this.now();if(o==="execution_start"){this.startRun(r);return}if(WR.has(o)){this.run||this.startRun(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Oh(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ou(l,d),outputTokens:l,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(BR.has(o)){if(!this.run)return;let s=this.run,a=fM(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+Oh(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ou(d,p),outputTokens:d,durationMs:p,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.run)return;let s=this.run,a=fM(n),l=a??s.exactOutputTokens+Oh(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ou(l,p),outputTokens:l,durationMs:p,source:d},this.run=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:DR(n)??o-e.startedAt}}});var bM=be(()=>{"use strict";dM();pM();uM();yM()});var vM={};Vn(vM,{EventStreamBuffer:()=>bc,EventStreamStore:()=>vc,ThroughputTracker:()=>Cc,createEventStreamView:()=>Bh});var CM=be(()=>{"use strict";bM()});var _h,zo,wc=be(()=>{"use strict";_h=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},zo=new _h});function dr(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function wM(t){let e=dr(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Du(t){if(typeof t!="string")return"";let e=t.indexOf(`
238
238
  `);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
239
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function gi(t){let e=wM(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Cs(t){switch(gi(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=wM(t.path);return e?e.toUpperCase():"File"}}}function xc(t){let e=t.markdown??"";return t.file?{filename:cr(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Du(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function Sc(t){let e=new Blob([t.content],{type:t.mime}),n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t.filename,o.click(),URL.revokeObjectURL(n)}var hi=be(()=>{"use strict"});function La(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+_u+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+_u+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=ci({icon:t.icon,label:t.label,className:_u+(n?" persona-artifact-doc-copy-btn":"")}):o=gn({icon:t.icon,label:t.label,className:_u+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Ac(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}var _u,Nu=be(()=>{"use strict";di();Ye();_u="persona-artifact-custom-action-btn"});function xM(t){let e=document.createElementNS(Nh,"svg");e.setAttribute("class",Vt("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Nh,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Nh,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var Nh,SM=be(()=>{"use strict";Ye();Nh="http://www.w3.org/2000/svg"});function AM(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),vs(t,e,0)}var MM=be(()=>{"use strict";Tu()});function Pa(t){t&&Vh.delete(t)}function FR(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?Cs(e):t.artifactType==="component"?"Component":"Document"}function Ia(t,e,n){let o=FR(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=Vh.get(a);t.status!=="complete"&&l===void 0&&(l=kM(),Vh.set(a,l));let d=l===void 0?0:Math.max(0,kM()-l),p=t.artifactType==="component",u=!p&&typeof t.markdown=="string"?t.markdown:"",m=p?0:u.length,h=p||u===""?0:u.split(`
239
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function gi(t){let e=wM(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Cs(t){switch(gi(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=wM(t.path);return e?e.toUpperCase():"File"}}}function xc(t){let e=t.markdown??"";return t.file?{filename:dr(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Du(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function Sc(t){let e=new Blob([t.content],{type:t.mime}),n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t.filename,o.click(),URL.revokeObjectURL(n)}var hi=be(()=>{"use strict"});function La(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+_u+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+_u+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=ci({icon:t.icon,label:t.label,className:_u+(n?" persona-artifact-doc-copy-btn":"")}):o=gn({icon:t.icon,label:t.label,className:_u+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Ac(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}var _u,Nu=be(()=>{"use strict";di();Ye();_u="persona-artifact-custom-action-btn"});function xM(t){let e=document.createElementNS(Nh,"svg");e.setAttribute("class",Vt("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Nh,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Nh,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var Nh,SM=be(()=>{"use strict";Ye();Nh="http://www.w3.org/2000/svg"});function AM(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),vs(t,e,0)}var MM=be(()=>{"use strict";Tu()});function Pa(t){t&&Vh.delete(t)}function FR(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?Cs(e):t.artifactType==="component"?"Component":"Document"}function Ia(t,e,n){let o=FR(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=Vh.get(a);t.status!=="complete"&&l===void 0&&(l=kM(),Vh.set(a,l));let d=l===void 0?0:Math.max(0,kM()-l),p=t.artifactType==="component",u=!p&&typeof t.markdown=="string"?t.markdown:"",m=p?0:u.length,h=p||u===""?0:u.split(`
240
240
  `).length,g=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:g,chars:m,lines:h,elapsedMs:d,content:()=>p?"":u,surface:n};try{let C=s(b);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function VR(t){t.className=Fh,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function yi(t,e,n){let o=t.querySelector(`:scope > .${Fh}`);o||(o=v("span",Fh),t.appendChild(o)),o.getAttribute(EM)!==e.label&&(VR(o),AM(o,e.label,n),o.setAttribute(EM,e.label));let r=t.querySelector(`:scope > .${TM}`),s=e.detail;s?(r||(r=v("span",TM),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var Fh,TM,EM,Vh,kM,Fu=be(()=>{"use strict";Ye();hi();MM();Fh="persona-artifact-status-label",TM="persona-artifact-status-detail",EM="data-artifact-status-label",Vh=new Map,kM=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function UR(t,e){let n=(t||"").trim().toLowerCase();if(n&&Vu[n])return Vu[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Vu[r])return Vu[r]}}return null}function $u(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let d=l.re.exec(t);if(d&&d.index===o&&d[0].length>0){s(o);let p=l.map?l.map(d[0]):l.type;n.push({type:p,value:d[0]}),o+=d[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}function LM(t){return $u(t,jR)}function GR(t){let e=$u(t,KR);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}function PM(t){let e=$u(t,YR),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}function XR(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,d=t.slice(r,l);for(let u of $u(d,QR))e.push(u);r=l;let p=/^<\s*(script|style)\b/i.exec(d);if(p&&!/\/>\s*$/.test(d)){let u=p[1].toLowerCase(),h=new RegExp("</\\s*"+u+"\\s*>","i").exec(t.slice(r)),g=h?r+h.index:o,b=t.slice(r,g),C=u==="script"?LM(b):PM(b);for(let S of C)e.push(S);r=g}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function JR(t,e){switch(e){case"html":return XR(t);case"css":return PM(t);case"js":return LM(t);case"json":return GR(t)}}function ZR(t){let e=$C(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=$R[r];if(a){let l=v("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
241
241
  `);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
242
242
  `)),n=v("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function IM(t,e,n){let o=t.length<=zR?UR(e,n):null,r=o?JR(t,o):[{type:"plain",value:t}];return ZR(r)}var $R,zR,Vu,qR,jR,KR,YR,QR,HM=be(()=>{"use strict";Ye();$R={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},zR=15e4,Vu={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};qR=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),jR=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>qR.has(t)?"keyword":"plain"}];KR=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];YR=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];QR=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}]});var RM,$h,WM,zh=be(()=>{"use strict";RM=null,$h=t=>{RM=t.componentRegistry},WM=()=>RM});function Mc(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Du(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}function eW(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function BM(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||Uh||s){o();return}Uh=!0;let a=eW(n);t.style.setProperty("view-transition-name",a);let l=()=>{Uh=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}function oW(t){let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function rW(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}function iW(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function aW(t){return`
243
- <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function lW(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(xM());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function cW(t,e,n,o,r,s){let a=null,l=0,d=!1,p=new Set,u=()=>{p.forEach(B=>clearTimeout(B)),p.clear()},m=(B,A)=>{let O=setTimeout(()=>{p.delete(O),!(typeof document>"u")&&B()},A);p.add(O)},h=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||d)return;let B=lW(r,s,o);a=B.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(B.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(h,sW))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):e.removeEventListener("load",M)},S=()=>{if(d||(d=!0,C(),u(),!a))return;let B=Math.max(0,o.minVisibleMs-(Date.now()-l));B>0?m(b,B):b()};function P(B){if(n===null)return;let A=B.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||B.source===e.contentWindow&&S()}function M(){let B=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};B(()=>B(()=>S()))}return m(g,o.delayMs),m(S,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):e.addEventListener("load",M),()=>{d=!0,u(),C(),h()}}function zu(t,e){let{config:n}=e,o=e.registry??WM()??$o,r=e.bodyLayout,s=n.markdown?Qd(n.markdown):null,a=Jd(n.sanitize),l=t,d=!1,p=K=>{let Y=Ao()!==null;s&&!Y&&!d&&(d=!0,ea(()=>z(l)));let re=s?s(K):Pr(K);return s&&Y&&a?a(re):re},u=v("div","persona-artifact-preview-body"),m=null,h=null,g=null,b=()=>{g&&(g(),g=null),m=null,h=null},C=null,S=null,P=null,M=!1,B=()=>{C=null,S=null,P=null,M=!1},A=null,O=null,E=()=>{A=null,O=null},W=40,R=0,V=K=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>K()):setTimeout(K,0),H=K=>K.scrollHeight-K.clientHeight-K.scrollTop<=W,w=K=>{if(!r)return;let Y=K.scrollHeight-K.clientHeight>1,re=K.scrollHeight-K.clientHeight-K.scrollTop;K.classList.toggle("persona-artifact-fade-top",r.fadeTop&&Y&&K.scrollTop>1),K.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&Y&&re>1)},T=K=>{R||(R=V(()=>{R=0,K.scrollTop=K.scrollHeight,w(K)}))},I=(K,Y,re,oe)=>{let se=!!r,ce=re.id+"|"+(se?"w":"p");if(!C||P!==ce||C.parentElement!==u){b(),E(),u.replaceChildren();let N=v("pre",tW+" persona-code-pre"),ye=v("code","persona-code");if(N.appendChild(ye),se){let ke=v("div","persona-artifact-source-window");if(ke.appendChild(N),u.appendChild(ke),!(r?.overflow==="clip")&&typeof ke.addEventListener=="function"){let Ee=()=>ke.scrollHeight-ke.clientHeight>1;ke.addEventListener("scroll",()=>{H(ke)&&(M=!1),w(ke)},{passive:!0}),ke.addEventListener("wheel",Ne=>{Ee()&&Ne.deltaY<0&&(M=!0)},{passive:!0}),ke.addEventListener("touchmove",()=>{Ee()&&(M=!0)},{passive:!0})}C=ke}else u.appendChild(N),C=N;S=ye,P=ce}let we=se?C:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",oe),we.classList.toggle("persona-artifact-source-window--clip",oe&&r?.overflow==="clip"));let ge=we?H(we):!0;if(S.replaceChildren(IM(K,Y?.language,Y?.path)),we){let N=re.status!=="complete";oe&&N&&r?.followOutput&&!M&&ge?T(we):N||(M=!1),w(we)}},D=K=>{b(),B(),E(),u.replaceChildren();let Y=v("div",nW);Y.innerHTML=p(K),u.appendChild(Y)},G=K=>{let Y=K.id,re=n.features?.artifacts,oe=Ia(K,re,"status-body");if(A&&O===Y&&A.parentElement===u){let we=A.querySelector(".persona-artifact-status-view-text");we&&yi(we,oe,re);return}b(),B(),u.replaceChildren();let se=v("div","persona-artifact-status-view"),ce=v("div","persona-artifact-status-view-text");yi(ce,oe,re),se.appendChild(ce),u.appendChild(se),A=se,O=Y},z=K=>{l=K;let Y=e.resolveViewMode?.(K)??r?.viewMode??"rendered",re=K.artifactType==="markdown"?K.file:void 0,oe=K.status!=="complete";oe||Pa(K.id);let se=oe?r?.streamingHeight:r?.completeHeight,ce=!!r&&typeof se=="number";if(r?.streamingView==="status"&&oe){G(K);return}if(re){let ge=Du(K.markdown??""),N=gi(re),ye=n.features?.artifacts?.filePreview?.enabled!==!1;if(!oe&&Y==="rendered"&&ye&&(N==="html"||N==="svg")){let nt=K.id+"\0"+ge;if(m&&h===nt&&m.parentElement===u)return;B(),E(),b(),u.replaceChildren();let Ee=n.features?.artifacts?.filePreview,Ne=Ee?.iframeSandbox??"allow-scripts";!Ee?.dangerouslyAllowSameOrigin&&Ne.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ne=Ne.split(/\s+/).filter(Ge=>Ge&&Ge!=="allow-same-origin").join(" "));let Pe=rW(Ee?.loading),dt=v("div","persona-artifact-frame"),Xe=v("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Ne),Xe.setAttribute("data-artifact-id",K.id);let xt=null;Pe.enabled&&Pe.injectReadySignal?(xt=iW(),Xe.srcdoc=ge+aW(xt)):Xe.srcdoc=ge,dt.appendChild(Xe),u.appendChild(dt),Pe.enabled&&(g=cW(dt,Xe,xt,Pe,K.id,n)),m=dt,h=nt;return}if(b(),!oe&&N==="markdown"&&Y==="rendered"){D(ge);return}I(ge,{language:re.language,path:re.path},K,ce);return}if(K.artifactType==="markdown"){if(Y==="source"){b(),I(K.markdown??"",void 0,K,ce);return}D(K.markdown??"");return}b(),B(),E(),u.replaceChildren();let we=K.component?o.get(K.component):void 0;if(we){let N={message:{id:K.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ye=we(K.props??{},N);if(ye){u.appendChild(ye);return}}catch{}}u.appendChild(oW(K))};return z(t),{el:u,update(K){z(K)},destroy(){b()}}}var Uh,tW,nW,sW,Uu=be(()=>{"use strict";Ye();SM();hi();Fu();HM();Xd();ti();Ff();wc();zh();Uh=!1;tW="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",nW="persona-text-sm persona-leading-relaxed persona-markdown-bubble";sW=220});function OM(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},d=m=>{let h=m;return s.findIndex(g=>g===h||g.contains(h))},p=m=>{let h=d(m.target);if(h<0)return;let g=h;if(m.key===r)g=Math.min(h+1,s.length-1);else if(m.key===o)g=Math.max(h-1,0);else if(m.key==="Home")g=0;else if(m.key==="End")g=s.length-1;else return;m.preventDefault(),g!==h&&e.onSelect(g)},u=m=>{let h=d(m.target);h>=0&&l(s[h])};return t.addEventListener("keydown",p),t.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(m,h){if(s=m,m.forEach((g,b)=>{g.setAttribute("role","tab");let C=b===h;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||h<0&&b===0?0:-1}),a){let g=(h>=0?m[h]:void 0)??m[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){t.removeEventListener("keydown",p),t.removeEventListener("focusin",u)}}}var DM=be(()=>{"use strict"});function qh(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),p=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:u,end:m}=p(n?.tabFade),h=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{h?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),w?.closeMenu()};h&&h.addEventListener("click",()=>{g(),e.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let S=v("span","persona-text-xs persona-font-medium persona-truncate");S.textContent=s;let P=gn({icon:"x",label:a});P.addEventListener("click",()=>{g(),e.onDismiss?.()});let M="rendered",B=bu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{M=ee==="source"?"source":"rendered",Je()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),O=n?.documentToolbarShowCopyLabel===!0,E=n?.documentToolbarShowCopyChevron===!0,W=n?.documentToolbarCopyMenuItems,R=!!(E&&W&&W.length>0),V=null,H,w=null;if(r&&(O||E)&&!R){if(H=O?ci({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E){let ee=Qe(ws.ChevronDown,14,"currentColor",2);ee&&H.appendChild(ee)}}else r&&R?(w=xA({label:"Copy",icon:"copy",iconSize:14,iconOnly:!O,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(W??[]).map(ee=>({id:ee.id,label:ee.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:ee=>{we(ee)}}),V=w.element,H=w.primaryButton):r?H=gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(H=gn({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&H.classList.add("persona-hidden"));let T=r?gn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):gn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||T.classList.add("persona-hidden");let I=r?gn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):gn({icon:"x",label:a}),D=gn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&D.classList.add("persona-hidden");let G=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),z=t.features?.artifacts?.toolbarActions??[],K=()=>{let ee=Ge.find(Ke=>Ke.id===yt)??Ge[Ge.length-1],Oe=ee?.id??null,$e=ee?.artifactType==="markdown"?ee.markdown??"":"",pt=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"",{filename:_t,mime:ve,content:Se}=xc({title:ee?.title,markdown:ee?.markdown??"",file:ee?.file});return{markdown:$e,jsonPayload:pt,id:Oe,file:ee?.file,suggestedFilename:_t,mime:ve,content:Se}},Y=()=>{let{suggestedFilename:ee,mime:Oe,content:$e}=K();$e&&Sc({filename:ee,mime:Oe,content:$e})},re=ee=>{let{id:Oe,...$e}=K();return{actionId:ee,artifactId:Oe,...$e}},oe=async()=>{let ee=Ge.find(Oe=>Oe.id===yt)??Ge[Ge.length-1];try{return await navigator.clipboard.writeText(Mc(ee)),!0}catch{return!1}},se=null,ce=()=>{se?.();let ee=H.querySelector("svg"),Oe=Number(ee?.getAttribute("width"))||16,$e=Qe(ws.Check,Oe,"currentColor",2);if(!ee||!$e)return;ee.replaceWith($e);let pt=H.querySelector("span");pt&&(pt.textContent="Copied");let _t=setTimeout(()=>se?.(),2e3);se=()=>{clearTimeout(_t),$e.replaceWith(ee),pt&&(pt.textContent="Copy"),se=null}};H.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&R){try{if(await ee(re("primary"))===!1){await oe()&&ce();return}ce()}catch{}return}await oe()&&ce()});async function we(ee){let Oe=n?.onDocumentToolbarCopyMenuSelect;try{if(Oe&&await Oe(re(ee))!==!1)return;if(ee==="download"){Y();return}let{markdown:$e,jsonPayload:pt}=K();ee==="markdown"||ee==="md"?await navigator.clipboard.writeText($e):ee==="json"||ee==="source"?await navigator.clipboard.writeText(pt):await navigator.clipboard.writeText($e||pt),ce()}catch{}}T.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Je()}),I.addEventListener("click",()=>{g(),e.onDismiss?.()});let ge=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),V?A.append(V,T,I):A.append(H,T,I),A.insertBefore(G,I),A.insertBefore(D,I),C.append(B.element,ge,A);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(H,G,D,P),C.appendChild(S),C.appendChild(ee)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let N=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");d&&N.style.setProperty("--persona-artifact-tab-fade-size",d);let ye=t.features?.artifacts?.renderTabBar,ke=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),nt=OM(N,{onSelect:ee=>e.onSelect(Ge[ee].id)}),Ee=ee=>{let Oe=ee.scrollWidth-ee.clientWidth,$e=Oe>1,pt=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",u&&$e&&pt>1),ee.classList.toggle("persona-artifact-tab-fade-end",m&&$e&&pt<Oe-1)},Ne=0,Pe=()=>{if(Ne)return;let ee=()=>{Ne=0,Ee(N)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};N.addEventListener("scroll",()=>Pe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Ee(N)).observe(N);let dt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Xe=()=>{dt.scrollLeft=0},xt=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Xe):setTimeout(Xe,0)};if(l){for(let ee of[N,ke])ee.style.paddingLeft=l,ee.style.paddingRight=l;dt.style.padding=l}b.appendChild(C),b.appendChild(N),b.appendChild(ke),b.appendChild(dt);let Ge=[],yt=null,X=!1,L=!1,j=!0,J=!1,Q=null,de="",Me=null,Te=!1,Fe=ee=>ee.artifactType==="markdown"&&!!ee.file||r?M:"rendered",je=ee=>{r||(ee&&!Te?(C.insertBefore(B.element,S),Te=!0):!ee&&Te&&(B.element.remove(),Te=!1))},lt=()=>yt&&Ge.find(ee=>ee.id===yt)||Ge[Ge.length-1],ot=()=>{let ee=Ac(lt());if(!ee){G.replaceChildren();return}let Oe=z.filter($e=>$e.visible===void 0||$e.visible(ee)).map($e=>La($e,{documentChrome:r,onClick:()=>{let pt=Ac(lt());if(pt)try{Promise.resolve($e.onClick(pt)).catch(()=>{})}catch{}}}));G.replaceChildren(...Oe)},Je=()=>{ot();let ee=r&&Ge.length<=1,Oe=!!ye;if(N.classList.toggle("persona-hidden",ee||Oe),ke.classList.toggle("persona-hidden",ee||!Oe),Oe&&ye){let _t=Ge.map(ve=>ve.id).join("|")+" "+(yt??"");if(_t!==de){de=_t;let ve=ye({records:Ge,selectedId:yt,onSelect:e.onSelect});ke.firstElementChild!==ve&&ke.replaceChildren(ve)}}else{nt.beforeRender(),N.replaceChildren();let _t=[],ve=-1;for(let[Se,Ke]of Ge.entries()){let ut=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ut.type="button";let vn=Ke.artifactType==="markdown"?Ke.file:void 0,Cn=vn?cr(vn.path):Ke.title||Ke.id.slice(0,8),wn=vn?.path||Ke.title||Cn;ut.textContent=Cn,ut.title=wn,ut.setAttribute("aria-label",wn),Ke.id===yt&&(ut.classList.add("persona-bg-persona-container","persona-border-persona-border"),ve=Se),ut.addEventListener("click",()=>e.onSelect(Ke.id)),N.appendChild(ut),_t.push(ut)}if(nt.render(_t,ve),ve>=0&&yt!==Q){Q=yt;let Se=_t[ve];typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({block:"nearest",inline:"nearest"})}Ee(N)}let $e=yt&&Ge.find(_t=>_t.id===yt)||Ge[Ge.length-1];if(!$e){dt.replaceChildren(),Me?.destroy(),Me=null,je(!1);return}let pt=$e.artifactType==="markdown"?$e.file:void 0;if(je(!!pt&&gi(pt)!=="other"),r){let _t=pt?Cs(pt):$e.artifactType==="markdown"?"MD":$e.component??"Component",ve=($e.title||"Document").trim(),Se=pt?cr(pt.path):ve.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${Se} \xB7 ${_t}`}else S.textContent=pt?cr(pt.path):s;Me?(Me.el.parentElement!==dt&&dt.replaceChildren(Me.el),Me.update($e)):(Me=zu($e,{config:t,resolveViewMode:Fe}),dt.replaceChildren(Me.el)),dt.classList.toggle("persona-artifact-content-flush",!!dt.querySelector(".persona-code-pre"))},mt=()=>{let ee=Ge.length>0;if(b.classList.toggle("persona-hidden",!ee),h){let pt=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&pt&&X?(h.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},Tt=()=>{J=!1,Je(),mt()};return{element:b,backdrop:h,update(ee){let Oe=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,$e=Oe!==yt;Ge=ee.artifacts,yt=Oe,Ge.length>0&&(X=!0),J=!0,j&&Tt(),$e&&Xe()},setMobileOpen(ee){X=ee,!ee&&h?(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):mt()},setExpanded(ee){ee!==L&&(L=ee,xt());let Oe=Qe(ee?ws.Minimize:ws.Maximize,16,"currentColor",2);Oe&&D.replaceChildren(Oe);let $e=ee?"Collapse artifacts panel":"Expand artifacts panel";D.setAttribute("aria-label",$e),D.title=$e},setExpandToggleVisible(ee){D.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||H.classList.toggle("persona-hidden",!ee)},setRefreshButtonVisible(ee){T.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){z=ee,ot()},setTabFade(ee){let Oe=p(ee);Oe.start===u&&Oe.end===m||(u=Oe.start,m=Oe.end,Ee(N))},setRenderTabBar(ee){ee!==ye&&(ye=ee,de="",Je())},setVisible(ee){ee!==j&&(j=ee,ee&&J&&Tt())},destroy(){Me?.destroy(),Me=null}}}var ws,_M=be(()=>{"use strict";Ye();hi();Nu();Uu();ws=require("lucide");ro();di();DM()});function NM(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?cr(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",d=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,p=n?Cs(n):l==="component"?"Component":"Document",u=document.createElement("div");u.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",u.tabIndex=0,u.setAttribute("role","button"),u.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&u.setAttribute("data-open-artifact",s);let m=document.createElement("div");m.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-muted, #9ca3af)",m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let h=document.createElement("div");h.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=e?.config?.features?.artifacts,S={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},P=Ia(S,C,"card");yi(b,P,C)}else s&&Pa(s),b.textContent=p;if(h.append(g,b),u.append(m,h),a==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let P={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let M of C)try{if(M.visible===void 0||M.visible(P)){let B=La(M);B.setAttribute("data-artifact-custom-action",M.id),B.className=`${B.className} persona-flex-shrink-0`,u.append(B)}}catch{}}let S=ci({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",s),u.append(S)}return u}var Tc,jh=be(()=>{"use strict";hi();Fu();di();Nu();Tc=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>NM(t,e)});if(l)return l}return NM(t,e)}});function Kh(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=xs.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Gh(t){return xs.has(t)}function dW(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function FM(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?cr(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Cs(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function pW(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}function bW(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:VM,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let P of a)P.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let d=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!d||Math.abs(d-e)<1){l(),r();return}let p=Math.abs(e-d),u=Math.round(Math.min(gW,Math.max(fW,uW+p*mW))),m=Math.round(u*yW),h=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=h?h.animate([{opacity:0},{opacity:1}],{duration:$M,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${d}px`}],{duration:u,easing:hW});t.style.height=`${d}px`;let C=!1,S=()=>{C||(C=!0,l(),r())};Promise.allSettled([b.finished,g?.finished].filter(Boolean)).then(S),window.setTimeout(S,Math.max(u,m+$M)+120)},VM)}function vW(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function CW(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:e?.followOutput!==!1,p,u,m=e?.fadeMask;m===!0?(p=!0,u=!0):m===!1?(p=!1,u=!1):m&&typeof m=="object"?(p=m.top===!0,u=m.bottom===!0):l==="clip"?(p=!1,u=!0):(p=!0,u=!0);let h=e?.transition==="none"?"none":"auto",g=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:l,fadeTop:p,fadeBottom:u,transition:h,completeDisplay:g}}function zM(t,e){let n=dW(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=vW(o),d=o?.inlineActions??[],p=CW(o),u=p.completeDisplay==="card",m=null,h=n,g=v("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let b=oe=>Tc(pW(oe),e),C=null,S=oe=>{C?.destroy(),C=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Ec),g.replaceChildren(b(oe)),xs.set(g,se=>{g.replaceChildren(b(se))})};if(u&&n.status==="complete")return S(n),g;let P=zu(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=P;let M=v("div","persona-artifact-inline-body");M.appendChild(P.el);let B=oe=>{let se=oe.status!=="complete",ce=se?p.streamingHeight:p.completeHeight,we=typeof ce=="number";we?g.style.setProperty(Ec,`${ce}px`):g.style.removeProperty(Ec);let ge=!!P.el.querySelector(".persona-code-pre"),N=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");M.classList.toggle("persona-artifact-content-flush",ge),M.classList.toggle("persona-artifact-inline-body--sized",we&&N),M.classList.toggle("persona-artifact-inline-body--cap",!se&&!N&&typeof p.completeHeight=="number")},A=n.status,O=(oe,se)=>{A!=="complete"&&oe.status==="complete"?(typeof p.completeHeight=="number"?g.style.setProperty(Ec,`${p.completeHeight}px`):g.style.removeProperty(Ec),BM(M,se?.suppressTransition?"none":p.transition,oe.id,()=>{P.update(oe),B(oe)})):P.update(oe),B(oe),A=oe.status};B(n);let E=p.overflow==="clip"&&a&&!!n.id;if(E&&(M.setAttribute("data-expand-artifact-inline",n.id),M.setAttribute("role","button"),M.setAttribute("tabindex","0"),M.classList.add("persona-cursor-pointer"),M.setAttribute("aria-label",`Open ${FM(n).title} in panel`)),!r)return g.appendChild(M),xs.set(g,O),g;let W=v("div","persona-artifact-inline-chrome");W.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let R=v("div","persona-artifact-inline-chrome-lead"),V=v("span","persona-flex persona-items-center persona-flex-shrink-0"),H=Qe(UM.FileText,16,"currentColor",2);H&&V.appendChild(H);let w=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),T=v("span","persona-artifact-inline-type");R.append(V,w,T);let I=v("div","persona-artifact-inline-chrome-actions"),D=v("span","persona-flex persona-items-center persona-gap-1"),G=()=>m??p.viewMode,z=l?bu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:G(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:oe=>{let se=oe==="source"?"source":"rendered";se!==G()&&(m=se,P.update(h),B(h))}}):null,K=s?gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;K&&n.id&&K.setAttribute("data-copy-artifact",n.id);let Y=a?gn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Y&&n.id&&Y.setAttribute("data-expand-artifact-inline",n.id),I.appendChild(D),z&&I.appendChild(z.element),K&&I.appendChild(K),Y&&I.appendChild(Y),W.append(R,I),g.append(W,M);let re=oe=>{let{title:se,typeLabel:ce}=FM(oe);w.textContent=se,w.title=se,E&&M.setAttribute("aria-label",`Open ${se} in panel`);let we=oe.status!=="complete";if(we){T.classList.contains("persona-artifact-inline-status")||(T.className="persona-artifact-inline-status",T.removeAttribute("data-preserve-animation"),T.replaceChildren());let ge=Ia(oe,o,"inline-chrome");yi(T,ge,o)}else Pa(oe.id),T.className="persona-artifact-inline-type",T.removeAttribute("data-preserve-animation"),T.replaceChildren(),T.textContent=ce;if(K&&K.classList.toggle("persona-hidden",we),z){let ge=oe.artifactType==="markdown"?oe.file:void 0,N=!1;if(!we&&ge&&p.viewMode!=="source"){let ye=gi(ge);ye==="markdown"?N=!0:(ye==="html"||ye==="svg")&&(N=o?.filePreview?.enabled!==!1)}z.element.classList.toggle("persona-hidden",!N),z.setSelected(G())}if(D.replaceChildren(),!we&&d.length>0){let ge=Ac(oe);if(ge)for(let N of d)try{if(N.visible===void 0||N.visible(ge)){let ye=La(N,{documentChrome:!0});ye.setAttribute("data-artifact-custom-action",N.id),ye.classList.add("persona-flex-shrink-0"),D.appendChild(ye)}}catch{}}};return re(n),xs.set(g,(oe,se)=>{if(u&&A!=="complete"&&oe.status==="complete"){let ce=g.isConnected?g.getBoundingClientRect().height:0;A="complete";let we=oe,ge=!1,N=ye=>{we=ye,ge=!0};xs.set(g,N),bW(g,ce,{swap:()=>{S(we),ge=!1,xs.set(g,N)},onSettled:()=>{ge?S(we):xs.set(g,ye=>{g.replaceChildren(b(ye))})}});return}(oe.status!=="complete"||oe.id!==h.id)&&(m=null),h=oe,O(oe,se),re(oe)}),g}var UM,xs,VM,uW,mW,fW,gW,hW,$M,yW,Ec,Yh,qM=be(()=>{"use strict";Ye();hi();Fu();Nu();di();UM=require("lucide");ro();Uu();jh();xs=new WeakMap;VM=180,uW=240,mW=.8,fW=300,gW=500,hW="cubic-bezier(0.2, 0, 0, 1)",$M=240,yW=.35;Ec="--persona-artifact-inline-body-height";Yh=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>zM(t,e)});if(l)return l}return zM(t,e)}});var jM=be(()=>{"use strict";_M();qM();jh();Uu();hi();zh();ti();wp()});var KM={};Vn(KM,{PersonaArtifactCard:()=>Tc,PersonaArtifactInline:()=>Yh,__provideMarkdownParsers:()=>_f,__setIconsExtraLoader:()=>mg,artifactCopyText:()=>Mc,createArtifactPane:()=>qh,downloadInfoFor:()=>xc,hasLiveInlineArtifactBlock:()=>Gh,initArtifactsUi:()=>$h,triggerArtifactDownload:()=>Sc,updateInlineArtifactBlocks:()=>Kh});var GM=be(()=>{"use strict";jM()});var Yu,sT,iT=be(()=>{"use strict";Ye();Yu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},sT=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Yu[a]??Yu.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),p=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=l.title,d.appendChild(p),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,d.appendChild(b)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${b.name}`;let S=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");S.textContent=b.label,C.appendChild(S);let P=b.type??"text",M;P==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=P),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${e.id}-${a}-${b.name}`,M.name=b.name,M.placeholder=b.placeholder??"",b.required&&(M.required=!0),C.appendChild(M),u.appendChild(C)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",m.appendChild(h),m.appendChild(g),u.appendChild(m),s.replaceChildren(d,u),u.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",S=new FormData(u),P={};S.forEach((M,B)=>{P[B]=M}),P.type=a,g.disabled=!0,h.textContent="Submitting\u2026";try{let M=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let B=await M.json();h.textContent=B.message??"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await o.sendMessage(String(B.nextPrompt))}catch(M){h.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})}});var aT={};Vn(aT,{enhanceWithForms:()=>sT,formDefinitions:()=>Yu});var lT=be(()=>{"use strict";iT()});function vT(){let t=document.createElement("div");t.className="persona-history-sr-only",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.setAttribute("data-persona-history-live-region","");let e;return{element:t,announce(n){e!==void 0&&clearTimeout(e),t.textContent="",e=setTimeout(()=>{e=void 0,t.textContent=n},0)},destroy(){e!==void 0&&clearTimeout(e),t.remove()}}}var CT=be(()=>{"use strict"});var wT,xT=be(()=>{"use strict";wT=`
243
+ <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function lW(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(xM());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function cW(t,e,n,o,r,s){let a=null,l=0,d=!1,p=new Set,u=()=>{p.forEach(B=>clearTimeout(B)),p.clear()},m=(B,A)=>{let O=setTimeout(()=>{p.delete(O),!(typeof document>"u")&&B()},A);p.add(O)},h=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||d)return;let B=lW(r,s,o);a=B.el,t.appendChild(a),l=Date.now(),o.label!==!1&&m(B.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),m(h,sW))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",P):e.removeEventListener("load",M)},S=()=>{if(d||(d=!0,C(),u(),!a))return;let B=Math.max(0,o.minVisibleMs-(Date.now()-l));B>0?m(b,B):b()};function P(B){if(n===null)return;let A=B.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||B.source===e.contentWindow&&S()}function M(){let B=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};B(()=>B(()=>S()))}return m(g,o.delayMs),m(S,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",P):e.addEventListener("load",M),()=>{d=!0,u(),C(),h()}}function zu(t,e){let{config:n}=e,o=e.registry??WM()??zo,r=e.bodyLayout,s=n.markdown?Qd(n.markdown):null,a=Jd(n.sanitize),l=t,d=!1,p=K=>{let Y=Mo()!==null;s&&!Y&&!d&&(d=!0,ea(()=>z(l)));let re=s?s(K):Pr(K);return s&&Y&&a?a(re):re},u=v("div","persona-artifact-preview-body"),m=null,h=null,g=null,b=()=>{g&&(g(),g=null),m=null,h=null},C=null,S=null,P=null,M=!1,B=()=>{C=null,S=null,P=null,M=!1},A=null,O=null,E=()=>{A=null,O=null},W=40,R=0,V=K=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>K()):setTimeout(K,0),H=K=>K.scrollHeight-K.clientHeight-K.scrollTop<=W,w=K=>{if(!r)return;let Y=K.scrollHeight-K.clientHeight>1,re=K.scrollHeight-K.clientHeight-K.scrollTop;K.classList.toggle("persona-artifact-fade-top",r.fadeTop&&Y&&K.scrollTop>1),K.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&Y&&re>1)},T=K=>{R||(R=V(()=>{R=0,K.scrollTop=K.scrollHeight,w(K)}))},I=(K,Y,re,oe)=>{let se=!!r,ce=re.id+"|"+(se?"w":"p");if(!C||P!==ce||C.parentElement!==u){b(),E(),u.replaceChildren();let N=v("pre",tW+" persona-code-pre"),ye=v("code","persona-code");if(N.appendChild(ye),se){let ke=v("div","persona-artifact-source-window");if(ke.appendChild(N),u.appendChild(ke),!(r?.overflow==="clip")&&typeof ke.addEventListener=="function"){let Ee=()=>ke.scrollHeight-ke.clientHeight>1;ke.addEventListener("scroll",()=>{H(ke)&&(M=!1),w(ke)},{passive:!0}),ke.addEventListener("wheel",Ne=>{Ee()&&Ne.deltaY<0&&(M=!0)},{passive:!0}),ke.addEventListener("touchmove",()=>{Ee()&&(M=!0)},{passive:!0})}C=ke}else u.appendChild(N),C=N;S=ye,P=ce}let we=se?C:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",oe),we.classList.toggle("persona-artifact-source-window--clip",oe&&r?.overflow==="clip"));let ge=we?H(we):!0;if(S.replaceChildren(IM(K,Y?.language,Y?.path)),we){let N=re.status!=="complete";oe&&N&&r?.followOutput&&!M&&ge?T(we):N||(M=!1),w(we)}},D=K=>{b(),B(),E(),u.replaceChildren();let Y=v("div",nW);Y.innerHTML=p(K),u.appendChild(Y)},G=K=>{let Y=K.id,re=n.features?.artifacts,oe=Ia(K,re,"status-body");if(A&&O===Y&&A.parentElement===u){let we=A.querySelector(".persona-artifact-status-view-text");we&&yi(we,oe,re);return}b(),B(),u.replaceChildren();let se=v("div","persona-artifact-status-view"),ce=v("div","persona-artifact-status-view-text");yi(ce,oe,re),se.appendChild(ce),u.appendChild(se),A=se,O=Y},z=K=>{l=K;let Y=e.resolveViewMode?.(K)??r?.viewMode??"rendered",re=K.artifactType==="markdown"?K.file:void 0,oe=K.status!=="complete";oe||Pa(K.id);let se=oe?r?.streamingHeight:r?.completeHeight,ce=!!r&&typeof se=="number";if(r?.streamingView==="status"&&oe){G(K);return}if(re){let ge=Du(K.markdown??""),N=gi(re),ye=n.features?.artifacts?.filePreview?.enabled!==!1;if(!oe&&Y==="rendered"&&ye&&(N==="html"||N==="svg")){let nt=K.id+"\0"+ge;if(m&&h===nt&&m.parentElement===u)return;B(),E(),b(),u.replaceChildren();let Ee=n.features?.artifacts?.filePreview,Ne=Ee?.iframeSandbox??"allow-scripts";!Ee?.dangerouslyAllowSameOrigin&&Ne.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ne=Ne.split(/\s+/).filter(Ge=>Ge&&Ge!=="allow-same-origin").join(" "));let Pe=rW(Ee?.loading),dt=v("div","persona-artifact-frame"),Xe=v("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Ne),Xe.setAttribute("data-artifact-id",K.id);let xt=null;Pe.enabled&&Pe.injectReadySignal?(xt=iW(),Xe.srcdoc=ge+aW(xt)):Xe.srcdoc=ge,dt.appendChild(Xe),u.appendChild(dt),Pe.enabled&&(g=cW(dt,Xe,xt,Pe,K.id,n)),m=dt,h=nt;return}if(b(),!oe&&N==="markdown"&&Y==="rendered"){D(ge);return}I(ge,{language:re.language,path:re.path},K,ce);return}if(K.artifactType==="markdown"){if(Y==="source"){b(),I(K.markdown??"",void 0,K,ce);return}D(K.markdown??"");return}b(),B(),E(),u.replaceChildren();let we=K.component?o.get(K.component):void 0;if(we){let N={message:{id:K.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ye=we(K.props??{},N);if(ye){u.appendChild(ye);return}}catch{}}u.appendChild(oW(K))};return z(t),{el:u,update(K){z(K)},destroy(){b()}}}var Uh,tW,nW,sW,Uu=be(()=>{"use strict";Ye();SM();hi();Fu();HM();Xd();ti();Ff();wc();zh();Uh=!1;tW="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",nW="persona-text-sm persona-leading-relaxed persona-markdown-bubble";sW=220});function OM(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},d=m=>{let h=m;return s.findIndex(g=>g===h||g.contains(h))},p=m=>{let h=d(m.target);if(h<0)return;let g=h;if(m.key===r)g=Math.min(h+1,s.length-1);else if(m.key===o)g=Math.max(h-1,0);else if(m.key==="Home")g=0;else if(m.key==="End")g=s.length-1;else return;m.preventDefault(),g!==h&&e.onSelect(g)},u=m=>{let h=d(m.target);h>=0&&l(s[h])};return t.addEventListener("keydown",p),t.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(m,h){if(s=m,m.forEach((g,b)=>{g.setAttribute("role","tab");let C=b===h;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||h<0&&b===0?0:-1}),a){let g=(h>=0?m[h]:void 0)??m[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){t.removeEventListener("keydown",p),t.removeEventListener("focusin",u)}}}var DM=be(()=>{"use strict"});function qh(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),p=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:u,end:m}=p(n?.tabFade),h=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{h?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),w?.closeMenu()};h&&h.addEventListener("click",()=>{g(),e.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let S=v("span","persona-text-xs persona-font-medium persona-truncate");S.textContent=s;let P=gn({icon:"x",label:a});P.addEventListener("click",()=>{g(),e.onDismiss?.()});let M="rendered",B=bu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{M=ee==="source"?"source":"rendered",Je()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),O=n?.documentToolbarShowCopyLabel===!0,E=n?.documentToolbarShowCopyChevron===!0,W=n?.documentToolbarCopyMenuItems,R=!!(E&&W&&W.length>0),V=null,H,w=null;if(r&&(O||E)&&!R){if(H=O?ci({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E){let ee=Qe(ws.ChevronDown,14,"currentColor",2);ee&&H.appendChild(ee)}}else r&&R?(w=xA({label:"Copy",icon:"copy",iconSize:14,iconOnly:!O,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(W??[]).map(ee=>({id:ee.id,label:ee.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:ee=>{we(ee)}}),V=w.element,H=w.primaryButton):r?H=gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(H=gn({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&H.classList.add("persona-hidden"));let T=r?gn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):gn({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||T.classList.add("persona-hidden");let I=r?gn({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):gn({icon:"x",label:a}),D=gn({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&D.classList.add("persona-hidden");let G=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),z=t.features?.artifacts?.toolbarActions??[],K=()=>{let ee=Ge.find(Ke=>Ke.id===yt)??Ge[Ge.length-1],Oe=ee?.id??null,$e=ee?.artifactType==="markdown"?ee.markdown??"":"",pt=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"",{filename:_t,mime:ve,content:Se}=xc({title:ee?.title,markdown:ee?.markdown??"",file:ee?.file});return{markdown:$e,jsonPayload:pt,id:Oe,file:ee?.file,suggestedFilename:_t,mime:ve,content:Se}},Y=()=>{let{suggestedFilename:ee,mime:Oe,content:$e}=K();$e&&Sc({filename:ee,mime:Oe,content:$e})},re=ee=>{let{id:Oe,...$e}=K();return{actionId:ee,artifactId:Oe,...$e}},oe=async()=>{let ee=Ge.find(Oe=>Oe.id===yt)??Ge[Ge.length-1];try{return await navigator.clipboard.writeText(Mc(ee)),!0}catch{return!1}},se=null,ce=()=>{se?.();let ee=H.querySelector("svg"),Oe=Number(ee?.getAttribute("width"))||16,$e=Qe(ws.Check,Oe,"currentColor",2);if(!ee||!$e)return;ee.replaceWith($e);let pt=H.querySelector("span");pt&&(pt.textContent="Copied");let _t=setTimeout(()=>se?.(),2e3);se=()=>{clearTimeout(_t),$e.replaceWith(ee),pt&&(pt.textContent="Copy"),se=null}};H.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&R){try{if(await ee(re("primary"))===!1){await oe()&&ce();return}ce()}catch{}return}await oe()&&ce()});async function we(ee){let Oe=n?.onDocumentToolbarCopyMenuSelect;try{if(Oe&&await Oe(re(ee))!==!1)return;if(ee==="download"){Y();return}let{markdown:$e,jsonPayload:pt}=K();ee==="markdown"||ee==="md"?await navigator.clipboard.writeText($e):ee==="json"||ee==="source"?await navigator.clipboard.writeText(pt):await navigator.clipboard.writeText($e||pt),ce()}catch{}}T.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Je()}),I.addEventListener("click",()=>{g(),e.onDismiss?.()});let ge=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),V?A.append(V,T,I):A.append(H,T,I),A.insertBefore(G,I),A.insertBefore(D,I),C.append(B.element,ge,A);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(H,G,D,P),C.appendChild(S),C.appendChild(ee)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let N=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");d&&N.style.setProperty("--persona-artifact-tab-fade-size",d);let ye=t.features?.artifacts?.renderTabBar,ke=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),nt=OM(N,{onSelect:ee=>e.onSelect(Ge[ee].id)}),Ee=ee=>{let Oe=ee.scrollWidth-ee.clientWidth,$e=Oe>1,pt=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",u&&$e&&pt>1),ee.classList.toggle("persona-artifact-tab-fade-end",m&&$e&&pt<Oe-1)},Ne=0,Pe=()=>{if(Ne)return;let ee=()=>{Ne=0,Ee(N)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};N.addEventListener("scroll",()=>Pe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Ee(N)).observe(N);let dt=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Xe=()=>{dt.scrollLeft=0},xt=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Xe):setTimeout(Xe,0)};if(l){for(let ee of[N,ke])ee.style.paddingLeft=l,ee.style.paddingRight=l;dt.style.padding=l}b.appendChild(C),b.appendChild(N),b.appendChild(ke),b.appendChild(dt);let Ge=[],yt=null,X=!1,L=!1,j=!0,J=!1,Q=null,de="",Me=null,Te=!1,Fe=ee=>ee.artifactType==="markdown"&&!!ee.file||r?M:"rendered",je=ee=>{r||(ee&&!Te?(C.insertBefore(B.element,S),Te=!0):!ee&&Te&&(B.element.remove(),Te=!1))},lt=()=>yt&&Ge.find(ee=>ee.id===yt)||Ge[Ge.length-1],ot=()=>{let ee=Ac(lt());if(!ee){G.replaceChildren();return}let Oe=z.filter($e=>$e.visible===void 0||$e.visible(ee)).map($e=>La($e,{documentChrome:r,onClick:()=>{let pt=Ac(lt());if(pt)try{Promise.resolve($e.onClick(pt)).catch(()=>{})}catch{}}}));G.replaceChildren(...Oe)},Je=()=>{ot();let ee=r&&Ge.length<=1,Oe=!!ye;if(N.classList.toggle("persona-hidden",ee||Oe),ke.classList.toggle("persona-hidden",ee||!Oe),Oe&&ye){let _t=Ge.map(ve=>ve.id).join("|")+" "+(yt??"");if(_t!==de){de=_t;let ve=ye({records:Ge,selectedId:yt,onSelect:e.onSelect});ke.firstElementChild!==ve&&ke.replaceChildren(ve)}}else{nt.beforeRender(),N.replaceChildren();let _t=[],ve=-1;for(let[Se,Ke]of Ge.entries()){let ut=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ut.type="button";let vn=Ke.artifactType==="markdown"?Ke.file:void 0,Cn=vn?dr(vn.path):Ke.title||Ke.id.slice(0,8),wn=vn?.path||Ke.title||Cn;ut.textContent=Cn,ut.title=wn,ut.setAttribute("aria-label",wn),Ke.id===yt&&(ut.classList.add("persona-bg-persona-container","persona-border-persona-border"),ve=Se),ut.addEventListener("click",()=>e.onSelect(Ke.id)),N.appendChild(ut),_t.push(ut)}if(nt.render(_t,ve),ve>=0&&yt!==Q){Q=yt;let Se=_t[ve];typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({block:"nearest",inline:"nearest"})}Ee(N)}let $e=yt&&Ge.find(_t=>_t.id===yt)||Ge[Ge.length-1];if(!$e){dt.replaceChildren(),Me?.destroy(),Me=null,je(!1);return}let pt=$e.artifactType==="markdown"?$e.file:void 0;if(je(!!pt&&gi(pt)!=="other"),r){let _t=pt?Cs(pt):$e.artifactType==="markdown"?"MD":$e.component??"Component",ve=($e.title||"Document").trim(),Se=pt?dr(pt.path):ve.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${Se} \xB7 ${_t}`}else S.textContent=pt?dr(pt.path):s;Me?(Me.el.parentElement!==dt&&dt.replaceChildren(Me.el),Me.update($e)):(Me=zu($e,{config:t,resolveViewMode:Fe}),dt.replaceChildren(Me.el)),dt.classList.toggle("persona-artifact-content-flush",!!dt.querySelector(".persona-code-pre"))},mt=()=>{let ee=Ge.length>0;if(b.classList.toggle("persona-hidden",!ee),h){let pt=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&pt&&X?(h.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},Tt=()=>{J=!1,Je(),mt()};return{element:b,backdrop:h,update(ee){let Oe=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,$e=Oe!==yt;Ge=ee.artifacts,yt=Oe,Ge.length>0&&(X=!0),J=!0,j&&Tt(),$e&&Xe()},setMobileOpen(ee){X=ee,!ee&&h?(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):mt()},setExpanded(ee){ee!==L&&(L=ee,xt());let Oe=Qe(ee?ws.Minimize:ws.Maximize,16,"currentColor",2);Oe&&D.replaceChildren(Oe);let $e=ee?"Collapse artifacts panel":"Expand artifacts panel";D.setAttribute("aria-label",$e),D.title=$e},setExpandToggleVisible(ee){D.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||H.classList.toggle("persona-hidden",!ee)},setRefreshButtonVisible(ee){T.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){z=ee,ot()},setTabFade(ee){let Oe=p(ee);Oe.start===u&&Oe.end===m||(u=Oe.start,m=Oe.end,Ee(N))},setRenderTabBar(ee){ee!==ye&&(ye=ee,de="",Je())},setVisible(ee){ee!==j&&(j=ee,ee&&J&&Tt())},destroy(){Me?.destroy(),Me=null}}}var ws,_M=be(()=>{"use strict";Ye();hi();Nu();Uu();ws=require("lucide");ro();di();DM()});function NM(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?dr(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",d=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,p=n?Cs(n):l==="component"?"Component":"Document",u=document.createElement("div");u.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",u.tabIndex=0,u.setAttribute("role","button"),u.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&u.setAttribute("data-open-artifact",s);let m=document.createElement("div");m.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",m.style.border="1px solid var(--persona-border, #e5e7eb)",m.style.color="var(--persona-muted, #9ca3af)",m.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let h=document.createElement("div");h.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=e?.config?.features?.artifacts,S={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},P=Ia(S,C,"card");yi(b,P,C)}else s&&Pa(s),b.textContent=p;if(h.append(g,b),u.append(m,h),a==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let P={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let M of C)try{if(M.visible===void 0||M.visible(P)){let B=La(M);B.setAttribute("data-artifact-custom-action",M.id),B.className=`${B.className} persona-flex-shrink-0`,u.append(B)}}catch{}}let S=ci({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",s),u.append(S)}return u}var Tc,jh=be(()=>{"use strict";hi();Fu();di();Nu();Tc=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>NM(t,e)});if(l)return l}return NM(t,e)}});function Kh(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=xs.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Gh(t){return xs.has(t)}function dW(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function FM(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?dr(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Cs(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function pW(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}function bW(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:VM,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let P of a)P.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let d=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!d||Math.abs(d-e)<1){l(),r();return}let p=Math.abs(e-d),u=Math.round(Math.min(gW,Math.max(fW,uW+p*mW))),m=Math.round(u*yW),h=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=h?h.animate([{opacity:0},{opacity:1}],{duration:$M,delay:m,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${d}px`}],{duration:u,easing:hW});t.style.height=`${d}px`;let C=!1,S=()=>{C||(C=!0,l(),r())};Promise.allSettled([b.finished,g?.finished].filter(Boolean)).then(S),window.setTimeout(S,Math.max(u,m+$M)+120)},VM)}function vW(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}function CW(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:e?.followOutput!==!1,p,u,m=e?.fadeMask;m===!0?(p=!0,u=!0):m===!1?(p=!1,u=!1):m&&typeof m=="object"?(p=m.top===!0,u=m.bottom===!0):l==="clip"?(p=!1,u=!0):(p=!0,u=!0);let h=e?.transition==="none"?"none":"auto",g=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:l,fadeTop:p,fadeBottom:u,transition:h,completeDisplay:g}}function zM(t,e){let n=dW(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=vW(o),d=o?.inlineActions??[],p=CW(o),u=p.completeDisplay==="card",m=null,h=n,g=v("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let b=oe=>Tc(pW(oe),e),C=null,S=oe=>{C?.destroy(),C=null,g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Ec),g.replaceChildren(b(oe)),xs.set(g,se=>{g.replaceChildren(b(se))})};if(u&&n.status==="complete")return S(n),g;let P=zu(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>m??p.viewMode});C=P;let M=v("div","persona-artifact-inline-body");M.appendChild(P.el);let B=oe=>{let se=oe.status!=="complete",ce=se?p.streamingHeight:p.completeHeight,we=typeof ce=="number";we?g.style.setProperty(Ec,`${ce}px`):g.style.removeProperty(Ec);let ge=!!P.el.querySelector(".persona-code-pre"),N=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");M.classList.toggle("persona-artifact-content-flush",ge),M.classList.toggle("persona-artifact-inline-body--sized",we&&N),M.classList.toggle("persona-artifact-inline-body--cap",!se&&!N&&typeof p.completeHeight=="number")},A=n.status,O=(oe,se)=>{A!=="complete"&&oe.status==="complete"?(typeof p.completeHeight=="number"?g.style.setProperty(Ec,`${p.completeHeight}px`):g.style.removeProperty(Ec),BM(M,se?.suppressTransition?"none":p.transition,oe.id,()=>{P.update(oe),B(oe)})):P.update(oe),B(oe),A=oe.status};B(n);let E=p.overflow==="clip"&&a&&!!n.id;if(E&&(M.setAttribute("data-expand-artifact-inline",n.id),M.setAttribute("role","button"),M.setAttribute("tabindex","0"),M.classList.add("persona-cursor-pointer"),M.setAttribute("aria-label",`Open ${FM(n).title} in panel`)),!r)return g.appendChild(M),xs.set(g,O),g;let W=v("div","persona-artifact-inline-chrome");W.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let R=v("div","persona-artifact-inline-chrome-lead"),V=v("span","persona-flex persona-items-center persona-flex-shrink-0"),H=Qe(UM.FileText,16,"currentColor",2);H&&V.appendChild(H);let w=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),T=v("span","persona-artifact-inline-type");R.append(V,w,T);let I=v("div","persona-artifact-inline-chrome-actions"),D=v("span","persona-flex persona-items-center persona-gap-1"),G=()=>m??p.viewMode,z=l?bu({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:G(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:oe=>{let se=oe==="source"?"source":"rendered";se!==G()&&(m=se,P.update(h),B(h))}}):null,K=s?gn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;K&&n.id&&K.setAttribute("data-copy-artifact",n.id);let Y=a?gn({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Y&&n.id&&Y.setAttribute("data-expand-artifact-inline",n.id),I.appendChild(D),z&&I.appendChild(z.element),K&&I.appendChild(K),Y&&I.appendChild(Y),W.append(R,I),g.append(W,M);let re=oe=>{let{title:se,typeLabel:ce}=FM(oe);w.textContent=se,w.title=se,E&&M.setAttribute("aria-label",`Open ${se} in panel`);let we=oe.status!=="complete";if(we){T.classList.contains("persona-artifact-inline-status")||(T.className="persona-artifact-inline-status",T.removeAttribute("data-preserve-animation"),T.replaceChildren());let ge=Ia(oe,o,"inline-chrome");yi(T,ge,o)}else Pa(oe.id),T.className="persona-artifact-inline-type",T.removeAttribute("data-preserve-animation"),T.replaceChildren(),T.textContent=ce;if(K&&K.classList.toggle("persona-hidden",we),z){let ge=oe.artifactType==="markdown"?oe.file:void 0,N=!1;if(!we&&ge&&p.viewMode!=="source"){let ye=gi(ge);ye==="markdown"?N=!0:(ye==="html"||ye==="svg")&&(N=o?.filePreview?.enabled!==!1)}z.element.classList.toggle("persona-hidden",!N),z.setSelected(G())}if(D.replaceChildren(),!we&&d.length>0){let ge=Ac(oe);if(ge)for(let N of d)try{if(N.visible===void 0||N.visible(ge)){let ye=La(N,{documentChrome:!0});ye.setAttribute("data-artifact-custom-action",N.id),ye.classList.add("persona-flex-shrink-0"),D.appendChild(ye)}}catch{}}};return re(n),xs.set(g,(oe,se)=>{if(u&&A!=="complete"&&oe.status==="complete"){let ce=g.isConnected?g.getBoundingClientRect().height:0;A="complete";let we=oe,ge=!1,N=ye=>{we=ye,ge=!0};xs.set(g,N),bW(g,ce,{swap:()=>{S(we),ge=!1,xs.set(g,N)},onSettled:()=>{ge?S(we):xs.set(g,ye=>{g.replaceChildren(b(ye))})}});return}(oe.status!=="complete"||oe.id!==h.id)&&(m=null),h=oe,O(oe,se),re(oe)}),g}var UM,xs,VM,uW,mW,fW,gW,hW,$M,yW,Ec,Yh,qM=be(()=>{"use strict";Ye();hi();Fu();Nu();di();UM=require("lucide");ro();Uu();jh();xs=new WeakMap;VM=180,uW=240,mW=.8,fW=300,gW=500,hW="cubic-bezier(0.2, 0, 0, 1)",$M=240,yW=.35;Ec="--persona-artifact-inline-body-height";Yh=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>zM(t,e)});if(l)return l}return zM(t,e)}});var jM=be(()=>{"use strict";_M();qM();jh();Uu();hi();zh();ti();wp()});var KM={};Vn(KM,{PersonaArtifactCard:()=>Tc,PersonaArtifactInline:()=>Yh,__provideMarkdownParsers:()=>_f,__setIconsExtraLoader:()=>mg,artifactCopyText:()=>Mc,createArtifactPane:()=>qh,downloadInfoFor:()=>xc,hasLiveInlineArtifactBlock:()=>Gh,initArtifactsUi:()=>$h,triggerArtifactDownload:()=>Sc,updateInlineArtifactBlocks:()=>Kh});var GM=be(()=>{"use strict";jM()});var Yu,sT,iT=be(()=>{"use strict";Ye();Yu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},sT=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Yu[a]??Yu.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),p=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=l.title,d.appendChild(p),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,d.appendChild(b)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${b.name}`;let S=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");S.textContent=b.label,C.appendChild(S);let P=b.type??"text",M;P==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=P),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${e.id}-${a}-${b.name}`,M.name=b.name,M.placeholder=b.placeholder??"",b.required&&(M.required=!0),C.appendChild(M),u.appendChild(C)});let m=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",m.appendChild(h),m.appendChild(g),u.appendChild(m),s.replaceChildren(d,u),u.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",S=new FormData(u),P={};S.forEach((M,B)=>{P[B]=M}),P.type=a,g.disabled=!0,h.textContent="Submitting\u2026";try{let M=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let B=await M.json();h.textContent=B.message??"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await o.sendMessage(String(B.nextPrompt))}catch(M){h.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})}});var aT={};Vn(aT,{enhanceWithForms:()=>sT,formDefinitions:()=>Yu});var lT=be(()=>{"use strict";iT()});function vT(){let t=document.createElement("div");t.className="persona-history-sr-only",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.setAttribute("data-persona-history-live-region","");let e;return{element:t,announce(n){e!==void 0&&clearTimeout(e),t.textContent="",e=setTimeout(()=>{e=void 0,t.textContent=n},0)},destroy(){e!==void 0&&clearTimeout(e),t.remove()}}}var CT=be(()=>{"use strict"});var wT,xT=be(()=>{"use strict";wT=`
244
244
  .persona-history-view {
245
245
  --persona-history-surface-bg: var(--persona-surface, #ffffff);
246
246
  --persona-history-topbar-bg: var(--persona-header-bg, var(--persona-surface, #ffffff));
@@ -1137,25 +1137,25 @@ ${e}
1137
1137
  .persona-history-view .persona-history-skeleton-bar { animation: none; }
1138
1138
  .persona-history-rail-host { transition: none; }
1139
1139
  }
1140
- `});function ly(t){if(!t)return Qu;let e={...Qu};for(let n of QW){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var QW,Qu,cy=be(()=>{"use strict";QW=["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"],Qu={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 Hc(t){if(!t)return Ic;let e={...Ic};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function pr(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Ic,Rc=be(()=>{"use strict";cy();Ic={...Qu,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function XW(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function py(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function JW(t,e){let n=py(t,e),o=XW(e);if(n>=o)return"today";if(n>=o-dy)return"yesterday";if(n>=o-7*dy)return"previous-7-days";if(n>=o-30*dy)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function ZW(t,e,n,o){if(t==="today")return o.groupToday;if(t==="yesterday")return o.groupYesterday;if(t==="previous-7-days")return o.groupPrevious7Days;if(t==="previous-30-days")return o.groupPrevious30Days;let r=new Date(py(e,n));return pr(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function ST(t,e,n,o="time"){let r=t.filter(a=>a.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let a=t.filter(l=>!l.starred);return a.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:a}),s}for(let a of t){if(a.starred)continue;let l=JW(a.updatedAt,e),d=s[s.length-1];if(d&&d.key===l){d.items.push(a);continue}s.push({key:l,label:ZW(l,a.updatedAt,e,n),items:[a]})}return s}function AT(t,e,n){let o=Math.max(0,e-py(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return pr(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return pr(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return pr(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?pr(n.relativeWeeks,{value:l}):pr(n.relativeYears,{value:Math.floor(a/365)})}function MT(t,e){return t===1?e.messageCountLabelOne:pr(e.messageCountLabel,{count:t})}var dy,uy=be(()=>{"use strict";Rc();dy=864e5});function Ss(t,e=20){let n=document.createElementNS(Xu,"svg");if(n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),t==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(Xu,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=tB[t];if(o){let r=document.createElementNS(Xu,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of eB[t]){let s=document.createElementNS(Xu,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var Xu,eB,tB,my=be(()=>{"use strict";Xu="http://www.w3.org/2000/svg",eB={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},tB={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function oB(t){let e=$("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return nB.test(t)?e.appendChild($("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function TT(t){let{conversation:e,copy:n,busy:o,pending:r}=t,s=o||r!==null,a=e.title.trim().length>0,l=e.starred?(()=>{let g=Ss("star",11);return g.setAttribute("fill","currentColor"),g.setAttribute("stroke-width","1"),$("span",{className:"persona-history-row-star"},g,$("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,d=$("div",{className:"persona-history-row-head"},$("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,$("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:AT(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?$("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=$("button",{className:Vt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":rB(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?oB(t.avatar):null,$("div",{className:"persona-history-row-body"},d,p,$("span",{className:"persona-history-row-count persona-history-sr-only",text:MT(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?fy({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:sB(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return $("li",{className:Vt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?iB(t):null,t.error?aB(t.error,n,e.id):null)}function iB(t){let{conversation:e,copy:n}=t;return gy({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Wc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function fy(t){let e=$("button",{className:Vt("persona-history-icon-button",t.className),attrs:{type:"button","aria-label":t.label,"aria-haspopup":"menu","aria-expanded":t.open?"true":"false","data-persona-history-focus":t.focusKey,...t.inert?{"aria-disabled":"true"}:{}}});e.appendChild(Ss("ellipsis",t.iconSize));let n=()=>e.getAttribute("aria-disabled")==="true";return e.addEventListener("click",o=>{o.stopPropagation(),!n()&&t.onToggle()}),e.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||e.getAttribute("aria-expanded")==="true")&&t.onToggle())}),e}function gy(t){let e=$("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=$("button",{className:Vt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{t.onCloseMenu(),n.onSelect()}),e.appendChild(o)}return e.addEventListener("keydown",n=>{let o=Array.from(e.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){t.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),e}function aB(t,e,n){let o=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",t.retry),$("div",{className:"persona-history-row-error",attrs:{role:"alert"}},$("span",{text:t.message}),o)}var nB,rB,sB,Wc,ET=be(()=>{"use strict";Ye();my();uy();nB=/^(https?:|\/|data:)/i;rB=t=>`row:${t}`,sB=t=>`menu:${t}`,Wc=t=>`menu-item:${t}`});function lB(t){switch(t){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return t;default:return"unknown"}}function kT(t){if(gp(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=lB(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function cB(t,e){switch(t.state){case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};default:return null}}function dB(t,e){switch(t){case"authentication_required":case"authentication_failed":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription};default:return{title:e.errorTitle,description:e.errorDescription}}}function Ju(t,e,n,o){let r=$("button",{className:"persona-history-secondary persona-history-state-action",text:t,attrs:{type:"button","data-persona-history-focus":e,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function Bc(t,e,n,o,r){return $("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},$("p",{className:"persona-history-state-title",text:e}),$("p",{className:"persona-history-state-description",text:n}),o)}function pB(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>$("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},$("div",{className:"persona-history-skeleton-head"},$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return $("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function LT(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return pB(n);if(e.kind==="empty"){let l=cB(t.identityStatus,n);return l?Bc("identity",l.title,l.description,t.onRetry?Ju(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Bc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?pr(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Bc("rate_limited",n.rateLimitedTitle,l,t.onRetry?Ju(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Bc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Ju(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=dB(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Bc("error",r,s,e.retryable&&t.onRetry?Ju(a,"state-retry",o,t.onRetry):null,!0)}var PT=be(()=>{"use strict";Ye();Rc();_l()});function Zu(t){return`${t.state}:${"reason"in t?t.reason:""}`}function HT(t,e){switch(t.state){case"verified":return{title:e.verifiedTitle,description:e.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:e.verifyingTitle,description:e.verifyingDescription,pending:!0};case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription,pending:!1};default:return{title:e.browserOnlyTitle,description:e.browserOnlyDescription,pending:!1}}}function vB(t){return t.state==="verified"||t.state==="browser_only"}function CB(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function hy(t){let e=Hc(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??uB,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],a=null,l={kind:"loading",phase:"initial"},d=null,p=t.activeConversationId,u=t.provider.getIdentityStatus(),m=Zu(u),h=null,g=!1,b=!1,C=0,S=t.presentation,P=t.collapsible!==!1,M=t.collapsed===!0,B=t.railSide==="right",A=t.renderDom!==!1,O=new Map,E=null,W=vT(),R=F=>{!A&&t.onAnnounce?t.onAnnounce(F):W.announce(F)},V=()=>d!==null,H=`${r}-body`,w=$("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),T=()=>S==="rail"&&P,I,D=()=>{if(t.railBrand){if(!T()){w.classList.remove("persona-history-back--branded");return}if(I===void 0){let F=t.railBrand(!0);I=F?$("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},F):null}I&&(w.classList.add("persona-history-back--branded"),w.appendChild(I))}},G=()=>{let F=T(),le=S==="rail";w.setAttribute("data-persona-history-focus",F?"collapse":"close"),w.setAttribute("aria-label",F?M?e.expandLabel:e.collapseLabel:le?e.closeLabel:e.backLabel),F?(w.setAttribute("aria-expanded",M?"false":"true"),w.setAttribute("aria-controls",H),t.collapseShortcut?.aria&&w.setAttribute("aria-keyshortcuts",t.collapseShortcut.aria)):(w.removeAttribute("aria-expanded"),w.removeAttribute("aria-controls"),w.removeAttribute("aria-keyshortcuts")),w.replaceChildren(Ss(F?"panel-left":le?"x":"arrow-left")),D()};G(),w.addEventListener("click",()=>{T()?t.onToggleCollapse?.():t.onClose()});let z=$("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),K=$("span",{className:"persona-history-scope-title"}),Y=$("p",{className:"persona-history-scope"},$("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},Ss("monitor",14)),K),re=$("div",{className:"persona-history-heading-group"},z),oe=!1,se,ce=()=>{let F=S==="rail",le=F?t.renderRailHeader:void 0,Be=null,et=le!==void 0;if(le)try{Be=le({collapsed:M,defaultTitle:e.viewTitle})}catch(he){et=!1,oe||(oe=!0,console.warn("[persona] history rail renderHeader threw",he))}if(!et&&F&&t.railBrand){if(se===void 0){let he=t.railBrand(!1);se=he?$("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},$("span",{className:"persona-history-brand-mark"},he),$("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}se&&(et=!0,Be=se)}z.classList.toggle("persona-history-sr-only",et),re.replaceChildren(z),Be&&re.appendChild(Be)};ce();let we=$("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});we.appendChild(Ss("plus")),we.addEventListener("click",()=>{an()});let ge=[w,we].map(F=>t.attachTooltip?.({anchor:F,text:()=>F.getAttribute("aria-label")??"",...F===w&&t.collapseShortcut?{hint:()=>T()?t.collapseShortcut.hint:""}:{}})),N=$("div",{className:"persona-history-topbar"}),ye=null,ke=()=>{let F=S==="rail",le=F?B?"rail-right":"rail":"panel";le!==ye&&(ye=le,le==="rail"?N.append(re,w):N.append(w,re),F?we.remove():N.appendChild(we),Q.classList.toggle("persona-history-view--rail-right",le==="rail-right"))},nt=$("div",{className:"persona-history-scope-alert"}),Ee=`${r}-scope`,Ne=Ss("plus",18),Pe=$("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},Ne,$("span",{text:e.newConversationLabel}));Pe.addEventListener("click",()=>{an()});let dt=$("div",{className:"persona-history-list-region"}),Xe=t.showDeleteAll!==!1,xt=!!t.provider.resetDevice,Ge=t.listActions??[],yt=Xe||xt||Ge.length>0?fy({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${Ci}`,open:!1,inert:!0,iconSize:16,onToggle:()=>wi(Ci)}):null,X=$("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),L=$("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Ci}},X,t.showScopeStatus?Y:null,yt),j=$("div",{className:"persona-history-body",attrs:{id:H}},t.showScopeStatus?nt:null,Pe,L,dt),J=t.headerPlacement??"inline";J==="external"&&N.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Q=$("div",{className:Vt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},W.element,J==="inline"?N:null,j),de=()=>{Q.classList.toggle("persona-history-view--rail-collapsed",M&&T())};de(),ke();let Me=(F,le)=>{let Be=`${r}-s${le}`,et=$("div",{className:Vt("persona-history-nav",F.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":F.id,...F.title?{"aria-labelledby":Be}:{"aria-label":F.id}}});F.title&&et.appendChild($("h3",{className:"persona-history-group-heading",text:F.title,attrs:{id:Be}}));for(let he of F.items){let We=he.iconNode?.()??null,zo=$("button",{className:Vt("persona-history-nav-item",We&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":he.label,"data-persona-rail-item":he.id}},We?$("span",{className:"persona-history-nav-icon"},We):null,$("span",{className:"persona-history-nav-label persona-history-truncate",text:he.label}),he.badge?$("span",{className:"persona-history-nav-badge",text:he.badge}):null);zo.addEventListener("click",()=>he.onSelect()),et.appendChild(zo)}return et},Te=null,Fe=null,je=()=>{!Te||!A||S!=="rail"||M===Fe||(Fe=M,t.railSections.forEach((F,le)=>{if(!F.render)return;let Be=Te[le],et=F.title?Be.firstElementChild:null,he=null;try{he=F.render(M)}catch(We){F.render=void 0,console.warn("[persona] history rail section threw",F.id,We)}Be.replaceChildren(...et?[et]:[],...he?[he]:[]),Be.hidden=!he}))},lt=()=>{let F=t.railSections;if(Q.classList.toggle("persona-history-view--has-nav",S==="rail"&&!!F?.some(le=>le.placement==="above-conversations")),!!F?.length){if(S!=="rail"){Te?.forEach(le=>le.remove());return}Te??(Te=F.map(Me));for(let le of["above-conversations","below-conversations","footer"]){let Be=le==="above-conversations"?L.parentNode===j?L:dt:null;F.forEach((et,he)=>{et.placement===le&&j.insertBefore(Te[he],Be)})}je()}};lt(),Np(Q,"persona-history-view",wT);let ot=(F,le)=>{let Be=Q.ownerDocument.defaultView?.getComputedStyle(Q).getPropertyValue(F),et=Number.parseFloat(Be??"");return Number.isFinite(et)&&et>=0?et:le},Je=(F,le)=>Q.ownerDocument.defaultView?.getComputedStyle(Q).getPropertyValue(F).trim()||le,mt=null,Tt=()=>{mt!==null&&(clearTimeout(mt),mt=null),Q.removeEventListener("animationend",Tt),Q.classList.remove("persona-history-view--enter")};Q.addEventListener("animationend",Tt),mt=setTimeout(()=>{mt=setTimeout(Tt,ot("--persona-history-enter-ms",mB)+60)},0);let ee=null,Oe=()=>{ee!==null&&(clearTimeout(ee),ee=null),N.classList.remove("persona-history-topbar--shell-enter")},$e=()=>{Oe(),N.classList.add("persona-history-topbar--shell-enter"),ee=setTimeout(Oe,IT+60)};J==="external"&&(ee=setTimeout(Oe,IT+60));let pt=[],_t=null,ve=()=>{if(_t)return _t;if(b||yB()||typeof Q.animate!="function")return Tt(),null;let F=Q.ownerDocument.defaultView?.getComputedStyle(j).opacity||"1";Tt(),Q.style.pointerEvents="none",Ke.style.pointerEvents="none";let le={duration:ot("--persona-history-exit-ms",fB),easing:Je("--persona-history-exit-easing",gB),fill:"forwards"},Be=hB[S];return pt=[j.animate([{opacity:F,transform:"none"},{opacity:0,transform:`translateX(${Be}px)`}],le)],_t=Promise.all(pt.map(bB)).then(()=>{}),_t},Se=(F,le)=>{F&&(le?F.setAttribute("aria-disabled","true"):F.removeAttribute("aria-disabled"))},Ke=N,ut=null,vn=()=>{let F=t.slots?.header;if(!F)return;let le=`${S}|${Zu(u)}|${d?`${d.kind}:${"conversationId"in d?d.conversationId:""}`:""}`;if(le===ut)return;ut=le;let Be=F({identityStatus:u,pendingAction:d,copy:e,defaultRenderer:()=>N})??N;Be!==Ke&&(Ke.replaceWith(Be),Ke=Be)},Cn=null,wn=()=>{if(!t.showScopeStatus)return;let F=Zu(u);if(F===Cn)return;Cn=F;let le=HT(u,e);K.textContent=le.title;let Be=vB(u);if(Y.hidden=!Be,nt.replaceChildren(...Be?[]:[$("span",{className:"persona-history-scope-alert-title",text:le.title})],$("span",{className:"persona-history-scope-description",text:le.description,attrs:{id:Ee}})),nt.setAttribute("data-persona-history-scope-tone",Be?"ambient":"attention"),Be?Y.setAttribute("aria-describedby",Ee):Y.removeAttribute("aria-describedby"),le.pending?nt.setAttribute("role","status"):nt.removeAttribute("role"),nt.setAttribute("data-persona-history-identity",u.state),Y.setAttribute("data-persona-history-identity",u.state),CB(u)){let et=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});et.addEventListener("click",()=>{V()||Ae("refresh")}),nt.appendChild(et)}},Wt=F=>d?d.kind==="open"&&d.conversationId===F?"opening":d.kind==="delete"&&d.conversationId===F?"deleting":null:null,St=()=>{let F=document.activeElement;return!(F instanceof HTMLElement)||!Q.contains(F)?null:F.getAttribute("data-persona-history-focus")},Et=F=>{if(g&&h){g=!1;let le=Q.querySelector(`[data-persona-history-focus="${Wc(h)}"]`);if(le){le.focus();return}}F&&Q.querySelector(`[data-persona-history-focus="${F}"]`)?.focus()},sn=()=>{if(!E)return null;let F=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),le=E;return F.addEventListener("click",()=>{V()||le.retry()}),$("div",{className:"persona-history-row-error",attrs:{role:"alert"}},$("span",{text:le.message}),F)},Rn=()=>ST(s,n(),e,t.grouping).map((F,le)=>{let Be=`${r}-g${le}`,et=$("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Be}});for(let he of F.items){let We=()=>TT({conversation:he,active:he.id===p,pending:Wt(he.id),busy:V(),menuOpen:h===he.id,error:O.get(he.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Wn(he.id)},onToggleMenu:()=>wi(he.id),onCloseMenu:$r=>Re($r),onDelete:()=>{bt(he.id)}}),Uo=t.slots?.conversation?.({conversation:he,active:he.id===p,pending:Wt(he.id),open:()=>Wn(he.id),requestDelete:()=>bt(he.id),defaultRenderer:We})??We();et.appendChild(Uo instanceof HTMLLIElement?Uo:$("li",{className:"persona-history-item"},Uo))}return $("div",{className:"persona-history-group",attrs:{"data-persona-history-group":F.key}},$("h3",{className:Vt("persona-history-group-heading",F.key==="recent"&&"persona-history-sr-only"),text:F.label,attrs:{id:Be}}),et)}),tn=()=>{if(!a)return null;let F=d?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",le=$("button",{className:"persona-history-secondary persona-history-load-more",text:F?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...F?{"aria-busy":"true","aria-disabled":"true"}:{},...V()&&!F?{"aria-disabled":"true"}:{}}});return le.addEventListener("click",()=>{V()||Ae("load-more")}),le},it=()=>{let F=St(),le=[sn()],Be=s.length>0;if(Be&&(le.push(...Rn()),le.push(tn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Be)){let he=l,We=he.kind==="loading"?void 0:()=>Ae("refresh"),zo=he.kind==="new_conversation_required"?()=>an():void 0,Uo=()=>LT({state:he,copy:e,identityStatus:u,busy:V(),...We?{onRetry:()=>{We()}}:{},...zo?{onStartNew:()=>{zo()}}:{}}),$r=t.slots?.state?.({state:he,identityStatus:u,copy:e,...We?{retry:We}:{},...zo?{startNewConversation:zo}:{},defaultRenderer:Uo});le.push($r??Uo())}dt.replaceChildren(...le.filter(he=>!!he)),Et(F)},_e=()=>{let F=l.kind==="loading"&&s.length===0,le=[],Be=()=>le.length===0?Wc(Ci):`${Wc(Ci)}-${le.length}`;if(!F)for(let et of Ge)le.push({label:et.label,focusKey:Be(),danger:et.danger===!0,onSelect:()=>{et.onSelect({conversations:[...s]})}});return Xe&&!(s.length===0&&(l.kind==="empty"||F))&&le.push({label:e.clearHistoryLabel,focusKey:Be(),danger:!0,onSelect:()=>{_a()}}),xt&&!F&&le.push({label:e.resetIdentityLabel,focusKey:Be(),danger:!0,onSelect:()=>{Na()}}),le},Kt=()=>{if(Se(Pe,V()),Se(we,V()),yt){let F=_e(),le=l.kind==="loading"&&s.length===0;yt.hidden=F.length===0&&!le,Se(yt,V()||F.length===0),yt.setAttribute("aria-expanded",h===Ci?"true":"false");let Be=L.querySelector(".persona-history-menu");if(h!==Ci||F.length===0)Be?.remove();else{let et=gy({label:e.listOptionsLabel,items:F,onCloseMenu:he=>Re(he)});Be?Be.replaceWith(et):L.appendChild(et)}}L.hidden=S!=="rail"&&(!yt||yt.hidden)&&(!t.showScopeStatus||Y.hidden)},Ze,Le=()=>{let F=t.onActiveConversationChange;if(!F)return;let le=s.find(et=>et.id===p)??null,Be=le?`${le.id}\0${le.title}\0${le.starred?1:0}`:"";Be!==Ze&&(Ze=Be,F(le))},ie=()=>{if(!b){if(Le(),!A){t.onModelChange?.();return}vn(),wn(),Kt(),it(),je()}},Re=F=>{if(!h)return;let le=h;h=null,g=!1,ie(),F?.restoreFocus&&Q.querySelector(`[data-persona-history-focus="menu:${le}"]`)?.focus()},wi=F=>{if(h===F){Re({restoreFocus:!0});return}h=F,g=!0,ie()},Vr=F=>{if(!h)return;let le=F.target;le instanceof Node&&Q.contains(le)&&le.closest?.(`[data-persona-history-item="${h}"]`)||Re()};document.addEventListener("pointerdown",Vr,!0);let Po=F=>{F.key!=="Escape"||!h||(F.stopPropagation(),Re({restoreFocus:!0}))};Q.addEventListener("keydown",Po);async function Ae(F){if(b)return;let le=++C,Be=F==="load-more"?a:null;if(!(F==="load-more"&&!Be)){d={kind:F==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:F},F!=="load-more"&&(O.clear(),E=null),Re(),ie();try{let et=await t.provider.list({limit:o,context:t.context,...Be?{cursor:Be}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||le!==C)return;s=Be?[...s,...et.items]:et.items,a=et.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(et){if(b||le!==C)return;l=kT(et)}finally{!b&&le===C&&(d=null,ie())}}}let Ve=F=>{s=s.filter(le=>le.id!==F),O.delete(F),p===F&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Wn(F){if(!(V()||b)){O.delete(F),Re(),d={kind:"open",conversationId:F},ie();try{if(await t.onSelect(F),b)return;p=F}catch{if(b)return;O.set(F,{message:e.openFailedLabel,retry:()=>{Wn(F)}})}finally{b||(d=null,ie())}}}async function bt(F){if(V()||b)return"cancelled";O.delete(F),d={kind:"delete",conversationId:F},ie();try{let le=await t.onRequestDeleteConversation(F);return b||le==="deleted"&&(Ve(F),R(e.conversationRemovedNotice)),le}catch(le){return b||(gp(le)&&le.code==="not_found"?Ve(F):O.set(F,{message:e.deleteFailedLabel,retry:()=>{bt(F)}})),"cancelled"}finally{b||(d=null,ie())}}async function an(){if(!(V()||b)){E=null,Re(),d={kind:"start-new"},ie();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;E={message:e.errorDescription,retry:()=>{an()}}}finally{b||(d=null,ie())}}}async function _a(){if(V()||b)return"cancelled";E=null,Re(),d={kind:"clear"},ie();try{let F=await t.onRequestClearHistory();return b||F==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},R(e.historyClearedNotice)),F}catch{return b||(E={message:e.errorDescription,retry:()=>{_a()}}),"cancelled"}finally{b||(d=null,ie())}}let kn={outcome:"cancelled"};async function Na(){if(V()||b||!t.onRequestResetIdentity)return kn;E=null,Re(),d={kind:"reset"},ie();try{let F=await t.onRequestResetIdentity();return b||F.outcome==="reset"&&(R(F.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),d=null,await Ae("refresh")),F}catch{return b||(E={message:e.errorDescription,retry:()=>{Na()}}),kn}finally{!b&&d?.kind==="reset"&&(d=null,ie())}}let om=t.provider.subscribeIdentityStatus(F=>{if(b)return;let le=Zu(F),Be=le!==m;u=F,m=le,ie(),Be&&F.state!=="verifying"&&R(HT(F,e).title)}),rm=t.provider.subscribeAvailability?.(F=>{if(!b){if(F){Ae("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},ie()}});return ie(),Ae("initial"),{element:Q,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:d,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{V()||await Ae("refresh")},loadMore:async()=>{V()||await Ae("load-more")},openConversation:F=>Wn(F),startNewConversation:()=>an(),requestDeleteConversation:F=>bt(F),requestClearConversationHistory:()=>_a(),requestResetHistoryIdentity:()=>Na()},setDomRenderEnabled:F=>{F!==A&&(A=F,F&&ie())},refresh:()=>{Ae("refresh")},setPresentation:F=>{if(F===S)return;Tt(),S=F,ut=null;let le=F==="rail";Q.classList.toggle("persona-history-view--panel",!le),Q.classList.toggle("persona-history-view--rail",le),Q.setAttribute("data-persona-history-presentation",F),G(),de(),ke(),ce(),lt(),ie()},setCollapsed:F=>{F!==M&&(M=F,de(),G(),ce(),je())},setRailSide:F=>{B=F==="right",ke()},getHeaderElement:()=>Ke,setHeaderPlacement:F=>{if(F===J)return;J=F;let le=F==="external";if(N.classList.toggle("persona-history-topbar--shell",le),le){$e(),Ke.remove();return}Oe(),Q.insertBefore(Ke,j)},setActiveConversationId:F=>{p!==F&&(p=F,ie())},applyConversationSummary:F=>{let le=s.findIndex(Be=>Be.id===F.id);le!==-1&&(s[le]=F,ie())},removeConversationSummary:F=>{s.some(le=>le.id===F)&&(Ve(F),ie())},setNewConversationRequired:F=>{F?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),ie()},playExit:ve,destroy:()=>{b=!0,C+=1,Tt(),Oe(),ge.forEach(F=>F?.destroy()),Ke.remove(),pt.forEach(F=>F.cancel()),pt=[],om(),rm?.(),document.removeEventListener("pointerdown",Vr,!0),Q.removeEventListener("keydown",Po),W.destroy(),Q.remove(),Q.replaceChildren()}}}var uB,Ci,mB,IT,fB,gB,hB,yB,bB,RT=be(()=>{"use strict";ya();Ye();CT();xT();Rc();uy();my();ET();PT();_l();uB=25,Ci="persona:list-options",mB=180,IT=120,fB=160,gB="cubic-bezier(0.4, 0, 1, 1)",hB={panel:20,rail:12},yB=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,bB=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var yy=be(()=>{"use strict";RT();Rc()});var WT={};Vn(WT,{HISTORY_VIEW_COPY_DEFAULTS:()=>Ic,createHistoryView:()=>hy,resolveHistoryViewCopy:()=>Hc});var BT=be(()=>{"use strict";yy();yy()});var o1={};Vn(o1,{createThemePreview:()=>aE});module.exports=k0(o1);function mC(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function no(t){return t?.type==="runtype"||t?.type==="custom"}var L0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function fC(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:L0()}catch{return!1}}Xd();Ff();var wC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,xC=t=>t.includes("|"),SC=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},O0=t=>`| ${t.join(" | ")} |`,D0=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,_0=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),AC=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
1140
+ `});function ly(t){if(!t)return Qu;let e={...Qu};for(let n of QW){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var QW,Qu,cy=be(()=>{"use strict";QW=["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"],Qu={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 Hc(t){if(!t)return Ic;let e={...Ic};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function ur(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var Ic,Rc=be(()=>{"use strict";cy();Ic={...Qu,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function XW(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function py(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function JW(t,e){let n=py(t,e),o=XW(e);if(n>=o)return"today";if(n>=o-dy)return"yesterday";if(n>=o-7*dy)return"previous-7-days";if(n>=o-30*dy)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function ZW(t,e,n,o){if(t==="today")return o.groupToday;if(t==="yesterday")return o.groupYesterday;if(t==="previous-7-days")return o.groupPrevious7Days;if(t==="previous-30-days")return o.groupPrevious30Days;let r=new Date(py(e,n));return ur(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function ST(t,e,n,o="time"){let r=t.filter(a=>a.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let a=t.filter(l=>!l.starred);return a.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:a}),s}for(let a of t){if(a.starred)continue;let l=JW(a.updatedAt,e),d=s[s.length-1];if(d&&d.key===l){d.items.push(a);continue}s.push({key:l,label:ZW(l,a.updatedAt,e,n),items:[a]})}return s}function AT(t,e,n){let o=Math.max(0,e-py(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return ur(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return ur(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return ur(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?ur(n.relativeWeeks,{value:l}):ur(n.relativeYears,{value:Math.floor(a/365)})}function MT(t,e){return t===1?e.messageCountLabelOne:ur(e.messageCountLabel,{count:t})}var dy,uy=be(()=>{"use strict";Rc();dy=864e5});function Ss(t,e=20){let n=document.createElementNS(Xu,"svg");if(n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),t==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(Xu,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=tB[t];if(o){let r=document.createElementNS(Xu,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of eB[t]){let s=document.createElementNS(Xu,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var Xu,eB,tB,my=be(()=>{"use strict";Xu="http://www.w3.org/2000/svg",eB={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},tB={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function oB(t){let e=$("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return nB.test(t)?e.appendChild($("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function TT(t){let{conversation:e,copy:n,busy:o,pending:r}=t,s=o||r!==null,a=e.title.trim().length>0,l=e.starred?(()=>{let g=Ss("star",11);return g.setAttribute("fill","currentColor"),g.setAttribute("stroke-width","1"),$("span",{className:"persona-history-row-star"},g,$("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,d=$("div",{className:"persona-history-row-head"},$("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,$("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:AT(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?$("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=$("button",{className:Vt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":rB(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?oB(t.avatar):null,$("div",{className:"persona-history-row-body"},d,p,$("span",{className:"persona-history-row-count persona-history-sr-only",text:MT(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let m=t.showDelete?fy({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:sB(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return $("li",{className:Vt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,m,t.menuOpen&&t.showDelete?iB(t):null,t.error?aB(t.error,n,e.id):null)}function iB(t){let{conversation:e,copy:n}=t;return gy({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Wc(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function fy(t){let e=$("button",{className:Vt("persona-history-icon-button",t.className),attrs:{type:"button","aria-label":t.label,"aria-haspopup":"menu","aria-expanded":t.open?"true":"false","data-persona-history-focus":t.focusKey,...t.inert?{"aria-disabled":"true"}:{}}});e.appendChild(Ss("ellipsis",t.iconSize));let n=()=>e.getAttribute("aria-disabled")==="true";return e.addEventListener("click",o=>{o.stopPropagation(),!n()&&t.onToggle()}),e.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||e.getAttribute("aria-expanded")==="true")&&t.onToggle())}),e}function gy(t){let e=$("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=$("button",{className:Vt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{t.onCloseMenu(),n.onSelect()}),e.appendChild(o)}return e.addEventListener("keydown",n=>{let o=Array.from(e.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){t.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),e}function aB(t,e,n){let o=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",t.retry),$("div",{className:"persona-history-row-error",attrs:{role:"alert"}},$("span",{text:t.message}),o)}var nB,rB,sB,Wc,ET=be(()=>{"use strict";Ye();my();uy();nB=/^(https?:|\/|data:)/i;rB=t=>`row:${t}`,sB=t=>`menu:${t}`,Wc=t=>`menu-item:${t}`});function lB(t){switch(t){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return t;default:return"unknown"}}function kT(t){if(gp(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=lB(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function cB(t,e){switch(t.state){case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};default:return null}}function dB(t,e){switch(t){case"authentication_required":case"authentication_failed":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription};default:return{title:e.errorTitle,description:e.errorDescription}}}function Ju(t,e,n,o){let r=$("button",{className:"persona-history-secondary persona-history-state-action",text:t,attrs:{type:"button","data-persona-history-focus":e,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function Bc(t,e,n,o,r){return $("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},$("p",{className:"persona-history-state-title",text:e}),$("p",{className:"persona-history-state-description",text:n}),o)}function pB(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>$("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},$("div",{className:"persona-history-skeleton-head"},$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),$("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return $("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function LT(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return pB(n);if(e.kind==="empty"){let l=cB(t.identityStatus,n);return l?Bc("identity",l.title,l.description,t.onRetry?Ju(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Bc("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?ur(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Bc("rate_limited",n.rateLimitedTitle,l,t.onRetry?Ju(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Bc("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Ju(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=dB(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Bc("error",r,s,e.retryable&&t.onRetry?Ju(a,"state-retry",o,t.onRetry):null,!0)}var PT=be(()=>{"use strict";Ye();Rc();_l()});function Zu(t){return`${t.state}:${"reason"in t?t.reason:""}`}function HT(t,e){switch(t.state){case"verified":return{title:e.verifiedTitle,description:e.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:e.verifyingTitle,description:e.verifyingDescription,pending:!0};case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription,pending:!1};default:return{title:e.browserOnlyTitle,description:e.browserOnlyDescription,pending:!1}}}function vB(t){return t.state==="verified"||t.state==="browser_only"}function CB(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function hy(t){let e=Hc(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??uB,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],a=null,l={kind:"loading",phase:"initial"},d=null,p=t.activeConversationId,u=t.provider.getIdentityStatus(),m=Zu(u),h=null,g=!1,b=!1,C=0,S=t.presentation,P=t.collapsible!==!1,M=t.collapsed===!0,B=t.railSide==="right",A=t.renderDom!==!1,O=new Map,E=null,W=vT(),R=F=>{!A&&t.onAnnounce?t.onAnnounce(F):W.announce(F)},V=()=>d!==null,H=`${r}-body`,w=$("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),T=()=>S==="rail"&&P,I,D=()=>{if(t.railBrand){if(!T()){w.classList.remove("persona-history-back--branded");return}if(I===void 0){let F=t.railBrand(!0);I=F?$("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},F):null}I&&(w.classList.add("persona-history-back--branded"),w.appendChild(I))}},G=()=>{let F=T(),le=S==="rail";w.setAttribute("data-persona-history-focus",F?"collapse":"close"),w.setAttribute("aria-label",F?M?e.expandLabel:e.collapseLabel:le?e.closeLabel:e.backLabel),F?(w.setAttribute("aria-expanded",M?"false":"true"),w.setAttribute("aria-controls",H),t.collapseShortcut?.aria&&w.setAttribute("aria-keyshortcuts",t.collapseShortcut.aria)):(w.removeAttribute("aria-expanded"),w.removeAttribute("aria-controls"),w.removeAttribute("aria-keyshortcuts")),w.replaceChildren(Ss(F?"panel-left":le?"x":"arrow-left")),D()};G(),w.addEventListener("click",()=>{T()?t.onToggleCollapse?.():t.onClose()});let z=$("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),K=$("span",{className:"persona-history-scope-title"}),Y=$("p",{className:"persona-history-scope"},$("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},Ss("monitor",14)),K),re=$("div",{className:"persona-history-heading-group"},z),oe=!1,se,ce=()=>{let F=S==="rail",le=F?t.renderRailHeader:void 0,Be=null,et=le!==void 0;if(le)try{Be=le({collapsed:M,defaultTitle:e.viewTitle})}catch(he){et=!1,oe||(oe=!0,console.warn("[persona] history rail renderHeader threw",he))}if(!et&&F&&t.railBrand){if(se===void 0){let he=t.railBrand(!1);se=he?$("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},$("span",{className:"persona-history-brand-mark"},he),$("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}se&&(et=!0,Be=se)}z.classList.toggle("persona-history-sr-only",et),re.replaceChildren(z),Be&&re.appendChild(Be)};ce();let we=$("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});we.appendChild(Ss("plus")),we.addEventListener("click",()=>{an()});let ge=[w,we].map(F=>t.attachTooltip?.({anchor:F,text:()=>F.getAttribute("aria-label")??"",...F===w&&t.collapseShortcut?{hint:()=>T()?t.collapseShortcut.hint:""}:{}})),N=$("div",{className:"persona-history-topbar"}),ye=null,ke=()=>{let F=S==="rail",le=F?B?"rail-right":"rail":"panel";le!==ye&&(ye=le,le==="rail"?N.append(re,w):N.append(w,re),F?we.remove():N.appendChild(we),Q.classList.toggle("persona-history-view--rail-right",le==="rail-right"))},nt=$("div",{className:"persona-history-scope-alert"}),Ee=`${r}-scope`,Ne=Ss("plus",18),Pe=$("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},Ne,$("span",{text:e.newConversationLabel}));Pe.addEventListener("click",()=>{an()});let dt=$("div",{className:"persona-history-list-region"}),Xe=t.showDeleteAll!==!1,xt=!!t.provider.resetDevice,Ge=t.listActions??[],yt=Xe||xt||Ge.length>0?fy({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${Ci}`,open:!1,inert:!0,iconSize:16,onToggle:()=>wi(Ci)}):null,X=$("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),L=$("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":Ci}},X,t.showScopeStatus?Y:null,yt),j=$("div",{className:"persona-history-body",attrs:{id:H}},t.showScopeStatus?nt:null,Pe,L,dt),J=t.headerPlacement??"inline";J==="external"&&N.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Q=$("div",{className:Vt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},W.element,J==="inline"?N:null,j),de=()=>{Q.classList.toggle("persona-history-view--rail-collapsed",M&&T())};de(),ke();let Me=(F,le)=>{let Be=`${r}-s${le}`,et=$("div",{className:Vt("persona-history-nav",F.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":F.id,...F.title?{"aria-labelledby":Be}:{"aria-label":F.id}}});F.title&&et.appendChild($("h3",{className:"persona-history-group-heading",text:F.title,attrs:{id:Be}}));for(let he of F.items){let We=he.iconNode?.()??null,Uo=$("button",{className:Vt("persona-history-nav-item",We&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":he.label,"data-persona-rail-item":he.id}},We?$("span",{className:"persona-history-nav-icon"},We):null,$("span",{className:"persona-history-nav-label persona-history-truncate",text:he.label}),he.badge?$("span",{className:"persona-history-nav-badge",text:he.badge}):null);Uo.addEventListener("click",()=>he.onSelect()),et.appendChild(Uo)}return et},Te=null,Fe=null,je=()=>{!Te||!A||S!=="rail"||M===Fe||(Fe=M,t.railSections.forEach((F,le)=>{if(!F.render)return;let Be=Te[le],et=F.title?Be.firstElementChild:null,he=null;try{he=F.render(M)}catch(We){F.render=void 0,console.warn("[persona] history rail section threw",F.id,We)}Be.replaceChildren(...et?[et]:[],...he?[he]:[]),Be.hidden=!he}))},lt=()=>{let F=t.railSections;if(Q.classList.toggle("persona-history-view--has-nav",S==="rail"&&!!F?.some(le=>le.placement==="above-conversations")),!!F?.length){if(S!=="rail"){Te?.forEach(le=>le.remove());return}Te??(Te=F.map(Me));for(let le of["above-conversations","below-conversations","footer"]){let Be=le==="above-conversations"?L.parentNode===j?L:dt:null;F.forEach((et,he)=>{et.placement===le&&j.insertBefore(Te[he],Be)})}je()}};lt(),Np(Q,"persona-history-view",wT);let ot=(F,le)=>{let Be=Q.ownerDocument.defaultView?.getComputedStyle(Q).getPropertyValue(F),et=Number.parseFloat(Be??"");return Number.isFinite(et)&&et>=0?et:le},Je=(F,le)=>Q.ownerDocument.defaultView?.getComputedStyle(Q).getPropertyValue(F).trim()||le,mt=null,Tt=()=>{mt!==null&&(clearTimeout(mt),mt=null),Q.removeEventListener("animationend",Tt),Q.classList.remove("persona-history-view--enter")};Q.addEventListener("animationend",Tt),mt=setTimeout(()=>{mt=setTimeout(Tt,ot("--persona-history-enter-ms",mB)+60)},0);let ee=null,Oe=()=>{ee!==null&&(clearTimeout(ee),ee=null),N.classList.remove("persona-history-topbar--shell-enter")},$e=()=>{Oe(),N.classList.add("persona-history-topbar--shell-enter"),ee=setTimeout(Oe,IT+60)};J==="external"&&(ee=setTimeout(Oe,IT+60));let pt=[],_t=null,ve=()=>{if(_t)return _t;if(b||yB()||typeof Q.animate!="function")return Tt(),null;let F=Q.ownerDocument.defaultView?.getComputedStyle(j).opacity||"1";Tt(),Q.style.pointerEvents="none",Ke.style.pointerEvents="none";let le={duration:ot("--persona-history-exit-ms",fB),easing:Je("--persona-history-exit-easing",gB),fill:"forwards"},Be=hB[S];return pt=[j.animate([{opacity:F,transform:"none"},{opacity:0,transform:`translateX(${Be}px)`}],le)],_t=Promise.all(pt.map(bB)).then(()=>{}),_t},Se=(F,le)=>{F&&(le?F.setAttribute("aria-disabled","true"):F.removeAttribute("aria-disabled"))},Ke=N,ut=null,vn=()=>{let F=t.slots?.header;if(!F)return;let le=`${S}|${Zu(u)}|${d?`${d.kind}:${"conversationId"in d?d.conversationId:""}`:""}`;if(le===ut)return;ut=le;let Be=F({identityStatus:u,pendingAction:d,copy:e,defaultRenderer:()=>N})??N;Be!==Ke&&(Ke.replaceWith(Be),Ke=Be)},Cn=null,wn=()=>{if(!t.showScopeStatus)return;let F=Zu(u);if(F===Cn)return;Cn=F;let le=HT(u,e);K.textContent=le.title;let Be=vB(u);if(Y.hidden=!Be,nt.replaceChildren(...Be?[]:[$("span",{className:"persona-history-scope-alert-title",text:le.title})],$("span",{className:"persona-history-scope-description",text:le.description,attrs:{id:Ee}})),nt.setAttribute("data-persona-history-scope-tone",Be?"ambient":"attention"),Be?Y.setAttribute("aria-describedby",Ee):Y.removeAttribute("aria-describedby"),le.pending?nt.setAttribute("role","status"):nt.removeAttribute("role"),nt.setAttribute("data-persona-history-identity",u.state),Y.setAttribute("data-persona-history-identity",u.state),CB(u)){let et=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});et.addEventListener("click",()=>{V()||Ae("refresh")}),nt.appendChild(et)}},Wt=F=>d?d.kind==="open"&&d.conversationId===F?"opening":d.kind==="delete"&&d.conversationId===F?"deleting":null:null,St=()=>{let F=document.activeElement;return!(F instanceof HTMLElement)||!Q.contains(F)?null:F.getAttribute("data-persona-history-focus")},Et=F=>{if(g&&h){g=!1;let le=Q.querySelector(`[data-persona-history-focus="${Wc(h)}"]`);if(le){le.focus();return}}F&&Q.querySelector(`[data-persona-history-focus="${F}"]`)?.focus()},sn=()=>{if(!E)return null;let F=$("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),le=E;return F.addEventListener("click",()=>{V()||le.retry()}),$("div",{className:"persona-history-row-error",attrs:{role:"alert"}},$("span",{text:le.message}),F)},Rn=()=>ST(s,n(),e,t.grouping).map((F,le)=>{let Be=`${r}-g${le}`,et=$("ul",{className:"persona-history-list",attrs:{"aria-labelledby":Be}});for(let he of F.items){let We=()=>TT({conversation:he,active:he.id===p,pending:Wt(he.id),busy:V(),menuOpen:h===he.id,error:O.get(he.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{Wn(he.id)},onToggleMenu:()=>wi(he.id),onCloseMenu:$r=>Re($r),onDelete:()=>{bt(he.id)}}),qo=t.slots?.conversation?.({conversation:he,active:he.id===p,pending:Wt(he.id),open:()=>Wn(he.id),requestDelete:()=>bt(he.id),defaultRenderer:We})??We();et.appendChild(qo instanceof HTMLLIElement?qo:$("li",{className:"persona-history-item"},qo))}return $("div",{className:"persona-history-group",attrs:{"data-persona-history-group":F.key}},$("h3",{className:Vt("persona-history-group-heading",F.key==="recent"&&"persona-history-sr-only"),text:F.label,attrs:{id:Be}}),et)}),tn=()=>{if(!a)return null;let F=d?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",le=$("button",{className:"persona-history-secondary persona-history-load-more",text:F?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...F?{"aria-busy":"true","aria-disabled":"true"}:{},...V()&&!F?{"aria-disabled":"true"}:{}}});return le.addEventListener("click",()=>{V()||Ae("load-more")}),le},it=()=>{let F=St(),le=[sn()],Be=s.length>0;if(Be&&(le.push(...Rn()),le.push(tn())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&Be)){let he=l,We=he.kind==="loading"?void 0:()=>Ae("refresh"),Uo=he.kind==="new_conversation_required"?()=>an():void 0,qo=()=>LT({state:he,copy:e,identityStatus:u,busy:V(),...We?{onRetry:()=>{We()}}:{},...Uo?{onStartNew:()=>{Uo()}}:{}}),$r=t.slots?.state?.({state:he,identityStatus:u,copy:e,...We?{retry:We}:{},...Uo?{startNewConversation:Uo}:{},defaultRenderer:qo});le.push($r??qo())}dt.replaceChildren(...le.filter(he=>!!he)),Et(F)},_e=()=>{let F=l.kind==="loading"&&s.length===0,le=[],Be=()=>le.length===0?Wc(Ci):`${Wc(Ci)}-${le.length}`;if(!F)for(let et of Ge)le.push({label:et.label,focusKey:Be(),danger:et.danger===!0,onSelect:()=>{et.onSelect({conversations:[...s]})}});return Xe&&!(s.length===0&&(l.kind==="empty"||F))&&le.push({label:e.clearHistoryLabel,focusKey:Be(),danger:!0,onSelect:()=>{_a()}}),xt&&!F&&le.push({label:e.resetIdentityLabel,focusKey:Be(),danger:!0,onSelect:()=>{Na()}}),le},Kt=()=>{if(Se(Pe,V()),Se(we,V()),yt){let F=_e(),le=l.kind==="loading"&&s.length===0;yt.hidden=F.length===0&&!le,Se(yt,V()||F.length===0),yt.setAttribute("aria-expanded",h===Ci?"true":"false");let Be=L.querySelector(".persona-history-menu");if(h!==Ci||F.length===0)Be?.remove();else{let et=gy({label:e.listOptionsLabel,items:F,onCloseMenu:he=>Re(he)});Be?Be.replaceWith(et):L.appendChild(et)}}L.hidden=S!=="rail"&&(!yt||yt.hidden)&&(!t.showScopeStatus||Y.hidden)},Ze,Le=()=>{let F=t.onActiveConversationChange;if(!F)return;let le=s.find(et=>et.id===p)??null,Be=le?`${le.id}\0${le.title}\0${le.starred?1:0}`:"";Be!==Ze&&(Ze=Be,F(le))},ie=()=>{if(!b){if(Le(),!A){t.onModelChange?.();return}vn(),wn(),Kt(),it(),je()}},Re=F=>{if(!h)return;let le=h;h=null,g=!1,ie(),F?.restoreFocus&&Q.querySelector(`[data-persona-history-focus="menu:${le}"]`)?.focus()},wi=F=>{if(h===F){Re({restoreFocus:!0});return}h=F,g=!0,ie()},Vr=F=>{if(!h)return;let le=F.target;le instanceof Node&&Q.contains(le)&&le.closest?.(`[data-persona-history-item="${h}"]`)||Re()};document.addEventListener("pointerdown",Vr,!0);let Io=F=>{F.key!=="Escape"||!h||(F.stopPropagation(),Re({restoreFocus:!0}))};Q.addEventListener("keydown",Io);async function Ae(F){if(b)return;let le=++C,Be=F==="load-more"?a:null;if(!(F==="load-more"&&!Be)){d={kind:F==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:F},F!=="load-more"&&(O.clear(),E=null),Re(),ie();try{let et=await t.provider.list({limit:o,context:t.context,...Be?{cursor:Be}:{},...t.targetId?{targetId:t.targetId}:{}});if(b||le!==C)return;s=Be?[...s,...et.items]:et.items,a=et.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(et){if(b||le!==C)return;l=kT(et)}finally{!b&&le===C&&(d=null,ie())}}}let Ve=F=>{s=s.filter(le=>le.id!==F),O.delete(F),p===F&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function Wn(F){if(!(V()||b)){O.delete(F),Re(),d={kind:"open",conversationId:F},ie();try{if(await t.onSelect(F),b)return;p=F}catch{if(b)return;O.set(F,{message:e.openFailedLabel,retry:()=>{Wn(F)}})}finally{b||(d=null,ie())}}}async function bt(F){if(V()||b)return"cancelled";O.delete(F),d={kind:"delete",conversationId:F},ie();try{let le=await t.onRequestDeleteConversation(F);return b||le==="deleted"&&(Ve(F),R(e.conversationRemovedNotice)),le}catch(le){return b||(gp(le)&&le.code==="not_found"?Ve(F):O.set(F,{message:e.deleteFailedLabel,retry:()=>{bt(F)}})),"cancelled"}finally{b||(d=null,ie())}}async function an(){if(!(V()||b)){E=null,Re(),d={kind:"start-new"},ie();try{if(await t.onStartNew(),b)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(b)return;E={message:e.errorDescription,retry:()=>{an()}}}finally{b||(d=null,ie())}}}async function _a(){if(V()||b)return"cancelled";E=null,Re(),d={kind:"clear"},ie();try{let F=await t.onRequestClearHistory();return b||F==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},R(e.historyClearedNotice)),F}catch{return b||(E={message:e.errorDescription,retry:()=>{_a()}}),"cancelled"}finally{b||(d=null,ie())}}let kn={outcome:"cancelled"};async function Na(){if(V()||b||!t.onRequestResetIdentity)return kn;E=null,Re(),d={kind:"reset"},ie();try{let F=await t.onRequestResetIdentity();return b||F.outcome==="reset"&&(R(F.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),d=null,await Ae("refresh")),F}catch{return b||(E={message:e.errorDescription,retry:()=>{Na()}}),kn}finally{!b&&d?.kind==="reset"&&(d=null,ie())}}let om=t.provider.subscribeIdentityStatus(F=>{if(b)return;let le=Zu(F),Be=le!==m;u=F,m=le,ie(),Be&&F.state!=="verifying"&&R(HT(F,e).title)}),rm=t.provider.subscribeAvailability?.(F=>{if(!b){if(F){Ae("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},ie()}});return ie(),Ae("initial"),{element:Q,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:d,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{V()||await Ae("refresh")},loadMore:async()=>{V()||await Ae("load-more")},openConversation:F=>Wn(F),startNewConversation:()=>an(),requestDeleteConversation:F=>bt(F),requestClearConversationHistory:()=>_a(),requestResetHistoryIdentity:()=>Na()},setDomRenderEnabled:F=>{F!==A&&(A=F,F&&ie())},refresh:()=>{Ae("refresh")},setPresentation:F=>{if(F===S)return;Tt(),S=F,ut=null;let le=F==="rail";Q.classList.toggle("persona-history-view--panel",!le),Q.classList.toggle("persona-history-view--rail",le),Q.setAttribute("data-persona-history-presentation",F),G(),de(),ke(),ce(),lt(),ie()},setCollapsed:F=>{F!==M&&(M=F,de(),G(),ce(),je())},setRailSide:F=>{B=F==="right",ke()},getHeaderElement:()=>Ke,setHeaderPlacement:F=>{if(F===J)return;J=F;let le=F==="external";if(N.classList.toggle("persona-history-topbar--shell",le),le){$e(),Ke.remove();return}Oe(),Q.insertBefore(Ke,j)},setActiveConversationId:F=>{p!==F&&(p=F,ie())},applyConversationSummary:F=>{let le=s.findIndex(Be=>Be.id===F.id);le!==-1&&(s[le]=F,ie())},removeConversationSummary:F=>{s.some(le=>le.id===F)&&(Ve(F),ie())},setNewConversationRequired:F=>{F?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),ie()},playExit:ve,destroy:()=>{b=!0,C+=1,Tt(),Oe(),ge.forEach(F=>F?.destroy()),Ke.remove(),pt.forEach(F=>F.cancel()),pt=[],om(),rm?.(),document.removeEventListener("pointerdown",Vr,!0),Q.removeEventListener("keydown",Io),W.destroy(),Q.remove(),Q.replaceChildren()}}}var uB,Ci,mB,IT,fB,gB,hB,yB,bB,RT=be(()=>{"use strict";ya();Ye();CT();xT();Rc();uy();my();ET();PT();_l();uB=25,Ci="persona:list-options",mB=180,IT=120,fB=160,gB="cubic-bezier(0.4, 0, 1, 1)",hB={panel:20,rail:12},yB=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,bB=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var yy=be(()=>{"use strict";RT();Rc()});var WT={};Vn(WT,{HISTORY_VIEW_COPY_DEFAULTS:()=>Ic,createHistoryView:()=>hy,resolveHistoryViewCopy:()=>Hc});var BT=be(()=>{"use strict";yy();yy()});var o1={};Vn(o1,{createThemePreview:()=>aE});module.exports=k0(o1);function mC(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function no(t){return t?.type==="runtype"||t?.type==="custom"}var L0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function fC(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:L0()}catch{return!1}}Xd();Ff();var wC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,xC=t=>t.includes("|"),SC=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},O0=t=>`| ${t.join(" | ")} |`,D0=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,_0=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),AC=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
1141
1141
  `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!xC(r)||wC.test(r)||!wC.test(s))continue;let a=SC(r).length;if(a<1)continue;let l=D0(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let d=o+2;for(;d<e.length;d++){let p=e[d];if(p.trim()===""||!xC(p))break;let u=O0(_0(SC(p),a));e[d]!==u&&(e[d]=u,n=!0)}o=d-1}return n?e.join(`
1142
- `):t};var MC="var(--persona-md-table-scroll-fade, 24px)",TC=new WeakSet;function kC(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function EC(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":MC),t.style.setProperty("--persona-fade-r",r<=1?"0px":MC)}function Vf(t){TC.has(t)||(TC.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&EC(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(EC)}ti();na();oo();var{setLoader:E1,load:Q0}=$t({fallbackImport:()=>Promise.resolve().then(()=>(DC(),OC))});var _C=Q0;function Mo(t){return t==="card"?"collapsed":t}function oa(t){return t.split(";",1)[0].trim().toLowerCase()}function X0(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(oa(r)===e)return{mode:Mo(s),selector:oa(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(oa(r)===o)return{mode:Mo(s),selector:o}}function J0(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Mo(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?oa(e.file.mimeType):void 0,d=l?X0(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:Mo(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:Mo(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:Mo(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:Mo(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Mo(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function is(t,e){return J0(t,e).mode}function El(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Z0="agent_",eL="flow_";function NC(t){return t.startsWith(Z0)?{kind:"agentId",agentId:t}:t.startsWith(eL)?{kind:"flowId",flowId:t}:null}function FC(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=NC(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=NC(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function op(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ra(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function VC(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var as=require("partial-json");Ye();var zf="ask_user_question",kl=8,sa="data-persona-ask-sheet-for",tL="Other",nL="Other\u2026",UC="Type your own answer here",qC="Send",oL="Next",rL="Back",sL="Submit all",iL="Skip",aL=3,Uf="data-ask-current-index",qf="data-ask-question-count",jC="data-ask-answers",jf="data-ask-grouped",KC="data-ask-layout",lL=t=>t.layout==="pills"?"pills":"rows",cL=t=>t.getAttribute(KC)==="pills"?"pills":"rows",zC=!1,GC=t=>t.replace(/["\\]/g,"\\$&"),ni=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===zf,Kf=t=>t?.features?.askUserQuestion??{},ia=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,as.parse)(r,as.STR|as.OBJ|as.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ll=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>kl&&!zC&&(zC=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${kl}.`)),e.slice(0,kl)},dL=t=>Ll(t)[0]??null,pL=(t,e)=>Ll(t)[e]??null,uL=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},YC=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},mL=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let p=v("span","persona-ask-row-description");p.textContent=t.description,a.appendChild(p)}s.appendChild(a);let d=YC(n,o,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},fL=t=>{let n=v("span",t==="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 n.setAttribute("aria-hidden","true"),n},gL=(t,e,n,o)=>{let s=v("div",o==="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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<aL;u++)s.appendChild(fL(o));return s}if(d.forEach((u,m)=>{s.appendChild(mL(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?tL:nL;if(o==="rows"){let m=v("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(d.length)),m.setAttribute("data-ask-other-row","true");let h=v("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=e.freeTextPlaceholder??UC,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??u),h.appendChild(g),m.appendChild(h);let b=YC(o,a,d.length);b&&m.appendChild(b),s.appendChild(m)}else{let m=v("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=e.freeTextLabel??u,s.appendChild(m)}}return s},QC=(t,e)=>{let o=v("div",e==="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");o.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=t.freeTextPlaceholder??UC,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??qC,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},hL=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??qC,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},yL=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??rL,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??iL,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=t===e-1;return l.textContent=d?n.submitAllLabel??sL:n.nextLabel??oL,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},oi=t=>{let e=t.getAttribute(jC);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},XC=(t,e)=>{t.setAttribute(jC,JSON.stringify(e))},To=t=>{let e=Number(t.getAttribute(Uf)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},bL=(t,e)=>{t.setAttribute(Uf,String(Math.max(0,Math.floor(e))))},aa=t=>{let e=Number(t.getAttribute(qf)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ls=t=>t.getAttribute(jf)==="true",vL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},CL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},rp=(t,e)=>{let{payload:n}=ia(e),o=Ll(n),r=oi(t),s={},a=new Set;return o.forEach((l,d)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},JC=t=>{let e=oi(t),n=To(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",u=r.has(p);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ZC=t=>{if(!ls(t))return;let e=oi(t),n=To(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Gf=(t,e,n)=>{let o=Kf(n),r=cL(t),{payload:s,complete:a}=ia(e),l=ls(t),d=To(t),p=aa(t),u=l?pL(s,d):dL(s),m=!!u?.multiSelect,h=t.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=l?`${d+1}/${p}`:"");let g=t.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let M=typeof u?.question=="string"?u.question:"";b.textContent=M,b.classList.toggle("persona-ask-question-skeleton",!M&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let M=gL(u,o,a,r);C.replaceWith(M)}if(r!=="rows"){let M=t.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(QC(o,r))}let S=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!S?t.appendChild(hL(o)):(!m||l)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let P=t.querySelector('[data-ask-nav-row="true"]');if(l){let M=yL(d,p,o);P?P.replaceWith(M):t.appendChild(M)}else P&&P.remove();JC(t),ZC(t)},wL=(t,e,n)=>{let o=Kf(e),r=lL(o),s=t.toolCall.id,a=Ll(n),l=Math.max(1,a.length),d=l>1,p=vL(t,a),u=d?CL(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(sa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(qf,String(l)),m.setAttribute(Uf,String(u)),m.setAttribute(jf,d?"true":"false"),m.setAttribute(KC,r),XC(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),uL(m,o);let h=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=v("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",h.appendChild(g);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",h.appendChild(b),m.appendChild(h);let S=v("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 S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),r!=="rows"&&m.appendChild(QC(o,r)),Gf(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},xL=(t,e,n)=>{let{payload:o}=ia(e),r=Math.max(1,Ll(o).length);r>aa(t)&&(t.setAttribute(qf,String(r)),r>1&&!ls(t)&&t.setAttribute(jf,"true")),Gf(t,e,n)};var sp=(t,e,n)=>{if(!n||!ni(t)||Kf(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${sa}]`).forEach(p=>{p.getAttribute(sa)!==r&&p.remove()});let a=n.querySelector(`[${sa}="${GC(r)}"]`);if(a){xL(a,t,e);return}let{payload:l}=ia(t),d=wL(t,e,l);n.appendChild(d)},la=(t,e)=>{if(!t)return;let n=e?`[${sa}="${GC(e)}"]`:`[${sa}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Yf=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),cs=(t,e)=>{let n=oi(t),o=To(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,XC(t,n),JC(t),ZC(t)},ip=(t,e,n,o)=>{let r=aa(t),s=Math.max(0,Math.min(r-1,o));bL(t,s),Gf(t,e,n)};var ds="suggest_replies";var SL={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},tw={name:ds,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:SL,origin:"sdk",annotations:{readOnlyHint:!0}},nw=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Pl=t=>t.variant==="tool"&&t.toolCall?.name===ds,AL=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},ow=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Pl(n))continue;let o=AL(n.toolCall?.args);return o.length>0?o:null}return null},ew=new Set,ML=(t,e,n)=>{let o=`${t}:${e}:${n}`;ew.has(o)||(ew.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},ps=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],d=n?.[a];l===void 0||d===void 0||l!==d&&ML(a,d,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var TL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:kl,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},EL={name:zf,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:TL,origin:"sdk",annotations:{readOnlyHint:!0}},ap=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(EL),ps(t).expose&&e.push(tw),e};ri();var uw="4.22.1";var si=uw;var da="[Image]";function mw(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function pp(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function rr(t){return{type:"text",text:t}}function fw(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var gw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],WL=["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=[...gw,...WL];function BL(t){return gw.includes(t)||t.startsWith("image/")}function up(t){return BL(t.type)}function hw(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function yw(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;up(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function bw(t,e=Hr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function OL(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function vw(t,e){let n=OL(e).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"}[t]||n||"FILE"}var DL=["user","assistant","system"],_L=0;function Cw(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function mp(t){return typeof t=="string"?t:void 0}function NL(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?rr(e.text):null;case"image":return typeof e.image=="string"?fw(e.image,{mimeType:mp(e.mimeType),alt:mp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?hw(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...mp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...mp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function FL(t,e){let n=Cw(e),o=t.map(a=>Cw(a.timestamp)),r=new Array(t.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let h=0;h<d;h+=1)r[s+h]=m!==null?m-(d-h):p!==null?p+h+1:_L+h;s=l+1}return r.map(a=>new Date(a).toISOString())}function ww(t,e){let n=FL(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!DL.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(NL).filter(u=>u!==null),p=mw(d);o.push({id:r.id,role:a,content:p||(pp(d)?da:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Wl(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Bl(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var VL="https://api.runtype.com/v1/dispatch",xw="https://api.runtype.com",at=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Sw=32768,Xf=49152,Aw=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},Mw=t=>"reason"in t?t.reason:void 0,Tw="The identity proof was not admitted; account history is unavailable",Ew="The identity proof was rejected",kw="The request carried no visitor credential",Lw="The stored visitor belongs to a different signed-in user",Jf=(t,e)=>t instanceof at&&t.code===e;function $L(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Zf=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function zL(t){switch(t){case"json":return dw;case"regex-json":return cw;case"xml":return pw;default:return lw}}var Pw=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function UL(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Pw(n);if(!Pw(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Rl(t);return Rl(e)!==null&&a===null?e:t}var Ol=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;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(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??VL,this.headers={"Content-Type":"application/json","X-Persona-Version":si,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??zL(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return _C().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:IC,getToolDisplayTitle:Zd,loadPolyfill:RC});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),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(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=FC(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||xw}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new at("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:e.after}),d=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":si,"X-Visitor-Token":s},signal:e.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}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 e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.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 e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}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 e=this.historyIdentityStatus;return e?.state==="browser_only"?e: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(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&Mw(n)===Mw(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||e.durableResume?e.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(d)});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new at("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new at("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&m.error==="visitor_required"?new at("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new at("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let r=await this.createClientSession({conversationId:e,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,e,!1)}catch(r){if(!Jf(r,"not_found")&&!Jf(r,"visitor_required")&&!Jf(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new at("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new at("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}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(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new at("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new at("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new at("proof_not_admitted",Tw);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new at("invalid_identity_proof",Ew);if(r.includes("visitor token required"))throw new at("visitor_token_missing",kw);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new at("visitor_identity_mismatch",Lw);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new at("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new at("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new at("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new at("proof_not_admitted",Tw);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new at("invalid_identity_proof",Ew)):r.includes("visitor token required")?new at("visitor_token_missing",kw):r.includes("visitor_identity_mismatch")?new at("visitor_identity_mismatch",Lw):new at("unauthorized",o||"History request was not authorized")}return new at("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new at("identity_contract_violation","Server reported an ignored identity proof on a success response"):new at("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new at("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new at("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":si,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),h=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new at("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new at("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Aw),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Aw(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>Sw)throw new at("payload_too_large",`displayContent exceeds the ${Sw} character limit`);o+=p}if(o>Xf)throw new at("payload_too_large",`Display projection batch exceeds the ${Xf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Xf,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.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(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=VC();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=await this.initSession();if(new Date>=new Date(a.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let b=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:b}),b}let l=await this.buildPayload(e.messages),d=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null,p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([b])=>b!=="sessionId"&&b!=="session_id")):void 0,u=this.isHistoryCapable(),m={sessionId:a.sessionId,messages:e.messages.filter(Zf).map(b=>{let C=u?Wl(b):void 0;return{id:b.id,role:b.role,content:b.contentParts??b.llmContent??b.rawContent??b.content,...C!==void 0&&{displayContent:C}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},{response:h,commit:g}=await this.sendWithClientToolsDiff(a.sessionId,l.clientTools,b=>{let C={...m,...b};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si,...d?{"X-Visitor-Token":d}:{}},body:JSON.stringify(C),signal:e.signal})});if(!h.ok){let b=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let S=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:S}),S}if(h.status===429){let S=new Error(b.hint||"Message limit reached for this session.");throw s({type:"error",error:S}),S}if(h.status===410&&b.error==="conversation_deleted"){let S=new at("conversation_deleted","This conversation was deleted");throw s({type:"error",error:S}),S}let C=new Error(b.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!h.body){let b=new Error("No response body received");throw s({type:"error",error:b}),b}g(),s({type:"status",status:"connected"});try{await this.streamResponse(h.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof at)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?HC(n):void 0,l=this.clientToolsFingerprintSessionId===e,d=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let h=0;;h++){if(m=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&h===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||xw}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let d={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(a,u,g=>{let b={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",b),fetch(s,{method:"POST",headers:d,body:JSON.stringify(b),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(s=>s.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Zf).filter(p=>p.role==="user"||p.role==="assistant"||p.role==="system").filter(p=>!p.variant||p.variant==="assistant").sort((p,u)=>{let m=new Date(p.createdAt).getTime(),h=new Date(u.createdAt).getTime();return m-h}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(e);return d&&(a.context=d),a}async buildPayload(e,n){let o=e.slice().filter(Zf).sort((p,u)=>{let m=new Date(p.createdAt).getTime(),h=new Date(u.createdAt).getTime();return m-h}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(e);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=X=>{let L=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,j=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,J=X.tools?X.tools.map(Q=>({...Q,chunks:Q.chunks?[...Q.chunks]:void 0})):void 0;return{...X,reasoning:L,toolCall:j,tools:J}},h=X=>{if(X.role!=="assistant"||X.variant)return!0;let L=Array.isArray(X.contentParts)&&X.contentParts.length>0,j=typeof X.rawContent=="string"&&X.rawContent.trim()!=="";return typeof X.content=="string"&&X.content.trim()!==""||L||j||!!X.stopReason},g=X=>{h(X)&&n({type:"message",message:m(X)})},b=null,C=null,S={current:null},P={current:null},M=null,B="",A=new Map,O=new Map,E=new Map,W=new Map,R=new Map,V=o,H=!1,w=()=>{if(b)return b;let X,L="",j=M;return!H&&V?(X=V,H=!0,L=r??""):V&&j?X=`${V}_${j}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:X,role:"assistant",content:L,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(b),b},T=X=>{let L=W.get(X);if(L)return L;let j={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:X,status:"streaming",chunks:[]}};return W.set(X,j),g(j),j},I=new Set,D=new Map,G=new Set,z=new Map,K=X=>{if(!X)return!1;let L=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return L==="emit_artifact_markdown"||L==="emit_artifact_component"},Y=X=>{let L=R.get(X);if(L)return L;let j={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:X,status:"pending"}};return R.set(X,j),g(j),j},re=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let L=Number(X);if(!Number.isNaN(L)&&Number.isFinite(L))return L;let j=Date.parse(X);if(!Number.isNaN(j))return j}return Date.now()},oe=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},se=new Map,ce=new Map,we=(X,L)=>{let j=oe(L),J=ce.get(X.id),Q=UL(J,j);X.rawContent=Q;let de=se.get(X.id),Me=ot=>{let Je=X.content??"";ot.trim()!==""&&(Je.trim().length===0||ot.startsWith(Je)||ot.trimStart().startsWith(Je.trim()))&&(X.content=ot)},Te=()=>{if(de){let ot=de.close?.();ot instanceof Promise&&ot.catch(()=>{})}se.delete(X.id),ce.delete(X.id),X.streaming=!1,g(X)};if(!de){Me(j),Te();return}let Fe=Rl(Q);if(Fe!==null&&Fe.trim()!==""){Me(Fe),Te();return}let je=ot=>{let Je=typeof ot=="string"?ot:ot?.text??null;if(Je!==null&&Je.trim()!=="")return Je;let mt=de.getExtractedText();return mt!==null&&mt.trim()!==""?mt:j},lt;try{lt=de.processChunk(Q)}catch{Me(j),Te();return}if(lt instanceof Promise){lt.then(ot=>{Me(je(ot)),Te()}).catch(()=>{Me(j),Te()});return}Me(je(lt)),Te()},ge=null,N=(X,L,j,J)=>{X.rawContent=L,se.has(X.id)||se.set(X.id,this.createStreamParser());let Q=se.get(X.id),de=L.trim().startsWith("{")||L.trim().startsWith("[");if(de&&ce.set(X.id,L),Q.__isPlainTextParser===!0){X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X);return}let Te=Q.processChunk(L);if(Te instanceof Promise)Te.then(Fe=>{let je=typeof Fe=="string"?Fe:Fe?.text??null;je!==null&&je.trim()!==""?(X.content=je,g(X)):!de&&!L.trim().startsWith("<")&&(X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X))}).catch(()=>{X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X)});else{let Fe=typeof Te=="string"?Te:Te?.text??null;Fe!==null&&Fe.trim()!==""?(X.content=Fe,g(X)):!de&&!L.trim().startsWith("<")&&(X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X))}},ye=(X,L)=>{let j=L??X.content;if(j==null||j===""){X.streaming=!1,g(X);return}let Q=ce.get(X.id)??oe(j);X.rawContent=Q;let de=se.get(X.id),Me=null,Te=!1;if(de&&(Me=de.getExtractedText(),Me===null&&(Me=Rl(Q)),Me===null)){let Fe=de.processChunk(Q);Fe instanceof Promise?(Te=!0,Fe.then(je=>{let lt=typeof je=="string"?je:je?.text??null;lt!==null&&(X.content=lt,X.streaming=!1,se.delete(X.id),ce.delete(X.id),g(X))}).catch(()=>{})):Me=typeof Fe=="string"?Fe:Fe?.text??null}if(!Te){Me!==null&&Me.trim()!==""?X.content=Me:ce.has(X.id)||(X.content=oe(j));let Fe=se.get(X.id);if(Fe){let je=Fe.close?.();je instanceof Promise&&je.catch(()=>{}),se.delete(X.id)}ce.delete(X.id),X.streaming=!1,g(X)}},ke=(X,L,j)=>{let J=O.get(X);if(J)return J;let Q={id:`nested-${L}-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...j?{variant:j}:{},...j==="reasoning"?{reasoning:{id:X,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:L}};return O.set(X,Q),g(Q),Q},nt=[],Ee,Ne=new Map,Pe=0,dt="agent",Xe=!1,xt=null,Ge=null,yt=this.config.iterationDisplay??"separate";for(Ee=()=>{for(let X=0;X<nt.length;X++){let L=nt[X];if(!Xe&&dt!=="flow"&&typeof L.stepType=="string"&&(dt="flow"),L.type==="reasoning_start"){let j=typeof L.id=="string"?L.id:null,J=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if(j&&J){A.set(j,J),ke(j,J,"reasoning");continue}let Q=L.id,de=T(Q);de.reasoning=de.reasoning??{id:Q,status:"streaming",chunks:[]},de.reasoning.startedAt=de.reasoning.startedAt??Date.now(),de.reasoning.completedAt=void 0,de.reasoning.durationMs=void 0,(L.scope==="loop"||L.scope==="turn")&&(de.reasoning.scope=L.scope),de.streaming=!0,de.reasoning.status="streaming",g(de)}else if(L.type==="reasoning_delta"){let j=typeof L.id=="string"?L.id:null;if(j&&A.has(j)&&O.has(j)){let de=O.get(j),Me=L.delta;Me&&de.reasoning&&(de.reasoning.chunks.push(String(Me)),g(de));continue}let J=L.id,Q=T(J);Q.reasoning=Q.reasoning??{id:J,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Date.now(),L.delta&&Q.reasoning.chunks.push(L.delta),Q.reasoning.status="streaming",Q.streaming=!0,g(Q)}else if(L.type==="reasoning_complete"){let j=typeof L.id=="string"?L.id:null;if(j&&A.has(j)&&O.has(j)){let Me=O.get(j);if(Me.reasoning){let Te=typeof L.text=="string"?L.text:"";Te&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Te),Me.reasoning.status="complete",Me.streaming=!1,g(Me)}A.delete(j),O.delete(j);continue}let J=L.id,Q=typeof L.text=="string"?L.text:"";!W.get(J)&&(Q||L.scope==="loop")&&T(J);let de=W.get(J);if(de?.reasoning){(L.scope==="loop"||L.scope==="turn")&&(de.reasoning.scope=L.scope),Q&&de.reasoning.chunks.length===0&&de.reasoning.chunks.push(Q),de.reasoning.status="complete",de.reasoning.completedAt=Date.now();let Me=de.reasoning.startedAt??Date.now();de.reasoning.durationMs=Math.max(0,(de.reasoning.completedAt??Date.now())-Me),de.streaming=!1,g(de)}}else if(L.type==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof L.iteration=="number"&&(Pe=L.iteration);let j=L.toolCallId,J=L.toolName;if(K(J)){I.add(j);continue}let Q=Y(j),de=Q.toolCall??{id:j,status:"pending"};de.name=J??de.name,de.status="running",de.success=void 0,de.error=void 0,de.duration=void 0,L.parameters!==void 0&&(de.args=L.parameters),de.startedAt=de.startedAt??re(L.startedAt),de.completedAt=void 0,de.durationMs=void 0,Q.toolCall=de,Q.streaming=!0,L.executionId&&(Q.agentMetadata={executionId:L.executionId,iteration:L.iteration}),g(Q)}else if(L.type==="tool_output_delta"){let j=L.toolCallId;if(I.has(j))continue;let J=Y(j),Q=J.toolCall??{id:j,status:"running"};Q.startedAt=Q.startedAt??Date.now();let de=L.delta;de&&(Q.chunks=Q.chunks??[],Q.chunks.push(String(de))),Q.status="running",J.toolCall=Q,J.streaming=!0,L.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:L.executionId,iteration:Pe}),g(J)}else if(L.type==="tool_complete"){let j=L.toolCallId;if(I.has(j)){I.delete(j);continue}let J=Y(j),Q=J.toolCall??{id:j,status:"running"};Q.status="complete",L.result!==void 0&&(Q.result=L.result),Q.name=L.toolName??Q.name,Q.success=L.success,Q.error=L.error,Q.completedAt=Date.now();let de=L.executionTime;if(typeof de=="number")Q.durationMs=de,Q.duration=de;else{let Me=Q.startedAt??Date.now();Q.durationMs=Math.max(0,(Q.completedAt??Date.now())-Me)}J.toolCall=Q,J.streaming=!1,L.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:L.executionId,iteration:L.iteration??Pe}),g(J)}else if(L.type==="await"&&L.toolName){let j=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,J=j??L.toolId??`local-${u()}`,Q=Y(J),de=L.toolName,Me=L.origin==="webmcp"&&!ta(de)?`webmcp:${de}`:de,Te=ta(Me),Fe=Q.toolCall??{id:J,status:"pending"};Fe.name=Me,Fe.args=L.parameters,Fe.status=Te?"running":"complete",Fe.chunks=Fe.chunks??[],Fe.startedAt=Fe.startedAt??re(L.awaitedAt),Te?(Fe.completedAt=void 0,Fe.duration=void 0,Fe.durationMs=void 0):Fe.completedAt=Fe.completedAt??Fe.startedAt,Q.toolCall=Fe,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:L.executionId??Q.agentMetadata?.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Q)}else if(L.type==="text_start"){let j=typeof L.id=="string"?L.id:null,J=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if(j&&J){A.set(j,J);continue}let Q=b;Q&&(dt==="flow"?(ye(Q),ge=Q):(Q.streaming=!1,g(Q)),b=null),M=typeof L.id=="string"?L.id:M,B=""}else if(L.type==="text_delta"){let j=typeof L.id=="string"?L.id:null,J=j?A.get(j):void 0;if(j&&J){let Me=typeof L.delta=="string"?L.delta:"",Te=(E.get(j)??"")+Me;if(E.set(j,Te),Te.trim()==="")continue;let Fe=ke(j,J);Fe.agentMetadata={...Fe.agentMetadata,executionId:L.executionId,parentToolId:J},N(Fe,Te,Me,void 0);continue}if(M=typeof L.id=="string"?L.id:M,dt==="flow"){let Me=typeof L.delta=="string"?L.delta:"";if(B+=Me,B.trim()==="")continue;let Te=w();Te.agentMetadata={executionId:L.executionId,iteration:Pe},N(Te,B,Me,void 0),C=Te;continue}let Q=typeof L.delta=="string"?L.delta:"";B+=Q;let de=w();de.agentMetadata={executionId:L.executionId,iteration:Pe,turnId:xt??void 0,agentName:Ge?.agentName},N(de,B,Q,void 0),C=de}else if(L.type==="text_complete"){let j=typeof L.id=="string"?L.id:null;if(j&&A.has(j)){let Q=O.get(j);Q&&ye(Q),A.delete(j),E.delete(j),O.delete(j);continue}let J=b;J&&(dt==="flow"?(ye(J),ge=J):((J.content??"")===""&&typeof L.text=="string"&&(J.content=L.text),J.streaming=!1,g(J)),b=null),M=null,B=""}else if(L.type==="step_complete"){if(L.stepType==="tool")continue;if(L.success===!1){let j=L.error||"Step failed";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,g(J)),n({type:"status",status:"idle"});continue}{let j=ge;ge=null;let J=L.stopReason,de=(L.result&&typeof L.result=="object"?L.result:null)?.response;if(j)J&&(j.stopReason=J),de!=null?we(j,de):j.streaming!==!1&&(se.delete(j.id),ce.delete(j.id),j.streaming=!1,g(j));else{let Me=de!=null&&de!=="";if(Me||J){let Te=w();J&&(Te.stopReason=J),Me?ye(Te,de):(Te.streaming=!1,g(Te))}}continue}}else if(L.type==="execution_start")dt=L.kind==="flow"?"flow":"agent",Xe=!0,dt==="agent"&&(Ge={executionId:L.executionId,agentId:L.agentId??"virtual",agentName:L.agentName??""});else if(L.type==="turn_start"){let j=typeof L.iteration=="number"?L.iteration:Pe;if(j!==Pe){if(yt==="separate"&&j>1){let J=b;J&&(J.streaming=!1,g(J),b=null)}Pe=j}xt=typeof L.id=="string"?L.id:null,C=null}else if(L.type==="tool_input_delta"){let j=L.toolCallId;if(j){let J=R.get(j);J?.toolCall&&(J.toolCall.chunks=J.toolCall.chunks??[],J.toolCall.chunks.push(L.delta??""),g(J))}}else if(L.type==="tool_input_complete"){if(I.has(L.toolCallId))continue;let j=Y(L.toolCallId),J=j.toolCall;J.args=L.parameters,J.name=L.toolName??J.name,g(j)}else if(L.type==="turn_complete"){let j=L.stopReason,J=b??C;if(j&&J!==null){let Q=L.id;(!Q||J.agentMetadata?.turnId===Q)&&(J.stopReason=j,g(J))}xt===L.id&&(xt=null)}else if(L.type==="media_start"){let j=String(L.id);Ne.set(j,{mediaType:typeof L.mediaType=="string"?L.mediaType:void 0,toolCallId:L.toolCallId,parts:[]})}else if(L.type==="media_delta"){let j=Ne.get(String(L.id));j&&typeof L.delta=="string"&&j.parts.push(L.delta)}else if(L.type==="media_complete"){let j=String(L.id),J=Ne.get(j);Ne.delete(j);let Q=(typeof L.mediaType=="string"?L.mediaType:void 0)??J?.mediaType??"application/octet-stream",de=typeof L.data=="string"?L.data:void 0,Me=typeof L.url=="string"?L.url:J&&J.parts.length>0?J.parts.join(""):void 0,Te=null;if(de)Te={type:"media",data:de,mediaType:Q};else if(Me){let ot=Q.toLowerCase();Te={type:ot==="image"||ot.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Q}}let Fe=L.toolCallId??J?.toolCallId,je=Te?[Te]:[],lt=[];for(let ot of je){if(!ot||typeof ot!="object")continue;let Je=ot,mt=typeof Je.type=="string"?Je.type:void 0,Tt=typeof Je.mediaType=="string"?Je.mediaType.toLowerCase():"",ee=null,Oe="";if(mt==="media"){let $e=typeof Je.data=="string"?Je.data:void 0;if(!$e)continue;Oe=Tt.length>0?Tt:"application/octet-stream",ee=`data:${Oe};base64,${$e}`}else if(mt==="image-url"){let $e=typeof Je.url=="string"?Je.url:void 0;if(!$e)continue;Oe=Tt,ee=$e}else if(mt==="file-url"){let $e=typeof Je.url=="string"?Je.url:void 0;if(!$e)continue;Oe=Tt,ee=$e}else continue;if(ee)if(mt==="image-url"||Oe.startsWith("image/"))lt.push({type:"image",image:ee,...Oe.includes("/")?{mimeType:Oe}:{}});else if(Oe.startsWith("audio/"))lt.push({type:"audio",audio:ee,mimeType:Oe});else if(Oe.startsWith("video/"))lt.push({type:"video",video:ee,mimeType:Oe});else{let $e=Oe||"application/octet-stream";lt.push({type:"file",data:ee,mimeType:$e,filename:$L($e)})}}if(lt.length>0){let ot=u(),Je=Fe,Tt={id:`agent-media-${typeof Je=="string"&&Je.length>0?`${Je}-${ot}`:String(ot)}`,role:"assistant",content:"",contentParts:lt,createdAt:new Date().toISOString(),streaming:!1,sequence:ot,agentMetadata:{executionId:L.executionId,iteration:Pe}};g(Tt);let ee=b;ee&&(ee.streaming=!1,g(ee)),b=null,S.current=null}}else if(L.type==="execution_complete"){let j=b;j&&(L.kind==="flow"&&j.streaming!==!1?ye(j):(j.streaming=!1,g(j)),b=null),M=null,B="",ge=null,n({type:"status",status:"idle",terminal:!0})}else if(L.type==="execution_error"){let j=typeof L.error=="string"?L.error:L.error?.message??"Execution error";n({type:"error",error:new Error(j)})}else if(L.type!=="ping"){if(L.type==="approval_start"){let j=L.approvalId??`approval-${u()}`,J={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:Ge?.agentId??"virtual",executionId:L.executionId??Ge?.executionId??"",toolName:L.toolName??"",toolType:L.toolType,description:L.description??`Execute ${L.toolName??"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};g(J)}else if(L.type==="approval_complete"){let j=L.approvalId;if(j){let Q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:L.decision??"approved",agentId:Ge?.agentId??"virtual",executionId:L.executionId??Ge?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};g(Q)}}else if(L.type==="artifact_start"||L.type==="artifact_delta"||L.type==="artifact_update"||L.type==="artifact_complete"){if(L.type==="artifact_start"){let j=L.artifactType,J=String(L.id),Q=typeof L.title=="string"?L.title:void 0,de=L.file,Me;if(de&&typeof de=="object"&&!Array.isArray(de)&&typeof de.path=="string"&&typeof de.mimeType=="string"&&(Me={path:de.path,mimeType:de.mimeType,...typeof de.language=="string"?{language:de.language}:{}}),n({type:"artifact_start",id:J,artifactType:j,title:Q,component:typeof L.component=="string"?L.component:void 0,...Me?{file:Me}:{}}),z.set(J,{markdown:"",title:Q,file:Me}),!G.has(J)){G.add(J);let Te=is(this.config.features?.artifacts,{artifactType:j,...Me?{file:Me}:{}}),Fe=typeof L.component=="string"?L.component:void 0,je={id:`artifact-ref-${J}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:El(Te,{artifactId:J,title:Q,artifactType:j,status:"streaming",...Me?{file:Me}:{},...Fe?{component:Fe}:{}})};D.set(J,je),g(je)}}else if(L.type==="artifact_delta"){let j=String(L.id),J=typeof L.delta=="string"?L.delta:String(L.delta??"");n({type:"artifact_delta",id:j,artDelta:J});let Q=z.get(j);Q&&(Q.markdown+=J)}else if(L.type==="artifact_update"){let j=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};n({type:"artifact_update",id:String(L.id),props:j,component:typeof L.component=="string"?L.component:void 0});let J=z.get(String(L.id));J&&(J.props={...J.props??{},...j})}else if(L.type==="artifact_complete"){let j=String(L.id);n({type:"artifact_complete",id:j});let J=D.get(j);if(J){J.streaming=!1;try{let Q=JSON.parse(J.rawContent??"{}");if(Q.props){Q.props.status="complete";let de=z.get(j);de?.markdown&&(Q.props.markdown=de.markdown),de?.file&&(Q.props.file=de.file),Q.component==="PersonaArtifactInline"&&de?.props&&Object.keys(de.props).length>0&&(Q.props.componentProps=de.props)}J.rawContent=JSON.stringify(Q)}catch{}z.delete(j),g(J),D.delete(j)}}}else if(L.type==="error"&&L.recoverable===!1&&L.error!=null&&L.error!==""){let j=typeof L.error=="string"?L.error:L.error?.message!=null?String(L.error.message):"Execution error";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,g(J)),n({type:"status",status:"idle"})}}}nt.length=0};;){let{done:X,value:L}=await s.read();if(X)break;l+=a.decode(L,{stream:!0});let j=l.split(`
1142
+ `):t};var MC="var(--persona-md-table-scroll-fade, 24px)",TC=new WeakSet;function kC(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function EC(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":MC),t.style.setProperty("--persona-fade-r",r<=1?"0px":MC)}function Vf(t){TC.has(t)||(TC.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&EC(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(EC)}ti();na();oo();var{setLoader:E1,load:Q0}=$t({fallbackImport:()=>Promise.resolve().then(()=>(DC(),OC))});var _C=Q0;function To(t){return t==="card"?"collapsed":t}function oa(t){return t.split(";",1)[0].trim().toLowerCase()}function X0(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(oa(r)===e)return{mode:To(s),selector:oa(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(oa(r)===o)return{mode:To(s),selector:o}}function J0(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:To(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?oa(e.file.mimeType):void 0,d=l?X0(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:To(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:To(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:To(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:To(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:To(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function is(t,e){return J0(t,e).mode}function El(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Z0="agent_",eL="flow_";function NC(t){return t.startsWith(Z0)?{kind:"agentId",agentId:t}:t.startsWith(eL)?{kind:"flowId",flowId:t}:null}function FC(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=NC(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=NC(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function op(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ra(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function VC(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var as=require("partial-json");Ye();var zf="ask_user_question",kl=8,sa="data-persona-ask-sheet-for",tL="Other",nL="Other\u2026",UC="Type your own answer here",qC="Send",oL="Next",rL="Back",sL="Submit all",iL="Skip",aL=3,Uf="data-ask-current-index",qf="data-ask-question-count",jC="data-ask-answers",jf="data-ask-grouped",KC="data-ask-layout",lL=t=>t.layout==="pills"?"pills":"rows",cL=t=>t.getAttribute(KC)==="pills"?"pills":"rows",zC=!1,GC=t=>t.replace(/["\\]/g,"\\$&"),ni=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===zf,Kf=t=>t?.features?.askUserQuestion??{},ia=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,as.parse)(r,as.STR|as.OBJ|as.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ll=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>kl&&!zC&&(zC=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${kl}.`)),e.slice(0,kl)},dL=t=>Ll(t)[0]??null,pL=(t,e)=>Ll(t)[e]??null,uL=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},YC=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},mL=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let p=v("span","persona-ask-row-description");p.textContent=t.description,a.appendChild(p)}s.appendChild(a);let d=YC(n,o,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},fL=t=>{let n=v("span",t==="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 n.setAttribute("aria-hidden","true"),n},gL=(t,e,n,o)=>{let s=v("div",o==="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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<aL;u++)s.appendChild(fL(o));return s}if(d.forEach((u,m)=>{s.appendChild(mL(u,m,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?tL:nL;if(o==="rows"){let m=v("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(d.length)),m.setAttribute("data-ask-other-row","true");let h=v("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=e.freeTextPlaceholder??UC,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??u),h.appendChild(g),m.appendChild(h);let b=YC(o,a,d.length);b&&m.appendChild(b),s.appendChild(m)}else{let m=v("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=e.freeTextLabel??u,s.appendChild(m)}}return s},QC=(t,e)=>{let o=v("div",e==="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");o.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=t.freeTextPlaceholder??UC,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??qC,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},hL=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??qC,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},yL=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??rL,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??iL,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=t===e-1;return l.textContent=d?n.submitAllLabel??sL:n.nextLabel??oL,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},oi=t=>{let e=t.getAttribute(jC);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},XC=(t,e)=>{t.setAttribute(jC,JSON.stringify(e))},Eo=t=>{let e=Number(t.getAttribute(Uf)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},bL=(t,e)=>{t.setAttribute(Uf,String(Math.max(0,Math.floor(e))))},aa=t=>{let e=Number(t.getAttribute(qf)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ls=t=>t.getAttribute(jf)==="true",vL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},CL=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},rp=(t,e)=>{let{payload:n}=ia(e),o=Ll(n),r=oi(t),s={},a=new Set;return o.forEach((l,d)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},JC=t=>{let e=oi(t),n=Eo(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",u=r.has(p);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ZC=t=>{if(!ls(t))return;let e=oi(t),n=Eo(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Gf=(t,e,n)=>{let o=Kf(n),r=cL(t),{payload:s,complete:a}=ia(e),l=ls(t),d=Eo(t),p=aa(t),u=l?pL(s,d):dL(s),m=!!u?.multiSelect,h=t.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=l?`${d+1}/${p}`:"");let g=t.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let M=typeof u?.question=="string"?u.question:"";b.textContent=M,b.classList.toggle("persona-ask-question-skeleton",!M&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let M=gL(u,o,a,r);C.replaceWith(M)}if(r!=="rows"){let M=t.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(QC(o,r))}let S=t.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!S?t.appendChild(hL(o)):(!m||l)&&S&&S.remove(),t.setAttribute("data-multi-select",m?"true":"false");let P=t.querySelector('[data-ask-nav-row="true"]');if(l){let M=yL(d,p,o);P?P.replaceWith(M):t.appendChild(M)}else P&&P.remove();JC(t),ZC(t)},wL=(t,e,n)=>{let o=Kf(e),r=lL(o),s=t.toolCall.id,a=Ll(n),l=Math.max(1,a.length),d=l>1,p=vL(t,a),u=d?CL(t,l):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(sa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(qf,String(l)),m.setAttribute(Uf,String(u)),m.setAttribute(jf,d?"true":"false"),m.setAttribute(KC,r),XC(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),uL(m,o);let h=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=v("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",h.appendChild(g);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",h.appendChild(b),m.appendChild(h);let S=v("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 S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),r!=="rows"&&m.appendChild(QC(o,r)),Gf(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},xL=(t,e,n)=>{let{payload:o}=ia(e),r=Math.max(1,Ll(o).length);r>aa(t)&&(t.setAttribute(qf,String(r)),r>1&&!ls(t)&&t.setAttribute(jf,"true")),Gf(t,e,n)};var sp=(t,e,n)=>{if(!n||!ni(t)||Kf(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${sa}]`).forEach(p=>{p.getAttribute(sa)!==r&&p.remove()});let a=n.querySelector(`[${sa}="${GC(r)}"]`);if(a){xL(a,t,e);return}let{payload:l}=ia(t),d=wL(t,e,l);n.appendChild(d)},la=(t,e)=>{if(!t)return;let n=e?`[${sa}="${GC(e)}"]`:`[${sa}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Yf=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),cs=(t,e)=>{let n=oi(t),o=Eo(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,XC(t,n),JC(t),ZC(t)},ip=(t,e,n,o)=>{let r=aa(t),s=Math.max(0,Math.min(r-1,o));bL(t,s),Gf(t,e,n)};var ds="suggest_replies";var SL={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},tw={name:ds,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:SL,origin:"sdk",annotations:{readOnlyHint:!0}},nw=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Pl=t=>t.variant==="tool"&&t.toolCall?.name===ds,AL=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},ow=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Pl(n))continue;let o=AL(n.toolCall?.args);return o.length>0?o:null}return null},ew=new Set,ML=(t,e,n)=>{let o=`${t}:${e}:${n}`;ew.has(o)||(ew.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},ps=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],d=n?.[a];l===void 0||d===void 0||l!==d&&ML(a,d,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var TL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:kl,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},EL={name:zf,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:TL,origin:"sdk",annotations:{readOnlyHint:!0}},ap=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(EL),ps(t).expose&&e.push(tw),e};ri();var uw="4.23.0";var si=uw;var da="[Image]";function mw(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function pp(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function sr(t){return{type:"text",text:t}}function fw(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var gw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],WL=["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=[...gw,...WL];function BL(t){return gw.includes(t)||t.startsWith("image/")}function up(t){return BL(t.type)}function hw(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function yw(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;up(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function bw(t,e=Hr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function OL(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function vw(t,e){let n=OL(e).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"}[t]||n||"FILE"}var DL=["user","assistant","system"],_L=0;function Cw(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function mp(t){return typeof t=="string"?t:void 0}function NL(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?sr(e.text):null;case"image":return typeof e.image=="string"?fw(e.image,{mimeType:mp(e.mimeType),alt:mp(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?hw(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...mp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...mp(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function FL(t,e){let n=Cw(e),o=t.map(a=>Cw(a.timestamp)),r=new Array(t.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let h=0;h<d;h+=1)r[s+h]=m!==null?m-(d-h):p!==null?p+h+1:_L+h;s=l+1}return r.map(a=>new Date(a).toISOString())}function ww(t,e){let n=FL(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!DL.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(NL).filter(u=>u!==null),p=mw(d);o.push({id:r.id,role:a,content:p||(pp(d)?da:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Wl(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Bl(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var VL="https://api.runtype.com/v1/dispatch",xw="https://api.runtype.com",at=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Sw=32768,Xf=49152,Aw=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},Mw=t=>"reason"in t?t.reason:void 0,Tw="The identity proof was not admitted; account history is unavailable",Ew="The identity proof was rejected",kw="The request carried no visitor credential",Lw="The stored visitor belongs to a different signed-in user",Jf=(t,e)=>t instanceof at&&t.code===e;function $L(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Zf=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function zL(t){switch(t){case"json":return dw;case"regex-json":return cw;case"xml":return pw;default:return lw}}var Pw=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function UL(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Pw(n);if(!Pw(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Rl(t);return Rl(e)!==null&&a===null?e:t}var Ol=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;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(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??VL,this.headers={"Content-Type":"application/json","X-Persona-Version":si,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??zL(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return _C().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:IC,getToolDisplayTitle:Zd,loadPolyfill:RC});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),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(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=FC(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||xw}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new at("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:e.after}),d=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":si,"X-Visitor-Token":s},signal:e.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}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 e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.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 e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}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 e=this.historyIdentityStatus;return e?.state==="browser_only"?e: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(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&Mw(n)===Mw(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||e.durableResume?e.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...l?{conversationId:l}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(d)});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new at("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new at("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&m.error==="visitor_required"?new at("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new at("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let r=await this.createClientSession({conversationId:e,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,e,!1)}catch(r){if(!Jf(r,"not_found")&&!Jf(r,"visitor_required")&&!Jf(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new at("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new at("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}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(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new at("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new at("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new at("proof_not_admitted",Tw);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new at("invalid_identity_proof",Ew);if(r.includes("visitor token required"))throw new at("visitor_token_missing",kw);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new at("visitor_identity_mismatch",Lw);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new at("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new at("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new at("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new at("proof_not_admitted",Tw);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new at("invalid_identity_proof",Ew)):r.includes("visitor token required")?new at("visitor_token_missing",kw):r.includes("visitor_identity_mismatch")?new at("visitor_identity_mismatch",Lw):new at("unauthorized",o||"History request was not authorized")}return new at("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new at("identity_contract_violation","Server reported an ignored identity proof on a success response"):new at("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new at("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new at("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":si,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),h=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new at("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new at("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Aw),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Aw(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>Sw)throw new at("payload_too_large",`displayContent exceeds the ${Sw} character limit`);o+=p}if(o>Xf)throw new at("payload_too_large",`Display projection batch exceeds the ${Xf} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Xf,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.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(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=VC();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=await this.initSession();if(new Date>=new Date(a.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let b=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:b}),b}let l=await this.buildPayload(e.messages),d=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null,p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([b])=>b!=="sessionId"&&b!=="session_id")):void 0,u=this.isHistoryCapable(),m={sessionId:a.sessionId,messages:e.messages.filter(Zf).map(b=>{let C=u?Wl(b):void 0;return{id:b.id,role:b.role,content:b.contentParts??b.llmContent??b.rawContent??b.content,...C!==void 0&&{displayContent:C}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},{response:h,commit:g}=await this.sendWithClientToolsDiff(a.sessionId,l.clientTools,b=>{let C={...m,...b};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":si,...d?{"X-Visitor-Token":d}:{}},body:JSON.stringify(C),signal:e.signal})});if(!h.ok){let b=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let S=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:S}),S}if(h.status===429){let S=new Error(b.hint||"Message limit reached for this session.");throw s({type:"error",error:S}),S}if(h.status===410&&b.error==="conversation_deleted"){let S=new at("conversation_deleted","This conversation was deleted");throw s({type:"error",error:S}),S}let C=new Error(b.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!h.body){let b=new Error("No response body received");throw s({type:"error",error:b}),b}g(),s({type:"status",status:"connected"});try{await this.streamResponse(h.body,s,e.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof at)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?HC(n):void 0,l=this.clientToolsFingerprintSessionId===e,d=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let h=0;;h++){if(m=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&h===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||xw}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let d={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(a,u,g=>{let b={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",b),fetch(s,{method:"POST",headers:d,body:JSON.stringify(b),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(s=>s.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Zf).filter(p=>p.role==="user"||p.role==="assistant"||p.role==="system").filter(p=>!p.variant||p.variant==="assistant").sort((p,u)=>{let m=new Date(p.createdAt).getTime(),h=new Date(u.createdAt).getTime();return m-h}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(e);return d&&(a.context=d),a}async buildPayload(e,n){let o=e.slice().filter(Zf).sort((p,u)=>{let m=new Date(p.createdAt).getTime(),h=new Date(u.createdAt).getTime();return m-h}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...ap(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(e);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=X=>{let L=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,j=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,J=X.tools?X.tools.map(Q=>({...Q,chunks:Q.chunks?[...Q.chunks]:void 0})):void 0;return{...X,reasoning:L,toolCall:j,tools:J}},h=X=>{if(X.role!=="assistant"||X.variant)return!0;let L=Array.isArray(X.contentParts)&&X.contentParts.length>0,j=typeof X.rawContent=="string"&&X.rawContent.trim()!=="";return typeof X.content=="string"&&X.content.trim()!==""||L||j||!!X.stopReason},g=X=>{h(X)&&n({type:"message",message:m(X)})},b=null,C=null,S={current:null},P={current:null},M=null,B="",A=new Map,O=new Map,E=new Map,W=new Map,R=new Map,V=o,H=!1,w=()=>{if(b)return b;let X,L="",j=M;return!H&&V?(X=V,H=!0,L=r??""):V&&j?X=`${V}_${j}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:X,role:"assistant",content:L,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(b),b},T=X=>{let L=W.get(X);if(L)return L;let j={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:X,status:"streaming",chunks:[]}};return W.set(X,j),g(j),j},I=new Set,D=new Map,G=new Set,z=new Map,K=X=>{if(!X)return!1;let L=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return L==="emit_artifact_markdown"||L==="emit_artifact_component"},Y=X=>{let L=R.get(X);if(L)return L;let j={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:X,status:"pending"}};return R.set(X,j),g(j),j},re=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let L=Number(X);if(!Number.isNaN(L)&&Number.isFinite(L))return L;let j=Date.parse(X);if(!Number.isNaN(j))return j}return Date.now()},oe=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},se=new Map,ce=new Map,we=(X,L)=>{let j=oe(L),J=ce.get(X.id),Q=UL(J,j);X.rawContent=Q;let de=se.get(X.id),Me=ot=>{let Je=X.content??"";ot.trim()!==""&&(Je.trim().length===0||ot.startsWith(Je)||ot.trimStart().startsWith(Je.trim()))&&(X.content=ot)},Te=()=>{if(de){let ot=de.close?.();ot instanceof Promise&&ot.catch(()=>{})}se.delete(X.id),ce.delete(X.id),X.streaming=!1,g(X)};if(!de){Me(j),Te();return}let Fe=Rl(Q);if(Fe!==null&&Fe.trim()!==""){Me(Fe),Te();return}let je=ot=>{let Je=typeof ot=="string"?ot:ot?.text??null;if(Je!==null&&Je.trim()!=="")return Je;let mt=de.getExtractedText();return mt!==null&&mt.trim()!==""?mt:j},lt;try{lt=de.processChunk(Q)}catch{Me(j),Te();return}if(lt instanceof Promise){lt.then(ot=>{Me(je(ot)),Te()}).catch(()=>{Me(j),Te()});return}Me(je(lt)),Te()},ge=null,N=(X,L,j,J)=>{X.rawContent=L,se.has(X.id)||se.set(X.id,this.createStreamParser());let Q=se.get(X.id),de=L.trim().startsWith("{")||L.trim().startsWith("[");if(de&&ce.set(X.id,L),Q.__isPlainTextParser===!0){X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X);return}let Te=Q.processChunk(L);if(Te instanceof Promise)Te.then(Fe=>{let je=typeof Fe=="string"?Fe:Fe?.text??null;je!==null&&je.trim()!==""?(X.content=je,g(X)):!de&&!L.trim().startsWith("<")&&(X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X))}).catch(()=>{X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X)});else{let Fe=typeof Te=="string"?Te:Te?.text??null;Fe!==null&&Fe.trim()!==""?(X.content=Fe,g(X)):!de&&!L.trim().startsWith("<")&&(X.content=J!==void 0?L:X.content+j,ce.delete(X.id),se.delete(X.id),X.rawContent=void 0,g(X))}},ye=(X,L)=>{let j=L??X.content;if(j==null||j===""){X.streaming=!1,g(X);return}let Q=ce.get(X.id)??oe(j);X.rawContent=Q;let de=se.get(X.id),Me=null,Te=!1;if(de&&(Me=de.getExtractedText(),Me===null&&(Me=Rl(Q)),Me===null)){let Fe=de.processChunk(Q);Fe instanceof Promise?(Te=!0,Fe.then(je=>{let lt=typeof je=="string"?je:je?.text??null;lt!==null&&(X.content=lt,X.streaming=!1,se.delete(X.id),ce.delete(X.id),g(X))}).catch(()=>{})):Me=typeof Fe=="string"?Fe:Fe?.text??null}if(!Te){Me!==null&&Me.trim()!==""?X.content=Me:ce.has(X.id)||(X.content=oe(j));let Fe=se.get(X.id);if(Fe){let je=Fe.close?.();je instanceof Promise&&je.catch(()=>{}),se.delete(X.id)}ce.delete(X.id),X.streaming=!1,g(X)}},ke=(X,L,j)=>{let J=O.get(X);if(J)return J;let Q={id:`nested-${L}-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...j?{variant:j}:{},...j==="reasoning"?{reasoning:{id:X,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:L}};return O.set(X,Q),g(Q),Q},nt=[],Ee,Ne=new Map,Pe=0,dt="agent",Xe=!1,xt=null,Ge=null,yt=this.config.iterationDisplay??"separate";for(Ee=()=>{for(let X=0;X<nt.length;X++){let L=nt[X];if(!Xe&&dt!=="flow"&&typeof L.stepType=="string"&&(dt="flow"),L.type==="reasoning_start"){let j=typeof L.id=="string"?L.id:null,J=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if(j&&J){A.set(j,J),ke(j,J,"reasoning");continue}let Q=L.id,de=T(Q);de.reasoning=de.reasoning??{id:Q,status:"streaming",chunks:[]},de.reasoning.startedAt=de.reasoning.startedAt??Date.now(),de.reasoning.completedAt=void 0,de.reasoning.durationMs=void 0,(L.scope==="loop"||L.scope==="turn")&&(de.reasoning.scope=L.scope),de.streaming=!0,de.reasoning.status="streaming",g(de)}else if(L.type==="reasoning_delta"){let j=typeof L.id=="string"?L.id:null;if(j&&A.has(j)&&O.has(j)){let de=O.get(j),Me=L.delta;Me&&de.reasoning&&(de.reasoning.chunks.push(String(Me)),g(de));continue}let J=L.id,Q=T(J);Q.reasoning=Q.reasoning??{id:J,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Date.now(),L.delta&&Q.reasoning.chunks.push(L.delta),Q.reasoning.status="streaming",Q.streaming=!0,g(Q)}else if(L.type==="reasoning_complete"){let j=typeof L.id=="string"?L.id:null;if(j&&A.has(j)&&O.has(j)){let Me=O.get(j);if(Me.reasoning){let Te=typeof L.text=="string"?L.text:"";Te&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Te),Me.reasoning.status="complete",Me.streaming=!1,g(Me)}A.delete(j),O.delete(j);continue}let J=L.id,Q=typeof L.text=="string"?L.text:"";!W.get(J)&&(Q||L.scope==="loop")&&T(J);let de=W.get(J);if(de?.reasoning){(L.scope==="loop"||L.scope==="turn")&&(de.reasoning.scope=L.scope),Q&&de.reasoning.chunks.length===0&&de.reasoning.chunks.push(Q),de.reasoning.status="complete",de.reasoning.completedAt=Date.now();let Me=de.reasoning.startedAt??Date.now();de.reasoning.durationMs=Math.max(0,(de.reasoning.completedAt??Date.now())-Me),de.streaming=!1,g(de)}}else if(L.type==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof L.iteration=="number"&&(Pe=L.iteration);let j=L.toolCallId,J=L.toolName;if(K(J)){I.add(j);continue}let Q=Y(j),de=Q.toolCall??{id:j,status:"pending"};de.name=J??de.name,de.status="running",de.success=void 0,de.error=void 0,de.duration=void 0,L.parameters!==void 0&&(de.args=L.parameters),de.startedAt=de.startedAt??re(L.startedAt),de.completedAt=void 0,de.durationMs=void 0,Q.toolCall=de,Q.streaming=!0,L.executionId&&(Q.agentMetadata={executionId:L.executionId,iteration:L.iteration}),g(Q)}else if(L.type==="tool_output_delta"){let j=L.toolCallId;if(I.has(j))continue;let J=Y(j),Q=J.toolCall??{id:j,status:"running"};Q.startedAt=Q.startedAt??Date.now();let de=L.delta;de&&(Q.chunks=Q.chunks??[],Q.chunks.push(String(de))),Q.status="running",J.toolCall=Q,J.streaming=!0,L.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:L.executionId,iteration:Pe}),g(J)}else if(L.type==="tool_complete"){let j=L.toolCallId;if(I.has(j)){I.delete(j);continue}let J=Y(j),Q=J.toolCall??{id:j,status:"running"};Q.status="complete",L.result!==void 0&&(Q.result=L.result),Q.name=L.toolName??Q.name,Q.success=L.success,Q.error=L.error,Q.completedAt=Date.now();let de=L.executionTime;if(typeof de=="number")Q.durationMs=de,Q.duration=de;else{let Me=Q.startedAt??Date.now();Q.durationMs=Math.max(0,(Q.completedAt??Date.now())-Me)}J.toolCall=Q,J.streaming=!1,L.executionId&&(J.agentMetadata=J.agentMetadata??{executionId:L.executionId,iteration:L.iteration??Pe}),g(J)}else if(L.type==="await"&&L.toolName){let j=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,J=j??L.toolId??`local-${u()}`,Q=Y(J),de=L.toolName,Me=L.origin==="webmcp"&&!ta(de)?`webmcp:${de}`:de,Te=ta(Me),Fe=Q.toolCall??{id:J,status:"pending"};Fe.name=Me,Fe.args=L.parameters,Fe.status=Te?"running":"complete",Fe.chunks=Fe.chunks??[],Fe.startedAt=Fe.startedAt??re(L.awaitedAt),Te?(Fe.completedAt=void 0,Fe.duration=void 0,Fe.durationMs=void 0):Fe.completedAt=Fe.completedAt??Fe.startedAt,Q.toolCall=Fe,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:L.executionId??Q.agentMetadata?.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Q)}else if(L.type==="text_start"){let j=typeof L.id=="string"?L.id:null,J=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if(j&&J){A.set(j,J);continue}let Q=b;Q&&(dt==="flow"?(ye(Q),ge=Q):(Q.streaming=!1,g(Q)),b=null),M=typeof L.id=="string"?L.id:M,B=""}else if(L.type==="text_delta"){let j=typeof L.id=="string"?L.id:null,J=j?A.get(j):void 0;if(j&&J){let Me=typeof L.delta=="string"?L.delta:"",Te=(E.get(j)??"")+Me;if(E.set(j,Te),Te.trim()==="")continue;let Fe=ke(j,J);Fe.agentMetadata={...Fe.agentMetadata,executionId:L.executionId,parentToolId:J},N(Fe,Te,Me,void 0);continue}if(M=typeof L.id=="string"?L.id:M,dt==="flow"){let Me=typeof L.delta=="string"?L.delta:"";if(B+=Me,B.trim()==="")continue;let Te=w();Te.agentMetadata={executionId:L.executionId,iteration:Pe},N(Te,B,Me,void 0),C=Te;continue}let Q=typeof L.delta=="string"?L.delta:"";B+=Q;let de=w();de.agentMetadata={executionId:L.executionId,iteration:Pe,turnId:xt??void 0,agentName:Ge?.agentName},N(de,B,Q,void 0),C=de}else if(L.type==="text_complete"){let j=typeof L.id=="string"?L.id:null;if(j&&A.has(j)){let Q=O.get(j);Q&&ye(Q),A.delete(j),E.delete(j),O.delete(j);continue}let J=b;J&&(dt==="flow"?(ye(J),ge=J):((J.content??"")===""&&typeof L.text=="string"&&(J.content=L.text),J.streaming=!1,g(J)),b=null),M=null,B=""}else if(L.type==="step_complete"){if(L.stepType==="tool")continue;if(L.success===!1){let j=L.error||"Step failed";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,g(J)),n({type:"status",status:"idle"});continue}{let j=ge;ge=null;let J=L.stopReason,de=(L.result&&typeof L.result=="object"?L.result:null)?.response;if(j)J&&(j.stopReason=J),de!=null?we(j,de):j.streaming!==!1&&(se.delete(j.id),ce.delete(j.id),j.streaming=!1,g(j));else{let Me=de!=null&&de!=="";if(Me||J){let Te=w();J&&(Te.stopReason=J),Me?ye(Te,de):(Te.streaming=!1,g(Te))}}continue}}else if(L.type==="execution_start")dt=L.kind==="flow"?"flow":"agent",Xe=!0,dt==="agent"&&(Ge={executionId:L.executionId,agentId:L.agentId??"virtual",agentName:L.agentName??""});else if(L.type==="turn_start"){let j=typeof L.iteration=="number"?L.iteration:Pe;if(j!==Pe){if(yt==="separate"&&j>1){let J=b;J&&(J.streaming=!1,g(J),b=null)}Pe=j}xt=typeof L.id=="string"?L.id:null,C=null}else if(L.type==="tool_input_delta"){let j=L.toolCallId;if(j){let J=R.get(j);J?.toolCall&&(J.toolCall.chunks=J.toolCall.chunks??[],J.toolCall.chunks.push(L.delta??""),g(J))}}else if(L.type==="tool_input_complete"){if(I.has(L.toolCallId))continue;let j=Y(L.toolCallId),J=j.toolCall;J.args=L.parameters,J.name=L.toolName??J.name,g(j)}else if(L.type==="turn_complete"){let j=L.stopReason,J=b??C;if(j&&J!==null){let Q=L.id;(!Q||J.agentMetadata?.turnId===Q)&&(J.stopReason=j,g(J))}xt===L.id&&(xt=null)}else if(L.type==="media_start"){let j=String(L.id);Ne.set(j,{mediaType:typeof L.mediaType=="string"?L.mediaType:void 0,toolCallId:L.toolCallId,parts:[]})}else if(L.type==="media_delta"){let j=Ne.get(String(L.id));j&&typeof L.delta=="string"&&j.parts.push(L.delta)}else if(L.type==="media_complete"){let j=String(L.id),J=Ne.get(j);Ne.delete(j);let Q=(typeof L.mediaType=="string"?L.mediaType:void 0)??J?.mediaType??"application/octet-stream",de=typeof L.data=="string"?L.data:void 0,Me=typeof L.url=="string"?L.url:J&&J.parts.length>0?J.parts.join(""):void 0,Te=null;if(de)Te={type:"media",data:de,mediaType:Q};else if(Me){let ot=Q.toLowerCase();Te={type:ot==="image"||ot.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:Q}}let Fe=L.toolCallId??J?.toolCallId,je=Te?[Te]:[],lt=[];for(let ot of je){if(!ot||typeof ot!="object")continue;let Je=ot,mt=typeof Je.type=="string"?Je.type:void 0,Tt=typeof Je.mediaType=="string"?Je.mediaType.toLowerCase():"",ee=null,Oe="";if(mt==="media"){let $e=typeof Je.data=="string"?Je.data:void 0;if(!$e)continue;Oe=Tt.length>0?Tt:"application/octet-stream",ee=`data:${Oe};base64,${$e}`}else if(mt==="image-url"){let $e=typeof Je.url=="string"?Je.url:void 0;if(!$e)continue;Oe=Tt,ee=$e}else if(mt==="file-url"){let $e=typeof Je.url=="string"?Je.url:void 0;if(!$e)continue;Oe=Tt,ee=$e}else continue;if(ee)if(mt==="image-url"||Oe.startsWith("image/"))lt.push({type:"image",image:ee,...Oe.includes("/")?{mimeType:Oe}:{}});else if(Oe.startsWith("audio/"))lt.push({type:"audio",audio:ee,mimeType:Oe});else if(Oe.startsWith("video/"))lt.push({type:"video",video:ee,mimeType:Oe});else{let $e=Oe||"application/octet-stream";lt.push({type:"file",data:ee,mimeType:$e,filename:$L($e)})}}if(lt.length>0){let ot=u(),Je=Fe,Tt={id:`agent-media-${typeof Je=="string"&&Je.length>0?`${Je}-${ot}`:String(ot)}`,role:"assistant",content:"",contentParts:lt,createdAt:new Date().toISOString(),streaming:!1,sequence:ot,agentMetadata:{executionId:L.executionId,iteration:Pe}};g(Tt);let ee=b;ee&&(ee.streaming=!1,g(ee)),b=null,S.current=null}}else if(L.type==="execution_complete"){let j=b;j&&(L.kind==="flow"&&j.streaming!==!1?ye(j):(j.streaming=!1,g(j)),b=null),M=null,B="",ge=null,n({type:"status",status:"idle",terminal:!0})}else if(L.type==="execution_error"){let j=typeof L.error=="string"?L.error:L.error?.message??"Execution error";n({type:"error",error:new Error(j)})}else if(L.type!=="ping"){if(L.type==="approval_start"){let j=L.approvalId??`approval-${u()}`,J={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:Ge?.agentId??"virtual",executionId:L.executionId??Ge?.executionId??"",toolName:L.toolName??"",toolType:L.toolType,description:L.description??`Execute ${L.toolName??"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};g(J)}else if(L.type==="approval_complete"){let j=L.approvalId;if(j){let Q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:L.decision??"approved",agentId:Ge?.agentId??"virtual",executionId:L.executionId??Ge?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};g(Q)}}else if(L.type==="artifact_start"||L.type==="artifact_delta"||L.type==="artifact_update"||L.type==="artifact_complete"){if(L.type==="artifact_start"){let j=L.artifactType,J=String(L.id),Q=typeof L.title=="string"?L.title:void 0,de=L.file,Me;if(de&&typeof de=="object"&&!Array.isArray(de)&&typeof de.path=="string"&&typeof de.mimeType=="string"&&(Me={path:de.path,mimeType:de.mimeType,...typeof de.language=="string"?{language:de.language}:{}}),n({type:"artifact_start",id:J,artifactType:j,title:Q,component:typeof L.component=="string"?L.component:void 0,...Me?{file:Me}:{}}),z.set(J,{markdown:"",title:Q,file:Me}),!G.has(J)){G.add(J);let Te=is(this.config.features?.artifacts,{artifactType:j,...Me?{file:Me}:{}}),Fe=typeof L.component=="string"?L.component:void 0,je={id:`artifact-ref-${J}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:El(Te,{artifactId:J,title:Q,artifactType:j,status:"streaming",...Me?{file:Me}:{},...Fe?{component:Fe}:{}})};D.set(J,je),g(je)}}else if(L.type==="artifact_delta"){let j=String(L.id),J=typeof L.delta=="string"?L.delta:String(L.delta??"");n({type:"artifact_delta",id:j,artDelta:J});let Q=z.get(j);Q&&(Q.markdown+=J)}else if(L.type==="artifact_update"){let j=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};n({type:"artifact_update",id:String(L.id),props:j,component:typeof L.component=="string"?L.component:void 0});let J=z.get(String(L.id));J&&(J.props={...J.props??{},...j})}else if(L.type==="artifact_complete"){let j=String(L.id);n({type:"artifact_complete",id:j});let J=D.get(j);if(J){J.streaming=!1;try{let Q=JSON.parse(J.rawContent??"{}");if(Q.props){Q.props.status="complete";let de=z.get(j);de?.markdown&&(Q.props.markdown=de.markdown),de?.file&&(Q.props.file=de.file),Q.component==="PersonaArtifactInline"&&de?.props&&Object.keys(de.props).length>0&&(Q.props.componentProps=de.props)}J.rawContent=JSON.stringify(Q)}catch{}z.delete(j),g(J),D.delete(j)}}}else if(L.type==="error"&&L.recoverable===!1&&L.error!=null&&L.error!==""){let j=typeof L.error=="string"?L.error:L.error?.message!=null?String(L.error.message):"Execution error";n({type:"error",error:new Error(j)});let J=b;J&&J.streaming&&(J.streaming=!1,g(J)),n({type:"status",status:"idle"})}}}nt.length=0};;){let{done:X,value:L}=await s.read();if(X)break;l+=a.decode(L,{stream:!0});let j=l.split(`
1143
1143
 
1144
1144
  `);l=j.pop()??"";for(let J of j){let Q=J.split(`
1145
- `),de="message",Me="",Te=null;for(let Je of Q)Je.startsWith("event:")?de=Je.replace("event:","").trim():Je.startsWith("data:")?Me+=Je.replace("data:","").trim():Je.startsWith("id:")&&(Te=Je.slice(3).trim());let Fe=()=>{Te!==null&&Te!==""&&n({type:"cursor",id:Te})};if(!Me){Fe();continue}let je;try{je=JSON.parse(Me)}catch(Je){n({type:"error",error:Je instanceof Error?Je:new Error("Failed to parse chat stream payload")});continue}let lt=je!==null&&typeof je=="object"&&!Array.isArray(je)?je:null,ot=de!=="message"?de:typeof lt?.type=="string"?lt.type:"message";if(this.onSSEEvent?.(ot,je),this.parseSSEEvent){S.current=b;let Je=await this.handleCustomSSEEvent(je,n,S,g,u,P);if(S.current&&S.current!==b&&(b=S.current),Je){Fe();continue}}lt&&(nt.push({...lt,type:ot}),Ee()),Fe()}}Ee()}};na();eg();var KL=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function GL(t){let e=t?.text?.trim()??"";return e?Dl(KL(t),e):""}function Hw(t){let e=GL(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[rr(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
1145
+ `),de="message",Me="",Te=null;for(let Je of Q)Je.startsWith("event:")?de=Je.replace("event:","").trim():Je.startsWith("data:")?Me+=Je.replace("data:","").trim():Je.startsWith("id:")&&(Te=Je.slice(3).trim());let Fe=()=>{Te!==null&&Te!==""&&n({type:"cursor",id:Te})};if(!Me){Fe();continue}let je;try{je=JSON.parse(Me)}catch(Je){n({type:"error",error:Je instanceof Error?Je:new Error("Failed to parse chat stream payload")});continue}let lt=je!==null&&typeof je=="object"&&!Array.isArray(je)?je:null,ot=de!=="message"?de:typeof lt?.type=="string"?lt.type:"message";if(this.onSSEEvent?.(ot,je),this.parseSSEEvent){S.current=b;let Je=await this.handleCustomSSEEvent(je,n,S,g,u,P);if(S.current&&S.current!==b&&(b=S.current),Je){Fe();continue}}lt&&(nt.push({...lt,type:ot}),Ee()),Fe()}}Ee()}};na();eg();var KL=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function GL(t){let e=t?.text?.trim()??"";return e?Dl(KL(t),e):""}function Hw(t){let e=GL(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[sr(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
1146
1146
 
1147
1147
  `)}:{}}function fp(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function Rw(t,e){let n=t.findIndex(r=>r.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function tg(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function Ww(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return tg(t,n.id)?n.id:null}return null}function ng(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}_l();function og(t){let e=["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 n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Nl=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):og(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var hp=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===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(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var Fl=class{constructor(){this.cancelled=!1}start(e){this.turnId=e,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(e){return!this.cancelled&&(!e||!this.turnId||e===this.turnId)}};oo();var{setLoader:xO,load:tP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Nw(),_w))});var lg=tP;function cg(t){if(!t)return"";let e=nP(t);return Fw(e!==null?e:t)}function nP(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Fw(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
1148
1148
  `),e=e.replace(/\n{2,}/g,`
1149
- `),e.trim()}var qw=null;var dg=()=>qw?qw():Promise.resolve().then(()=>(Uw(),zw));oo();var{setLoader:HO,load:aP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Kw(),jw))});var Gw=aP;var lP=["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 cP(t,e){return lP.some(n=>t[n]!==e[n])}var ir=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function pg(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="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 n.message?`${o}
1149
+ `),e.trim()}var qw=null;var dg=()=>qw?qw():Promise.resolve().then(()=>(Uw(),zw));oo();var{setLoader:HO,load:aP}=$t({fallbackImport:()=>Promise.resolve().then(()=>(Kw(),jw))});var Gw=aP;var lP=["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 cP(t,e){return lP.some(n=>t[n]!==e[n])}var ar=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function pg(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="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 n.message?`${o}
1150
1150
 
1151
- _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]}),dP=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Yw=t=>ta(t)||t===ds,vp=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new Fl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new hp(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(ta(n.name)||n.name===ds&&ps(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.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?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ol(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.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&&lg().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||dg().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return fC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Nl.isSupported()?new Nl({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return dg().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=lg().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,d,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new Fl,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){this.clientSession=e,this.injectWelcomeMessage(e)}injectWelcomeMessage(e){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new ir("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new sr("unsupported_scope","This history scope is not supported.");return{scope:s}}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(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new ir("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(s!==this.historyOpenEpoch)throw new ir("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new ir("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,d=this.olderPageRequests.get(l);if(d)return d;let p=this.fetchOlderPage(r,e,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(e,n,o,r){let s=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Bl(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new ir("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new ir("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new ir("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){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(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}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 ir("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}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(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.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 e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||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(),n&&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(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),d=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(g=>l.has(g.id)||g.id===m?!0:p!==void 0&&g.createdAt<p);u=Bl(h,a.messages).map(g=>this.ensureSequence(g))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Wl(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Wl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(e,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(e,r,!0);return}if(s instanceof at&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof at?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:e,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),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(e){return e instanceof at&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r,s){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!t.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};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 s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}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(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=mC(this.config,o),s=cP(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Ol(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=e,g={id:a??(n==="user"?op():n==="assistant"?ra():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(g),g}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:h,rawContent:g}=o,C={id:d??(r==="user"?op():r==="assistant"?ra():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...h!==void 0&&{voiceProcessing:h},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=e,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
1151
+ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]}),dP=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Yw=t=>ta(t)||t===ds,vp=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new Fl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new hp(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(ta(n.name)||n.name===ds&&ps(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.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?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ol(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.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&&lg().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||dg().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return fC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Nl.isSupported()?new Nl({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return dg().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=lg().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,d,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new Fl,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){this.clientSession=e,this.injectWelcomeMessage(e)}injectWelcomeMessage(e){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new ar("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new ir("unsupported_scope","This history scope is not supported.");return{scope:s}}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(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new ar("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(s!==this.historyOpenEpoch)throw new ar("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new ar("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,d=this.olderPageRequests.get(l);if(d)return d;let p=this.fetchOlderPage(r,e,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(e,n,o,r){let s=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Bl(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new ar("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new ar("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new ar("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){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(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}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 ar("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}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(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.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 e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||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(),n&&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(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),d=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(g=>l.has(g.id)||g.id===m?!0:p!==void 0&&g.createdAt<p);u=Bl(h,a.messages).map(g=>this.ensureSequence(g))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Wl(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Wl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(e,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(e,r,!0);return}if(s instanceof at&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof at?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:e,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),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(e){return e instanceof at&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r,s){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!t.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};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 s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}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(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=mC(this.config,o),s=cP(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Ol(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=e,g={id:a??(n==="user"?op():n==="assistant"?ra():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(g),g}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:h,rawContent:g}=o,C={id:d??(r==="user"?op():r==="assistant"?ra():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...h!==void 0&&{voiceProcessing:h},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=e,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
1152
1152
 
1153
1153
  `),a=[s,n].filter(Boolean).join(`
1154
1154
 
1155
- `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(rr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(d){let p=[];a&&p.push(rr(a)),p.push(...r.contentParts),e.contentParts=p}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.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 s=op(),a=ra();this.activeAssistantMessageId=null;let l=n?.contentParts&&pp(n.contentParts)?da:"",d={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(h=>h.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(g=>g.id===s)??d,h=Hw({quote:n.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={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.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 g=pg(m,this.config.errorMessage);if(g){let b={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(b)}}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(e,n){let o=Rw(this.messages,e);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?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}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,h=s?s.options?.quote:void 0,g=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:g===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n: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 e=ra();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=pg(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let h=await u.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(a={[h]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,d=e.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,h)=>{let g=typeof m?.question=="string"?m.question:"";if(!g)return;let b=u[g],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${h}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${h}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==ds?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async d=>{let p=d.toolCall?.name,u=d.toolCall?.id;if(!p||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let h=this.markWebMcpToolRunning(d),g=d.agentMetadata?.webMcpToolCallId??p;if(p===ds)return{dedupeKey:m,resumeKey:g,output:nw(),toolMessage:d,startedAt:h,completedAt:Date.now()};let b=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),C;if(!b)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await b}catch(S){let P=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));return P||this.callbacks.onError?.(S instanceof Error?S:new Error(String(S))),this.markWebMcpToolComplete(d,ug(P?"Aborted by cancel()":dP(S)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,ug("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:g,output:C,toolMessage:d,startedAt:h,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(e,d,{signal:r.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===ds?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,ug("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=is(this.config.features?.artifacts,e),r=El(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=is(this.config.features?.artifacts,n),s=El(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&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(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}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(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.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(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Gw().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>pg(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ra(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=cg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return og(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=cg(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,m=n.approval;a.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&Yw(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,m=this.webMcpInflightKeys.has(u),h=this.webMcpResolvedKeys.has(u),g=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&g!==void 0&&Yw(g)&&r.toolCall?.status==="complete";(m||h||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};Ye();var Eo=require("lucide");ro();Yt();var CP={add:t=>yw(t)},wP=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Ap={allowedTypes:Hr,maxFileSize:10*1024*1024,maxFiles:4};function xP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function SP(t){return t==="application/pdf"?Eo.FileText:t.startsWith("text/")?Eo.FileText:t.includes("word")?Eo.FileText:t.includes("excel")||t.includes("spreadsheet")?Eo.FileSpreadsheet:t==="application/json"?Eo.FileCode:Eo.File}var $l=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Ap.allowedTypes,maxFileSize:e.maxFileSize??Ap.maxFileSize,maxFiles:e.maxFiles??Ap.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:CP}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ap.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=bw(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:xP(),file:o,previewUrl:up(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let r=await this.adapter().add(e.file,{signal:n.signal,onProgress:s=>{o()||e.status!=="uploading"||(e.progress=wP(s),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=r,e.status="ready",e.progress=void 0,e.error=void 0}catch(r){if(o())return;e.status="error",e.progress=void 0,e.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=up(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let u=v("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=v("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=SP(e.file.type),h=Qe(m,20,"var(--persona-muted, #6b7280)",1.5);h&&u.appendChild(h);let g=v("span");g.textContent=vw(e.file.type,e.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--persona-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",u.appendChild(g),o.appendChild(u)}let r=$("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let a=$("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=Ie("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(e.id)}),r.append(s,a),o.appendChild(r);let d=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=Qe(Eo.X,10,"var(--persona-text-inverse, #ffffff)",2);p?d.appendChild(p):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=e.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var Zw=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),AP=(t,e)=>t.length===e.length&&t.every((n,o)=>{let r=e[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function ex(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,r=!1,s=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},l=()=>(n||(n=a()),n),d=()=>{if(o=!1,r||e.size===0)return;let u=l();for(let m of[...e])try{m(u)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(d))};return{getState:l,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,p())},setAttachments:u=>{AP(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{Zw(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{Zw(t.activeModeIds,u)||(t.activeModeIds=[...u],p())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,p())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,p())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,p())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,p())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,p())},flush:()=>{o&&d()},destroy:()=>{r=!0,o=!1,e.clear()}}}Ye();var so=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},tx=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function nx(t,e={}){let n=so(t,"[data-persona-composer-form]"),o=so(t,"[data-persona-composer-input]");if(!n||!o){let P=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(P);return typeof console<"u"&&console.warn(P),null}let r={header:so(t,"[data-persona-composer-header]"),body:so(t,"[data-persona-composer-body]"),actionsStart:so(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:so(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:so(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:so(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:so(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=tx("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):t.appendChild(a));let l=r.body??o.parentElement??n,d=(S,P,M,B,A)=>{if(P)return P;s.add(S);let O=tx(M,B);return A.appendChild(O),O},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),h=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",t),g=[],b=(S,P)=>S.target===P.target&&S.type===P.type&&S.handler===P.handler,C=so(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:h,attachmentInput:C,attachmentPreviews:so(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:so(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:so(t,"[data-persona-composer-submit]")??void 0,micButton:so(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(S,P,M,B)=>{S.addEventListener(P,M,B),g.push({target:S,type:P,handler:M,options:B})},removeListener:(S,P,M,B)=>{S.removeEventListener(P,M,B),g=g.filter(A=>!b(A,{target:S,type:P,handler:M}))},destroy:()=>{for(let S of g)S.target.removeEventListener(S.type,S.handler,S.options);g=[]}}}Ye();Yt();fs();var MP=8,TP=8,hg=10,ox=200,rx=300,sx=0,Tp=t=>Math.max(0,t);function ix(t){t.delayMs!==void 0&&(ox=Tp(t.delayMs)),t.skipDelayMs!==void 0&&(rx=Tp(t.skipDelayMs))}var EP=()=>Date.now()<sx,kP=t=>{sx=t>0?Date.now()+t:0},Mp=new WeakMap,bg="data-persona-tooltip-suppressed",LP=t=>typeof t.closest=="function"&&t.closest(`[${bg}]`)!==null;function ax(t){Mp.get(t)?.hide()}var lx=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,PP=t=>{let e=t.getRootNode?.();return lx(e)?e:t.ownerDocument.body},yg=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),IP=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function Mn(t){Mp.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=MP,viewportPadding:l=TP}=t,d=()=>e.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,h=null,g=null,b,C=!1,S=!1,P=!1,M=()=>(typeof o=="function"?o():o).trim(),B=()=>(typeof r=="function"?r():r??"").trim(),A=()=>Tp(t.delayMs??ox),O=()=>Tp(t.skipDelayMs??rx),E=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},W=()=>{E();let re=u!==null;g?.(),g=null,u?.remove(),u=null,m=null,h=null,re&&kP(O())},R=()=>{if(!u)return;let re=d(),oe=p(),se=e.getBoundingClientRect(),ce=u.getBoundingClientRect(),we=re.documentElement.clientWidth||oe.innerWidth,ge=re.documentElement.clientHeight||oe.innerHeight,N=we-l-ce.width,ye=se.left+se.width/2-ce.width/2,ke=yg(ye,l,N),nt=se.top-l,Ee=ge-l-se.bottom,Ne=ce.height+a,Pe=nt>=Ne||nt>=Ee?"top":"bottom",dt=Pe==="top"?se.top-a-ce.height:se.bottom+a,Xe=ge-l-ce.height,xt=yg(dt,l,Xe),Ge=se.left+se.width/2,yt=Math.max(hg,ce.width-hg),X=yg(Ge-ke,hg,yt);u.dataset.placement=Pe,u.style.left=`${ke}px`,u.style.top=`${xt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${X}px`)},V=()=>{if(P||!s||u||!e.isConnected||LP(e))return;let re=M(),oe=PP(e);if(!re||!oe)return;let se=d(),ce=p();u=se.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(fa);let we=ce.getComputedStyle?.(e);if(we){for(let Ne of IP){let Pe=we.getPropertyValue(Ne).trim();Pe&&u.style.setProperty(Ne,Pe)}we.fontFamily&&(u.style.fontFamily=we.fontFamily)}m=se.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=re,u.appendChild(m);let ge=B();ge&&(h=se.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=ge,u.appendChild(h));let N=se.createElement("span");N.className="persona-control-tooltip__arrow",u.appendChild(N),oe.appendChild(u),R(),u.dataset.state="open";let ye=()=>{if(!e.isConnected){W();return}m&&(m.textContent=M()),h&&(h.textContent=B()),R()};ce.addEventListener("scroll",ye,!0),ce.addEventListener("resize",ye);let ke=e.getRootNode(),nt=lx(ke)?ke:se.documentElement,Ee=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||W()});Ee?.observe(nt,{childList:!0,subtree:!0}),g=()=>{ce.removeEventListener("scroll",ye,!0),ce.removeEventListener("resize",ye),Ee?.disconnect()}},H=re=>{if(!(P||u)){if(E(),re||A()<=0||EP()){V();return}b=p().setTimeout(()=>{b=void 0,V()},A())}},w=()=>{C||S?H(S):W()},T=()=>{let re=p();(!re.matchMedia||!re.matchMedia("(hover: none)").matches)&&(C=!0,w())},I=()=>{C=!1,w()},D=()=>{try{S=e.matches(":focus-visible")}catch{S=!0}w()},G=()=>{S=!1,w()},z=()=>{C=!1,S=!1,W()},K=re=>{re.key==="Escape"&&z()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",I),e.addEventListener("focus",D),e.addEventListener("blur",G),e.addEventListener("keydown",K),e.addEventListener("click",z);let Y={get isOpen(){return u!==null},show:V,hide:W,reposition:R,destroy:()=>{P||(P=!0,W(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",I),e.removeEventListener("focus",D),e.removeEventListener("blur",G),e.removeEventListener("keydown",K),e.removeEventListener("click",z),Mp.delete(e))}};return Mp.set(e,Y),Y}Ye();Yt();var cx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ga(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];cx(s)&&cx(r)?n[o]=ga(s,r):n[o]=r}return n}var Rr="min(440px, calc(100vw - 24px))",px="440px",vg="How can I help...",HP={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:Rr,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)"},It={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:HP,copy:{inputPlaceholder:vg,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 dx(t,e){if(!(!t&&!e))return t?e?ga(t,e):t:e}function Ep(t){return t?{...It,...t,theme:dx(It.theme,t.theme),darkTheme:dx(It.darkTheme,t.darkTheme),launcher:{...It.launcher,...t.launcher,dock:{...It.launcher?.dock,...t.launcher?.dock},clearChat:{...It.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...It.tooltip,...t.tooltip},copy:{...It.copy,...t.copy},sendButton:{...It.sendButton,...t.sendButton},statusIndicator:{...It.statusIndicator,...t.statusIndicator},voiceRecognition:{...It.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=It.features?.artifacts,n=t.features?.artifacts,o=It.features?.scrollToBottom,r=t.features?.scrollToBottom,s=It.features?.scrollBehavior,a=t.features?.scrollBehavior,l=It.features?.streamAnimation,d=t.features?.streamAnimation,p=It.features?.askUserQuestion,u=t.features?.askUserQuestion,m=It.features?.history,h=t.features?.history,g=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},C=s===void 0&&a===void 0?void 0:{...s,...a},S=l===void 0&&d===void 0?void 0:{...l,...d},P=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},M=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...It.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...g!==void 0?{artifacts:g}:{},...S!==void 0?{streamAnimation:S}:{},...P!==void 0?{askUserQuestion:P}:{},...M!==void 0?{history:M}:{}}})(),suggestionChips:t.suggestionChips??It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...It.layout,...t.layout,header:{...It.layout?.header,...t.layout?.header},messages:{...It.layout?.messages,...t.layout?.messages,avatar:{...It.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...It.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...It.layout?.slots,...t.layout?.slots}},markdown:{...It.markdown,...t.markdown,options:{...It.markdown?.options,...t.markdown?.options}},messageActions:{...It.messageActions,...t.messageActions}}:It}function Cg(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function kp(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function ux(t,e){t.style.maxHeight=`${e*Cg(t)}px`,t.style.overflowY="auto"}function ql(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function mx(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function fx(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!mx(e)}function RP(t){return(t.submitKey??"enter")!=="enter"||mx(t)?"enter":"send"}function Lp(t,e){t.setAttribute("enterkeyhint",RP(e))}function Pp(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?t.removeAttribute(r):t.setAttribute(r,s)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function wg(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var fo="persona-composer-control",Vo="persona-composer-control--glyph",Sg=40,$n=24,Ip=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(t);for(let s of n){let a=r.getPropertyValue(s).trim();a?e.style.setProperty(s,a):e.style.removeProperty(s)}},Hp=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??vg,n.dir="auto",Lp(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(n)}),Pp(n,t?.composer?.inputAttributes),n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=kp(t?.composer?.maxLines,e?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let d=o*Cg(n);return r=`${d}px`,n.style.maxHeight=r,d},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:a}},BP="[data-persona-glyph-stack]",Ag=(t,e,n="send")=>{let o=$("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},Rp=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",p=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,h=parseFloat(m??"")||Sg,g=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),S=$("button",{className:Vt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${fo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!b&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?b||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":b||void 0,backgroundColor:n&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),P=null,M=null,B=null;if(n){let E=parseFloat(e.iconSize??"")||Math.round(h*.5),W=e.iconStrokeWidth??2,R=b?.trim()||"currentColor";r&&(P=Ie(r,E,R,W)),M=Ie(s,E,R,W),P&&M?(B=Ag(P,M),S.appendChild(B)):P?S.appendChild(P):(S.textContent=o,M=null)}else S.textContent=d;S.setAttribute("aria-label",a),C.appendChild(S),Mn({anchor:S,trigger:C,text:()=>S.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:S,wrapper:C,setMode:E=>{if(E===A)return;A=E;let W=E==="stop"?l:a;S.setAttribute("aria-label",W),S.setAttribute("data-persona-send-mode",E),n?(S.querySelector(BP)??B)?.setAttribute("data-mode",E):S.textContent=E==="stop"?p:d},glyphStack:B}},ha=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype",s=e.provider?.type==="custom";if(!(o||r||s))return null;let l=e.iconName??"mic",d=e.iconSize,p=parseFloat(d??"")||$n,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,h=v("div","persona-send-button-wrapper"),g=$("button",{className:Vt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",fo,!d&&Vo),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),C=Ie(l,p,m||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",h.appendChild(g);let S=e.tooltipText??"Start voice recognition",P=e.showTooltip??!1;return Mn({anchor:g,trigger:h,text:()=>g.getAttribute("aria-label")??S,enabled:P}),{button:g,wrapper:h}},Wp=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Hr).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=e.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),a=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${fo} ${Vo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=Ie(r,$n,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let d=e.buttonTooltipText??"Attach file";return Mn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},Bp=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let a=v("a");a.href=e.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Op=()=>$("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});ya();Ye();Yt();var DP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',_P=["--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"],Mg="data-persona-menu-focus",NP=new Set(["ArrowDown","ArrowUp","Home","End"]);function bx(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(DP)??t}var FP=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function vx(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${fo} ${Vo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=$("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let D=t.getButtonSize?.()??"";r.style.width=D,r.style.height=D,r.style.minWidth=D,r.style.minHeight=D,r.style.lineHeight="1",r.replaceChildren();let G=Ie("plus",$n,"currentColor",1.5);G?r.appendChild(G):r.textContent="+"},l=()=>{r.setAttribute("aria-label",e),r.setAttribute("title",e),s.setAttribute("aria-label",e)};l(),a();let d=[],p=-1,u=!1,m=()=>{let G=s.getRootNode().activeElement;return G instanceof HTMLElement?G:null},h=()=>{let D=m();for(let G of d){let z=!!D&&bx(G)===D;G.toggleAttribute(Mg,z&&u)}},g=()=>d.filter(D=>D.isConnected||s.contains(D)).map(bx).filter(D=>!FP(D)),b=(D,G)=>{D.forEach((z,K)=>{z.setAttribute("tabindex",K===G?"0":"-1")})},C=D=>{let G=g();if(G.length===0)return;let z=(D%G.length+G.length)%G.length;p=z,b(G,z),G[z].focus(),h()},S=()=>o.ownerDocument??document,P=null,M=null,B=null,A=()=>{P&&(S().removeEventListener("focusin",P,!0),P=null)},O=()=>{M&&(s.removeEventListener("focusin",M),M=null),B&&(s.removeEventListener("pointerdown",B,!0),B=null)},E=null,W=()=>(E||(E=gs({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),E),R=()=>E?.isOpen===!0,V=(D=!1)=>{if(R()){E?.close(),r.setAttribute("aria-expanded","false"),A(),O(),p=-1,u=!1;for(let G of d)G.removeAttribute(Mg);D&&r.focus()}},H=(D=0,G=!1)=>{if(n||R())return;u=G,Ip(r,s,_P),W().open(),r.setAttribute("aria-expanded","true");let z=g();b(z,-1),C(D<0?z.length-1:D),P=K=>{let Y=typeof K.composedPath=="function"?K.composedPath():[];Y.includes(s)||Y.includes(o)||V()},S().addEventListener("focusin",P,!0),M=()=>h(),s.addEventListener("focusin",M),B=()=>{u=!1},s.addEventListener("pointerdown",B,!0)},w=D=>{D.preventDefault(),D.stopPropagation(),R()?V(!0):H(0)},T=D=>{if(D.key==="ArrowDown"||D.key==="Enter"||D.key===" "){D.preventDefault(),u=!0,R()?C(0):H(0,!0);return}D.key==="ArrowUp"&&(D.preventDefault(),u=!0,R()?C(-1):H(-1,!0))},I=D=>{switch(NP.has(D.key)&&(u=!0),D.key){case"ArrowDown":D.preventDefault(),C(p+1);return;case"ArrowUp":D.preventDefault(),C(p-1);return;case"Home":D.preventDefault(),C(0);return;case"End":D.preventDefault(),C(g().length-1);return;case"Escape":D.preventDefault(),D.stopPropagation(),V(!0);return;case"Tab":V(!0);return;default:}};return r.addEventListener("click",w),r.addEventListener("keydown",T),s.addEventListener("keydown",I),{trigger:o,triggerButton:r,panel:s,setItems:D=>{for(let z of d)D.includes(z)||z.removeAttribute(Mg);if(d=[...D],!R())return;let G=g();b(G,Math.min(p,G.length-1)),h()},isOpen:R,open:()=>H(0),close:V,setLabel:D=>{D!==e&&(e=D,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),O(),r.removeEventListener("click",w),r.removeEventListener("keydown",T),s.removeEventListener("keydown",I),E?.destroy(),E=null,o.remove(),s.remove(),d=[]}}}var ar={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Cx="data-persona-composer-action",Tg="data-persona-composer-disable-when-streaming",VP="core:overflow",$P=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function zP(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=v("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function Eg(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-r)}var wx=(t,e)=>{!t||typeof console>"u"||console.warn(e)},UP=(t,e)=>e.includes(":")?e:`${t}:${e}`;function qP(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){wx(e,`[Persona] composer action "${l.id}" is already contributed by ${xx(d)}; the ${xx(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of t.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,d,p)=>{let u=p?UP(p,l.id):l.id,m=l.order??ar.custom;l.placement==="end"&&m>=ar.send&&(wx(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${ar.send-1}.`),m=ar.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:d,pluginId:p,action:l})};for(let l of t.configActions??[])a(l,"config");for(let l of t.plugins){if(!l.contributeComposerActions)continue;let d;try{d=l.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of d??[])a(p,"plugin",l.id)}return n.sort((l,d)=>l.order===d.order?l.sequence-d.sequence:l.order-d.order)}var xx=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Sx=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,jP=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function KP(t,e){if(!t||t==="always")return!0;let n=jP(e);return t==="when-text"?n:!n}var hs=t=>t.kind==="custom",kg=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,GP=t=>{let e=kg(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},YP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function QP(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(YP)||o.childNodes.forEach(n)};return n(t),e.trim()}var XP=t=>QP(t).length===0;function Ax(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(w,T)=>{let I=w.button;if(!I)return;I.setAttribute("role","menuitem"),I.setAttribute("tabindex","-1"),I.className="persona-composer-overflow-menu__item";for(let z of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])I.style[z]="";I.style.lineHeight="1",T.tooltipText?I.setAttribute("title",T.tooltipText):I.removeAttribute("title"),I.replaceChildren();let D=v("span","persona-composer-overflow-menu__icon");if(T.iconName){let z=Ie(T.iconName,16,"currentColor",1.5);z&&D.appendChild(z)}let G=v("span","persona-composer-overflow-menu__label");G.textContent=T.shortLabel??T.label,I.append(D,G)},a=(w,T)=>{let I=w.button;if(!I)return;if(I.setAttribute("aria-label",T.label),T.pressed===void 0?I.removeAttribute("aria-pressed"):I.setAttribute("aria-pressed",T.pressed?"true":"false"),I.toggleAttribute(Tg,T.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,s(w,T);return}I.removeAttribute("role"),I.removeAttribute("tabindex"),I.removeAttribute("title");let D=r(),G=!!T.shortLabel;if(I.className=Vt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",fo,Vo,G&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),I.style.width=D&&!G?D:"",I.style.height=D??"",I.style.minWidth=D&&!G?D:"",I.style.minHeight=D??"",I.style.fontSize=G?"":"18px",I.style.lineHeight="1",I.style.color=T.iconColor??"",I.style.backgroundColor=T.backgroundColor??"",I.replaceChildren(),T.iconName){let z=Ie(T.iconName,$n,"currentColor",1.5);z&&I.appendChild(z)}if(G){let z=v("span","persona-composer-action-button__label");z.textContent=T.shortLabel,I.appendChild(z)}else I.firstChild||(I.textContent=T.label);w.tooltip?.destroy(),w.tooltip=Mn({anchor:I,trigger:w.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(w,T)=>{let I=w.action,D=$("button",{attrs:{type:"button"}}),G=D;if(T==="bar"){let Y=v("div","persona-send-button-wrapper");Y.appendChild(D),G=Y}G.setAttribute(Cx,w.id);let z={resolved:w,element:G,button:D,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},K=Y=>{if(Y.preventDefault(),Y.stopPropagation(),z.busy||D.disabled)return;let re=z.resolved.action;z.mode==="menu"&&g?.close(!0);let oe;try{oe=re.onSelect(t.actionContext,Y)}catch(se){t.reportError(se,{actionId:z.resolved.id});return}!oe||typeof oe.then!="function"||(z.busy=!0,D.setAttribute("aria-busy","true"),oe.catch(se=>{t.reportError(se,{actionId:z.resolved.id})}).finally(()=>{z.busy=!1,D.removeAttribute("aria-busy")}))};return D.addEventListener("click",K),z.detach=()=>D.removeEventListener("click",K),a(z,I),z},d=w=>{let T=w.action,I;try{I=T.render({...t.actionContext,id:w.id,action:T})}catch(D){return t.reportError(D,{actionId:w.id}),null}return I?.element?(I.element.setAttribute(Cx,w.id),I.element.toggleAttribute(Tg,T.disableWhenStreaming===!0),{resolved:w,element:I.element,owned:!0,managed:!0,destroy:I.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,T)=>{if(w.builtIn){let D=w.builtIn.element;return D?{resolved:w,element:D,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let I=w.action;return I?hs(I)?d(w):l(w,T):null},u=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(T){t.reportError(T,{actionId:w.resolved.id})}w.element.remove()}},m=(w,T)=>{for(let I=0;I<T.length;I++){let D=T[I];if(!D.managed)continue;let G=null;for(let z=I+1;z<T.length;z++){let K=T[z];if(!K.managed&&K.element.parentElement===w){G=K.element;break}}G?(D.element.parentElement!==w||D.element.nextSibling!==G)&&w.insertBefore(D.element,G):w.lastChild!==D.element&&w.appendChild(D.element)}},h=(w,T)=>{if(w.button){w.button.disabled=T;return}if(!w.owned)return;let I=w.element;I.toggleAttribute("data-disabled",T),I.setAttribute("aria-disabled",T?"true":"false");let D=I instanceof HTMLButtonElement||I instanceof HTMLSelectElement||I instanceof HTMLInputElement||I instanceof HTMLTextAreaElement?I:I.querySelector("button, select, input, textarea");D&&(D.disabled=T)},g=null,b=null,C=null,S=0,P=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},M=()=>(g?g.setLabel(t.getOverflowLabel?.()??"More actions"):g=vx({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),B=w=>{b!==w&&(C?.disconnect(),b=w,S=Eg(w),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(T=>{let D=T[T.length-1]?.contentRect?.width??Eg(w);D!==S&&(S=D,V())}),C.observe(w)))},A=(w,T)=>{let I=zP(w.collapseAutoActionsBelow,T);if(I===null)return!1;let D=S||Eg(T);return D>0&&D<I},O=(w,T,I)=>{if(!T)return"bar";if(w.resolved.builtIn){let G=$P(w.resolved.id);return G&&T.includeBuiltIns?.includes(G)?"menu":"bar"}let D=w.resolved.presentation;return D==="overflow"||D==="auto"&&I?"menu":"bar"},E=w=>{let T=w.menuSlot;if(!T)return;if(!XP(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let I=GP(w.element);if(!I){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=v("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==I&&(w.menuLabel.textContent=I),w.menuLabel.parentElement!==T&&T.appendChild(w.menuLabel)},W=(w,T)=>{if(w.mode===T)return w;let I=w.resolved.action;if(I&&!hs(I)){u(w),e.delete(w.resolved.id);let D=l(w.resolved,T);return e.set(w.resolved.id,D),D}if(T==="menu"){let D=$("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[bg]:""}});D.appendChild(w.element),ax(kg(w.element)),w.menuSlot=D;let G=z=>{let K=kg(w.element);if(K.disabled)return;let Y=z.target===K||K.contains(z.target);g?.close(!0),Y||K.click()};D.addEventListener("click",G,!0),w.detachMenuSlot=()=>D.removeEventListener("click",G,!0),w.managed=!0,E(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=T,w},R=(w,T)=>{let I=T.map(D=>D.menuSlot??D.element);for(I.forEach((D,G)=>{let z=w.children[G];z!==D&&(z?w.insertBefore(D,z):w.appendChild(D))});w.children.length>I.length;)w.lastElementChild?.remove()},V=()=>{if(o)return;let w=t.getBindings();if(!w)return;let T=t.getState(),I=T.phase==="streaming",D=P();D&&B(w.footer);let G=D?A(D,w.footer):!1,z={start:[],end:[]},K=[];for(let Y of n){let re=e.get(Y.id);if(!re)continue;let oe=Y.action,se=oe?Sx(oe.visible,T,!0)&&KP(oe.visibility,T):!0;if(re.visible!==se&&(re.visible=se,!se&&re.managed&&(re.menuSlot??re.element).remove()),!!se){if(re=W(re,O(re,D,G)),oe){let ce=Sx(oe.disabled,T,!1)||oe.disableWhenStreaming===!0&&I;h(re,ce),!hs(oe)&&oe.pressed!==void 0&&re.button?.setAttribute("aria-pressed",oe.pressed?"true":"false")}re.mode==="menu"?(E(re),K.push(re)):z[Y.placement].push(re)}}if(K.length>0){let Y=M();R(Y.panel,K),Y.setItems(K.map(ce=>ce.menuSlot??ce.element)),Y.applyButtonSize();let re=Number.isFinite(D?.order)?D?.order:ar.overflow,oe=z.start.findIndex(ce=>ce.resolved.order>re),se={resolved:{id:VP,placement:"start",presentation:"bar",order:re,sequence:-1,source:"core"},element:Y.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};z.start.splice(oe<0?z.start.length:oe,0,se)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));m(w.actionsStart,z.start),m(w.actionsEnd,z.end)};return{resolve:()=>{if(o)return;let w=qP(t.collect()),T=new Set(w.map(I=>I.id));for(let[I,D]of e)T.has(I)||(u(D),e.delete(I));for(let I of w){let D=e.get(I.id);if(!D){let Y=p(I,"bar");Y&&e.set(I.id,Y);continue}let G=D.resolved.action,z=I.action;if(!!G!=!!z||G&&z&&hs(G)!==hs(z)||G&&z&&hs(G)&&hs(z)&&G.render!==z.render){u(D),e.delete(I.id);let Y=p(I,D.mode);Y&&e.set(I.id,Y);continue}D.resolved=I,I.builtIn?(D.managed=I.builtIn.managed===!0||D.mode==="menu",I.builtIn.element&&D.mode==="bar"&&(D.element=I.builtIn.element)):z&&!hs(z)?a(D,z):z&&D.element.toggleAttribute(Tg,z.disableWhenStreaming===!0)}n=w,V()},sync:V,getResolved:()=>n,getOverflowMenu:()=>g,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,b=null;for(let w of e.values())u(w);e.clear(),g?.destroy(),g=null,n=[]}}}}ya();Ye();Yt();var JP="core:model",ZP=700,Mx=16,eI=["--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"],Tx=()=>{let t=$("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=$("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Ex(t){let e=t.label??"Model",n=t.presentation??"native",o=null,r=d=>{let p=t.getSelectedModelId();return d.find(u=>u.id===p)??d[0]},s=()=>{let d=$("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),S=C.map(P=>`${P.id}:${P.label}`).join("|");S!==p&&(p=S,d.replaceChildren(...C.map(P=>{let M=$("option",{attrs:{value:P.id}});return M.textContent=P.label,M}))),d.value=r(C)?.id??""};u(),o=u;let m=()=>{d.value&&t.onSelect(d.value)};d.addEventListener("change",m);let h=C=>C.stopPropagation();d.addEventListener("click",h);let{wrapper:g,chevron:b}=Tx();return g.append(d,b),{element:g,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",h)}}},a=()=>{let d=$("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"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");d.append(p,u);let m=$("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),h=new Map,g="",b=null,C=()=>b?.isOpen===!0,S=(T=!1)=>{C()&&(b?.close(),d.setAttribute("aria-expanded","false"),T&&d.focus())},P=T=>{let I=[...h.values()];if(I.length===0)return;let D=(T%I.length+I.length)%I.length;I[D].focus()},M=T=>{if(C())return;b||(b=gs({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Ip(d,m,eI),b.open(),d.setAttribute("aria-expanded","true");let D=[...h.keys()].indexOf(r(t.getModels())?.id??"");P(T??(D>=0?D:0))},B=T=>{S(!0),t.onSelect(T)},A=T=>{T.preventDefault(),T.stopPropagation();let I=T.currentTarget.getAttribute("data-persona-model-option");I&&B(I)},O=T=>{let I=$("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let Y=Ie(T.icon,Mx,"currentColor",1.5);if(Y){let re=v("span","persona-composer-model-option-icon");re.appendChild(Y),I.appendChild(re)}}let D=v("span","persona-composer-model-option-body"),G=v("span","persona-composer-model-option-label");if(G.textContent=T.label,D.appendChild(G),T.description){let Y=v("span","persona-composer-model-option-description");Y.textContent=T.description,D.appendChild(Y)}I.appendChild(D);let z=v("span","persona-composer-model-option-check");z.setAttribute("aria-hidden","true");let K=Ie("check",Mx,"currentColor",2);return K&&z.appendChild(K),I.appendChild(z),I.addEventListener("click",A),I},E=()=>{let T=t.getModels(),I=T.map(z=>`${z.id}:${z.label}:${z.icon??""}:${z.description??""}`).join("|");if(I!==g){g=I;for(let z of h.values())z.removeEventListener("click",A);h.clear(),m.replaceChildren(...T.map(z=>{let K=O(z);return h.set(z.id,K),K}))}let D=r(T);for(let[z,K]of h)K.setAttribute("aria-selected",String(z===D?.id));p.textContent=D?.label??"";let G=t.getSuffix?.()??"";u.textContent=G,d.setAttribute("aria-label",[e,[D?.label,G].filter(Boolean).join(" ")].filter(Boolean).join(": "))};E(),o=E;let W=T=>{T.preventDefault(),T.stopPropagation(),C()?S(!0):M()},R=T=>{if(T.key==="ArrowDown"){T.preventDefault(),C()?P(0):M(0);return}T.key==="ArrowUp"&&(T.preventDefault(),C()?P(-1):M(-1))},V=T=>{let I=[...h.values()],D=I.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),P(D+1);return;case"ArrowUp":T.preventDefault(),P(D-1);return;case"Home":T.preventDefault(),P(0);return;case"End":T.preventDefault(),P(I.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};d.addEventListener("click",W),d.addEventListener("keydown",R),m.addEventListener("keydown",V);let{wrapper:H,chevron:w}=Tx();return H.append(d,w),{element:H,destroy:()=>{o===E&&(o=null),d.removeEventListener("click",W),d.removeEventListener("keydown",R),m.removeEventListener("keydown",V);for(let T of h.values())T.removeEventListener("click",A);h.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:JP,kind:"custom",placement:"end",order:ZP,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}Ye();Yt();Fp();var tI=":scope > [data-persona-composer-mode]";function kx(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=$("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let b=v("span","persona-mention-chip-icon"),C=Ie(p.iconName,12,"currentColor",1.5);C&&b.appendChild(C),u.appendChild(b)}let m=v("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let h=$("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),g=Ie("x",12,"currentColor",2);return g?h.appendChild(g):h.textContent="\xD7",h.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),t.onRemove(p.id)}),u.appendChild(h),u},a=()=>Array.from(e.querySelectorAll(tI)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),ba(e)},m=e.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!h||h==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:e,render:(p,u)=>{if(o)return;let m=u.filter(C=>p.includes(C.id)),h=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(h===n)return;n=h;let g=new Map;for(let C of a()){let S=C.getAttribute("data-persona-composer-mode");S&&m.some(M=>M.id===S)&&!C.hasAttribute("data-persona-chip-exit")?g.set(S,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let b=e.firstChild;for(let C of m){let S=g.get(C.id);S||(S=s(C),r.has(C.id)||(S.setAttribute("data-persona-chip-enter",""),S.addEventListener("animationend",()=>S?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),S!==b&&e.insertBefore(S,b),b=S.nextSibling}ba(e)},destroy:()=>{o=!0,d(),ba(e)}}}Ye();Yt();var Lx=t=>`core:mode:${t}`;var Ig=t=>Math.min(300+t,499),Px=t=>`core:mode-group:${t}`;function Vp(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function nI(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ix(t,e){return t?.length?t.filter(n=>!Vp(n.groupId,e)&&!nI(n.groupId,e)):[]}var oI=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Hx(t,e,n,o){let r=n.find(l=>l.id===e);if(!r)return[...t];let s=t.includes(e),a=new Set(t);if(s)a.delete(e);else{if(oI(r,o)==="single"){let l=n.filter(d=>d.groupId===r.groupId).map(d=>d.id);a=new Set([...a].filter(d=>!l.includes(d)))}a.add(e)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function $p(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Rx(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Wx(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var rI=16;function Bx(t){let e=null;return{action:{id:Px(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=$("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},l=p=>{let u=$("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=Ie(p.iconName,rI,"currentColor",1.5);h&&u.appendChild(h)}let m=v("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(g=>`${g.id}:${g.shortLabel??g.label}:${g.iconName??""}`).join("|");if(m!==s){s=m;for(let b of r.values())b.removeEventListener("click",a);r.clear();let g=u.map(b=>{let C=l(b);return r.set(b.id,C),C});o.replaceChildren(...g)}let h=t.getActiveIds();for(let[g,b]of r)b.setAttribute("aria-pressed",String(h.includes(g)))};return d(),e=d,{element:o,destroy:()=>{e===d&&(e=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>e?.()}}Fp();Ye();Yt();function Ox(t){let e=$("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,r=s=>{let a=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let m=v("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=$("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=fp(s.text),l.appendChild(d);let p=$("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=Ie("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(a,l,p)};return{element:e,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){e.replaceChildren(),e.style.display="none";return}r(s),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}Ye();Yt();function Dx(t){let e=$("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,r=(a,l,d,p)=>{let u=$("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=Ie(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),u},s=a=>{let l=fp(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:e,render:a=>{if(o||a===n)return;if(n=a,!a){e.replaceChildren(),e.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=t.label??"Sends next";let d=$("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=s(a),e.replaceChildren(l,d,r("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),r("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}Ye();function _x(t){let e=$("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=$("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=v("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=$("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&t.onSave(l)};return r.append(s(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),s(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),t.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),e.append(n,r),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Nx(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function Fx(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(d=>n.has(d.sourceId)),r=o.length===(t.mentionRefs?.length??0)&&o.length>0,s=new Set(e.modes.map(d=>d.id)),a=(t.activeModeIds??[]).filter(d=>s.has(d)),l=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...r?{mentionRefs:o}:{},...r&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...t.quote?.text?{quote:t.quote}:{}}}function Vx(t){let e=t.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(r(),t.write())},cancel:r,destroy:()=>{o=!0,r()}}}function $x(t){return t.wrapped||t.text.includes(`
1156
- `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function zx(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function Ux(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let a=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-a>s*1.5}zp();function Hg(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function Kx(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var sI=t=>typeof t?.then=="function";function jx(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function Gx(t,e,n){let o;try{o=t(Hg(e),{signal:n})}catch(r){return{status:"error",error:r}}return sI(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:jx(e,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):jx(e,o)}Ye();Up();Rg();Ye();Yt();function Jx(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",r=e.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),a=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${fo} ${Vo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=Ie(o,$n,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),Mn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}oo();var{setLoader:oN,load:uI}=$t({fallbackImport:()=>Promise.resolve().then(()=>(hS(),gS))});var Dg=uI;Yt();oo();var{setLoader:gN,load:xI}=$t({fallbackImport:()=>Promise.resolve().then(()=>(kS(),ES)),resetOnSetLoader:!0});var LS=xI;Ye();Yt();function Jl(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=$("span",{className:Vt("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=Ie(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild($("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function PS(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=qp(e).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(O=>typeof O.matchCommand=="function")),r=A=>o.some(O=>O.trigger?O.position==="line-start"?A.split(`
1155
+ `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(sr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(d){let p=[];a&&p.push(sr(a)),p.push(...r.contentParts),e.contentParts=p}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.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 s=op(),a=ra();this.activeAssistantMessageId=null;let l=n?.contentParts&&pp(n.contentParts)?da:"",d={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(h=>h.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(g=>g.id===s)??d,h=Hw({quote:n.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={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.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 g=pg(m,this.config.errorMessage);if(g){let b={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(b)}}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(e,n){let o=Rw(this.messages,e);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?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}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,h=s?s.options?.quote:void 0,g=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:g===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n: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 e=ra();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=pg(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let h=await u.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(a={[h]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,d=e.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,h)=>{let g=typeof m?.question=="string"?m.question:"";if(!g)return;let b=u[g],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${h}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${h}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==ds?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async d=>{let p=d.toolCall?.name,u=d.toolCall?.id;if(!p||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let h=this.markWebMcpToolRunning(d),g=d.agentMetadata?.webMcpToolCallId??p;if(p===ds)return{dedupeKey:m,resumeKey:g,output:nw(),toolMessage:d,startedAt:h,completedAt:Date.now()};let b=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),C;if(!b)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await b}catch(S){let P=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));return P||this.callbacks.onError?.(S instanceof Error?S:new Error(String(S))),this.markWebMcpToolComplete(d,ug(P?"Aborted by cancel()":dP(S)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,ug("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:g,output:C,toolMessage:d,startedAt:h,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(e,d,{signal:r.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===ds?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,ug("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=is(this.config.features?.artifacts,e),r=El(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=is(this.config.features?.artifacts,n),s=El(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&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(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}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(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.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(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Gw().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>pg(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ra(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=cg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return og(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=cg(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,m=n.approval;a.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&Yw(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,m=this.webMcpInflightKeys.has(u),h=this.webMcpResolvedKeys.has(u),g=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&g!==void 0&&Yw(g)&&r.toolCall?.status==="complete";(m||h||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};Ye();var ko=require("lucide");ro();Yt();var CP={add:t=>yw(t)},wP=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,Ap={allowedTypes:Hr,maxFileSize:10*1024*1024,maxFiles:4};function xP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function SP(t){return t==="application/pdf"?ko.FileText:t.startsWith("text/")?ko.FileText:t.includes("word")?ko.FileText:t.includes("excel")||t.includes("spreadsheet")?ko.FileSpreadsheet:t==="application/json"?ko.FileCode:ko.File}var $l=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??Ap.allowedTypes,maxFileSize:e.maxFileSize??Ap.maxFileSize,maxFiles:e.maxFiles??Ap.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:CP}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ap.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=bw(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:xP(),file:o,previewUrl:up(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let r=await this.adapter().add(e.file,{signal:n.signal,onProgress:s=>{o()||e.status!=="uploading"||(e.progress=wP(s),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=r,e.status="ready",e.progress=void 0,e.error=void 0}catch(r){if(o())return;e.status="error",e.progress=void 0,e.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=up(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let u=v("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=v("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=SP(e.file.type),h=Qe(m,20,"var(--persona-muted, #6b7280)",1.5);h&&u.appendChild(h);let g=v("span");g.textContent=vw(e.file.type,e.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--persona-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",u.appendChild(g),o.appendChild(u)}let r=$("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=v("div","persona-attachment-progress");s.appendChild(v("div","persona-attachment-progress__bar"));let a=$("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=Ie("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(e.id)}),r.append(s,a),o.appendChild(r);let d=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=Qe(ko.X,10,"var(--persona-text-inverse, #ffffff)",2);p?d.appendChild(p):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=e.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var Zw=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),AP=(t,e)=>t.length===e.length&&t.every((n,o)=>{let r=e[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function ex(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,r=!1,s=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},l=()=>(n||(n=a()),n),d=()=>{if(o=!1,r||e.size===0)return;let u=l();for(let m of[...e])try{m(u)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(d))};return{getState:l,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,p())},setAttachments:u=>{AP(t.attachments,u)||(t.attachments=[...u],p())},setMentionRefs:u=>{Zw(t.mentionRefs,u)||(t.mentionRefs=[...u],p())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,p())},setActiveModeIds:u=>{Zw(t.activeModeIds,u)||(t.activeModeIds=[...u],p())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,p())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,p())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,p())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,p())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,p())},flush:()=>{o&&d()},destroy:()=>{r=!0,o=!1,e.clear()}}}Ye();var so=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},tx=(t,e)=>{let n=v("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function nx(t,e={}){let n=so(t,"[data-persona-composer-form]"),o=so(t,"[data-persona-composer-input]");if(!n||!o){let P=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(P);return typeof console<"u"&&console.warn(P),null}let r={header:so(t,"[data-persona-composer-header]"),body:so(t,"[data-persona-composer-body]"),actionsStart:so(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:so(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:so(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:so(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:so(t,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=tx("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):t.appendChild(a));let l=r.body??o.parentElement??n,d=(S,P,M,B,A)=>{if(P)return P;s.add(S);let O=tx(M,B);return A.appendChild(O),O},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),h=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",t),g=[],b=(S,P)=>S.target===P.target&&S.type===P.type&&S.handler===P.handler,C=so(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:h,attachmentInput:C,attachmentPreviews:so(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:so(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:so(t,"[data-persona-composer-submit]")??void 0,micButton:so(t,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(S,P,M,B)=>{S.addEventListener(P,M,B),g.push({target:S,type:P,handler:M,options:B})},removeListener:(S,P,M,B)=>{S.removeEventListener(P,M,B),g=g.filter(A=>!b(A,{target:S,type:P,handler:M}))},destroy:()=>{for(let S of g)S.target.removeEventListener(S.type,S.handler,S.options);g=[]}}}Ye();Yt();fs();var MP=8,TP=8,hg=10,ox=200,rx=300,sx=0,Tp=t=>Math.max(0,t);function ix(t){t.delayMs!==void 0&&(ox=Tp(t.delayMs)),t.skipDelayMs!==void 0&&(rx=Tp(t.skipDelayMs))}var EP=()=>Date.now()<sx,kP=t=>{sx=t>0?Date.now()+t:0},Mp=new WeakMap,bg="data-persona-tooltip-suppressed",LP=t=>typeof t.closest=="function"&&t.closest(`[${bg}]`)!==null;function ax(t){Mp.get(t)?.hide()}var lx=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,PP=t=>{let e=t.getRootNode?.();return lx(e)?e:t.ownerDocument.body},yg=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),IP=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function Mn(t){Mp.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=MP,viewportPadding:l=TP}=t,d=()=>e.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,h=null,g=null,b,C=!1,S=!1,P=!1,M=()=>(typeof o=="function"?o():o).trim(),B=()=>(typeof r=="function"?r():r??"").trim(),A=()=>Tp(t.delayMs??ox),O=()=>Tp(t.skipDelayMs??rx),E=()=>{b!==void 0&&(p().clearTimeout(b),b=void 0)},W=()=>{E();let re=u!==null;g?.(),g=null,u?.remove(),u=null,m=null,h=null,re&&kP(O())},R=()=>{if(!u)return;let re=d(),oe=p(),se=e.getBoundingClientRect(),ce=u.getBoundingClientRect(),we=re.documentElement.clientWidth||oe.innerWidth,ge=re.documentElement.clientHeight||oe.innerHeight,N=we-l-ce.width,ye=se.left+se.width/2-ce.width/2,ke=yg(ye,l,N),nt=se.top-l,Ee=ge-l-se.bottom,Ne=ce.height+a,Pe=nt>=Ne||nt>=Ee?"top":"bottom",dt=Pe==="top"?se.top-a-ce.height:se.bottom+a,Xe=ge-l-ce.height,xt=yg(dt,l,Xe),Ge=se.left+se.width/2,yt=Math.max(hg,ce.width-hg),X=yg(Ge-ke,hg,yt);u.dataset.placement=Pe,u.style.left=`${ke}px`,u.style.top=`${xt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${X}px`)},V=()=>{if(P||!s||u||!e.isConnected||LP(e))return;let re=M(),oe=PP(e);if(!re||!oe)return;let se=d(),ce=p();u=se.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(fa);let we=ce.getComputedStyle?.(e);if(we){for(let Ne of IP){let Pe=we.getPropertyValue(Ne).trim();Pe&&u.style.setProperty(Ne,Pe)}we.fontFamily&&(u.style.fontFamily=we.fontFamily)}m=se.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=re,u.appendChild(m);let ge=B();ge&&(h=se.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=ge,u.appendChild(h));let N=se.createElement("span");N.className="persona-control-tooltip__arrow",u.appendChild(N),oe.appendChild(u),R(),u.dataset.state="open";let ye=()=>{if(!e.isConnected){W();return}m&&(m.textContent=M()),h&&(h.textContent=B()),R()};ce.addEventListener("scroll",ye,!0),ce.addEventListener("resize",ye);let ke=e.getRootNode(),nt=lx(ke)?ke:se.documentElement,Ee=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||W()});Ee?.observe(nt,{childList:!0,subtree:!0}),g=()=>{ce.removeEventListener("scroll",ye,!0),ce.removeEventListener("resize",ye),Ee?.disconnect()}},H=re=>{if(!(P||u)){if(E(),re||A()<=0||EP()){V();return}b=p().setTimeout(()=>{b=void 0,V()},A())}},w=()=>{C||S?H(S):W()},T=()=>{let re=p();(!re.matchMedia||!re.matchMedia("(hover: none)").matches)&&(C=!0,w())},I=()=>{C=!1,w()},D=()=>{try{S=e.matches(":focus-visible")}catch{S=!0}w()},G=()=>{S=!1,w()},z=()=>{C=!1,S=!1,W()},K=re=>{re.key==="Escape"&&z()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",I),e.addEventListener("focus",D),e.addEventListener("blur",G),e.addEventListener("keydown",K),e.addEventListener("click",z);let Y={get isOpen(){return u!==null},show:V,hide:W,reposition:R,destroy:()=>{P||(P=!0,W(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",I),e.removeEventListener("focus",D),e.removeEventListener("blur",G),e.removeEventListener("keydown",K),e.removeEventListener("click",z),Mp.delete(e))}};return Mp.set(e,Y),Y}Ye();Yt();var cx=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ga(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];cx(s)&&cx(r)?n[o]=ga(s,r):n[o]=r}return n}var Rr="min(440px, calc(100vw - 24px))",px="440px",vg="How can I help...",HP={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:Rr,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)"},It={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:HP,copy:{inputPlaceholder:vg,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 dx(t,e){if(!(!t&&!e))return t?e?ga(t,e):t:e}function Ep(t){return t?{...It,...t,theme:dx(It.theme,t.theme),darkTheme:dx(It.darkTheme,t.darkTheme),launcher:{...It.launcher,...t.launcher,dock:{...It.launcher?.dock,...t.launcher?.dock},clearChat:{...It.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...It.tooltip,...t.tooltip},copy:{...It.copy,...t.copy},sendButton:{...It.sendButton,...t.sendButton},statusIndicator:{...It.statusIndicator,...t.statusIndicator},voiceRecognition:{...It.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=It.features?.artifacts,n=t.features?.artifacts,o=It.features?.scrollToBottom,r=t.features?.scrollToBottom,s=It.features?.scrollBehavior,a=t.features?.scrollBehavior,l=It.features?.streamAnimation,d=t.features?.streamAnimation,p=It.features?.askUserQuestion,u=t.features?.askUserQuestion,m=It.features?.history,h=t.features?.history,g=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},C=s===void 0&&a===void 0?void 0:{...s,...a},S=l===void 0&&d===void 0?void 0:{...l,...d},P=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},M=m===void 0&&h===void 0?void 0:{...m,...h,copy:{...m?.copy,...h?.copy}};return{...It.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...g!==void 0?{artifacts:g}:{},...S!==void 0?{streamAnimation:S}:{},...P!==void 0?{askUserQuestion:P}:{},...M!==void 0?{history:M}:{}}})(),suggestionChips:t.suggestionChips??It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...It.layout,...t.layout,header:{...It.layout?.header,...t.layout?.header},messages:{...It.layout?.messages,...t.layout?.messages,avatar:{...It.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...It.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...It.layout?.slots,...t.layout?.slots}},markdown:{...It.markdown,...t.markdown,options:{...It.markdown?.options,...t.markdown?.options}},messageActions:{...It.messageActions,...t.messageActions}}:It}function Cg(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function kp(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function ux(t,e){t.style.maxHeight=`${e*Cg(t)}px`,t.style.overflowY="auto"}function ql(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function mx(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function fx(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!mx(e)}function RP(t){return(t.submitKey??"enter")!=="enter"||mx(t)?"enter":"send"}function Lp(t,e){t.setAttribute("enterkeyhint",RP(e))}function Pp(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?t.removeAttribute(r):t.setAttribute(r,s)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function wg(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var fo="persona-composer-control",$o="persona-composer-control--glyph",Sg=40,$n=24,Ip=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(t);for(let s of n){let a=r.getPropertyValue(s).trim();a?e.style.setProperty(s,a):e.style.removeProperty(s)}},Hp=(t,e)=>{let n=v("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??vg,n.dir="auto",Lp(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(n)}),Pp(n,t?.composer?.inputAttributes),n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=kp(t?.composer?.maxLines,e?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let d=o*Cg(n);return r=`${d}px`,n.style.maxHeight=r,d},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:a}},BP="[data-persona-glyph-stack]",Ag=(t,e,n="send")=>{let o=$("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},Rp=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",p=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,h=parseFloat(m??"")||Sg,g=e.backgroundColor,b=e.textColor,C=v("div","persona-send-button-wrapper"),S=$("button",{className:Vt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${fo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!b&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?b||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":b||void 0,backgroundColor:n&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),P=null,M=null,B=null;if(n){let E=parseFloat(e.iconSize??"")||Math.round(h*.5),W=e.iconStrokeWidth??2,R=b?.trim()||"currentColor";r&&(P=Ie(r,E,R,W)),M=Ie(s,E,R,W),P&&M?(B=Ag(P,M),S.appendChild(B)):P?S.appendChild(P):(S.textContent=o,M=null)}else S.textContent=d;S.setAttribute("aria-label",a),C.appendChild(S),Mn({anchor:S,trigger:C,text:()=>S.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:S,wrapper:C,setMode:E=>{if(E===A)return;A=E;let W=E==="stop"?l:a;S.setAttribute("aria-label",W),S.setAttribute("data-persona-send-mode",E),n?(S.querySelector(BP)??B)?.setAttribute("data-mode",E):S.textContent=E==="stop"?p:d},glyphStack:B}},ha=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype",s=e.provider?.type==="custom";if(!(o||r||s))return null;let l=e.iconName??"mic",d=e.iconSize,p=parseFloat(d??"")||$n,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,h=v("div","persona-send-button-wrapper"),g=$("button",{className:Vt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",fo,!d&&$o),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),C=Ie(l,p,m||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",h.appendChild(g);let S=e.tooltipText??"Start voice recognition",P=e.showTooltip??!1;return Mn({anchor:g,trigger:h,text:()=>g.getAttribute("aria-label")??S,enabled:P}),{button:g,wrapper:h}},Wp=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??Hr).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=e.buttonIconName??"paperclip",s=v("div","persona-send-button-wrapper"),a=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${fo} ${$o}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=Ie(r,$n,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let d=e.buttonTooltipText??"Attach file";return Mn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},Bp=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let a=v("a");a.href=e.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Op=()=>$("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});ya();Ye();Yt();var DP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',_P=["--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"],Mg="data-persona-menu-focus",NP=new Set(["ArrowDown","ArrowUp","Home","End"]);function bx(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(DP)??t}var FP=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function vx(t){let e=t.label,n=!1,o=v("div","persona-send-button-wrapper"),r=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${fo} ${$o}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=$("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let D=t.getButtonSize?.()??"";r.style.width=D,r.style.height=D,r.style.minWidth=D,r.style.minHeight=D,r.style.lineHeight="1",r.replaceChildren();let G=Ie("plus",$n,"currentColor",1.5);G?r.appendChild(G):r.textContent="+"},l=()=>{r.setAttribute("aria-label",e),r.setAttribute("title",e),s.setAttribute("aria-label",e)};l(),a();let d=[],p=-1,u=!1,m=()=>{let G=s.getRootNode().activeElement;return G instanceof HTMLElement?G:null},h=()=>{let D=m();for(let G of d){let z=!!D&&bx(G)===D;G.toggleAttribute(Mg,z&&u)}},g=()=>d.filter(D=>D.isConnected||s.contains(D)).map(bx).filter(D=>!FP(D)),b=(D,G)=>{D.forEach((z,K)=>{z.setAttribute("tabindex",K===G?"0":"-1")})},C=D=>{let G=g();if(G.length===0)return;let z=(D%G.length+G.length)%G.length;p=z,b(G,z),G[z].focus(),h()},S=()=>o.ownerDocument??document,P=null,M=null,B=null,A=()=>{P&&(S().removeEventListener("focusin",P,!0),P=null)},O=()=>{M&&(s.removeEventListener("focusin",M),M=null),B&&(s.removeEventListener("pointerdown",B,!0),B=null)},E=null,W=()=>(E||(E=gs({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),E),R=()=>E?.isOpen===!0,V=(D=!1)=>{if(R()){E?.close(),r.setAttribute("aria-expanded","false"),A(),O(),p=-1,u=!1;for(let G of d)G.removeAttribute(Mg);D&&r.focus()}},H=(D=0,G=!1)=>{if(n||R())return;u=G,Ip(r,s,_P),W().open(),r.setAttribute("aria-expanded","true");let z=g();b(z,-1),C(D<0?z.length-1:D),P=K=>{let Y=typeof K.composedPath=="function"?K.composedPath():[];Y.includes(s)||Y.includes(o)||V()},S().addEventListener("focusin",P,!0),M=()=>h(),s.addEventListener("focusin",M),B=()=>{u=!1},s.addEventListener("pointerdown",B,!0)},w=D=>{D.preventDefault(),D.stopPropagation(),R()?V(!0):H(0)},T=D=>{if(D.key==="ArrowDown"||D.key==="Enter"||D.key===" "){D.preventDefault(),u=!0,R()?C(0):H(0,!0);return}D.key==="ArrowUp"&&(D.preventDefault(),u=!0,R()?C(-1):H(-1,!0))},I=D=>{switch(NP.has(D.key)&&(u=!0),D.key){case"ArrowDown":D.preventDefault(),C(p+1);return;case"ArrowUp":D.preventDefault(),C(p-1);return;case"Home":D.preventDefault(),C(0);return;case"End":D.preventDefault(),C(g().length-1);return;case"Escape":D.preventDefault(),D.stopPropagation(),V(!0);return;case"Tab":V(!0);return;default:}};return r.addEventListener("click",w),r.addEventListener("keydown",T),s.addEventListener("keydown",I),{trigger:o,triggerButton:r,panel:s,setItems:D=>{for(let z of d)D.includes(z)||z.removeAttribute(Mg);if(d=[...D],!R())return;let G=g();b(G,Math.min(p,G.length-1)),h()},isOpen:R,open:()=>H(0),close:V,setLabel:D=>{D!==e&&(e=D,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),O(),r.removeEventListener("click",w),r.removeEventListener("keydown",T),s.removeEventListener("keydown",I),E?.destroy(),E=null,o.remove(),s.remove(),d=[]}}}var lr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Cx="data-persona-composer-action",Tg="data-persona-composer-disable-when-streaming",VP="core:overflow",$P=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function zP(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=v("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function Eg(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-r)}var wx=(t,e)=>{!t||typeof console>"u"||console.warn(e)},UP=(t,e)=>e.includes(":")?e:`${t}:${e}`;function qP(t){let{debug:e}=t,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){wx(e,`[Persona] composer action "${l.id}" is already contributed by ${xx(d)}; the ${xx(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of t.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,d,p)=>{let u=p?UP(p,l.id):l.id,m=l.order??lr.custom;l.placement==="end"&&m>=lr.send&&(wx(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${lr.send-1}.`),m=lr.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:d,pluginId:p,action:l})};for(let l of t.configActions??[])a(l,"config");for(let l of t.plugins){if(!l.contributeComposerActions)continue;let d;try{d=l.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of d??[])a(p,"plugin",l.id)}return n.sort((l,d)=>l.order===d.order?l.sequence-d.sequence:l.order-d.order)}var xx=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Sx=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,jP=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function KP(t,e){if(!t||t==="always")return!0;let n=jP(e);return t==="when-text"?n:!n}var hs=t=>t.kind==="custom",kg=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,GP=t=>{let e=kg(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},YP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function QP(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(YP)||o.childNodes.forEach(n)};return n(t),e.trim()}var XP=t=>QP(t).length===0;function Ax(t){let e=new Map,n=[],o=!1,r=()=>t.getButtonSize?.(),s=(w,T)=>{let I=w.button;if(!I)return;I.setAttribute("role","menuitem"),I.setAttribute("tabindex","-1"),I.className="persona-composer-overflow-menu__item";for(let z of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])I.style[z]="";I.style.lineHeight="1",T.tooltipText?I.setAttribute("title",T.tooltipText):I.removeAttribute("title"),I.replaceChildren();let D=v("span","persona-composer-overflow-menu__icon");if(T.iconName){let z=Ie(T.iconName,16,"currentColor",1.5);z&&D.appendChild(z)}let G=v("span","persona-composer-overflow-menu__label");G.textContent=T.shortLabel??T.label,I.append(D,G)},a=(w,T)=>{let I=w.button;if(!I)return;if(I.setAttribute("aria-label",T.label),T.pressed===void 0?I.removeAttribute("aria-pressed"):I.setAttribute("aria-pressed",T.pressed?"true":"false"),I.toggleAttribute(Tg,T.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,s(w,T);return}I.removeAttribute("role"),I.removeAttribute("tabindex"),I.removeAttribute("title");let D=r(),G=!!T.shortLabel;if(I.className=Vt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",fo,$o,G&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),I.style.width=D&&!G?D:"",I.style.height=D??"",I.style.minWidth=D&&!G?D:"",I.style.minHeight=D??"",I.style.fontSize=G?"":"18px",I.style.lineHeight="1",I.style.color=T.iconColor??"",I.style.backgroundColor=T.backgroundColor??"",I.replaceChildren(),T.iconName){let z=Ie(T.iconName,$n,"currentColor",1.5);z&&I.appendChild(z)}if(G){let z=v("span","persona-composer-action-button__label");z.textContent=T.shortLabel,I.appendChild(z)}else I.firstChild||(I.textContent=T.label);w.tooltip?.destroy(),w.tooltip=Mn({anchor:I,trigger:w.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(w,T)=>{let I=w.action,D=$("button",{attrs:{type:"button"}}),G=D;if(T==="bar"){let Y=v("div","persona-send-button-wrapper");Y.appendChild(D),G=Y}G.setAttribute(Cx,w.id);let z={resolved:w,element:G,button:D,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},K=Y=>{if(Y.preventDefault(),Y.stopPropagation(),z.busy||D.disabled)return;let re=z.resolved.action;z.mode==="menu"&&g?.close(!0);let oe;try{oe=re.onSelect(t.actionContext,Y)}catch(se){t.reportError(se,{actionId:z.resolved.id});return}!oe||typeof oe.then!="function"||(z.busy=!0,D.setAttribute("aria-busy","true"),oe.catch(se=>{t.reportError(se,{actionId:z.resolved.id})}).finally(()=>{z.busy=!1,D.removeAttribute("aria-busy")}))};return D.addEventListener("click",K),z.detach=()=>D.removeEventListener("click",K),a(z,I),z},d=w=>{let T=w.action,I;try{I=T.render({...t.actionContext,id:w.id,action:T})}catch(D){return t.reportError(D,{actionId:w.id}),null}return I?.element?(I.element.setAttribute(Cx,w.id),I.element.toggleAttribute(Tg,T.disableWhenStreaming===!0),{resolved:w,element:I.element,owned:!0,managed:!0,destroy:I.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,T)=>{if(w.builtIn){let D=w.builtIn.element;return D?{resolved:w,element:D,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let I=w.action;return I?hs(I)?d(w):l(w,T):null},u=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(T){t.reportError(T,{actionId:w.resolved.id})}w.element.remove()}},m=(w,T)=>{for(let I=0;I<T.length;I++){let D=T[I];if(!D.managed)continue;let G=null;for(let z=I+1;z<T.length;z++){let K=T[z];if(!K.managed&&K.element.parentElement===w){G=K.element;break}}G?(D.element.parentElement!==w||D.element.nextSibling!==G)&&w.insertBefore(D.element,G):w.lastChild!==D.element&&w.appendChild(D.element)}},h=(w,T)=>{if(w.button){w.button.disabled=T;return}if(!w.owned)return;let I=w.element;I.toggleAttribute("data-disabled",T),I.setAttribute("aria-disabled",T?"true":"false");let D=I instanceof HTMLButtonElement||I instanceof HTMLSelectElement||I instanceof HTMLInputElement||I instanceof HTMLTextAreaElement?I:I.querySelector("button, select, input, textarea");D&&(D.disabled=T)},g=null,b=null,C=null,S=0,P=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},M=()=>(g?g.setLabel(t.getOverflowLabel?.()??"More actions"):g=vx({label:t.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),B=w=>{b!==w&&(C?.disconnect(),b=w,S=Eg(w),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(T=>{let D=T[T.length-1]?.contentRect?.width??Eg(w);D!==S&&(S=D,V())}),C.observe(w)))},A=(w,T)=>{let I=zP(w.collapseAutoActionsBelow,T);if(I===null)return!1;let D=S||Eg(T);return D>0&&D<I},O=(w,T,I)=>{if(!T)return"bar";if(w.resolved.builtIn){let G=$P(w.resolved.id);return G&&T.includeBuiltIns?.includes(G)?"menu":"bar"}let D=w.resolved.presentation;return D==="overflow"||D==="auto"&&I?"menu":"bar"},E=w=>{let T=w.menuSlot;if(!T)return;if(!XP(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let I=GP(w.element);if(!I){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=v("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==I&&(w.menuLabel.textContent=I),w.menuLabel.parentElement!==T&&T.appendChild(w.menuLabel)},W=(w,T)=>{if(w.mode===T)return w;let I=w.resolved.action;if(I&&!hs(I)){u(w),e.delete(w.resolved.id);let D=l(w.resolved,T);return e.set(w.resolved.id,D),D}if(T==="menu"){let D=$("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[bg]:""}});D.appendChild(w.element),ax(kg(w.element)),w.menuSlot=D;let G=z=>{let K=kg(w.element);if(K.disabled)return;let Y=z.target===K||K.contains(z.target);g?.close(!0),Y||K.click()};D.addEventListener("click",G,!0),w.detachMenuSlot=()=>D.removeEventListener("click",G,!0),w.managed=!0,E(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=T,w},R=(w,T)=>{let I=T.map(D=>D.menuSlot??D.element);for(I.forEach((D,G)=>{let z=w.children[G];z!==D&&(z?w.insertBefore(D,z):w.appendChild(D))});w.children.length>I.length;)w.lastElementChild?.remove()},V=()=>{if(o)return;let w=t.getBindings();if(!w)return;let T=t.getState(),I=T.phase==="streaming",D=P();D&&B(w.footer);let G=D?A(D,w.footer):!1,z={start:[],end:[]},K=[];for(let Y of n){let re=e.get(Y.id);if(!re)continue;let oe=Y.action,se=oe?Sx(oe.visible,T,!0)&&KP(oe.visibility,T):!0;if(re.visible!==se&&(re.visible=se,!se&&re.managed&&(re.menuSlot??re.element).remove()),!!se){if(re=W(re,O(re,D,G)),oe){let ce=Sx(oe.disabled,T,!1)||oe.disableWhenStreaming===!0&&I;h(re,ce),!hs(oe)&&oe.pressed!==void 0&&re.button?.setAttribute("aria-pressed",oe.pressed?"true":"false")}re.mode==="menu"?(E(re),K.push(re)):z[Y.placement].push(re)}}if(K.length>0){let Y=M();R(Y.panel,K),Y.setItems(K.map(ce=>ce.menuSlot??ce.element)),Y.applyButtonSize();let re=Number.isFinite(D?.order)?D?.order:lr.overflow,oe=z.start.findIndex(ce=>ce.resolved.order>re),se={resolved:{id:VP,placement:"start",presentation:"bar",order:re,sequence:-1,source:"core"},element:Y.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};z.start.splice(oe<0?z.start.length:oe,0,se)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));m(w.actionsStart,z.start),m(w.actionsEnd,z.end)};return{resolve:()=>{if(o)return;let w=qP(t.collect()),T=new Set(w.map(I=>I.id));for(let[I,D]of e)T.has(I)||(u(D),e.delete(I));for(let I of w){let D=e.get(I.id);if(!D){let Y=p(I,"bar");Y&&e.set(I.id,Y);continue}let G=D.resolved.action,z=I.action;if(!!G!=!!z||G&&z&&hs(G)!==hs(z)||G&&z&&hs(G)&&hs(z)&&G.render!==z.render){u(D),e.delete(I.id);let Y=p(I,D.mode);Y&&e.set(I.id,Y);continue}D.resolved=I,I.builtIn?(D.managed=I.builtIn.managed===!0||D.mode==="menu",I.builtIn.element&&D.mode==="bar"&&(D.element=I.builtIn.element)):z&&!hs(z)?a(D,z):z&&D.element.toggleAttribute(Tg,z.disableWhenStreaming===!0)}n=w,V()},sync:V,getResolved:()=>n,getOverflowMenu:()=>g,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,b=null;for(let w of e.values())u(w);e.clear(),g?.destroy(),g=null,n=[]}}}}ya();Ye();Yt();var JP="core:model",ZP=700,Mx=16,eI=["--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"],Tx=()=>{let t=$("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=$("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Ex(t){let e=t.label??"Model",n=t.presentation??"native",o=null,r=d=>{let p=t.getSelectedModelId();return d.find(u=>u.id===p)??d[0]},s=()=>{let d=$("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=t.getModels(),S=C.map(P=>`${P.id}:${P.label}`).join("|");S!==p&&(p=S,d.replaceChildren(...C.map(P=>{let M=$("option",{attrs:{value:P.id}});return M.textContent=P.label,M}))),d.value=r(C)?.id??""};u(),o=u;let m=()=>{d.value&&t.onSelect(d.value)};d.addEventListener("change",m);let h=C=>C.stopPropagation();d.addEventListener("click",h);let{wrapper:g,chevron:b}=Tx();return g.append(d,b),{element:g,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",h)}}},a=()=>{let d=$("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"}}),p=v("span","persona-composer-model-picker-label"),u=v("span","persona-composer-model-picker-suffix");d.append(p,u);let m=$("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),h=new Map,g="",b=null,C=()=>b?.isOpen===!0,S=(T=!1)=>{C()&&(b?.close(),d.setAttribute("aria-expanded","false"),T&&d.focus())},P=T=>{let I=[...h.values()];if(I.length===0)return;let D=(T%I.length+I.length)%I.length;I[D].focus()},M=T=>{if(C())return;b||(b=gs({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Ip(d,m,eI),b.open(),d.setAttribute("aria-expanded","true");let D=[...h.keys()].indexOf(r(t.getModels())?.id??"");P(T??(D>=0?D:0))},B=T=>{S(!0),t.onSelect(T)},A=T=>{T.preventDefault(),T.stopPropagation();let I=T.currentTarget.getAttribute("data-persona-model-option");I&&B(I)},O=T=>{let I=$("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let Y=Ie(T.icon,Mx,"currentColor",1.5);if(Y){let re=v("span","persona-composer-model-option-icon");re.appendChild(Y),I.appendChild(re)}}let D=v("span","persona-composer-model-option-body"),G=v("span","persona-composer-model-option-label");if(G.textContent=T.label,D.appendChild(G),T.description){let Y=v("span","persona-composer-model-option-description");Y.textContent=T.description,D.appendChild(Y)}I.appendChild(D);let z=v("span","persona-composer-model-option-check");z.setAttribute("aria-hidden","true");let K=Ie("check",Mx,"currentColor",2);return K&&z.appendChild(K),I.appendChild(z),I.addEventListener("click",A),I},E=()=>{let T=t.getModels(),I=T.map(z=>`${z.id}:${z.label}:${z.icon??""}:${z.description??""}`).join("|");if(I!==g){g=I;for(let z of h.values())z.removeEventListener("click",A);h.clear(),m.replaceChildren(...T.map(z=>{let K=O(z);return h.set(z.id,K),K}))}let D=r(T);for(let[z,K]of h)K.setAttribute("aria-selected",String(z===D?.id));p.textContent=D?.label??"";let G=t.getSuffix?.()??"";u.textContent=G,d.setAttribute("aria-label",[e,[D?.label,G].filter(Boolean).join(" ")].filter(Boolean).join(": "))};E(),o=E;let W=T=>{T.preventDefault(),T.stopPropagation(),C()?S(!0):M()},R=T=>{if(T.key==="ArrowDown"){T.preventDefault(),C()?P(0):M(0);return}T.key==="ArrowUp"&&(T.preventDefault(),C()?P(-1):M(-1))},V=T=>{let I=[...h.values()],D=I.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),P(D+1);return;case"ArrowUp":T.preventDefault(),P(D-1);return;case"Home":T.preventDefault(),P(0);return;case"End":T.preventDefault(),P(I.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};d.addEventListener("click",W),d.addEventListener("keydown",R),m.addEventListener("keydown",V);let{wrapper:H,chevron:w}=Tx();return H.append(d,w),{element:H,destroy:()=>{o===E&&(o=null),d.removeEventListener("click",W),d.removeEventListener("keydown",R),m.removeEventListener("keydown",V);for(let T of h.values())T.removeEventListener("click",A);h.clear(),b?.destroy(),b=null,m.remove()}}};return{action:{id:JP,kind:"custom",placement:"end",order:ZP,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}Ye();Yt();Fp();var tI=":scope > [data-persona-composer-mode]";function kx(t){let e=t.row,n="",o=!1,r=new Set(t.initialIds??[]),s=p=>{let u=$("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let b=v("span","persona-mention-chip-icon"),C=Ie(p.iconName,12,"currentColor",1.5);C&&b.appendChild(C),u.appendChild(b)}let m=v("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let h=$("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),g=Ie("x",12,"currentColor",2);return g?h.appendChild(g):h.textContent="\xD7",h.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),t.onRemove(p.id)}),u.appendChild(h),u},a=()=>Array.from(e.querySelectorAll(tI)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),ba(e)},m=e.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!h||h==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:e,render:(p,u)=>{if(o)return;let m=u.filter(C=>p.includes(C.id)),h=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(h===n)return;n=h;let g=new Map;for(let C of a()){let S=C.getAttribute("data-persona-composer-mode");S&&m.some(M=>M.id===S)&&!C.hasAttribute("data-persona-chip-exit")?g.set(S,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let b=e.firstChild;for(let C of m){let S=g.get(C.id);S||(S=s(C),r.has(C.id)||(S.setAttribute("data-persona-chip-enter",""),S.addEventListener("animationend",()=>S?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),S!==b&&e.insertBefore(S,b),b=S.nextSibling}ba(e)},destroy:()=>{o=!0,d(),ba(e)}}}Ye();Yt();var Lx=t=>`core:mode:${t}`;var Ig=t=>Math.min(300+t,499),Px=t=>`core:mode-group:${t}`;function Vp(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function nI(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ix(t,e){return t?.length?t.filter(n=>!Vp(n.groupId,e)&&!nI(n.groupId,e)):[]}var oI=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Hx(t,e,n,o){let r=n.find(l=>l.id===e);if(!r)return[...t];let s=t.includes(e),a=new Set(t);if(s)a.delete(e);else{if(oI(r,o)==="single"){let l=n.filter(d=>d.groupId===r.groupId).map(d=>d.id);a=new Set([...a].filter(d=>!l.includes(d)))}a.add(e)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function $p(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Rx(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Wx(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var rI=16;function Bx(t){let e=null;return{action:{id:Px(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=$("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},l=p=>{let u=$("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=Ie(p.iconName,rI,"currentColor",1.5);h&&u.appendChild(h)}let m=v("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(g=>`${g.id}:${g.shortLabel??g.label}:${g.iconName??""}`).join("|");if(m!==s){s=m;for(let b of r.values())b.removeEventListener("click",a);r.clear();let g=u.map(b=>{let C=l(b);return r.set(b.id,C),C});o.replaceChildren(...g)}let h=t.getActiveIds();for(let[g,b]of r)b.setAttribute("aria-pressed",String(h.includes(g)))};return d(),e=d,{element:o,destroy:()=>{e===d&&(e=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>e?.()}}Fp();Ye();Yt();function Ox(t){let e=$("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,r=s=>{let a=v("span","persona-composer-quote-bar"),l=v("div","persona-composer-quote-content");if(s.sourceLabel){let m=v("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=$("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=fp(s.text),l.appendChild(d);let p=$("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=Ie("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(a,l,p)};return{element:e,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){e.replaceChildren(),e.style.display="none";return}r(s),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}Ye();Yt();function Dx(t){let e=$("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,r=(a,l,d,p)=>{let u=$("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=Ie(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),u},s=a=>{let l=fp(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:e,render:a=>{if(o||a===n)return;if(n=a,!a){e.replaceChildren(),e.style.display="none";return}let l=v("span","persona-composer-pending-badge");l.textContent=t.label??"Sends next";let d=$("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=s(a),e.replaceChildren(l,d,r("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),r("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}Ye();function _x(t){let e=$("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=$("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=v("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=$("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&t.onSave(l)};return r.append(s(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),s(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),t.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),e.append(n,r),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Nx(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function Fx(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(d=>n.has(d.sourceId)),r=o.length===(t.mentionRefs?.length??0)&&o.length>0,s=new Set(e.modes.map(d=>d.id)),a=(t.activeModeIds??[]).filter(d=>s.has(d)),l=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...r?{mentionRefs:o}:{},...r&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...t.quote?.text?{quote:t.quote}:{}}}function Vx(t){let e=t.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(r(),t.write())},cancel:r,destroy:()=>{o=!0,r()}}}function $x(t){return t.wrapped||t.text.includes(`
1156
+ `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission||t.dictationActive)}function zx(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function Ux(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let a=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-a>s*1.5}zp();function Hg(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function Kx(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var sI=t=>typeof t?.then=="function";function jx(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function Gx(t,e,n){let o;try{o=t(Hg(e),{signal:n})}catch(r){return{status:"error",error:r}}return sI(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:jx(e,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):jx(e,o)}Ye();Up();Rg();Ye();Yt();function Jx(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",r=e.buttonTooltipText??"Add context",s=v("div","persona-send-button-wrapper"),a=$("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${fo} ${$o}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=Ie(o,$n,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),Mn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}oo();var{setLoader:oN,load:uI}=$t({fallbackImport:()=>Promise.resolve().then(()=>(hS(),gS))});var Dg=uI;Yt();oo();var{setLoader:gN,load:xI}=$t({fallbackImport:()=>Promise.resolve().then(()=>(kS(),ES)),resetOnSetLoader:!0});var LS=xI;Ye();Yt();function Jl(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=$("span",{className:Vt("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=Ie(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild($("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function PS(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=qp(e).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(O=>typeof O.matchCommand=="function")),r=A=>o.some(O=>O.trigger?O.position==="line-start"?A.split(`
1157
1157
  `).some(W=>W.startsWith(O.trigger)):(O.position==="anywhere"?A:A.split(`
1158
- `)[0]).startsWith(O.trigger):!1),s=(A,O)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:O}))}catch{}},a=!t.chipRow,l=t.chipRow??$("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=t.textarea,m=null,h=null,g=null,b=null,C=()=>{if(d)return Promise.resolve(d);if(p)return p;let A=Dg().then(O=>(O.setMentionIconRenderer(Ie),d=O.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:l,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:B,emit:s}),d)).catch(O=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",O),p===A&&(p=null),null));return p=A,A},S=()=>{LS().then(A=>{let O=A.mountInlineComposer({textarea:t.textarea,renderToken:W=>Jl(W,{render:e.renderMentionToken}),onMentionRemoved:W=>d?.untrackMention(W)});m=O.input,h=O.destroy;let E=u;E.replaceWith(O.element),u=O.element,b={next:O.element,prev:E},g?.(O.element,E),d?d.rebindComposer(O.input):p&&p.then(W=>W?.rebindComposer(O.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&S();let P=[],M=new Map;for(let A of n){if(!A.showButton)continue;let O=Jx({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(E=>E?.openMenu(A.trigger))}});P.push(O),M.set(A.trigger,O.button)}let B=(A,O,E)=>{let W=M.get(O);W&&(W.setAttribute("aria-expanded",A?"true":"false"),A?W.setAttribute("aria-controls",E):W.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(d){d.handleInput();return}if(!Qx(A))return;let O=u,E=O.selectionStart??0;Kl(O.value,E,n)&&C().then(W=>W?.handleInput())},handleKeydown:A=>{if(d?.isMenuOpen())return d.handleKeydown(A);if(A.key==="Backspace"&&d?.hasMentions()&&!b){let O=u,E=O.selectionStart===0&&O.selectionEnd===0;if((O.value.length===0||E)&&d.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(d??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>d?.clear(),prefetch:()=>{Dg().catch(()=>{})},onComposerSwap:A=>{g=A,b&&A(b.next,b.prev)},destroy:()=>{d?.destroy(),h?.();for(let A of P)A.wrapper.remove();a&&l.remove()}}}var ou="16px",ru="transparent",SI=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),AI={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:SI,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"}},MI={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"}},TI={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:Rr,maxWidth:px,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ou,canvasBackground:ru},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"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function zn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?zn(t,o):o}function HS(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=zn(t,a);d!==void 0&&(e[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function EI(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function RS(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=RS(s,r):n[o]=r}return n}function kI(t,e){return e?RS(t,e):t}function va(t,e={}){let n={palette:AI,semantic:MI,components:TI},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:kI(n.components,t?.components)};if(e.validate!==!1){let r=EI(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}var jg=t=>t.trim()==="0"?"0px":t,IS="--persona-",LI=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let a=e.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=e.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(d=>{let p=d.endsWith("%"),u=parseFloat(p?d.slice(0,-1):d);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},PI=.179,Tn=(t,e)=>{for(let[n,...o]of e){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):t[IS+s],r!==void 0)break;r!==void 0&&(t[IS+n]=r)}};function WS(t){let e=HS(t),n={};for(let[N,ye]of Object.entries(e)){let ke=N.replace(/\./g,"-");n[`--persona-${ke}`]=ye.value}Tn(n,[["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 o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Tn(n,[["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"]]),Tn(n,[["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"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Tn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ou,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ru,Tn(n,[["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"]]),Tn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],Tn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],Tn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[N,ye]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ke=n[`--persona-components-history-overlay-${N}`];ke&&(n[`--persona-history-overlay-${ye}`]=ke)}for(let[N,ye]of[["background","bg"],["borderRadius","radius"]]){let ke=n[`--persona-components-history-menu-${N}`];ke&&(n[`--persona-history-menu-${ye}`]=ke)}let m=t.components?.history?.motion;if(m){let N=nt=>{if(nt===void 0)return;let Ee=String(nt).trim();return/^\d+(\.\d+)?$/.test(Ee)?`${Ee}ms`:Ee},ye=N(m.enterDurationMs);ye!==void 0&&(n["--persona-history-enter-ms"]=ye);let ke=N(m.exitDurationMs);ke!==void 0&&(n["--persona-history-exit-ms"]=ke),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let N of["scrim","shadow"]){let ye=n[`--persona-components-history-confirm-${N}`];ye&&(n[`--persona-history-confirm-${N}`]=ye)}for(let[N,ye]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ke=n[`--persona-components-tooltip-${N}`];ke&&(n[`--persona-tooltip-${ye}`]=ke)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[N,ye]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ke=n[`--persona-components-messageActions-${N}`];ke&&(n[`--persona-message-action-${ye}`]=ke)}Tn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let g=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],C=(!g||g==="transparent"||g==="none")&&(!b||b==="none"),S=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&S==="1.5rem"?"1.5rem 0":S,Tn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Tn(n,[["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 P=n["--persona-components-markdown-heading-h1-fontSize"];P&&(n["--persona-md-h1-size"]=P);let M=n["--persona-components-markdown-heading-h1-fontWeight"];M&&(n["--persona-md-h1-weight"]=M);let B=n["--persona-components-markdown-heading-h2-fontSize"];B&&(n["--persona-md-h2-size"]=B);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),Tn(n,[["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"]]),Tn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Tn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Tn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Tn(n,[["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"]]),n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],Tn(n,[["message-border","components-message-border","border"]]),Tn(n,[["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 E=t.components,W=E?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let R=E?.labelButton;R&&(R.background&&(n["--persona-label-btn-bg"]=R.background),R.border&&(n["--persona-label-btn-border"]=R.border),R.color&&(n["--persona-label-btn-color"]=R.color),R.padding&&(n["--persona-label-btn-padding"]=R.padding),R.borderRadius&&(n["--persona-label-btn-radius"]=R.borderRadius),R.hoverBackground&&(n["--persona-label-btn-hover-bg"]=R.hoverBackground),R.fontSize&&(n["--persona-label-btn-font-size"]=R.fontSize),R.gap&&(n["--persona-label-btn-gap"]=R.gap));let V=E?.toggleGroup;V&&(V.gap&&(n["--persona-toggle-group-gap"]=V.gap),V.borderRadius&&(n["--persona-toggle-group-radius"]=V.borderRadius));let H=E?.artifact;if(H?.toolbar){let N=H.toolbar;N.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=jg(N.toggleGroupGap)),N.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=jg(N.toggleGroupPadding)),N.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=zn(t,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=jg(N.copyBorderRadius)),N.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(H?.tab){let N=H.tab;N.background&&(n["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(n["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(n["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(n["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(n["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(n["--persona-artifact-tab-list-padding"]=N.listPadding)}if(H?.pane){let N=H.pane;if(N.toolbarBackground){let ye=zn(t,N.toolbarBackground)??N.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ye}}if(H?.card){let N=H.card;N.background&&(n["--persona-artifact-card-bg"]=N.background),N.border&&(n["--persona-artifact-card-border"]=N.border),N.borderRadius&&(n["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(H?.inline){let N=H.inline;N.background&&(n["--persona-artifact-inline-bg"]=zn(t,N.background)??N.background),N.border&&(n["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(n["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=zn(t,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=zn(t,N.chromeBorder)??N.chromeBorder),N.titleColor&&(n["--persona-artifact-inline-title-color"]=zn(t,N.titleColor)??N.titleColor),N.mutedColor&&(n["--persona-artifact-inline-muted-color"]=zn(t,N.mutedColor)??N.mutedColor),N.frameHeight&&(n["--persona-artifact-inline-frame-height"]=N.frameHeight)}let w=E?.code;w&&(w.keywordColor&&(n["--persona-code-keyword-color"]=w.keywordColor),w.stringColor&&(n["--persona-code-string-color"]=w.stringColor),w.commentColor&&(n["--persona-code-comment-color"]=w.commentColor),w.numberColor&&(n["--persona-code-number-color"]=w.numberColor),w.tagColor&&(n["--persona-code-tag-color"]=w.tagColor),w.attrColor&&(n["--persona-code-attr-color"]=w.attrColor),w.propertyColor&&(n["--persona-code-property-color"]=w.propertyColor),w.lineNumberColor&&(n["--persona-code-line-number-color"]=w.lineNumberColor),w.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=w.gutterBorderColor),w.background&&(n["--persona-code-bg"]=zn(t,w.background)??w.background));let T=n["--persona-surface"],I=n["--persona-container"],D=n["--persona-palette-colors-gray-100"]??"#f3f4f6",G=n["--persona-palette-colors-gray-200"]??"#e5e7eb",z=n["--persona-palette-colors-gray-300"]??"#d1d5db",K=!I||I===T,Y=LI(T??n["--persona-background"]),re=K&&Y!==void 0&&Y<PI,oe=re?"rgba(255, 255, 255, 0.08)":D,se=re?"rgba(255, 255, 255, 0.12)":G,ce=re?"rgba(255, 255, 255, 0.16)":z,we=K?oe:I,ge=K?se:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??we,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ge,K&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??we,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??we,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??we,n}var II={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"}}},HI={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},BS=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Kg=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",RI=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Kg()},OS=t=>RI(t),WI=t=>va(t),BI=t=>{let e=ga(HI,t??{})??{};return va({...e,palette:{...e.palette,colors:{...II.colors,...e.palette?.colors}}},{validate:!1})},Ca=t=>{let e=OS(t),n=BS(t?.theme),o=BS(t?.darkTheme);return e==="dark"?BI(ga(n??{},o??{})):WI(n)},OI=t=>WS(t),Zl=(t,e)=>{let n=Ca(e),o=OI(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",OS(e))},su=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Kg())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Kg());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};var Fr=require("lucide");Yt();ro();Ye();var ys=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var iu="24px",Gg=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",ec=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},DS=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var _S=null;var Yg=()=>{if(_S!==null)return _S;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},DI="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",au=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},lu=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return au("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(au("unsupported",t),null):(n==="space"&&(o.key=" "),o)},_I=t=>DI.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),NS=(t,e)=>{let n=lu(t);if(!n)return"";let o=Yg(),r=_I(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},cu=t=>NS(t,!1),tc=t=>NS(t,!0),NI=(t,e)=>e.key?.toLowerCase()===t.key&&(Yg()?e.metaKey:e.ctrlKey)===t.mod&&!(Yg()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,FI=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},FS=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=s=>{if(s.isComposing||!e.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of e.values())if(NI(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&FI(a))){s.preventDefault();try{l.run(s)}catch(d){au(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=lu(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=e.get(l);return d?(au(`${d.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",tc(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var VS=require("idiomorph"),du=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;VS.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var $S=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Qg={index:-1,draft:""};function zS(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function US(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function qS(){return new Map}function jS(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function KS(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function GS(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}Jg();fs();ac();oo();var{setLoader:QN,load:pH}=$t({fallbackImport:()=>Promise.resolve().then(()=>(yA(),hA))});var bA=pH;fs();function rh(t,e=Hn){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var cc=0,bs=null;function sh(t=document){if(cc++,cc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;bs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,cc=Math.max(0,cc-1),cc===0&&bs)){let n=t.body,o=t.defaultView??window;n.style.overflow=bs.originalOverflow,n.style.position=bs.originalPosition,n.style.top=bs.originalTop,n.style.width=bs.originalWidth,o.scrollTo(0,bs.scrollY),bs=null}}}var dc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rn=t=>(t?.launcher?.mountMode??"floating")==="docked",pc=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",ko=t=>{let e=t?.launcher?.dock;return{side:e?.side??dc.side,width:e?.width??dc.width,animate:e?.animate??dc.animate,reveal:e?.reveal??dc.reveal,maxHeight:e?.maxHeight??dc.maxHeight}};Ye();Ye();var CA=require("lucide");Yt();ro();var ih=t=>t==="followUp"?"follow-up":t,ah=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},uH=t=>{switch(t){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'}},vA=new WeakSet,mH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,fH=t=>{mH()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},lh=t=>{var B,A,O;let{item:e,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:h,submitPrompt:g}=t,b=o==="followUp",C=e.behavior,S=()=>{if(u.isStreaming())return;let E={suggestion:{...e},surface:o,source:r,behavior:C},W=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:E,bubbles:!0,composed:!0,cancelable:!0}));if(b&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!W)return;for(let V of d)if(V.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let R=m();if(C==="fill"){R.value=e.prompt,R.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),R.focus();return}if(g){g(e.prompt);return}R.value="",u.sendMessage(e.prompt)},P=()=>{let E=v("button",`persona-suggestion persona-suggestion--${s}`);if(E.type="button",E.disabled=a,E.dataset.suggestionId=e.id,E.dataset.emphasis=e.emphasis,E.dataset.behavior=C,s==="chip"&&(p?.fontFamily&&(E.style.fontFamily=uH(p.fontFamily)),p?.fontWeight&&(E.style.fontWeight=p.fontWeight),p?.paddingX&&(E.style.paddingLeft=p.paddingX,E.style.paddingRight=p.paddingX),p?.paddingY&&(E.style.paddingTop=p.paddingY,E.style.paddingBottom=p.paddingY)),e.icon){let R=Ie(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);R&&(R.classList.add("persona-suggestion__icon"),e.iconColor&&(R.style.color=e.iconColor),E.appendChild(R))}let W=v("span","persona-suggestion__copy");if(W.appendChild($("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&W.appendChild($("span",{className:"persona-suggestion__description",text:e.description})),E.appendChild(W),s!=="chip"){let R=Qe(CA.ArrowRight,16,"currentColor",1.8);R&&(R.classList.add("persona-suggestion__arrow"),E.appendChild(R))}return E.addEventListener("click",S),E},M=null;for(let E of d)if(E.renderSuggestion&&(M=E.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:P,select:S}),M))break;return M??(M=P()),(B=M.dataset).suggestionId||(B.suggestionId=e.id),(A=M.dataset).behavior||(A.behavior=C),(O=M.dataset).emphasis||(O.emphasis=e.emphasis),M instanceof HTMLButtonElement||M.setAttribute("aria-disabled",a?"true":"false"),M},uc=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){s();return}let m=getComputedStyle(t).direction==="rtl",h=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),g=4,b=h<=g,C=h>=u-g,S=m?!C:!b,P=m?!b:!C;t.toggleAttribute("data-scroll-left",S),t.toggleAttribute("data-scroll-right",P)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,h,g,b,C)=>{t.replaceChildren(),e.length=0,n.length=0;let S=C?.source??"config",P=C?.surface??(S==="config"?"starter":"followUp"),M=P==="followUp",B=C?.variant??"chip",A=C?.behavior??"send",O=C?.overflow??"wrap",E=C?.config??{},W=C?.plugins??[],R=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,V=M?"followUps":"starters";!vA.has(E)&&E.debug===!0&&B!=="chip"&&E.suggestions?.[V]?.overflow!==void 0&&(vA.add(E),console.info(`[persona] suggestions.${V}.overflow applies to the "chip" variant only; the "${B}" variant manages its own stacking.`));let H=z=>z.map(ah).filter(K=>K!==null).map(K=>({...K,behavior:K.behavior??A})),w=H(u??[]);W.forEach(z=>{z.transformSuggestions&&(w=H(z.transformSuggestions({suggestions:w.map(K=>({...K})),surface:P,source:S,config:E})))});let T=R===void 0?w:w.slice(0,R);if(!T.length){t.hidden=!0,o=null,s();return}if(!M&&(g??m.getMessages()).some(K=>K.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=ih(P),t.dataset.variant=B,t.dataset.overflow=O;let I=document.createDocumentFragment(),D=m.isStreaming();T.forEach((z,K)=>{let Y=lh({item:z,index:K,surface:P,source:S,variant:B,streaming:D,config:E,plugins:W,chipsConfig:b,session:m,getTextarea:()=>h,eventTarget:t,submitPrompt:C?.submitPrompt});I.appendChild(Y),n.push(Y),[...Y instanceof HTMLButtonElement?[Y]:[],...Array.from(Y.querySelectorAll("button"))].forEach(oe=>{e.includes(oe)||(oe.disabled=D,e.push(oe))})}),t.appendChild(I),a(),l();let G=JSON.stringify({normalized:T,surface:P,variant:B,source:S});G!==o&&(o=G,fH(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(z=>({...z})),surface:P,source:S,variant:B},bubbles:!0,composed:!0})),M&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(z=>z.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"};fs();Ye();Yt();Ye();Yt();var gH="persona-header-control",hH="persona-header-control--glyph",yH="persona-header-control--sparse",bH=20,vH={x:[1.4,1.05]},wA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",CH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=vH[e]??[1,1.5],l=!o;t.classList.toggle(hH,l),t.classList.toggle(yH,l&&s!==1);let d=parseFloat(o??"")||bH,p=Ie(e,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(p)):r&&(t.textContent=r)},ai=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=wA,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:h,borderRadius:g,paddingX:b,paddingY:C,hidden:S,extraClassName:P,attrs:M}=t,B=v("div",a),A=!!(m||h),O=$("button",{className:Vt(gH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!g&&"persona-rounded-full",P),attrs:{type:"button","aria-label":e,...M},style:{width:l,height:l,minWidth:l,minHeight:l,display:S?"none":void 0,color:p||Un.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:g,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?yu(O,r,{iconSize:d,iconText:s}):s&&(O.textContent=s),B.appendChild(O),Mn({anchor:O,trigger:B,text:()=>O.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:O,wrapper:B}},xa=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=wA,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=ai({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},Sa=(t,e={})=>{let{wrapperClassName:n=CH,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=ai({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var Un={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)"},ch={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)"},wH={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)"},li=t=>{let{config:e,showClose:n=!0}=t,o=$("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:Un.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=e?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=$("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let O=parseFloat(s)||24,E=Ie(d,O*.6,"currentColor",1);E?p.replaceChildren(E):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let O=v("img");O.src=e.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=s,O.style.width=s,p.replaceChildren(O)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=$("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Un.titleColor,...ch}}),h=$("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Un.subtitleColor,...wH}});u.append(m,h),l?o.append(u):o.append(p,u);let g=r.clearChat??{},b=g.enabled??!0,C=g.placement??"inline",S=null,P=null;if(b){let E=Sa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=E.button,P=E.wrapper,C==="top-right"&&(P.style.right="48px"),C==="inline"&&o.appendChild(P)}let M=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:B,wrapper:A}=xa(e,{showClose:n,wrapperClassName:M});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:h,closeButton:B,closeButtonWrapper:A,clearChatButton:S,clearChatButtonWrapper:P}},mc=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};Ye();dh();di();var xH=t=>{let e=li({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function SH(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=ai({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?cu(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=tc(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=fc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(s)}}var AH=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Un.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,u;if(d){let A=SA({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:O=>{let E=R=>{R===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},W=d.onSelect(O);W instanceof Promise?W.then(E,()=>{}):E(W)},hover:d.hover,className:""});p=A.element,p.style.color=Un.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Un.titleColor,Object.assign(u.style,ch),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=r.onTitleClick;p.addEventListener("click",E=>{E.target.closest("button")||O()}),p.addEventListener("keydown",E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),O())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=A.background??"",p.style.borderColor=A.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:g}=xa(e,{showClose:n,wrapperClassName:m});o&&h.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");d||SH(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},S=null,P=null;if(C.enabled??!0){let A=C.placement??"inline",O=Sa(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});S=O.button,P=O.wrapper,A==="top-right"?P.style.right="48px":b.appendChild(P)}b.appendChild(g),l.appendChild(b);let M=v("div");M.style.display="none";let B=v("span");return B.style.display="none",{header:l,iconHolder:M,headerTitle:u,headerSubtitle:B,closeButton:h,closeButtonWrapper:g,clearChatButton:S,clearChatButtonWrapper:P}},AA={default:xH,minimal:AH},MH=t=>AA[t]??AA.default,vu=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let d=v("span"),p=v("span"),u=v("button");u.style.display="none";let m=v("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=MH(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Ye();var gc=t=>{let{config:e}=t,n=$("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Op(),r=$("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:s,attachAutoResize:a}=Hp(e);a();let l=Rp(e),d=ha(e),p=Wp(e),u=Bp(e),m=$("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let h=$("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=$("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=$("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&g.append(p.wrapper),d&&b.append(d.wrapper),b.append(l.wrapper),h.append(g,b),r.append(h),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:h,leftActions:g,rightActions:b,setSendButtonMode:l.setMode}};Ye();var Cu=require("lucide");ro();var MA=()=>{let t=$("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=Qe(Cu.MessageSquare,16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Qe(Cu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},wu=t=>{let{config:e}=t,n=$("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Op(),r=Bp(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Hp(e,{defaultMaxLines:5});a();let l=Rp(e),d=ha(e),p=Wp(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=$("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=$("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let h=$("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&h.append(d.wrapper),h.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,h);let g=$("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(g),p&&g.append(p.previewsContainer),n.append(o,u,r);let b=u;return{footer:n,suggestions:o,composerForm:u,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:b,leftActions:m,rightActions:h,setSendButtonMode:l.setMode}};Ye();Yt();Ye();di();Yt();ac();var TH=t=>{switch(t){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}},EH=(t,e)=>{if(!t)return null;let n=TH(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},kH=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},LH=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},uh=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},mh=320,PA=320,PH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),IH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),HH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),RH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),WH=t=>{if(!t||t.length===0)return null;let e=$("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=$("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=Ie(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild($("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},BH=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Jl(o.ref,{readonly:!0,render:e}))}return n},TA="\uE000",EA="\uE001",OH=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=h=>`${TA}${r}:${h}${EA}`,a=e.map((h,g)=>h.kind==="text"?h.text:s(g)).join(""),l=n(a);if(!e.every((h,g)=>h.kind==="text"||l.includes(s(g)))){t.replaceChildren(BH(e,o));return}t.innerHTML=l;let p=new RegExp(`${TA}${r}:(\\d+)${EA}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let h=u.nextNode();h;h=u.nextNode())m.push(h);for(let h of m){let g=h;for(let b=p.exec(g.data);b;b=p.exec(g.data)){let C=e[Number(b[1])],S=g.splitText(b.index);S.data=S.data.slice(b[0].length),C?.kind==="mention"&&S.parentNode?.insertBefore(Jl(C.ref,{readonly:!0,render:o}),S),g=S}}},DH=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,d)=>{let p=v("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${mh}px`,p.style.maxHeight=`${PA}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),LH(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},_H=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!uh(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mh}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},NH=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!uh(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mh}px`,r.style.maxHeight=`${PA}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},FH=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!uh(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.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",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},hc=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";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="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},VH=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:hc};if(e){let r=e(o);if(r!==null)return r}return hc()},$H=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},kA=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},yc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.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 n},LA={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"}},zH=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=LA[n??"bubble"]??LA.bubble;o.padding&&(t.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},xu="custom:",UH=t=>`${xu}${t}`,IA=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),qH=(t,e,n,o)=>{let r=e.showCopy??!0,s=e.showUpvote??!0,a=e.showDownvote??!0,l=e.showReadAloud??!1,d=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=IA(e,t.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let B=v("div");return B.style.display="none",B.id=`actions-${t.id}`,B.setAttribute("data-actions-for",t.id),B}let h=e.visibility??"hover",g=e.align??"right",b=e.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[g],S={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[b],P=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${S} ${h==="hover"?"persona-message-actions-hover":""}`);P.id=`actions-${t.id}`,P.setAttribute("data-actions-for",t.id);let M=(B,A,O)=>{let E=gn({icon:B,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return E.setAttribute("data-action",O),E};r&&P.appendChild(M("copy","Copy message","copy")),l&&P.appendChild(M("volume-2","Read aloud","read-aloud")),s&&P.appendChild(M("thumbs-up","Upvote","upvote")),a&&P.appendChild(M("thumbs-down","Downvote","downvote")),d&&P.appendChild(M("refresh-cw","Regenerate response","regenerate")),p&&P.appendChild(M("pencil","Edit message","edit")),u&&P.appendChild(M("quote","Quote message","quote"));for(let B of m)P.appendChild(M(B.iconName??"ellipsis",B.label,UH(B.id)));return P},fh=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,h=d?.position??"left",g=p?.position??"below",b=yc(t.role,l),C=v("div",b.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let S=s?.widgetConfig?.theme?.components?.message;zH(C,t.role,l,t.role==="user"?S?.user:S?.assistant),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=PH(t),M=t.content?.trim()??"",A=P.length>0&&M===da,O=fu(s?.widgetConfig?.features?.streamAnimation),E=s?.widgetConfig?.features?.streamAnimation?.plugins,W=t.role==="assistant"&&O.type!=="none"?oc(O.type,E):null,R=t.role==="assistant"&&W?.isAnimating?.(t)===!0,V=t.role==="assistant"&&W!==null&&(!!t.streaming||R);V&&W?.bubbleClass&&C.classList.add(W.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),t.streaming&&H.classList.add("persona-content-streaming"),V&&W&&(W.containerClass&&H.classList.add(W.containerClass),H.style.setProperty("--persona-stream-step",`${O.speed}ms`),H.style.setProperty("--persona-stream-duration",`${O.duration}ms`));let w=V?gu(t.content??"",O.buffer,W,t,!!t.streaming):t.content??"",T=()=>{let ge=e({text:w,message:t,streaming:!!t.streaming,raw:t.rawContent});return V&&W?.wrap==="char"?rc(ge,"char",t.id,{skipTags:W.skipTags}):V&&W?.wrap==="word"?rc(ge,"word",t.id,{skipTags:W.skipTags}):ge},I=null;if(A?(I=document.createElement("div"),I.innerHTML=T(),I.style.display="none",H.appendChild(I)):t.contentSegments?.length?OH(H,t.contentSegments,ge=>e({text:ge,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):H.innerHTML=T(),V&&W?.useCaret&&!A&&M){let ge=hu(),N=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ye=N[N.length-1];if(ye?.parentNode)ye.parentNode.insertBefore(ge,ye.nextSibling);else{let ke=H.lastElementChild;ke?ke.appendChild(ge):H.appendChild(ge)}}if(m&&g==="inline"&&t.createdAt){let ge=kA(t,p,"span");ge.classList.add("persona-timestamp-inline");let N=H.lastElementChild;N?N.appendChild(ge):H.appendChild(ge)}if(P.length>0){let ge=DH(P,!A&&!!M,()=>{A&&I&&(I.style.display="")});ge?C.appendChild(ge):A&&I&&(I.style.display="")}let D=IH(t);if(D.length>0){let ge=_H(D);ge&&C.appendChild(ge)}let G=HH(t);if(G.length>0){let ge=NH(G);ge&&C.appendChild(ge)}let z=RH(t);if(z.length>0){let ge=FH(z);ge&&C.appendChild(ge)}let K=t.contentSegments?.length?null:WH(t.contextMentions);if(K&&C.appendChild(K),C.appendChild(H),m&&g==="below"&&t.createdAt){let ge=kA(t,p);ge.classList.add("persona-mt-1"),C.appendChild(ge)}let Y=t.role==="assistant"?EH(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ge=!!(w&&w.trim()),N=O.placeholder==="skeleton",ye=N&&O.buffer==="line"&&ge;if(ge)ye&&C.appendChild(sc());else if(N)C.appendChild(sc());else{let ke=VH("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ke&&C.appendChild(ke)}}Y&&t.stopReason&&!t.streaming&&(M||(H.style.display="none"),C.appendChild(kH(t.stopReason,Y)));let re=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,oe=s?.actionEligibility,se=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&oe?.canEdit===!0||o?.showQuote===!0&&oe?.canQuote===!0||IA(o,"user").length>0);if((re||se)&&o){let ge=qH(t,se?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,oe);C.appendChild(ge)}if(!u||t.role==="system")return C;let ce=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),we=$H(d,t.role);return h==="right"||h==="left"&&t.role==="user"?ce.append(C,we):ce.append(we,C),ce};var jH=40,KH=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=Ie(e.name,jH);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild($("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild($("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},HA=(t,e,n={})=>{let o=$("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle"),l=$("div",{className:"persona-welcome-head-text"},r,s),d=$("div",{className:"persona-welcome-title-row"},o,l);return{host:$("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:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,a,e),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:e}},Aa=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},Au=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",KH(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},GH="data-persona-welcome-plugin",RA="data-persona-welcome-overlay",Su="persona-welcome-overlay-active",gh=new WeakMap,hh=(t,e,n)=>{n.setAttribute(GH,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(RA,""),t.classList.contains(Su)||(gh.set(t,t.scrollTop),t.classList.add(Su),t.scrollTop=0)},yh=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(RA),t.classList.contains(Su)&&(t.classList.remove(Su),t.scrollTop=gh.get(t)??t.scrollTop,gh.delete(t))},WA=()=>{let t=$("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Mu=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=$("div",{className:yc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="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))"}});t.appendChild($("div",{className:"persona-flex"},r)),t.hidden=!1},BA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,OA=(t,e)=>{if(BA()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,s=0,a=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let C=t.previousElementSibling,S=t.nextElementSibling,M=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-M),a=Math.max(0,S?S.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}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,g=()=>{h||(h=!0,t.style.overflow=l,e(m))};return m.finished.then(g).catch(g),m},DA=(t,e,n)=>{if(e<=1||BA()||typeof t.animate!="function"||!t.isConnected)return null;let o=n==="drop"?-e:e;return t.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var YH="Hello \u{1F44B}",QH="I can answer questions and help you get things done here.",_A=new WeakSet,qn=(t,e)=>!!t&&t[e]!==void 0,XH=(t,e)=>{!t||t.debug!==!0||!e.length||_A.has(t)||(_A.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Br=t=>{let e=t?.welcome,n=t?.copy,o=qn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":qn(e,"dismiss")?e.dismiss:"never",s=[];qn(e,"title")&&qn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),qn(e,"subtitle")&&qn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),qn(e,"variant")&&qn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&qn(e,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&qn(e,"dismiss")&&e.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let a=e?.anchor==="center"?"center":"bottom",l=ec(e?.anchorComposerTop)!==null;return qn(e,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(qn(e,"anchorComposerTop")||qn(e,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),XH(t,s),{title:qn(e,"title")?e.title:n?.welcomeTitle??YH,kicker:e?.kicker??"",subtitle:qn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??QH,icon:e?.icon,align:e?.align==="start"||e?.align==="center"?e.align:void 0,iconPlacement:e?.icon&&typeof e.icon!="function"&&e.icon.placement==="inline"?"inline":"above",variant:o,dismiss:r,message:o==="hero"?void 0:e?.message,anchor:a,anchorComposerTop:l?e.anchorComposerTop:"44%",composerGap:e?.composerGap?.trim()||iu}},NA=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ma=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var FA="16px",vh="10px",Ch="14px",VA=t=>{let e=t?.launcher?.enabled??!0,n=rn(t);if(pc(t)){let u=t?.launcher?.composerBar??{},m=v("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(t?.launcher?.zIndex??Hn);let h=v("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 g=v("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=u.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Hn),{wrapper:m,panel:h,pillRoot:g}}if(n){let u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!e){let u=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=t?.launcher?.width??"100%";return u.style.width=h,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let r=t?.launcher??{},s=r.position&&go[r.position]?go[r.position]:go["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??Hn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=t?.launcher?.width??t?.launcherWidth??Rr;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},wh=t=>{let e=$("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":ih(t)}});return e.hidden=!0,e},$A=(t,e)=>{let n=wh("starter"),o=HA(t,n,{flatShadow:rn(t)}),r=Br(t);Au(o,r),Aa(e,o.host,Ma(r,t?.initialMessages));let s=WA();return Mu(s,r.message,t),{welcome:o,greetingHost:s}},JH=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=xa(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:FA,iconSize:vh});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let W=Sa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:FA,iconSize:Ch});a=W.button,l=W.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=$("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=$("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=$A(t,p),{host:h,title:g,subtitle:b}=u,C=u.starterSuggestions,S=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),P=wh("followUp"),M=ys(t,!0);M&&(S.style.maxWidth=M,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),p.append(h,m,S,P);let B=$("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"}}),A=wu({config:t}),{root:O,textNode:E}=MA();return n.append(d,r,p,B),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:S,starterSuggestions:C,transcriptSuggestions:P,composerOverlay:B,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:h,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:g,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:A.footer,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:O,peekTextNode:E}},zA=(t,e=!0)=>{if(pc(t))return JH(t,e);let n=$("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?vu(t,o,{showClose:e}):li({config:t,showClose:e}),a=$("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"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=$A(t,a),{host:p,title:u,subtitle:m}=l,h=l.starterSuggestions,g=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=wh("followUp"),C=ys(t,!1);C&&(g.style.maxWidth=C,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),a.append(p,d,g,b);let S=gc({config:t}),P=t?.layout?.showFooter!==!1;r?mc(n,s,t):(s.header.style.display="none",mc(n,s,t)),n.append(a);let M=$("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 P||(S.footer.style.display="none"),n.append(S.footer),n.append(M),{container:n,body:a,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:b,composerOverlay:M,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};Ye();Yt();fs();var xh=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
1158
+ `)[0]).startsWith(O.trigger):!1),s=(A,O)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:O}))}catch{}},a=!t.chipRow,l=t.chipRow??$("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=t.textarea,m=null,h=null,g=null,b=null,C=()=>{if(d)return Promise.resolve(d);if(p)return p;let A=Dg().then(O=>(O.setMentionIconRenderer(Ie),d=O.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:l,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:B,emit:s}),d)).catch(O=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",O),p===A&&(p=null),null));return p=A,A},S=()=>{LS().then(A=>{let O=A.mountInlineComposer({textarea:t.textarea,renderToken:W=>Jl(W,{render:e.renderMentionToken}),onMentionRemoved:W=>d?.untrackMention(W)});m=O.input,h=O.destroy;let E=u;E.replaceWith(O.element),u=O.element,b={next:O.element,prev:E},g?.(O.element,E),d?d.rebindComposer(O.input):p&&p.then(W=>W?.rebindComposer(O.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&S();let P=[],M=new Map;for(let A of n){if(!A.showButton)continue;let O=Jx({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(E=>E?.openMenu(A.trigger))}});P.push(O),M.set(A.trigger,O.button)}let B=(A,O,E)=>{let W=M.get(O);W&&(W.setAttribute("aria-expanded",A?"true":"false"),A?W.setAttribute("aria-controls",E):W.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(d){d.handleInput();return}if(!Qx(A))return;let O=u,E=O.selectionStart??0;Kl(O.value,E,n)&&C().then(W=>W?.handleInput())},handleKeydown:A=>{if(d?.isMenuOpen())return d.handleKeydown(A);if(A.key==="Backspace"&&d?.hasMentions()&&!b){let O=u,E=O.selectionStart===0&&O.selectionEnd===0;if((O.value.length===0||E)&&d.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(d??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>d?.clear(),prefetch:()=>{Dg().catch(()=>{})},onComposerSwap:A=>{g=A,b&&A(b.next,b.prev)},destroy:()=>{d?.destroy(),h?.();for(let A of P)A.wrapper.remove();a&&l.remove()}}}var ou="16px",ru="transparent",SI=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),AI={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:SI,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"}},MI={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"}},TI={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:Rr,maxWidth:px,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ou,canvasBackground:ru},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"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function zn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?zn(t,o):o}function HS(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=zn(t,a);d!==void 0&&(e[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function EI(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function RS(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=RS(s,r):n[o]=r}return n}function kI(t,e){return e?RS(t,e):t}function va(t,e={}){let n={palette:AI,semantic:MI,components:TI},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:kI(n.components,t?.components)};if(e.validate!==!1){let r=EI(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}var jg=t=>t.trim()==="0"?"0px":t,IS="--persona-",LI=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let a=e.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=e.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(d=>{let p=d.endsWith("%"),u=parseFloat(p?d.slice(0,-1):d);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},PI=.179,Tn=(t,e)=>{for(let[n,...o]of e){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):t[IS+s],r!==void 0)break;r!==void 0&&(t[IS+n]=r)}};function WS(t){let e=HS(t),n={};for(let[N,ye]of Object.entries(e)){let ke=N.replace(/\./g,"-");n[`--persona-${ke}`]=ye.value}Tn(n,[["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 o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],Tn(n,[["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"]]),Tn(n,[["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"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,Tn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ou,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ru,Tn(n,[["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"]]),Tn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],Tn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],Tn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[N,ye]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ke=n[`--persona-components-history-overlay-${N}`];ke&&(n[`--persona-history-overlay-${ye}`]=ke)}for(let[N,ye]of[["background","bg"],["borderRadius","radius"]]){let ke=n[`--persona-components-history-menu-${N}`];ke&&(n[`--persona-history-menu-${ye}`]=ke)}let m=t.components?.history?.motion;if(m){let N=nt=>{if(nt===void 0)return;let Ee=String(nt).trim();return/^\d+(\.\d+)?$/.test(Ee)?`${Ee}ms`:Ee},ye=N(m.enterDurationMs);ye!==void 0&&(n["--persona-history-enter-ms"]=ye);let ke=N(m.exitDurationMs);ke!==void 0&&(n["--persona-history-exit-ms"]=ke),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let N of["scrim","shadow"]){let ye=n[`--persona-components-history-confirm-${N}`];ye&&(n[`--persona-history-confirm-${N}`]=ye)}for(let[N,ye]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ke=n[`--persona-components-tooltip-${N}`];ke&&(n[`--persona-tooltip-${ye}`]=ke)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[N,ye]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ke=n[`--persona-components-messageActions-${N}`];ke&&(n[`--persona-message-action-${ye}`]=ke)}Tn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let g=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],C=(!g||g==="transparent"||g==="none")&&(!b||b==="none"),S=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&S==="1.5rem"?"1.5rem 0":S,Tn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),Tn(n,[["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 P=n["--persona-components-markdown-heading-h1-fontSize"];P&&(n["--persona-md-h1-size"]=P);let M=n["--persona-components-markdown-heading-h1-fontWeight"];M&&(n["--persona-md-h1-weight"]=M);let B=n["--persona-components-markdown-heading-h2-fontSize"];B&&(n["--persona-md-h2-size"]=B);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),Tn(n,[["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"]]),Tn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Tn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Tn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Tn(n,[["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"]]),n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],Tn(n,[["message-border","components-message-border","border"]]),Tn(n,[["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 E=t.components,W=E?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let R=E?.labelButton;R&&(R.background&&(n["--persona-label-btn-bg"]=R.background),R.border&&(n["--persona-label-btn-border"]=R.border),R.color&&(n["--persona-label-btn-color"]=R.color),R.padding&&(n["--persona-label-btn-padding"]=R.padding),R.borderRadius&&(n["--persona-label-btn-radius"]=R.borderRadius),R.hoverBackground&&(n["--persona-label-btn-hover-bg"]=R.hoverBackground),R.fontSize&&(n["--persona-label-btn-font-size"]=R.fontSize),R.gap&&(n["--persona-label-btn-gap"]=R.gap));let V=E?.toggleGroup;V&&(V.gap&&(n["--persona-toggle-group-gap"]=V.gap),V.borderRadius&&(n["--persona-toggle-group-radius"]=V.borderRadius));let H=E?.artifact;if(H?.toolbar){let N=H.toolbar;N.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=jg(N.toggleGroupGap)),N.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=jg(N.toggleGroupPadding)),N.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=zn(t,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=jg(N.copyBorderRadius)),N.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(H?.tab){let N=H.tab;N.background&&(n["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(n["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(n["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(n["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(n["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(n["--persona-artifact-tab-list-padding"]=N.listPadding)}if(H?.pane){let N=H.pane;if(N.toolbarBackground){let ye=zn(t,N.toolbarBackground)??N.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ye}}if(H?.card){let N=H.card;N.background&&(n["--persona-artifact-card-bg"]=N.background),N.border&&(n["--persona-artifact-card-border"]=N.border),N.borderRadius&&(n["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(H?.inline){let N=H.inline;N.background&&(n["--persona-artifact-inline-bg"]=zn(t,N.background)??N.background),N.border&&(n["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(n["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=zn(t,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=zn(t,N.chromeBorder)??N.chromeBorder),N.titleColor&&(n["--persona-artifact-inline-title-color"]=zn(t,N.titleColor)??N.titleColor),N.mutedColor&&(n["--persona-artifact-inline-muted-color"]=zn(t,N.mutedColor)??N.mutedColor),N.frameHeight&&(n["--persona-artifact-inline-frame-height"]=N.frameHeight)}let w=E?.code;w&&(w.keywordColor&&(n["--persona-code-keyword-color"]=w.keywordColor),w.stringColor&&(n["--persona-code-string-color"]=w.stringColor),w.commentColor&&(n["--persona-code-comment-color"]=w.commentColor),w.numberColor&&(n["--persona-code-number-color"]=w.numberColor),w.tagColor&&(n["--persona-code-tag-color"]=w.tagColor),w.attrColor&&(n["--persona-code-attr-color"]=w.attrColor),w.propertyColor&&(n["--persona-code-property-color"]=w.propertyColor),w.lineNumberColor&&(n["--persona-code-line-number-color"]=w.lineNumberColor),w.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=w.gutterBorderColor),w.background&&(n["--persona-code-bg"]=zn(t,w.background)??w.background));let T=n["--persona-surface"],I=n["--persona-container"],D=n["--persona-palette-colors-gray-100"]??"#f3f4f6",G=n["--persona-palette-colors-gray-200"]??"#e5e7eb",z=n["--persona-palette-colors-gray-300"]??"#d1d5db",K=!I||I===T,Y=LI(T??n["--persona-background"]),re=K&&Y!==void 0&&Y<PI,oe=re?"rgba(255, 255, 255, 0.08)":D,se=re?"rgba(255, 255, 255, 0.12)":G,ce=re?"rgba(255, 255, 255, 0.16)":z,we=K?oe:I,ge=K?se:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??we,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ge,K&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??we,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??we,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??we,n}var II={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"}}},HI={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},BS=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Kg=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",RI=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Kg()},OS=t=>RI(t),WI=t=>va(t),BI=t=>{let e=ga(HI,t??{})??{};return va({...e,palette:{...e.palette,colors:{...II.colors,...e.palette?.colors}}},{validate:!1})},Ca=t=>{let e=OS(t),n=BS(t?.theme),o=BS(t?.darkTheme);return e==="dark"?BI(ga(n??{},o??{})):WI(n)},OI=t=>WS(t),Zl=(t,e)=>{let n=Ca(e),o=OI(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",OS(e))},su=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Kg())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Kg());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};var Fr=require("lucide");Yt();ro();Ye();var ys=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var iu="24px",Gg=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",ec=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},DS=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var _S=null;var Yg=()=>{if(_S!==null)return _S;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},DI="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",au=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},lu=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return au("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(au("unsupported",t),null):(n==="space"&&(o.key=" "),o)},_I=t=>DI.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),NS=(t,e)=>{let n=lu(t);if(!n)return"";let o=Yg(),r=_I(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},cu=t=>NS(t,!1),tc=t=>NS(t,!0),NI=(t,e)=>e.key?.toLowerCase()===t.key&&(Yg()?e.metaKey:e.ctrlKey)===t.mod&&!(Yg()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,FI=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},FS=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=s=>{if(s.isComposing||!e.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of e.values())if(NI(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&FI(a))){s.preventDefault();try{l.run(s)}catch(d){au(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=lu(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=e.get(l);return d?(au(`${d.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",tc(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};var VS=require("idiomorph"),du=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;VS.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var $S=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Qg={index:-1,draft:""};function zS(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function US(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function qS(){return new Map}function jS(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function KS(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function GS(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}Jg();fs();ac();oo();var{setLoader:QN,load:pH}=$t({fallbackImport:()=>Promise.resolve().then(()=>(yA(),hA))});var bA=pH;fs();function rh(t,e=Hn){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var cc=0,bs=null;function sh(t=document){if(cc++,cc===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;bs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,cc=Math.max(0,cc-1),cc===0&&bs)){let n=t.body,o=t.defaultView??window;n.style.overflow=bs.originalOverflow,n.style.position=bs.originalPosition,n.style.top=bs.originalTop,n.style.width=bs.originalWidth,o.scrollTo(0,bs.scrollY),bs=null}}}var dc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rn=t=>(t?.launcher?.mountMode??"floating")==="docked",pc=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Lo=t=>{let e=t?.launcher?.dock;return{side:e?.side??dc.side,width:e?.width??dc.width,animate:e?.animate??dc.animate,reveal:e?.reveal??dc.reveal,maxHeight:e?.maxHeight??dc.maxHeight}};Ye();Ye();var CA=require("lucide");Yt();ro();var ih=t=>t==="followUp"?"follow-up":t,ah=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},uH=t=>{switch(t){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'}},vA=new WeakSet,mH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,fH=t=>{mH()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},lh=t=>{var B,A,O;let{item:e,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:h,submitPrompt:g}=t,b=o==="followUp",C=e.behavior,S=()=>{if(u.isStreaming())return;let E={suggestion:{...e},surface:o,source:r,behavior:C},W=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:E,bubbles:!0,composed:!0,cancelable:!0}));if(b&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!W)return;for(let V of d)if(V.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let R=m();if(C==="fill"){R.value=e.prompt,R.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),R.focus();return}if(g){g(e.prompt);return}R.value="",u.sendMessage(e.prompt)},P=()=>{let E=v("button",`persona-suggestion persona-suggestion--${s}`);if(E.type="button",E.disabled=a,E.dataset.suggestionId=e.id,E.dataset.emphasis=e.emphasis,E.dataset.behavior=C,s==="chip"&&(p?.fontFamily&&(E.style.fontFamily=uH(p.fontFamily)),p?.fontWeight&&(E.style.fontWeight=p.fontWeight),p?.paddingX&&(E.style.paddingLeft=p.paddingX,E.style.paddingRight=p.paddingX),p?.paddingY&&(E.style.paddingTop=p.paddingY,E.style.paddingBottom=p.paddingY)),e.icon){let R=Ie(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);R&&(R.classList.add("persona-suggestion__icon"),e.iconColor&&(R.style.color=e.iconColor),E.appendChild(R))}let W=v("span","persona-suggestion__copy");if(W.appendChild($("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&W.appendChild($("span",{className:"persona-suggestion__description",text:e.description})),E.appendChild(W),s!=="chip"){let R=Qe(CA.ArrowRight,16,"currentColor",1.8);R&&(R.classList.add("persona-suggestion__arrow"),E.appendChild(R))}return E.addEventListener("click",S),E},M=null;for(let E of d)if(E.renderSuggestion&&(M=E.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:P,select:S}),M))break;return M??(M=P()),(B=M.dataset).suggestionId||(B.suggestionId=e.id),(A=M.dataset).behavior||(A.behavior=C),(O=M.dataset).emphasis||(O.emphasis=e.emphasis),M instanceof HTMLButtonElement||M.setAttribute("aria-disabled",a?"true":"false"),M},uc=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){s();return}let m=getComputedStyle(t).direction==="rtl",h=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),g=4,b=h<=g,C=h>=u-g,S=m?!C:!b,P=m?!b:!C;t.toggleAttribute("data-scroll-left",S),t.toggleAttribute("data-scroll-right",P)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,h,g,b,C)=>{t.replaceChildren(),e.length=0,n.length=0;let S=C?.source??"config",P=C?.surface??(S==="config"?"starter":"followUp"),M=P==="followUp",B=C?.variant??"chip",A=C?.behavior??"send",O=C?.overflow??"wrap",E=C?.config??{},W=C?.plugins??[],R=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,V=M?"followUps":"starters";!vA.has(E)&&E.debug===!0&&B!=="chip"&&E.suggestions?.[V]?.overflow!==void 0&&(vA.add(E),console.info(`[persona] suggestions.${V}.overflow applies to the "chip" variant only; the "${B}" variant manages its own stacking.`));let H=z=>z.map(ah).filter(K=>K!==null).map(K=>({...K,behavior:K.behavior??A})),w=H(u??[]);W.forEach(z=>{z.transformSuggestions&&(w=H(z.transformSuggestions({suggestions:w.map(K=>({...K})),surface:P,source:S,config:E})))});let T=R===void 0?w:w.slice(0,R);if(!T.length){t.hidden=!0,o=null,s();return}if(!M&&(g??m.getMessages()).some(K=>K.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=ih(P),t.dataset.variant=B,t.dataset.overflow=O;let I=document.createDocumentFragment(),D=m.isStreaming();T.forEach((z,K)=>{let Y=lh({item:z,index:K,surface:P,source:S,variant:B,streaming:D,config:E,plugins:W,chipsConfig:b,session:m,getTextarea:()=>h,eventTarget:t,submitPrompt:C?.submitPrompt});I.appendChild(Y),n.push(Y),[...Y instanceof HTMLButtonElement?[Y]:[],...Array.from(Y.querySelectorAll("button"))].forEach(oe=>{e.includes(oe)||(oe.disabled=D,e.push(oe))})}),t.appendChild(I),a(),l();let G=JSON.stringify({normalized:T,surface:P,variant:B,source:S});G!==o&&(o=G,fH(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(z=>({...z})),surface:P,source:S,variant:B},bubbles:!0,composed:!0})),M&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(z=>z.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"};fs();Ye();Yt();Ye();Yt();var gH="persona-header-control",hH="persona-header-control--glyph",yH="persona-header-control--sparse",bH=20,vH={x:[1.4,1.05]},wA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",CH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yu=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=vH[e]??[1,1.5],l=!o;t.classList.toggle(hH,l),t.classList.toggle(yH,l&&s!==1);let d=parseFloat(o??"")||bH,p=Ie(e,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(p)):r&&(t.textContent=r)},ai=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=wA,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:h,borderRadius:g,paddingX:b,paddingY:C,hidden:S,extraClassName:P,attrs:M}=t,B=v("div",a),A=!!(m||h),O=$("button",{className:Vt(gH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!g&&"persona-rounded-full",P),attrs:{type:"button","aria-label":e,...M},style:{width:l,height:l,minWidth:l,minHeight:l,display:S?"none":void 0,color:p||Un.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:g,paddingLeft:b,paddingRight:b,paddingTop:C,paddingBottom:C}});return r?yu(O,r,{iconSize:d,iconText:s}):s&&(O.textContent=s),B.appendChild(O),Mn({anchor:O,trigger:B,text:()=>O.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:O,wrapper:B}},xa=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=wA,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=ai({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},Sa=(t,e={})=>{let{wrapperClassName:n=CH,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=ai({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var Un={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)"},ch={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)"},wH={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)"},li=t=>{let{config:e,showClose:n=!0}=t,o=$("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:Un.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=e?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=$("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let O=parseFloat(s)||24,E=Ie(d,O*.6,"currentColor",1);E?p.replaceChildren(E):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let O=v("img");O.src=e.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=s,O.style.width=s,p.replaceChildren(O)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=$("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Un.titleColor,...ch}}),h=$("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Un.subtitleColor,...wH}});u.append(m,h),l?o.append(u):o.append(p,u);let g=r.clearChat??{},b=g.enabled??!0,C=g.placement??"inline",S=null,P=null;if(b){let E=Sa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=E.button,P=E.wrapper,C==="top-right"&&(P.style.right="48px"),C==="inline"&&o.appendChild(P)}let M=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:B,wrapper:A}=xa(e,{showClose:n,wrapperClassName:M});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:h,closeButton:B,closeButtonWrapper:A,clearChatButton:S,clearChatButtonWrapper:P}},mc=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};Ye();dh();di();var xH=t=>{let e=li({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function SH(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=ai({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?cu(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=tc(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=fc({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(s)}}var AH=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Un.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,u;if(d){let A=SA({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:O=>{let E=R=>{R===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},W=d.onSelect(O);W instanceof Promise?W.then(E,()=>{}):E(W)},hover:d.hover,className:""});p=A.element,p.style.color=Un.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Un.titleColor,Object.assign(u.style,ch),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=r.onTitleClick;p.addEventListener("click",E=>{E.target.closest("button")||O()}),p.addEventListener("keydown",E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),O())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=A.background??"",p.style.borderColor=A.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:g}=xa(e,{showClose:n,wrapperClassName:m});o&&h.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");d||SH(b,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},S=null,P=null;if(C.enabled??!0){let A=C.placement??"inline",O=Sa(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});S=O.button,P=O.wrapper,A==="top-right"?P.style.right="48px":b.appendChild(P)}b.appendChild(g),l.appendChild(b);let M=v("div");M.style.display="none";let B=v("span");return B.style.display="none",{header:l,iconHolder:M,headerTitle:u,headerSubtitle:B,closeButton:h,closeButtonWrapper:g,clearChatButton:S,clearChatButtonWrapper:P}},AA={default:xH,minimal:AH},MH=t=>AA[t]??AA.default,vu=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let d=v("span"),p=v("span"),u=v("button");u.style.display="none";let m=v("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=MH(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Ye();var gc=t=>{let{config:e}=t,n=$("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Op(),r=$("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:s,attachAutoResize:a}=Hp(e);a();let l=Rp(e),d=ha(e),p=Wp(e),u=Bp(e),m=$("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let h=$("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=$("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),b=$("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&g.append(p.wrapper),d&&b.append(d.wrapper),b.append(l.wrapper),h.append(g,b),r.append(h),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:h,leftActions:g,rightActions:b,setSendButtonMode:l.setMode}};Ye();var Cu=require("lucide");ro();var MA=()=>{let t=$("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=Qe(Cu.MessageSquare,16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=Qe(Cu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},wu=t=>{let{config:e}=t,n=$("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Op(),r=Bp(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Hp(e,{defaultMaxLines:5});a();let l=Rp(e),d=ha(e),p=Wp(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=$("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=$("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let h=$("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&h.append(d.wrapper),h.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,h);let g=$("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(g),p&&g.append(p.previewsContainer),n.append(o,u,r);let b=u;return{footer:n,suggestions:o,composerForm:u,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:b,leftActions:m,rightActions:h,setSendButtonMode:l.setMode}};Ye();Yt();Ye();di();Yt();ac();var TH=t=>{switch(t){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}},EH=(t,e)=>{if(!t)return null;let n=TH(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},kH=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},LH=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},uh=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},mh=320,PA=320,PH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),IH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),HH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),RH=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),WH=t=>{if(!t||t.length===0)return null;let e=$("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=$("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=Ie(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild($("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},BH=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Jl(o.ref,{readonly:!0,render:e}))}return n},TA="\uE000",EA="\uE001",OH=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=h=>`${TA}${r}:${h}${EA}`,a=e.map((h,g)=>h.kind==="text"?h.text:s(g)).join(""),l=n(a);if(!e.every((h,g)=>h.kind==="text"||l.includes(s(g)))){t.replaceChildren(BH(e,o));return}t.innerHTML=l;let p=new RegExp(`${TA}${r}:(\\d+)${EA}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let h=u.nextNode();h;h=u.nextNode())m.push(h);for(let h of m){let g=h;for(let b=p.exec(g.data);b;b=p.exec(g.data)){let C=e[Number(b[1])],S=g.splitText(b.index);S.data=S.data.slice(b[0].length),C?.kind==="mention"&&S.parentNode?.insertBefore(Jl(C.ref,{readonly:!0,render:o}),S),g=S}}},DH=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,d)=>{let p=v("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${mh}px`,p.style.maxHeight=`${PA}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),LH(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},_H=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!uh(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mh}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},NH=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!uh(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mh}px`,r.style.maxHeight=`${PA}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},FH=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!uh(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.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",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},hc=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";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="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},VH=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:hc};if(e){let r=e(o);if(r!==null)return r}return hc()},$H=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},kA=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},yc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.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 n},LA={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"}},zH=(t,e,n="bubble",o)=>{if(!o)return;let r=e==="user"?"user":"assistant",s=LA[n??"bubble"]??LA.bubble;o.padding&&(t.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},xu="custom:",UH=t=>`${xu}${t}`,IA=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),qH=(t,e,n,o)=>{let r=e.showCopy??!0,s=e.showUpvote??!0,a=e.showDownvote??!0,l=e.showReadAloud??!1,d=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=IA(e,t.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let B=v("div");return B.style.display="none",B.id=`actions-${t.id}`,B.setAttribute("data-actions-for",t.id),B}let h=e.visibility??"hover",g=e.align??"right",b=e.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[g],S={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[b],P=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${S} ${h==="hover"?"persona-message-actions-hover":""}`);P.id=`actions-${t.id}`,P.setAttribute("data-actions-for",t.id);let M=(B,A,O)=>{let E=gn({icon:B,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return E.setAttribute("data-action",O),E};r&&P.appendChild(M("copy","Copy message","copy")),l&&P.appendChild(M("volume-2","Read aloud","read-aloud")),s&&P.appendChild(M("thumbs-up","Upvote","upvote")),a&&P.appendChild(M("thumbs-down","Downvote","downvote")),d&&P.appendChild(M("refresh-cw","Regenerate response","regenerate")),p&&P.appendChild(M("pencil","Edit message","edit")),u&&P.appendChild(M("quote","Quote message","quote"));for(let B of m)P.appendChild(M(B.iconName??"ellipsis",B.label,UH(B.id)));return P},fh=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,h=d?.position??"left",g=p?.position??"below",b=yc(t.role,l),C=v("div",b.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let S=s?.widgetConfig?.theme?.components?.message;zH(C,t.role,l,t.role==="user"?S?.user:S?.assistant),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=PH(t),M=t.content?.trim()??"",A=P.length>0&&M===da,O=fu(s?.widgetConfig?.features?.streamAnimation),E=s?.widgetConfig?.features?.streamAnimation?.plugins,W=t.role==="assistant"&&O.type!=="none"?oc(O.type,E):null,R=t.role==="assistant"&&W?.isAnimating?.(t)===!0,V=t.role==="assistant"&&W!==null&&(!!t.streaming||R);V&&W?.bubbleClass&&C.classList.add(W.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),t.streaming&&H.classList.add("persona-content-streaming"),V&&W&&(W.containerClass&&H.classList.add(W.containerClass),H.style.setProperty("--persona-stream-step",`${O.speed}ms`),H.style.setProperty("--persona-stream-duration",`${O.duration}ms`));let w=V?gu(t.content??"",O.buffer,W,t,!!t.streaming):t.content??"",T=()=>{let ge=e({text:w,message:t,streaming:!!t.streaming,raw:t.rawContent});return V&&W?.wrap==="char"?rc(ge,"char",t.id,{skipTags:W.skipTags}):V&&W?.wrap==="word"?rc(ge,"word",t.id,{skipTags:W.skipTags}):ge},I=null;if(A?(I=document.createElement("div"),I.innerHTML=T(),I.style.display="none",H.appendChild(I)):t.contentSegments?.length?OH(H,t.contentSegments,ge=>e({text:ge,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):H.innerHTML=T(),V&&W?.useCaret&&!A&&M){let ge=hu(),N=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ye=N[N.length-1];if(ye?.parentNode)ye.parentNode.insertBefore(ge,ye.nextSibling);else{let ke=H.lastElementChild;ke?ke.appendChild(ge):H.appendChild(ge)}}if(m&&g==="inline"&&t.createdAt){let ge=kA(t,p,"span");ge.classList.add("persona-timestamp-inline");let N=H.lastElementChild;N?N.appendChild(ge):H.appendChild(ge)}if(P.length>0){let ge=DH(P,!A&&!!M,()=>{A&&I&&(I.style.display="")});ge?C.appendChild(ge):A&&I&&(I.style.display="")}let D=IH(t);if(D.length>0){let ge=_H(D);ge&&C.appendChild(ge)}let G=HH(t);if(G.length>0){let ge=NH(G);ge&&C.appendChild(ge)}let z=RH(t);if(z.length>0){let ge=FH(z);ge&&C.appendChild(ge)}let K=t.contentSegments?.length?null:WH(t.contextMentions);if(K&&C.appendChild(K),C.appendChild(H),m&&g==="below"&&t.createdAt){let ge=kA(t,p);ge.classList.add("persona-mt-1"),C.appendChild(ge)}let Y=t.role==="assistant"?EH(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ge=!!(w&&w.trim()),N=O.placeholder==="skeleton",ye=N&&O.buffer==="line"&&ge;if(ge)ye&&C.appendChild(sc());else if(N)C.appendChild(sc());else{let ke=VH("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ke&&C.appendChild(ke)}}Y&&t.stopReason&&!t.streaming&&(M||(H.style.display="none"),C.appendChild(kH(t.stopReason,Y)));let re=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,oe=s?.actionEligibility,se=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&oe?.canEdit===!0||o?.showQuote===!0&&oe?.canQuote===!0||IA(o,"user").length>0);if((re||se)&&o){let ge=qH(t,se?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,oe);C.appendChild(ge)}if(!u||t.role==="system")return C;let ce=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),we=$H(d,t.role);return h==="right"||h==="left"&&t.role==="user"?ce.append(C,we):ce.append(we,C),ce};var jH=40,KH=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=Ie(e.name,jH);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild($("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild($("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},HA=(t,e,n={})=>{let o=$("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("p","persona-welcome-kicker");r.hidden=!0;let s=v("h2","persona-welcome-title"),a=v("p","persona-welcome-subtitle"),l=$("div",{className:"persona-welcome-head-text"},r,s),d=$("div",{className:"persona-welcome-title-row"},o,l);return{host:$("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:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,a,e),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:e}},Aa=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},Au=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",KH(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},GH="data-persona-welcome-plugin",RA="data-persona-welcome-overlay",Su="persona-welcome-overlay-active",gh=new WeakMap,hh=(t,e,n)=>{n.setAttribute(GH,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(RA,""),t.classList.contains(Su)||(gh.set(t,t.scrollTop),t.classList.add(Su),t.scrollTop=0)},yh=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(RA),t.classList.contains(Su)&&(t.classList.remove(Su),t.scrollTop=gh.get(t)??t.scrollTop,gh.delete(t))},WA=()=>{let t=$("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Mu=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=$("div",{className:yc("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="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))"}});t.appendChild($("div",{className:"persona-flex"},r)),t.hidden=!1},BA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,OA=(t,e)=>{if(BA()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,s=0,a=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let C=t.previousElementSibling,S=t.nextElementSibling,M=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-M),a=Math.max(0,S?S.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}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,g=()=>{h||(h=!0,t.style.overflow=l,e(m))};return m.finished.then(g).catch(g),m},DA=(t,e,n)=>{if(e<=1||BA()||typeof t.animate!="function"||!t.isConnected)return null;let o=n==="drop"?-e:e;return t.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var YH="Hello \u{1F44B}",QH="I can answer questions and help you get things done here.",_A=new WeakSet,qn=(t,e)=>!!t&&t[e]!==void 0,XH=(t,e)=>{!t||t.debug!==!0||!e.length||_A.has(t)||(_A.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Br=t=>{let e=t?.welcome,n=t?.copy,o=qn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":qn(e,"dismiss")?e.dismiss:"never",s=[];qn(e,"title")&&qn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),qn(e,"subtitle")&&qn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),qn(e,"variant")&&qn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&qn(e,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&qn(e,"dismiss")&&e.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let a=e?.anchor==="center"?"center":"bottom",l=ec(e?.anchorComposerTop)!==null;return qn(e,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(qn(e,"anchorComposerTop")||qn(e,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),XH(t,s),{title:qn(e,"title")?e.title:n?.welcomeTitle??YH,kicker:e?.kicker??"",subtitle:qn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??QH,icon:e?.icon,align:e?.align==="start"||e?.align==="center"?e.align:void 0,iconPlacement:e?.icon&&typeof e.icon!="function"&&e.icon.placement==="inline"?"inline":"above",variant:o,dismiss:r,message:o==="hero"?void 0:e?.message,anchor:a,anchorComposerTop:l?e.anchorComposerTop:"44%",composerGap:e?.composerGap?.trim()||iu}},NA=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ma=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var FA="16px",vh="10px",Ch="14px",VA=t=>{let e=t?.launcher?.enabled??!0,n=rn(t);if(pc(t)){let u=t?.launcher?.composerBar??{},m=v("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(t?.launcher?.zIndex??Hn);let h=v("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 g=v("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=u.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Hn),{wrapper:m,panel:h,pillRoot:g}}if(n){let u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!e){let u=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=t?.launcher?.width??"100%";return u.style.width=h,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let r=t?.launcher??{},s=r.position&&go[r.position]?go[r.position]:go["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??Hn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=t?.launcher?.width??t?.launcherWidth??Rr;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},wh=t=>{let e=$("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":ih(t)}});return e.hidden=!0,e},$A=(t,e)=>{let n=wh("starter"),o=HA(t,n,{flatShadow:rn(t)}),r=Br(t);Au(o,r),Aa(e,o.host,Ma(r,t?.initialMessages));let s=WA();return Mu(s,r.message,t),{welcome:o,greetingHost:s}},JH=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=xa(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:FA,iconSize:vh});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let W=Sa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:FA,iconSize:Ch});a=W.button,l=W.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=$("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=$("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=$A(t,p),{host:h,title:g,subtitle:b}=u,C=u.starterSuggestions,S=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),P=wh("followUp"),M=ys(t,!0);M&&(S.style.maxWidth=M,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),p.append(h,m,S,P);let B=$("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"}}),A=wu({config:t}),{root:O,textNode:E}=MA();return n.append(d,r,p,B),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:S,starterSuggestions:C,transcriptSuggestions:P,composerOverlay:B,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:h,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:g,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:A.footer,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:O,peekTextNode:E}},zA=(t,e=!0)=>{if(pc(t))return JH(t,e);let n=$("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?vu(t,o,{showClose:e}):li({config:t,showClose:e}),a=$("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"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=$A(t,a),{host:p,title:u,subtitle:m}=l,h=l.starterSuggestions,g=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=wh("followUp"),C=ys(t,!1);C&&(g.style.maxWidth=C,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),a.append(p,d,g,b);let S=gc({config:t}),P=t?.layout?.showFooter!==!1;r?mc(n,s,t):(s.header.style.display="none",mc(n,s,t)),n.append(a);let M=$("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 P||(S.footer.style.display="none"),n.append(S.footer),n.append(M),{container:n,body:a,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:b,composerOverlay:M,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};Ye();Yt();fs();var xh=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
1159
1159
  <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>
1160
1160
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
1161
1161
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -1166,11 +1166,11 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1166
1166
  `,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=rn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let B=a.title??"Chat Assistant";d.textContent=B,d.setAttribute("title",B)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let B=a.subtitle??"Here to help you get answers fast";p.textContent=B,p.setAttribute("title",B)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let B=a.agentIconSize??"40px";if(m.style.height=B,m.style.width=B,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let A=parseFloat(B)||24,O=Ie(a.agentIconName,A*.6,"var(--persona-text-inverse, #ffffff)",1.5);O?(m.appendChild(O),m.style.display=""):(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}let h=n.querySelector("[data-role='launcher-image']");if(h){let B=a.agentIconSize??"40px";h.style.height=B,h.style.width=B,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let B=a.callToActionIconSize??"32px";g.style.height=B,g.style.width=B,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let A=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,A=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",a.callToActionIconName){let O=parseFloat(B)||24,E=Math.max(O-A,8),W=Ie(a.callToActionIconName,E,"currentColor",1.5);W?g.appendChild(W):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&go[a.position]?go[a.position]:go["bottom-right"],C="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",S="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";n.className=l?S:`${C} ${b}`,l||(n.style.zIndex=String(a.zIndex??Hn));let P="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??P,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:M,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}},ZH="teaser-dismissed",qA=new Set,UA=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${ZH}`},eR=(t,e)=>{if(qA.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},tR=(t,e)=>{if(qA.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},nR=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,oR=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||rn(t??{})?null:e},jA=(t,e)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,m=!1,h=!1,g=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{d!==null&&(clearTimeout(d),d=null)},C=()=>{!s||!p||(p=!1,s.hidden=!0)},S=G=>{b(),m=!0,C(),tR(UA(o),G&&g())},P=G=>{!r||m||S(G==="user"&&p)},M=()=>{d=null,!(!s||m||h)&&(u=!0,p=!0,s.hidden=!1,!(nR()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},B=()=>{!r||!s||m||u||h||eR(UA(o),g())||(b(),d=setTimeout(M,Math.max(0,r.delayMs??0)))},A=()=>{S(g()),e()},O=G=>{G.stopPropagation(),S(g())},W=xh(t,()=>{P("user"),e()}),R=()=>{b(),l?.removeEventListener("click",A),a?.removeEventListener("click",O),s?.remove(),s=null,l=null,a=null,p=!1},V=()=>{l=$("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),a=$("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",O),s=$("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,W.element)},H=()=>{let G=o.launcher?.position??"bottom-right",z=go[G]??go["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",W.element.style.position="";return}n.className=Vt("persona-launcher-surface",z),n.setAttribute("data-teaser",G),n.style.zIndex=String(o.launcher?.zIndex??Hn),W.element.style.position="static"},w=G=>{let z=oR(G);if(r=z,!z){R();return}s||V(),l.textContent=z.text,a.hidden=z.dismissible===!1,a.setAttribute("aria-label",z.dismissLabel??"Dismiss message"),B()},T=G=>{o=G,W.update(G),w(G),H()},I=(G,z="user")=>{h=G,G&&P(z)},D=()=>{R(),W.destroy(),n.remove()};return n.appendChild(W.element),t&&(w(t),H()),{element:n,launcher:W,get teaser(){return s?{element:s,show:M,dismiss:S}:null},setPanelOpen:I,update:T,destroy:D}};var KA=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=VA(t),s=zA(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:d,composer:p,replaceHeader:h=>(d.element.replaceWith(h.header),d.element=h.header,d.iconHolder=h.iconHolder,d.headerTitle=h.headerTitle,d.headerSubtitle=h.headerSubtitle,d.closeButton=h.closeButton,d.closeButtonWrapper=h.closeButtonWrapper,d.clearChatButton=h.clearChatButton,d.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{p.footer.replaceWith(h),p.footer=h}}},Sh=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>xh(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=jA(t,n);return{instance:r,element:r.element}};var rR=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},sR=(t,e,n)=>`${rR(t)}plugin:${e}:${n}`,GA=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>sR(t(),r,a);return{get:a=>{let l=s(a),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return e.get(l)??null},set:(a,l)=>{let d=s(a),p=o();if(p)try{p.setItem(d,l);return}catch{n=!0}e.set(d,l)},remove:a=>{let l=s(a);e.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};Ye();Yt();ri();Tu();Ye();var Eu=require("lucide");ro();var iR=["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"],aR="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",lR="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",cR=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ku=(t,e)=>{let n=v("div",["persona-message-bubble",t,...iR].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},Lu=t=>{let e=v("button",t.expandable?aR:lR);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Ah=(t,e,n)=>{t.innerHTML="";let o=Qe(e?Eu.ChevronUp:Eu.ChevronDown,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},Pu=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=v("div","persona-flex persona-items-center");Ah(o,n.expanded,n.iconColor);let r=v("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),t.append(e,r),o},Iu=t=>{let e=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();cR(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Hu=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Ah(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},Ru=(t,e,n)=>{let o=n.stateSet.has(t),r=e.querySelector('button[data-expand-header="true"]'),s=e.querySelector(".persona-border-t"),a=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&Ah(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var Ta=new Set,dR=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
1167
1167
  `):""},YA=(t,e)=>{Ru(t,e,{stateSet:Ta,previewKind:"reasoning",iconColor:"currentColor"})},Mh=(t,e)=>{let n=t.reasoning,o=ku("persona-reasoning-bubble",t.id);if(!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Ta.has(t.id),l=n.status!=="complete",d=dR(t,r.previewMaxLines??3),p=Lu({expandable:s,expanded:a,bubbleType:"reasoning"}),u=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary"),h="Thinking...",g=e?.reasoning??{},b=String(n.startedAt??Date.now()),C=()=>{let D=v("span","");return D.setAttribute("data-tool-elapsed",b),D.textContent=cp(n),D},S=g.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:h,previewText:d,isActive:l,config:e??{},elapsed:cp(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(m.textContent=S,u.appendChild(m)):S instanceof HTMLElement?u.appendChild(S):(m.textContent=h,u.appendChild(m));let P=v("span","persona-text-xs persona-text-persona-primary");P.textContent=sw(n),u.appendChild(P);let M=r.loadingAnimation??"none",B=g.activeTextTemplate,A=g.completeTextTemplate,O=l?B:A,E=S instanceof HTMLElement,W=(D,G)=>{m.textContent="";let z=dp(D,""),K=0;for(let Y of z){let re=Y.styles.length>0?(()=>{let oe=v("span",Y.styles.map(se=>`persona-tool-text-${se}`).join(" "));return m.appendChild(oe),oe})():m;if(Y.isDuration&&l)re.appendChild(C());else{let oe=Y.isDuration?cp(n):Y.text;G?K=vs(re,oe,K):re.appendChild(document.createTextNode(oe))}}};if(!E&&O)if(P.style.display="none",m.style.display="",l&&M!=="none"){let D=g.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),M==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`),W(O,!1)):(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`),M==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),W(O,!0))}else W(O,!1);else if(!E&&l&&M!=="none"){m.style.display="";let D=g.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`);else{m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${D}ms`),M==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let G=m.textContent||h;m.textContent="",vs(m,G,0)}n.status==="complete"&&(m.style.display="none")}else E||(n.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!E){let D=v("span","persona-reasoning-header-icon"),G=Ie(r.iconName,16,"currentColor",2);G&&(D.appendChild(G),p.appendChild(D))}let R="currentColor",V=Pu(p,u,{expandable:s,expanded:a,iconColor:R,metaGap:!1}),H=Iu({bubble:o,previewKind:"reasoning",expanded:a,isActive:l,previewText:d,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:d,isActive:l,config:e??{}})});if(!s)return o.append(p,H),o;let w=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");w.style.display=a?"":"none";let T=n.chunks.join(""),I=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return I.textContent=T||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),w.appendChild(I),Hu({expanded:a,header:p,toggleIcon:V,content:w,collapsedPreview:H,iconColor:R}),o.append(p,H,w),o};Ye();ri();Tu();var Ea=new Set,QA=t=>t.toggleTextColor||t.headerTextColor||"var(--persona-primary, #171717)",pR=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
1168
1168
  `);let r=us(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
1169
- `):""},Th=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},uR=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=n?.success===!1?n.error||"Tool failed":pR(t,o?.previewMaxLines??3),a=n?aw(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",d=e?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&d.activeTextTemplate?p=Qf(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=Qf(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},XA=(t,e,n)=>{Ru(t,e,{stateSet:Ea,previewKind:"tool",iconColor:QA(n?.toolCall??{})})},Eh=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=ku("persona-tool-bubble",t.id);if(o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&Ea.has(t.id),{summary:d,previewText:p,isActive:u}=uR(t,e),m=Lu({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),C=()=>{let w=v("span","");return w.setAttribute("data-tool-elapsed",b),w.textContent=Hl(n),w},S=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:Hl(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(g.textContent=S,h.appendChild(g)):S instanceof HTMLElement?h.appendChild(S):(g.textContent=d,h.appendChild(g));let P=s.loadingAnimation??"none",M=o.activeTextTemplate,B=o.completeTextTemplate,A=u?M:B,O=S instanceof HTMLElement,E=(w,T)=>{g.textContent="";let I=n.name?.trim()||"tool",D=dp(w,I),G=0;for(let z of D){let K=z.styles.length>0?(()=>{let Y=v("span",z.styles.map(re=>`persona-tool-text-${re}`).join(" "));return g.appendChild(Y),Y})():g;if(z.isDuration&&u)K.appendChild(C());else{let Y=z.isDuration?Hl(n):z.text;T?G=vs(K,Y,G):K.appendChild(document.createTextNode(Y))}}};if(!O)if(u&&P!=="none"){let w=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),P==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),A&&E(A,!1);else if(g.classList.add(`persona-tool-loading-${P}`),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),A)E(A,!0);else{let T=g.textContent||d;g.textContent="",vs(g,T,0)}}else A&&E(A,!1);let W=QA(o),R=Pu(m,h,{expandable:a,expanded:l,iconColor:W,metaGap:!0}),V=Iu({bubble:r,previewKind:"tool",expanded:l,isActive:u,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:p,isActive:u,config:e??{}})});if(!a)return r.append(m,V),r;let H=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=l?"":"none",o.contentBackgroundColor&&(H.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(H.style.color=o.contentTextColor),o.contentPaddingX&&(H.style.paddingLeft=o.contentPaddingX,H.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(H.style.paddingTop=o.contentPaddingY,H.style.paddingBottom=o.contentPaddingY),n.name){let w=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?w.style.color=o.contentTextColor:o.headerTextColor&&(w.style.color=o.headerTextColor),w.textContent=n.name,H.appendChild(w)}if(n.args!==void 0){let w=v("div","persona-space-y-1"),T=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(T.style.color=o.labelTextColor),T.textContent="Arguments";let I=v("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",Th(I,o),I.textContent=us(n.args),w.append(T,I),H.appendChild(w)}if(n.chunks&&n.chunks.length){let w=v("div","persona-space-y-1"),T=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(T.style.color=o.labelTextColor),T.textContent="Activity";let I=v("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",Th(I,o),I.textContent=n.chunks.join(""),w.append(T,I),H.appendChild(w)}if(n.success===!1&&H.appendChild($("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let w=v("div","persona-space-y-1"),T=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(T.style.color=o.labelTextColor),T.textContent="Result";let I=v("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",Th(I,o),I.textContent=us(n.result),w.append(T,I),H.appendChild(w)}if(n.status==="complete"&&typeof n.duration=="number"){let w=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(w.style.color=o.contentTextColor),w.textContent=`Duration: ${n.duration}ms`,H.appendChild(w)}return Hu({expanded:l,header:m,toggleIcon:R,content:H,collapsedPreview:V,iconColor:W}),r.append(m,V,H),r};ri();oo();var{setLoader:mV,load:vR,provide:fV,getSync:CR}=$t({fallbackImport:()=>Promise.resolve().then(()=>(iM(),sM))});var aM=vR;var lM=CR;na();oo();var{setLoader:PV,load:NR}=$t({fallbackImport:()=>Promise.resolve().then(()=>(CM(),vM))});var Dh=NR;oo();wc();ti();wp();var Qh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:$$,load:wW,provide:z$,getSync:xW}=$t({fallbackImport:()=>Promise.resolve().then(()=>(GM(),KM))}),Ha=null,qu=new Set,YM=t=>{if(Ha)return Ha;Ha=t,t.initArtifactsUi({componentRegistry:$o});for(let o of Qh)$o.has(o)||$o.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Ao();e?t.__provideMarkdownParsers(e):ea(()=>{let o=Ao();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Cp());let n=[...qu];qu.clear();for(let o of n)try{o()}catch{}return t};var ju=()=>wW().then(YM);var Dr=()=>{if(Ha)return Ha;let t=xW();return t?YM(t):null},Xh=t=>Ha?()=>{}:(qu.add(t),()=>{qu.delete(t)});function jn(t){return t?.features?.artifacts?.enabled===!0}function QM(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!jn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function SW(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var XM=["panel","seamless","detached"];function Jh(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&XM.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Zh(t){return!t||!jn(t)?!1:Jh(t)==="detached"}function kc(t,e){if(!jn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),SW(t),QM(t,e);return}let n=e.features?.artifacts?.layout,o=Jh(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of a){let p=l?.trim();p?t.style.setProperty(d,p):t.style.removeProperty(d)}QM(t,e)}function Lc(t,e){for(let l of XM)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!jn(e))return;let n=e.features?.artifacts?.layout,o=Jh(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function JM(t,e){return!e||!jn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var AW=new Set(["__proto__","prototype","constructor"]),MW=new Set(["collapsed","card","panel","inline"]),ZM=new Set(["markdown","component"]),TW=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,bi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Gu=t=>!AW.has(t),ey=t=>typeof t=="string"&&MW.has(t),vi=t=>Object.keys(t).length>0;function dr(t,e,n,o){t.push({path:e,code:n,message:o})}var EW="Ignored because this key is not part of the persisted preference schema.",Ku="Ignored an unsupported value.",kW="Expected collapsed, panel, or inline.",LW='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',eT={kind:"mode",message:Ku},Ra={kind:"string",message:"Expected a CSS length string."},_r={kind:"boolean"},PW={paneWidth:Ra,paneMaxWidth:Ra,paneMinWidth:Ra,expandedPanelWidth:Ra,resizableMinWidth:Ra,resizableMaxWidth:Ra,expandLauncherPanelWhenOpen:_r,resizable:_r},IW={kind:"object",message:"Expected a preference object.",children:{showToolCalls:_r,showReasoning:_r,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ku},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ku},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ku},expandable:_r,grouped:_r}},reasoningDisplay:{kind:"object",children:{expandable:_r,activePreview:_r}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:eT,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:eT,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:ZM,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:ZM}}},filePreview:{kind:"object",children:{enabled:_r}},layout:{kind:"object",children:PW}}}}};function tT(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:dr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:dr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:dr(o,n,"invalid_value",e.message);case"mode":return ey(t)?Mo(t):dr(o,n,"invalid_value",e.message);case"modeMap":{if(!bi(t))return dr(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[a,l]of Object.entries(t)){let d=r?a:oa(a);Gu(a)&&(r?r.has(a):TW.test(d))?ey(l)?s[d]=Mo(l):dr(o,`${n}.${a}`,"invalid_value",kW):dr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":LW)}return vi(s)?s:void 0}case"object":{if(e.bareMode&&ey(t))return Mo(t);if(!bi(t))return dr(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!Gu(l)||!r.includes(l))&&dr(o,s(l),"unknown_key",EW);let a={};for(let l of r){let d=e.children[l],p=tT(t[l],d,s(l),o);if(d.deprecated&&t[l]!==void 0&&dr(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=bi(m)&&bi(p)?{...m,...p}:p}return vi(a)?a:void 0}}}function HW(t){let e=[];return{preferences:(t===null?void 0:tT(t,IW,"",e))??{},issues:e}}function Wa(t){if(Array.isArray(t))return t.map(Wa);if(!bi(t))return t;let e={};for(let[n,o]of Object.entries(t))Gu(n)&&o!==void 0&&(e[n]=Wa(o));return e}function nT(t,e){let n=Wa(t);for(let[o,r]of Object.entries(e)){if(!Gu(o)||r===void 0)continue;let s=n[o];n[o]=bi(s)&&bi(r)?nT(s,r):Wa(r)}return n}function RW(t){let e={},n;for(let r of t){let s=HW(r).preferences;n=oT(n,s.artifacts?.display),e=nT(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function WW(t,e){if(e===void 0)return t===void 0?void 0:Wa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...vi(r)?{byMediaType:r}:{}};return vi(s)?s:void 0}function oT(t,e){if(e===void 0)return t===void 0?void 0:Wa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=WW(n.files,e.files),a={...o?{default:o}:{},...vi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return vi(a)?a:void 0}function BW(t={},e){let n=RW(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=oT(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function ty(t){let e=t.preferences;return!e||!vi(e)?t:{...t,features:BW(t.features??{},[e])}}function OW(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function DW(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function _W(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function NW(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function ny(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function rT(t,e,n,o,r,s,a=200){let l=OW(r,200),d=NW(e,n,o,a);d=Math.max(l,d);let p=DW(s);return p!==null&&(d=Math.min(d,p)),_W(t,l,d)}oo();var{setLoader:Z$,load:FW,provide:ez,getSync:VW}=$t({fallbackImport:()=>Promise.resolve().then(()=>(lT(),aT))});var cT=FW;var dT=VW;var oy=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},ry=new oy;var pT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$W=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),uT=(t,e,n)=>{if(!pT(t)||!pT(e)||$W.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=uT(t[r],e[r],s)}return o};function mT(t,e){let n=uT(t,e,"");return Ep(n)}var fT=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var zW=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},UW=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},iy=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=zW(t),n=UW(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},sy=t=>typeof t=="string"?t:t==null?"":String(t),Pc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:sy(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=sy(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:sy(n.text)}}},gT=t=>Array.isArray(t)?t.map(e=>String(e)):[],ay=t=>{let e=new Set(gT(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(gT(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.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 l=a?t.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let d={action:l,message:s.message};t.emit("action:detected",d);for(let p of t.handlers)if(p)try{let u=()=>{t.emit("action:resubmit",d)},m=p(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});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(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var qW=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},jW=t=>t.map(e=>({...e,streaming:!1})),KW=t=>t.map(e=>({...e,status:"complete"})),hT=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?qW(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?jW(n.messages):void 0,artifacts:n.artifacts?KW(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var GW=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},yT=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return GW(t)},YW=async(t,e)=>{let n=await yT(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await yT(`${t}\0${e}`)}`}};var bT=(t,e,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,h=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},g=()=>{let E=h();if(!E)return p;try{return E.getItem(o)}catch{return a=!0,p}},b=(E,W)=>{if(l||E===p)return;let R=p;p=E,d+=1;let V={previousToken:R,token:E,source:W,revision:d};for(let H of m)H(V)},C=E=>{l||E.key!==null&&E.key!==o||b(E.key===null?null:E.newValue??null,"external")},S=(async()=>{let E=await YW(t,e);o=E.storageKey,r=E.leaseKey,s=E.lockName,p=g(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),P=E=>new Promise(W=>setTimeout(W,E)),M=()=>{let E=h();if(!E)return null;try{let W=E.getItem(r);if(!W)return null;let R=JSON.parse(W);return typeof R?.expiresAt=="number"&&typeof R?.ownerNonce=="string"?R:null}catch{return null}},B=E=>{let W=h();if(W)try{M()?.ownerNonce===E&&W.removeItem(r)}catch{}},A=E=>new Promise(W=>{let R=setTimeout(V,E);function V(){clearTimeout(R),window.removeEventListener("storage",H),W()}function H(w){(w.key===null||w.key===r)&&V()}window.addEventListener("storage",H)}),O=async E=>{let W=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,R=Date.now()+15e3;for(;Date.now()<R;){let V=h();if(!V)break;let H=Date.now(),w=M();if(w&&w.expiresAt>H&&w.ownerNonce!==W){await A(Math.min(w.expiresAt-H,500));continue}try{V.setItem(r,JSON.stringify({ownerNonce:W,expiresAt:H+1e4}))}catch{a=!0;break}if(await P(20+Math.random()*40),M()?.ownerNonce!==W){await A(500);continue}u=W;try{return await E()}finally{u=null,B(W)}}return E()};return{ready:S,async get(){return await S,b(g(),"external"),p},async set(E){await S;let W=h();if(W)try{W.setItem(o,E)}catch{a=!0}b(E,"local")},async clear(){await S;let E=h();if(E)try{E.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return d},subscribe(E){return m.add(E),()=>{m.delete(E)}},async withFirstInitLock(E){await S;let W=globalThis.navigator?.locks;return W?.request?W.request(s,()=>E()):h()?O(E):E()},matches(E,W,R){return E===t&&W===e&&R===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&B(u)}}};oo();var{setLoader:$z,load:wB}=$t({fallbackImport:()=>Promise.resolve().then(()=>(BT(),WT))});var by=wB;var vy=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Nr=t=>Object.freeze({...t}),OT=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),DT=t=>t?Nr(t):null;function _T(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let A of d.splice(0))try{A()}catch(O){vy("renderHistoryView cleanup",O)}},u=(A,O)=>{for(let E of e){let W=E[A];if(W)try{let R=W(O);if(R)return R}catch(R){vy(A,R)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),h={header:A=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Nr(A.identityStatus),pendingAction:DT(A.pendingAction),copy:Nr(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:OT(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...m(),state:Nr(A.state),identityStatus:Nr(A.identityStatus),copy:Nr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},g=e.flatMap(A=>(A.railSections??[]).map(O=>({...O,placement:O.placement??"above-conversations",items:[],render:E=>O.render(Object.freeze({collapsed:E,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:h,renderDom:!1,onModelChange:()=>B(),railSections:g}),C=Object.freeze({...b.operations,close:t.close}),S=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),P=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(OT)),activeConversationId:A.activeConversationId,state:Nr(A.state),pendingAction:DT(A.pendingAction),identityStatus:Nr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Nr(b.copy),actions:C,defaultRenderer:S,requestRender:()=>B(),onCleanup:O=>{d.push(O)}}),M=()=>{a=!1;let A=null;for(let E of e)if(E.renderHistoryView){try{A=E.renderHistoryView(P(b.getModel()))}catch(W){vy("renderHistoryView",W),A=null}if(A)break}let O=!A||A.contains(b.element);return a=O,b.setDomRenderEnabled(O),A??b.element};function B(){if(!(!s||o||r)){r=!0;try{p();let A=M();if(A===l)return;let O=l;l=A,t.onElementChanged(A,O)}finally{r=!1}}}return s=!0,B(),{view:b,get element(){return l??b.element},requestRender:B,dispose:()=>{o=!0,p()}}}var xB=null;function NT(){return xB}_l();var SB=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"]]),AB=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."]]),Cy=t=>AB.get(t)??"Conversation history is unavailable right now.";function MB(t){if(t instanceof sr)return t;if(t instanceof at){let e=SB.get(t.code)??"unavailable";return new sr(e,Cy(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new sr("unavailable",Cy("unavailable"))}function FT(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new sr("unsupported_scope",Cy("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw MB(p)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let p=await e().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=ww(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Bl([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>e().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}cy();Ye();var TB="button:not([disabled])";function em(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=$("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=$("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=$("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"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"}},$("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),$("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),$("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=$("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))"}},l);return new Promise(p=>{let u=!1,m=g=>{u||(u=!0,d.removeEventListener("keydown",h,!0),d.remove(),e?.focus(),p(g))};function h(g){if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),m(!1);return}if(g.key!=="Tab")return;let b=Array.from(l.querySelectorAll(TB));if(b.length===0)return;let C=b[0],S=b[b.length-1],P=document.activeElement;g.shiftKey&&(P===C||!l.contains(P))?(g.preventDefault(),S.focus()):!g.shiftKey&&P===S&&(g.preventDefault(),C.focus())}d.addEventListener("keydown",h,!0),d.addEventListener("pointerdown",g=>{g.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),t.host.appendChild(d),s.focus()})}wc();wc();var wy=require("partial-json");Ye();function VT(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=$o.get(t.component);if(!s){if(Qh.includes(t.component)){ju().catch(()=>{});let l=v("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function $T(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function xy(t){let e=$T(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function zT(t){let e=$T(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var EB=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function UT(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:p=EB}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,g.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),h.appendChild(g);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let E=1;E<=5;E++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${E} star${E>1?"s":""}: ${p[E-1]}`),W.title=p[E-1],W.dataset.rating=String(E),W.innerHTML=`
1169
+ `):""},Th=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},uR=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=n?.success===!1?n.error||"Tool failed":pR(t,o?.previewMaxLines??3),a=n?aw(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",d=e?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&d.activeTextTemplate?p=Qf(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=Qf(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},XA=(t,e,n)=>{Ru(t,e,{stateSet:Ea,previewKind:"tool",iconColor:QA(n?.toolCall??{})})},Eh=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=ku("persona-tool-bubble",t.id);if(o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&Ea.has(t.id),{summary:d,previewText:p,isActive:u}=uR(t,e),m=Lu({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),C=()=>{let w=v("span","");return w.setAttribute("data-tool-elapsed",b),w.textContent=Hl(n),w},S=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:Hl(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(g.textContent=S,h.appendChild(g)):S instanceof HTMLElement?h.appendChild(S):(g.textContent=d,h.appendChild(g));let P=s.loadingAnimation??"none",M=o.activeTextTemplate,B=o.completeTextTemplate,A=u?M:B,O=S instanceof HTMLElement,E=(w,T)=>{g.textContent="";let I=n.name?.trim()||"tool",D=dp(w,I),G=0;for(let z of D){let K=z.styles.length>0?(()=>{let Y=v("span",z.styles.map(re=>`persona-tool-text-${re}`).join(" "));return g.appendChild(Y),Y})():g;if(z.isDuration&&u)K.appendChild(C());else{let Y=z.isDuration?Hl(n):z.text;T?G=vs(K,Y,G):K.appendChild(document.createTextNode(Y))}}};if(!O)if(u&&P!=="none"){let w=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),P==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),A&&E(A,!1);else if(g.classList.add(`persona-tool-loading-${P}`),g.style.setProperty("--persona-tool-anim-duration",`${w}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),A)E(A,!0);else{let T=g.textContent||d;g.textContent="",vs(g,T,0)}}else A&&E(A,!1);let W=QA(o),R=Pu(m,h,{expandable:a,expanded:l,iconColor:W,metaGap:!0}),V=Iu({bubble:r,previewKind:"tool",expanded:l,isActive:u,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:p,isActive:u,config:e??{}})});if(!a)return r.append(m,V),r;let H=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=l?"":"none",o.contentBackgroundColor&&(H.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(H.style.color=o.contentTextColor),o.contentPaddingX&&(H.style.paddingLeft=o.contentPaddingX,H.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(H.style.paddingTop=o.contentPaddingY,H.style.paddingBottom=o.contentPaddingY),n.name){let w=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?w.style.color=o.contentTextColor:o.headerTextColor&&(w.style.color=o.headerTextColor),w.textContent=n.name,H.appendChild(w)}if(n.args!==void 0){let w=v("div","persona-space-y-1"),T=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(T.style.color=o.labelTextColor),T.textContent="Arguments";let I=v("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",Th(I,o),I.textContent=us(n.args),w.append(T,I),H.appendChild(w)}if(n.chunks&&n.chunks.length){let w=v("div","persona-space-y-1"),T=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(T.style.color=o.labelTextColor),T.textContent="Activity";let I=v("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",Th(I,o),I.textContent=n.chunks.join(""),w.append(T,I),H.appendChild(w)}if(n.success===!1&&H.appendChild($("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let w=v("div","persona-space-y-1"),T=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(T.style.color=o.labelTextColor),T.textContent="Result";let I=v("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",Th(I,o),I.textContent=us(n.result),w.append(T,I),H.appendChild(w)}if(n.status==="complete"&&typeof n.duration=="number"){let w=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(w.style.color=o.contentTextColor),w.textContent=`Duration: ${n.duration}ms`,H.appendChild(w)}return Hu({expanded:l,header:m,toggleIcon:R,content:H,collapsedPreview:V,iconColor:W}),r.append(m,V,H),r};ri();oo();var{setLoader:mV,load:vR,provide:fV,getSync:CR}=$t({fallbackImport:()=>Promise.resolve().then(()=>(iM(),sM))});var aM=vR;var lM=CR;na();oo();var{setLoader:PV,load:NR}=$t({fallbackImport:()=>Promise.resolve().then(()=>(CM(),vM))});var Dh=NR;oo();wc();ti();wp();var Qh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:$$,load:wW,provide:z$,getSync:xW}=$t({fallbackImport:()=>Promise.resolve().then(()=>(GM(),KM))}),Ha=null,qu=new Set,YM=t=>{if(Ha)return Ha;Ha=t,t.initArtifactsUi({componentRegistry:zo});for(let o of Qh)zo.has(o)||zo.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=Mo();e?t.__provideMarkdownParsers(e):ea(()=>{let o=Mo();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Cp());let n=[...qu];qu.clear();for(let o of n)try{o()}catch{}return t};var ju=()=>wW().then(YM);var Dr=()=>{if(Ha)return Ha;let t=xW();return t?YM(t):null},Xh=t=>Ha?()=>{}:(qu.add(t),()=>{qu.delete(t)});function jn(t){return t?.features?.artifacts?.enabled===!0}function QM(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!jn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function SW(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var XM=["panel","seamless","detached"];function Jh(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&XM.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Zh(t){return!t||!jn(t)?!1:Jh(t)==="detached"}function kc(t,e){if(!jn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),SW(t),QM(t,e);return}let n=e.features?.artifacts?.layout,o=Jh(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of a){let p=l?.trim();p?t.style.setProperty(d,p):t.style.removeProperty(d)}QM(t,e)}function Lc(t,e){for(let l of XM)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!jn(e))return;let n=e.features?.artifacts?.layout,o=Jh(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function JM(t,e){return!e||!jn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var AW=new Set(["__proto__","prototype","constructor"]),MW=new Set(["collapsed","card","panel","inline"]),ZM=new Set(["markdown","component"]),TW=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,bi=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Gu=t=>!AW.has(t),ey=t=>typeof t=="string"&&MW.has(t),vi=t=>Object.keys(t).length>0;function pr(t,e,n,o){t.push({path:e,code:n,message:o})}var EW="Ignored because this key is not part of the persisted preference schema.",Ku="Ignored an unsupported value.",kW="Expected collapsed, panel, or inline.",LW='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',eT={kind:"mode",message:Ku},Ra={kind:"string",message:"Expected a CSS length string."},_r={kind:"boolean"},PW={paneWidth:Ra,paneMaxWidth:Ra,paneMinWidth:Ra,expandedPanelWidth:Ra,resizableMinWidth:Ra,resizableMaxWidth:Ra,expandLauncherPanelWhenOpen:_r,resizable:_r},IW={kind:"object",message:"Expected a preference object.",children:{showToolCalls:_r,showReasoning:_r,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ku},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ku},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ku},expandable:_r,grouped:_r}},reasoningDisplay:{kind:"object",children:{expandable:_r,activePreview:_r}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:eT,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:eT,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:ZM,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:ZM}}},filePreview:{kind:"object",children:{enabled:_r}},layout:{kind:"object",children:PW}}}}};function tT(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:pr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:pr(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:pr(o,n,"invalid_value",e.message);case"mode":return ey(t)?To(t):pr(o,n,"invalid_value",e.message);case"modeMap":{if(!bi(t))return pr(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[a,l]of Object.entries(t)){let d=r?a:oa(a);Gu(a)&&(r?r.has(a):TW.test(d))?ey(l)?s[d]=To(l):pr(o,`${n}.${a}`,"invalid_value",kW):pr(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":LW)}return vi(s)?s:void 0}case"object":{if(e.bareMode&&ey(t))return To(t);if(!bi(t))return pr(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!Gu(l)||!r.includes(l))&&pr(o,s(l),"unknown_key",EW);let a={};for(let l of r){let d=e.children[l],p=tT(t[l],d,s(l),o);if(d.deprecated&&t[l]!==void 0&&pr(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=bi(m)&&bi(p)?{...m,...p}:p}return vi(a)?a:void 0}}}function HW(t){let e=[];return{preferences:(t===null?void 0:tT(t,IW,"",e))??{},issues:e}}function Wa(t){if(Array.isArray(t))return t.map(Wa);if(!bi(t))return t;let e={};for(let[n,o]of Object.entries(t))Gu(n)&&o!==void 0&&(e[n]=Wa(o));return e}function nT(t,e){let n=Wa(t);for(let[o,r]of Object.entries(e)){if(!Gu(o)||r===void 0)continue;let s=n[o];n[o]=bi(s)&&bi(r)?nT(s,r):Wa(r)}return n}function RW(t){let e={},n;for(let r of t){let s=HW(r).preferences;n=oT(n,s.artifacts?.display),e=nT(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function WW(t,e){if(e===void 0)return t===void 0?void 0:Wa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...vi(r)?{byMediaType:r}:{}};return vi(s)?s:void 0}function oT(t,e){if(e===void 0)return t===void 0?void 0:Wa(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=WW(n.files,e.files),a={...o?{default:o}:{},...vi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return vi(a)?a:void 0}function BW(t={},e){let n=RW(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=oT(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function ty(t){let e=t.preferences;return!e||!vi(e)?t:{...t,features:BW(t.features??{},[e])}}function OW(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function DW(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function _W(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function NW(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function ny(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function rT(t,e,n,o,r,s,a=200){let l=OW(r,200),d=NW(e,n,o,a);d=Math.max(l,d);let p=DW(s);return p!==null&&(d=Math.min(d,p)),_W(t,l,d)}oo();var{setLoader:Z$,load:FW,provide:ez,getSync:VW}=$t({fallbackImport:()=>Promise.resolve().then(()=>(lT(),aT))});var cT=FW;var dT=VW;var oy=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},ry=new oy;var pT=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$W=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),uT=(t,e,n)=>{if(!pT(t)||!pT(e)||$W.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=uT(t[r],e[r],s)}return o};function mT(t,e){let n=uT(t,e,"");return Ep(n)}var fT=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var zW=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},UW=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},iy=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=zW(t),n=UW(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},sy=t=>typeof t=="string"?t:t==null?"":String(t),Pc={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:sy(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=sy(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:sy(n.text)}}},gT=t=>Array.isArray(t)?t.map(e=>String(e)):[],ay=t=>{let e=new Set(gT(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(gT(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.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 l=a?t.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let d={action:l,message:s.message};t.emit("action:detected",d);for(let p of t.handlers)if(p)try{let u=()=>{t.emit("action:resubmit",d)},m=p(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});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(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var qW=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},jW=t=>t.map(e=>({...e,streaming:!1})),KW=t=>t.map(e=>({...e,status:"complete"})),hT=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?qW(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?jW(n.messages):void 0,artifacts:n.artifacts?KW(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var GW=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},yT=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return GW(t)},YW=async(t,e)=>{let n=await yT(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await yT(`${t}\0${e}`)}`}};var bT=(t,e,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,h=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},g=()=>{let E=h();if(!E)return p;try{return E.getItem(o)}catch{return a=!0,p}},b=(E,W)=>{if(l||E===p)return;let R=p;p=E,d+=1;let V={previousToken:R,token:E,source:W,revision:d};for(let H of m)H(V)},C=E=>{l||E.key!==null&&E.key!==o||b(E.key===null?null:E.newValue??null,"external")},S=(async()=>{let E=await YW(t,e);o=E.storageKey,r=E.leaseKey,s=E.lockName,p=g(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),P=E=>new Promise(W=>setTimeout(W,E)),M=()=>{let E=h();if(!E)return null;try{let W=E.getItem(r);if(!W)return null;let R=JSON.parse(W);return typeof R?.expiresAt=="number"&&typeof R?.ownerNonce=="string"?R:null}catch{return null}},B=E=>{let W=h();if(W)try{M()?.ownerNonce===E&&W.removeItem(r)}catch{}},A=E=>new Promise(W=>{let R=setTimeout(V,E);function V(){clearTimeout(R),window.removeEventListener("storage",H),W()}function H(w){(w.key===null||w.key===r)&&V()}window.addEventListener("storage",H)}),O=async E=>{let W=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,R=Date.now()+15e3;for(;Date.now()<R;){let V=h();if(!V)break;let H=Date.now(),w=M();if(w&&w.expiresAt>H&&w.ownerNonce!==W){await A(Math.min(w.expiresAt-H,500));continue}try{V.setItem(r,JSON.stringify({ownerNonce:W,expiresAt:H+1e4}))}catch{a=!0;break}if(await P(20+Math.random()*40),M()?.ownerNonce!==W){await A(500);continue}u=W;try{return await E()}finally{u=null,B(W)}}return E()};return{ready:S,async get(){return await S,b(g(),"external"),p},async set(E){await S;let W=h();if(W)try{W.setItem(o,E)}catch{a=!0}b(E,"local")},async clear(){await S;let E=h();if(E)try{E.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return d},subscribe(E){return m.add(E),()=>{m.delete(E)}},async withFirstInitLock(E){await S;let W=globalThis.navigator?.locks;return W?.request?W.request(s,()=>E()):h()?O(E):E()},matches(E,W,R){return E===t&&W===e&&R===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&B(u)}}};oo();var{setLoader:$z,load:wB}=$t({fallbackImport:()=>Promise.resolve().then(()=>(BT(),WT))});var by=wB;var vy=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Nr=t=>Object.freeze({...t}),OT=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),DT=t=>t?Nr(t):null;function _T(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let A of d.splice(0))try{A()}catch(O){vy("renderHistoryView cleanup",O)}},u=(A,O)=>{for(let E of e){let W=E[A];if(W)try{let R=W(O);if(R)return R}catch(R){vy(A,R)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),h={header:A=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:Nr(A.identityStatus),pendingAction:DT(A.pendingAction),copy:Nr(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:OT(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...m(),state:Nr(A.state),identityStatus:Nr(A.identityStatus),copy:Nr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},g=e.flatMap(A=>(A.railSections??[]).map(O=>({...O,placement:O.placement??"above-conversations",items:[],render:E=>O.render(Object.freeze({collapsed:E,presentation:t.getPresentation(),actions:C}))}))),b=t.createView({slots:h,renderDom:!1,onModelChange:()=>B(),railSections:g}),C=Object.freeze({...b.operations,close:t.close}),S=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),P=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(OT)),activeConversationId:A.activeConversationId,state:Nr(A.state),pendingAction:DT(A.pendingAction),identityStatus:Nr(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Nr(b.copy),actions:C,defaultRenderer:S,requestRender:()=>B(),onCleanup:O=>{d.push(O)}}),M=()=>{a=!1;let A=null;for(let E of e)if(E.renderHistoryView){try{A=E.renderHistoryView(P(b.getModel()))}catch(W){vy("renderHistoryView",W),A=null}if(A)break}let O=!A||A.contains(b.element);return a=O,b.setDomRenderEnabled(O),A??b.element};function B(){if(!(!s||o||r)){r=!0;try{p();let A=M();if(A===l)return;let O=l;l=A,t.onElementChanged(A,O)}finally{r=!1}}}return s=!0,B(),{view:b,get element(){return l??b.element},requestRender:B,dispose:()=>{o=!0,p()}}}var xB=null;function NT(){return xB}_l();var SB=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"]]),AB=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."]]),Cy=t=>AB.get(t)??"Conversation history is unavailable right now.";function MB(t){if(t instanceof ir)return t;if(t instanceof at){let e=SB.get(t.code)??"unavailable";return new ir(e,Cy(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new ir("unavailable",Cy("unavailable"))}function FT(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new ir("unsupported_scope",Cy("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw MB(p)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let p=await e().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=ww(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Bl([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>e().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}cy();Ye();var TB="button:not([disabled])";function em(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=$("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=$("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=$("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"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"}},$("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),$("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),$("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=$("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))"}},l);return new Promise(p=>{let u=!1,m=g=>{u||(u=!0,d.removeEventListener("keydown",h,!0),d.remove(),e?.focus(),p(g))};function h(g){if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),m(!1);return}if(g.key!=="Tab")return;let b=Array.from(l.querySelectorAll(TB));if(b.length===0)return;let C=b[0],S=b[b.length-1],P=document.activeElement;g.shiftKey&&(P===C||!l.contains(P))?(g.preventDefault(),S.focus()):!g.shiftKey&&P===S&&(g.preventDefault(),C.focus())}d.addEventListener("keydown",h,!0),d.addEventListener("pointerdown",g=>{g.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),t.host.appendChild(d),s.focus()})}wc();wc();var wy=require("partial-json");Ye();function VT(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=zo.get(t.component);if(!s){if(Qh.includes(t.component)){ju().catch(()=>{});let l=v("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function $T(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function xy(t){let e=$T(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function zT(t){let e=$T(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var EB=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function UT(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:p=EB}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,g.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),h.appendChild(g);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let E=1;E<=5;E++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${E} star${E>1?"s":""}: ${p[E-1]}`),W.title=p[E-1],W.dataset.rating=String(E),W.innerHTML=`
1170
1170
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1171
1171
  <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>
1172
1172
  </svg>
1173
- `,W.addEventListener("click",()=>{m=E,P.forEach((R,V)=>{let H=V<E;R.classList.toggle("selected",H),R.setAttribute("aria-checked",V===E-1?"true":"false")})}),P.push(W),S.appendChild(W)}h.appendChild(S);let M=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=s,M.rows=3,M.setAttribute("aria-label","Additional comments"),E.appendChild(M),h.appendChild(E)}let B=document.createElement("div");B.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let E=M?.value.trim()||void 0;await e(m,E),u.remove()}catch(E){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",E)}}),B.appendChild(A),B.appendChild(O),h.appendChild(B),u.appendChild(h),u}function qT(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=t,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,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,b.appendChild(S),g.appendChild(b);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,M.appendChild(B),M.appendChild(A);let O=document.createElement("div");O.className="persona-feedback-numbers";let E=[];for(let w=0;w<=10;w++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-number-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`Rating ${w} out of 10`),T.textContent=String(w),T.dataset.rating=String(w),w<=6?T.classList.add("persona-feedback-detractor"):w<=8?T.classList.add("persona-feedback-passive"):T.classList.add("persona-feedback-promoter"),T.addEventListener("click",()=>{h=w,E.forEach((I,D)=>{I.classList.toggle("selected",D===w),I.setAttribute("aria-checked",D===w?"true":"false")})}),E.push(T),O.appendChild(T)}P.appendChild(M),P.appendChild(O),g.appendChild(P);let W=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),w.appendChild(W),g.appendChild(w)}let R=document.createElement("div");R.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=l,V.addEventListener("click",()=>{n?.(),m.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let w=W?.value.trim()||void 0;await e(h,w),m.remove()}catch(w){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",w)}}),R.appendChild(V),R.appendChild(H),g.appendChild(R),m.appendChild(g),m}var Ba="persona-chat-history",PB=30*1e3,IB=641,Oa="data-persona-composer-reason",HB={"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 RB(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=HB[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function tm(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function WB(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function BB(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Sy=t=>!t||typeof t!="object"?{}:{...t},jT=t=>t.map(e=>({...e,streaming:!1})),KT=(t,e,n)=>{let o=t?.markdown?Qd(t.markdown):null,r=Jd(t?.sanitize);t?.postprocessMessage&&r&&t?.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 s=!1,a=l=>{let d=l.text??"",p=l.message.rawContent??null;if(e){let h=e.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});h!==null&&(d=h.text,h.persist||(l.message.__skipPersist=!0),h.resubmit&&!l.streaming&&n&&n())}let u=Ao()!==null,m;if(t?.postprocessMessage){let h=t.postprocessMessage({...l,text:d,raw:p??l.text??""});m=r?r(h):h}else if(o){let h=l.streaming?AC(d):d,g=o(h);m=r&&u?r(g):g}else m=Pr(d);return m};return l=>{try{return a(l)}catch(d){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),Pr(l.text??"")}}};function GT(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=Ie(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var OB=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},DB=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:OB(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),YT=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Ep(e),r=()=>{ix({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=ty(o);let a=ry.getForInstance(o.plugins),l=FS(t),d=[],p=!1,u=GA(()=>o),m=null,h=null,g=null,b=!1,C=null,S=i=>{m=i,i.initApprovalUi({webMcpToolTitle:Zd});let c=i.createBuiltInApprovalPlugin();h=c.plugin,g=c.teardown},P=()=>{if(m)return m;let i=lM();return i?(S(i),i):(aM().then(c=>{b||m||(S(c),C?.())}).catch(()=>{}),null)},M=!1,B=!1,A=null,O=(i,c,f,y)=>{if(!i.querySelector("[data-tv-form]"))return;let x=dT();if(x){x.enhanceWithForms(i,c,f,y);return}cT().then(()=>{M||B||!A||(B=!0,A())}).catch(()=>{})};o.components&&$o.registerAll(o.components);let E=fT(),R=o.persistState===!1?null:o.storageAdapter??hT(),V=!!o.clientToken&&typeof o.reconnectStream!="function",H={},w=null,T,I=new Promise(i=>{T=i}),D,G=!1,z=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:f,open:y}=c;return y&&(G=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(R?.load)try{let i=R.load();if(i&&typeof i.then=="function")w=i.then(c=>z(c??{messages:[],metadata:{}}));else{let f=z(i??{messages:[],metadata:{}});f.metadata&&(H=Sy(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),D=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=z({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}w||T();let K=()=>H,Y=i=>{H=i({...H})??{},Wi()},re=o.actionParsers&&o.actionParsers.length?o.actionParsers:[iy],oe=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pc.message,Pc.messageAndClick],se=ay({parsers:re,handlers:oe,getSessionMetadata:K,updateSessionMetadata:Y,emit:E.emit,documentRef:typeof document<"u"?document:null});se.syncFromMetadata();let ce=o.launcher?.enabled??!0,we=o.launcher?.autoExpand??!1,ge=o.autoFocusInput??!1,N=we,ye=ce,ke=o.layout?.header?.layout,nt=!1,Ee=()=>pc(o),Ne=()=>ce||Ee(),Pe=Ee()?!1:ce?we:!0,dt=!1,Xe=null,xt=()=>{dt=!0,Xe&&clearTimeout(Xe),Xe=setTimeout(()=>{dt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),dt=!1)},1e4)},Ge=KT(o,se,xt),yt=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,L=o.features?.showEventStreamToggle??!1,j=o.features?.scrollToBottom??{},J=o.features?.scrollBehavior??{},Q=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Me=`${Q()}event-stream`,Te=null,Fe=o.features?.eventStream?.maxEvents??2e3,je=null,lt=null,ot=null,Je=!1,mt=null,Tt=!1,ee=null,Oe=0,$e=(i,c)=>{je?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},pt=(i,c)=>{lt?.processEvent(i,c),je?$e(i,c):ot&&(ot.length>=Fe&&ot.shift(),ot.push({type:i,payload:c}))},_t=()=>{je||!L||(ot??(ot=[]),Dh().then(i=>{if(Je||je||!L)return;Te=new i.EventStreamStore(Me),je=new i.EventStreamBuffer(Fe,Te),lt=lt??new i.ThroughputTracker,Te.open().then(()=>je?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let c=ot??[];ot=null;for(let f of c)lt?.processEvent(f.type,f.payload),$e(f.type,f.payload)}).catch(()=>{}))};L&&_t();let ve=!1,Se=null,Ke=()=>{},ut=()=>{},vn=()=>{},Cn=()=>{},wn=()=>{},Wt=()=>Tt||ve&&Se==="panel",St={onCopy:i=>{E.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{E.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},Et=o.statusIndicator??{},sn=i=>i==="idle"?Et.idleText??fn.idle:i==="connecting"?Et.connectingText??fn.connecting:i==="connected"?Et.connectedText??fn.connected:i==="error"?Et.errorText??fn.error:i==="paused"?Et.pausedText??fn.paused:i==="resuming"?Et.resumingText??fn.resuming:fn[i];function Rn(i,c,f,y){if(!i.hasAttribute(Oa))if(y==="idle"&&f.idleLink){i.textContent="";let x=document.createElement("a");x.href=f.idleLink,x.target="_blank",x.rel="noopener noreferrer",x.textContent=c,x.style.color="inherit",x.style.textDecoration="none",i.appendChild(x)}else i.textContent=c}let tn=KA({config:o,showClose:Ne()}),{wrapper:it,panel:_e,pillRoot:Kt}=tn.shell,Ze=tn.panelElements,{container:Le,body:ie,messagesWrapper:Re,starterSuggestions:wi,transcriptSuggestions:Vr,suggestions:Po,textarea:Ae,sendButton:Ve,composerForm:Wn,statusText:bt,welcomeHost:an,welcomeIconHolder:_a,greetingHost:kn,introKicker:Na,introTitle:om,introSubtitle:rm,closeButton:F,iconHolder:le,headerTitle:Be,headerSubtitle:et,header:he,footer:We,actionsRow:zo}=Ze,Uo=Ze.leftActions,$r=Ze.rightActions,qo=Ze.sendButtonWrapper,Py=Ze.setSendButtonMode,fe=Ze.micButton,io=Ze.micButtonWrapper,Gt=Ze.attachmentButton,Kn=Ze.attachmentButtonWrapper,zt=Ze.attachmentInput,Gn=Ze.attachmentPreviewsContainer;Le.classList.add("persona-relative"),ie.classList.add("persona-relative");let lE=12,Fa=()=>j.label??"",cE=()=>j.iconName??"arrow-down",dE=()=>j.enabled!==!1,ao=()=>J.mode??"anchor-top",zr=()=>ao()==="follow"||ao()==="anchor-top"&&Qa,Va=()=>J.anchorTopOffset??16,pE=()=>J.restorePosition??"bottom",Iy=()=>J.pauseOnInteraction===!0,Hy=()=>J.showActivityWhilePinned!==!1,Ry=()=>J.announce===!0,sm=()=>J.scrollbar??"on-scroll",ln=v("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");ln.type="button",ln.style.display="none",ln.setAttribute("data-persona-scroll-to-bottom","true");let $a=v("span","persona-flex persona-items-center"),im=v("span",""),As=v("span","");As.setAttribute("data-persona-scroll-to-bottom-count",""),As.style.display="none",ln.append($a,im,As),Le.appendChild(ln);let ho=v("div","persona-stream-anchor-spacer");ho.setAttribute("aria-hidden","true"),ho.setAttribute("data-persona-anchor-spacer",""),ho.style.flexShrink="0",ho.style.pointerEvents="none",ho.style.height="0px",ho.style.display="none",ie.appendChild(ho);let ur=v("div","persona-sr-only");ur.setAttribute("aria-live","polite"),ur.setAttribute("aria-atomic","true"),ur.setAttribute("role","status"),ur.setAttribute("data-persona-live-region",""),Object.assign(ur.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Le.appendChild(ur);let za=null,Dc=null,_c=i=>{!Ry()||!i||(Dc=i,za===null&&(za=setTimeout(()=>{za=null,Dc&&Ry()&&(ur.textContent=Dc),Dc=null},400)))},Nc="empty",Fc=0,am=()=>Fc||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Ms=()=>{let c=We.style.display==="none"?0:We.offsetHeight;ln.style.bottom=`${c+am()+lE}px`};Ms();let lm=()=>{Ti||(We.style.marginBottom=Fc>0?`${Fc}px`:"")},Vc=()=>{let i=Gg(o,Ee()),c=Br(o),y=We.style.display==="none"?0:We.offsetHeight,x=c.anchor==="center"&&Nc==="empty"?ec(c.anchorComposerTop)??ec("44%"):null,k=x===null||Ee()?0:DS({columnHeight:Le.clientHeight,footerHeight:y,fraction:x});t.style.setProperty("--persona-composer-overlay-height",`${y}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?k:0}px`),Fc=i==="block"?k:0,lm(),Ms()},Wy=()=>{let i=!!Fa();ln.setAttribute("aria-label",Fa()||"Jump to latest"),ln.title=Fa(),ln.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),$a.innerHTML="";let c=Ie(cE(),"14px","currentColor",2);c?($a.appendChild(c),$a.style.display=""):$a.style.display="none",im.textContent=Fa(),im.style.display=i?"":"none"};Wy();let At=null,nn=null,ze=ex(),uE=i=>{try{Le.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ze.subscribe(uE);let jo=()=>{ze.setText(Ae?.value??"")},Ts=()=>{ze.setMentionRefs(nn?.getMentionRefs()??[])},mE=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),By=i=>{let c=Object.freeze(i.map(mE));ze.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Bm()};ze.setSelectedModelId(o.composer?.selectedModelId);let Ua=()=>o.composer?.modes??[],xi=()=>Ix(Ua(),o.composer?.modeGroups);{let i=$p(o.composer?.defaultActiveModeIds??[],Ua());i.length&&ze.setActiveModeIds(i)}function Oy(i){if(ze.getState().selectedModelId!==i){ze.setSelectedModelId(i),Ur?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function $c(i){ze.setActiveModeIds(i),mr?.render(i,xi()),Si.forEach(c=>c.repaint()),Go?.resolve(),md(),Io()}function cm(i){$c(Hx(ze.getState().activeModeIds,i,Ua(),o.composer?.modeGroups))}let Ur=null,dm=null,mr=null,Si=new Map,qr=null;function Ko(i){ze.setQuote(i),qr?.render(ze.getState().quote),Io(),kb()}let Dy=!1;function pm(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Dy&&o.debug===!0&&(Dy=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let jr=null;function Ai(i){ze.setPendingSubmission(i),jr?.render(ze.getState().pendingSubmission),Io()}let fE=i=>{let c=Si.get(i);if(c)return c;let f=Bx({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(y=>y.id===i),getModes:()=>Ua().filter(y=>y.groupId===i),getActiveIds:()=>ze.getState().activeModeIds,onSelect:y=>cm(y)});return Si.set(i,f),f},gE=()=>{let i=[],c=ze.getState().activeModeIds,f=new Set;if(Ua().forEach((y,x)=>{if(Vp(y.groupId,o.composer?.modeGroups)){let k=y.groupId;if(f.has(k))return;f.add(k);let q=fE(k);q.action.order=Ig(x),q.action.label=o.composer?.modeGroups?.find(te=>te.id===k)?.label??k,i.push(q.action);return}i.push({id:Lx(y.id),kind:"button",placement:"start",order:Ig(x),presentation:y.presentation??"auto",label:y.label,shortLabel:y.shortLabel,iconName:y.iconName,pressed:c.includes(y.id),onSelect:()=>cm(y.id)})}),o.composer?.models?.length&&!a.some(y=>y.renderComposer)){let y=o.composer?.modelPicker?.presentation??"native";(!Ur||dm!==y)&&(dm=y,Ur=Ex({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ze.getState().selectedModelId,onSelect:x=>Oy(x),presentation:y,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Ur.action)}return i},um=null,_y=a.find(i=>i.renderHeader);if(_y?.renderHeader){let i=_y.renderHeader({config:o,defaultRenderer:()=>{let c=li({config:o,showClose:Ne()});return mc(Le,c,o),c.header},onClose:()=>Nt(!1,"user")});if(i){let c=he;c&&(c.replaceWith(i),he=i,tn.header.element=i)}}let Ny=()=>{mt&&(ie.style.display="none",We.parentNode?.insertBefore(mt.element,We),mt.update())},mm=()=>{if(!je){_t();return}if(Tt=!0,mt?Ny():Dh().then(c=>{mt||!Tt||!je||(mt=c.createEventStreamView({buffer:je,getFullHistory:()=>je.getAllFromStore(),onClose:()=>Mi(),config:o,plugins:a,getThroughput:()=>lt?.getMetric()??{status:"idle"},renderIconByName:Ie}),Ny())}).catch(()=>{Mi()}),kt){kt.style.boxShadow=`inset 0 0 0 1.5px ${Un.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&kt.classList.add(f))}let i=()=>{if(!Tt)return;let c=Date.now();c-Oe>=200&&(mt?.update(),Oe=c),ee=requestAnimationFrame(i)};Oe=0,ee=requestAnimationFrame(i),yn(),E.emit("eventStream:opened",{timestamp:Date.now()})},Mi=()=>{if(Tt){if(Tt=!1,mt&&mt.element.remove(),ie.style.display="",kt){kt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&kt.classList.remove(c))}ee!==null&&(cancelAnimationFrame(ee),ee=null),yn(),E.emit("eventStream:closed",{timestamp:Date.now()})}},kt=null;if(L){let i=o.features?.eventStream?.classNames,c="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"+(i?.toggleButton?" "+i.toggleButton:"");kt=v("button",c),kt.style.width="28px",kt.style.height="28px",kt.style.color=Un.actionIconColor,kt.type="button",kt.setAttribute("aria-label","Event Stream"),kt.title="Event Stream";let f=Qe(Fr.Activity,"18px","currentColor",1.5);f&&kt.appendChild(f);let y=Ze.clearChatButtonWrapper,x=Ze.closeButtonWrapper,k=y||x;k&&k.parentNode===he?he.insertBefore(kt,k):he.appendChild(kt),kt.addEventListener("click",()=>{Tt?Mi():mm()})}let Fy=i=>{let c=o.attachments;if(!c?.enabled)return;let f=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!f){f=v("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 x=i.querySelector("[data-persona-composer-form]");x?.parentNode?x.parentNode.insertBefore(f,x):i.insertBefore(f,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let x=v("input");x.type="file",x.setAttribute("data-persona-composer-attachment-input",""),x.accept=(c.allowedTypes??Hr).join(","),x.multiple=(c.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(x)}},Ti=!1,Vy=i=>{let c=a.find(x=>x.renderComposer);if(!c?.renderComposer)return null;let f=o.composer,y=p?_.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>eC(),storage:u(c.id),onSubmit:x=>{!_||_.isStreaming()||Fd(x.trim(),{consumeDraft:!1})},streaming:y,disabled:y,openAttachmentPicker:()=>{Jo()||zt?.click()},models:f?.models,selectedModelId:ze.getState().selectedModelId??f?.selectedModelId,onModelChange:x=>Oy(x),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{um?.()}:void 0})},$y=Vy(()=>gc({config:o}).footer);$y&&(tn.replaceComposer($y),We=tn.composer.footer,Ti=!0);let Lt=null,hE=i=>{Wn=i.form,Ae=i.input,qo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ve=i.sendButton),i.micButton&&(fe=i.micButton,io=i.micButton.parentElement),i.found.status&&(bt=i.found.status),i.found.suggestions&&(Po=i.found.suggestions),i.attachmentButton&&(Gt=i.attachmentButton,Kn=i.attachmentButton.parentElement),zt=i.attachmentInput??null,Gn=i.attachmentPreviews??null,i.found.actionsRow&&(zo=i.found.actionsRow),Uo=i.found.actionsStart,$r=i.found.actionsEnd};function fm(){let i=Ae;if(!i)return;let c=o.composer?.inputAttributes,f=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Pp(i,c),f&&i.setAttribute("aria-label",f),Lp(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(i)}),ux(i,kp(o.composer?.maxLines,Ee()?5:3))}let zy=i=>{Lt=nx(i,{debug:o.debug===!0}),Lt&&hE(Lt),fm()};Fy(We),zy(We),jo();let qa=ys(o,Ee());qa&&(Re.style.maxWidth=qa,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",kn.style.maxWidth=qa,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%",wi.style.maxWidth=qa,Vr.style.maxWidth=qa,Vr.style.marginLeft="auto",Vr.style.marginRight="auto",Vr.style.width="100%");let Uy=()=>{let i=ys(o,Ee());if(!(!i||Ee()))for(let c of[Wn,Po,Gn,bt])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Uy();let qy=()=>{!o.attachments?.enabled||!zt||!Gn||(At?At.remountPreviews(Gn):(At=$l.fromConfig(o.attachments,By),At.setPreviewsContainer(Gn)),Lt?.addListener(zt,"change",i=>{let c=i.target;At?.handleFileSelect(c.files),c.value=""}),Le.querySelector(".persona-attachment-drop-overlay")||Le.appendChild(GT(o.attachments.dropOverlay)))};qy();let yE=()=>nn?.prefetch(),jy=()=>{if(!o.contextMentions?.enabled||!Ae)return;let i=Lt?.header??null,c=i?Pg(i):void 0;if(nn=PS({config:o,textarea:Ae,anchor:Wn??Ae,getMessages:()=>_.getMessages(),liveRegionHost:Le,chipRow:c}),nn&&!c){let f=Ae;f.parentElement?.insertBefore(nn.contextRow,f)}};jy();let Go=null,bE={getState:()=>ze.getState(),getValue:()=>Ae?.value??"",setValue:i=>{Ae&&(Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),jo())},submit:()=>{jl(Lt?.form??null)},openAttachmentPicker:()=>{Jo()||zt?.click()},toggleVoice:()=>{um?.()},requestRender:()=>Go?.resolve()},vE=()=>{let i=[];return(nn?.affordanceButtons??[]).forEach((f,y)=>{i.push({id:`core:mention-${y}`,placement:"start",order:ar.mention+y,element:f,managed:!0})}),Kn&&i.push({id:"core:attachment",placement:"start",order:ar.attachment,element:Kn}),io&&i.push({id:"core:mic",placement:"end",order:ar.mic,element:io}),qo&&i.push({id:"core:send",placement:"end",order:ar.send,element:qo}),i},Ky=()=>{Go?.destroy(),Go=Ax({getBindings:()=>Lt,collect:()=>({builtIns:vE(),configActions:[...gE(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>ze.getState(),requestRender:()=>Go?.resolve()},debug:o.debug===!0}),actionContext:bE,getState:()=>ze.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Go.resolve()};Ky();let gm=()=>{if(mr?.destroy(),mr=null,!xi().length)return;let i=Lt?.header;i&&(mr=kx({row:Pg(i),onRemove:c=>cm(c),initialIds:ze.getState().activeModeIds}),mr.render(ze.getState().activeModeIds,xi()))};gm();let Gy=()=>{qr?.destroy(),qr=null,jr?.destroy(),jr=null;let i=Lt?.header;i&&(qr=Ox({onDismiss:()=>Ko(void 0)}),i.appendChild(qr.element),qr.render(ze.getState().quote),pm()==="defer-one"&&(jr=Dx({onEdit:()=>Kk(),onRemove:()=>Ai(void 0)}),i.appendChild(jr.element),jr.render(ze.getState().pendingSubmission)))};Gy();let hm=zx(),CE=()=>{let i=Lt?.header?.querySelector(Lg);if(i)return i.childElementCount>0;let c=ze.getState();return c.mentionRefs.length>0||$p(c.activeModeIds,xi()).length>0},Yy=()=>!1;function Io(){let i=ze.getState(),c=hm.observe(Ux(Ae),i.text);We.toggleAttribute("data-persona-composer-compact",$x({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:CE(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:Yy()}))}function Qy(){o.composer?.layout==="single-row"&&!Ee()?We.setAttribute("data-persona-composer-layout","single-row"):We.removeAttribute("data-persona-composer-layout")}Qy(),ze.subscribe(()=>{Go?.sync(),Bm(),pd(),Io(),kb()}),pd();let Xy=!1,wE=i=>{if(Xy||o.debug!==!0)return;let c=["messages","composer"].filter(f=>i[f]);c.length&&(Xy=!0,console.warn(`[persona] layout.slots.${c.join(" and layout.slots.")} ${c.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 i=o.layout?.slots??{};wE(i);let c=y=>{switch(y){case"body-top":return ie.querySelector("[data-persona-intro-card]");case"messages":return Re;case"footer-top":return Po;case"composer":return Wn;case"footer-bottom":return bt;default:return null}},f=(y,x)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")he.insertBefore(x,he.firstChild);else if(y==="header-right")he.appendChild(x);else{let k=he.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(x,k.nextSibling):he.appendChild(x)}break;case"body-top":{let k=ie.querySelector("[data-persona-intro-card]");k?k.replaceWith(x):ie.insertBefore(x,ie.firstChild);break}case"body-bottom":ie.appendChild(x);break;case"footer-top":Po.replaceWith(x);break;case"footer-bottom":bt.replaceWith(x);break;default:break}};for(let[y,x]of Object.entries(i))if(x)try{let k=x({config:o,defaultContent:()=>c(y)});k&&f(y,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,k)}})();let Jy=i=>{let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let y=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let k=f.getAttribute("data-bubble-type");if(k==="reasoning")Ta.has(x)?Ta.delete(x):Ta.add(x),YA(x,y);else if(k==="tool")Ea.has(x)?Ea.delete(x):Ea.add(x),XA(x,y,o);else if(k==="approval"&&m){let te=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Z=m.approvalDetailsExpansionState.get(x)??te;m.approvalDetailsExpansionState.set(x,!Z),m.updateApprovalDetailsUI(x,y,o)}cn.delete(x)};Re.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Jy(i))}),Re.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Jy(i))}),Re.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let f=Re.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let x=y.toString(),k=$S(x);!k||k===x||(c.setData("text/plain",k),i.preventDefault())});let ym=new Map,Zy=null,eb="idle",xE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},SE=(i,c)=>{let{icon:f,label:y}=xE[c];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let x=Ie(f,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},tb=()=>{Re.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let y=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;SE(c,y&&y===Zy?eb:"idle")})};Re.addEventListener("click",i=>{let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest("[data-actions-for]");if(!y)return;let x=y.getAttribute("data-actions-for");if(!x)return;let k=f.getAttribute("data-action");if(k==="copy"){let te=_.getMessages().find(Z=>Z.id===x);if(te&&St.onCopy){let Z=te.content||"";navigator.clipboard.writeText(Z).then(()=>{f.classList.add("persona-message-action-success");let ne=Qe(Fr.Check,14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let pe=Qe(Fr.Copy,14,"currentColor",2);pe&&(f.innerHTML="",f.appendChild(pe))},2e3)}).catch(ne=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ne)}),St.onCopy(te)}}else if(k==="read-aloud")_.toggleReadAloud(x);else if(k==="upvote"||k==="downvote"){let te=(ym.get(x)??null)===k,Z=k==="upvote"?"thumbs-up":"thumbs-down";if(te){ym.delete(x),f.classList.remove("persona-message-action-active");let ne=Ie(Z,14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne))}else{let ne=k==="upvote"?"downvote":"upvote",pe=y.querySelector(`[data-action="${ne}"]`);if(pe){pe.classList.remove("persona-message-action-active");let Ft=Ie(ne==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ft&&(pe.innerHTML="",pe.appendChild(Ft))}ym.set(x,k),f.classList.add("persona-message-action-active");let Ce=Ie(Z,14,"currentColor",2);Ce&&(Ce.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(Ce)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let wt=_.getMessages().find(Ot=>Ot.id===x);wt&&St.onFeedback&&St.onFeedback({type:k,messageId:wt.id,message:wt})}}else if(k==="regenerate")zc?.regenerate(x);else if(k==="edit")zc?.edit(x);else if(k==="quote")zc?.quote(x);else if(k?.startsWith(xu)){let q=k.slice(xu.length),te=o.messageActions?.custom?.find(ne=>ne.id===q),Z=_.getMessages().find(ne=>ne.id===x);if(!te||!Z)return;try{te.onSelect(Z)}catch(ne){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,ne)}}});let zc=null;Re.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest(".persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let k=f.getAttribute("data-approval-action");if(!k)return;let q=k==="approve"?"approved":"denied",Z=_.getMessages().find(pe=>pe.id===x);if(!Z?.approval)return;let ne=y.querySelector("[data-approval-buttons]");ne&&ne.querySelectorAll("button").forEach(Ce=>{Ce.disabled=!0,Ce.style.opacity="0.5",Ce.style.cursor="not-allowed"}),Z.approval.toolType==="webmcp"?_.resolveWebMcpApproval(x,q):_.resolveApproval(Z.approval,q)});let ft=null,nb=!1,ja=null,Es=()=>{},Ka="none",Uc=null,yo={artifacts:[],selectedId:null},fr=!1,Ho=!1,Ga=!1,Ei=!1,ob=()=>Ei||yo.artifacts.some(i=>is(o.features?.artifacts,i)==="panel"),qc=()=>yo.artifacts.length>0&&!fr&&ob(),Bt={current:null},bm=(i,c)=>{let f=_.getArtifactById(c),y=f?.markdown,x=f?.title||"artifact",k=f?.file,q=f?.artifactType??"markdown";if(!y){let ne=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ne){let Ce=_.getMessages().find(He=>He.id===ne);if(Ce?.rawContent)try{let He=JSON.parse(Ce.rawContent);y=He?.props?.markdown,x=He?.props?.title||x,He?.props?.file&&typeof He.props.file=="object"&&(k=He.props.file),!f&&typeof He?.props?.artifactType=="string"&&(q=He.props.artifactType)}catch{}}}return{markdown:y,title:x,file:k,artifactType:q}};Re.addEventListener("click",i=>{let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:k,title:q,file:te}=bm(f,y);if(!k)return;let Z=Dr();Z&&Z.triggerArtifactDownload(Z.downloadInfoFor({title:q,markdown:k,file:te}))}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-artifact-custom-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-artifact-custom-action");if(!y)return;let x=f.closest("[data-artifact-inline]"),k=x?null:f.closest("[data-open-artifact]"),q=x?x.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Z=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Ot=>Ot.id===y);if(!Z)return;let{markdown:ne,title:pe,file:Ce,artifactType:He}=bm(f,q??""),wt={artifactId:q,title:pe,artifactType:He,markdown:ne,file:Ce};try{Promise.resolve(Z.onClick(wt)).catch(()=>{})}catch{}}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-copy-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-copy-artifact");if(!y)return;let x=_.getArtifactById(y),k=Dr();if(!k)return;let q="";if(x)q=k.artifactCopyText(x);else{let{markdown:te,file:Z,artifactType:ne}=bm(f,y);ne==="markdown"&&(q=k.artifactCopyText({id:y,artifactType:"markdown",status:"complete",markdown:te??"",...Z?{file:Z}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let te=Qe(Fr.Check,16,"currentColor",2);te&&(f.replaceChildren(te),setTimeout(()=>{let Z=Qe(Fr.Copy,16,"currentColor",2);Z&&f.replaceChildren(Z)},1500))}).catch(()=>{})}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-expand-artifact-inline]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(fr=!1,Ei=!0,Ho=!0,Ga=!0,_.selectArtifact(y),Ro())}),Re.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let f=c.closest("[data-open-artifact]");if(!f)return;let y=f.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),fr=!1,Ei=!0,_.selectArtifact(y),Ro())}),Re.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let ki=Ze.composerOverlay,Li=(i,c,f)=>{let y=c.trim();if(!y||!Bt.current)return;let x=i.getAttribute("data-tool-call-id")??"",k=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:x,answer:y,answers:f.structured,values:f.values??(f.source==="multi"?y.split(", "):[y]),isFreeText:k,source:f.source},bubbles:!0,composed:!0})),la(ki,x);let q=Bt.current.getMessages().find(te=>te.toolCall?.id===x);q?.agentMetadata?.awaitingLocalTool?Bt.current.resolveAskUserQuestion(q,f.structured??y):Bt.current.sendMessage(y)},ks=i=>{let c=Bt.current;if(!c)return;let f=i.getAttribute("data-tool-call-id")??"",y=c.getMessages().find(x=>x.toolCall?.id===f);y&&c.persistAskUserQuestionProgress(y,{answers:rp(i,y),currentIndex:To(i)})},rb=i=>Object.entries(i).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),vm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=To(i),f=aa(i);if(c>=f-1)return;let y=Bt.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(ip(i,y,o,c+1),ks(i))};ki.addEventListener("click",i=>{let f=i.target.closest("[data-ask-user-action]");if(!f)return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;let x=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),x==="dismiss"){let k=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),la(ki,k);let q=Bt.current?.getMessages().find(te=>te.toolCall?.id===k);q?.agentMetadata?.awaitingLocalTool&&(Bt.current?.markAskUserQuestionResolved(q),Bt.current?.resolveAskUserQuestion(q,"(dismissed)"));return}if(x==="pick"){let k=f.getAttribute("data-option-label");if(!k)return;let q=y.getAttribute("data-multi-select")==="true",te=ls(y);if(te&&q){let Z=oi(y)[To(y)],ne=new Set(Array.isArray(Z)?Z:[]);ne.has(k)?ne.delete(k):ne.add(k),cs(y,Array.from(ne)),ks(y);return}if(te){cs(y,k),ks(y),vm(y);return}if(q){let Z=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Z?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Z);let ne=y.querySelector('[data-ask-user-action="submit-multi"]');ne&&(ne.disabled=Yf(y).length===0);return}Li(y,k,{source:"pick",values:[k]});return}if(x==="submit-multi"){let k=Yf(y);if(k.length===0)return;Li(y,k.join(", "),{source:"multi",values:k});return}if(x==="open-free-text"){let k=y.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(x==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(x==="submit-free-text"){let q=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!q.trim())return;if(ls(y)){cs(y,q.trim()),ks(y),vm(y);return}Li(y,q,{source:"free-text"});return}if(x==="next"||x==="back"){if(!Bt.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(Ce=>Ce.toolCall?.id===k);if(!q)return;let Z=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Z){let Ce=oi(y)[To(y)];(typeof Ce!="string"||Ce!==Z)&&cs(y,Z)}let ne=x==="next"?1:-1,pe=To(y)+ne;ip(y,q,o,pe),ks(y);return}if(x==="submit-all"){if(!Bt.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(Ce=>Ce.toolCall?.id===k);if(!q)return;let Z=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Z&&cs(y,Z);let ne=rp(y,q);Bt.current.persistAskUserQuestionProgress(q,{answers:ne,currentIndex:To(y)});let pe=rb(ne);Li(y,pe||"(submitted)",{source:"submit-all",structured:ne});return}if(x==="skip"){if(!Bt.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(He=>He.toolCall?.id===k);if(!q)return;let te=ls(y),Z=To(y),ne=aa(y),pe=Z>=ne-1;if(!te){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),la(ki,k),q.agentMetadata?.awaitingLocalTool&&(Bt.current.markAskUserQuestionResolved(q),Bt.current.resolveAskUserQuestion(q,"(dismissed)"));return}cs(y,"");let Ce=y.querySelector('[data-ask-free-text-input="true"]');if(Ce&&(Ce.value=""),pe){let He=rp(y,q),wt=rb(He);Li(y,wt||"(skipped)",{source:"submit-all",structured:He});return}ip(y,q,o,Z+1),ks(y);return}}),ki.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let f=i.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let x=f.value;if(x.trim()){if(ls(y)){cs(y,x.trim()),ks(y),vm(y);return}Li(y,x,{source:"free-text"})}});let sb=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let c=i.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let f=ki.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),k=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",sb);let Yo=null,Ut=null,Ya=null,jc=null,Kc=()=>{},ib=!1,Gc="",Yc="";function Cm(){jc?.(),jc=null}let AE=()=>{let i=$i&&Gs?.isConnected?Gs:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},ab=()=>{if(!Yo||!Ut)return;let i=t.classList.contains("persona-artifact-welded-split"),c=t.ownerDocument.defaultView??window,f=c.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||f){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let y=Yo.firstElementChild;if(!y||y===Ut)return;let x=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${x}px`,Ut.style.zIndex="5";let k=ny(Yo,c),q=y.offsetWidth+k/2-x/2;Ut.style.left=`${Math.max(0,q)}px`},Qc=()=>{},ME=()=>{let i=t.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>f?!1:ce||rn(o)},Xc=()=>!jn(o)||!qc()||t.classList.contains("persona-artifact-narrow-host")||ME()||(t.ownerDocument.defaultView??window).innerWidth<IB?"none":Zh(o)?"detached":"welded",Ro=()=>{if(!ft||!jn(o))return;kc(t,o),Lc(t,o),Qc();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=_e.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let f=qc();ft.setVisible(f),ft.update(yo),fr?(ft.setMobileOpen(!1),ft.element.classList.add("persona-hidden"),ft.backdrop?.classList.add("persona-hidden"),Ho=!1,Ga=!1):yo.artifacts.length>0&&ob()?(ft.element.classList.remove("persona-hidden"),ft.setMobileOpen(!0)):(ft.setMobileOpen(!1),ft.element.classList.add("persona-hidden"),ft.backdrop?.classList.add("persona-hidden"),Ho=!1,Ga=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ft.setExpandToggleVisible(y),ft.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ft.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ft.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ft.setTabFade(o.features?.artifacts?.layout?.tabFade),ft.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!Ga&&(Ho=!1),Ho!==ib){let k=ft.element;Ho?(Gc=k.style.width,Yc=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Gc&&(k.style.width=Gc),Yc&&(k.style.maxWidth=Yc),Gc="",Yc=""),ib=Ho}t.classList.toggle("persona-artifact-expanded",Ho),ft.setExpanded(Ho);let x=Xc();x!==Ka&&(Ka=x,Es()),Kc()};if(jn(o)){_e.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Le),Yo=c,c.appendChild(i),_e.appendChild(c);let f=x=>{nb||ft||(ft=x.createArtifactPane(o,{onSelect:k=>Bt.current?.selectArtifact(k),onDismiss:()=>{fr=!0,Ro()},onToggleExpand:()=>{let k=!Ho,q=yo.selectedId??yo.artifacts[yo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:k})!==!0&&(Ho=k,k||(Ga=!1),Ro())}}),ft.element.classList.add("persona-hidden"),c.appendChild(ft.element),ft.backdrop&&_e.appendChild(ft.backdrop),Kc(),Ro())},y=Dr();y?f(y):(Xh(()=>{let x=Dr();x&&f(x)}),ju().catch(()=>{})),Kc=()=>{if(!Yo||!ft)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ya?.(),Ya=null,Cm(),Ut&&(Ut.remove(),Ut=null),ft.element.style.removeProperty("width"),ft.element.style.removeProperty("maxWidth");return}if(!Ut){let k=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");k.setAttribute("role","separator"),k.setAttribute("aria-orientation","vertical"),k.setAttribute("aria-label","Resize artifacts panel"),k.tabIndex=0;let q=t.ownerDocument,te=q.defaultView??window,Z=ne=>{if(!ft||ne.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||te.innerWidth<=640)return;ne.preventDefault(),Cm();let pe=ne.clientX,Ce=ft.element.getBoundingClientRect().width,He=o.features?.artifacts?.layout,wt=Ft=>{let xn=Yo.getBoundingClientRect().width,pn=t.classList.contains("persona-artifact-welded-split"),Jt=ny(Yo,te),Bn=pn?0:k.getBoundingClientRect().width||6,Mt=Ce-(Ft.clientX-pe),On=rT(Mt,xn,Jt,Bn,He?.resizableMinWidth,He?.resizableMaxWidth,AE());ft.element.style.width=`${On}px`,ft.element.style.maxWidth="none",ab()},Ot=()=>{q.removeEventListener("pointermove",wt),q.removeEventListener("pointerup",Ot),q.removeEventListener("pointercancel",Ot),jc=null;try{k.releasePointerCapture(ne.pointerId)}catch{}};jc=Ot,q.addEventListener("pointermove",wt),q.addEventListener("pointerup",Ot),q.addEventListener("pointercancel",Ot);try{k.setPointerCapture(ne.pointerId)}catch{}};k.addEventListener("pointerdown",Z),Ut=k,Yo.insertBefore(k,ft.element),Ya=()=>{k.removeEventListener("pointerdown",Z)}}if(Ut){let k=qc();Ut.classList.toggle("persona-hidden",!k),ab()}},Qc=()=>{if(!ce||!ft||(o.launcher?.sidebarMode??!1)||rn(o)&&ko(o).reveal==="emerge")return;let k=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640;if(q&&k.innerWidth<=te||!JM(o,ce))return;let Z=o.launcher?.width??o.launcherWidth??Rr,ne=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";qc()?(_e.style.width=ne,_e.style.maxWidth=ne):(_e.style.width=Z,_e.style.maxWidth=Z)},typeof ResizeObserver<"u"&&(ja=new ResizeObserver(()=>{Ro()}),ja.observe(_e))}else _e.appendChild(Le);Ee()&&Kt&&(Ze.peekBanner&&Kt.appendChild(Ze.peekBanner),Kt.appendChild(We)),t.appendChild(it),Kt&&t.appendChild(Kt);let wm=()=>{if(Ee()){_e.style.width="100%",_e.style.maxWidth="100%";let st=o.launcher?.composerBar??{},Ue=it.dataset.state==="expanded",_n=st.expandedSize??"anchored";if(!(Ue&&_n!=="fullscreen")){Le.style.background="",Le.style.border="",Le.style.borderRadius="",Le.style.overflow="",Le.style.boxShadow="";return}let Zn=o.theme?.components?.panel,eo=Ca(o),Rt=(on,to)=>on==null||on===""?to:zn(eo,on)??on,Dt="1px solid var(--persona-border)",rt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Lr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Le.style.background="var(--persona-surface, #ffffff)",Le.style.border=Rt(Zn?.border,Dt),Le.style.borderRadius=Rt(Zn?.borderRadius,Lr),Le.style.boxShadow=Rt(Zn?.shadow,rt),Le.style.overflow="hidden";return}let i=rn(o),c=o.launcher?.sidebarMode??!1,f=i||c||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,q=Ca(o),te=(st,Ue)=>st==null||st===""?Ue:zn(q,st)??st,Z=t.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,Ce=Z.innerWidth<=pe,He=ne&&Ce&&ce,wt=i&&ne&&Ce,Ot=o.launcher?.position??"bottom-left",Ft=Ot==="bottom-left"||Ot==="top-left",xn=o.launcher?.zIndex??Hn,pn="var(--persona-panel-border, 1px solid var(--persona-border))",Jt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Bn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Mt=x&&!He&&!wt;Mt?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let On=Mt?pn:c||He?"none":pn,nr=Mt?Jt:He?"none":c?Ft?"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))":y?"none":Jt;i&&!He&&!Mt&&(nr="none",On="none");let kr=Mt?Bn:c||He?"0":Bn,Oo=te(k?.border,On),Sl=te(k?.shadow,nr),ei=te(k?.borderRadius,kr),Do=Xc(),Ln=Do==="detached",_o=Do==="welded";t.classList.toggle("persona-artifact-detached-split",Ln),t.classList.toggle("persona-artifact-welded-split",_o);let Zi="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)))))",qe=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&jn(o)&&Zh(o)&&y&&!i;t.classList.toggle("persona-artifact-chat-flush",qe);let xe=Ln||qe?"none":Sl,Zt=Ln?pn:_o?"none":Oo,un=Ln?Bn:ei;qe&&(Zt="none",un="0");let Pn=k?.borderRadius!=null&&k.borderRadius!=="",mn=qe&&!Pn?"0":ei,bn=ie.scrollTop;t.style.cssText="",it.style.cssText="",_e.style.cssText="",Le.style.cssText="",ie.style.cssText="",Ti||(We.style.cssText=""),Tt&&(ie.style.display="none"),(f||y)&&(t.style.minWidth="0");let en=()=>{if(bn<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===bn)return;let Ue=ie.scrollHeight-ie.clientHeight;Ue<=0||(ie.scrollTop=Math.min(bn,Ue))})};if(He){it.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"),it.style.cssText=`
1173
+ `,W.addEventListener("click",()=>{m=E,P.forEach((R,V)=>{let H=V<E;R.classList.toggle("selected",H),R.setAttribute("aria-checked",V===E-1?"true":"false")})}),P.push(W),S.appendChild(W)}h.appendChild(S);let M=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=s,M.rows=3,M.setAttribute("aria-label","Additional comments"),E.appendChild(M),h.appendChild(E)}let B=document.createElement("div");B.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let E=M?.value.trim()||void 0;await e(m,E),u.remove()}catch(E){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",E)}}),B.appendChild(A),B.appendChild(O),h.appendChild(B),u.appendChild(h),u}function qT(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=t,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,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,b.appendChild(S),g.appendChild(b);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,M.appendChild(B),M.appendChild(A);let O=document.createElement("div");O.className="persona-feedback-numbers";let E=[];for(let w=0;w<=10;w++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-number-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`Rating ${w} out of 10`),T.textContent=String(w),T.dataset.rating=String(w),w<=6?T.classList.add("persona-feedback-detractor"):w<=8?T.classList.add("persona-feedback-passive"):T.classList.add("persona-feedback-promoter"),T.addEventListener("click",()=>{h=w,E.forEach((I,D)=>{I.classList.toggle("selected",D===w),I.setAttribute("aria-checked",D===w?"true":"false")})}),E.push(T),O.appendChild(T)}P.appendChild(M),P.appendChild(O),g.appendChild(P);let W=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),w.appendChild(W),g.appendChild(w)}let R=document.createElement("div");R.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=l,V.addEventListener("click",()=>{n?.(),m.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let w=W?.value.trim()||void 0;await e(h,w),m.remove()}catch(w){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",w)}}),R.appendChild(V),R.appendChild(H),g.appendChild(R),m.appendChild(g),m}var Ba="persona-chat-history",PB=30*1e3,IB=641,Oa="data-persona-composer-reason",HB={"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 RB(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=HB[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function tm(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function WB(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function BB(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Sy=t=>!t||typeof t!="object"?{}:{...t},jT=t=>t.map(e=>({...e,streaming:!1})),KT=(t,e,n)=>{let o=t?.markdown?Qd(t.markdown):null,r=Jd(t?.sanitize);t?.postprocessMessage&&r&&t?.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 s=!1,a=l=>{let d=l.text??"",p=l.message.rawContent??null;if(e){let h=e.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});h!==null&&(d=h.text,h.persist||(l.message.__skipPersist=!0),h.resubmit&&!l.streaming&&n&&n())}let u=Mo()!==null,m;if(t?.postprocessMessage){let h=t.postprocessMessage({...l,text:d,raw:p??l.text??""});m=r?r(h):h}else if(o){let h=l.streaming?AC(d):d,g=o(h);m=r&&u?r(g):g}else m=Pr(d);return m};return l=>{try{return a(l)}catch(d){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),Pr(l.text??"")}}};function GT(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=Ie(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var OB=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},DB=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:OB(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),YT=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Ep(e),r=()=>{ix({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=ty(o);let a=ry.getForInstance(o.plugins),l=FS(t),d=[],p=!1,u=GA(()=>o),m=null,h=null,g=null,b=!1,C=null,S=i=>{m=i,i.initApprovalUi({webMcpToolTitle:Zd});let c=i.createBuiltInApprovalPlugin();h=c.plugin,g=c.teardown},P=()=>{if(m)return m;let i=lM();return i?(S(i),i):(aM().then(c=>{b||m||(S(c),C?.())}).catch(()=>{}),null)},M=!1,B=!1,A=null,O=(i,c,f,y)=>{if(!i.querySelector("[data-tv-form]"))return;let x=dT();if(x){x.enhanceWithForms(i,c,f,y);return}cT().then(()=>{M||B||!A||(B=!0,A())}).catch(()=>{})};o.components&&zo.registerAll(o.components);let E=fT(),R=o.persistState===!1?null:o.storageAdapter??hT(),V=!!o.clientToken&&typeof o.reconnectStream!="function",H={},w=null,T,I=new Promise(i=>{T=i}),D,G=!1,z=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:f,open:y}=c;return y&&(G=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(R?.load)try{let i=R.load();if(i&&typeof i.then=="function")w=i.then(c=>z(c??{messages:[],metadata:{}}));else{let f=z(i??{messages:[],metadata:{}});f.metadata&&(H=Sy(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null}),D=f.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=z({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}w||T();let K=()=>H,Y=i=>{H=i({...H})??{},Wi()},re=o.actionParsers&&o.actionParsers.length?o.actionParsers:[iy],oe=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pc.message,Pc.messageAndClick],se=ay({parsers:re,handlers:oe,getSessionMetadata:K,updateSessionMetadata:Y,emit:E.emit,documentRef:typeof document<"u"?document:null});se.syncFromMetadata();let ce=o.launcher?.enabled??!0,we=o.launcher?.autoExpand??!1,ge=o.autoFocusInput??!1,N=we,ye=ce,ke=o.layout?.header?.layout,nt=!1,Ee=()=>pc(o),Ne=()=>ce||Ee(),Pe=Ee()?!1:ce?we:!0,dt=!1,Xe=null,xt=()=>{dt=!0,Xe&&clearTimeout(Xe),Xe=setTimeout(()=>{dt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),dt=!1)},1e4)},Ge=KT(o,se,xt),yt=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,L=o.features?.showEventStreamToggle??!1,j=o.features?.scrollToBottom??{},J=o.features?.scrollBehavior??{},Q=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Me=`${Q()}event-stream`,Te=null,Fe=o.features?.eventStream?.maxEvents??2e3,je=null,lt=null,ot=null,Je=!1,mt=null,Tt=!1,ee=null,Oe=0,$e=(i,c)=>{je?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},pt=(i,c)=>{lt?.processEvent(i,c),je?$e(i,c):ot&&(ot.length>=Fe&&ot.shift(),ot.push({type:i,payload:c}))},_t=()=>{je||!L||(ot??(ot=[]),Dh().then(i=>{if(Je||je||!L)return;Te=new i.EventStreamStore(Me),je=new i.EventStreamBuffer(Fe,Te),lt=lt??new i.ThroughputTracker,Te.open().then(()=>je?.restore()).catch(f=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",f)});let c=ot??[];ot=null;for(let f of c)lt?.processEvent(f.type,f.payload),$e(f.type,f.payload)}).catch(()=>{}))};L&&_t();let ve=!1,Se=null,Ke=()=>{},ut=()=>{},vn=()=>{},Cn=()=>{},wn=()=>{},Wt=()=>Tt||ve&&Se==="panel",St={onCopy:i=>{E.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{E.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},Et=o.statusIndicator??{},sn=i=>i==="idle"?Et.idleText??fn.idle:i==="connecting"?Et.connectingText??fn.connecting:i==="connected"?Et.connectedText??fn.connected:i==="error"?Et.errorText??fn.error:i==="paused"?Et.pausedText??fn.paused:i==="resuming"?Et.resumingText??fn.resuming:fn[i];function Rn(i,c,f,y){if(!i.hasAttribute(Oa))if(y==="idle"&&f.idleLink){i.textContent="";let x=document.createElement("a");x.href=f.idleLink,x.target="_blank",x.rel="noopener noreferrer",x.textContent=c,x.style.color="inherit",x.style.textDecoration="none",i.appendChild(x)}else i.textContent=c}let tn=KA({config:o,showClose:Ne()}),{wrapper:it,panel:_e,pillRoot:Kt}=tn.shell,Ze=tn.panelElements,{container:Le,body:ie,messagesWrapper:Re,starterSuggestions:wi,transcriptSuggestions:Vr,suggestions:Io,textarea:Ae,sendButton:Ve,composerForm:Wn,statusText:bt,welcomeHost:an,welcomeIconHolder:_a,greetingHost:kn,introKicker:Na,introTitle:om,introSubtitle:rm,closeButton:F,iconHolder:le,headerTitle:Be,headerSubtitle:et,header:he,footer:We,actionsRow:Uo}=Ze,qo=Ze.leftActions,$r=Ze.rightActions,jo=Ze.sendButtonWrapper,Py=Ze.setSendButtonMode,fe=Ze.micButton,io=Ze.micButtonWrapper,Gt=Ze.attachmentButton,Kn=Ze.attachmentButtonWrapper,zt=Ze.attachmentInput,Gn=Ze.attachmentPreviewsContainer;Le.classList.add("persona-relative"),ie.classList.add("persona-relative");let lE=12,Fa=()=>j.label??"",cE=()=>j.iconName??"arrow-down",dE=()=>j.enabled!==!1,ao=()=>J.mode??"anchor-top",zr=()=>ao()==="follow"||ao()==="anchor-top"&&Qa,Va=()=>J.anchorTopOffset??16,pE=()=>J.restorePosition??"bottom",Iy=()=>J.pauseOnInteraction===!0,Hy=()=>J.showActivityWhilePinned!==!1,Ry=()=>J.announce===!0,sm=()=>J.scrollbar??"on-scroll",ln=v("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");ln.type="button",ln.style.display="none",ln.setAttribute("data-persona-scroll-to-bottom","true");let $a=v("span","persona-flex persona-items-center"),im=v("span",""),As=v("span","");As.setAttribute("data-persona-scroll-to-bottom-count",""),As.style.display="none",ln.append($a,im,As),Le.appendChild(ln);let ho=v("div","persona-stream-anchor-spacer");ho.setAttribute("aria-hidden","true"),ho.setAttribute("data-persona-anchor-spacer",""),ho.style.flexShrink="0",ho.style.pointerEvents="none",ho.style.height="0px",ho.style.display="none",ie.appendChild(ho);let mr=v("div","persona-sr-only");mr.setAttribute("aria-live","polite"),mr.setAttribute("aria-atomic","true"),mr.setAttribute("role","status"),mr.setAttribute("data-persona-live-region",""),Object.assign(mr.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Le.appendChild(mr);let za=null,Dc=null,_c=i=>{!Ry()||!i||(Dc=i,za===null&&(za=setTimeout(()=>{za=null,Dc&&Ry()&&(mr.textContent=Dc),Dc=null},400)))},Nc="empty",Fc=0,am=()=>Fc||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Ms=()=>{let c=We.style.display==="none"?0:We.offsetHeight;ln.style.bottom=`${c+am()+lE}px`};Ms();let lm=()=>{Ti||(We.style.marginBottom=Fc>0?`${Fc}px`:"")},Vc=()=>{let i=Gg(o,Ee()),c=Br(o),y=We.style.display==="none"?0:We.offsetHeight,x=c.anchor==="center"&&Nc==="empty"?ec(c.anchorComposerTop)??ec("44%"):null,k=x===null||Ee()?0:DS({columnHeight:Le.clientHeight,footerHeight:y,fraction:x});t.style.setProperty("--persona-composer-overlay-height",`${y}px`),t.style.setProperty("--persona-composer-lift",`${i==="overlay"?k:0}px`),Fc=i==="block"?k:0,lm(),Ms()},Wy=()=>{let i=!!Fa();ln.setAttribute("aria-label",Fa()||"Jump to latest"),ln.title=Fa(),ln.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),$a.innerHTML="";let c=Ie(cE(),"14px","currentColor",2);c?($a.appendChild(c),$a.style.display=""):$a.style.display="none",im.textContent=Fa(),im.style.display=i?"":"none"};Wy();let At=null,nn=null,ze=ex(),uE=i=>{try{Le.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ze.subscribe(uE);let Ko=()=>{ze.setText(Ae?.value??"")},Ts=()=>{ze.setMentionRefs(nn?.getMentionRefs()??[])},mE=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),By=i=>{let c=Object.freeze(i.map(mE));ze.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(f){console.error("[AgentWidget] attachments.onChange failed:",f)}Bm()};ze.setSelectedModelId(o.composer?.selectedModelId);let Ua=()=>o.composer?.modes??[],xi=()=>Ix(Ua(),o.composer?.modeGroups);{let i=$p(o.composer?.defaultActiveModeIds??[],Ua());i.length&&ze.setActiveModeIds(i)}function Oy(i){if(ze.getState().selectedModelId!==i){ze.setSelectedModelId(i),Ur?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function $c(i){ze.setActiveModeIds(i),fr?.render(i,xi()),Si.forEach(c=>c.repaint()),Yo?.resolve(),md(),Ho()}function cm(i){$c(Hx(ze.getState().activeModeIds,i,Ua(),o.composer?.modeGroups))}let Ur=null,dm=null,fr=null,Si=new Map,qr=null;function Go(i){ze.setQuote(i),qr?.render(ze.getState().quote),Ho(),kb()}let Dy=!1;function pm(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Dy&&o.debug===!0&&(Dy=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let jr=null;function Ai(i){ze.setPendingSubmission(i),jr?.render(ze.getState().pendingSubmission),Ho()}let fE=i=>{let c=Si.get(i);if(c)return c;let f=Bx({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(y=>y.id===i),getModes:()=>Ua().filter(y=>y.groupId===i),getActiveIds:()=>ze.getState().activeModeIds,onSelect:y=>cm(y)});return Si.set(i,f),f},gE=()=>{let i=[],c=ze.getState().activeModeIds,f=new Set;if(Ua().forEach((y,x)=>{if(Vp(y.groupId,o.composer?.modeGroups)){let k=y.groupId;if(f.has(k))return;f.add(k);let q=fE(k);q.action.order=Ig(x),q.action.label=o.composer?.modeGroups?.find(te=>te.id===k)?.label??k,i.push(q.action);return}i.push({id:Lx(y.id),kind:"button",placement:"start",order:Ig(x),presentation:y.presentation??"auto",label:y.label,shortLabel:y.shortLabel,iconName:y.iconName,pressed:c.includes(y.id),onSelect:()=>cm(y.id)})}),o.composer?.models?.length&&!a.some(y=>y.renderComposer)){let y=o.composer?.modelPicker?.presentation??"native";(!Ur||dm!==y)&&(dm=y,Ur=Ex({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ze.getState().selectedModelId,onSelect:x=>Oy(x),presentation:y,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Ur.action)}return i},um=null,_y=a.find(i=>i.renderHeader);if(_y?.renderHeader){let i=_y.renderHeader({config:o,defaultRenderer:()=>{let c=li({config:o,showClose:Ne()});return mc(Le,c,o),c.header},onClose:()=>Nt(!1,"user")});if(i){let c=he;c&&(c.replaceWith(i),he=i,tn.header.element=i)}}let Ny=()=>{mt&&(ie.style.display="none",We.parentNode?.insertBefore(mt.element,We),mt.update())},mm=()=>{if(!je){_t();return}if(Tt=!0,mt?Ny():Dh().then(c=>{mt||!Tt||!je||(mt=c.createEventStreamView({buffer:je,getFullHistory:()=>je.getAllFromStore(),onClose:()=>Mi(),config:o,plugins:a,getThroughput:()=>lt?.getMetric()??{status:"idle"},renderIconByName:Ie}),Ny())}).catch(()=>{Mi()}),kt){kt.style.boxShadow=`inset 0 0 0 1.5px ${Un.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&kt.classList.add(f))}let i=()=>{if(!Tt)return;let c=Date.now();c-Oe>=200&&(mt?.update(),Oe=c),ee=requestAnimationFrame(i)};Oe=0,ee=requestAnimationFrame(i),yn(),E.emit("eventStream:opened",{timestamp:Date.now()})},Mi=()=>{if(Tt){if(Tt=!1,mt&&mt.element.remove(),ie.style.display="",kt){kt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&kt.classList.remove(c))}ee!==null&&(cancelAnimationFrame(ee),ee=null),yn(),E.emit("eventStream:closed",{timestamp:Date.now()})}},kt=null;if(L){let i=o.features?.eventStream?.classNames,c="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"+(i?.toggleButton?" "+i.toggleButton:"");kt=v("button",c),kt.style.width="28px",kt.style.height="28px",kt.style.color=Un.actionIconColor,kt.type="button",kt.setAttribute("aria-label","Event Stream"),kt.title="Event Stream";let f=Qe(Fr.Activity,"18px","currentColor",1.5);f&&kt.appendChild(f);let y=Ze.clearChatButtonWrapper,x=Ze.closeButtonWrapper,k=y||x;k&&k.parentNode===he?he.insertBefore(kt,k):he.appendChild(kt),kt.addEventListener("click",()=>{Tt?Mi():mm()})}let Fy=i=>{let c=o.attachments;if(!c?.enabled)return;let f=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!f){f=v("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 x=i.querySelector("[data-persona-composer-form]");x?.parentNode?x.parentNode.insertBefore(f,x):i.insertBefore(f,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let x=v("input");x.type="file",x.setAttribute("data-persona-composer-attachment-input",""),x.accept=(c.allowedTypes??Hr).join(","),x.multiple=(c.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(x)}},Ti=!1,Vy=i=>{let c=a.find(x=>x.renderComposer);if(!c?.renderComposer)return null;let f=o.composer,y=p?_.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>eC(),storage:u(c.id),onSubmit:x=>{!_||_.isStreaming()||Fd(x.trim(),{consumeDraft:!1})},streaming:y,disabled:y,openAttachmentPicker:()=>{Zo()||zt?.click()},models:f?.models,selectedModelId:ze.getState().selectedModelId??f?.selectedModelId,onModelChange:x=>Oy(x),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{um?.()}:void 0})},$y=Vy(()=>gc({config:o}).footer);$y&&(tn.replaceComposer($y),We=tn.composer.footer,Ti=!0);let Lt=null,hE=i=>{Wn=i.form,Ae=i.input,jo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ve=i.sendButton),i.micButton&&(fe=i.micButton,io=i.micButton.parentElement),i.found.status&&(bt=i.found.status),i.found.suggestions&&(Io=i.found.suggestions),i.attachmentButton&&(Gt=i.attachmentButton,Kn=i.attachmentButton.parentElement),zt=i.attachmentInput??null,Gn=i.attachmentPreviews??null,i.found.actionsRow&&(Uo=i.found.actionsRow),qo=i.found.actionsStart,$r=i.found.actionsEnd};function fm(){let i=Ae;if(!i)return;let c=o.composer?.inputAttributes,f=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Pp(i,c),f&&i.setAttribute("aria-label",f),Lp(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(i)}),ux(i,kp(o.composer?.maxLines,Ee()?5:3))}let zy=i=>{Lt=nx(i,{debug:o.debug===!0}),Lt&&hE(Lt),fm()};Fy(We),zy(We),Ko();let qa=ys(o,Ee());qa&&(Re.style.maxWidth=qa,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",kn.style.maxWidth=qa,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%",wi.style.maxWidth=qa,Vr.style.maxWidth=qa,Vr.style.marginLeft="auto",Vr.style.marginRight="auto",Vr.style.width="100%");let Uy=()=>{let i=ys(o,Ee());if(!(!i||Ee()))for(let c of[Wn,Io,Gn,bt])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Uy();let qy=()=>{!o.attachments?.enabled||!zt||!Gn||(At?At.remountPreviews(Gn):(At=$l.fromConfig(o.attachments,By),At.setPreviewsContainer(Gn)),Lt?.addListener(zt,"change",i=>{let c=i.target;At?.handleFileSelect(c.files),c.value=""}),Le.querySelector(".persona-attachment-drop-overlay")||Le.appendChild(GT(o.attachments.dropOverlay)))};qy();let yE=()=>nn?.prefetch(),jy=()=>{if(!o.contextMentions?.enabled||!Ae)return;let i=Lt?.header??null,c=i?Pg(i):void 0;if(nn=PS({config:o,textarea:Ae,anchor:Wn??Ae,getMessages:()=>_.getMessages(),liveRegionHost:Le,chipRow:c}),nn&&!c){let f=Ae;f.parentElement?.insertBefore(nn.contextRow,f)}};jy();let Yo=null,bE={getState:()=>ze.getState(),getValue:()=>Ae?.value??"",setValue:i=>{Ae&&(Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ko())},submit:()=>{jl(Lt?.form??null)},openAttachmentPicker:()=>{Zo()||zt?.click()},toggleVoice:()=>{um?.()},requestRender:()=>Yo?.resolve()},vE=()=>{let i=[];return(nn?.affordanceButtons??[]).forEach((f,y)=>{i.push({id:`core:mention-${y}`,placement:"start",order:lr.mention+y,element:f,managed:!0})}),Kn&&i.push({id:"core:attachment",placement:"start",order:lr.attachment,element:Kn}),io&&i.push({id:"core:mic",placement:"end",order:lr.mic,element:io}),jo&&i.push({id:"core:send",placement:"end",order:lr.send,element:jo}),i},Ky=()=>{Yo?.destroy(),Yo=Ax({getBindings:()=>Lt,collect:()=>({builtIns:vE(),configActions:[...gE(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>ze.getState(),requestRender:()=>Yo?.resolve()},debug:o.debug===!0}),actionContext:bE,getState:()=>ze.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Yo.resolve()};Ky();let gm=()=>{if(fr?.destroy(),fr=null,!xi().length)return;let i=Lt?.header;i&&(fr=kx({row:Pg(i),onRemove:c=>cm(c),initialIds:ze.getState().activeModeIds}),fr.render(ze.getState().activeModeIds,xi()))};gm();let Gy=()=>{qr?.destroy(),qr=null,jr?.destroy(),jr=null;let i=Lt?.header;i&&(qr=Ox({onDismiss:()=>Go(void 0)}),i.appendChild(qr.element),qr.render(ze.getState().quote),pm()==="defer-one"&&(jr=Dx({onEdit:()=>Kk(),onRemove:()=>Ai(void 0)}),i.appendChild(jr.element),jr.render(ze.getState().pendingSubmission)))};Gy();let hm=zx(),CE=()=>{let i=Lt?.header?.querySelector(Lg);if(i)return i.childElementCount>0;let c=ze.getState();return c.mentionRefs.length>0||$p(c.activeModeIds,xi()).length>0},Yy=()=>!1;function Ho(){let i=ze.getState(),c=hm.observe(Ux(Ae),i.text);We.toggleAttribute("data-persona-composer-compact",$x({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:CE(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:Yy()}))}function Qy(){o.composer?.layout==="single-row"&&!Ee()?We.setAttribute("data-persona-composer-layout","single-row"):We.removeAttribute("data-persona-composer-layout")}Qy(),ze.subscribe(()=>{Yo?.sync(),Bm(),pd(),Ho(),kb()}),pd();let Xy=!1,wE=i=>{if(Xy||o.debug!==!0)return;let c=["messages","composer"].filter(f=>i[f]);c.length&&(Xy=!0,console.warn(`[persona] layout.slots.${c.join(" and layout.slots.")} ${c.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 i=o.layout?.slots??{};wE(i);let c=y=>{switch(y){case"body-top":return ie.querySelector("[data-persona-intro-card]");case"messages":return Re;case"footer-top":return Io;case"composer":return Wn;case"footer-bottom":return bt;default:return null}},f=(y,x)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")he.insertBefore(x,he.firstChild);else if(y==="header-right")he.appendChild(x);else{let k=he.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(x,k.nextSibling):he.appendChild(x)}break;case"body-top":{let k=ie.querySelector("[data-persona-intro-card]");k?k.replaceWith(x):ie.insertBefore(x,ie.firstChild);break}case"body-bottom":ie.appendChild(x);break;case"footer-top":Io.replaceWith(x);break;case"footer-bottom":bt.replaceWith(x);break;default:break}};for(let[y,x]of Object.entries(i))if(x)try{let k=x({config:o,defaultContent:()=>c(y)});k&&f(y,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,k)}})();let Jy=i=>{let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let y=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let k=f.getAttribute("data-bubble-type");if(k==="reasoning")Ta.has(x)?Ta.delete(x):Ta.add(x),YA(x,y);else if(k==="tool")Ea.has(x)?Ea.delete(x):Ea.add(x),XA(x,y,o);else if(k==="approval"&&m){let te=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Z=m.approvalDetailsExpansionState.get(x)??te;m.approvalDetailsExpansionState.set(x,!Z),m.updateApprovalDetailsUI(x,y,o)}cn.delete(x)};Re.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Jy(i))}),Re.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Jy(i))}),Re.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let f=Re.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let x=y.toString(),k=$S(x);!k||k===x||(c.setData("text/plain",k),i.preventDefault())});let ym=new Map,Zy=null,eb="idle",xE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},SE=(i,c)=>{let{icon:f,label:y}=xE[c];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let x=Ie(f,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},tb=()=>{Re.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let y=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;SE(c,y&&y===Zy?eb:"idle")})};Re.addEventListener("click",i=>{let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest("[data-actions-for]");if(!y)return;let x=y.getAttribute("data-actions-for");if(!x)return;let k=f.getAttribute("data-action");if(k==="copy"){let te=_.getMessages().find(Z=>Z.id===x);if(te&&St.onCopy){let Z=te.content||"";navigator.clipboard.writeText(Z).then(()=>{f.classList.add("persona-message-action-success");let ne=Qe(Fr.Check,14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let pe=Qe(Fr.Copy,14,"currentColor",2);pe&&(f.innerHTML="",f.appendChild(pe))},2e3)}).catch(ne=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ne)}),St.onCopy(te)}}else if(k==="read-aloud")_.toggleReadAloud(x);else if(k==="upvote"||k==="downvote"){let te=(ym.get(x)??null)===k,Z=k==="upvote"?"thumbs-up":"thumbs-down";if(te){ym.delete(x),f.classList.remove("persona-message-action-active");let ne=Ie(Z,14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne))}else{let ne=k==="upvote"?"downvote":"upvote",pe=y.querySelector(`[data-action="${ne}"]`);if(pe){pe.classList.remove("persona-message-action-active");let Ft=Ie(ne==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ft&&(pe.innerHTML="",pe.appendChild(Ft))}ym.set(x,k),f.classList.add("persona-message-action-active");let Ce=Ie(Z,14,"currentColor",2);Ce&&(Ce.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(Ce)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let wt=_.getMessages().find(Ot=>Ot.id===x);wt&&St.onFeedback&&St.onFeedback({type:k,messageId:wt.id,message:wt})}}else if(k==="regenerate")zc?.regenerate(x);else if(k==="edit")zc?.edit(x);else if(k==="quote")zc?.quote(x);else if(k?.startsWith(xu)){let q=k.slice(xu.length),te=o.messageActions?.custom?.find(ne=>ne.id===q),Z=_.getMessages().find(ne=>ne.id===x);if(!te||!Z)return;try{te.onSelect(Z)}catch(ne){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,ne)}}});let zc=null;Re.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest(".persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let k=f.getAttribute("data-approval-action");if(!k)return;let q=k==="approve"?"approved":"denied",Z=_.getMessages().find(pe=>pe.id===x);if(!Z?.approval)return;let ne=y.querySelector("[data-approval-buttons]");ne&&ne.querySelectorAll("button").forEach(Ce=>{Ce.disabled=!0,Ce.style.opacity="0.5",Ce.style.cursor="not-allowed"}),Z.approval.toolType==="webmcp"?_.resolveWebMcpApproval(x,q):_.resolveApproval(Z.approval,q)});let ft=null,nb=!1,ja=null,Es=()=>{},Ka="none",Uc=null,yo={artifacts:[],selectedId:null},gr=!1,Ro=!1,Ga=!1,Ei=!1,ob=()=>Ei||yo.artifacts.some(i=>is(o.features?.artifacts,i)==="panel"),qc=()=>yo.artifacts.length>0&&!gr&&ob(),Bt={current:null},bm=(i,c)=>{let f=_.getArtifactById(c),y=f?.markdown,x=f?.title||"artifact",k=f?.file,q=f?.artifactType??"markdown";if(!y){let ne=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ne){let Ce=_.getMessages().find(He=>He.id===ne);if(Ce?.rawContent)try{let He=JSON.parse(Ce.rawContent);y=He?.props?.markdown,x=He?.props?.title||x,He?.props?.file&&typeof He.props.file=="object"&&(k=He.props.file),!f&&typeof He?.props?.artifactType=="string"&&(q=He.props.artifactType)}catch{}}}return{markdown:y,title:x,file:k,artifactType:q}};Re.addEventListener("click",i=>{let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:k,title:q,file:te}=bm(f,y);if(!k)return;let Z=Dr();Z&&Z.triggerArtifactDownload(Z.downloadInfoFor({title:q,markdown:k,file:te}))}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-artifact-custom-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-artifact-custom-action");if(!y)return;let x=f.closest("[data-artifact-inline]"),k=x?null:f.closest("[data-open-artifact]"),q=x?x.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Z=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Ot=>Ot.id===y);if(!Z)return;let{markdown:ne,title:pe,file:Ce,artifactType:He}=bm(f,q??""),wt={artifactId:q,title:pe,artifactType:He,markdown:ne,file:Ce};try{Promise.resolve(Z.onClick(wt)).catch(()=>{})}catch{}}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-copy-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-copy-artifact");if(!y)return;let x=_.getArtifactById(y),k=Dr();if(!k)return;let q="";if(x)q=k.artifactCopyText(x);else{let{markdown:te,file:Z,artifactType:ne}=bm(f,y);ne==="markdown"&&(q=k.artifactCopyText({id:y,artifactType:"markdown",status:"complete",markdown:te??"",...Z?{file:Z}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let te=Qe(Fr.Check,16,"currentColor",2);te&&(f.replaceChildren(te),setTimeout(()=>{let Z=Qe(Fr.Copy,16,"currentColor",2);Z&&f.replaceChildren(Z)},1500))}).catch(()=>{})}),Re.addEventListener("click",i=>{let f=i.target.closest("[data-expand-artifact-inline]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(gr=!1,Ei=!0,Ro=!0,Ga=!0,_.selectArtifact(y),Wo())}),Re.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let f=c.closest("[data-open-artifact]");if(!f)return;let y=f.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),gr=!1,Ei=!0,_.selectArtifact(y),Wo())}),Re.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let ki=Ze.composerOverlay,Li=(i,c,f)=>{let y=c.trim();if(!y||!Bt.current)return;let x=i.getAttribute("data-tool-call-id")??"",k=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:x,answer:y,answers:f.structured,values:f.values??(f.source==="multi"?y.split(", "):[y]),isFreeText:k,source:f.source},bubbles:!0,composed:!0})),la(ki,x);let q=Bt.current.getMessages().find(te=>te.toolCall?.id===x);q?.agentMetadata?.awaitingLocalTool?Bt.current.resolveAskUserQuestion(q,f.structured??y):Bt.current.sendMessage(y)},ks=i=>{let c=Bt.current;if(!c)return;let f=i.getAttribute("data-tool-call-id")??"",y=c.getMessages().find(x=>x.toolCall?.id===f);y&&c.persistAskUserQuestionProgress(y,{answers:rp(i,y),currentIndex:Eo(i)})},rb=i=>Object.entries(i).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),vm=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=Eo(i),f=aa(i);if(c>=f-1)return;let y=Bt.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(ip(i,y,o,c+1),ks(i))};ki.addEventListener("click",i=>{let f=i.target.closest("[data-ask-user-action]");if(!f)return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;let x=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),x==="dismiss"){let k=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),la(ki,k);let q=Bt.current?.getMessages().find(te=>te.toolCall?.id===k);q?.agentMetadata?.awaitingLocalTool&&(Bt.current?.markAskUserQuestionResolved(q),Bt.current?.resolveAskUserQuestion(q,"(dismissed)"));return}if(x==="pick"){let k=f.getAttribute("data-option-label");if(!k)return;let q=y.getAttribute("data-multi-select")==="true",te=ls(y);if(te&&q){let Z=oi(y)[Eo(y)],ne=new Set(Array.isArray(Z)?Z:[]);ne.has(k)?ne.delete(k):ne.add(k),cs(y,Array.from(ne)),ks(y);return}if(te){cs(y,k),ks(y),vm(y);return}if(q){let Z=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Z?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Z);let ne=y.querySelector('[data-ask-user-action="submit-multi"]');ne&&(ne.disabled=Yf(y).length===0);return}Li(y,k,{source:"pick",values:[k]});return}if(x==="submit-multi"){let k=Yf(y);if(k.length===0)return;Li(y,k.join(", "),{source:"multi",values:k});return}if(x==="open-free-text"){let k=y.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(x==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(x==="submit-free-text"){let q=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!q.trim())return;if(ls(y)){cs(y,q.trim()),ks(y),vm(y);return}Li(y,q,{source:"free-text"});return}if(x==="next"||x==="back"){if(!Bt.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(Ce=>Ce.toolCall?.id===k);if(!q)return;let Z=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Z){let Ce=oi(y)[Eo(y)];(typeof Ce!="string"||Ce!==Z)&&cs(y,Z)}let ne=x==="next"?1:-1,pe=Eo(y)+ne;ip(y,q,o,pe),ks(y);return}if(x==="submit-all"){if(!Bt.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(Ce=>Ce.toolCall?.id===k);if(!q)return;let Z=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Z&&cs(y,Z);let ne=rp(y,q);Bt.current.persistAskUserQuestionProgress(q,{answers:ne,currentIndex:Eo(y)});let pe=rb(ne);Li(y,pe||"(submitted)",{source:"submit-all",structured:ne});return}if(x==="skip"){if(!Bt.current)return;let k=y.getAttribute("data-tool-call-id")??"",q=Bt.current.getMessages().find(He=>He.toolCall?.id===k);if(!q)return;let te=ls(y),Z=Eo(y),ne=aa(y),pe=Z>=ne-1;if(!te){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),la(ki,k),q.agentMetadata?.awaitingLocalTool&&(Bt.current.markAskUserQuestionResolved(q),Bt.current.resolveAskUserQuestion(q,"(dismissed)"));return}cs(y,"");let Ce=y.querySelector('[data-ask-free-text-input="true"]');if(Ce&&(Ce.value=""),pe){let He=rp(y,q),wt=rb(He);Li(y,wt||"(skipped)",{source:"submit-all",structured:He});return}ip(y,q,o,Z+1),ks(y);return}}),ki.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let f=i.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let x=f.value;if(x.trim()){if(ls(y)){cs(y,x.trim()),ks(y),vm(y);return}Li(y,x,{source:"free-text"})}});let sb=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let c=i.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let f=ki.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),k=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",sb);let Qo=null,Ut=null,Ya=null,jc=null,Kc=()=>{},ib=!1,Gc="",Yc="";function Cm(){jc?.(),jc=null}let AE=()=>{let i=$i&&Gs?.isConnected?Gs:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},ab=()=>{if(!Qo||!Ut)return;let i=t.classList.contains("persona-artifact-welded-split"),c=t.ownerDocument.defaultView??window,f=c.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||f){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let y=Qo.firstElementChild;if(!y||y===Ut)return;let x=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${x}px`,Ut.style.zIndex="5";let k=ny(Qo,c),q=y.offsetWidth+k/2-x/2;Ut.style.left=`${Math.max(0,q)}px`},Qc=()=>{},ME=()=>{let i=t.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>f?!1:ce||rn(o)},Xc=()=>!jn(o)||!qc()||t.classList.contains("persona-artifact-narrow-host")||ME()||(t.ownerDocument.defaultView??window).innerWidth<IB?"none":Zh(o)?"detached":"welded",Wo=()=>{if(!ft||!jn(o))return;kc(t,o),Lc(t,o),Qc();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=_e.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let f=qc();ft.setVisible(f),ft.update(yo),gr?(ft.setMobileOpen(!1),ft.element.classList.add("persona-hidden"),ft.backdrop?.classList.add("persona-hidden"),Ro=!1,Ga=!1):yo.artifacts.length>0&&ob()?(ft.element.classList.remove("persona-hidden"),ft.setMobileOpen(!0)):(ft.setMobileOpen(!1),ft.element.classList.add("persona-hidden"),ft.backdrop?.classList.add("persona-hidden"),Ro=!1,Ga=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ft.setExpandToggleVisible(y),ft.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ft.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ft.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ft.setTabFade(o.features?.artifacts?.layout?.tabFade),ft.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!Ga&&(Ro=!1),Ro!==ib){let k=ft.element;Ro?(Gc=k.style.width,Yc=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Gc&&(k.style.width=Gc),Yc&&(k.style.maxWidth=Yc),Gc="",Yc=""),ib=Ro}t.classList.toggle("persona-artifact-expanded",Ro),ft.setExpanded(Ro);let x=Xc();x!==Ka&&(Ka=x,Es()),Kc()};if(jn(o)){_e.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Le),Qo=c,c.appendChild(i),_e.appendChild(c);let f=x=>{nb||ft||(ft=x.createArtifactPane(o,{onSelect:k=>Bt.current?.selectArtifact(k),onDismiss:()=>{gr=!0,Wo()},onToggleExpand:()=>{let k=!Ro,q=yo.selectedId??yo.artifacts[yo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:k})!==!0&&(Ro=k,k||(Ga=!1),Wo())}}),ft.element.classList.add("persona-hidden"),c.appendChild(ft.element),ft.backdrop&&_e.appendChild(ft.backdrop),Kc(),Wo())},y=Dr();y?f(y):(Xh(()=>{let x=Dr();x&&f(x)}),ju().catch(()=>{})),Kc=()=>{if(!Qo||!ft)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ya?.(),Ya=null,Cm(),Ut&&(Ut.remove(),Ut=null),ft.element.style.removeProperty("width"),ft.element.style.removeProperty("maxWidth");return}if(!Ut){let k=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");k.setAttribute("role","separator"),k.setAttribute("aria-orientation","vertical"),k.setAttribute("aria-label","Resize artifacts panel"),k.tabIndex=0;let q=t.ownerDocument,te=q.defaultView??window,Z=ne=>{if(!ft||ne.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||te.innerWidth<=640)return;ne.preventDefault(),Cm();let pe=ne.clientX,Ce=ft.element.getBoundingClientRect().width,He=o.features?.artifacts?.layout,wt=Ft=>{let xn=Qo.getBoundingClientRect().width,pn=t.classList.contains("persona-artifact-welded-split"),Jt=ny(Qo,te),Bn=pn?0:k.getBoundingClientRect().width||6,Mt=Ce-(Ft.clientX-pe),On=rT(Mt,xn,Jt,Bn,He?.resizableMinWidth,He?.resizableMaxWidth,AE());ft.element.style.width=`${On}px`,ft.element.style.maxWidth="none",ab()},Ot=()=>{q.removeEventListener("pointermove",wt),q.removeEventListener("pointerup",Ot),q.removeEventListener("pointercancel",Ot),jc=null;try{k.releasePointerCapture(ne.pointerId)}catch{}};jc=Ot,q.addEventListener("pointermove",wt),q.addEventListener("pointerup",Ot),q.addEventListener("pointercancel",Ot);try{k.setPointerCapture(ne.pointerId)}catch{}};k.addEventListener("pointerdown",Z),Ut=k,Qo.insertBefore(k,ft.element),Ya=()=>{k.removeEventListener("pointerdown",Z)}}if(Ut){let k=qc();Ut.classList.toggle("persona-hidden",!k),ab()}},Qc=()=>{if(!ce||!ft||(o.launcher?.sidebarMode??!1)||rn(o)&&Lo(o).reveal==="emerge")return;let k=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640;if(q&&k.innerWidth<=te||!JM(o,ce))return;let Z=o.launcher?.width??o.launcherWidth??Rr,ne=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";qc()?(_e.style.width=ne,_e.style.maxWidth=ne):(_e.style.width=Z,_e.style.maxWidth=Z)},typeof ResizeObserver<"u"&&(ja=new ResizeObserver(()=>{Wo()}),ja.observe(_e))}else _e.appendChild(Le);Ee()&&Kt&&(Ze.peekBanner&&Kt.appendChild(Ze.peekBanner),Kt.appendChild(We)),t.appendChild(it),Kt&&t.appendChild(Kt);let wm=()=>{if(Ee()){_e.style.width="100%",_e.style.maxWidth="100%";let st=o.launcher?.composerBar??{},Ue=it.dataset.state==="expanded",_n=st.expandedSize??"anchored";if(!(Ue&&_n!=="fullscreen")){Le.style.background="",Le.style.border="",Le.style.borderRadius="",Le.style.overflow="",Le.style.boxShadow="";return}let Zn=o.theme?.components?.panel,eo=Ca(o),Rt=(on,to)=>on==null||on===""?to:zn(eo,on)??on,Dt="1px solid var(--persona-border)",rt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Lr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Le.style.background="var(--persona-surface, #ffffff)",Le.style.border=Rt(Zn?.border,Dt),Le.style.borderRadius=Rt(Zn?.borderRadius,Lr),Le.style.boxShadow=Rt(Zn?.shadow,rt),Le.style.overflow="hidden";return}let i=rn(o),c=o.launcher?.sidebarMode??!1,f=i||c||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,q=Ca(o),te=(st,Ue)=>st==null||st===""?Ue:zn(q,st)??st,Z=t.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,Ce=Z.innerWidth<=pe,He=ne&&Ce&&ce,wt=i&&ne&&Ce,Ot=o.launcher?.position??"bottom-left",Ft=Ot==="bottom-left"||Ot==="top-left",xn=o.launcher?.zIndex??Hn,pn="var(--persona-panel-border, 1px solid var(--persona-border))",Jt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Bn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Mt=x&&!He&&!wt;Mt?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let On=Mt?pn:c||He?"none":pn,or=Mt?Jt:He?"none":c?Ft?"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))":y?"none":Jt;i&&!He&&!Mt&&(or="none",On="none");let kr=Mt?Bn:c||He?"0":Bn,Do=te(k?.border,On),Sl=te(k?.shadow,or),ei=te(k?.borderRadius,kr),_o=Xc(),Ln=_o==="detached",No=_o==="welded";t.classList.toggle("persona-artifact-detached-split",Ln),t.classList.toggle("persona-artifact-welded-split",No);let Zi="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)))))",qe=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&jn(o)&&Zh(o)&&y&&!i;t.classList.toggle("persona-artifact-chat-flush",qe);let xe=Ln||qe?"none":Sl,Zt=Ln?pn:No?"none":Do,un=Ln?Bn:ei;qe&&(Zt="none",un="0");let Pn=k?.borderRadius!=null&&k.borderRadius!=="",mn=qe&&!Pn?"0":ei,bn=ie.scrollTop;t.style.cssText="",it.style.cssText="",_e.style.cssText="",Le.style.cssText="",ie.style.cssText="",Ti||(We.style.cssText=""),Tt&&(ie.style.display="none"),(f||y)&&(t.style.minWidth="0");let en=()=>{if(bn<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===bn)return;let Ue=ie.scrollHeight-ie.clientHeight;Ue<=0||(ie.scrollTop=Math.min(bn,Ue))})};if(He){it.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"),it.style.cssText=`
1174
1174
  position: fixed !important;
1175
1175
  inset: 0 !important;
1176
1176
  width: 100% !important;
@@ -1206,7 +1206,7 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1206
1206
  overflow: hidden !important;
1207
1207
  border-radius: 0 !important;
1208
1208
  border: none !important;
1209
- `,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",We.style.flexShrink="0",lm(),nt=!0,en();return}let tt=o?.launcher?.width??o?.launcherWidth??Rr;if(!c&&!i)y&&f?(_e.style.width="100%",_e.style.maxWidth="100%"):(_e.style.width=tt,_e.style.maxWidth=tt);else if(i)if(ko(o).reveal==="emerge"&&!x){let Ue=ko(o).width;_e.style.width=Ue,_e.style.maxWidth=Ue}else _e.style.width="100%",_e.style.maxWidth="100%";if(Qc(),_e.style.boxShadow=xe,_e.style.borderRadius=mn,Ln?_e.style.border="none":_o&&(_e.style.border=Oo),Le.style.border=Zt,Le.style.borderRadius=un,Le.style.boxShadow=Ln&&!qe?Zi:"",qe&&(Le.style.background="transparent",ie.style.background="transparent",We.style.background="transparent",We.style.borderTop="none"),_o){let st=o.features?.artifacts?.layout;Uc=st?.unifiedSplitOuterRadius?.trim()||st?.paneBorderRadius?.trim()||ei}else Uc=null;if(i&&!He&&!Mt&&!Ln&&!_o&&k?.border===void 0&&(Le.style.border="none",ko(o).side==="right"?Le.style.borderLeft="1px solid var(--persona-border)":Le.style.borderRight="1px solid var(--persona-border)"),i&&!He&&_o&&k?.border===void 0&&(ko(o).side==="right"?_e.style.borderLeft="1px solid var(--persona-border)":_e.style.borderRight="1px solid var(--persona-border)"),f&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",y&&(t.style.width="100%"),it.style.display="flex",it.style.flexDirection="column",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.maxHeight="100%",it.style.height="100%",y&&(it.style.overflow="hidden"),_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1 1 0%",_e.style.minHeight="0",_e.style.maxHeight="100%",_e.style.height="100%",Ln||(_e.style.overflow="hidden"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",We.style.flexShrink="0"),y&&(Mt||Ln||qe)&&!i&&(qe||(it.style.padding="var(--persona-panel-inset)"),it.style.background="var(--persona-panel-canvas-bg)"),it.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"),!c&&!y&&!i&&(go[Ot]??go["bottom-right"]).split(" ").forEach(Ue=>it.classList.add(Ue)),c){let st=o.launcher?.sidebarWidth??"420px";x?it.style.cssText=`
1209
+ `,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",We.style.flexShrink="0",lm(),nt=!0,en();return}let tt=o?.launcher?.width??o?.launcherWidth??Rr;if(!c&&!i)y&&f?(_e.style.width="100%",_e.style.maxWidth="100%"):(_e.style.width=tt,_e.style.maxWidth=tt);else if(i)if(Lo(o).reveal==="emerge"&&!x){let Ue=Lo(o).width;_e.style.width=Ue,_e.style.maxWidth=Ue}else _e.style.width="100%",_e.style.maxWidth="100%";if(Qc(),_e.style.boxShadow=xe,_e.style.borderRadius=mn,Ln?_e.style.border="none":No&&(_e.style.border=Do),Le.style.border=Zt,Le.style.borderRadius=un,Le.style.boxShadow=Ln&&!qe?Zi:"",qe&&(Le.style.background="transparent",ie.style.background="transparent",We.style.background="transparent",We.style.borderTop="none"),No){let st=o.features?.artifacts?.layout;Uc=st?.unifiedSplitOuterRadius?.trim()||st?.paneBorderRadius?.trim()||ei}else Uc=null;if(i&&!He&&!Mt&&!Ln&&!No&&k?.border===void 0&&(Le.style.border="none",Lo(o).side==="right"?Le.style.borderLeft="1px solid var(--persona-border)":Le.style.borderRight="1px solid var(--persona-border)"),i&&!He&&No&&k?.border===void 0&&(Lo(o).side==="right"?_e.style.borderLeft="1px solid var(--persona-border)":_e.style.borderRight="1px solid var(--persona-border)"),f&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",y&&(t.style.width="100%"),it.style.display="flex",it.style.flexDirection="column",it.style.flex="1 1 0%",it.style.minHeight="0",it.style.maxHeight="100%",it.style.height="100%",y&&(it.style.overflow="hidden"),_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1 1 0%",_e.style.minHeight="0",_e.style.maxHeight="100%",_e.style.height="100%",Ln||(_e.style.overflow="hidden"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",We.style.flexShrink="0"),y&&(Mt||Ln||qe)&&!i&&(qe||(it.style.padding="var(--persona-panel-inset)"),it.style.background="var(--persona-panel-canvas-bg)"),it.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"),!c&&!y&&!i&&(go[Ot]??go["bottom-right"]).split(" ").forEach(Ue=>it.classList.add(Ue)),c){let st=o.launcher?.sidebarWidth??"420px";x?it.style.cssText=`
1210
1210
  position: fixed !important;
1211
1211
  top: var(--persona-panel-inset) !important;
1212
1212
  bottom: var(--persona-panel-inset) !important;
@@ -1245,7 +1245,7 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1245
1245
  padding: 0 !important;
1246
1246
  box-shadow: ${xe} !important;
1247
1247
  border-radius: ${mn} !important;
1248
- ${Ln?"border: none !important;":_o?`border: ${Oo} !important;`:""}
1248
+ ${Ln?"border: none !important;":No?`border: ${Do} !important;`:""}
1249
1249
  `,_e.style.setProperty("width","100%","important"),_e.style.setProperty("max-width","100%","important"),Le.style.cssText=`
1250
1250
  display: flex !important;
1251
1251
  flex-direction: column !important;
@@ -1264,7 +1264,7 @@ _Details: ${n.message}_`:o}var ug=t=>({isError:!0,content:[{type:"text",text:t}]
1264
1264
  border-top: none !important;
1265
1265
  padding: 8px 16px 12px 16px !important;
1266
1266
  ${qe?"background: transparent !important;":""}
1267
- `)}if(!y&&!i){let st="max-height: -moz-available !important; max-height: stretch !important;",Ue=c?"":"padding-top: 1.25em !important;",_n=c?"":`z-index: ${o.launcher?.zIndex??Hn} !important;`;it.style.cssText+=st+Ue+_n}lm(),en()},xm=()=>{t.style.setProperty("--persona-content-max-width",ys(o,Ee()))},lb=!1,cb=()=>{let i=Gg(o,Ee());Ee()&&o.composer?.placement&&o.debug===!0&&!lb&&(lb=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=Br(o);t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",Nc),t.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",c.composerGap??iu),Vc()},db=()=>{if(Ee())return;let i=rn(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ce)return;let y=t.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=k)return;let q=y.innerHeight,te=64,Z=o.launcher?.heightOffset??0,ne=Math.max(200,q-te),pe=Math.min(640,ne);_e.style.height=`${Math.max(200,pe-Z)}px`};wm(),Zl(t,o),kc(t,o),Lc(t,o),xm(),cb(),Es=()=>{wm(),db(),Zl(t,o),kc(t,o),Lc(t,o),xm(),cb(),Uc?t.style.setProperty("--persona-artifact-welded-outer-radius",Uc):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ut(),Ke()};let De=[];De.push(()=>{nb=!0}),De.push(()=>{d.forEach(i=>i()),l.destroy()}),De.push(()=>{document.removeEventListener("keydown",sb)}),De.push(()=>{za!==null&&clearTimeout(za)});let Qo=null,Xo=null;De.push(()=>{Qo?.(),Qo=null,Xo?.(),Xo=null}),ja&&De.push(()=>{ja?.disconnect(),ja=null}),De.push(()=>{Ya?.(),Ya=null,Cm(),Ut&&(Ut.remove(),Ut=null),ft?.element.style.removeProperty("width"),ft?.element.style.removeProperty("maxWidth"),ft?.destroy()}),L&&De.push(()=>{Je=!0,ot=null,ee!==null&&(cancelAnimationFrame(ee),ee=null),mt?.destroy(),mt=null,je?.destroy(),je=null,Te=null});let Ls=null,pb=()=>{Ls&&(Ls(),Ls=null),o.colorScheme==="auto"&&(Ls=su(()=>{Zl(t,o)}))};pb(),De.push(()=>{Ls&&(Ls(),Ls=null)}),De.push(()=>{b=!0,g?.()}),De.push(()=>{M=!0});let ub=!1;De.push(()=>{ub=!0});let Sm=(i,c)=>{let f=oc(i,c);return f||!ZS.includes(i)?f:(bA().then(y=>{if(ub)return;ii(y.wipe),ii(y.glyphCycle);let x=oc(i,c);x&&ic(x,t)}).catch(()=>{}),null)},Jc=o.features?.streamAnimation;if(Jc?.type&&Jc.type!=="none"){let i=Sm(Jc.type,Jc.plugins);i&&ic(i,t),De.push(()=>eA(t))}let gr=uc(Po),mb=uc(wi),fb=uc(Vr),Ps=[gr,mb,fb];De.push(()=>{Ps.forEach(i=>i.destroy())});let Is=null,_,Hs=null,gb=!1,hb=0,yb=null,bb=i=>i.reduce((c,f)=>f.role==="user"?c+1:c,0),vb=i=>{for(let c=i.length-1;c>=0;c--)if(Pl(i[c]))return i[c].id??null;return null},Cb=!1,TE=()=>{Cb||o.debug!==!0||(Cb=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},wb=!1,xb=!1,Sb=(i,c)=>{wb||o.debug!==!0||!c.enabled||c.expose||gb||xb&&(_.isStreaming()||i.some(Pl)||(wb=!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.")))},Pi=i=>{if(!_)return;let c=i??_.getMessages(),f=ne=>{ne.render([],_,Ae,c)},y=ne=>{Ps.forEach(pe=>{pe!==ne&&f(pe)})};Hs&&(bb(c)>hb||vb(c)!==yb)&&(Hs=null);let x=ps(o);Sb(c,x);let k=x.enabled?ow(c):null,q=Hs??k,te=Hs?"host":"agent";if(q){let ne=o.suggestions?.followUps,pe=ne?.placement??(ne?"auto":"composer"),He=(pe==="auto"?Ee()?"composer":"after-message":pe)==="after-message"?fb:gr;y(He),He.render(q,_,Ae,c,o.suggestionChipsConfig,{source:te,surface:"followUp",variant:ne?.variant??"chip",behavior:ne?.behavior??"send",overflow:ne?.overflow??"wrap",maxItems:ne?.maxItems??4,config:o,plugins:a,submitPrompt:Nd});return}if(c.some(ne=>ne.role==="user")){Ps.forEach(f);return}let Z=o.suggestions?.starters;if(Z){let ne=Ma(Br(o),c),pe=Z.placement??"auto",Ce=pe==="auto"?ne?"welcome":"composer":pe;if(Ce==="welcome"&&!ne){TE(),Ps.forEach(f);return}let He=Ce==="welcome"?mb:gr;y(He),He.render(Z.items??o.suggestionChips,_,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:Z.variant??"card",behavior:Z.behavior??"send",overflow:Z.overflow??"wrap",maxItems:Z.maxItems??4,config:o,plugins:a,submitPrompt:Nd});return}y(gr),gr.render(o.suggestionChips,_,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Nd})},Ab=()=>{Hs&&(Hs=null,Pi())},EE=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){Ab();return}let f=_?_.getMessages():[];Hs=c,gb=!0,hb=bb(f),yb=vb(f),Pi(f)},lo=!1,cn=qS(),Ii=new Map,Rs=new Map,Kr=new Map,Ws=null,Gr=null;function Bs(){if(!Ws)return;let i=Ws;Ws=null,Gr?.destroy(),Gr=null,cn.delete(i),Le.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),_&&bo(Re,_.getMessages(),Ge)}let Os=0,kE=Ao()!==null,co=pu(),po=0,Yr=null,Yn=!1,Zc=!1,Qr=0,hn=null,Ds=null,Am=!1,Hi=!1,_s=null,Qa=!0,ed=!1,Ri=null,td=!1,Ns=()=>{td=!0,HE()},Mm=null,LE=4,hr=24,PE=80,IE=1e3,yr=null,Mb=()=>{t.setAttribute("data-persona-scrollbar",sm()),sm()!=="on-scroll"&&(yr!==null&&clearTimeout(yr),yr=null,ie.removeAttribute("data-persona-scrollbar-visible"))},HE=()=>{sm()==="on-scroll"&&(ie.setAttribute("data-persona-scrollbar-visible",""),yr!==null&&clearTimeout(yr),yr=setTimeout(()=>{yr=null,Wr(ie,hr)&&ie.removeAttribute("data-persona-scrollbar-visible")},IE))};Mb(),De.push(()=>{yr!==null&&clearTimeout(yr)});let Tm=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Yy=()=>gt.active,Io();let Tb=o.voiceRecognition?.autoResume??!1,br=i=>{E.emit("voice:state",{active:gt.active,source:i,timestamp:Date.now()})},Wo=()=>{Y(i=>({...i,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},RE=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Sy(H.voiceState),c=!!i.active,f=Number(i.timestamp??0);gt.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-f<PB&&setTimeout(()=>{gt.active||(gt.manuallyDeactivated=!1,no(o.voiceRecognition?.provider)?_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),br("restore"),_.isVoiceActive()&&Xi()}):$d("restore"))},1e3)},WE=()=>_?jT(_.getMessages()).filter(i=>!i.__skipPersist):[],nd=null,Eb=(i,c)=>{typeof console<"u"&&console.error(i,c)},od=(i,c)=>{let f=()=>{try{let q=i();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(te=>{Eb(c,te)})}catch(q){return Eb(c,q),null}},y=nd,x=y?y.then(()=>f()??void 0):f();if(!x)return;let k=x.finally(()=>{nd===k&&(nd=null)});nd=k};function Wi(i){if(!R?.save)return;let c=i?jT(i):_?WE():[],f=V&&_?.getResumableHandle();f&&(H={...H,durableResume:{executionId:f.executionId,after:f.lastEventId}});let y={messages:c,metadata:H,artifacts:yo.artifacts,selectedArtifactId:yo.selectedId,...Fs?{draft:Fs}:{}};od(()=>R.save(y),"[AgentWidget] Failed to persist state:")}let Fs,rd=()=>!R?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Xa=Vx({write:()=>{if(!rd())return;let i=ze.getState(),c=Nx({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Sf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Fs)&&(Fs=c,Wi())}});function kb(){rd()&&Xa.schedule()}function Em(){Xa.flush()}function Lb(i){if(!rd())return;let c=Fx(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});c&&(Fs=i,Ae&&!Ae.value&&(Ae.value=c.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),jo()),c.selectedModelId&&(ze.setSelectedModelId(c.selectedModelId),Ur?.repaint()),$c(c.activeModeIds??[]),c.quote&&Ko(c.quote),Xa.cancel())}function sd(){Xa.cancel(),Fs&&(Fs=void 0,rd()&&Wi())}let Bi=null,Pb=()=>it.querySelector("#persona-scroll-container")||ie,Oi=()=>{Bi!==null&&(cancelAnimationFrame(Bi),Bi=null),Yn=!1},Ib=()=>{Yr!==null&&(cancelAnimationFrame(Yr),Yr=null),Zc=!1,Oi()},BE=()=>lo&&Lm()&&(ao()!=="anchor-top"||Hy()),km=()=>{let i=Fa()||"Jump to latest",c=BE();ln.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Qr>0?(As.textContent=String(Qr),As.style.display="",ln.setAttribute("aria-label",`${i} (${Qr} new)`)):(As.textContent="",As.style.display="none",ln.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Hb=()=>{Qr!==0&&(Qr=0,km())},OE=()=>{let i=hn?.spacerHeight??0;return i<=0?Wr(ie,hr):cd(i)-ie.scrollTop-ie.clientHeight<=hr},Lm=()=>zr()?!co.isFollowing():!OE(),Pm=()=>!!_&&_.getMessages().length>0,yn=()=>{if(!dE()||Wt()){ln.parentNode&&ln.remove(),ln.style.display="none";return}ln.parentNode!==Le&&Le.appendChild(ln),Ms();let c=lr(ie)>0&&Lm()&&Pm();c?km():Hb(),ln.style.display=c?"":"none"},Ja=()=>{co.pause()&&(Ib(),yn())},Qn=()=>{co.resume(),Hb(),yn()},Xr=(i=!1)=>{zr()&&Pm()&&co.isFollowing()&&(!i&&!lo||(Yr!==null&&(cancelAnimationFrame(Yr),Yr=null),Zc=!0,Yr=requestAnimationFrame(()=>{Yr=null,Zc=!1,co.isFollowing()&&DE(Pb(),i?220:140)})))},Rb=(i,c,f,y=()=>!0)=>{let x=i.scrollTop,k=c(),q=k-x;if(Oi(),Math.abs(q)<1){Yn=!0,i.scrollTop=k,po=i.scrollTop,Yn=!1;return}let te=performance.now();Yn=!0;let Z=pe=>1-Math.pow(1-pe,3),ne=pe=>{if(!y()){Oi();return}let Ce=c();Ce!==k&&(k=Ce,q=k-x);let He=pe-te,wt=Math.min(He/f,1),Ot=Z(wt),Ft=x+q*Ot;i.scrollTop=Ft,po=i.scrollTop,wt<1?Bi=requestAnimationFrame(ne):(i.scrollTop=k,po=i.scrollTop,Bi=null,Yn=!1)};Bi=requestAnimationFrame(ne)},DE=(i,c=500)=>{let f=lr(i)-i.scrollTop;if(Math.abs(f)<1){po=i.scrollTop;return}if(Math.abs(f)>=PE){Oi(),Yn=!0,i.scrollTop=lr(i),po=i.scrollTop,Yn=!1;return}Rb(i,()=>lr(i),c,()=>co.isFollowing())},id=()=>{if(!Pm()){yn();return}let i=Pb();Yn=!0,i.scrollTop=lr(i),po=i.scrollTop,Yn=!1,yn()},Vs=i=>{let c=0,f=i;for(;f&&f!==ie;)c+=f.offsetTop,f=f.offsetParent;return c},_E=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},ad=()=>QS(_E(),ie),Im=()=>{if(pE()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(k=>k.role==="user");if(!c)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ie.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let x=Math.min(Math.max(0,Vs(y)-Va()),lr(ie));return Yn=!0,ie.scrollTop=x,po=ie.scrollTop,Yn=!1,ao()==="follow"&&!Wr(ie,hr)&&co.pause(),yn(),!0},ld=i=>{let c=Math.max(0,Math.round(i));ho.style.height=`${c}px`,ho.style.display=c>0?"":"none",hn&&(hn.spacerHeight=Math.max(0,i))},cd=i=>{let c=parseFloat(getComputedStyle(ie).paddingBottom)||0,f=0;for(let x of Array.from(ie.children)){if(x===ho||x.offsetHeight===0)continue;let k=Vs(x)+x.offsetHeight;k>f&&(f=k)}let y=ie.scrollHeight-i;return f>0?Math.min(f+c,y):y},NE=()=>{if(!hn||hn.spacerHeight<=0)return;let i=cd(hn.spacerHeight),c=Math.max(0,Math.round(ie.scrollTop)+ie.clientHeight-i+hr);c<hn.spacerHeight&&(ld(c),yn())},Bo=()=>{Ds!==null&&(cancelAnimationFrame(Ds),Ds=null),Oi(),hn=null,ho.style.height="0px",ho.style.display="none"},Wb=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Hm=i=>ie.querySelector(`[data-message-id="${Wb(i)}"]`),Bb=i=>{Ds!==null&&cancelAnimationFrame(Ds),Ds=requestAnimationFrame(()=>{Ds=null;let c=Wb(i),f=ie.querySelector(`[data-message-id="${c}"]`);if(!f)return;let y=Vs(f),x=hn?.spacerHeight??0,k=cd(x),{targetScrollTop:q,spacerHeight:te}=Xg({anchorOffsetTop:y,topOffset:Va(),viewportHeight:ie.clientHeight,contentHeight:k,slack:hr});hn={initialSpacerHeight:te,contentHeightAtAnchor:k,spacerHeight:te},ld(te),Rb(ie,()=>f.isConnected?Math.max(0,Vs(f)-Va()):q,220)})},Xn=()=>{if(ao()!=="anchor-top"||!hn||!Ri)return;let i=Hm(Ri);if(!i)return;Oi();let c=hn.spacerHeight,f=cd(c),{targetScrollTop:y,spacerHeight:x}=Xg({anchorOffsetTop:Vs(i),topOffset:Va(),viewportHeight:ie.clientHeight,contentHeight:f,slack:hr});hn={initialSpacerHeight:x,contentHeightAtAnchor:f,spacerHeight:x},ld(x),Yn=!0,ie.scrollTop=y,po=ie.scrollTop,Yn=!1,yn()},FE=()=>{if(zr()){if(!co.isFollowing()||Wr(ie,1))return;Xr(!lo);return}if(hn&&hn.initialSpacerHeight>0){let i=ie.scrollHeight-hn.spacerHeight,c=XS({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:i});c!==hn.spacerHeight&&ld(c)}yn()},VE=i=>{let c=ao();c==="follow"?(Qn(),Xr(!0)):c==="anchor-top"&&(Qa=!1,ed=!0,td=!1,Ri=i,Bb(i))},$E=()=>{if(ao()==="anchor-top"){if(ed){Qa=!1;return}Qa=!0,Bo(),Qn(),Xr(!0)}},zE=96,UE=i=>{if(_s===null)return!0;let c=Hm(_s),f=Hm(i);if(!c||!f)return!0;let y=Vs(f)-Vs(c);return Va()+y>ie.clientHeight-zE},qE=i=>{if(ao()!=="anchor-top"||!ed||td||ad())return;let c=_s===null;for(let f of i){if(!c){f.id===_s&&(c=!0);continue}if(YS(f)){if(f.id===Ri||!UE(f.id))return;Ri=f.id,Bb(f.id);return}}},jE=i=>{let c=new Map;i.forEach(f=>{let y=Tm.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(E.emit("assistant:message",f),!Hi&&(ao()!=="anchor-top"||Hy())&&Lm()&&(Qr+=1,km(),yn(),_c(Qr===1?"1 new message below.":`${Qr} new messages below.`))),f.role==="assistant"&&y?.streaming&&f.streaming===!1&&E.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&E.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):E.emit("approval:requested",{approval:f.approval,message:f}))}),Tm.clear(),c.forEach((f,y)=>{Tm.set(y,f)})},Za=(i,c)=>{let f=c==="user"?"user":"assistant",y=o.layout?.messages?.[f],x=y?.width??"content",k=y?.maxWidth??(x==="full"?"100%":void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${x}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",x),k?i.style.setProperty("--persona-message-row-max-width",k):i.style.removeProperty("--persona-message-row-max-width")},vr=(i,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),Za(f,c),f},KE=(i,c,f)=>{let y=document.createElement("div"),k=(()=>{let U=a.find(ct=>ct.renderLoadingIndicator);if(U?.renderLoadingIndicator)return U.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),q=(U,ct)=>ct==null?!1:typeof ct=="string"?(U.textContent=ct,!0):(U.appendChild(ct),!0),te=new Set,Z=new Map,ne=new Set,pe=a.some(U=>U.renderAskUserQuestion),Ce=[],He=[],wt=o.enableComponentStreaming!==!1,Ot=o.approval!==!1,Ft=[],xn=o.messageActions,pn=xn?.showRegenerate===!0&&xn.enabled!==!1&&Bt.current?.isStreaming()!==!0?Ww(c):null,Jt=xn?.showEdit===!0&&xn.enabled!==!1,Bn=xn?.showQuote===!0&&xn.enabled!==!1,Mt=null,On=o.features?.reasoningDisplay?.completedVisibility,nr=U=>On==="removed"?!0:On==="removed-when-short"?iw(U,o.features?.reasoningDisplay?.shortThinkThreshold):!1,kr=o.features?.toolCallDisplay?.completedVisibility==="removed",Oo=U=>U.variant==="reasoning"&&U.reasoning?.status==="complete"?nr(U.reasoning):kr&&U.variant==="tool"&&U.toolCall?.status==="complete";if(c.forEach(U=>{if(Oo(U))return;if(te.add(U.id),Z.set(U.id,U.role),Ws===U.id&&Gr){let Ue=vr(U.id,U.role);Ue.setAttribute("data-persona-message-edit-stub","true"),Ue.setAttribute("data-preserve-runtime","true"),y.appendChild(Ue),Mt={messageId:U.id,element:Gr.element};return}let ct=pe&&ni(U),qe=Ot&&U.variant==="approval"&&!!U.approval,xe=!ct&&U.role==="assistant"&&!U.variant&&wt&&xy(U);!qe&&Kr.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Kr.delete(U.id)),!xe&&Rs.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Rs.delete(U.id));let Zt=ni(U)?`:${U.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${U.agentMetadata?.askUserQuestionAnswers?Object.keys(U.agentMetadata.askUserQuestionAnswers).length:0}`:"",un={canRegenerate:pn===U.id,canEdit:Jt&&ng(U),canQuote:Bn&&!U.variant&&(U.content?.trim().length??0)>0},Pn=`${un.canRegenerate?"r":""}${un.canEdit?"e":""}${un.canQuote?"q":""}`,mn=US(U,Os)+Zt+`:${Pn}`,bn=ct||qe||xe?null:jS(cn,U.id,mn);if(bn){y.appendChild(bn.cloneNode(!0)),ni(U)&&U.toolCall?.id&&U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}let en=null,Dn=a.find(Ue=>!!(U.variant==="reasoning"&&Ue.renderReasoning||U.variant==="tool"&&Ue.renderToolCall||!U.variant&&Ue.renderMessage)),tt=o.layout?.messages;if(ni(U)&&U.agentMetadata?.askUserQuestionAnswered===!0){Ii.delete(U.id),i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime");return}if(Pl(U)&&ps(o).enabled)return;if(ni(U)&&o.features?.askUserQuestion?.enabled!==!1){let Ue=a.find(_n=>typeof _n.renderAskUserQuestion=="function");if(Ue&&Bt.current){let _n=Ii.get(U.id),rs=_n!==mn,Zn=null;if(rs){let{payload:Dt,complete:rt}=ia(U),Lr=U.id,on=()=>Bt.current?.getMessages().find(to=>to.id===Lr);Zn=Ue.renderAskUserQuestion({message:U,payload:Dt,complete:rt,resolve:to=>{let Al=on();Al&&Bt.current?.resolveAskUserQuestion(Al,to)},dismiss:()=>{let to=on();to?.agentMetadata?.awaitingLocalTool&&(Bt.current?.markAskUserQuestionResolved(to),Bt.current?.resolveAskUserQuestion(to,"(dismissed)"))},config:o})}let eo=_n!=null;if(rs&&Zn===null&&!eo){U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}let Rt=vr(U.id,U.role);Rt.setAttribute("data-ask-plugin-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),y.appendChild(Rt),Ce.push({messageId:U.id,fingerprint:mn,bubble:Zn});return}else{U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}}else if(qe){let Ue=P();if(!Ue){y.appendChild(vr(U.id,U.role));return}let _n=a.find(Rt=>typeof Rt.renderApproval=="function")??h,Zn=Kr.get(U.id)!==mn,eo=null;if(Zn&&_n?.renderApproval){let Rt=U.id,Dt=(rt,Lr)=>{let on=Bt.current?.getMessages().find(to=>to.id===Rt);on?.approval&&(on.approval.toolType==="webmcp"?Bt.current?.resolveWebMcpApproval(on.id,rt):Bt.current?.resolveApproval(on.approval,rt,Lr))};eo=_n.renderApproval({message:U,defaultRenderer:()=>Ue.createApprovalBubble(U,o),config:o,approve:rt=>Dt("approved",rt),deny:rt=>Dt("denied",rt)})}if(Zn&&eo===null)i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Kr.delete(U.id),en=Ue.createApprovalBubble(U,o);else{let Rt=vr(U.id,U.role);Rt.setAttribute("data-approval-plugin-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),y.appendChild(Rt),Ft.push({messageId:U.id,fingerprint:mn,bubble:eo});return}}else if(Dn)if(U.variant==="reasoning"&&U.reasoning&&Dn.renderReasoning){if(!yt)return;en=Dn.renderReasoning({message:U,defaultRenderer:()=>Mh(U,o),config:o})}else if(U.variant==="tool"&&U.toolCall&&Dn.renderToolCall){if(!X)return;en=Dn.renderToolCall({message:U,defaultRenderer:()=>Eh(U,o),config:o})}else Dn.renderMessage&&(en=Dn.renderMessage({message:U,defaultRenderer:()=>{let Ue=fh(U,f,tt,o.messageActions,St,{loadingIndicatorRenderer:k,widgetConfig:o,actionEligibility:un});return U.role!=="user"&&O(Ue,U,o,_),Ue},config:o}));if(!en&&xe){let Ue=zT(U);if(Ue){let _n=Rs.get(U.id),rs=_n!==mn,Zn=o.wrapComponentDirectiveInBubble!==!1&&$o.getOptions(Ue.component)?.bubbleChrome!==!1,eo=null;if(rs){let Rt=VT(Ue,{config:o,message:U,transform:f});if(Rt&&Ue.component==="PersonaArtifactInline"){let Dt=Rt.hasAttribute("data-artifact-inline")?Rt:Rt.querySelector("[data-artifact-inline]"),rt=Dt?.getAttribute("data-artifact-inline")??"",Lr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(rt):rt,on=rt?i.querySelector(`#wrapper-${U.id}`)?.querySelector(`[data-artifact-inline="${Lr}"]`)??null:null;Dt&&on&&on!==Dt&&Dr()?.hasLiveInlineArtifactBlock(on)&&(Dt===Rt?Rt=on:Dt.replaceWith(on))}if(Rt)if(Zn){let Dt=document.createElement("div");if(Dt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Dt.id=`bubble-${U.id}`,Dt.setAttribute("data-message-id",U.id),U.content&&U.content.trim()){let rt=document.createElement("div");rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",rt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Dt.appendChild(rt)}Dt.appendChild(Rt),eo=Dt}else{let Dt=document.createElement("div");if(Dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Dt.id=`bubble-${U.id}`,Dt.setAttribute("data-message-id",U.id),Dt.setAttribute("data-persona-component-directive","true"),U.content&&U.content.trim()){let rt=document.createElement("div");rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",rt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Dt.appendChild(rt)}Dt.appendChild(Rt),eo=Dt}}if(eo||_n!=null){let Rt=vr(U.id,U.role);Rt.setAttribute("data-component-directive-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),y.appendChild(Rt),He.push({messageId:U.id,fingerprint:mn,bubble:eo});return}}}if(!en)if(U.variant==="reasoning"&&U.reasoning){if(!yt)return;en=Mh(U,o)}else if(U.variant==="tool"&&U.toolCall){if(!X)return;en=Eh(U,o)}else if(U.variant==="approval"&&U.approval){if(o.approval===!1)return;let Ue=P();if(!Ue)return;en=Ue.createApprovalBubble(U,o)}else{let Ue=o.layout?.messages;Ue?.renderUserMessage&&U.role==="user"?en=Ue.renderUserMessage({message:U,config:o,streaming:!!U.streaming}):Ue?.renderAssistantMessage&&U.role==="assistant"?en=Ue.renderAssistantMessage({message:U,config:o,streaming:!!U.streaming}):en=fh(U,f,Ue,o.messageActions,St,{loadingIndicatorRenderer:k,widgetConfig:o,actionEligibility:un}),U.role!=="user"&&en&&O(en,U,o,_)}let st=vr(U.id,U.role);st.appendChild(en),KS(cn,U.id,mn,st),y.appendChild(st)}),Ze.composerOverlay&&Ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ct=>{let qe=ct.getAttribute("data-persona-ask-sheet-for");qe&&!ne.has(qe)&&la(Ze.composerOverlay,qe)}),o.features?.toolCallDisplay?.grouped){let U=[],ct=[],qe=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(xe=>{if(xe.variant==="tool"&&xe.toolCall&&X){if(kr&&xe.toolCall.status==="complete")return;ct.push(xe);return}xe.variant==="reasoning"&&(!yt||xe.reasoning?.status==="complete"&&nr(xe.reasoning))||((ct.length>1||qe&&ct.length>0)&&U.push(ct),ct=[])}),(ct.length>1||qe&&ct.length>0)&&U.push(ct),U.forEach(xe=>{let Zt=xe.map(tt=>Array.from(y.children).find(st=>st instanceof HTMLElement&&st.getAttribute("data-wrapper-id")===tt.id)).filter(tt=>!!tt);if(Zt.length<(qe?1:2))return;let un=vr(`tool-group-${xe[0].id}`,"assistant");un.setAttribute("data-persona-tool-group-row","true");let Pn=document.createElement("div");Pn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Pn.setAttribute("data-persona-tool-group","true");let mn=document.createElement("div");mn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mn.id=`tool-group-summary-${xe[0].id}`;let bn=`Called ${xe.length} ${xe.length===1?"tool":"tools"}`,en=o.toolCall?.renderGroupedSummary?.({messages:xe,toolCalls:xe.map(tt=>tt.toolCall).filter(tt=>!!tt),defaultSummary:bn,config:o});q(mn,en)||(mn.textContent=bn);let Dn=document.createElement("div");Dn.className="persona-tool-group-stack persona-flex persona-flex-col",Dn.id=`tool-group-stack-${xe[0].id}`,Dn.setAttribute("data-persona-tool-group-stack","true"),Pn.appendChild(mn),qe||Pn.appendChild(Dn),un.appendChild(Pn),Zt[0].before(un),Zt.forEach((tt,st)=>{if(qe){tt.remove();return}tt.style.setProperty("--persona-message-row-max-width","100%");let Ue=document.createElement("div");Ue.className="persona-tool-group-item persona-relative",Ue.setAttribute("data-persona-tool-group-item","true"),st<Zt.length-1&&Ue.setAttribute("data-persona-tool-group-connector","true"),Ue.appendChild(tt),Dn.appendChild(Ue)})})}GS(cn,te);let Sl=U=>U.variant==="tool"&&!X||U.variant==="reasoning"&&!yt||Oo(U),ei=c.some(U=>U.role==="assistant"&&U.streaming&&!Sl(U)),Do=c.length-1;for(;Do>=0&&Sl(c[Do]);)Do--;let Ln=Do>=0?c[Do]:void 0,_o=Do<c.length-1,Zi=Ln?.role==="assistant"&&!Ln.streaming&&Ln.variant!=="approval"&&!_o;if(lo&&c.some(U=>U.role==="user")&&!ei&&!Zi){let U={config:o,streaming:!0,location:"standalone",defaultRenderer:hc},ct=a.find(xe=>xe.renderLoadingIndicator),qe=null;if(ct?.renderLoadingIndicator&&(qe=ct.renderLoadingIndicator(U)),qe===null&&o.loadingIndicator?.render&&(qe=o.loadingIndicator.render(U)),qe===null&&(qe=hc()),qe){let xe=document.createElement("div"),Zt=o.loadingIndicator?.showBubble!==!1,un=o.layout?.messages?.layout??"bubble";xe.className=Zt?yc("assistant",un).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),xe.setAttribute("data-typing-indicator","true"),Zt&&(xe.style.color="var(--persona-message-assistant-text, var(--persona-text))",un!=="flat"&&(xe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",xe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),xe.appendChild(qe);let Pn=vr("typing-indicator","assistant");Pn.appendChild(xe),y.appendChild(Pn)}}if(!lo&&c.length>0){let U=c[c.length-1],ct={config:o,lastMessage:U,messageCount:c.length},qe=a.find(Zt=>Zt.renderIdleIndicator),xe=null;if(qe?.renderIdleIndicator&&(xe=qe.renderIdleIndicator(ct)),xe===null&&o.loadingIndicator?.renderIdle&&(xe=o.loadingIndicator.renderIdle(ct)),xe){let Zt=document.createElement("div"),un=o.loadingIndicator?.showBubble!==!1;Zt.className=un?["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(" "),Zt.setAttribute("data-idle-indicator","true"),Zt.appendChild(xe);let Pn=vr("idle-indicator","assistant");Pn.appendChild(Zt),y.appendChild(Pn)}}if(kC(y),du(i,y),Vf(i),Mt){let{messageId:U,element:ct}=Mt,qe=i.querySelector(`#wrapper-${U}`);qe&&ct.parentElement!==qe&&(Za(qe,Z.get(U)??"user"),qe.replaceChildren(ct))}if(Ce.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of Ce){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Ii.set(U,ct)))}if(Ii.size>0)for(let U of Ii.keys())te.has(U)||Ii.delete(U);if(He.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of He){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Rs.set(U,ct)))}if(Rs.size>0)for(let U of Rs.keys())te.has(U)||Rs.delete(U);if(Ft.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of Ft){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Kr.set(U,ct)))}if(Kr.size>0)for(let U of Kr.keys())te.has(U)||Kr.delete(U)},Rm=!1,dd=()=>{Rm||(Rm=!0,CC().catch(()=>{Rm=!1}))},bo=(i,c,f)=>{c.length>0&&dd(),KE(i,c,f),tb()},el=null,GE=()=>{if(el)return;let i=f=>{let y=f.composedPath();y.includes(it)||Kt&&y.includes(Kt)||Nt(!1,"user")};el=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Ob=()=>{if(!el)return;(t.ownerDocument??document).removeEventListener("pointerdown",el,!0),el=null};De.push(()=>Ob());let tl=null,YE=()=>{if(tl)return;let i=f=>{f.key==="Escape"&&(f.isComposing||Nt(!1,"user"))};tl=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Db=()=>{if(!tl)return;(t.ownerDocument??document).removeEventListener("keydown",tl,!0),tl=null};De.push(()=>Db());let nl=!1,_b=new Set,QE=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Di=()=>{if(!Ee())return;let i=Ze.peekBanner,c=Ze.peekTextNode;if(!i||!c)return;if(Pe){i.classList.remove("persona-pill-peek--visible");return}let f=_?.getMessages()??[],y;for(let pn=f.length-1;pn>=0;pn--){let Jt=f[pn];if(Jt.role==="assistant"&&Jt.content){y=Jt;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let x=y.content,k=!!y.streaming,q=QE(),te=fu(q),Z=te.type!=="none"?Sm(te.type,q?.plugins):null,ne=Z?.isAnimating?.(y)===!0,pe=Z!==null&&(k||ne);pe&&Z&&!_b.has(Z.name)&&(ic(Z,t),_b.add(Z.name));let Ce=pe&&Z?.containerClass?Z.containerClass:null,He=c.dataset.personaPeekStreamClass??null;He&&He!==Ce&&(c.classList.remove(He),delete c.dataset.personaPeekStreamClass),Ce&&He!==Ce&&(c.classList.add(Ce),c.dataset.personaPeekStreamClass=Ce),pe?(c.style.setProperty("--persona-stream-step",`${te.speed}ms`),c.style.setProperty("--persona-stream-duration",`${te.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let wt=pe?gu(x,te.buffer,Z,y,k):x;if(pe&&te.placeholder==="skeleton"&&k&&(!wt||!wt.trim())){let pn=document.createElement("div"),Jt=sc();Jt.classList.add("persona-pill-peek__skeleton"),pn.appendChild(Jt),du(c,pn)}else{let pn=Math.max(0,wt.length-100),Jt=wt.length>100?wt.slice(-100):wt,Bn=Pr(Jt);if(!pe||!Z){let Mt=wt.length>100?`\u2026${Jt}`:Jt;c.textContent!==Mt&&(c.textContent=Mt)}else{let Mt=Bn;(Z.wrap==="char"||Z.wrap==="word")&&(Mt=rc(Bn,Z.wrap,`peek-${y.id}`,{skipTags:Z.skipTags,startIndex:pn}));let On=document.createElement("div");if(On.innerHTML=Mt,Z.useCaret&&Jt.length>0){let nr=hu(),kr=On.querySelectorAll(".persona-stream-char, .persona-stream-word"),Oo=kr[kr.length-1];Oo?.parentNode?Oo.parentNode.insertBefore(nr,Oo.nextSibling):On.appendChild(nr)}du(c,On),Z.onAfterRender?.({container:c,bubble:i,messageId:y.id,message:y,speed:te.speed,duration:te.duration})}}let xn=lo||nl;i.classList.toggle("persona-pill-peek--visible",xn)};if(Ee()){let i=Ze.peekBanner;if(i){let y=x=>{x.preventDefault(),x.stopPropagation(),Nt(!0,"user")};i.addEventListener("pointerdown",y),De.push(()=>{i.removeEventListener("pointerdown",y)})}let c=()=>{nl||(nl=!0,Di())},f=()=>{nl&&(nl=!1,Di())};_e.addEventListener("pointerenter",c),_e.addEventListener("pointerleave",f),De.push(()=>{_e.removeEventListener("pointerenter",c),_e.removeEventListener("pointerleave",f)}),Kt&&(Kt.addEventListener("pointerenter",c),Kt.addEventListener("pointerleave",f),De.push(()=>{Kt.removeEventListener("pointerenter",c),Kt.removeEventListener("pointerleave",f)}))}let XE=i=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",y=c.bottomOffset??"16px",x=c.collapsedMaxWidth,k=c.expandedMaxWidth??"880px",q=c.expandedTopOffset??"5vh",te=c.modalMaxWidth??"880px",Z=c.modalMaxHeight??"min(90vh, 800px)",ne="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Ce=it.style;if(Ce.left="",Ce.right="",Ce.top="",Ce.bottom="",Ce.transform="",Ce.width="",Ce.maxWidth="",Ce.height="",Ce.maxHeight="",Kt){let He=Kt.style;He.bottom=y,He.width=x??""}if(i&&f!=="fullscreen"){if(f==="modal"){Ce.top="50%",Ce.left="50%",Ce.transform="translate(-50%, -50%)",Ce.bottom="auto",Ce.right="auto",Ce.width=te,Ce.maxWidth=ne,Ce.maxHeight=Z,Ce.height=Z;return}Ce.left="50%",Ce.transform="translateX(-50%)",Ce.bottom=`calc(${y} + ${pe})`,Ce.top=q,Ce.width=k,Ce.maxWidth=ne}},ol=()=>{if(Pe&&dd(),!Ne())return;if(Ee()){let ne=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=Pe?"expanded":"collapsed";it.dataset.state=pe,it.dataset.expandedSize=ne,Kt&&(Kt.dataset.state=pe,Kt.dataset.expandedSize=ne),it.style.removeProperty("display"),it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),XE(Pe),Le.style.display=Pe?"flex":"none",Es(),Pe?(GE(),YE()):(Ob(),Db()),Di();return}let i=rn(o),c=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,x=c.innerWidth<=f,k=y&&x&&ce,q=ko(o).reveal;Pe?(it.style.removeProperty("display"),it.style.display=i?"flex":"",it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-95","persona-opacity-0"),_e.classList.add("persona-scale-100","persona-opacity-100"),Qt?(Qt.setPanelOpen(!0),Qt.element.style.display="none"):Fn&&(Fn.style.display="none")):(i?i&&(q==="overlay"||q==="push")&&!k?(it.style.removeProperty("display"),it.style.display="flex",it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(it.style.setProperty("display","none","important"),it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(it.style.display="",it.classList.add("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100"),_e.classList.add("persona-scale-95","persona-opacity-0")),Qt?(Qt.setPanelOpen(!1),Qt.element.style.display=i?"none":""):Fn&&(Fn.style.display=i?"none":""))},Nt=(i,c="user")=>{if(!Ne()||Pe===i)return;let f=Pe;Pe=i,ol();let y=(()=>{let k=o.launcher?.sidebarMode??!1,q=t.ownerDocument.defaultView??window,te=o.launcher?.mobileFullscreen??!0,Z=o.launcher?.mobileBreakpoint??640,ne=q.innerWidth<=Z,pe=rn(o)&&te&&ne,Ce=Ee()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||te&&ne&&ce||pe||Ce})();if(Pe&&y){if(!Qo){let k=t.getRootNode(),q=k instanceof ShadowRoot?k.host:t.closest(".persona-host");q&&(Qo=rh(q,o.launcher?.zIndex??Hn))}Xo||(Xo=sh(t.ownerDocument))}else Pe||(Qo?.(),Qo=null,Xo?.(),Xo=null);Pe&&(Cl(),Im()||(ao()==="follow"?Xr(!0):id()));let x={open:Pe,source:c,timestamp:Date.now()};Pe&&!f?E.emit("widget:opened",x):!Pe&&f&&E.emit("widget:closed",x),E.emit("widget:state",{open:Pe,launcherEnabled:ce,voiceActive:gt.active,streaming:_.isStreaming()})},Jr={inputDisabled:!1,sendDisabled:!1},Jo=()=>Jr.inputDisabled,Wm=()=>no(o.voiceRecognition?.provider)&&!!_&&(_.isBargeInActive()||["listening","processing","speaking"].includes(_.getVoiceStatus())),$s=()=>Jr.inputDisabled||Jr.sendDisabled,JE=()=>(Jr.inputDisabled?Jr.inputReason:void 0)??(Jr.sendDisabled?Jr.sendReason:void 0);function Bm(){if(!Ve)return;if(ze.getState().phase==="streaming"){Ve.disabled=!1;return}let i=At?!At.isReady():!1;Ve.disabled=$s()||i}function pd(){if(!qo)return;let i=ze.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;qo.toggleAttribute("data-persona-send-hidden",c)}function ZE(){let i=JE();if(Ee()){let c=Wn??We;i?c.setAttribute("title",i):c.removeAttribute("title"),We.toggleAttribute(Oa,!!i);return}if(i){bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.setAttribute(Oa,""),bt.textContent=i;return}if(bt.hasAttribute(Oa)&&(bt.removeAttribute("role"),bt.removeAttribute("aria-live"),bt.removeAttribute(Oa),p)){let c=_.getStatus();Rn(bt,sn(c),o.statusIndicator??{},c)}}function Om(){let i=wg(o.composer?.inputDisabled),c=wg(o.composer?.sendDisabled);Jr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},ze.setInputDisabled(i.disabled),ze.setSendDisabled(c.disabled);let f=ze.getState().phase==="streaming",y=i.disabled,x=f||y;Ae&&(Ae instanceof HTMLTextAreaElement?Ae.disabled=y:Ae.setAttribute("contenteditable",y?"false":"true"),Ae.setAttribute("aria-disabled",y?"true":"false")),Gt&&(Gt.disabled=y),zt&&(zt.disabled=y);for(let k of nn?.affordanceButtons??[])k.querySelectorAll("button").forEach(q=>{q.disabled=y});fe&&(fe.disabled=y||f&&!Wm()),Ps.forEach(k=>{k.elements.forEach(q=>{q.toggleAttribute("data-disabled",x),q instanceof HTMLButtonElement||q.setAttribute("aria-disabled",x?"true":"false")}),k.buttons.forEach(q=>{q.disabled=x})}),Vm.forEach(k=>{k.toggleAttribute("data-disabled",x),k instanceof HTMLButtonElement?k.disabled=x:k.setAttribute("aria-disabled",x?"true":"false"),k.querySelectorAll("button").forEach(q=>{q.disabled=x})}),We.dataset.personaComposerStreaming=f?"true":"false",We.dataset.personaComposerInputDisabled=y?"true":"false",We.dataset.personaComposerSendDisabled=$s()?"true":"false",We.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=f)}),Bm(),ZE()}let rl=i=>{ze.setStreaming(i),Py(i?"stop":"send"),Om()},zs=()=>{gt.active||Ae&&Ae.focus()};E.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>zs(),200)});let Us=null,sl=!1,Dm=!an.hidden,Zr=null,_m=!w,ud=null;De.push(()=>{ud?.cancel(),ud=null});let ek=i=>{let c=NA(i);if(c===Nc)return;Nc=c,t.setAttribute("data-persona-conversation-state",c);let f=am();Vc(),_m&&(ud?.cancel(),ud=DA(We,c==="active"?f:am(),c==="active"?"drop":"rise")),Xn()},Nb=null,Fb,Vb=null,_i=null,Nm=!1,il=i=>{let c=Br(o),f=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(f!==Nb||c.icon!==Fb)&&(Nb=f,Fb=c.icon,Au({host:an,iconHolder:_a,kicker:Na,title:om,subtitle:rm,starterSuggestions:wi},c));let y=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;y!==Vb&&(Vb=y,Mu(kn,c.message,o));let x=i??(_?_.getMessages():o.initialMessages);ek(x);let k=sl,q=!k&&Ma(c,x),te=q!==Dm;if(Dm=q,_i){Zr?.cancel(),Zr=null,k!==Nm&&(Nm=k,k?yh(ie,an,null):hh(ie,an,_i)),Aa(ie,an,!k);return}if(te&&!q&&!k&&c.dismiss==="on-first-message"&&_m){Zr=OA(an,ne=>{Zr===ne&&(Zr=null),!Dm&&!_i&&(Aa(ie,an,!1),Xn()),ne?.cancel()});return}if(Zr){if(!q&&!k)return;Zr.cancel(),Zr=null}let Z=!an.hidden;Aa(ie,an,q),!q&&Z&&Xn()},Fm=[],Vm=[],$m=!1,$b=null,zb,Ub=()=>{Vm.length=0;let i=Fm.splice(0,Fm.length);for(let c of i)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};De.push(Ub);let tk=(i,c)=>{let f=ah(i,c);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let y=o.suggestions?.starters,x=lh({item:{...f,behavior:f.behavior??y?.behavior??"send"},index:c,surface:"starter",source:"config",variant:y?.variant??"card",streaming:p?_.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:_,getTextarea:()=>Ae,eventTarget:an,submitPrompt:Nd});return Vm.push(x),x},zm=()=>{if($m)return;$m=!0;let i=Br(o);$b=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,zb=i.icon;try{Ub(),yh(ie,an,_i),_i=null,Nm=!1;let c=_?_.getMessages():o.initialMessages,f=Ma(i,c),y=0,x=null;for(let k of a)if(k.renderWelcome&&(x=k.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>an,sendMessage:q=>{if(!_||_.isStreaming())return;let te=q.trim();te&&_.sendMessage(te)},requestRender:()=>zm(),renderStarter:q=>tk(q,y++),storage:u(k.id),onCleanup:q=>{Fm.push(q)}}),x))break;x&&x!==an&&(_i=x,hh(ie,an,x))}finally{$m=!1}il()},nk=()=>{let i=Br(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===$b&&i.icon===zb||zm()},md=()=>{il(),Ti||(Ae.placeholder=Wx(ze.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(Ve.textContent=o.copy?.sendButtonLabel??"Send")),Ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},ok=!!o.setStoredConversationId,Ni=i=>Y(c=>{let f={...c};return delete f[i],f}),fd=i=>{let c=H[i];return typeof c=="string"?c:null},qb=()=>{let i=H.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>fd("sessionId"),setStoredSessionId:i=>{Y(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ni("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>fd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{Y(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ni("conversationId"))});let jb=()=>o.clientToken??null,Kb=i=>bT(i,Q(),o.persistState===!1),Gb=jb(),Cr=Gb?Kb(Gb):null,wr={...Cr?{visitorStore:Cr}:{},historyBootstrapReady:I,getStoredMessageCursor:()=>fd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){Ni("historyMessageCursor");return}Y(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=H.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:i=>{if(!i){Ni("pendingDisplayProjections");return}Y(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:qb,setStoredResumableHandle:i=>{if(!i){Ni("durableResume");return}Y(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>V&&qb()!==null,...ok?{}:{getStoredConversationRevision:()=>fd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){Ni("conversationRevision");return}Y(c=>({...c,conversationRevision:i}))}}};if(V){let i=o.onExecutionState,c=t.ownerDocument.defaultView,f=!1,y=()=>f=!0,x=()=>f=!1;c?.addEventListener("pagehide",y),c?.addEventListener("pageshow",x),De.push(()=>{c?.removeEventListener("pagehide",y),c?.removeEventListener("pageshow",x)}),o={...o,reconnectStream:o.reconnectStream??(k=>_.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!f)&&wr.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),i?.(k)}}}let rk=()=>{let i=jb();if(i&&Cr?.matches(i,Q(),o.persistState===!1)||!i&&!Cr)return;Cr?.destroy(),Cr=i?Kb(i):null;let c={...wr};Cr?c.visitorStore=Cr:delete c.visitorStore,wr=c,_.setHistoryInternals(wr)},qs=null,sk=()=>{qs==null&&(qs=setInterval(()=>{let i=Re.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(qs),qs=null;return}let c=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=lp(c-y))})},100))},Um=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((q,te)=>Um(q,c[te]));let f=i,y=c,x=Object.keys(f),k=Object.keys(y);return x.length===k.length&&x.every(q=>Object.prototype.hasOwnProperty.call(y,q)&&Um(f[q],y[q]))},Yb=i=>{let{content:c,rawContent:f,llmContent:y,...x}=i;return x},qm=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!xy(i),ik=(i,c,f)=>{if(i.length!==c.length)return!1;let y=i[f.index],x=c[f.index];return!y||!x||y.id!==f.id||x.id!==f.id?!1:(!Object.is(y.content,x.content)||!Object.is(y.rawContent,x.rawContent)||!Object.is(y.llmContent,x.llmContent))&&qm(y)&&qm(x)&&Um(Yb(y),Yb(x))},jm=null,Fi=null,js=null,xr=null,Km=null,ak=i=>{if(!V)return Wi(i);Km=i,queueMicrotask(()=>{Km===i&&(Km=null,Wi(i))})},gd=i=>{jm=i;let c,f;Fi=null;for(let x=i.length-1;x>=0;x-=1){let k=i[x];if(!c&&k.role==="user"&&(c=k),!f&&k.role==="assistant"&&(f=k),!Fi&&qm(k)&&(Fi={index:x,id:k.id}),c&&f&&Fi)break}bo(Re,i,Ge),Dr()?.updateInlineArtifactBlocks(Re,yo.artifacts,{suppressTransition:lo}),sk(),il(i),Pi(i),Xr(!lo),jE(i),i.length===0&&(Bo(),Qa=!0,ed=!1,Ri=null,td=!1),!Am||Hi?(Am=!0,_s=c?.id??null,Mm=f?.id??null):c&&c.id!==_s?(_s=c.id,VE(c.id)):f&&f.id!==Mm&&$E(),f&&(Mm=f.id),qE(i);let y=gt.lastUserMessageId;c&&c.id!==y&&(gt.lastUserMessageId=c.id,E.emit("user:message",c)),gt.lastUserMessageWasVoice=!!c?.viaVoice,ak(i),Di()},Gm=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null);let i=js;js=null,i&&gd(i)},Qb=()=>{xr!==null&&cancelAnimationFrame(xr),xr=null,js=null},lk=i=>{let c=js??jm;if(lo&&c&&Fi&&ik(c,i,Fi)){js=i,xr===null&&(xr=requestAnimationFrame(()=>{xr=null;let f=js;js=null,f&&gd(f)}));return}if(i.length===0){Qb(),gd(i);return}Gm(),gd(i)};_=new vp(o,{onMessagesChanged(i){lk(i)},onStatusChanged(i){let c=o.statusIndicator??{};Rn(bt,(y=>y==="idle"?c.idleText??fn.idle:y==="connecting"?c.connectingText??fn.connecting:y==="connected"?c.connectedText??fn.connected:y==="error"?c.errorText??fn.error:y==="paused"?c.pausedText??fn.paused:y==="resuming"?c.resumingText??fn.resuming:fn[y])(i),c,i),wn()},onStreamingChanged(i){i||(_?.getMessages().length===0?Qb():Gm()),lo=i,rl(i),wn(),_&&bo(Re,_.getMessages(),Ge),i||(Xr(!0),NE(),xb=!0,_&&Sb(_.getMessages(),ps(o))),yn(),_c(i?"Responding\u2026":"Response complete."),Di()},onVoiceStatusChanged(i){if(E.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!no(o.voiceRecognition?.provider)))switch(i){case"listening":Er(),Xi();break;case"processing":Er(),d0();break;case"speaking":Er(),p0();break;default:i==="idle"&&_.isBargeInActive()?(Er(),Xi(),fe?.setAttribute("aria-label","End voice session")):(gt.active=!1,Er(),br("system"),Wo());break}},onArtifactsState(i){yo=i,i.artifacts.length===0&&(Ei=!1),Dr()?.updateInlineArtifactBlocks(Re,i.artifacts,{suppressTransition:lo}),Ro(),Wi()},onHistoryStateChanged(i){vn(i)},onHistoryNotice(i){Cn(i)},onReconnect(i){let{executionId:c,lastEventId:f}=i.handle;i.phase==="paused"?E.emit("stream:paused",{executionId:c,after:f}):i.phase==="resuming"?E.emit("stream:resuming",{executionId:c,after:f,attempt:i.attempt??1}):E.emit("stream:resumed",{executionId:c,after:f})}},wr),Bt.current=_,De.push(()=>_.cancel()),De.push(()=>{_.destroy(),Cr?.destroy()});let Ym=null;if(_.onReadAloudChange((i,c)=>{Zy=i,eb=c,tb();let f=i??Ym;i&&(Ym=i);let y=f?_.getMessages().find(x=>x.id===f)??null:null;E.emit("message:read-aloud",{messageId:f,message:y,state:c,timestamp:Date.now()}),c==="idle"&&(Ym=null)}),p=!0,Am=!0,o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider))try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let ck=720,dk=250,Ct=ly(o.features?.history?.copy),uo=null,Qm=!1,Ht=null,hd=null,yd="conversation",Xm=null,Nn=null,Zo=null,bd=_.getHistoryState(),Jm=null,al=0,Zm=null,vd=null,Cd=null,ef=`persona-history-${Math.random().toString(36).slice(2,8)}`,tf=()=>o.features?.history?.enabled===!0,er=()=>tf()&&!!uo&&!Qm,Xb=()=>{let i=_.getStatus();return lo||i==="paused"||i==="resuming"},nf=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",f=uo?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},Vi=()=>hd?.scope??nf(),Jb=()=>_.getClientSession()?.targetId??null,Zb=i=>`${i.state}:${"reason"in i?i.reason:""}`,pk=i=>{let c=Zb(i);c!==Jm&&(Jm=c,E.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},wd=i=>{i&&(ur.textContent="",ur.textContent=i)},ev=null,tv=null,uk=()=>{if(!tf())return null;let i=NT();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(ev!==c&&(ev=c,tv=c()),tv):_.isClientTokenMode()?FT({client:_.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>_.bindActivatedSession(f),getClient:()=>_.getClient()}):null},nv=()=>{vd?.(),vd=null,Cd?.(),Cd=null,Qm=!1,uo=uk();let i={...wr};uo?i.historyProvider=uo:delete i.historyProvider,wr=i,_.setHistoryInternals(wr),uo&&(vd=uo.subscribeAvailability?.(c=>{Qm=!c,c||Jn({restoreFocus:!1}),ts()})??null,Cd=uo.subscribeIdentityStatus(c=>pk(c)),Jm=Zb(uo.getIdentityStatus()))},of=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ce||rn(o)))return"panel";let c=Yo??Le;return(c.getBoundingClientRect().width||c.clientWidth)>=ck?"rail":"panel"},vo=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},xd="data-persona-history-suppressed",mo=null,es=null,Ks=null,ll=null,rf=null,ov="",rv=()=>he===rf?ov:o.layout?.showHeader===!1?"none":"",mk=()=>Se==="panel"&&!!Ks&&ll===Ks.element&&o.layout?.showHeader!==!1&&rv()!=="none",fk=()=>{for(let i of Array.from(he.children))i!==mo&&i.setAttribute(xd,"")},gk=()=>{for(let i of Array.from(Le.querySelectorAll(`[${xd}]`)))i.removeAttribute(xd)},hk=()=>{let i=Ks;if(!i)return;if(Array.from(he.children).some(y=>y!==mo&&!y.hasAttribute(xd))){es&&es!==he&&(es.style.removeProperty("min-height"),es=null);let y=he.offsetHeight;y>0&&(he.style.minHeight=`${y}px`,es=he)}mo||(mo=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==mo&&mo.replaceChildren(f),mo.parentNode!==he&&he.appendChild(mo),fk()},sv=()=>{es&&(es.style.removeProperty("min-height"),es=null),mo&&(Ks?.setHeaderPlacement("inline"),mo.remove(),mo=null,gk())},Sd=null,sf=()=>{if(Sd){if(ie.style.display="none",vo(ie,!0),We.hidden=!0,vo(We,!0),mk()){hk(),he.style.display=rv(),vo(he,!1);return}sv(),he.style.display="none",vo(he,!0)}};Ke=sf;let yk=i=>{let c=ie.style.display,f=We.hidden,y=We,x=he,k=he.style.display;rf=x,ov=k,Sd=()=>{Sd=null,sv(),rf=null,ie.style.display=c,vo(ie,!1),y.hidden=f,vo(y,!1),We!==y&&(We.hidden=!1,vo(We,!1)),x.style.display=k,vo(x,!1),he!==x&&(he.style.display=o.layout?.showHeader===!1?"none":"",vo(he,!1))},We.parentNode?.insertBefore(i,We),sf()},$i=null,Gs=null,cl=null,zi=null,iv=()=>[he,Ze.closeButtonWrapper,Ze.clearChatButtonWrapper,ie,We],bk=52,Ad=()=>o.features?.history?.rail?.collapsible!==!1,Ui=()=>o.features?.history?.rail?.side==="right"?"right":"left",af=200,lf=400,cf=i=>Math.min(lf,Math.max(af,Math.round(i))),vk=()=>o.features?.history?.rail?.resizable===!0,dl,Ck=()=>{if(dl===void 0&&(dl=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Q()}rail-width`));i&&(dl=i)}catch{}return dl},pl=()=>cf(Ck()??o.features?.history?.rail?.width??260),wk=i=>{if(dl=i,o.persistState!==!1)try{window.localStorage.setItem(`${Q()}rail-width`,String(i))}catch{}},Md=()=>Ad()&&o.features?.history?.rail?.collapsedBehavior==="overlay",dn=!1,av=i=>{let c=v("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},xk=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let c=!1,f;return y=>{if(i.render)try{return i.render({collapsed:y})??null}catch(x){return c||(c=!0,console.warn("[persona] history rail brand threw",x)),null}return f===void 0&&(i.iconUrl?f=av(i.iconUrl):f=i.icon?Ie(i.icon,20):null),f?f.cloneNode(!0):null}},Sk=()=>o.features?.history?.rail?.sections?.map(i=>{let c=!1,f=y=>{c||(c=!0,console.warn("[persona] history rail section threw",i.id,y))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(y=>{let x;return{id:y.id,label:y.label,badge:y.badge,iconNode:()=>{if(x!==void 0)return x;try{y.renderIcon?x=y.renderIcon()??null:y.iconUrl?x=av(y.iconUrl):x=y.icon?Ie(y.icon,20):null}catch(k){f(k),x=null}return x},onSelect:()=>{try{y.onSelect()}catch(k){f(k)}}}})}})??[],Ak=i=>{let c=Sk();for(let f of i)c.some(y=>y.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):c.push(f);return c.length?c:void 0},ul=null,lv=()=>`${Q()}rail-collapsed`,df=()=>{if(ul===null&&(ul=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(lv());i&&(ul=i==="1")}catch{}return ul},pf=i=>{if(ul=i,o.persistState!==!1)try{window.localStorage.setItem(lv(),i?"1":"0")}catch{}},ml=()=>Se==="rail"&&Ad()&&!Md()&&df(),uf=()=>{},cv=()=>{if(Md()){uf();return}pf(!df()),Ht?.view.setCollapsed(ml()),ut(),Xn()},mf=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!lu(i)?null:{combo:i,hint:cu(i),aria:tc(i)}},dv=()=>{d.forEach(c=>c()),d=[];let i=mf();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ve&&Se==="rail"&&Ad()||ji(),run:()=>Md()?uf():cv()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${c.id}"]`);f?f.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of a)for(let f of c.shortcuts??[])d.push(l.register({...f,id:`${c.id}:${f.id}`}))};dv();let Mk=300,Td="var(--persona-history-overlay-margin,8px)",Co=null,Sr=null,Ed=0,Ar=null,qi=null,Ys=!1,ff=0,pv=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ji=()=>er()&&Md()&&(Se??of())==="rail",Tk=()=>ve&&!dn,fl=()=>{qi!==null&&clearTimeout(qi),qi=null},Ek=()=>{by().catch(()=>{})},uv=()=>{fl(),dn&&(qi=setTimeout(()=>{qi=null,!(Ys||!dn)&&(Ar?.contains(document.activeElement)||Jn({restoreFocus:!1}))},Mk))},kk=(i,c)=>{let f=Ar?.getBoundingClientRect();if(!f)return!1;let y=Co?.getBoundingClientRect(),x=y?Math.min(y.top,f.top):f.top;return i>=f.left&&i<=f.right&&c>=x&&c<=f.bottom||!!y&&i>=y.left&&i<=y.right&&c>=y.top&&c<=y.bottom},gf=i=>{dn&&(Ys=kk(i.clientX,i.clientY),Ys?fl():qi===null&&uv())},mv=i=>{ve||!ji()||(dn=!0,hl({invoker:Co,keyboard:i?.keyboard===!0}).then(()=>{ve?!Ys&&document.activeElement!==Co&&Jn():dn=!1}))},fv=()=>{let i=ll?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",dn?Ct.expandLabel:Ct.collapseLabel),i.setAttribute("aria-expanded",dn?"false":"true"))},gv=()=>{pf(!1);let i=Ht;if(!dn||!i){hl({invoker:Co});return}let c=document.activeElement===Co;dn=!1,kd(),i.element.remove(),yf(i.element),fv(),c&&Pd(),Xn(),ts()},Lk=()=>{pf(!0),Jn()};uf=()=>{!ve||dn?gv():Lk()};let Pk=()=>{let i=mf(),c=ai({ariaLabel:Ct.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":ef,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Ys=!0,fl(),!(pv()||Date.now()<ff)&&mv()}),f.addEventListener("mouseleave",()=>{Ys=!1,ff=0,uv()}),f.addEventListener("focus",()=>{ve||Ek()}),f.addEventListener("click",y=>{er()&&(y.detail!==0&&pv()&&!ve?mv():gv())}),Co=f,Sr=c.wrapper},gl=()=>{if(Sr&&!Sr.isConnected&&(Sr=null,Co=null),!ji()){Sr?.remove(),Sr=null,Co=null;return}Co||Pk();let i=Sr,c=Co;if(!i||!c)return;let f=Ui()!=="right"?he.firstChild:null;(f??he.lastChild)!==i&&he.insertBefore(i,f),i.style.display=Tk()||Ed>0?"none":"",c.setAttribute("aria-label",Ct.expandLabel),c.setAttribute("aria-expanded",ve?"true":"false"),Ar&&ut()},hv=i=>{if(!dn)return;let c=i.target;c instanceof Node&&(Ar?.contains(c)||Sr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Jn({restoreFocus:!1}))};document.addEventListener("pointerdown",hv,!0),De.push(()=>{document.removeEventListener("pointerdown",hv,!0),document.removeEventListener("pointermove",gf),Ki?.(),fl()});let hf=null,Ki=null,yv=16,bv=i=>{wk(cf(i)),ut(),Xn()},Ik=()=>{let i=v("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(af)),i.setAttribute("aria-valuemax",String(lf)),i.addEventListener("pointerdown",c=>{let f=Gs;if(!f||c.button!==0)return;c.preventDefault(),Ki?.();let y=c.clientX,x=f.getBoundingClientRect().width||pl(),k=Ui()==="right"?-1:1,q=x,te=t.ownerDocument;f.style.transition="none";let Z=pe=>{q=cf(x+k*(pe.clientX-y)),f.style.flex=`0 0 ${q}px`,i.setAttribute("aria-valuenow",String(q))},ne=()=>{Ki=null,te.removeEventListener("pointermove",Z),te.removeEventListener("pointerup",ne),te.removeEventListener("pointercancel",ne),f.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}bv(q)};Ki=ne,te.addEventListener("pointermove",Z),te.addEventListener("pointerup",ne),te.addEventListener("pointercancel",ne);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let f=Ui()==="right"?-yv:yv,y=pl(),x=c.key==="ArrowRight"?y+f:c.key==="ArrowLeft"?y-f:c.key==="Home"?af:c.key==="End"?lf:null;x!==null&&(c.preventDefault(),bv(x))}),i},Hk=(i,c)=>{if(!vk()||ml()){Ki?.(),hf?.remove();return}let f=hf??Ik();hf=f,f.setAttribute("aria-label",Ct.resizeLabel),f.setAttribute("aria-valuenow",String(pl())),f.nextElementSibling!==c&&i.insertBefore(f,c)};ut=()=>{Ht?.view.setRailSide(Ui());let i=Ui()==="right",c=Ar;if(c){let te=Co?Co.getBoundingClientRect().bottom-Le.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(te))}px + ${Td})`,c.style.width=`${pl()}px`,c.style.left=i?"":Td,c.style.right=i?Td:""}let f=Gs,y=$i,x=cl;if(!f||!y||!x)return;f.style.flex=`0 0 ${ml()?bk:pl()}px`;let k="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":k,f.style.borderLeft=i?k:"";let q=i?x:f;y.firstElementChild!==q&&y.append(q,i?f:x),Hk(y,i?f:x)};let vv=i=>{if(zi&&Gs){zi.replaceWith(i),zi=null,ut();return}let c=v("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("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 y=v("div","persona-history-rail-host");y.style.cssText="display:flex;min-height:0;overflow:hidden",Le.insertBefore(c,he.parentNode===Le?he:ie);for(let x of iv())x?.parentNode===Le&&f.appendChild(x);c.append(y,f),y.appendChild(i),$i=c,Gs=y,cl=f,ut()},Rk=()=>{if($i)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",zi=i,vv(i),Xn()},Cv=()=>{zi&&(kd(),Xn())},Wk=i=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Td};display:flex;overflow:hidden;z-index:${fa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Le.style.position="relative",Le.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",gf),Ar=c,ut(),fv()},kd=()=>{Sd?.(),Ar&&(Ys&&(ff=Date.now()+150),document.removeEventListener("pointermove",gf),Ar.remove(),Ar=null);let i=$i;if(i){Ki?.();for(let c of iv())c&&i.contains(c)&&Le.insertBefore(c,i);i.remove(),$i=null,Gs=null,cl=null,zi=null}},wv=i=>{ll=i,i.id=ef,i.style.flex="1 1 auto",i.style.minHeight="0"},yf=i=>{wv(i),(Se!=="rail"||dn)&&Cv(),Se!=="rail"?yk(i):dn?Wk(i):vv(i)},Ld=()=>{if(gl(),Hv(),!ve||!Ht)return;let i=of();if(i===Se)return;let c=document.activeElement,f=c instanceof HTMLElement&&(Ht.element.contains(c)||mo?.contains(c)===!0)?c:null;kd(),Ht.element.remove(),Ht.view.setHeaderPlacement("inline"),Se=i,Ht.view.setPresentation(i),Ht.view.setCollapsed(ml()),Ht.requestRender(),Ht.element.isConnected||yf(Ht.element),f?.isConnected?f.focus():Pd(),yn(),Xn(),ts()},xv=(i,c)=>mo?.querySelector(c)??i.querySelector(c),Pd=()=>{let i=Ht?.element??ll;if(!i)return;let c=xv(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=xv(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},hl=async i=>{if(!er()||ve)return;let c=uo;if(!c)return;if(!dn&&ji()&&df()){gl();return}Id();let f=++al;yd=i?.returnSurface??"conversation",Xm=i?.invoker??Nn;let y=ji()&&!dn;y&&(Ed+=1,gl(),Rk());let x;try{x=await by()}catch{wd(Ct.openHistoryLabel),y&&(Ed-=1,f===al&&(Cv(),gl()));return}if(y&&(Ed-=1),f!==al||ve)return;hd={scope:nf()},Se=of(),ve=!0;let k=Se==="panel"&&o.layout?.showHeader!==!1&&he.style.display!=="none"?"external":"inline",q=o.features?.history?.rowAvatar,te=mf(),Z=te?{hint:te.hint,aria:te.aria}:null,ne={provider:c,context:hd,targetId:Jb(),presentation:Se,collapsible:Ad(),collapsed:ml(),railSide:Ui(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:xk(),onToggleCollapse:cv,...Z?{collapseShortcut:Z}:{},headerPlacement:k,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:q===!1?!1:typeof q=="string"?q:o.launcher?.iconUrl,activeConversationId:_.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:pe=>vf(pe,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:pe=>Qs(pe),attachTooltip:Mn,onStartNew:()=>Cf({focusComposer:!0}),onClose:()=>Jn(),onRequestDeleteConversation:pe=>Iv(pe),onRequestClearHistory:()=>Fk(),...c.resetDevice?{onRequestResetIdentity:()=>Vk()}:{}};Ht=_T({plugins:a,config:o,getPresentation:()=>Se??"panel",getReturnSurface:()=>yd,close:()=>Jn(),createView:({slots:pe,renderDom:Ce,onModelChange:He,railSections:wt})=>(Ks=x.createHistoryView({...ne,railSections:Ak(wt),slots:pe,renderDom:Ce,onModelChange:He,onAnnounce:wd}),Ks),onElementChanged:(pe,Ce)=>{if(!Ce?.isConnected)return yf(pe);wv(pe),Ce.replaceWith(pe),sf()}}),Ht.view.setNewConversationRequired(bd.recovery==="new_conversation_required"),i?.focus!==!1&&(Se!=="rail"||i?.keyboard===!0)&&Pd(),yn(),Xn(),ts(),E.emit("history:opened",{presentation:Se,returnSurface:yd,timestamp:Date.now()})},Id=()=>{},Jn=i=>{if(!ve)return;al+=1;let c=yd,f=Xm,y=Ht,x=i?.restoreFocus!==!1;ve=!1;let k=!1,q=null,te=()=>{if(!k){if(k=!0,Id=()=>{},q!==null&&clearTimeout(q),dn=!1,fl(),kd(),y?.dispose(),y?.view.destroy(),y?.element.remove(),Ht===y&&(Ht=null,Ks=null,ll=null,Se=null,hd=null,Xm=null),yn(),Xn(),ts(),x){let ne=f??Nn;ne?.isConnected?ne.focus():zs()}E.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},Z=y&&y.element===y.view.element?y.view.playExit():null;if(!Z){te();return}Id=te,q=setTimeout(te,dk),Z.then(te)},Sv=i=>{if(!(i.key!=="Escape"||!ve||!Ht)){if(Se==="rail"){let c=i.target;if(!(c instanceof Node)||!(Ht.element.contains(c)||dn&&Sr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Jn()}};Le.addEventListener("keydown",Sv),De.push(()=>Le.removeEventListener("keydown",Sv));let Hd=null,Av=!1,yl=()=>{if(!Be)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Hd?.trim()||null;Be.textContent=c??o.launcher?.title??"Chat Assistant";let f=Be.closest(".persona-combo-btn");if(!f)return;let y=!i||_.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",y?"false":"true"),f.setAttribute("aria-haspopup",y?"true":"false"),y||f.setAttribute("aria-expanded","false"),f.style.cursor=y?"pointer":"default";let x=f.querySelector("svg");x&&(x.style.display=y?"":"none")},Bk=i=>{i!==Hd&&(Hd=i,yl())},Qs=i=>{Av=i?.starred===!0,Bk(i&&i.title.trim()||null),yl()};yl(),Le.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,f=_.getActiveConversationId();f&&(c==="delete"?Iv(f):c==="star"&&_.canUpdateConversations()&&wf(f,{starred:!Av}).catch(()=>{}))});let Rd=0,Ok=250,Wd=null,Bd=()=>{Wd&&clearTimeout(Wd),Wd=null};De.push(Bd);let Mv=()=>{Bd();let i=Us;i&&(sl=!0,i.hidden=!1,Re.style.display="none",il())},Od=()=>{Rd+=1,Bd(),Us&&(Us.remove(),Us=null,sl=!1,Re.style.removeProperty("display"),vo(We,!1),il())},Dk=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Re.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},bf=(i,c)=>$("div",{className:Vt("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),Tv=()=>$("div",{className:"persona-conversation-loading-body"},bf("58%",!1),bf("72%",!0),bf("44%",!1)),Ev=i=>{Us?.remove(),Us=i,i.hidden=!sl,ie.insertBefore(i,Re),Bd(),sl||(Wd=setTimeout(Mv,Ok)),vo(We,!0)},_k=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Tv},c=null,f=a.find(y=>y.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Ev($("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ct.openConversationLoadingLabel}},c??Tv()))},Nk=i=>{let c=()=>{vf(i,{focusComposer:!0}).catch(()=>{})},f=er()?()=>{Od(),hl()}:void 0,y=(te,Z)=>{let ne=$("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:te});return ne.addEventListener("click",Z),ne},x=()=>$("div",{className:"persona-conversation-loading-error-body"},$("p",{className:"persona-conversation-loading-error-title",text:Ct.openConversationErrorTitle}),$("div",{className:"persona-conversation-loading-error-actions"},y(Ct.openConversationRetryLabel,c),f?y(Ct.openConversationBackLabel,f):null)),k=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Ct.openConversationErrorTitle,retryLabel:Ct.openConversationRetryLabel,backLabel:Ct.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:x}),q=null;for(let te of a)if(te.renderHistoryOpenError){try{q=te.renderHistoryOpenError(k)}catch(Z){console.warn("[persona] renderHistoryOpenError threw",Z),q=null}if(q)break}Ev($("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},q??x())),Mv()};E.on("history:closed",()=>{Us&&vo(We,!0)});let vf=async(i,{focusComposer:c=!1}={})=>{let f=Vi(),y=!!Ht;Ht?.view.setActiveConversationId(i),Od();let x=Rd;_k(),ve&&(Se==="panel"||dn)&&Jn({restoreFocus:!1}),Hi=!0;try{await _.openConversation(i,{scope:f})}catch(k){throw x===Rd&&Nk(i),k}finally{Hi=!1}x===Rd&&(Od(),cn.clear(),Bo(),Qn(),Im()||id(),Dk(),Mr(),y||Qs(null),E.emit("history:conversationOpened",{conversationId:i,title:Hd,scope:f,timestamp:Date.now()}),c&&zs())},Cf=async({focusComposer:i=!1}={})=>{Od(),await _.startNewConversation({scope:Vi()}),Qs(null),cn.clear(),Bo(),Qn(),id(),Mr();let c=_.getActiveConversationId();Ht?.view.setActiveConversationId(c),E.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),ve&&(Se==="panel"||dn)&&Jn({restoreFocus:!1}),i&&zs()},wf=async(i,c)=>{let f=await _.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return Ht?.view.applyConversationSummary(f),!Ht&&i===_.getActiveConversationId()&&Qs(f),f},kv=async i=>{let c=Vi(),f=_.getActiveConversationId()===i;await _.deleteConversation(i,{scope:c}),Ht?.view.removeConversationSummary(i),f&&(Qs(null),cn.clear(),Bo(),Qn(),Mr()),E.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:f,timestamp:Date.now()})},Lv=async i=>{let c=i?.scope??Vi(),f=i?.allTargets?null:i?.targetId??Jb(),y=await _.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Qs(null),cn.clear(),Bo(),Qn(),Mr(),E.emit("history:cleared",{deleted:y.deleted,scope:c,targetId:f,timestamp:Date.now()}),y},Pv=async()=>{if(!uo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await _.resetHistoryDevice()).remoteRevocationConfirmed}finally{Qs(null),_.clearArtifacts(),cn.clear(),jm=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),H={},se.syncFromMetadata(),R?.clear&&od(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),Bo(),Qn(),Mr(),Jn({restoreFocus:!1}),zs(),Pe||Qt?.launcher.element.focus()}return wd(i?Ct.identityResetNotice:Ct.identityResetUnconfirmedNotice),E.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},xf=()=>Yo?_e:Le,Iv=async i=>await em({host:xf(),title:Ct.deleteConversationConfirmTitle,description:Ct.deleteConversationConfirm,confirmLabel:Ct.deleteConversationConfirmLabel,cancelLabel:Ct.confirmCancelLabel})?(await kv(i),"deleted"):"cancelled",Fk=async()=>{let i=Vi()==="verified-user";return await em({host:xf(),title:Ct.clearHistoryConfirmTitle,description:i?Ct.clearHistoryVerifiedConfirm:Ct.clearHistoryConfirm,confirmLabel:Ct.clearHistoryConfirmLabel,cancelLabel:Ct.confirmCancelLabel})?(await Lv(),"cleared"):"cancelled"},Vk=async()=>{if(!await em({host:xf(),title:Ct.resetIdentityConfirmTitle,description:Ct.resetIdentityConfirm,confirmLabel:Ct.resetIdentityConfirmLabel,cancelLabel:Ct.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Pv();return{outcome:"reset",remoteRevocationConfirmed:c}},wo=v("button","persona-history-earlier");wo.type="button",wo.textContent=Ct.showEarlierMessagesLabel,wo.setAttribute("data-persona-history-earlier",""),Object.assign(wo.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 Mr=()=>{if(!(er()&&!!bd.nextMessageCursor&&!!_.getActiveConversationId())){wo.remove();return}wo.textContent=Ct.showEarlierMessagesLabel,wo.parentNode!==ie&&ie.insertBefore(wo,ie.firstChild)};wo.addEventListener("click",()=>{let i=_.getActiveConversationId(),c=bd.nextMessageCursor;if(!i||!c||wo.disabled)return;wo.disabled=!0;let f=ie.scrollHeight,y=ie.scrollTop;_.loadOlderMessages(i,c,{scope:Vi()}).then(()=>{ie.scrollTop=y+(ie.scrollHeight-f),Xn()}).catch(()=>{}).finally(()=>{wo.disabled=!1,Mr()})});let $k=()=>{let i=ai({ariaLabel:Ct.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 i.button.addEventListener("click",c=>{if(!(!er()||Xb())){if(ve){Jn();return}hl({invoker:i.button,keyboard:c.detail===0})}}),i},Hv=()=>{if(!er()){Zo?.remove(),Nn=null,Zo=null;return}if(Zo&&!Zo.isConnected&&(Nn=null,Zo=null),!Nn&&he){let y=$k();Nn=y.button,Zo=y.wrapper;let x=Ze.clearChatButtonWrapper||Ze.closeButtonWrapper;x?.parentNode&&he.contains(x)?x.parentNode.insertBefore(Zo,x):he.appendChild(Zo)}if(!Nn||!Zo)return;let i=ji()||ve&&Se==="rail";if(Zo.style.display=i?"none":"",i){document.activeElement===Nn&&Pd();return}let c=Xb();Nn.disabled=c,Nn.setAttribute("aria-disabled",c?"true":"false");let f=c?Ct.openHistoryBusyLabel:Ct.openHistoryLabel;Nn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(Nn.removeAttribute("aria-expanded"),Nn.removeAttribute("aria-controls")):(Nn.setAttribute("aria-expanded",ve?"true":"false"),Nn.setAttribute("aria-controls",ef))},Dd=!1,zk=()=>{let i=Ze.clearChatButton;if(i){if(er()){Dd||(Zm=i.getAttribute("aria-label")??"",Dd=!0),i.setAttribute("aria-label",Ct.newConversationLabel),i.removeAttribute("title");return}Dd&&(Dd=!1,Zm&&i.setAttribute("aria-label",Zm))}},ts=()=>{Ct=ly(o.features?.history?.copy),Hv(),gl(),zk(),Mr()};wn=ts,vn=i=>{bd=i,Ht?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),rl(i.sendBlocked||lo),Mr()},Cn=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(cn.clear(),Bo(),Qn()),wd(i.message),Ht?.view.refresh()},nv(),ts(),De.push(()=>{vd?.(),Cd?.(),al+=1,Id(),Ht?.dispose(),Ht?.view.destroy(),Ht=null}),o.clientToken&&_.initClientSession().then(()=>{if(er())return _.reconcileBootConversation({scope:nf()})}).then(()=>{Mr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(L||o.onSSEEvent)&&_.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),pt(i,c)});let Rv=()=>{let i=o.resume??(V?wr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(i)};w?w.then(i=>{if(i){if(i.metadata&&(H=Sy(i.metadata),se.syncFromMetadata()),i.messages?.length){Hi=!0;try{_.hydrateMessages(i.messages)}finally{Hi=!1}dd()}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Lb(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{_m=!0,T(),Rv()}):(Lb(D),Rv());let Uk=()=>{!Ee()||Pe||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Nt(!0,"auto")},qk=(i,c)=>i?c?{refs:[...i.refs,...c.refs],finalize:async()=>{let[f,y]=await Promise.allSettled([i.finalize(),c.finalize()]),x=[];return f.status==="fulfilled"?x.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),y.status==="fulfilled"?x.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),DB(x)}}:i:c,Sf=()=>{let c=Ae.getInlineMessageFields?.();return c&&c.contentSegments.some(y=>y.kind==="mention")?c.contentSegments:void 0},Tr=!1,Xs=null,_d=()=>{Ae.value="",Ae.style.height="auto",jo(),vl()},Af="data-persona-composer-notice",Gi=null;function jk(i){_c(i),!(Ee()||!bt)&&(bt.hasAttribute(Oa)||(bt.setAttribute(Af,""),bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.textContent=i,Gi&&clearTimeout(Gi),Gi=setTimeout(()=>{if(Gi=null,!!bt?.hasAttribute(Af)&&(bt.removeAttribute(Af),bt.removeAttribute("role"),bt.removeAttribute("aria-live"),p)){let c=_.getStatus();Rn(bt,sn(c),o.statusIndicator??{},c)}},4e3)))}function Kk(){let i=ze.getState().pendingSubmission;i&&(Ai(void 0),Ae&&(Ae.value=i.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),jo()),i.options.selectedModelId&&(ze.setSelectedModelId(i.options.selectedModelId),Ur?.repaint()),i.options.activeModeIds?.length&&$c(i.options.activeModeIds),i.options.quote&&Ko(i.options.quote),Ae?.focus())}let Gk=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},Wv=(i={})=>{let c=(i.overrideText??Ae?.value??"").trim();return i.resolveInlineCommand&&c?(nn?.takeInlineCommand(c)??Promise.resolve(null)).then(f=>Bv(i,c,f)):Bv(i,c,null)},Bv=(i,c,f)=>{if(f?.kind==="action"){_d(),nn?.clear(),Ts();return}let y=f?.kind==="server"?f.mentions:null,x=f?.kind==="prompt"?f.sendText:c,k=i.pending?.contentParts,q=(At?.hasAttachments()??!1)||(k?.length??0)>0;if(!Kx({text:x,hasAttachments:q,attachmentsReady:At?.isReady()??!0,hasMentions:nn?.hasMentions()??!1,hasServerMentions:!!y,inputDisabled:Jo(),sendDisabled:$s()}))return;let te=_.isStreaming()?pm():"block";if(te==="defer-one"&&!i.pending){if(ze.getState().pendingSubmission){jk("One message is already queued. Edit or remove it first.");return}Yk({intent:i,sendText:x,serverMentions:y});return}let Z={text:x,mentionRefs:[...nn?.getMentionRefs()??[],...y?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:Sf(),options:{...ze.getState().selectedModelId&&{selectedModelId:ze.getState().selectedModelId},...ze.getState().activeModeIds.length>0&&{activeModeIds:[...ze.getState().activeModeIds]},...ze.getState().quote&&{quote:{...ze.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(Z.options={...i.pending.options},Z.contentSegments=i.pending.contentSegments,Z.mentionRefs=[...i.pending.mentionRefs],Z.viaVoice=i.pending.viaVoice);let ne=()=>{if(k?.length)return[...k];if(!At?.hasAttachments())return;let Ft=[...At.getContentParts()];return Z.text&&Ft.push(rr(Z.text)),Ft};Z.contentParts=ne();let pe=()=>{Bs(),Uk();let Ft=nn?.collectForSubmit()??null,xn=qk(Ft,y),pn=ne();i.consumeDraft!==!1&&_d();let Jt={selectedModelId:Z.options.selectedModelId,activeModeIds:Z.options.activeModeIds},Bn=te==="interrupt";Bn&&_.cancel(),_.sendMessage(Z.text,{contentParts:pn,mentions:xn??void 0,contentSegments:Z.contentSegments,viaVoice:Z.viaVoice,composerOptions:Jt,...Z.options.quote&&{quote:Z.options.quote},...Bn&&{interrupt:!0}}),At?.hasAttachments()&&At.clearAttachments(),Ft&&nn?.clear(),Ts();let Mt=ze.getState().activeModeIds,On=Rx(Mt,o.composer?.modes);On.length!==Mt.length&&$c(On),ze.getState().quote&&Ko(void 0),sd(),hm.release(),Io()},Ce=o.composer?.onBeforeSend;if(!Ce){pe();return}let He=new AbortController;Xs=He;let wt=Ft=>{if(Xs=null,Ft.status==="error"){Gk(Ft.error);return}Ft.status==="proceed"&&pe()},Ot=Gx(Ce,Z,He.signal);if(!(Ot instanceof Promise)){wt(Ot);return}return ze.setPreparing(!0),Ot.then(wt).finally(()=>ze.setPreparing(!1))};function Yk(i){let c=ze.getState(),f=At?.hasAttachments()??!1,y=f?[...At.getContentParts()]:[];f&&i.sendText&&y.push(rr(i.sendText));let x=Hg({text:i.sendText,contentParts:y.length?y:void 0,mentionRefs:[...nn?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Sf(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Ai(x),i.intent.consumeDraft!==!1&&_d(),f&&At.clearAttachments(),nn?.clear(),Ts(),c.quote&&Ko(void 0),sd(),hm.release(),Io(),_c("Message queued. It sends when the response finishes.")}function Qk(){let i=ze.getState().pendingSubmission;i&&(Ai(void 0),Fd(i.text,{consumeDraft:!1,pending:i}))}function Xk(i){if(o.messageActions?.showEdit!==!0)return;let c=_.getMessages().find(f=>f.id===i);!c||!ng(c)||Ws!==i&&(Bs(),Ws=i,Gr=_x({messageId:i,initialText:c.content,onSave:f=>Jk(i,f),onCancel:()=>Bs()}),cn.delete(i),bo(Re,_.getMessages(),Ge),Gr.focus())}function Jk(i,c){let f=Gr;if(Ws=null,Gr=null,f?.destroy(),cn.delete(i),!_.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){bo(Re,_.getMessages(),Ge);return}Xn()}function Zk(i){if(_.isStreaming())return;let c=tg(_.getMessages(),i);c&&(Bs(),_.resubmitFrom(c,{reason:"retry"})&&Xn())}zc={regenerate:Zk,edit:Xk,quote:i=>{let f=_.getMessages().find(y=>y.id===i)?.content?.trim();f&&(Ko({text:f,messageId:i}),Ae?.focus())}};let bl=async i=>{if(!Tr){Tr=!0;try{await Wv({resolveInlineCommand:!0,...i})}finally{Tr=!1}}};function Nd(i){$s()||(_d(),Fd(i,{consumeDraft:!1}))}let Fd=(i,c)=>{if(Tr)return;Tr=!0;let f=()=>{Tr=!1};try{let y=Wv({...c,overrideText:i});y instanceof Promise?y.finally(f):f()}catch(y){throw f(),y}},e0=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),lt?.reset(),mt?.update();return}Tr||bl()},t0=()=>o.features?.composerHistory!==!1,Mf={...Qg},Tf=!1,vl=()=>{Mf={...Qg}},n0=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),o0=i=>{if(!Ae)return;Tf=!0,Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Tf=!1;let c=Ae.value.length;Ae.setSelectionRange(c,c)},r0=i=>{Tf||(i.isComposing||nn?.handleInput(i.inputType??void 0),vl())},s0=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(Ae)}),i0=i=>{if(Ae&&!Jo()&&!(!i.isComposing&&nn?.handleKeydown(i))){if(t0()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=Ae.selectionStart===0&&Ae.selectionEnd===0,f=zS({direction:i.key==="ArrowUp"?"up":"down",history:n0(),currentValue:Ae.value,atStart:c,state:Mf});if(Mf=f.state,f.handled){i.preventDefault(),f.value!==void 0&&o0(f.value);return}}if(fx(i,s0())){if(_.isStreaming()){if(i.preventDefault(),pm()==="block"||Tr||$s())return;vl(),bl();return}if(Tr){i.preventDefault();return}if($s()){i.preventDefault();return}vl(),i.preventDefault(),Ve.click()}}},Ov=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Le)){if(Xs){Xs.abort(),Xs=null,i.preventDefault(),i.stopImmediatePropagation();return}_.isStreaming()&&(_.cancel(),lt?.reset(),mt?.update(),vl(),i.preventDefault(),i.stopImmediatePropagation())}},a0=async i=>{if(o.attachments?.enabled!==!0||!At||Jo())return;let c=RB(i.clipboardData);c.length!==0&&(i.preventDefault(),await At.handleFiles(c))},xo=null,tr=!1,Yi=null,qt=null,Ef=()=>o.voiceRecognition?.completionBehavior==="review";function Js(i){fe?.setAttribute("data-state",i),i==="recording"?c0():If()}let Dv="--persona-voice-level",kf=.5,Qi=null,Lf=-1,Vd=0,_v=()=>{let i=[],c=io??fe?.parentElement??null;return c&&i.push(c),We&&i.push(We),i},Pf=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Lf){Lf=c;for(let f of _v())f.style.setProperty(Dv,String(c))}},l0=()=>{Lf=-1,Vd=0;for(let i of _v())i.style.removeProperty(Dv)};function c0(){if(Qi!==null)return;if(typeof requestAnimationFrame!="function"){Pf(p?_.getVoiceLevel()??kf:kf);return}let i=()=>{Qi=requestAnimationFrame(i);let c=p?_.getVoiceLevel():null;if(c===null){Pf(kf);return}Vd+=(c-Vd)*.3,Pf(Vd)};Qi=requestAnimationFrame(i)}function If(){Qi!==null&&(cancelAnimationFrame(Qi),Qi=null),l0()}let Nv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$d=(i="user")=>{if(tr||_.isStreaming())return;let c=Nv();if(!c)return;xo=new c;let f=o.voiceRecognition??{},y=f.pauseDuration??2e3;xo.continuous=f.provider?.browser?.continuous??!0,xo.interimResults=!0,xo.lang=f.provider?.browser?.language??"en-US";let x=Ae.value;xo.onresult=k=>{let q="",te="";for(let ne=0;ne<k.results.length;ne++){let pe=k.results[ne],Ce=pe[0].transcript;pe.isFinal?q+=Ce+" ":te=Ce}let Z=x+q+te;Ae.value=Z,jo(),Yi&&clearTimeout(Yi),(q||te)&&(Yi=window.setTimeout(()=>{if(Ae.value.trim()&&xo&&tr){if(ns(),Ef())return;bl({viaVoice:!0})}},y))},xo.onerror=k=>{k.error!=="no-speech"&&ns()},xo.onend=()=>{if(tr){let k=Ae.value.trim();!Ef()&&k&&k!==x.trim()&&bl({viaVoice:!0}),ns()}};try{if(xo.start(),tr=!0,gt.active=!0,i!=="system"&&(gt.manuallyDeactivated=!1),br(i),Wo(),Io(),fe){let k=o.voiceRecognition??{};qt={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||$n};let q=k.recordingBackgroundColor,te=k.recordingIconColor,Z=k.recordingBorderColor;if(fe.classList.add("persona-voice-recording"),Js("recording"),fe.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=te??"var(--persona-voice-recording-indicator, #ffffff)",te){let ne=fe.querySelector("svg");ne&&ne.setAttribute("stroke",te)}Z&&(fe.style.borderColor=Z),fe.setAttribute("aria-label","Stop voice recognition")}}catch{ns("system")}},ns=(i="user")=>{if(tr){if(tr=!1,Yi&&(clearTimeout(Yi),Yi=null),xo){try{xo.stop()}catch{}xo=null}if(gt.active=!1,br(i),Wo(),Io(),fe){if(fe.classList.remove("persona-voice-recording"),Js("idle"),qt){fe.style.backgroundColor=qt.backgroundColor,fe.style.color=qt.color,fe.style.borderColor=qt.borderColor;let c=fe.querySelector("svg");c&&c.setAttribute("stroke",qt.color||"currentColor"),qt=null}fe.setAttribute("aria-label","Start voice recognition")}}},Hf=()=>{if(!fe||qt)return;let i=o.voiceRecognition??{};qt={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||$n}},Rf=(i,c)=>{if(!fe)return;let f=fe.querySelector("svg");f&&f.remove();let y=qt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||$n),x=Ie(i,y,c,1.5);x&&fe.appendChild(x)},zd=()=>{fe&&fe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Xi=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(zd(),fe.classList.add("persona-voice-recording"),Js("recording"),fe.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let x=fe.querySelector("svg");x&&x.setAttribute("stroke",f)}y&&(fe.style.borderColor=y),fe.setAttribute("aria-label","Stop voice recognition")},d0=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=_.getVoiceInterruptionMode(),f=i.processingIconName??"loader",y=i.processingIconColor??qt?.color??"",x=i.processingBackgroundColor??qt?.backgroundColor??"",k=i.processingBorderColor??qt?.borderColor??"";zd(),fe.classList.add("persona-voice-processing"),Js("processing"),fe.style.backgroundColor=x,fe.style.borderColor=k;let q=y||"currentColor";fe.style.color=q,Rf(f,q),fe.setAttribute("aria-label","Processing voice input"),c==="none"&&(fe.style.cursor="default")},p0=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=_.getVoiceInterruptionMode(),f=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",y=i.speakingIconName??f,x=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??qt?.color??"":qt?.color??""),k=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":qt?.backgroundColor??""),q=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":qt?.borderColor??"");zd(),fe.classList.add("persona-voice-speaking"),Js("speaking"),fe.style.backgroundColor=k,fe.style.borderColor=q;let te=x||"currentColor";fe.style.color=te,Rf(y,te);let Z=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";fe.setAttribute("aria-label",Z),c==="none"&&(fe.style.cursor="default"),c==="barge-in"&&fe.classList.add("persona-voice-recording")},Er=()=>{fe&&(zd(),Js("idle"),qt&&(fe.style.backgroundColor=qt.backgroundColor??"",fe.style.color=qt.color??"",fe.style.borderColor=qt.borderColor??"",Rf(qt.iconName,qt.color||"currentColor"),qt=null),fe.style.cursor="",fe.setAttribute("aria-label","Start voice recognition"))},Wf=()=>{if(!Jo()){if(no(o.voiceRecognition?.provider)){let i=_.getVoiceStatus(),c=_.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Wo(),br("user"),Er()});return}_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),gt.manuallyDeactivated=!_.isVoiceActive(),Wo(),br("user"),_.isVoiceActive()?Xi():Er()});return}if(tr){let i=Ae.value.trim();gt.manuallyDeactivated=!0,Wo(),ns("user"),i&&!Ef()&&bl()}else gt.manuallyDeactivated=!1,Wo(),$d("user")}};um=Wf,fe&&De.push(()=>{no(o.voiceRecognition?.provider)?(_.isVoiceActive()&&_.toggleVoice(),Er()):ns("system")});let u0=E.on("assistant:complete",()=>{ze.getState().pendingSubmission&&setTimeout(()=>{_.isStreaming()||Qk()},0)});De.push(u0);let m0=E.on("assistant:complete",()=>{Tb&&(gt.active||gt.manuallyDeactivated||Tb==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{!gt.active&&!gt.manuallyDeactivated&&(no(o.voiceRecognition?.provider)?_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),br("auto"),_.isVoiceActive()&&Xi()}):$d("auto"))},600))});De.push(m0);let f0=E.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});De.push(f0);let Fv=()=>{Nt(!Pe,"user")},Qt=null,Fn=null;if(ce&&!Ee()){let{instance:i,element:c}=Sh({config:o,plugins:a,onToggle:Fv});Qt=i,i||(Fn=c)}Qt?t.appendChild(Qt.element):Fn&&t.appendChild(Fn),ol(),Pi(),md(),zm(),rl(_.isStreaming()),Im()||(ao()==="follow"?Xr(!0):id()),RE(),ge&&(!ce||Ee()?setTimeout(()=>zs(),0):Pe&&setTimeout(()=>zs(),200));let Zs=null,Vv=()=>{Zs&&(Zs.disconnect(),Zs.observe(We),Zs.observe(Le))},Cl=()=>{if(Ee()){Ms(),ol();return}let i=rn(o),c=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,k=f.innerWidth<=x,q=y&&k&&ce;try{if(q){Es(),Ka=Xc();return}let te=!1;nt&&(nt=!1,Es(),te=!0);let Z=Xc();if(!te&&Z!==Ka&&(Es(),te=!0),Ka=Z,te&&Kc(),!ce&&!i){_e.style.height="",_e.style.width="";return}if(!c&&!i){let pe=o?.launcher?.width??o?.launcherWidth??Rr;_e.style.width=pe,_e.style.maxWidth=pe}Qc(),db()}finally{if(Ms(),Vc(),ol(),Pe&&ce){let Z=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ne=o.launcher?.sidebarMode??!1,pe=o.launcher?.mobileFullscreen??!0,Ce=rn(o)&&pe&&Z,He=ne||pe&&Z&&ce||Ce;if(He&&!Xo){let wt=t.getRootNode(),Ot=wt instanceof ShadowRoot?wt.host:t.closest(".persona-host");Ot&&!Qo&&(Qo=rh(Ot,o.launcher?.zIndex??Hn)),Xo=sh(t.ownerDocument)}else He||(Qo?.(),Qo=null,Xo?.(),Xo=null)}}};Cl();let Ud=t.ownerDocument.defaultView??window;if(Ud.addEventListener("resize",Cl),De.push(()=>Ud.removeEventListener("resize",Cl)),typeof ResizeObserver<"u"){Zs=new ResizeObserver(()=>{Vc()}),Vv(),De.push(()=>{Zs?.disconnect(),Zs=null});let i=new ResizeObserver(()=>{Ld()});i.observe(Le),De.push(()=>i.disconnect())}Ud.addEventListener("resize",Ld),De.push(()=>Ud.removeEventListener("resize",Ld)),po=ie.scrollTop;let $v=lr(ie),zv=()=>{let i=ie.scrollTop,c=lr(ie),f=c<$v;if($v=c,!zr()){po=i,yn();return}let{action:y,nextLastScrollTop:x}=uu({following:co.isFollowing(),currentScrollTop:i,lastScrollTop:po,nearBottom:Wr(ie,hr),userScrollThreshold:LE,isAutoScrolling:Yn||Zc||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(po=x,y==="resume"){ad()||Qn();return}y==="pause"&&Ja()};if(ie.addEventListener("scroll",zv,{passive:!0}),De.push(()=>ie.removeEventListener("scroll",zv)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{FE(),Vf(Re)});i.observe(Re),i.observe(ie),De.push(()=>i.disconnect())}let Uv=()=>{zr()&&co.isFollowing()&&ad()&&Ja()},qv=ie.ownerDocument;qv.addEventListener("selectionchange",Uv),De.push(()=>{qv.removeEventListener("selectionchange",Uv)});let g0=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),jv=i=>{g0.has(i.key)&&(Ns(),Iy()&&zr()&&co.isFollowing()&&Ja())},Kv=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ns(),Iy()&&zr()&&co.isFollowing()&&Ja())};ie.addEventListener("keydown",jv),ie.addEventListener("focusin",Kv),De.push(()=>{ie.removeEventListener("keydown",jv),ie.removeEventListener("focusin",Kv)});let Gv=i=>{if(i.deltaY!==0&&Ns(),!zr())return;let c=mu({following:co.isFollowing(),deltaY:i.deltaY,nearBottom:Wr(ie,hr),resumeWhenNearBottom:!0});c==="pause"?Ja():c==="resume"&&!ad()&&Qn()};ie.addEventListener("wheel",Gv,{passive:!0}),ie.addEventListener("touchmove",Ns,{passive:!0}),ie.addEventListener("pointerdown",Ns,{passive:!0}),De.push(()=>{ie.removeEventListener("touchmove",Ns),ie.removeEventListener("pointerdown",Ns)}),De.push(()=>ie.removeEventListener("wheel",Gv)),ln.addEventListener("click",()=>{Bo(),ie.scrollTop=ie.scrollHeight,po=ie.scrollTop,Qn(),Xr(!0),yn()}),De.push(()=>ln.remove()),De.push(()=>{Ib(),Bo()});let Yv=()=>{F&&(Is&&(F.removeEventListener("click",Is),Is=null),Ne()?(F.style.display="",Is=()=>{Nt(!1,"user")},F.addEventListener("click",Is)):F.style.display="none")};Yv(),(()=>{let{clearChatButton:i}=Ze;i&&i.addEventListener("click",()=>{if(er()){Cf({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}_.clearMessages(),cn.clear(),Qn(),la(Ze.composerOverlay);try{localStorage.removeItem(Ba),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ba}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ba)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),R?.clear&&od(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},se.syncFromMetadata(),At?.clearAttachments(),sd(),Ai(void 0),Ko(void 0),Bs(),je?.clear(),lt?.reset(),mt?.update()})})();let Qv=[["keydown",i0],["input",r0],["input",jo],["input",Ts],["keyup",Ts],["paste",a0],["focus",yE]],Xv=i=>{if(i)for(let[c,f]of Qv)Lt?.addListener(i,c,f)},h0=i=>{if(i)for(let[c,f]of Qv)Lt?.removeListener(i,c,f)},Jv=()=>{Lt&&(Lt.addListener(Lt.form,"submit",e0),Lt.addListener(Lt.footer,"click",Ts),Xv(Ae),fe&&Lt.addListener(fe,"click",Wf))};Jv();let Zv=()=>{nn?.onComposerSwap((i,c)=>{h0(c),Ae=i,Lt&&(Lt.input=i),Xv(i),fm(),Om(),jo()})};Zv();let Bf=!1;function eC(){if(!Bf){Bf=!0;try{let i=Ae?.value??"",c=We.ownerDocument??document,f=Ae?c.activeElement===Ae:!1;If(),Lt?.destroy(),Lt=null,nn?.destroy(),nn=null;let y=null,x=()=>(y=Ee()?wu({config:o}):gc({config:o}),y.footer),k=Vy(x)??x();tn.replaceComposer(k),We=tn.composer.footer;let q=y!==null&&k===y.footer;Ti=!q,Py=q?y.setSendButtonMode:()=>{},Fy(We),zy(We),Uy(),qy(),jy(),Zv(),Ky(),gm(),Gy(),Jv();let te=Ps.indexOf(gr);gr.destroy(),gr=uc(Po),te>=0&&(Ps[te]=gr),Ae&&(Ae.value=i),jo(),Ts(),md(),Pi(),rl(_.isStreaming()),gt.active&&Js("recording"),Es(),Vv(),Ms(),Io(),pd(),f&&Ae?.focus()}finally{Bf=!1}}}let wl=t.ownerDocument??document;wl.addEventListener("keydown",Ov,!0);let tC=()=>{Em()},nC=()=>{wl.visibilityState==="hidden"&&Em()};typeof window<"u"&&(window.addEventListener("pagehide",tC),wl.addEventListener("visibilitychange",nC),De.push(()=>{window.removeEventListener("pagehide",tC),wl.removeEventListener("visibilitychange",nC)}));let oC="persona-attachment-drop-active",xl=0,Of=()=>{xl=0,Le.classList.remove(oC)},Ji=()=>o.attachments?.enabled===!0&&At!==null&&!Jo(),rC=i=>{!tm(i.dataTransfer)||!Ji()||(xl++,xl===1&&Le.classList.add(oC))},sC=i=>{!tm(i.dataTransfer)||!Ji()||(xl--,xl<=0&&Of())},iC=i=>{!tm(i.dataTransfer)||!Ji()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},aC=i=>{if(!tm(i.dataTransfer)||!Ji())return;i.preventDefault(),i.stopPropagation(),Of();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&At.handleFiles(c)},os=!0;Le.addEventListener("dragenter",rC,os),Le.addEventListener("dragleave",sC,os),t.addEventListener("dragover",iC,os),t.addEventListener("drop",aC,os);let qd=t.ownerDocument,lC=i=>{Ji()&&i.preventDefault()},cC=i=>{Ji()&&i.preventDefault()};qd.addEventListener("dragover",lC),qd.addEventListener("drop",cC),De.push(()=>{Lt?.destroy(),Lt=null,If(),Go?.destroy(),Go=null,mr?.destroy(),mr=null,qr?.destroy(),qr=null,jr?.destroy(),jr=null,Ur=null,dm=null,Em(),Xa.destroy(),Gi&&clearTimeout(Gi),Bs(),Xs?.abort(),Xs=null,At?.destroy(),At=null,ze.destroy(),wl.removeEventListener("keydown",Ov,!0),nn?.destroy()}),De.push(()=>{Le.removeEventListener("dragenter",rC,os),Le.removeEventListener("dragleave",sC,os),t.removeEventListener("dragover",iC,os),t.removeEventListener("drop",aC,os),qd.removeEventListener("dragover",lC),qd.removeEventListener("drop",cC),Of()}),De.push(()=>{_.cancel()}),Qt?De.push(()=>{Qt?.destroy()}):Fn&&De.push(()=>{Fn?.remove()});let Xt={update(i){let c=o.toolCall,f=o.messageActions,y=o.layout?.messages,x=o.colorScheme,k=o.loadingIndicator,q=o.iterationDisplay,te=o.features?.showReasoning,Z=o.features?.showToolCalls,ne=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,Ce=o.features?.streamAnimation?.type,He=o.features?.history?.enabled===!0,wt=o.features?.history?.provider,Ot=o.getIdentityProof,Ft=o.clientToken,xn=o.contextMentions;o=mT({...o,features:s},i),s=o.features,o=ty(o),r(),wm(),Zl(t,o),kc(t,o),Lc(t,o),ut(),Ro(),o.colorScheme!==x&&pb();let pn=ry.getForInstance(o.plugins);a.length=0,a.push(...pn),dv(),ce=o.launcher?.enabled??!0,we=o.launcher?.autoExpand??!1,yt=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,j=o.features?.scrollToBottom??{};let Jt=ao();J=o.features?.scrollBehavior??{},Jt!==ao()&&(Bo(),Qn()),Mb(),Wy(),yn();let Bn=L;if(L=o.features?.showEventStreamToggle??!1,L&&!Bn){if(je||(_t(),_.setSSEEventCallback((ue,ht)=>{o.onSSEEvent?.(ue,ht),pt(ue,ht)})),!kt&&he){let ue=o.features?.eventStream?.classNames,ht="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"+(ue?.toggleButton?" "+ue.toggleButton:"");kt=v("button",ht),kt.style.width="28px",kt.style.height="28px",kt.style.color=Un.actionIconColor,kt.type="button",kt.setAttribute("aria-label","Event Stream"),kt.title="Event Stream";let vt=Qe(Fr.Activity,"18px","currentColor",1.5);vt&&kt.appendChild(vt);let Pt=Ze.clearChatButtonWrapper,jt=Ze.closeButtonWrapper,In=Pt||jt;In&&In.parentNode===he?he.insertBefore(kt,In):he.appendChild(kt),kt.addEventListener("click",()=>{Tt?Mi():mm()})}}else!L&&Bn&&(Mi(),kt&&(kt.remove(),kt=null),je?.clear(),Te?.destroy(),je=null,Te=null,lt?.reset(),lt=null,ot=null);if(o.launcher?.enabled===!1&&Qt&&(Qt.destroy(),Qt=null),o.launcher?.enabled===!1&&Fn&&(Fn.remove(),Fn=null),o.launcher?.enabled!==!1&&!Qt&&!Fn){let{instance:ue,element:ht}=Sh({config:o,plugins:a,onToggle:Fv});Qt=ue,ue||(Fn=ht),t.appendChild(ht)}Qt&&Qt.update(o),yl(),et&&o.launcher?.subtitle!==void 0&&(et.textContent=o.launcher.subtitle);let Mt=o.layout?.header;if(Mt?.layout!==ke&&he){let ue=Mt?vu(o,Mt,{showClose:Ne(),onClose:()=>Nt(!1,"user")}):li({config:o,showClose:Ne(),onClose:()=>Nt(!1,"user")});tn.replaceHeader(ue),he=tn.header.element,le=tn.header.iconHolder,Be=tn.header.headerTitle,et=tn.header.headerSubtitle,F=tn.header.closeButton,ke=Mt?.layout,yl()}else if(Mt){if(le&&(le.style.display=Mt.showIcon===!1?"none":""),Be&&(Be.style.display=Mt.showTitle===!1?"none":""),et&&(et.style.display=Mt.showSubtitle===!1?"none":""),F){let ue=Ne()&&Mt.showCloseButton!==!1;F.style.display=ue?"":"none"}if(Ze.clearChatButtonWrapper){let ue=Mt.showClearChat;if(ue!==void 0){Ze.clearChatButtonWrapper.style.display=ue?"":"none";let{closeButtonWrapper:ht}=Ze;ht&&!ht.classList.contains("persona-absolute")&&(ue?ht.classList.remove("persona-ml-auto"):ht.classList.add("persona-ml-auto"))}}}let nr=o.layout?.showHeader!==!1;he&&(he.style.display=nr?"":"none");let kr=o.layout?.showFooter!==!1;We&&(We.style.display=kr?"":"none"),Ms(),yn(),ce!==ye?ce?Nt(we,"auto"):(Pe=!0,ol()):we!==N&&Nt(we,"auto"),N=we,ye=ce,Cl(),Yv();let ei=JSON.stringify(o.toolCall)!==JSON.stringify(c),Do=JSON.stringify(o.messageActions)!==JSON.stringify(f),Ln=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),_o=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,Zi=o.iterationDisplay!==q,U=(o.features?.showReasoning??!0)!==(te??!0)||(o.features?.showToolCalls??!0)!==(Z??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ne)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(ei||Do||Ln||_o||Zi||U)&&_&&(Os++,bo(Re,_.getMessages(),Ge));let qe=o.features?.streamAnimation?.type;if(qe!==Ce&&qe&&qe!=="none"){let ue=Sm(qe,o.features?.streamAnimation?.plugins);ue&&ic(ue,t)}let xe=o.launcher??{},Zt=xe.headerIconHidden??!1,un=o.layout?.header?.showIcon,Pn=Zt||un===!1,mn=xe.headerIconName,bn=xe.headerIconSize??"48px";if(le){let ue=he,ht=ue?.querySelector(".persona-flex-col");if(Pn)le.style.display="none",ue&&ht&&!ue.contains(ht)&&ue.insertBefore(ht,ue.firstChild);else{if(le.style.display="",le.style.height=bn,le.style.width=bn,ue&&ht&&(ue.contains(le)?le.nextSibling!==ht&&(le.remove(),ue.insertBefore(le,ht)):ue.insertBefore(le,ht)),mn){let Pt=parseFloat(bn)||24,jt=Ie(mn,Pt*.6,"currentColor",1);jt?le.replaceChildren(jt):le.textContent=xe.agentIconText??"\u{1F4AC}"}else if(xe.iconUrl){let Pt=le.querySelector("img");if(Pt)Pt.src=xe.iconUrl,Pt.style.height=bn,Pt.style.width=bn;else{let jt=document.createElement("img");jt.src=xe.iconUrl,jt.alt="",jt.className="persona-rounded-xl persona-object-cover",jt.style.height=bn,jt.style.width=bn,le.replaceChildren(jt)}}else{let Pt=le.querySelector("svg"),jt=le.querySelector("img");(Pt||jt)&&le.replaceChildren(),le.textContent=xe.agentIconText??"\u{1F4AC}"}let vt=le.querySelector("img");vt&&(vt.style.height=bn,vt.style.width=bn)}}let en=o.layout?.header?.showTitle,Dn=o.layout?.header?.showSubtitle;if(Be&&(Be.style.display=en===!1?"none":""),et&&(et.style.display=Dn===!1?"none":""),F){let ue=Ne()&&o.layout?.header?.showCloseButton!==!1;if(F.style.display=ue?"":"none",!Ee()){let Sn=xe.closeButtonSize??"";F.style.height=Sn,F.style.width=Sn,F.style.minWidth=Sn,F.style.minHeight=Sn}let ht=xe.closeButtonPlacement??"inline",{closeButtonWrapper:vt}=Ze,Pt=ht==="top-right",jt=vt?.classList.contains("persona-absolute");if(vt&&Pt!==jt)if(vt.remove(),Pt){vt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Sn=cl??Le;Sn.style.position="relative",Sn.appendChild(vt)}else{let Sn=xe.clearChat?.placement??"inline",An=xe.clearChat?.enabled??!0;vt.className=An&&Sn==="inline"?"":"persona-ml-auto",he&&he.appendChild(vt)}if(F.style.color=xe.closeButtonColor||Un.actionIconColor,xe.closeButtonBackgroundColor?(F.style.backgroundColor=xe.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let Sn=xe.closeButtonBorderWidth||"0px",An=xe.closeButtonBorderColor||"transparent";F.style.border=`${Sn} solid ${An}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");xe.closeButtonBorderRadius?(F.style.borderRadius=xe.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(F.style.paddingLeft=xe.closeButtonPaddingX,F.style.paddingRight=xe.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),xe.closeButtonPaddingY?(F.style.paddingTop=xe.closeButtonPaddingY,F.style.paddingBottom=xe.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom=""),yu(F,xe.closeButtonIconName??"x",{iconSize:Ee()?vh:void 0,iconText:xe.closeButtonIconText??"\xD7"});let In=xe.closeButtonTooltipText??"Close chat",No=xe.closeButtonShowTooltip??!0;F.setAttribute("aria-label",In),vt&&Mn({anchor:F,trigger:vt,text:()=>F?.getAttribute("aria-label")??In,enabled:No})}let{clearChatButton:tt,clearChatButtonWrapper:st}=Ze;if(tt){let ue=xe.clearChat??{},ht=ue.enabled??!0,vt=o.layout?.header?.showClearChat,Pt=vt!==void 0?vt:ht,jt=ue.placement??"inline";if(st){st.style.display=Pt?"":"none";let{closeButtonWrapper:In}=Ze;!Ee()&&In&&!In.classList.contains("persona-absolute")&&(Pt?In.classList.remove("persona-ml-auto"):In.classList.add("persona-ml-auto"));let No=jt==="top-right",Sn=st.classList.contains("persona-absolute");if(!Ee()&&No!==Sn&&Pt){if(st.remove(),No){st.className="persona-absolute persona-top-4 persona-z-50",st.style.right="48px";let or=cl??Le;or.style.position="relative",or.appendChild(st)}else{st.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",st.style.right="";let or=Ze.closeButtonWrapper;he&&or&&or.parentElement===he?he.insertBefore(st,or):he&&he.appendChild(st)}let An=Ze.closeButtonWrapper;An&&!An.classList.contains("persona-absolute")&&(No?An.classList.add("persona-ml-auto"):An.classList.remove("persona-ml-auto"))}}if(Pt){if(!Ee()){let An=ue.size??"";tt.style.height=An,tt.style.width=An,tt.style.minWidth=An,tt.style.minHeight=An}let In=ue.iconColor??"";if(tt.style.color=In||Un.actionIconColor,yu(tt,ue.iconName??"refresh-cw",{iconSize:Ee()?Ch:void 0}),ue.backgroundColor?(tt.style.backgroundColor=ue.backgroundColor,tt.classList.remove("hover:persona-bg-gray-100")):(tt.style.backgroundColor="",tt.classList.add("hover:persona-bg-gray-100")),ue.borderWidth||ue.borderColor){let An=ue.borderWidth||"0px",or=ue.borderColor||"transparent";tt.style.border=`${An} solid ${or}`,tt.classList.remove("persona-border-none")}else tt.style.border="",tt.classList.add("persona-border-none");ue.borderRadius?(tt.style.borderRadius=ue.borderRadius,tt.classList.remove("persona-rounded-full")):(tt.style.borderRadius="",tt.classList.add("persona-rounded-full")),ue.paddingX?(tt.style.paddingLeft=ue.paddingX,tt.style.paddingRight=ue.paddingX):(tt.style.paddingLeft="",tt.style.paddingRight=""),ue.paddingY?(tt.style.paddingTop=ue.paddingY,tt.style.paddingBottom=ue.paddingY):(tt.style.paddingTop="",tt.style.paddingBottom="");let No=ue.tooltipText??"Clear chat",Sn=ue.showTooltip??!0;tt.setAttribute("aria-label",No),st&&Mn({anchor:tt,trigger:st,text:()=>tt?.getAttribute("aria-label")??No,enabled:Sn})}}let Ue=o.actionParsers&&o.actionParsers.length?o.actionParsers:[iy],_n=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pc.message,Pc.messageAndClick];se=ay({parsers:Ue,handlers:_n,getSessionMetadata:K,updateSessionMetadata:Y,emit:E.emit,documentRef:typeof document<"u"?document:null}),Ge=KT(o,se,xt),rk(),_.updateConfig(o),(o.features?.history?.enabled===!0!==He||o.features?.history?.provider!==wt||o.getIdentityProof!==Ot||o.clientToken!==Ft)&&(Jn({restoreFocus:!1}),nv()),ts(),Ld(),bo(Re,_.getMessages(),Ge),Pi(),md(),nk(),rl(_.isStreaming()),xn!==o.contextMentions&&eC();let rs=o.voiceRecognition?.enabled===!0,Zn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),eo=no(o.voiceRecognition?.provider);if(rs&&(Zn||eo))if(!fe||!io){let ue=ha(o);if(ue){fe=ue.button,io=ue.wrapper;let ht=qo&&qo.parentElement===$r?qo:null;$r?$r.insertBefore(io,ht):Wn?.appendChild(io),Lt&&(Lt.micButton=fe),Lt?.addListener(fe,"click",Wf),fe.disabled=Jo()||_.isStreaming()&&!Wm()}}else{let ue=o.voiceRecognition??{},ht=o.sendButton??{},vt=ue.iconName??"mic",Pt=ue.iconSize,jt=parseFloat(Pt??"")||$n;fe.classList.add(fo),fe.classList.toggle(Vo,!Pt),fe.style.width=Pt??"",fe.style.height=Pt??"",fe.style.minWidth=Pt??"",fe.style.minHeight=Pt??"";let In=ue.iconColor??ht.textColor;fe.innerHTML="";let No=Ie(vt,jt,In||"currentColor",1.5);No?fe.appendChild(No):fe.textContent="\u{1F3A4}";let Sn=ue.backgroundColor??ht.backgroundColor;Sn?fe.style.backgroundColor=Sn:fe.style.backgroundColor="",In?fe.style.color=In:fe.style.color="var(--persona-text, #111827)",ue.borderWidth?(fe.style.borderWidth=ue.borderWidth,fe.style.borderStyle="solid"):(fe.style.borderWidth="",fe.style.borderStyle=""),ue.borderColor?fe.style.borderColor=ue.borderColor:fe.style.borderColor="",ue.paddingX?(fe.style.paddingLeft=ue.paddingX,fe.style.paddingRight=ue.paddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),ue.paddingY?(fe.style.paddingTop=ue.paddingY,fe.style.paddingBottom=ue.paddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let An=ue.tooltipText??"Start voice recognition",or=ue.showTooltip??!1;fe.setAttribute("aria-label",An),io&&Mn({anchor:fe,trigger:io,text:()=>fe?.getAttribute("aria-label")??An,enabled:or}),io.style.display="",fe.disabled=Jo()||_.isStreaming()&&!Wm()}else fe&&io&&(io.style.display="none",no(o.voiceRecognition?.provider)?_.isVoiceActive()&&_.toggleVoice():tr&&ns());if(o.attachments?.enabled===!0){if(!Kn||!Gt){let ue=o.attachments??{};Gn||(Gn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Gn.style.display="none",(Ae.parentElement??Wn).insertBefore(Gn,Ae)),zt||(zt=document.createElement("input"),zt.type="file",zt.accept=(ue.allowedTypes??Hr).join(","),zt.multiple=(ue.maxFiles??4)>1,zt.style.display="none",zt.setAttribute("aria-label","Attach files"),(Ae.parentElement??Wn).insertBefore(zt,Ae)),Kn=v("div","persona-send-button-wrapper"),Gt=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${fo} ${Vo}`),Gt.type="button",Gt.setAttribute("aria-label",ue.buttonTooltipText??"Attach file");let ht=ue.buttonIconName??"paperclip";Gt.style.fontSize="18px",Gt.style.lineHeight="1";let vt=Ie(ht,$n,"currentColor",1.5);vt?Gt.appendChild(vt):Gt.textContent="\u{1F4CE}",Gt.addEventListener("click",jt=>{jt.preventDefault(),zt?.click()}),Kn.appendChild(Gt);let Pt=ue.buttonTooltipText??"Attach file";Mn({anchor:Gt,trigger:Kn,text:()=>Gt?.getAttribute("aria-label")??Pt}),Uo?Uo.append(Kn):Wn.appendChild(Kn),Lt&&(Lt.attachmentButton=Gt,Lt.attachmentInput=zt??void 0,Lt.attachmentPreviews=Gn??void 0),!At&&zt&&Gn&&(At=$l.fromConfig(ue,By),At.setPreviewsContainer(Gn),Lt?.addListener(zt,"change",async()=>{At&&zt?.files&&(await At.handleFileSelect(zt.files),zt.value="")}))}else{Kn.style.display="";let ue=o.attachments??{};zt&&(zt.accept=(ue.allowedTypes??Hr).join(","),zt.multiple=(ue.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:ue.allowedTypes,maxFileSize:ue.maxFileSize,maxFiles:ue.maxFiles,adapter:ue.adapter})}if(Le.querySelector(".persona-attachment-drop-overlay")?.remove(),Le.appendChild(GT(o.attachments?.dropOverlay)),Gt){let ue=o.attachments??{},ht=ue.buttonTooltipText??"Attach file";Gt.setAttribute("aria-label",ht),Gt.textContent="";let vt=Ie(ue.buttonIconName??"paperclip",$n,"currentColor",1.5);vt?Gt.appendChild(vt):Gt.textContent="\u{1F4CE}",Kn&&Mn({anchor:Gt,trigger:Kn,text:()=>Gt?.getAttribute("aria-label")??ht})}}else Kn&&(Kn.style.display="none"),At&&At.clearAttachments(),Le.querySelector(".persona-attachment-drop-overlay")?.remove();let rt=o.sendButton??{},Lr=rt.useIcon??!1,on=rt.iconText??"\u2191",to=rt.iconName,Al=rt.tooltipText??"Send message",v0=rt.showTooltip??!1,Ml=rt.size,C0=parseFloat(Ml??"")||Sg,jd=rt.backgroundColor,Tl=rt.textColor;if(Lr){if(Ve.style.width=Ml??"",Ve.style.height=Ml??"",Ve.style.minWidth=Ml??"",Ve.style.minHeight=Ml??"",Ve.style.fontSize="18px",Ve.style.lineHeight="1",Tl?Ve.style.color=Tl:Ve.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!_.isStreaming())if(Ve.innerHTML="",to){let ue=parseFloat(rt.iconSize??"")||Math.round(C0*.5),ht=Tl?.trim()||"currentColor",vt=rt.iconStrokeWidth??2,Pt=Ie(to,ue,ht,vt),jt=Ie(rt.stopIconName??"square",ue,ht,vt);Pt&&jt?Ve.appendChild(Ag(Pt,jt)):Pt?Ve.appendChild(Pt):Ve.textContent=on}else Ve.textContent=on;Ve.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${fo}`,jd?(Ve.style.backgroundColor=jd,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=o.copy?.sendButtonLabel??"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.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",jd?(Ve.style.backgroundColor=jd,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),Tl?Ve.style.color=Tl:Ve.classList.add("persona-text-white");rt.borderWidth?(Ve.style.borderWidth=rt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),rt.borderColor?Ve.style.borderColor=rt.borderColor:Ve.style.borderColor="",rt.paddingX?(Ve.style.paddingLeft=rt.paddingX,Ve.style.paddingRight=rt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),rt.paddingY?(Ve.style.paddingTop=rt.paddingY,Ve.style.paddingBottom=rt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom=""),_.isStreaming()||Ve.setAttribute("aria-label",Al),pd(),qo&&Mn({anchor:Ve,trigger:qo,text:()=>Ve.getAttribute("aria-label")??Al,enabled:v0}),Qy();let dC=$p(ze.getState().activeModeIds,o.composer?.modes);ze.setActiveModeIds(dC),xi().length>0!==!!mr&&gm(),mr?.render(dC,xi());for(let ue of[...Si.keys()])Vp(ue,o.composer?.modeGroups)||Si.delete(ue);Si.forEach(ue=>ue.repaint()),Ur?.repaint(),Go?.resolve();let Kd=ys(o,Ee());if(xm(),Kd){Re.style.maxWidth=Kd,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",kn.style.maxWidth=Kd,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%";for(let ue of[Wn,Po,Gn,bt])ue&&(ue.style.maxWidth=Kd,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%")}else{Re.style.maxWidth="",Re.style.marginLeft="",Re.style.marginRight="",Re.style.width="",kn.style.maxWidth="",kn.style.marginLeft="",kn.style.marginRight="",kn.style.width="";for(let ue of[Wn,Po,Gn,bt])ue&&(ue.style.maxWidth="",ue.style.marginLeft="",ue.style.marginRight="",ue.style.width="")}let ss=o.statusIndicator??{},w0=ss.visible??!0;if(bt.style.display=w0?"":"none",_){let ue=_.getStatus();Rn(bt,(vt=>vt==="idle"?ss.idleText??fn.idle:vt==="connecting"?ss.connectingText??fn.connecting:vt==="connected"?ss.connectedText??fn.connected:vt==="error"?ss.errorText??fn.error:fn[vt])(ue),ss,ue)}bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let x0=ss.align==="left"?"persona-text-left":ss.align==="center"?"persona-text-center":"persona-text-right";bt.classList.add(x0),fm(),Om(),Io(),Ke()},open(){Ne()&&Nt(!0,"api")},close(){Ne()&&Nt(!1,"api")},toggle(){Ne()&&Nt(!Pe,"api")},reconnect(){_.reconnectNow()},clearChat(){fr=!1,_.clearMessages(),cn.clear(),Qn();try{localStorage.removeItem(Ba),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ba}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ba)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),R?.clear&&od(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},se.syncFromMetadata(),At?.clearAttachments(),sd(),Ai(void 0),Ko(void 0),Bs(),je?.clear(),lt?.reset(),mt?.update()},setMessage(i){return!Ae||_.isStreaming()||Jo()?!1:(!Pe&&Ne()&&Nt(!0,"system"),Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming()||$s())return!1;let c=i?.trim()||Ae.value.trim();return c?(!Pe&&Ne()&&Nt(!0,"system"),Ae.value="",Ae.style.height="auto",jo(),Fd(c,{consumeDraft:!1}),!0):!1},getComposerState(){return ze.getState()},setQuote(i){let c=i?.text?.trim();c&&Ko({...i,text:c})},clearQuote(){Ko(void 0)},startVoiceRecognition(){return _.isStreaming()?!1:no(o.voiceRecognition?.provider)?(_.isVoiceActive()||_.isBargeInActive()||(!Pe&&Ne()&&Nt(!0,"system"),gt.manuallyDeactivated=!1,Wo(),_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),br("user"),_.isVoiceActive()&&Xi()})),!0):tr?!0:Nv()?(!Pe&&Ne()&&Nt(!0,"system"),gt.manuallyDeactivated=!1,Wo(),$d("user"),!0):!1},stopVoiceRecognition(){return no(o.voiceRecognition?.provider)?!_.isVoiceActive()&&!_.isBargeInActive()?!1:((_.isBargeInActive()?_.deactivateBargeIn():_.toggleVoice()).then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Wo(),br("user"),Er()}),!0):tr?(gt.manuallyDeactivated=!0,Wo(),ns("user"),!0):!1},injectMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!Pe&&Ne()&&Nt(!0,"system");let c=_.injectAssistantMessage(i);return dt&&(dt=!1,Xe&&(clearTimeout(Xe),Xe=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),c},injectUserMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!Pe&&Ne()&&Nt(!0,"system"),_.injectTestEvent(i)},async connectStream(i,c){return _.connectStream(i,c)},__pushEventStreamEvent(i){L&&(_t(),pt(i.type,i.payload))},showEventStream(){L&&mm()},hideEventStream(){Tt&&Mi()},isEventStreamVisible(){return Tt},listConversations(i){return _.listConversations(i)},getActiveConversationId(){return _.getActiveConversationId()},openConversation(i,c){return vf(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Cf({focusComposer:i?.focus===!0})},deleteConversation(i){return kv(i)},renameConversation(i,c){return wf(i,{title:c})},setConversationStarred(i,c){return wf(i,{starred:c})},clearConversationHistory(i){return Lv(i)},resetHistoryIdentity(){return Pv()},getHistoryIdentityStatus(){return uo?uo.getIdentityStatus():tf()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return hl({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Jn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return ve},showArtifacts(){jn(o)&&(fr=!1,Ei=!0,Ro(),ft?.setMobileOpen(!0))},hideArtifacts(){jn(o)&&(fr=!0,Ro())},upsertArtifact(i){return jn(o)?(is(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(fr=!1,Ei=!0),_.upsertArtifact(i)):null},selectArtifact(i){jn(o)&&_.selectArtifact(i)},clearArtifacts(){jn(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return ce&&!Pe&&!Ee()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(i,c,f){let x=_.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!x?.approval)throw new Error(`Approval not found: ${i}`);if(x.approval.toolType==="webmcp"){_.resolveWebMcpApproval(x.id,c);return}return _.resolveApproval(x.approval,c,f)},setFollowUpSuggestions(i){EE(i)},clearFollowUpSuggestions(){Ab()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...H}},updatePersistentMetadata(i){Y(i)},on(i,c){return E.on(i,c)},off(i,c){E.off(i,c)},isOpen(){return Ne()&&Pe},isVoiceActive(){return gt.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:Ne()&&Pe,launcherEnabled:ce,voiceActive:gt.active,streaming:_.isStreaming()}},showCSATFeedback(i){!Pe&&Ne()&&Nt(!0,"system");let c=Re.querySelector(".persona-feedback-container");c&&c.remove();let f=UT({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});Re.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Pe&&Ne()&&Nt(!0,"system");let c=Re.querySelector(".persona-feedback-container");c&&c.remove();let f=qT({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});Re.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return _.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return _.submitNPSFeedback(i,c)},destroy(){Gm(),qs!=null&&(clearInterval(qs),qs=null),De.forEach(i=>i()),it.remove(),Kt?.remove(),Qt?.destroy(),Fn?.remove(),Is&&F.removeEventListener("click",Is)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Xt,getMessages:Xt.getMessages,getStatus:Xt.getStatus,getMetadata:Xt.getPersistentMetadata,updateMetadata:Xt.updatePersistentMetadata,clearHistory:()=>Xt.clearChat(),setVoiceActive:f=>f?Xt.startVoiceRecognition():Xt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,De.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),c=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.focusInput()};if(window.addEventListener("persona:focusInput",c),De.push(()=>{window.removeEventListener("persona:focusInput",c)}),L){let ne=Ce=>{let He=Ce.detail;(!He?.instanceId||He.instanceId===i)&&Xt.showEventStream()},pe=Ce=>{let He=Ce.detail;(!He?.instanceId||He.instanceId===i)&&Xt.hideEventStream()};window.addEventListener("persona:showEventStream",ne),window.addEventListener("persona:hideEventStream",pe),De.push(()=>{window.removeEventListener("persona:showEventStream",ne),window.removeEventListener("persona:hideEventStream",pe)})}let f=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.showHistory()},y=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",y),De.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",y)});let x=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.showArtifacts()},k=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.hideArtifacts()},q=ne=>{let pe=ne.detail;pe?.instanceId&&pe.instanceId!==i||pe?.artifact&&Xt.upsertArtifact(pe.artifact)},te=ne=>{let pe=ne.detail;pe?.instanceId&&pe.instanceId!==i||typeof pe?.id=="string"&&Xt.selectArtifact(pe.id)},Z=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",te),window.addEventListener("persona:clearArtifacts",Z),De.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",te),window.removeEventListener("persona:clearArtifacts",Z)})}let So=WB(o.persistState);if(So&&Ne()){let i=BB(So.storage),c=`${So.keyPrefix}widget-open`,f=`${So.keyPrefix}widget-voice`,y=`${So.keyPrefix}widget-voice-mode`;if(i){let x=So.persist?.openState&&i.getItem(c)==="true",k=So.persist?.voiceState&&i.getItem(f)==="true",q=So.persist?.voiceState&&i.getItem(y)==="true";if(x&&(Qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Xt.open(),setTimeout(()=>{if(k||q)Xt.startVoiceRecognition();else if(So.persist?.focusInput){let te=t.querySelector("textarea");te&&te.focus()}},100)},0)),So.persist?.openState&&(E.on("widget:opened",()=>{i.setItem(c,"true")}),E.on("widget:closed",()=>{i.setItem(c,"false")})),So.persist?.voiceState&&(E.on("voice:state",te=>{i.setItem(f,te.active?"true":"false")}),E.on("user:message",te=>{i.setItem(y,te.viaVoice?"true":"false")})),So.clearOnChatClear){let te=()=>{i.removeItem(c),i.removeItem(f),i.removeItem(y)},Z=()=>te();window.addEventListener("persona:clear-chat",Z),De.push(()=>{window.removeEventListener("persona:clear-chat",Z)})}}}if(G&&Ne()&&(Qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Xt.open()},0)),Di(),!kE){let i=ea(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))});De.push(i)}C=()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))},_.getMessages().length>0&&dd(),A=()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))};let y0=Jw(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))});De.push(y0);let b0=Xh(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge),Dr()?.updateInlineArtifactBlocks(Re,yo.artifacts,{suppressTransition:!0}),Ro())});return De.push(b0),Xt};fs();var QT=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},_B=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},NB=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},FB=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},XT=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Ey=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},JT=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Ey(t)},Ay=t=>{t.style.transition=""},My=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Ty=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},nm=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},VB=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},$B=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},zB=t=>{let e=Ca(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:zn(e,r)??r;return{inset:o(n?.inset,ou),canvasBackground:o(n?.canvasBackground,ru)}},ZT=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},UB=(t,e,n,o,r,s,a,l)=>{let d=ko(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",h=l?.canvasBackground??"";VB(t,e,n,o,p),$B(t,e,n,o,d.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.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 g=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,S=g!=null?g.innerWidth<=C:!1;if(b&&S&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),My(e),Ay(o),JT(o),Ty(n),nm(r,o),ZT(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Hn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),JT(o),_B(o,d.maxHeight),ZT(o,u&&a,m,h),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",My(e),Ay(o),Ty(n),nm(r,o);let M=d.animate?"transform 180ms ease":"none",B=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Ay(o),Ey(o),nm(r,o);let M=QT(d.width,t.clientWidth),B=Math.max(0,t.clientWidth),A=d.animate?"margin-left 180ms ease":"none",O=d.side==="right"?a?-M:0:a?0:-M;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${B+M}px`,e.style.transition=A,e.style.marginLeft=`${O}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",My(e),Ey(o),Ty(n),nm(r,o);let M=d.reveal==="emerge";M?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let B=a?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",O=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",NB(o,d.maxHeight),o.style.overflow=M||O?"hidden":"visible",o.style.transition=A,M){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let E=u?`calc(${QT(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=E,r.style.minWidth=E,r.style.maxWidth=E,r.style.boxSizing="border-box"}}},qB=(t,e)=>{let n=t.ownerDocument.createElement("div");return XT(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){XT(n,o)},destroy(){n.remove()}}},jB=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,t),d.appendChild(t);let h=null,g=()=>{h?.disconnect(),h=null},b=null,C=()=>{b=e?.launcher?.detachedPanel===!0?zB(e):null};C();let S=()=>{UB(a,l,d,p,u,e,m,b)},P=null,M=()=>{P?.(),P=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(P=su(()=>{C(),S()}))},B=()=>{g(),ko(e).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{S()}),h.observe(a)))},A=!1,O=()=>{S(),B(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,FB(a,ko(e)))},E=a.ownerDocument.defaultView,W=()=>{O()};return E?.addEventListener("resize",W),ko(e).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),O(),M(),{mode:"docked",host:u,shell:a,syncWidgetState(R){let V=R.launcherEnabled?R.open:!0;m!==V&&(m=V,O())},updateConfig(R){e=R,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),O(),M()},destroy(){E?.removeEventListener("resize",W),P?.(),P=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},eE=(t,e)=>rn(e)?jB(t,e):qB(t,e);var Oc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},tE=.15,nE=1.5,ky="persona-preview-shell-theme",KB={load:()=>null,save:()=>{},clear:()=>{}},GB=["How do I get started?","Pricing & plans","Talk to support"];function Ly(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function YB(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function oE(t){let e=YB(t);return`* { box-sizing: border-box; }
1267
+ `)}if(!y&&!i){let st="max-height: -moz-available !important; max-height: stretch !important;",Ue=c?"":"padding-top: 1.25em !important;",_n=c?"":`z-index: ${o.launcher?.zIndex??Hn} !important;`;it.style.cssText+=st+Ue+_n}lm(),en()},xm=()=>{t.style.setProperty("--persona-content-max-width",ys(o,Ee()))},lb=!1,cb=()=>{let i=Gg(o,Ee());Ee()&&o.composer?.placement&&o.debug===!0&&!lb&&(lb=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=Br(o);t.setAttribute("data-persona-composer-placement",i),t.setAttribute("data-persona-conversation-state",Nc),t.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",c.composerGap??iu),Vc()},db=()=>{if(Ee())return;let i=rn(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ce)return;let y=t.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=k)return;let q=y.innerHeight,te=64,Z=o.launcher?.heightOffset??0,ne=Math.max(200,q-te),pe=Math.min(640,ne);_e.style.height=`${Math.max(200,pe-Z)}px`};wm(),Zl(t,o),kc(t,o),Lc(t,o),xm(),cb(),Es=()=>{wm(),db(),Zl(t,o),kc(t,o),Lc(t,o),xm(),cb(),Uc?t.style.setProperty("--persona-artifact-welded-outer-radius",Uc):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ut(),Ke()};let De=[];De.push(()=>{nb=!0}),De.push(()=>{d.forEach(i=>i()),l.destroy()}),De.push(()=>{document.removeEventListener("keydown",sb)}),De.push(()=>{za!==null&&clearTimeout(za)});let Xo=null,Jo=null;De.push(()=>{Xo?.(),Xo=null,Jo?.(),Jo=null}),ja&&De.push(()=>{ja?.disconnect(),ja=null}),De.push(()=>{Ya?.(),Ya=null,Cm(),Ut&&(Ut.remove(),Ut=null),ft?.element.style.removeProperty("width"),ft?.element.style.removeProperty("maxWidth"),ft?.destroy()}),L&&De.push(()=>{Je=!0,ot=null,ee!==null&&(cancelAnimationFrame(ee),ee=null),mt?.destroy(),mt=null,je?.destroy(),je=null,Te=null});let Ls=null,pb=()=>{Ls&&(Ls(),Ls=null),o.colorScheme==="auto"&&(Ls=su(()=>{Zl(t,o)}))};pb(),De.push(()=>{Ls&&(Ls(),Ls=null)}),De.push(()=>{b=!0,g?.()}),De.push(()=>{M=!0});let ub=!1;De.push(()=>{ub=!0});let Sm=(i,c)=>{let f=oc(i,c);return f||!ZS.includes(i)?f:(bA().then(y=>{if(ub)return;ii(y.wipe),ii(y.glyphCycle);let x=oc(i,c);x&&ic(x,t)}).catch(()=>{}),null)},Jc=o.features?.streamAnimation;if(Jc?.type&&Jc.type!=="none"){let i=Sm(Jc.type,Jc.plugins);i&&ic(i,t),De.push(()=>eA(t))}let hr=uc(Io),mb=uc(wi),fb=uc(Vr),Ps=[hr,mb,fb];De.push(()=>{Ps.forEach(i=>i.destroy())});let Is=null,_,Hs=null,gb=!1,hb=0,yb=null,bb=i=>i.reduce((c,f)=>f.role==="user"?c+1:c,0),vb=i=>{for(let c=i.length-1;c>=0;c--)if(Pl(i[c]))return i[c].id??null;return null},Cb=!1,TE=()=>{Cb||o.debug!==!0||(Cb=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},wb=!1,xb=!1,Sb=(i,c)=>{wb||o.debug!==!0||!c.enabled||c.expose||gb||xb&&(_.isStreaming()||i.some(Pl)||(wb=!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.")))},Pi=i=>{if(!_)return;let c=i??_.getMessages(),f=ne=>{ne.render([],_,Ae,c)},y=ne=>{Ps.forEach(pe=>{pe!==ne&&f(pe)})};Hs&&(bb(c)>hb||vb(c)!==yb)&&(Hs=null);let x=ps(o);Sb(c,x);let k=x.enabled?ow(c):null,q=Hs??k,te=Hs?"host":"agent";if(q){let ne=o.suggestions?.followUps,pe=ne?.placement??(ne?"auto":"composer"),He=(pe==="auto"?Ee()?"composer":"after-message":pe)==="after-message"?fb:hr;y(He),He.render(q,_,Ae,c,o.suggestionChipsConfig,{source:te,surface:"followUp",variant:ne?.variant??"chip",behavior:ne?.behavior??"send",overflow:ne?.overflow??"wrap",maxItems:ne?.maxItems??4,config:o,plugins:a,submitPrompt:Nd});return}if(c.some(ne=>ne.role==="user")){Ps.forEach(f);return}let Z=o.suggestions?.starters;if(Z){let ne=Ma(Br(o),c),pe=Z.placement??"auto",Ce=pe==="auto"?ne?"welcome":"composer":pe;if(Ce==="welcome"&&!ne){TE(),Ps.forEach(f);return}let He=Ce==="welcome"?mb:hr;y(He),He.render(Z.items??o.suggestionChips,_,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:Z.variant??"card",behavior:Z.behavior??"send",overflow:Z.overflow??"wrap",maxItems:Z.maxItems??4,config:o,plugins:a,submitPrompt:Nd});return}y(hr),hr.render(o.suggestionChips,_,Ae,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Nd})},Ab=()=>{Hs&&(Hs=null,Pi())},EE=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){Ab();return}let f=_?_.getMessages():[];Hs=c,gb=!0,hb=bb(f),yb=vb(f),Pi(f)},lo=!1,cn=qS(),Ii=new Map,Rs=new Map,Kr=new Map,Ws=null,Gr=null;function Bs(){if(!Ws)return;let i=Ws;Ws=null,Gr?.destroy(),Gr=null,cn.delete(i),Le.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),_&&bo(Re,_.getMessages(),Ge)}let Os=0,kE=Mo()!==null,co=pu(),po=0,Yr=null,Yn=!1,Zc=!1,Qr=0,hn=null,Ds=null,Am=!1,Hi=!1,_s=null,Qa=!0,ed=!1,Ri=null,td=!1,Ns=()=>{td=!0,HE()},Mm=null,LE=4,yr=24,PE=80,IE=1e3,br=null,Mb=()=>{t.setAttribute("data-persona-scrollbar",sm()),sm()!=="on-scroll"&&(br!==null&&clearTimeout(br),br=null,ie.removeAttribute("data-persona-scrollbar-visible"))},HE=()=>{sm()==="on-scroll"&&(ie.setAttribute("data-persona-scrollbar-visible",""),br!==null&&clearTimeout(br),br=setTimeout(()=>{br=null,Wr(ie,yr)&&ie.removeAttribute("data-persona-scrollbar-visible")},IE))};Mb(),De.push(()=>{br!==null&&clearTimeout(br)});let Tm=new Map,gt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Yy=()=>gt.active,Ho();let Tb=o.voiceRecognition?.autoResume??!1,vr=i=>{E.emit("voice:state",{active:gt.active,source:i,timestamp:Date.now()})},Bo=()=>{Y(i=>({...i,voiceState:{active:gt.active,timestamp:Date.now(),manuallyDeactivated:gt.manuallyDeactivated}}))},RE=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Sy(H.voiceState),c=!!i.active,f=Number(i.timestamp??0);gt.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-f<PB&&setTimeout(()=>{gt.active||(gt.manuallyDeactivated=!1,no(o.voiceRecognition?.provider)?_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),vr("restore"),_.isVoiceActive()&&Xi()}):$d("restore"))},1e3)},WE=()=>_?jT(_.getMessages()).filter(i=>!i.__skipPersist):[],nd=null,Eb=(i,c)=>{typeof console<"u"&&console.error(i,c)},od=(i,c)=>{let f=()=>{try{let q=i();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(te=>{Eb(c,te)})}catch(q){return Eb(c,q),null}},y=nd,x=y?y.then(()=>f()??void 0):f();if(!x)return;let k=x.finally(()=>{nd===k&&(nd=null)});nd=k};function Wi(i){if(!R?.save)return;let c=i?jT(i):_?WE():[],f=V&&_?.getResumableHandle();f&&(H={...H,durableResume:{executionId:f.executionId,after:f.lastEventId}});let y={messages:c,metadata:H,artifacts:yo.artifacts,selectedArtifactId:yo.selectedId,...Fs?{draft:Fs}:{}};od(()=>R.save(y),"[AgentWidget] Failed to persist state:")}let Fs,rd=()=>!R?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Xa=Vx({write:()=>{if(!rd())return;let i=ze.getState(),c=Nx({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Sf(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Fs)&&(Fs=c,Wi())}});function kb(){rd()&&Xa.schedule()}function Em(){Xa.flush()}function Lb(i){if(!rd())return;let c=Fx(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(f=>f.id),modelIds:(o.composer?.models??[]).map(f=>f.id),modes:o.composer?.modes??[]});c&&(Fs=i,Ae&&!Ae.value&&(Ae.value=c.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ko()),c.selectedModelId&&(ze.setSelectedModelId(c.selectedModelId),Ur?.repaint()),$c(c.activeModeIds??[]),c.quote&&Go(c.quote),Xa.cancel())}function sd(){Xa.cancel(),Fs&&(Fs=void 0,rd()&&Wi())}let Bi=null,Pb=()=>it.querySelector("#persona-scroll-container")||ie,Oi=()=>{Bi!==null&&(cancelAnimationFrame(Bi),Bi=null),Yn=!1},Ib=()=>{Yr!==null&&(cancelAnimationFrame(Yr),Yr=null),Zc=!1,Oi()},BE=()=>lo&&Lm()&&(ao()!=="anchor-top"||Hy()),km=()=>{let i=Fa()||"Jump to latest",c=BE();ln.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Qr>0?(As.textContent=String(Qr),As.style.display="",ln.setAttribute("aria-label",`${i} (${Qr} new)`)):(As.textContent="",As.style.display="none",ln.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Hb=()=>{Qr!==0&&(Qr=0,km())},OE=()=>{let i=hn?.spacerHeight??0;return i<=0?Wr(ie,yr):cd(i)-ie.scrollTop-ie.clientHeight<=yr},Lm=()=>zr()?!co.isFollowing():!OE(),Pm=()=>!!_&&_.getMessages().length>0,yn=()=>{if(!dE()||Wt()){ln.parentNode&&ln.remove(),ln.style.display="none";return}ln.parentNode!==Le&&Le.appendChild(ln),Ms();let c=cr(ie)>0&&Lm()&&Pm();c?km():Hb(),ln.style.display=c?"":"none"},Ja=()=>{co.pause()&&(Ib(),yn())},Qn=()=>{co.resume(),Hb(),yn()},Xr=(i=!1)=>{zr()&&Pm()&&co.isFollowing()&&(!i&&!lo||(Yr!==null&&(cancelAnimationFrame(Yr),Yr=null),Zc=!0,Yr=requestAnimationFrame(()=>{Yr=null,Zc=!1,co.isFollowing()&&DE(Pb(),i?220:140)})))},Rb=(i,c,f,y=()=>!0)=>{let x=i.scrollTop,k=c(),q=k-x;if(Oi(),Math.abs(q)<1){Yn=!0,i.scrollTop=k,po=i.scrollTop,Yn=!1;return}let te=performance.now();Yn=!0;let Z=pe=>1-Math.pow(1-pe,3),ne=pe=>{if(!y()){Oi();return}let Ce=c();Ce!==k&&(k=Ce,q=k-x);let He=pe-te,wt=Math.min(He/f,1),Ot=Z(wt),Ft=x+q*Ot;i.scrollTop=Ft,po=i.scrollTop,wt<1?Bi=requestAnimationFrame(ne):(i.scrollTop=k,po=i.scrollTop,Bi=null,Yn=!1)};Bi=requestAnimationFrame(ne)},DE=(i,c=500)=>{let f=cr(i)-i.scrollTop;if(Math.abs(f)<1){po=i.scrollTop;return}if(Math.abs(f)>=PE){Oi(),Yn=!0,i.scrollTop=cr(i),po=i.scrollTop,Yn=!1;return}Rb(i,()=>cr(i),c,()=>co.isFollowing())},id=()=>{if(!Pm()){yn();return}let i=Pb();Yn=!0,i.scrollTop=cr(i),po=i.scrollTop,Yn=!1,yn()},Vs=i=>{let c=0,f=i;for(;f&&f!==ie;)c+=f.offsetTop,f=f.offsetParent;return c},_E=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},ad=()=>QS(_E(),ie),Im=()=>{if(pE()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(k=>k.role==="user");if(!c)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ie.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let x=Math.min(Math.max(0,Vs(y)-Va()),cr(ie));return Yn=!0,ie.scrollTop=x,po=ie.scrollTop,Yn=!1,ao()==="follow"&&!Wr(ie,yr)&&co.pause(),yn(),!0},ld=i=>{let c=Math.max(0,Math.round(i));ho.style.height=`${c}px`,ho.style.display=c>0?"":"none",hn&&(hn.spacerHeight=Math.max(0,i))},cd=i=>{let c=parseFloat(getComputedStyle(ie).paddingBottom)||0,f=0;for(let x of Array.from(ie.children)){if(x===ho||x.offsetHeight===0)continue;let k=Vs(x)+x.offsetHeight;k>f&&(f=k)}let y=ie.scrollHeight-i;return f>0?Math.min(f+c,y):y},NE=()=>{if(!hn||hn.spacerHeight<=0)return;let i=cd(hn.spacerHeight),c=Math.max(0,Math.round(ie.scrollTop)+ie.clientHeight-i+yr);c<hn.spacerHeight&&(ld(c),yn())},Oo=()=>{Ds!==null&&(cancelAnimationFrame(Ds),Ds=null),Oi(),hn=null,ho.style.height="0px",ho.style.display="none"},Wb=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Hm=i=>ie.querySelector(`[data-message-id="${Wb(i)}"]`),Bb=i=>{Ds!==null&&cancelAnimationFrame(Ds),Ds=requestAnimationFrame(()=>{Ds=null;let c=Wb(i),f=ie.querySelector(`[data-message-id="${c}"]`);if(!f)return;let y=Vs(f),x=hn?.spacerHeight??0,k=cd(x),{targetScrollTop:q,spacerHeight:te}=Xg({anchorOffsetTop:y,topOffset:Va(),viewportHeight:ie.clientHeight,contentHeight:k,slack:yr});hn={initialSpacerHeight:te,contentHeightAtAnchor:k,spacerHeight:te},ld(te),Rb(ie,()=>f.isConnected?Math.max(0,Vs(f)-Va()):q,220)})},Xn=()=>{if(ao()!=="anchor-top"||!hn||!Ri)return;let i=Hm(Ri);if(!i)return;Oi();let c=hn.spacerHeight,f=cd(c),{targetScrollTop:y,spacerHeight:x}=Xg({anchorOffsetTop:Vs(i),topOffset:Va(),viewportHeight:ie.clientHeight,contentHeight:f,slack:yr});hn={initialSpacerHeight:x,contentHeightAtAnchor:f,spacerHeight:x},ld(x),Yn=!0,ie.scrollTop=y,po=ie.scrollTop,Yn=!1,yn()},FE=()=>{if(zr()){if(!co.isFollowing()||Wr(ie,1))return;Xr(!lo);return}if(hn&&hn.initialSpacerHeight>0){let i=ie.scrollHeight-hn.spacerHeight,c=XS({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:i});c!==hn.spacerHeight&&ld(c)}yn()},VE=i=>{let c=ao();c==="follow"?(Qn(),Xr(!0)):c==="anchor-top"&&(Qa=!1,ed=!0,td=!1,Ri=i,Bb(i))},$E=()=>{if(ao()==="anchor-top"){if(ed){Qa=!1;return}Qa=!0,Oo(),Qn(),Xr(!0)}},zE=96,UE=i=>{if(_s===null)return!0;let c=Hm(_s),f=Hm(i);if(!c||!f)return!0;let y=Vs(f)-Vs(c);return Va()+y>ie.clientHeight-zE},qE=i=>{if(ao()!=="anchor-top"||!ed||td||ad())return;let c=_s===null;for(let f of i){if(!c){f.id===_s&&(c=!0);continue}if(YS(f)){if(f.id===Ri||!UE(f.id))return;Ri=f.id,Bb(f.id);return}}},jE=i=>{let c=new Map;i.forEach(f=>{let y=Tm.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(E.emit("assistant:message",f),!Hi&&(ao()!=="anchor-top"||Hy())&&Lm()&&(Qr+=1,km(),yn(),_c(Qr===1?"1 new message below.":`${Qr} new messages below.`))),f.role==="assistant"&&y?.streaming&&f.streaming===!1&&E.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&E.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):E.emit("approval:requested",{approval:f.approval,message:f}))}),Tm.clear(),c.forEach((f,y)=>{Tm.set(y,f)})},Za=(i,c)=>{let f=c==="user"?"user":"assistant",y=o.layout?.messages?.[f],x=y?.width??"content",k=y?.maxWidth??(x==="full"?"100%":void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${x}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",x),k?i.style.setProperty("--persona-message-row-max-width",k):i.style.removeProperty("--persona-message-row-max-width")},Cr=(i,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),Za(f,c),f},KE=(i,c,f)=>{let y=document.createElement("div"),k=(()=>{let U=a.find(ct=>ct.renderLoadingIndicator);if(U?.renderLoadingIndicator)return U.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),q=(U,ct)=>ct==null?!1:typeof ct=="string"?(U.textContent=ct,!0):(U.appendChild(ct),!0),te=new Set,Z=new Map,ne=new Set,pe=a.some(U=>U.renderAskUserQuestion),Ce=[],He=[],wt=o.enableComponentStreaming!==!1,Ot=o.approval!==!1,Ft=[],xn=o.messageActions,pn=xn?.showRegenerate===!0&&xn.enabled!==!1&&Bt.current?.isStreaming()!==!0?Ww(c):null,Jt=xn?.showEdit===!0&&xn.enabled!==!1,Bn=xn?.showQuote===!0&&xn.enabled!==!1,Mt=null,On=o.features?.reasoningDisplay?.completedVisibility,or=U=>On==="removed"?!0:On==="removed-when-short"?iw(U,o.features?.reasoningDisplay?.shortThinkThreshold):!1,kr=o.features?.toolCallDisplay?.completedVisibility==="removed",Do=U=>U.variant==="reasoning"&&U.reasoning?.status==="complete"?or(U.reasoning):kr&&U.variant==="tool"&&U.toolCall?.status==="complete";if(c.forEach(U=>{if(Do(U))return;if(te.add(U.id),Z.set(U.id,U.role),Ws===U.id&&Gr){let Ue=Cr(U.id,U.role);Ue.setAttribute("data-persona-message-edit-stub","true"),Ue.setAttribute("data-preserve-runtime","true"),y.appendChild(Ue),Mt={messageId:U.id,element:Gr.element};return}let ct=pe&&ni(U),qe=Ot&&U.variant==="approval"&&!!U.approval,xe=!ct&&U.role==="assistant"&&!U.variant&&wt&&xy(U);!qe&&Kr.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Kr.delete(U.id)),!xe&&Rs.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Rs.delete(U.id));let Zt=ni(U)?`:${U.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${U.agentMetadata?.askUserQuestionAnswers?Object.keys(U.agentMetadata.askUserQuestionAnswers).length:0}`:"",un={canRegenerate:pn===U.id,canEdit:Jt&&ng(U),canQuote:Bn&&!U.variant&&(U.content?.trim().length??0)>0},Pn=`${un.canRegenerate?"r":""}${un.canEdit?"e":""}${un.canQuote?"q":""}`,mn=US(U,Os)+Zt+`:${Pn}`,bn=ct||qe||xe?null:jS(cn,U.id,mn);if(bn){y.appendChild(bn.cloneNode(!0)),ni(U)&&U.toolCall?.id&&U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}let en=null,Dn=a.find(Ue=>!!(U.variant==="reasoning"&&Ue.renderReasoning||U.variant==="tool"&&Ue.renderToolCall||!U.variant&&Ue.renderMessage)),tt=o.layout?.messages;if(ni(U)&&U.agentMetadata?.askUserQuestionAnswered===!0){Ii.delete(U.id),i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime");return}if(Pl(U)&&ps(o).enabled)return;if(ni(U)&&o.features?.askUserQuestion?.enabled!==!1){let Ue=a.find(_n=>typeof _n.renderAskUserQuestion=="function");if(Ue&&Bt.current){let _n=Ii.get(U.id),rs=_n!==mn,Zn=null;if(rs){let{payload:Dt,complete:rt}=ia(U),Lr=U.id,on=()=>Bt.current?.getMessages().find(to=>to.id===Lr);Zn=Ue.renderAskUserQuestion({message:U,payload:Dt,complete:rt,resolve:to=>{let Al=on();Al&&Bt.current?.resolveAskUserQuestion(Al,to)},dismiss:()=>{let to=on();to?.agentMetadata?.awaitingLocalTool&&(Bt.current?.markAskUserQuestionResolved(to),Bt.current?.resolveAskUserQuestion(to,"(dismissed)"))},config:o})}let eo=_n!=null;if(rs&&Zn===null&&!eo){U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}let Rt=Cr(U.id,U.role);Rt.setAttribute("data-ask-plugin-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),y.appendChild(Rt),Ce.push({messageId:U.id,fingerprint:mn,bubble:Zn});return}else{U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),sp(U,o,Ze.composerOverlay));return}}else if(qe){let Ue=P();if(!Ue){y.appendChild(Cr(U.id,U.role));return}let _n=a.find(Rt=>typeof Rt.renderApproval=="function")??h,Zn=Kr.get(U.id)!==mn,eo=null;if(Zn&&_n?.renderApproval){let Rt=U.id,Dt=(rt,Lr)=>{let on=Bt.current?.getMessages().find(to=>to.id===Rt);on?.approval&&(on.approval.toolType==="webmcp"?Bt.current?.resolveWebMcpApproval(on.id,rt):Bt.current?.resolveApproval(on.approval,rt,Lr))};eo=_n.renderApproval({message:U,defaultRenderer:()=>Ue.createApprovalBubble(U,o),config:o,approve:rt=>Dt("approved",rt),deny:rt=>Dt("denied",rt)})}if(Zn&&eo===null)i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Kr.delete(U.id),en=Ue.createApprovalBubble(U,o);else{let Rt=Cr(U.id,U.role);Rt.setAttribute("data-approval-plugin-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),y.appendChild(Rt),Ft.push({messageId:U.id,fingerprint:mn,bubble:eo});return}}else if(Dn)if(U.variant==="reasoning"&&U.reasoning&&Dn.renderReasoning){if(!yt)return;en=Dn.renderReasoning({message:U,defaultRenderer:()=>Mh(U,o),config:o})}else if(U.variant==="tool"&&U.toolCall&&Dn.renderToolCall){if(!X)return;en=Dn.renderToolCall({message:U,defaultRenderer:()=>Eh(U,o),config:o})}else Dn.renderMessage&&(en=Dn.renderMessage({message:U,defaultRenderer:()=>{let Ue=fh(U,f,tt,o.messageActions,St,{loadingIndicatorRenderer:k,widgetConfig:o,actionEligibility:un});return U.role!=="user"&&O(Ue,U,o,_),Ue},config:o}));if(!en&&xe){let Ue=zT(U);if(Ue){let _n=Rs.get(U.id),rs=_n!==mn,Zn=o.wrapComponentDirectiveInBubble!==!1&&zo.getOptions(Ue.component)?.bubbleChrome!==!1,eo=null;if(rs){let Rt=VT(Ue,{config:o,message:U,transform:f});if(Rt&&Ue.component==="PersonaArtifactInline"){let Dt=Rt.hasAttribute("data-artifact-inline")?Rt:Rt.querySelector("[data-artifact-inline]"),rt=Dt?.getAttribute("data-artifact-inline")??"",Lr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(rt):rt,on=rt?i.querySelector(`#wrapper-${U.id}`)?.querySelector(`[data-artifact-inline="${Lr}"]`)??null:null;Dt&&on&&on!==Dt&&Dr()?.hasLiveInlineArtifactBlock(on)&&(Dt===Rt?Rt=on:Dt.replaceWith(on))}if(Rt)if(Zn){let Dt=document.createElement("div");if(Dt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Dt.id=`bubble-${U.id}`,Dt.setAttribute("data-message-id",U.id),U.content&&U.content.trim()){let rt=document.createElement("div");rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",rt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Dt.appendChild(rt)}Dt.appendChild(Rt),eo=Dt}else{let Dt=document.createElement("div");if(Dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Dt.id=`bubble-${U.id}`,Dt.setAttribute("data-message-id",U.id),Dt.setAttribute("data-persona-component-directive","true"),U.content&&U.content.trim()){let rt=document.createElement("div");rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",rt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Dt.appendChild(rt)}Dt.appendChild(Rt),eo=Dt}}if(eo||_n!=null){let Rt=Cr(U.id,U.role);Rt.setAttribute("data-component-directive-stub","true"),Rt.setAttribute("data-preserve-runtime","true"),y.appendChild(Rt),He.push({messageId:U.id,fingerprint:mn,bubble:eo});return}}}if(!en)if(U.variant==="reasoning"&&U.reasoning){if(!yt)return;en=Mh(U,o)}else if(U.variant==="tool"&&U.toolCall){if(!X)return;en=Eh(U,o)}else if(U.variant==="approval"&&U.approval){if(o.approval===!1)return;let Ue=P();if(!Ue)return;en=Ue.createApprovalBubble(U,o)}else{let Ue=o.layout?.messages;Ue?.renderUserMessage&&U.role==="user"?en=Ue.renderUserMessage({message:U,config:o,streaming:!!U.streaming}):Ue?.renderAssistantMessage&&U.role==="assistant"?en=Ue.renderAssistantMessage({message:U,config:o,streaming:!!U.streaming}):en=fh(U,f,Ue,o.messageActions,St,{loadingIndicatorRenderer:k,widgetConfig:o,actionEligibility:un}),U.role!=="user"&&en&&O(en,U,o,_)}let st=Cr(U.id,U.role);st.appendChild(en),KS(cn,U.id,mn,st),y.appendChild(st)}),Ze.composerOverlay&&Ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ct=>{let qe=ct.getAttribute("data-persona-ask-sheet-for");qe&&!ne.has(qe)&&la(Ze.composerOverlay,qe)}),o.features?.toolCallDisplay?.grouped){let U=[],ct=[],qe=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(xe=>{if(xe.variant==="tool"&&xe.toolCall&&X){if(kr&&xe.toolCall.status==="complete")return;ct.push(xe);return}xe.variant==="reasoning"&&(!yt||xe.reasoning?.status==="complete"&&or(xe.reasoning))||((ct.length>1||qe&&ct.length>0)&&U.push(ct),ct=[])}),(ct.length>1||qe&&ct.length>0)&&U.push(ct),U.forEach(xe=>{let Zt=xe.map(tt=>Array.from(y.children).find(st=>st instanceof HTMLElement&&st.getAttribute("data-wrapper-id")===tt.id)).filter(tt=>!!tt);if(Zt.length<(qe?1:2))return;let un=Cr(`tool-group-${xe[0].id}`,"assistant");un.setAttribute("data-persona-tool-group-row","true");let Pn=document.createElement("div");Pn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Pn.setAttribute("data-persona-tool-group","true");let mn=document.createElement("div");mn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mn.id=`tool-group-summary-${xe[0].id}`;let bn=`Called ${xe.length} ${xe.length===1?"tool":"tools"}`,en=o.toolCall?.renderGroupedSummary?.({messages:xe,toolCalls:xe.map(tt=>tt.toolCall).filter(tt=>!!tt),defaultSummary:bn,config:o});q(mn,en)||(mn.textContent=bn);let Dn=document.createElement("div");Dn.className="persona-tool-group-stack persona-flex persona-flex-col",Dn.id=`tool-group-stack-${xe[0].id}`,Dn.setAttribute("data-persona-tool-group-stack","true"),Pn.appendChild(mn),qe||Pn.appendChild(Dn),un.appendChild(Pn),Zt[0].before(un),Zt.forEach((tt,st)=>{if(qe){tt.remove();return}tt.style.setProperty("--persona-message-row-max-width","100%");let Ue=document.createElement("div");Ue.className="persona-tool-group-item persona-relative",Ue.setAttribute("data-persona-tool-group-item","true"),st<Zt.length-1&&Ue.setAttribute("data-persona-tool-group-connector","true"),Ue.appendChild(tt),Dn.appendChild(Ue)})})}GS(cn,te);let Sl=U=>U.variant==="tool"&&!X||U.variant==="reasoning"&&!yt||Do(U),ei=c.some(U=>U.role==="assistant"&&U.streaming&&!Sl(U)),_o=c.length-1;for(;_o>=0&&Sl(c[_o]);)_o--;let Ln=_o>=0?c[_o]:void 0,No=_o<c.length-1,Zi=Ln?.role==="assistant"&&!Ln.streaming&&Ln.variant!=="approval"&&!No;if(lo&&c.some(U=>U.role==="user")&&!ei&&!Zi){let U={config:o,streaming:!0,location:"standalone",defaultRenderer:hc},ct=a.find(xe=>xe.renderLoadingIndicator),qe=null;if(ct?.renderLoadingIndicator&&(qe=ct.renderLoadingIndicator(U)),qe===null&&o.loadingIndicator?.render&&(qe=o.loadingIndicator.render(U)),qe===null&&(qe=hc()),qe){let xe=document.createElement("div"),Zt=o.loadingIndicator?.showBubble!==!1,un=o.layout?.messages?.layout??"bubble";xe.className=Zt?yc("assistant",un).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),xe.setAttribute("data-typing-indicator","true"),Zt&&(xe.style.color="var(--persona-message-assistant-text, var(--persona-text))",un!=="flat"&&(xe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",xe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),xe.appendChild(qe);let Pn=Cr("typing-indicator","assistant");Pn.appendChild(xe),y.appendChild(Pn)}}if(!lo&&c.length>0){let U=c[c.length-1],ct={config:o,lastMessage:U,messageCount:c.length},qe=a.find(Zt=>Zt.renderIdleIndicator),xe=null;if(qe?.renderIdleIndicator&&(xe=qe.renderIdleIndicator(ct)),xe===null&&o.loadingIndicator?.renderIdle&&(xe=o.loadingIndicator.renderIdle(ct)),xe){let Zt=document.createElement("div"),un=o.loadingIndicator?.showBubble!==!1;Zt.className=un?["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(" "),Zt.setAttribute("data-idle-indicator","true"),Zt.appendChild(xe);let Pn=Cr("idle-indicator","assistant");Pn.appendChild(Zt),y.appendChild(Pn)}}if(kC(y),du(i,y),Vf(i),Mt){let{messageId:U,element:ct}=Mt,qe=i.querySelector(`#wrapper-${U}`);qe&&ct.parentElement!==qe&&(Za(qe,Z.get(U)??"user"),qe.replaceChildren(ct))}if(Ce.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of Ce){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Ii.set(U,ct)))}if(Ii.size>0)for(let U of Ii.keys())te.has(U)||Ii.delete(U);if(He.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of He){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Rs.set(U,ct)))}if(Rs.size>0)for(let U of Rs.keys())te.has(U)||Rs.delete(U);if(Ft.length>0)for(let{messageId:U,fingerprint:ct,bubble:qe}of Ft){let xe=i.querySelector(`#wrapper-${U}`);xe&&(Za(xe,Z.get(U)??"assistant"),qe!==null&&(xe.replaceChildren(qe),xe.setAttribute("data-bubble-fp",ct),Kr.set(U,ct)))}if(Kr.size>0)for(let U of Kr.keys())te.has(U)||Kr.delete(U)},Rm=!1,dd=()=>{Rm||(Rm=!0,CC().catch(()=>{Rm=!1}))},bo=(i,c,f)=>{c.length>0&&dd(),KE(i,c,f),tb()},el=null,GE=()=>{if(el)return;let i=f=>{let y=f.composedPath();y.includes(it)||Kt&&y.includes(Kt)||Nt(!1,"user")};el=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Ob=()=>{if(!el)return;(t.ownerDocument??document).removeEventListener("pointerdown",el,!0),el=null};De.push(()=>Ob());let tl=null,YE=()=>{if(tl)return;let i=f=>{f.key==="Escape"&&(f.isComposing||Nt(!1,"user"))};tl=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},Db=()=>{if(!tl)return;(t.ownerDocument??document).removeEventListener("keydown",tl,!0),tl=null};De.push(()=>Db());let nl=!1,_b=new Set,QE=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Di=()=>{if(!Ee())return;let i=Ze.peekBanner,c=Ze.peekTextNode;if(!i||!c)return;if(Pe){i.classList.remove("persona-pill-peek--visible");return}let f=_?.getMessages()??[],y;for(let pn=f.length-1;pn>=0;pn--){let Jt=f[pn];if(Jt.role==="assistant"&&Jt.content){y=Jt;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let x=y.content,k=!!y.streaming,q=QE(),te=fu(q),Z=te.type!=="none"?Sm(te.type,q?.plugins):null,ne=Z?.isAnimating?.(y)===!0,pe=Z!==null&&(k||ne);pe&&Z&&!_b.has(Z.name)&&(ic(Z,t),_b.add(Z.name));let Ce=pe&&Z?.containerClass?Z.containerClass:null,He=c.dataset.personaPeekStreamClass??null;He&&He!==Ce&&(c.classList.remove(He),delete c.dataset.personaPeekStreamClass),Ce&&He!==Ce&&(c.classList.add(Ce),c.dataset.personaPeekStreamClass=Ce),pe?(c.style.setProperty("--persona-stream-step",`${te.speed}ms`),c.style.setProperty("--persona-stream-duration",`${te.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let wt=pe?gu(x,te.buffer,Z,y,k):x;if(pe&&te.placeholder==="skeleton"&&k&&(!wt||!wt.trim())){let pn=document.createElement("div"),Jt=sc();Jt.classList.add("persona-pill-peek__skeleton"),pn.appendChild(Jt),du(c,pn)}else{let pn=Math.max(0,wt.length-100),Jt=wt.length>100?wt.slice(-100):wt,Bn=Pr(Jt);if(!pe||!Z){let Mt=wt.length>100?`\u2026${Jt}`:Jt;c.textContent!==Mt&&(c.textContent=Mt)}else{let Mt=Bn;(Z.wrap==="char"||Z.wrap==="word")&&(Mt=rc(Bn,Z.wrap,`peek-${y.id}`,{skipTags:Z.skipTags,startIndex:pn}));let On=document.createElement("div");if(On.innerHTML=Mt,Z.useCaret&&Jt.length>0){let or=hu(),kr=On.querySelectorAll(".persona-stream-char, .persona-stream-word"),Do=kr[kr.length-1];Do?.parentNode?Do.parentNode.insertBefore(or,Do.nextSibling):On.appendChild(or)}du(c,On),Z.onAfterRender?.({container:c,bubble:i,messageId:y.id,message:y,speed:te.speed,duration:te.duration})}}let xn=lo||nl;i.classList.toggle("persona-pill-peek--visible",xn)};if(Ee()){let i=Ze.peekBanner;if(i){let y=x=>{x.preventDefault(),x.stopPropagation(),Nt(!0,"user")};i.addEventListener("pointerdown",y),De.push(()=>{i.removeEventListener("pointerdown",y)})}let c=()=>{nl||(nl=!0,Di())},f=()=>{nl&&(nl=!1,Di())};_e.addEventListener("pointerenter",c),_e.addEventListener("pointerleave",f),De.push(()=>{_e.removeEventListener("pointerenter",c),_e.removeEventListener("pointerleave",f)}),Kt&&(Kt.addEventListener("pointerenter",c),Kt.addEventListener("pointerleave",f),De.push(()=>{Kt.removeEventListener("pointerenter",c),Kt.removeEventListener("pointerleave",f)}))}let XE=i=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",y=c.bottomOffset??"16px",x=c.collapsedMaxWidth,k=c.expandedMaxWidth??"880px",q=c.expandedTopOffset??"5vh",te=c.modalMaxWidth??"880px",Z=c.modalMaxHeight??"min(90vh, 800px)",ne="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Ce=it.style;if(Ce.left="",Ce.right="",Ce.top="",Ce.bottom="",Ce.transform="",Ce.width="",Ce.maxWidth="",Ce.height="",Ce.maxHeight="",Kt){let He=Kt.style;He.bottom=y,He.width=x??""}if(i&&f!=="fullscreen"){if(f==="modal"){Ce.top="50%",Ce.left="50%",Ce.transform="translate(-50%, -50%)",Ce.bottom="auto",Ce.right="auto",Ce.width=te,Ce.maxWidth=ne,Ce.maxHeight=Z,Ce.height=Z;return}Ce.left="50%",Ce.transform="translateX(-50%)",Ce.bottom=`calc(${y} + ${pe})`,Ce.top=q,Ce.width=k,Ce.maxWidth=ne}},ol=()=>{if(Pe&&dd(),!Ne())return;if(Ee()){let ne=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=Pe?"expanded":"collapsed";it.dataset.state=pe,it.dataset.expandedSize=ne,Kt&&(Kt.dataset.state=pe,Kt.dataset.expandedSize=ne),it.style.removeProperty("display"),it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),XE(Pe),Le.style.display=Pe?"flex":"none",Es(),Pe?(GE(),YE()):(Ob(),Db()),Di();return}let i=rn(o),c=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,x=c.innerWidth<=f,k=y&&x&&ce,q=Lo(o).reveal;Pe?(it.style.removeProperty("display"),it.style.display=i?"flex":"",it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-95","persona-opacity-0"),_e.classList.add("persona-scale-100","persona-opacity-100"),Qt?(Qt.setPanelOpen(!0),Qt.element.style.display="none"):Fn&&(Fn.style.display="none")):(i?i&&(q==="overlay"||q==="push")&&!k?(it.style.removeProperty("display"),it.style.display="flex",it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(it.style.setProperty("display","none","important"),it.classList.remove("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(it.style.display="",it.classList.add("persona-pointer-events-none","persona-opacity-0"),_e.classList.remove("persona-scale-100","persona-opacity-100"),_e.classList.add("persona-scale-95","persona-opacity-0")),Qt?(Qt.setPanelOpen(!1),Qt.element.style.display=i?"none":""):Fn&&(Fn.style.display=i?"none":""))},Nt=(i,c="user")=>{if(!Ne()||Pe===i)return;let f=Pe;Pe=i,ol();let y=(()=>{let k=o.launcher?.sidebarMode??!1,q=t.ownerDocument.defaultView??window,te=o.launcher?.mobileFullscreen??!0,Z=o.launcher?.mobileBreakpoint??640,ne=q.innerWidth<=Z,pe=rn(o)&&te&&ne,Ce=Ee()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||te&&ne&&ce||pe||Ce})();if(Pe&&y){if(!Xo){let k=t.getRootNode(),q=k instanceof ShadowRoot?k.host:t.closest(".persona-host");q&&(Xo=rh(q,o.launcher?.zIndex??Hn))}Jo||(Jo=sh(t.ownerDocument))}else Pe||(Xo?.(),Xo=null,Jo?.(),Jo=null);Pe&&(Cl(),Im()||(ao()==="follow"?Xr(!0):id()));let x={open:Pe,source:c,timestamp:Date.now()};Pe&&!f?E.emit("widget:opened",x):!Pe&&f&&E.emit("widget:closed",x),E.emit("widget:state",{open:Pe,launcherEnabled:ce,voiceActive:gt.active,streaming:_.isStreaming()})},Jr={inputDisabled:!1,sendDisabled:!1},Zo=()=>Jr.inputDisabled,Wm=()=>no(o.voiceRecognition?.provider)&&!!_&&(_.isBargeInActive()||["listening","processing","speaking"].includes(_.getVoiceStatus())),$s=()=>Jr.inputDisabled||Jr.sendDisabled,JE=()=>(Jr.inputDisabled?Jr.inputReason:void 0)??(Jr.sendDisabled?Jr.sendReason:void 0);function Bm(){if(!Ve)return;if(ze.getState().phase==="streaming"){Ve.disabled=!1;return}let i=At?!At.isReady():!1;Ve.disabled=$s()||i}function pd(){if(!jo)return;let i=ze.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;jo.toggleAttribute("data-persona-send-hidden",c)}function ZE(){let i=JE();if(Ee()){let c=Wn??We;i?c.setAttribute("title",i):c.removeAttribute("title"),We.toggleAttribute(Oa,!!i);return}if(i){bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.setAttribute(Oa,""),bt.textContent=i;return}if(bt.hasAttribute(Oa)&&(bt.removeAttribute("role"),bt.removeAttribute("aria-live"),bt.removeAttribute(Oa),p)){let c=_.getStatus();Rn(bt,sn(c),o.statusIndicator??{},c)}}function Om(){let i=wg(o.composer?.inputDisabled),c=wg(o.composer?.sendDisabled);Jr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},ze.setInputDisabled(i.disabled),ze.setSendDisabled(c.disabled);let f=ze.getState().phase==="streaming",y=i.disabled,x=f||y;Ae&&(Ae instanceof HTMLTextAreaElement?Ae.disabled=y:Ae.setAttribute("contenteditable",y?"false":"true"),Ae.setAttribute("aria-disabled",y?"true":"false")),Gt&&(Gt.disabled=y),zt&&(zt.disabled=y);for(let k of nn?.affordanceButtons??[])k.querySelectorAll("button").forEach(q=>{q.disabled=y});fe&&(fe.disabled=y||f&&!Wm()),Ps.forEach(k=>{k.elements.forEach(q=>{q.toggleAttribute("data-disabled",x),q instanceof HTMLButtonElement||q.setAttribute("aria-disabled",x?"true":"false")}),k.buttons.forEach(q=>{q.disabled=x})}),Vm.forEach(k=>{k.toggleAttribute("data-disabled",x),k instanceof HTMLButtonElement?k.disabled=x:k.setAttribute("aria-disabled",x?"true":"false"),k.querySelectorAll("button").forEach(q=>{q.disabled=x})}),We.dataset.personaComposerStreaming=f?"true":"false",We.dataset.personaComposerInputDisabled=y?"true":"false",We.dataset.personaComposerSendDisabled=$s()?"true":"false",We.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=f)}),Bm(),ZE()}let rl=i=>{ze.setStreaming(i),Py(i?"stop":"send"),Om()},zs=()=>{gt.active||Ae&&Ae.focus()};E.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>zs(),200)});let Us=null,sl=!1,Dm=!an.hidden,Zr=null,_m=!w,ud=null;De.push(()=>{ud?.cancel(),ud=null});let ek=i=>{let c=NA(i);if(c===Nc)return;Nc=c,t.setAttribute("data-persona-conversation-state",c);let f=am();Vc(),_m&&(ud?.cancel(),ud=DA(We,c==="active"?f:am(),c==="active"?"drop":"rise")),Xn()},Nb=null,Fb,Vb=null,_i=null,Nm=!1,il=i=>{let c=Br(o),f=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(f!==Nb||c.icon!==Fb)&&(Nb=f,Fb=c.icon,Au({host:an,iconHolder:_a,kicker:Na,title:om,subtitle:rm,starterSuggestions:wi},c));let y=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;y!==Vb&&(Vb=y,Mu(kn,c.message,o));let x=i??(_?_.getMessages():o.initialMessages);ek(x);let k=sl,q=!k&&Ma(c,x),te=q!==Dm;if(Dm=q,_i){Zr?.cancel(),Zr=null,k!==Nm&&(Nm=k,k?yh(ie,an,null):hh(ie,an,_i)),Aa(ie,an,!k);return}if(te&&!q&&!k&&c.dismiss==="on-first-message"&&_m){Zr=OA(an,ne=>{Zr===ne&&(Zr=null),!Dm&&!_i&&(Aa(ie,an,!1),Xn()),ne?.cancel()});return}if(Zr){if(!q&&!k)return;Zr.cancel(),Zr=null}let Z=!an.hidden;Aa(ie,an,q),!q&&Z&&Xn()},Fm=[],Vm=[],$m=!1,$b=null,zb,Ub=()=>{Vm.length=0;let i=Fm.splice(0,Fm.length);for(let c of i)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};De.push(Ub);let tk=(i,c)=>{let f=ah(i,c);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let y=o.suggestions?.starters,x=lh({item:{...f,behavior:f.behavior??y?.behavior??"send"},index:c,surface:"starter",source:"config",variant:y?.variant??"card",streaming:p?_.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:_,getTextarea:()=>Ae,eventTarget:an,submitPrompt:Nd});return Vm.push(x),x},zm=()=>{if($m)return;$m=!0;let i=Br(o);$b=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,zb=i.icon;try{Ub(),yh(ie,an,_i),_i=null,Nm=!1;let c=_?_.getMessages():o.initialMessages,f=Ma(i,c),y=0,x=null;for(let k of a)if(k.renderWelcome&&(x=k.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>an,sendMessage:q=>{if(!_||_.isStreaming())return;let te=q.trim();te&&_.sendMessage(te)},requestRender:()=>zm(),renderStarter:q=>tk(q,y++),storage:u(k.id),onCleanup:q=>{Fm.push(q)}}),x))break;x&&x!==an&&(_i=x,hh(ie,an,x))}finally{$m=!1}il()},nk=()=>{let i=Br(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===$b&&i.icon===zb||zm()},md=()=>{il(),Ti||(Ae.placeholder=Wx(ze.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(Ve.textContent=o.copy?.sendButtonLabel??"Send")),Ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},ok=!!o.setStoredConversationId,Ni=i=>Y(c=>{let f={...c};return delete f[i],f}),fd=i=>{let c=H[i];return typeof c=="string"?c:null},qb=()=>{let i=H.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>fd("sessionId"),setStoredSessionId:i=>{Y(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ni("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>fd("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{Y(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ni("conversationId"))});let jb=()=>o.clientToken??null,Kb=i=>bT(i,Q(),o.persistState===!1),Gb=jb(),vo=Gb?Kb(Gb):null,wr={...vo?{visitorStore:vo}:{},historyBootstrapReady:I,getStoredMessageCursor:()=>fd("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){Ni("historyMessageCursor");return}Y(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=H.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:i=>{if(!i){Ni("pendingDisplayProjections");return}Y(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:qb,setStoredResumableHandle:i=>{if(!i){Ni("durableResume");return}Y(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>V&&qb()!==null,...ok?{}:{getStoredConversationRevision:()=>fd("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){Ni("conversationRevision");return}Y(c=>({...c,conversationRevision:i}))}}};if(V){let i=o.onExecutionState,c=t.ownerDocument.defaultView,f=!1,y=()=>f=!0,x=()=>f=!1;c?.addEventListener("pagehide",y),c?.addEventListener("pageshow",x),De.push(()=>{c?.removeEventListener("pagehide",y),c?.removeEventListener("pageshow",x)}),o={...o,reconnectStream:o.reconnectStream??(k=>_.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!f)&&wr.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),i?.(k)}}}let rk=()=>{let i=jb();if(i&&vo?.matches(i,Q(),o.persistState===!1)||!i&&!vo)return;vo?.destroy(),vo=i?Kb(i):null;let c={...wr};vo?c.visitorStore=vo:delete c.visitorStore,wr=c,_.setHistoryInternals(wr)},qs=null,sk=()=>{qs==null&&(qs=setInterval(()=>{let i=Re.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(qs),qs=null;return}let c=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=lp(c-y))})},100))},Um=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((q,te)=>Um(q,c[te]));let f=i,y=c,x=Object.keys(f),k=Object.keys(y);return x.length===k.length&&x.every(q=>Object.prototype.hasOwnProperty.call(y,q)&&Um(f[q],y[q]))},Yb=i=>{let{content:c,rawContent:f,llmContent:y,...x}=i;return x},qm=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!xy(i),ik=(i,c,f)=>{if(i.length!==c.length)return!1;let y=i[f.index],x=c[f.index];return!y||!x||y.id!==f.id||x.id!==f.id?!1:(!Object.is(y.content,x.content)||!Object.is(y.rawContent,x.rawContent)||!Object.is(y.llmContent,x.llmContent))&&qm(y)&&qm(x)&&Um(Yb(y),Yb(x))},jm=null,Fi=null,js=null,xr=null,Km=null,ak=i=>{if(!V)return Wi(i);Km=i,queueMicrotask(()=>{Km===i&&(Km=null,Wi(i))})},gd=i=>{jm=i;let c,f;Fi=null;for(let x=i.length-1;x>=0;x-=1){let k=i[x];if(!c&&k.role==="user"&&(c=k),!f&&k.role==="assistant"&&(f=k),!Fi&&qm(k)&&(Fi={index:x,id:k.id}),c&&f&&Fi)break}bo(Re,i,Ge),Dr()?.updateInlineArtifactBlocks(Re,yo.artifacts,{suppressTransition:lo}),sk(),il(i),Pi(i),Xr(!lo),jE(i),i.length===0&&(Oo(),Qa=!0,ed=!1,Ri=null,td=!1),!Am||Hi?(Am=!0,_s=c?.id??null,Mm=f?.id??null):c&&c.id!==_s?(_s=c.id,VE(c.id)):f&&f.id!==Mm&&$E(),f&&(Mm=f.id),qE(i);let y=gt.lastUserMessageId;c&&c.id!==y&&(gt.lastUserMessageId=c.id,E.emit("user:message",c)),gt.lastUserMessageWasVoice=!!c?.viaVoice,ak(i),Di()},Gm=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null);let i=js;js=null,i&&gd(i)},Qb=()=>{xr!==null&&cancelAnimationFrame(xr),xr=null,js=null},lk=i=>{let c=js??jm;if(lo&&c&&Fi&&ik(c,i,Fi)){js=i,xr===null&&(xr=requestAnimationFrame(()=>{xr=null;let f=js;js=null,f&&gd(f)}));return}if(i.length===0){Qb(),gd(i);return}Gm(),gd(i)};_=new vp(o,{onMessagesChanged(i){lk(i)},onStatusChanged(i){let c=o.statusIndicator??{};Rn(bt,(y=>y==="idle"?c.idleText??fn.idle:y==="connecting"?c.connectingText??fn.connecting:y==="connected"?c.connectedText??fn.connected:y==="error"?c.errorText??fn.error:y==="paused"?c.pausedText??fn.paused:y==="resuming"?c.resumingText??fn.resuming:fn[y])(i),c,i),wn()},onStreamingChanged(i){i||(_?.getMessages().length===0?Qb():Gm()),lo=i,rl(i),wn(),_&&bo(Re,_.getMessages(),Ge),i||(Xr(!0),NE(),xb=!0,_&&Sb(_.getMessages(),ps(o))),yn(),_c(i?"Responding\u2026":"Response complete."),Di()},onVoiceStatusChanged(i){if(E.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!no(o.voiceRecognition?.provider)))switch(i){case"listening":Er(),Xi();break;case"processing":Er(),d0();break;case"speaking":Er(),p0();break;default:i==="idle"&&_.isBargeInActive()?(Er(),Xi(),fe?.setAttribute("aria-label","End voice session")):(gt.active=!1,Er(),vr("system"),Bo());break}},onArtifactsState(i){yo=i,i.artifacts.length===0&&(Ei=!1),Dr()?.updateInlineArtifactBlocks(Re,i.artifacts,{suppressTransition:lo}),Wo(),Wi()},onHistoryStateChanged(i){vn(i)},onHistoryNotice(i){Cn(i)},onReconnect(i){let{executionId:c,lastEventId:f}=i.handle;i.phase==="paused"?E.emit("stream:paused",{executionId:c,after:f}):i.phase==="resuming"?E.emit("stream:resuming",{executionId:c,after:f,attempt:i.attempt??1}):E.emit("stream:resumed",{executionId:c,after:f})}},wr),Bt.current=_,De.push(()=>_.cancel()),De.push(()=>{_.destroy(),vo?.destroy(),vo=null});let Ym=null;if(_.onReadAloudChange((i,c)=>{Zy=i,eb=c,tb();let f=i??Ym;i&&(Ym=i);let y=f?_.getMessages().find(x=>x.id===f)??null:null;E.emit("message:read-aloud",{messageId:f,message:y,state:c,timestamp:Date.now()}),c==="idle"&&(Ym=null)}),p=!0,Am=!0,o.voiceRecognition?.enabled===!0&&no(o.voiceRecognition.provider))try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let ck=720,dk=250,Ct=ly(o.features?.history?.copy),uo=null,Qm=!1,Ht=null,hd=null,yd="conversation",Xm=null,Nn=null,er=null,bd=_.getHistoryState(),Jm=null,al=0,Zm=null,vd=null,Cd=null,ef=`persona-history-${Math.random().toString(36).slice(2,8)}`,tf=()=>o.features?.history?.enabled===!0,tr=()=>tf()&&!!uo&&!Qm,Xb=()=>{let i=_.getStatus();return lo||i==="paused"||i==="resuming"},nf=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",f=uo?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},Vi=()=>hd?.scope??nf(),Jb=()=>_.getClientSession()?.targetId??null,Zb=i=>`${i.state}:${"reason"in i?i.reason:""}`,pk=i=>{let c=Zb(i);c!==Jm&&(Jm=c,E.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},wd=i=>{i&&(mr.textContent="",mr.textContent=i)},ev=null,tv=null,uk=()=>{if(!tf())return null;let i=NT();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(ev!==c&&(ev=c,tv=c()),tv):_.isClientTokenMode()?FT({client:_.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>_.bindActivatedSession(f),getClient:()=>_.getClient()}):null},nv=()=>{vd?.(),vd=null,Cd?.(),Cd=null,Qm=!1,uo=uk();let i={...wr};uo?i.historyProvider=uo:delete i.historyProvider,wr=i,_.setHistoryInternals(wr),uo&&(vd=uo.subscribeAvailability?.(c=>{Qm=!c,c||Jn({restoreFocus:!1}),ts()})??null,Cd=uo.subscribeIdentityStatus(c=>pk(c)),Jm=Zb(uo.getIdentityStatus()))},of=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ce||rn(o)))return"panel";let c=Qo??Le;return(c.getBoundingClientRect().width||c.clientWidth)>=ck?"rail":"panel"},Co=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},xd="data-persona-history-suppressed",mo=null,es=null,Ks=null,ll=null,rf=null,ov="",rv=()=>he===rf?ov:o.layout?.showHeader===!1?"none":"",mk=()=>Se==="panel"&&!!Ks&&ll===Ks.element&&o.layout?.showHeader!==!1&&rv()!=="none",fk=()=>{for(let i of Array.from(he.children))i!==mo&&i.setAttribute(xd,"")},gk=()=>{for(let i of Array.from(Le.querySelectorAll(`[${xd}]`)))i.removeAttribute(xd)},hk=()=>{let i=Ks;if(!i)return;if(Array.from(he.children).some(y=>y!==mo&&!y.hasAttribute(xd))){es&&es!==he&&(es.style.removeProperty("min-height"),es=null);let y=he.offsetHeight;y>0&&(he.style.minHeight=`${y}px`,es=he)}mo||(mo=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==mo&&mo.replaceChildren(f),mo.parentNode!==he&&he.appendChild(mo),fk()},sv=()=>{es&&(es.style.removeProperty("min-height"),es=null),mo&&(Ks?.setHeaderPlacement("inline"),mo.remove(),mo=null,gk())},Sd=null,sf=()=>{if(Sd){if(ie.style.display="none",Co(ie,!0),We.hidden=!0,Co(We,!0),mk()){hk(),he.style.display=rv(),Co(he,!1);return}sv(),he.style.display="none",Co(he,!0)}};Ke=sf;let yk=i=>{let c=ie.style.display,f=We.hidden,y=We,x=he,k=he.style.display;rf=x,ov=k,Sd=()=>{Sd=null,sv(),rf=null,ie.style.display=c,Co(ie,!1),y.hidden=f,Co(y,!1),We!==y&&(We.hidden=!1,Co(We,!1)),x.style.display=k,Co(x,!1),he!==x&&(he.style.display=o.layout?.showHeader===!1?"none":"",Co(he,!1))},We.parentNode?.insertBefore(i,We),sf()},$i=null,Gs=null,cl=null,zi=null,iv=()=>[he,Ze.closeButtonWrapper,Ze.clearChatButtonWrapper,ie,We],bk=52,Ad=()=>o.features?.history?.rail?.collapsible!==!1,Ui=()=>o.features?.history?.rail?.side==="right"?"right":"left",af=200,lf=400,cf=i=>Math.min(lf,Math.max(af,Math.round(i))),vk=()=>o.features?.history?.rail?.resizable===!0,dl,Ck=()=>{if(dl===void 0&&(dl=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Q()}rail-width`));i&&(dl=i)}catch{}return dl},pl=()=>cf(Ck()??o.features?.history?.rail?.width??260),wk=i=>{if(dl=i,o.persistState!==!1)try{window.localStorage.setItem(`${Q()}rail-width`,String(i))}catch{}},Md=()=>Ad()&&o.features?.history?.rail?.collapsedBehavior==="overlay",dn=!1,av=i=>{let c=v("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},xk=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let c=!1,f;return y=>{if(i.render)try{return i.render({collapsed:y})??null}catch(x){return c||(c=!0,console.warn("[persona] history rail brand threw",x)),null}return f===void 0&&(i.iconUrl?f=av(i.iconUrl):f=i.icon?Ie(i.icon,20):null),f?f.cloneNode(!0):null}},Sk=()=>o.features?.history?.rail?.sections?.map(i=>{let c=!1,f=y=>{c||(c=!0,console.warn("[persona] history rail section threw",i.id,y))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(y=>{let x;return{id:y.id,label:y.label,badge:y.badge,iconNode:()=>{if(x!==void 0)return x;try{y.renderIcon?x=y.renderIcon()??null:y.iconUrl?x=av(y.iconUrl):x=y.icon?Ie(y.icon,20):null}catch(k){f(k),x=null}return x},onSelect:()=>{try{y.onSelect()}catch(k){f(k)}}}})}})??[],Ak=i=>{let c=Sk();for(let f of i)c.some(y=>y.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):c.push(f);return c.length?c:void 0},ul=null,lv=()=>`${Q()}rail-collapsed`,df=()=>{if(ul===null&&(ul=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(lv());i&&(ul=i==="1")}catch{}return ul},pf=i=>{if(ul=i,o.persistState!==!1)try{window.localStorage.setItem(lv(),i?"1":"0")}catch{}},ml=()=>Se==="rail"&&Ad()&&!Md()&&df(),uf=()=>{},cv=()=>{if(Md()){uf();return}pf(!df()),Ht?.view.setCollapsed(ml()),ut(),Xn()},mf=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!lu(i)?null:{combo:i,hint:cu(i),aria:tc(i)}},dv=()=>{d.forEach(c=>c()),d=[];let i=mf();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ve&&Se==="rail"&&Ad()||ji(),run:()=>Md()?uf():cv()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${c.id}"]`);f?f.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of a)for(let f of c.shortcuts??[])d.push(l.register({...f,id:`${c.id}:${f.id}`}))};dv();let Mk=300,Td="var(--persona-history-overlay-margin,8px)",wo=null,Sr=null,Ed=0,Ar=null,qi=null,Ys=!1,ff=0,pv=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ji=()=>tr()&&Md()&&(Se??of())==="rail",Tk=()=>ve&&!dn,fl=()=>{qi!==null&&clearTimeout(qi),qi=null},Ek=()=>{by().catch(()=>{})},uv=()=>{fl(),dn&&(qi=setTimeout(()=>{qi=null,!(Ys||!dn)&&(Ar?.contains(document.activeElement)||Jn({restoreFocus:!1}))},Mk))},kk=(i,c)=>{let f=Ar?.getBoundingClientRect();if(!f)return!1;let y=wo?.getBoundingClientRect(),x=y?Math.min(y.top,f.top):f.top;return i>=f.left&&i<=f.right&&c>=x&&c<=f.bottom||!!y&&i>=y.left&&i<=y.right&&c>=y.top&&c<=y.bottom},gf=i=>{dn&&(Ys=kk(i.clientX,i.clientY),Ys?fl():qi===null&&uv())},mv=i=>{ve||!ji()||(dn=!0,hl({invoker:wo,keyboard:i?.keyboard===!0}).then(()=>{ve?!Ys&&document.activeElement!==wo&&Jn():dn=!1}))},fv=()=>{let i=ll?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",dn?Ct.expandLabel:Ct.collapseLabel),i.setAttribute("aria-expanded",dn?"false":"true"))},gv=()=>{pf(!1);let i=Ht;if(!dn||!i){hl({invoker:wo});return}let c=document.activeElement===wo;dn=!1,kd(),i.element.remove(),yf(i.element),fv(),c&&Pd(),Xn(),ts()},Lk=()=>{pf(!0),Jn()};uf=()=>{!ve||dn?gv():Lk()};let Pk=()=>{let i=mf(),c=ai({ariaLabel:Ct.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":ef,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Ys=!0,fl(),!(pv()||Date.now()<ff)&&mv()}),f.addEventListener("mouseleave",()=>{Ys=!1,ff=0,uv()}),f.addEventListener("focus",()=>{ve||Ek()}),f.addEventListener("click",y=>{tr()&&(y.detail!==0&&pv()&&!ve?mv():gv())}),wo=f,Sr=c.wrapper},gl=()=>{if(Sr&&!Sr.isConnected&&(Sr=null,wo=null),!ji()){Sr?.remove(),Sr=null,wo=null;return}wo||Pk();let i=Sr,c=wo;if(!i||!c)return;let f=Ui()!=="right"?he.firstChild:null;(f??he.lastChild)!==i&&he.insertBefore(i,f),i.style.display=Tk()||Ed>0?"none":"",c.setAttribute("aria-label",Ct.expandLabel),c.setAttribute("aria-expanded",ve?"true":"false"),Ar&&ut()},hv=i=>{if(!dn)return;let c=i.target;c instanceof Node&&(Ar?.contains(c)||Sr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Jn({restoreFocus:!1}))};document.addEventListener("pointerdown",hv,!0),De.push(()=>{document.removeEventListener("pointerdown",hv,!0),document.removeEventListener("pointermove",gf),Ki?.(),fl()});let hf=null,Ki=null,yv=16,bv=i=>{wk(cf(i)),ut(),Xn()},Ik=()=>{let i=v("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(af)),i.setAttribute("aria-valuemax",String(lf)),i.addEventListener("pointerdown",c=>{let f=Gs;if(!f||c.button!==0)return;c.preventDefault(),Ki?.();let y=c.clientX,x=f.getBoundingClientRect().width||pl(),k=Ui()==="right"?-1:1,q=x,te=t.ownerDocument;f.style.transition="none";let Z=pe=>{q=cf(x+k*(pe.clientX-y)),f.style.flex=`0 0 ${q}px`,i.setAttribute("aria-valuenow",String(q))},ne=()=>{Ki=null,te.removeEventListener("pointermove",Z),te.removeEventListener("pointerup",ne),te.removeEventListener("pointercancel",ne),f.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}bv(q)};Ki=ne,te.addEventListener("pointermove",Z),te.addEventListener("pointerup",ne),te.addEventListener("pointercancel",ne);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let f=Ui()==="right"?-yv:yv,y=pl(),x=c.key==="ArrowRight"?y+f:c.key==="ArrowLeft"?y-f:c.key==="Home"?af:c.key==="End"?lf:null;x!==null&&(c.preventDefault(),bv(x))}),i},Hk=(i,c)=>{if(!vk()||ml()){Ki?.(),hf?.remove();return}let f=hf??Ik();hf=f,f.setAttribute("aria-label",Ct.resizeLabel),f.setAttribute("aria-valuenow",String(pl())),f.nextElementSibling!==c&&i.insertBefore(f,c)};ut=()=>{Ht?.view.setRailSide(Ui());let i=Ui()==="right",c=Ar;if(c){let te=wo?wo.getBoundingClientRect().bottom-Le.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(te))}px + ${Td})`,c.style.width=`${pl()}px`,c.style.left=i?"":Td,c.style.right=i?Td:""}let f=Gs,y=$i,x=cl;if(!f||!y||!x)return;f.style.flex=`0 0 ${ml()?bk:pl()}px`;let k="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":k,f.style.borderLeft=i?k:"";let q=i?x:f;y.firstElementChild!==q&&y.append(q,i?f:x),Hk(y,i?f:x)};let vv=i=>{if(zi&&Gs){zi.replaceWith(i),zi=null,ut();return}let c=v("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("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 y=v("div","persona-history-rail-host");y.style.cssText="display:flex;min-height:0;overflow:hidden",Le.insertBefore(c,he.parentNode===Le?he:ie);for(let x of iv())x?.parentNode===Le&&f.appendChild(x);c.append(y,f),y.appendChild(i),$i=c,Gs=y,cl=f,ut()},Rk=()=>{if($i)return;let i=v("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",zi=i,vv(i),Xn()},Cv=()=>{zi&&(kd(),Xn())},Wk=i=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Td};display:flex;overflow:hidden;z-index:${fa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Le.style.position="relative",Le.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",gf),Ar=c,ut(),fv()},kd=()=>{Sd?.(),Ar&&(Ys&&(ff=Date.now()+150),document.removeEventListener("pointermove",gf),Ar.remove(),Ar=null);let i=$i;if(i){Ki?.();for(let c of iv())c&&i.contains(c)&&Le.insertBefore(c,i);i.remove(),$i=null,Gs=null,cl=null,zi=null}},wv=i=>{ll=i,i.id=ef,i.style.flex="1 1 auto",i.style.minHeight="0"},yf=i=>{wv(i),(Se!=="rail"||dn)&&Cv(),Se!=="rail"?yk(i):dn?Wk(i):vv(i)},Ld=()=>{if(gl(),Hv(),!ve||!Ht)return;let i=of();if(i===Se)return;let c=document.activeElement,f=c instanceof HTMLElement&&(Ht.element.contains(c)||mo?.contains(c)===!0)?c:null;kd(),Ht.element.remove(),Ht.view.setHeaderPlacement("inline"),Se=i,Ht.view.setPresentation(i),Ht.view.setCollapsed(ml()),Ht.requestRender(),Ht.element.isConnected||yf(Ht.element),f?.isConnected?f.focus():Pd(),yn(),Xn(),ts()},xv=(i,c)=>mo?.querySelector(c)??i.querySelector(c),Pd=()=>{let i=Ht?.element??ll;if(!i)return;let c=xv(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=xv(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},hl=async i=>{if(!tr()||ve)return;let c=uo;if(!c)return;if(!dn&&ji()&&df()){gl();return}Id();let f=++al;yd=i?.returnSurface??"conversation",Xm=i?.invoker??Nn;let y=ji()&&!dn;y&&(Ed+=1,gl(),Rk());let x;try{x=await by()}catch{wd(Ct.openHistoryLabel),y&&(Ed-=1,f===al&&(Cv(),gl()));return}if(y&&(Ed-=1),f!==al||ve)return;hd={scope:nf()},Se=of(),ve=!0;let k=Se==="panel"&&o.layout?.showHeader!==!1&&he.style.display!=="none"?"external":"inline",q=o.features?.history?.rowAvatar,te=mf(),Z=te?{hint:te.hint,aria:te.aria}:null,ne={provider:c,context:hd,targetId:Jb(),presentation:Se,collapsible:Ad(),collapsed:ml(),railSide:Ui(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:xk(),onToggleCollapse:cv,...Z?{collapseShortcut:Z}:{},headerPlacement:k,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:q===!1?!1:typeof q=="string"?q:o.launcher?.iconUrl,activeConversationId:_.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:pe=>vf(pe,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:pe=>Qs(pe),attachTooltip:Mn,onStartNew:()=>Cf({focusComposer:!0}),onClose:()=>Jn(),onRequestDeleteConversation:pe=>Iv(pe),onRequestClearHistory:()=>Fk(),...c.resetDevice?{onRequestResetIdentity:()=>Vk()}:{}};Ht=_T({plugins:a,config:o,getPresentation:()=>Se??"panel",getReturnSurface:()=>yd,close:()=>Jn(),createView:({slots:pe,renderDom:Ce,onModelChange:He,railSections:wt})=>(Ks=x.createHistoryView({...ne,railSections:Ak(wt),slots:pe,renderDom:Ce,onModelChange:He,onAnnounce:wd}),Ks),onElementChanged:(pe,Ce)=>{if(!Ce?.isConnected)return yf(pe);wv(pe),Ce.replaceWith(pe),sf()}}),Ht.view.setNewConversationRequired(bd.recovery==="new_conversation_required"),i?.focus!==!1&&(Se!=="rail"||i?.keyboard===!0)&&Pd(),yn(),Xn(),ts(),E.emit("history:opened",{presentation:Se,returnSurface:yd,timestamp:Date.now()})},Id=()=>{},Jn=i=>{if(!ve)return;al+=1;let c=yd,f=Xm,y=Ht,x=i?.restoreFocus!==!1;ve=!1;let k=!1,q=null,te=()=>{if(!k){if(k=!0,Id=()=>{},q!==null&&clearTimeout(q),dn=!1,fl(),kd(),y?.dispose(),y?.view.destroy(),y?.element.remove(),Ht===y&&(Ht=null,Ks=null,ll=null,Se=null,hd=null,Xm=null),yn(),Xn(),ts(),x){let ne=f??Nn;ne?.isConnected?ne.focus():zs()}E.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},Z=y&&y.element===y.view.element?y.view.playExit():null;if(!Z){te();return}Id=te,q=setTimeout(te,dk),Z.then(te)},Sv=i=>{if(!(i.key!=="Escape"||!ve||!Ht)){if(Se==="rail"){let c=i.target;if(!(c instanceof Node)||!(Ht.element.contains(c)||dn&&Sr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Jn()}};Le.addEventListener("keydown",Sv),De.push(()=>Le.removeEventListener("keydown",Sv));let Hd=null,Av=!1,yl=()=>{if(!Be)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Hd?.trim()||null;Be.textContent=c??o.launcher?.title??"Chat Assistant";let f=Be.closest(".persona-combo-btn");if(!f)return;let y=!i||_.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",y?"false":"true"),f.setAttribute("aria-haspopup",y?"true":"false"),y||f.setAttribute("aria-expanded","false"),f.style.cursor=y?"pointer":"default";let x=f.querySelector("svg");x&&(x.style.display=y?"":"none")},Bk=i=>{i!==Hd&&(Hd=i,yl())},Qs=i=>{Av=i?.starred===!0,Bk(i&&i.title.trim()||null),yl()};yl(),Le.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,f=_.getActiveConversationId();f&&(c==="delete"?Iv(f):c==="star"&&_.canUpdateConversations()&&wf(f,{starred:!Av}).catch(()=>{}))});let Rd=0,Ok=250,Wd=null,Bd=()=>{Wd&&clearTimeout(Wd),Wd=null};De.push(Bd);let Mv=()=>{Bd();let i=Us;i&&(sl=!0,i.hidden=!1,Re.style.display="none",il())},Od=()=>{Rd+=1,Bd(),Us&&(Us.remove(),Us=null,sl=!1,Re.style.removeProperty("display"),Co(We,!1),il())},Dk=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Re.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},bf=(i,c)=>$("div",{className:Vt("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),Tv=()=>$("div",{className:"persona-conversation-loading-body"},bf("58%",!1),bf("72%",!0),bf("44%",!1)),Ev=i=>{Us?.remove(),Us=i,i.hidden=!sl,ie.insertBefore(i,Re),Bd(),sl||(Wd=setTimeout(Mv,Ok)),Co(We,!0)},_k=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Tv},c=null,f=a.find(y=>y.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Ev($("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ct.openConversationLoadingLabel}},c??Tv()))},Nk=i=>{let c=()=>{vf(i,{focusComposer:!0}).catch(()=>{})},f=tr()?()=>{Od(),hl()}:void 0,y=(te,Z)=>{let ne=$("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:te});return ne.addEventListener("click",Z),ne},x=()=>$("div",{className:"persona-conversation-loading-error-body"},$("p",{className:"persona-conversation-loading-error-title",text:Ct.openConversationErrorTitle}),$("div",{className:"persona-conversation-loading-error-actions"},y(Ct.openConversationRetryLabel,c),f?y(Ct.openConversationBackLabel,f):null)),k=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Ct.openConversationErrorTitle,retryLabel:Ct.openConversationRetryLabel,backLabel:Ct.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:x}),q=null;for(let te of a)if(te.renderHistoryOpenError){try{q=te.renderHistoryOpenError(k)}catch(Z){console.warn("[persona] renderHistoryOpenError threw",Z),q=null}if(q)break}Ev($("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},q??x())),Mv()};E.on("history:closed",()=>{Us&&Co(We,!0)});let vf=async(i,{focusComposer:c=!1}={})=>{let f=Vi(),y=!!Ht;Ht?.view.setActiveConversationId(i),Od();let x=Rd;_k(),ve&&(Se==="panel"||dn)&&Jn({restoreFocus:!1}),Hi=!0;try{await _.openConversation(i,{scope:f})}catch(k){throw x===Rd&&Nk(i),k}finally{Hi=!1}x===Rd&&(Od(),cn.clear(),Oo(),Qn(),Im()||id(),Dk(),Mr(),y||Qs(null),E.emit("history:conversationOpened",{conversationId:i,title:Hd,scope:f,timestamp:Date.now()}),c&&zs())},Cf=async({focusComposer:i=!1}={})=>{Od(),await _.startNewConversation({scope:Vi()}),Qs(null),cn.clear(),Oo(),Qn(),id(),Mr();let c=_.getActiveConversationId();Ht?.view.setActiveConversationId(c),E.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),ve&&(Se==="panel"||dn)&&Jn({restoreFocus:!1}),i&&zs()},wf=async(i,c)=>{let f=await _.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return Ht?.view.applyConversationSummary(f),!Ht&&i===_.getActiveConversationId()&&Qs(f),f},kv=async i=>{let c=Vi(),f=_.getActiveConversationId()===i;await _.deleteConversation(i,{scope:c}),Ht?.view.removeConversationSummary(i),f&&(Qs(null),cn.clear(),Oo(),Qn(),Mr()),E.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:f,timestamp:Date.now()})},Lv=async i=>{let c=i?.scope??Vi(),f=i?.allTargets?null:i?.targetId??Jb(),y=await _.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Qs(null),cn.clear(),Oo(),Qn(),Mr(),E.emit("history:cleared",{deleted:y.deleted,scope:c,targetId:f,timestamp:Date.now()}),y},Pv=async()=>{if(!uo?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await _.resetHistoryDevice()).remoteRevocationConfirmed}finally{Qs(null),_.clearArtifacts(),cn.clear(),jm=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),H={},se.syncFromMetadata(),R?.clear&&od(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),Oo(),Qn(),Mr(),Jn({restoreFocus:!1}),zs(),Pe||Qt?.launcher.element.focus()}return wd(i?Ct.identityResetNotice:Ct.identityResetUnconfirmedNotice),E.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},xf=()=>Qo?_e:Le,Iv=async i=>await em({host:xf(),title:Ct.deleteConversationConfirmTitle,description:Ct.deleteConversationConfirm,confirmLabel:Ct.deleteConversationConfirmLabel,cancelLabel:Ct.confirmCancelLabel})?(await kv(i),"deleted"):"cancelled",Fk=async()=>{let i=Vi()==="verified-user";return await em({host:xf(),title:Ct.clearHistoryConfirmTitle,description:i?Ct.clearHistoryVerifiedConfirm:Ct.clearHistoryConfirm,confirmLabel:Ct.clearHistoryConfirmLabel,cancelLabel:Ct.confirmCancelLabel})?(await Lv(),"cleared"):"cancelled"},Vk=async()=>{if(!await em({host:xf(),title:Ct.resetIdentityConfirmTitle,description:Ct.resetIdentityConfirm,confirmLabel:Ct.resetIdentityConfirmLabel,cancelLabel:Ct.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Pv();return{outcome:"reset",remoteRevocationConfirmed:c}},xo=v("button","persona-history-earlier");xo.type="button",xo.textContent=Ct.showEarlierMessagesLabel,xo.setAttribute("data-persona-history-earlier",""),Object.assign(xo.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 Mr=()=>{if(!(tr()&&!!bd.nextMessageCursor&&!!_.getActiveConversationId())){xo.remove();return}xo.textContent=Ct.showEarlierMessagesLabel,xo.parentNode!==ie&&ie.insertBefore(xo,ie.firstChild)};xo.addEventListener("click",()=>{let i=_.getActiveConversationId(),c=bd.nextMessageCursor;if(!i||!c||xo.disabled)return;xo.disabled=!0;let f=ie.scrollHeight,y=ie.scrollTop;_.loadOlderMessages(i,c,{scope:Vi()}).then(()=>{ie.scrollTop=y+(ie.scrollHeight-f),Xn()}).catch(()=>{}).finally(()=>{xo.disabled=!1,Mr()})});let $k=()=>{let i=ai({ariaLabel:Ct.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 i.button.addEventListener("click",c=>{if(!(!tr()||Xb())){if(ve){Jn();return}hl({invoker:i.button,keyboard:c.detail===0})}}),i},Hv=()=>{if(!tr()){er?.remove(),Nn=null,er=null;return}if(er&&!er.isConnected&&(Nn=null,er=null),!Nn&&he){let y=$k();Nn=y.button,er=y.wrapper;let x=Ze.clearChatButtonWrapper||Ze.closeButtonWrapper;x?.parentNode&&he.contains(x)?x.parentNode.insertBefore(er,x):he.appendChild(er)}if(!Nn||!er)return;let i=ji()||ve&&Se==="rail";if(er.style.display=i?"none":"",i){document.activeElement===Nn&&Pd();return}let c=Xb();Nn.disabled=c,Nn.setAttribute("aria-disabled",c?"true":"false");let f=c?Ct.openHistoryBusyLabel:Ct.openHistoryLabel;Nn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(Nn.removeAttribute("aria-expanded"),Nn.removeAttribute("aria-controls")):(Nn.setAttribute("aria-expanded",ve?"true":"false"),Nn.setAttribute("aria-controls",ef))},Dd=!1,zk=()=>{let i=Ze.clearChatButton;if(i){if(tr()){Dd||(Zm=i.getAttribute("aria-label")??"",Dd=!0),i.setAttribute("aria-label",Ct.newConversationLabel),i.removeAttribute("title");return}Dd&&(Dd=!1,Zm&&i.setAttribute("aria-label",Zm))}},ts=()=>{Ct=ly(o.features?.history?.copy),Hv(),gl(),zk(),Mr()};wn=ts,vn=i=>{bd=i,Ht?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),rl(i.sendBlocked||lo),Mr()},Cn=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(cn.clear(),Oo(),Qn()),wd(i.message),Ht?.view.refresh()},nv(),ts(),De.push(()=>{vd?.(),Cd?.(),al+=1,Id(),Ht?.dispose(),Ht?.view.destroy(),Ht=null}),o.clientToken&&_.initClientSession().then(()=>{if(tr())return _.reconcileBootConversation({scope:nf()})}).then(()=>{Mr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(L||o.onSSEEvent)&&_.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),pt(i,c)});let Rv=()=>{let i=o.resume??(V?wr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(i)};w?w.then(i=>{if(i){if(i.metadata&&(H=Sy(i.metadata),se.syncFromMetadata()),i.messages?.length){Hi=!0;try{_.hydrateMessages(i.messages)}finally{Hi=!1}dd()}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Lb(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{_m=!0,T(),Rv()}):(Lb(D),Rv());let Uk=()=>{!Ee()||Pe||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Nt(!0,"auto")},qk=(i,c)=>i?c?{refs:[...i.refs,...c.refs],finalize:async()=>{let[f,y]=await Promise.allSettled([i.finalize(),c.finalize()]),x=[];return f.status==="fulfilled"?x.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),y.status==="fulfilled"?x.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),DB(x)}}:i:c,Sf=()=>{let c=Ae.getInlineMessageFields?.();return c&&c.contentSegments.some(y=>y.kind==="mention")?c.contentSegments:void 0},Tr=!1,Xs=null,_d=()=>{Ae.value="",Ae.style.height="auto",Ko(),vl()},Af="data-persona-composer-notice",Gi=null;function jk(i){_c(i),!(Ee()||!bt)&&(bt.hasAttribute(Oa)||(bt.setAttribute(Af,""),bt.setAttribute("role","status"),bt.setAttribute("aria-live","polite"),bt.textContent=i,Gi&&clearTimeout(Gi),Gi=setTimeout(()=>{if(Gi=null,!!bt?.hasAttribute(Af)&&(bt.removeAttribute(Af),bt.removeAttribute("role"),bt.removeAttribute("aria-live"),p)){let c=_.getStatus();Rn(bt,sn(c),o.statusIndicator??{},c)}},4e3)))}function Kk(){let i=ze.getState().pendingSubmission;i&&(Ai(void 0),Ae&&(Ae.value=i.text,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ko()),i.options.selectedModelId&&(ze.setSelectedModelId(i.options.selectedModelId),Ur?.repaint()),i.options.activeModeIds?.length&&$c(i.options.activeModeIds),i.options.quote&&Go(i.options.quote),Ae?.focus())}let Gk=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},Wv=(i={})=>{let c=(i.overrideText??Ae?.value??"").trim();return i.resolveInlineCommand&&c?(nn?.takeInlineCommand(c)??Promise.resolve(null)).then(f=>Bv(i,c,f)):Bv(i,c,null)},Bv=(i,c,f)=>{if(f?.kind==="action"){_d(),nn?.clear(),Ts();return}let y=f?.kind==="server"?f.mentions:null,x=f?.kind==="prompt"?f.sendText:c,k=i.pending?.contentParts,q=(At?.hasAttachments()??!1)||(k?.length??0)>0;if(!Kx({text:x,hasAttachments:q,attachmentsReady:At?.isReady()??!0,hasMentions:nn?.hasMentions()??!1,hasServerMentions:!!y,inputDisabled:Zo(),sendDisabled:$s()}))return;let te=_.isStreaming()?pm():"block";if(te==="defer-one"&&!i.pending){if(ze.getState().pendingSubmission){jk("One message is already queued. Edit or remove it first.");return}Yk({intent:i,sendText:x,serverMentions:y});return}let Z={text:x,mentionRefs:[...nn?.getMentionRefs()??[],...y?.refs??[]],contentSegments:f?.kind==="prompt"?void 0:Sf(),options:{...ze.getState().selectedModelId&&{selectedModelId:ze.getState().selectedModelId},...ze.getState().activeModeIds.length>0&&{activeModeIds:[...ze.getState().activeModeIds]},...ze.getState().quote&&{quote:{...ze.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(Z.options={...i.pending.options},Z.contentSegments=i.pending.contentSegments,Z.mentionRefs=[...i.pending.mentionRefs],Z.viaVoice=i.pending.viaVoice);let ne=()=>{if(k?.length)return[...k];if(!At?.hasAttachments())return;let Ft=[...At.getContentParts()];return Z.text&&Ft.push(sr(Z.text)),Ft};Z.contentParts=ne();let pe=()=>{Bs(),Uk();let Ft=nn?.collectForSubmit()??null,xn=qk(Ft,y),pn=ne();i.consumeDraft!==!1&&_d();let Jt={selectedModelId:Z.options.selectedModelId,activeModeIds:Z.options.activeModeIds},Bn=te==="interrupt";Bn&&_.cancel(),_.sendMessage(Z.text,{contentParts:pn,mentions:xn??void 0,contentSegments:Z.contentSegments,viaVoice:Z.viaVoice,composerOptions:Jt,...Z.options.quote&&{quote:Z.options.quote},...Bn&&{interrupt:!0}}),At?.hasAttachments()&&At.clearAttachments(),Ft&&nn?.clear(),Ts();let Mt=ze.getState().activeModeIds,On=Rx(Mt,o.composer?.modes);On.length!==Mt.length&&$c(On),ze.getState().quote&&Go(void 0),sd(),hm.release(),Ho()},Ce=o.composer?.onBeforeSend;if(!Ce){pe();return}let He=new AbortController;Xs=He;let wt=Ft=>{if(Xs=null,Ft.status==="error"){Gk(Ft.error);return}Ft.status==="proceed"&&pe()},Ot=Gx(Ce,Z,He.signal);if(!(Ot instanceof Promise)){wt(Ot);return}return ze.setPreparing(!0),Ot.then(wt).finally(()=>ze.setPreparing(!1))};function Yk(i){let c=ze.getState(),f=At?.hasAttachments()??!1,y=f?[...At.getContentParts()]:[];f&&i.sendText&&y.push(sr(i.sendText));let x=Hg({text:i.sendText,contentParts:y.length?y:void 0,mentionRefs:[...nn?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Sf(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Ai(x),i.intent.consumeDraft!==!1&&_d(),f&&At.clearAttachments(),nn?.clear(),Ts(),c.quote&&Go(void 0),sd(),hm.release(),Ho(),_c("Message queued. It sends when the response finishes.")}function Qk(){let i=ze.getState().pendingSubmission;i&&(Ai(void 0),Fd(i.text,{consumeDraft:!1,pending:i}))}function Xk(i){if(o.messageActions?.showEdit!==!0)return;let c=_.getMessages().find(f=>f.id===i);!c||!ng(c)||Ws!==i&&(Bs(),Ws=i,Gr=_x({messageId:i,initialText:c.content,onSave:f=>Jk(i,f),onCancel:()=>Bs()}),cn.delete(i),bo(Re,_.getMessages(),Ge),Gr.focus())}function Jk(i,c){let f=Gr;if(Ws=null,Gr=null,f?.destroy(),cn.delete(i),!_.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){bo(Re,_.getMessages(),Ge);return}Xn()}function Zk(i){if(_.isStreaming())return;let c=tg(_.getMessages(),i);c&&(Bs(),_.resubmitFrom(c,{reason:"retry"})&&Xn())}zc={regenerate:Zk,edit:Xk,quote:i=>{let f=_.getMessages().find(y=>y.id===i)?.content?.trim();f&&(Go({text:f,messageId:i}),Ae?.focus())}};let bl=async i=>{if(!Tr){Tr=!0;try{await Wv({resolveInlineCommand:!0,...i})}finally{Tr=!1}}};function Nd(i){$s()||(_d(),Fd(i,{consumeDraft:!1}))}let Fd=(i,c)=>{if(Tr)return;Tr=!0;let f=()=>{Tr=!1};try{let y=Wv({...c,overrideText:i});y instanceof Promise?y.finally(f):f()}catch(y){throw f(),y}},e0=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),lt?.reset(),mt?.update();return}Tr||bl()},t0=()=>o.features?.composerHistory!==!1,Mf={...Qg},Tf=!1,vl=()=>{Mf={...Qg}},n0=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),o0=i=>{if(!Ae)return;Tf=!0,Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Tf=!1;let c=Ae.value.length;Ae.setSelectionRange(c,c)},r0=i=>{Tf||(i.isComposing||nn?.handleInput(i.inputType??void 0),vl())},s0=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ql(Ae)}),i0=i=>{if(Ae&&!Zo()&&!(!i.isComposing&&nn?.handleKeydown(i))){if(t0()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=Ae.selectionStart===0&&Ae.selectionEnd===0,f=zS({direction:i.key==="ArrowUp"?"up":"down",history:n0(),currentValue:Ae.value,atStart:c,state:Mf});if(Mf=f.state,f.handled){i.preventDefault(),f.value!==void 0&&o0(f.value);return}}if(fx(i,s0())){if(_.isStreaming()){if(i.preventDefault(),pm()==="block"||Tr||$s())return;vl(),bl();return}if(Tr){i.preventDefault();return}if($s()){i.preventDefault();return}vl(),i.preventDefault(),Ve.click()}}},Ov=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(Le)){if(Xs){Xs.abort(),Xs=null,i.preventDefault(),i.stopImmediatePropagation();return}_.isStreaming()&&(_.cancel(),lt?.reset(),mt?.update(),vl(),i.preventDefault(),i.stopImmediatePropagation())}},a0=async i=>{if(o.attachments?.enabled!==!0||!At||Zo())return;let c=RB(i.clipboardData);c.length!==0&&(i.preventDefault(),await At.handleFiles(c))},So=null,nr=!1,Yi=null,qt=null,Ef=()=>o.voiceRecognition?.completionBehavior==="review";function Js(i){fe?.setAttribute("data-state",i),i==="recording"?c0():If()}let Dv="--persona-voice-level",kf=.5,Qi=null,Lf=-1,Vd=0,_v=()=>{let i=[],c=io??fe?.parentElement??null;return c&&i.push(c),We&&i.push(We),i},Pf=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Lf){Lf=c;for(let f of _v())f.style.setProperty(Dv,String(c))}},l0=()=>{Lf=-1,Vd=0;for(let i of _v())i.style.removeProperty(Dv)};function c0(){if(Qi!==null)return;if(typeof requestAnimationFrame!="function"){Pf(p?_.getVoiceLevel()??kf:kf);return}let i=()=>{Qi=requestAnimationFrame(i);let c=p?_.getVoiceLevel():null;if(c===null){Pf(kf);return}Vd+=(c-Vd)*.3,Pf(Vd)};Qi=requestAnimationFrame(i)}function If(){Qi!==null&&(cancelAnimationFrame(Qi),Qi=null),l0()}let Nv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$d=(i="user")=>{if(nr||_.isStreaming())return;let c=Nv();if(!c)return;So=new c;let f=o.voiceRecognition??{},y=f.pauseDuration??2e3;So.continuous=f.provider?.browser?.continuous??!0,So.interimResults=!0,So.lang=f.provider?.browser?.language??"en-US";let x=Ae.value;So.onresult=k=>{let q="",te="";for(let ne=0;ne<k.results.length;ne++){let pe=k.results[ne],Ce=pe[0].transcript;pe.isFinal?q+=Ce+" ":te=Ce}let Z=x+q+te;Ae.value=Z,Ko(),Yi&&clearTimeout(Yi),(q||te)&&(Yi=window.setTimeout(()=>{if(Ae.value.trim()&&So&&nr){if(ns(),Ef())return;bl({viaVoice:!0})}},y))},So.onerror=k=>{k.error!=="no-speech"&&ns()},So.onend=()=>{if(nr){let k=Ae.value.trim();!Ef()&&k&&k!==x.trim()&&bl({viaVoice:!0}),ns()}};try{if(So.start(),nr=!0,gt.active=!0,i!=="system"&&(gt.manuallyDeactivated=!1),vr(i),Bo(),Ho(),fe){let k=o.voiceRecognition??{};qt={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||$n};let q=k.recordingBackgroundColor,te=k.recordingIconColor,Z=k.recordingBorderColor;if(fe.classList.add("persona-voice-recording"),Js("recording"),fe.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=te??"var(--persona-voice-recording-indicator, #ffffff)",te){let ne=fe.querySelector("svg");ne&&ne.setAttribute("stroke",te)}Z&&(fe.style.borderColor=Z),fe.setAttribute("aria-label","Stop voice recognition")}}catch{ns("system")}},ns=(i="user")=>{if(nr){if(nr=!1,Yi&&(clearTimeout(Yi),Yi=null),So){try{So.stop()}catch{}So=null}if(gt.active=!1,vr(i),Bo(),Ho(),fe){if(fe.classList.remove("persona-voice-recording"),Js("idle"),qt){fe.style.backgroundColor=qt.backgroundColor,fe.style.color=qt.color,fe.style.borderColor=qt.borderColor;let c=fe.querySelector("svg");c&&c.setAttribute("stroke",qt.color||"currentColor"),qt=null}fe.setAttribute("aria-label","Start voice recognition")}}},Hf=()=>{if(!fe||qt)return;let i=o.voiceRecognition??{};qt={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||$n}},Rf=(i,c)=>{if(!fe)return;let f=fe.querySelector("svg");f&&f.remove();let y=qt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||$n),x=Ie(i,y,c,1.5);x&&fe.appendChild(x)},zd=()=>{fe&&fe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Xi=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(zd(),fe.classList.add("persona-voice-recording"),Js("recording"),fe.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let x=fe.querySelector("svg");x&&x.setAttribute("stroke",f)}y&&(fe.style.borderColor=y),fe.setAttribute("aria-label","Stop voice recognition")},d0=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=_.getVoiceInterruptionMode(),f=i.processingIconName??"loader",y=i.processingIconColor??qt?.color??"",x=i.processingBackgroundColor??qt?.backgroundColor??"",k=i.processingBorderColor??qt?.borderColor??"";zd(),fe.classList.add("persona-voice-processing"),Js("processing"),fe.style.backgroundColor=x,fe.style.borderColor=k;let q=y||"currentColor";fe.style.color=q,Rf(f,q),fe.setAttribute("aria-label","Processing voice input"),c==="none"&&(fe.style.cursor="default")},p0=()=>{if(!fe)return;Hf();let i=o.voiceRecognition??{},c=_.getVoiceInterruptionMode(),f=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",y=i.speakingIconName??f,x=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??qt?.color??"":qt?.color??""),k=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":qt?.backgroundColor??""),q=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":qt?.borderColor??"");zd(),fe.classList.add("persona-voice-speaking"),Js("speaking"),fe.style.backgroundColor=k,fe.style.borderColor=q;let te=x||"currentColor";fe.style.color=te,Rf(y,te);let Z=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";fe.setAttribute("aria-label",Z),c==="none"&&(fe.style.cursor="default"),c==="barge-in"&&fe.classList.add("persona-voice-recording")},Er=()=>{fe&&(zd(),Js("idle"),qt&&(fe.style.backgroundColor=qt.backgroundColor??"",fe.style.color=qt.color??"",fe.style.borderColor=qt.borderColor??"",Rf(qt.iconName,qt.color||"currentColor"),qt=null),fe.style.cursor="",fe.setAttribute("aria-label","Start voice recognition"))},Wf=()=>{if(!Zo()){if(no(o.voiceRecognition?.provider)){let i=_.getVoiceStatus(),c=_.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Bo(),vr("user"),Er()});return}_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),gt.manuallyDeactivated=!_.isVoiceActive(),Bo(),vr("user"),_.isVoiceActive()?Xi():Er()});return}if(nr){let i=Ae.value.trim();gt.manuallyDeactivated=!0,Bo(),ns("user"),i&&!Ef()&&bl()}else gt.manuallyDeactivated=!1,Bo(),$d("user")}};um=Wf,fe&&De.push(()=>{no(o.voiceRecognition?.provider)?(_.isVoiceActive()&&_.toggleVoice(),Er()):ns("system")});let u0=E.on("assistant:complete",()=>{ze.getState().pendingSubmission&&setTimeout(()=>{_.isStreaming()||Qk()},0)});De.push(u0);let m0=E.on("assistant:complete",()=>{Tb&&(gt.active||gt.manuallyDeactivated||Tb==="assistant"&&!gt.lastUserMessageWasVoice||setTimeout(()=>{!gt.active&&!gt.manuallyDeactivated&&(no(o.voiceRecognition?.provider)?_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),vr("auto"),_.isVoiceActive()&&Xi()}):$d("auto"))},600))});De.push(m0);let f0=E.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});De.push(f0);let Fv=()=>{Nt(!Pe,"user")},Qt=null,Fn=null;if(ce&&!Ee()){let{instance:i,element:c}=Sh({config:o,plugins:a,onToggle:Fv});Qt=i,i||(Fn=c)}Qt?t.appendChild(Qt.element):Fn&&t.appendChild(Fn),ol(),Pi(),md(),zm(),rl(_.isStreaming()),Im()||(ao()==="follow"?Xr(!0):id()),RE(),ge&&(!ce||Ee()?setTimeout(()=>zs(),0):Pe&&setTimeout(()=>zs(),200));let Zs=null,Vv=()=>{Zs&&(Zs.disconnect(),Zs.observe(We),Zs.observe(Le))},Cl=()=>{if(Ee()){Ms(),ol();return}let i=rn(o),c=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,k=f.innerWidth<=x,q=y&&k&&ce;try{if(q){Es(),Ka=Xc();return}let te=!1;nt&&(nt=!1,Es(),te=!0);let Z=Xc();if(!te&&Z!==Ka&&(Es(),te=!0),Ka=Z,te&&Kc(),!ce&&!i){_e.style.height="",_e.style.width="";return}if(!c&&!i){let pe=o?.launcher?.width??o?.launcherWidth??Rr;_e.style.width=pe,_e.style.maxWidth=pe}Qc(),db()}finally{if(Ms(),Vc(),ol(),Pe&&ce){let Z=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ne=o.launcher?.sidebarMode??!1,pe=o.launcher?.mobileFullscreen??!0,Ce=rn(o)&&pe&&Z,He=ne||pe&&Z&&ce||Ce;if(He&&!Jo){let wt=t.getRootNode(),Ot=wt instanceof ShadowRoot?wt.host:t.closest(".persona-host");Ot&&!Xo&&(Xo=rh(Ot,o.launcher?.zIndex??Hn)),Jo=sh(t.ownerDocument)}else He||(Xo?.(),Xo=null,Jo?.(),Jo=null)}}};Cl();let Ud=t.ownerDocument.defaultView??window;if(Ud.addEventListener("resize",Cl),De.push(()=>Ud.removeEventListener("resize",Cl)),typeof ResizeObserver<"u"){Zs=new ResizeObserver(()=>{Vc()}),Vv(),De.push(()=>{Zs?.disconnect(),Zs=null});let i=new ResizeObserver(()=>{Ld()});i.observe(Le),De.push(()=>i.disconnect())}Ud.addEventListener("resize",Ld),De.push(()=>Ud.removeEventListener("resize",Ld)),po=ie.scrollTop;let $v=cr(ie),zv=()=>{let i=ie.scrollTop,c=cr(ie),f=c<$v;if($v=c,!zr()){po=i,yn();return}let{action:y,nextLastScrollTop:x}=uu({following:co.isFollowing(),currentScrollTop:i,lastScrollTop:po,nearBottom:Wr(ie,yr),userScrollThreshold:LE,isAutoScrolling:Yn||Zc||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(po=x,y==="resume"){ad()||Qn();return}y==="pause"&&Ja()};if(ie.addEventListener("scroll",zv,{passive:!0}),De.push(()=>ie.removeEventListener("scroll",zv)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{FE(),Vf(Re)});i.observe(Re),i.observe(ie),De.push(()=>i.disconnect())}let Uv=()=>{zr()&&co.isFollowing()&&ad()&&Ja()},qv=ie.ownerDocument;qv.addEventListener("selectionchange",Uv),De.push(()=>{qv.removeEventListener("selectionchange",Uv)});let g0=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),jv=i=>{g0.has(i.key)&&(Ns(),Iy()&&zr()&&co.isFollowing()&&Ja())},Kv=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ns(),Iy()&&zr()&&co.isFollowing()&&Ja())};ie.addEventListener("keydown",jv),ie.addEventListener("focusin",Kv),De.push(()=>{ie.removeEventListener("keydown",jv),ie.removeEventListener("focusin",Kv)});let Gv=i=>{if(i.deltaY!==0&&Ns(),!zr())return;let c=mu({following:co.isFollowing(),deltaY:i.deltaY,nearBottom:Wr(ie,yr),resumeWhenNearBottom:!0});c==="pause"?Ja():c==="resume"&&!ad()&&Qn()};ie.addEventListener("wheel",Gv,{passive:!0}),ie.addEventListener("touchmove",Ns,{passive:!0}),ie.addEventListener("pointerdown",Ns,{passive:!0}),De.push(()=>{ie.removeEventListener("touchmove",Ns),ie.removeEventListener("pointerdown",Ns)}),De.push(()=>ie.removeEventListener("wheel",Gv)),ln.addEventListener("click",()=>{Oo(),ie.scrollTop=ie.scrollHeight,po=ie.scrollTop,Qn(),Xr(!0),yn()}),De.push(()=>ln.remove()),De.push(()=>{Ib(),Oo()});let Yv=()=>{F&&(Is&&(F.removeEventListener("click",Is),Is=null),Ne()?(F.style.display="",Is=()=>{Nt(!1,"user")},F.addEventListener("click",Is)):F.style.display="none")};Yv(),(()=>{let{clearChatButton:i}=Ze;i&&i.addEventListener("click",()=>{if(tr()){Cf({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}_.clearMessages(),cn.clear(),Qn(),la(Ze.composerOverlay);try{localStorage.removeItem(Ba),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ba}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ba)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),R?.clear&&od(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},se.syncFromMetadata(),At?.clearAttachments(),sd(),Ai(void 0),Go(void 0),Bs(),je?.clear(),lt?.reset(),mt?.update()})})();let Qv=[["keydown",i0],["input",r0],["input",Ko],["input",Ts],["keyup",Ts],["paste",a0],["focus",yE]],Xv=i=>{if(i)for(let[c,f]of Qv)Lt?.addListener(i,c,f)},h0=i=>{if(i)for(let[c,f]of Qv)Lt?.removeListener(i,c,f)},Jv=()=>{Lt&&(Lt.addListener(Lt.form,"submit",e0),Lt.addListener(Lt.footer,"click",Ts),Xv(Ae),fe&&Lt.addListener(fe,"click",Wf))};Jv();let Zv=()=>{nn?.onComposerSwap((i,c)=>{h0(c),Ae=i,Lt&&(Lt.input=i),Xv(i),fm(),Om(),Ko()})};Zv();let Bf=!1;function eC(){if(!Bf){Bf=!0;try{let i=Ae?.value??"",c=We.ownerDocument??document,f=Ae?c.activeElement===Ae:!1;If(),Lt?.destroy(),Lt=null,nn?.destroy(),nn=null;let y=null,x=()=>(y=Ee()?wu({config:o}):gc({config:o}),y.footer),k=Vy(x)??x();tn.replaceComposer(k),We=tn.composer.footer;let q=y!==null&&k===y.footer;Ti=!q,Py=q?y.setSendButtonMode:()=>{},Fy(We),zy(We),Uy(),qy(),jy(),Zv(),Ky(),gm(),Gy(),Jv();let te=Ps.indexOf(hr);hr.destroy(),hr=uc(Io),te>=0&&(Ps[te]=hr),Ae&&(Ae.value=i),Ko(),Ts(),md(),Pi(),rl(_.isStreaming()),gt.active&&Js("recording"),Es(),Vv(),Ms(),Ho(),pd(),f&&Ae?.focus()}finally{Bf=!1}}}let wl=t.ownerDocument??document;wl.addEventListener("keydown",Ov,!0);let tC=()=>{Em()},nC=()=>{wl.visibilityState==="hidden"&&Em()};typeof window<"u"&&(window.addEventListener("pagehide",tC),wl.addEventListener("visibilitychange",nC),De.push(()=>{window.removeEventListener("pagehide",tC),wl.removeEventListener("visibilitychange",nC)}));let oC="persona-attachment-drop-active",xl=0,Of=()=>{xl=0,Le.classList.remove(oC)},Ji=()=>o.attachments?.enabled===!0&&At!==null&&!Zo(),rC=i=>{!tm(i.dataTransfer)||!Ji()||(xl++,xl===1&&Le.classList.add(oC))},sC=i=>{!tm(i.dataTransfer)||!Ji()||(xl--,xl<=0&&Of())},iC=i=>{!tm(i.dataTransfer)||!Ji()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},aC=i=>{if(!tm(i.dataTransfer)||!Ji())return;i.preventDefault(),i.stopPropagation(),Of();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&At.handleFiles(c)},os=!0;Le.addEventListener("dragenter",rC,os),Le.addEventListener("dragleave",sC,os),t.addEventListener("dragover",iC,os),t.addEventListener("drop",aC,os);let qd=t.ownerDocument,lC=i=>{Ji()&&i.preventDefault()},cC=i=>{Ji()&&i.preventDefault()};qd.addEventListener("dragover",lC),qd.addEventListener("drop",cC),De.push(()=>{Lt?.destroy(),Lt=null,If(),Yo?.destroy(),Yo=null,fr?.destroy(),fr=null,qr?.destroy(),qr=null,jr?.destroy(),jr=null,Ur=null,dm=null,Em(),Xa.destroy(),Gi&&clearTimeout(Gi),Bs(),Xs?.abort(),Xs=null,At?.destroy(),At=null,ze.destroy(),wl.removeEventListener("keydown",Ov,!0),nn?.destroy()}),De.push(()=>{Le.removeEventListener("dragenter",rC,os),Le.removeEventListener("dragleave",sC,os),t.removeEventListener("dragover",iC,os),t.removeEventListener("drop",aC,os),qd.removeEventListener("dragover",lC),qd.removeEventListener("drop",cC),Of()}),De.push(()=>{_.cancel()}),Qt?De.push(()=>{Qt?.destroy()}):Fn&&De.push(()=>{Fn?.remove()});let Xt={update(i){let c=o.toolCall,f=o.messageActions,y=o.layout?.messages,x=o.colorScheme,k=o.loadingIndicator,q=o.iterationDisplay,te=o.features?.showReasoning,Z=o.features?.showToolCalls,ne=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,Ce=o.features?.streamAnimation?.type,He=o.features?.history?.enabled===!0,wt=o.features?.history?.provider,Ot=o.getIdentityProof,Ft=o.clientToken,xn=o.contextMentions;o=mT({...o,features:s},i),s=o.features,o=ty(o),r(),wm(),Zl(t,o),kc(t,o),Lc(t,o),ut(),Wo(),o.colorScheme!==x&&pb();let pn=ry.getForInstance(o.plugins);a.length=0,a.push(...pn),dv(),ce=o.launcher?.enabled??!0,we=o.launcher?.autoExpand??!1,yt=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,j=o.features?.scrollToBottom??{};let Jt=ao();J=o.features?.scrollBehavior??{},Jt!==ao()&&(Oo(),Qn()),Mb(),Wy(),yn();let Bn=L;if(L=o.features?.showEventStreamToggle??!1,L&&!Bn){if(je||(_t(),_.setSSEEventCallback((ue,ht)=>{o.onSSEEvent?.(ue,ht),pt(ue,ht)})),!kt&&he){let ue=o.features?.eventStream?.classNames,ht="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"+(ue?.toggleButton?" "+ue.toggleButton:"");kt=v("button",ht),kt.style.width="28px",kt.style.height="28px",kt.style.color=Un.actionIconColor,kt.type="button",kt.setAttribute("aria-label","Event Stream"),kt.title="Event Stream";let vt=Qe(Fr.Activity,"18px","currentColor",1.5);vt&&kt.appendChild(vt);let Pt=Ze.clearChatButtonWrapper,jt=Ze.closeButtonWrapper,In=Pt||jt;In&&In.parentNode===he?he.insertBefore(kt,In):he.appendChild(kt),kt.addEventListener("click",()=>{Tt?Mi():mm()})}}else!L&&Bn&&(Mi(),kt&&(kt.remove(),kt=null),je?.clear(),Te?.destroy(),je=null,Te=null,lt?.reset(),lt=null,ot=null);if(o.launcher?.enabled===!1&&Qt&&(Qt.destroy(),Qt=null),o.launcher?.enabled===!1&&Fn&&(Fn.remove(),Fn=null),o.launcher?.enabled!==!1&&!Qt&&!Fn){let{instance:ue,element:ht}=Sh({config:o,plugins:a,onToggle:Fv});Qt=ue,ue||(Fn=ht),t.appendChild(ht)}Qt&&Qt.update(o),yl(),et&&o.launcher?.subtitle!==void 0&&(et.textContent=o.launcher.subtitle);let Mt=o.layout?.header;if(Mt?.layout!==ke&&he){let ue=Mt?vu(o,Mt,{showClose:Ne(),onClose:()=>Nt(!1,"user")}):li({config:o,showClose:Ne(),onClose:()=>Nt(!1,"user")});tn.replaceHeader(ue),he=tn.header.element,le=tn.header.iconHolder,Be=tn.header.headerTitle,et=tn.header.headerSubtitle,F=tn.header.closeButton,ke=Mt?.layout,yl()}else if(Mt){if(le&&(le.style.display=Mt.showIcon===!1?"none":""),Be&&(Be.style.display=Mt.showTitle===!1?"none":""),et&&(et.style.display=Mt.showSubtitle===!1?"none":""),F){let ue=Ne()&&Mt.showCloseButton!==!1;F.style.display=ue?"":"none"}if(Ze.clearChatButtonWrapper){let ue=Mt.showClearChat;if(ue!==void 0){Ze.clearChatButtonWrapper.style.display=ue?"":"none";let{closeButtonWrapper:ht}=Ze;ht&&!ht.classList.contains("persona-absolute")&&(ue?ht.classList.remove("persona-ml-auto"):ht.classList.add("persona-ml-auto"))}}}let or=o.layout?.showHeader!==!1;he&&(he.style.display=or?"":"none");let kr=o.layout?.showFooter!==!1;We&&(We.style.display=kr?"":"none"),Ms(),yn(),ce!==ye?ce?Nt(we,"auto"):(Pe=!0,ol()):we!==N&&Nt(we,"auto"),N=we,ye=ce,Cl(),Yv();let ei=JSON.stringify(o.toolCall)!==JSON.stringify(c),_o=JSON.stringify(o.messageActions)!==JSON.stringify(f),Ln=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),No=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,Zi=o.iterationDisplay!==q,U=(o.features?.showReasoning??!0)!==(te??!0)||(o.features?.showToolCalls??!0)!==(Z??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ne)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(ei||_o||Ln||No||Zi||U)&&_&&(Os++,bo(Re,_.getMessages(),Ge));let qe=o.features?.streamAnimation?.type;if(qe!==Ce&&qe&&qe!=="none"){let ue=Sm(qe,o.features?.streamAnimation?.plugins);ue&&ic(ue,t)}let xe=o.launcher??{},Zt=xe.headerIconHidden??!1,un=o.layout?.header?.showIcon,Pn=Zt||un===!1,mn=xe.headerIconName,bn=xe.headerIconSize??"48px";if(le){let ue=he,ht=ue?.querySelector(".persona-flex-col");if(Pn)le.style.display="none",ue&&ht&&!ue.contains(ht)&&ue.insertBefore(ht,ue.firstChild);else{if(le.style.display="",le.style.height=bn,le.style.width=bn,ue&&ht&&(ue.contains(le)?le.nextSibling!==ht&&(le.remove(),ue.insertBefore(le,ht)):ue.insertBefore(le,ht)),mn){let Pt=parseFloat(bn)||24,jt=Ie(mn,Pt*.6,"currentColor",1);jt?le.replaceChildren(jt):le.textContent=xe.agentIconText??"\u{1F4AC}"}else if(xe.iconUrl){let Pt=le.querySelector("img");if(Pt)Pt.src=xe.iconUrl,Pt.style.height=bn,Pt.style.width=bn;else{let jt=document.createElement("img");jt.src=xe.iconUrl,jt.alt="",jt.className="persona-rounded-xl persona-object-cover",jt.style.height=bn,jt.style.width=bn,le.replaceChildren(jt)}}else{let Pt=le.querySelector("svg"),jt=le.querySelector("img");(Pt||jt)&&le.replaceChildren(),le.textContent=xe.agentIconText??"\u{1F4AC}"}let vt=le.querySelector("img");vt&&(vt.style.height=bn,vt.style.width=bn)}}let en=o.layout?.header?.showTitle,Dn=o.layout?.header?.showSubtitle;if(Be&&(Be.style.display=en===!1?"none":""),et&&(et.style.display=Dn===!1?"none":""),F){let ue=Ne()&&o.layout?.header?.showCloseButton!==!1;if(F.style.display=ue?"":"none",!Ee()){let Sn=xe.closeButtonSize??"";F.style.height=Sn,F.style.width=Sn,F.style.minWidth=Sn,F.style.minHeight=Sn}let ht=xe.closeButtonPlacement??"inline",{closeButtonWrapper:vt}=Ze,Pt=ht==="top-right",jt=vt?.classList.contains("persona-absolute");if(vt&&Pt!==jt)if(vt.remove(),Pt){vt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Sn=cl??Le;Sn.style.position="relative",Sn.appendChild(vt)}else{let Sn=xe.clearChat?.placement??"inline",An=xe.clearChat?.enabled??!0;vt.className=An&&Sn==="inline"?"":"persona-ml-auto",he&&he.appendChild(vt)}if(F.style.color=xe.closeButtonColor||Un.actionIconColor,xe.closeButtonBackgroundColor?(F.style.backgroundColor=xe.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let Sn=xe.closeButtonBorderWidth||"0px",An=xe.closeButtonBorderColor||"transparent";F.style.border=`${Sn} solid ${An}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");xe.closeButtonBorderRadius?(F.style.borderRadius=xe.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(F.style.paddingLeft=xe.closeButtonPaddingX,F.style.paddingRight=xe.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),xe.closeButtonPaddingY?(F.style.paddingTop=xe.closeButtonPaddingY,F.style.paddingBottom=xe.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom=""),yu(F,xe.closeButtonIconName??"x",{iconSize:Ee()?vh:void 0,iconText:xe.closeButtonIconText??"\xD7"});let In=xe.closeButtonTooltipText??"Close chat",Fo=xe.closeButtonShowTooltip??!0;F.setAttribute("aria-label",In),vt&&Mn({anchor:F,trigger:vt,text:()=>F?.getAttribute("aria-label")??In,enabled:Fo})}let{clearChatButton:tt,clearChatButtonWrapper:st}=Ze;if(tt){let ue=xe.clearChat??{},ht=ue.enabled??!0,vt=o.layout?.header?.showClearChat,Pt=vt!==void 0?vt:ht,jt=ue.placement??"inline";if(st){st.style.display=Pt?"":"none";let{closeButtonWrapper:In}=Ze;!Ee()&&In&&!In.classList.contains("persona-absolute")&&(Pt?In.classList.remove("persona-ml-auto"):In.classList.add("persona-ml-auto"));let Fo=jt==="top-right",Sn=st.classList.contains("persona-absolute");if(!Ee()&&Fo!==Sn&&Pt){if(st.remove(),Fo){st.className="persona-absolute persona-top-4 persona-z-50",st.style.right="48px";let rr=cl??Le;rr.style.position="relative",rr.appendChild(st)}else{st.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",st.style.right="";let rr=Ze.closeButtonWrapper;he&&rr&&rr.parentElement===he?he.insertBefore(st,rr):he&&he.appendChild(st)}let An=Ze.closeButtonWrapper;An&&!An.classList.contains("persona-absolute")&&(Fo?An.classList.add("persona-ml-auto"):An.classList.remove("persona-ml-auto"))}}if(Pt){if(!Ee()){let An=ue.size??"";tt.style.height=An,tt.style.width=An,tt.style.minWidth=An,tt.style.minHeight=An}let In=ue.iconColor??"";if(tt.style.color=In||Un.actionIconColor,yu(tt,ue.iconName??"refresh-cw",{iconSize:Ee()?Ch:void 0}),ue.backgroundColor?(tt.style.backgroundColor=ue.backgroundColor,tt.classList.remove("hover:persona-bg-gray-100")):(tt.style.backgroundColor="",tt.classList.add("hover:persona-bg-gray-100")),ue.borderWidth||ue.borderColor){let An=ue.borderWidth||"0px",rr=ue.borderColor||"transparent";tt.style.border=`${An} solid ${rr}`,tt.classList.remove("persona-border-none")}else tt.style.border="",tt.classList.add("persona-border-none");ue.borderRadius?(tt.style.borderRadius=ue.borderRadius,tt.classList.remove("persona-rounded-full")):(tt.style.borderRadius="",tt.classList.add("persona-rounded-full")),ue.paddingX?(tt.style.paddingLeft=ue.paddingX,tt.style.paddingRight=ue.paddingX):(tt.style.paddingLeft="",tt.style.paddingRight=""),ue.paddingY?(tt.style.paddingTop=ue.paddingY,tt.style.paddingBottom=ue.paddingY):(tt.style.paddingTop="",tt.style.paddingBottom="");let Fo=ue.tooltipText??"Clear chat",Sn=ue.showTooltip??!0;tt.setAttribute("aria-label",Fo),st&&Mn({anchor:tt,trigger:st,text:()=>tt?.getAttribute("aria-label")??Fo,enabled:Sn})}}let Ue=o.actionParsers&&o.actionParsers.length?o.actionParsers:[iy],_n=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pc.message,Pc.messageAndClick];se=ay({parsers:Ue,handlers:_n,getSessionMetadata:K,updateSessionMetadata:Y,emit:E.emit,documentRef:typeof document<"u"?document:null}),Ge=KT(o,se,xt),rk(),_.updateConfig(o),(o.features?.history?.enabled===!0!==He||o.features?.history?.provider!==wt||o.getIdentityProof!==Ot||o.clientToken!==Ft)&&(Jn({restoreFocus:!1}),nv()),ts(),Ld(),bo(Re,_.getMessages(),Ge),Pi(),md(),nk(),rl(_.isStreaming()),xn!==o.contextMentions&&eC();let rs=o.voiceRecognition?.enabled===!0,Zn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),eo=no(o.voiceRecognition?.provider);if(rs&&(Zn||eo))if(!fe||!io){let ue=ha(o);if(ue){fe=ue.button,io=ue.wrapper;let ht=jo&&jo.parentElement===$r?jo:null;$r?$r.insertBefore(io,ht):Wn?.appendChild(io),Lt&&(Lt.micButton=fe),Lt?.addListener(fe,"click",Wf),fe.disabled=Zo()||_.isStreaming()&&!Wm()}}else{let ue=o.voiceRecognition??{},ht=o.sendButton??{},vt=ue.iconName??"mic",Pt=ue.iconSize,jt=parseFloat(Pt??"")||$n;fe.classList.add(fo),fe.classList.toggle($o,!Pt),fe.style.width=Pt??"",fe.style.height=Pt??"",fe.style.minWidth=Pt??"",fe.style.minHeight=Pt??"";let In=ue.iconColor??ht.textColor;fe.innerHTML="";let Fo=Ie(vt,jt,In||"currentColor",1.5);Fo?fe.appendChild(Fo):fe.textContent="\u{1F3A4}";let Sn=ue.backgroundColor??ht.backgroundColor;Sn?fe.style.backgroundColor=Sn:fe.style.backgroundColor="",In?fe.style.color=In:fe.style.color="var(--persona-text, #111827)",ue.borderWidth?(fe.style.borderWidth=ue.borderWidth,fe.style.borderStyle="solid"):(fe.style.borderWidth="",fe.style.borderStyle=""),ue.borderColor?fe.style.borderColor=ue.borderColor:fe.style.borderColor="",ue.paddingX?(fe.style.paddingLeft=ue.paddingX,fe.style.paddingRight=ue.paddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),ue.paddingY?(fe.style.paddingTop=ue.paddingY,fe.style.paddingBottom=ue.paddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let An=ue.tooltipText??"Start voice recognition",rr=ue.showTooltip??!1;fe.setAttribute("aria-label",An),io&&Mn({anchor:fe,trigger:io,text:()=>fe?.getAttribute("aria-label")??An,enabled:rr}),io.style.display="",fe.disabled=Zo()||_.isStreaming()&&!Wm()}else fe&&io&&(io.style.display="none",no(o.voiceRecognition?.provider)?_.isVoiceActive()&&_.toggleVoice():nr&&ns());if(o.attachments?.enabled===!0){if(!Kn||!Gt){let ue=o.attachments??{};Gn||(Gn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Gn.style.display="none",(Ae.parentElement??Wn).insertBefore(Gn,Ae)),zt||(zt=document.createElement("input"),zt.type="file",zt.accept=(ue.allowedTypes??Hr).join(","),zt.multiple=(ue.maxFiles??4)>1,zt.style.display="none",zt.setAttribute("aria-label","Attach files"),(Ae.parentElement??Wn).insertBefore(zt,Ae)),Kn=v("div","persona-send-button-wrapper"),Gt=v("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${fo} ${$o}`),Gt.type="button",Gt.setAttribute("aria-label",ue.buttonTooltipText??"Attach file");let ht=ue.buttonIconName??"paperclip";Gt.style.fontSize="18px",Gt.style.lineHeight="1";let vt=Ie(ht,$n,"currentColor",1.5);vt?Gt.appendChild(vt):Gt.textContent="\u{1F4CE}",Gt.addEventListener("click",jt=>{jt.preventDefault(),zt?.click()}),Kn.appendChild(Gt);let Pt=ue.buttonTooltipText??"Attach file";Mn({anchor:Gt,trigger:Kn,text:()=>Gt?.getAttribute("aria-label")??Pt}),qo?qo.append(Kn):Wn.appendChild(Kn),Lt&&(Lt.attachmentButton=Gt,Lt.attachmentInput=zt??void 0,Lt.attachmentPreviews=Gn??void 0),!At&&zt&&Gn&&(At=$l.fromConfig(ue,By),At.setPreviewsContainer(Gn),Lt?.addListener(zt,"change",async()=>{At&&zt?.files&&(await At.handleFileSelect(zt.files),zt.value="")}))}else{Kn.style.display="";let ue=o.attachments??{};zt&&(zt.accept=(ue.allowedTypes??Hr).join(","),zt.multiple=(ue.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:ue.allowedTypes,maxFileSize:ue.maxFileSize,maxFiles:ue.maxFiles,adapter:ue.adapter})}if(Le.querySelector(".persona-attachment-drop-overlay")?.remove(),Le.appendChild(GT(o.attachments?.dropOverlay)),Gt){let ue=o.attachments??{},ht=ue.buttonTooltipText??"Attach file";Gt.setAttribute("aria-label",ht),Gt.textContent="";let vt=Ie(ue.buttonIconName??"paperclip",$n,"currentColor",1.5);vt?Gt.appendChild(vt):Gt.textContent="\u{1F4CE}",Kn&&Mn({anchor:Gt,trigger:Kn,text:()=>Gt?.getAttribute("aria-label")??ht})}}else Kn&&(Kn.style.display="none"),At&&At.clearAttachments(),Le.querySelector(".persona-attachment-drop-overlay")?.remove();let rt=o.sendButton??{},Lr=rt.useIcon??!1,on=rt.iconText??"\u2191",to=rt.iconName,Al=rt.tooltipText??"Send message",v0=rt.showTooltip??!1,Ml=rt.size,C0=parseFloat(Ml??"")||Sg,jd=rt.backgroundColor,Tl=rt.textColor;if(Lr){if(Ve.style.width=Ml??"",Ve.style.height=Ml??"",Ve.style.minWidth=Ml??"",Ve.style.minHeight=Ml??"",Ve.style.fontSize="18px",Ve.style.lineHeight="1",Tl?Ve.style.color=Tl:Ve.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!_.isStreaming())if(Ve.innerHTML="",to){let ue=parseFloat(rt.iconSize??"")||Math.round(C0*.5),ht=Tl?.trim()||"currentColor",vt=rt.iconStrokeWidth??2,Pt=Ie(to,ue,ht,vt),jt=Ie(rt.stopIconName??"square",ue,ht,vt);Pt&&jt?Ve.appendChild(Ag(Pt,jt)):Pt?Ve.appendChild(Pt):Ve.textContent=on}else Ve.textContent=on;Ve.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${fo}`,jd?(Ve.style.backgroundColor=jd,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=o.copy?.sendButtonLabel??"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.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",jd?(Ve.style.backgroundColor=jd,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),Tl?Ve.style.color=Tl:Ve.classList.add("persona-text-white");rt.borderWidth?(Ve.style.borderWidth=rt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),rt.borderColor?Ve.style.borderColor=rt.borderColor:Ve.style.borderColor="",rt.paddingX?(Ve.style.paddingLeft=rt.paddingX,Ve.style.paddingRight=rt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),rt.paddingY?(Ve.style.paddingTop=rt.paddingY,Ve.style.paddingBottom=rt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom=""),_.isStreaming()||Ve.setAttribute("aria-label",Al),pd(),jo&&Mn({anchor:Ve,trigger:jo,text:()=>Ve.getAttribute("aria-label")??Al,enabled:v0}),Qy();let dC=$p(ze.getState().activeModeIds,o.composer?.modes);ze.setActiveModeIds(dC),xi().length>0!==!!fr&&gm(),fr?.render(dC,xi());for(let ue of[...Si.keys()])Vp(ue,o.composer?.modeGroups)||Si.delete(ue);Si.forEach(ue=>ue.repaint()),Ur?.repaint(),Yo?.resolve();let Kd=ys(o,Ee());if(xm(),Kd){Re.style.maxWidth=Kd,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",kn.style.maxWidth=Kd,kn.style.marginLeft="auto",kn.style.marginRight="auto",kn.style.width="100%";for(let ue of[Wn,Io,Gn,bt])ue&&(ue.style.maxWidth=Kd,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%")}else{Re.style.maxWidth="",Re.style.marginLeft="",Re.style.marginRight="",Re.style.width="",kn.style.maxWidth="",kn.style.marginLeft="",kn.style.marginRight="",kn.style.width="";for(let ue of[Wn,Io,Gn,bt])ue&&(ue.style.maxWidth="",ue.style.marginLeft="",ue.style.marginRight="",ue.style.width="")}let ss=o.statusIndicator??{},w0=ss.visible??!0;if(bt.style.display=w0?"":"none",_){let ue=_.getStatus();Rn(bt,(vt=>vt==="idle"?ss.idleText??fn.idle:vt==="connecting"?ss.connectingText??fn.connecting:vt==="connected"?ss.connectedText??fn.connected:vt==="error"?ss.errorText??fn.error:fn[vt])(ue),ss,ue)}bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let x0=ss.align==="left"?"persona-text-left":ss.align==="center"?"persona-text-center":"persona-text-right";bt.classList.add(x0),fm(),Om(),Ho(),Ke()},open(){Ne()&&Nt(!0,"api")},close(){Ne()&&Nt(!1,"api")},toggle(){Ne()&&Nt(!Pe,"api")},reconnect(){_.reconnectNow()},clearChat(){gr=!1,_.clearMessages(),cn.clear(),Qn();try{localStorage.removeItem(Ba),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ba}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ba)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),R?.clear&&od(()=>R.clear(),"[AgentWidget] Failed to clear storage adapter:"),H={},se.syncFromMetadata(),At?.clearAttachments(),sd(),Ai(void 0),Go(void 0),Bs(),je?.clear(),lt?.reset(),mt?.update()},setMessage(i){return!Ae||_.isStreaming()||Zo()?!1:(!Pe&&Ne()&&Nt(!0,"system"),Ae.value=i,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming()||$s())return!1;let c=i?.trim()||Ae.value.trim();return c?(!Pe&&Ne()&&Nt(!0,"system"),Ae.value="",Ae.style.height="auto",Ko(),Fd(c,{consumeDraft:!1}),!0):!1},getComposerState(){return ze.getState()},setQuote(i){let c=i?.text?.trim();c&&Go({...i,text:c})},clearQuote(){Go(void 0)},startVoiceRecognition(){return _.isStreaming()?!1:no(o.voiceRecognition?.provider)?(_.isVoiceActive()||_.isBargeInActive()||(!Pe&&Ne()&&Nt(!0,"system"),gt.manuallyDeactivated=!1,Bo(),_.toggleVoice().then(()=>{gt.active=_.isVoiceActive(),vr("user"),_.isVoiceActive()&&Xi()})),!0):nr?!0:Nv()?(!Pe&&Ne()&&Nt(!0,"system"),gt.manuallyDeactivated=!1,Bo(),$d("user"),!0):!1},stopVoiceRecognition(){return no(o.voiceRecognition?.provider)?!_.isVoiceActive()&&!_.isBargeInActive()?!1:((_.isBargeInActive()?_.deactivateBargeIn():_.toggleVoice()).then(()=>{gt.active=!1,gt.manuallyDeactivated=!0,Bo(),vr("user"),Er()}),!0):nr?(gt.manuallyDeactivated=!0,Bo(),ns("user"),!0):!1},injectMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!Pe&&Ne()&&Nt(!0,"system");let c=_.injectAssistantMessage(i);return dt&&(dt=!1,Xe&&(clearTimeout(Xe),Xe=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),c},injectUserMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!Pe&&Ne()&&Nt(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!Pe&&Ne()&&Nt(!0,"system"),_.injectTestEvent(i)},async connectStream(i,c){return _.connectStream(i,c)},__pushEventStreamEvent(i){L&&(_t(),pt(i.type,i.payload))},showEventStream(){L&&mm()},hideEventStream(){Tt&&Mi()},isEventStreamVisible(){return Tt},listConversations(i){return _.listConversations(i)},getActiveConversationId(){return _.getActiveConversationId()},openConversation(i,c){return vf(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Cf({focusComposer:i?.focus===!0})},deleteConversation(i){return kv(i)},renameConversation(i,c){return wf(i,{title:c})},setConversationStarred(i,c){return wf(i,{starred:c})},clearConversationHistory(i){return Lv(i)},resetHistoryIdentity(){return Pv()},async getVisitorToken(){let i=vo;if(!i)return null;let c=await i.get();return i===vo?c:null},getHistoryIdentityStatus(){return uo?uo.getIdentityStatus():tf()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return hl({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Jn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return ve},showArtifacts(){jn(o)&&(gr=!1,Ei=!0,Wo(),ft?.setMobileOpen(!0))},hideArtifacts(){jn(o)&&(gr=!0,Wo())},upsertArtifact(i){return jn(o)?(is(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(gr=!1,Ei=!0),_.upsertArtifact(i)):null},selectArtifact(i){jn(o)&&_.selectArtifact(i)},clearArtifacts(){jn(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return ce&&!Pe&&!Ee()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(i,c,f){let x=_.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!x?.approval)throw new Error(`Approval not found: ${i}`);if(x.approval.toolType==="webmcp"){_.resolveWebMcpApproval(x.id,c);return}return _.resolveApproval(x.approval,c,f)},setFollowUpSuggestions(i){EE(i)},clearFollowUpSuggestions(){Ab()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...H}},updatePersistentMetadata(i){Y(i)},on(i,c){return E.on(i,c)},off(i,c){E.off(i,c)},isOpen(){return Ne()&&Pe},isVoiceActive(){return gt.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:Ne()&&Pe,launcherEnabled:ce,voiceActive:gt.active,streaming:_.isStreaming()}},showCSATFeedback(i){!Pe&&Ne()&&Nt(!0,"system");let c=Re.querySelector(".persona-feedback-container");c&&c.remove();let f=UT({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});Re.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Pe&&Ne()&&Nt(!0,"system");let c=Re.querySelector(".persona-feedback-container");c&&c.remove();let f=qT({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});Re.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return _.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return _.submitNPSFeedback(i,c)},destroy(){Gm(),qs!=null&&(clearInterval(qs),qs=null),De.forEach(i=>i()),it.remove(),Kt?.remove(),Qt?.destroy(),Fn?.remove(),Is&&F.removeEventListener("click",Is)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Xt,getMessages:Xt.getMessages,getStatus:Xt.getStatus,getMetadata:Xt.getPersistentMetadata,updateMetadata:Xt.updatePersistentMetadata,clearHistory:()=>Xt.clearChat(),setVoiceActive:f=>f?Xt.startVoiceRecognition():Xt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,De.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),c=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.focusInput()};if(window.addEventListener("persona:focusInput",c),De.push(()=>{window.removeEventListener("persona:focusInput",c)}),L){let ne=Ce=>{let He=Ce.detail;(!He?.instanceId||He.instanceId===i)&&Xt.showEventStream()},pe=Ce=>{let He=Ce.detail;(!He?.instanceId||He.instanceId===i)&&Xt.hideEventStream()};window.addEventListener("persona:showEventStream",ne),window.addEventListener("persona:hideEventStream",pe),De.push(()=>{window.removeEventListener("persona:showEventStream",ne),window.removeEventListener("persona:hideEventStream",pe)})}let f=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.showHistory()},y=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",y),De.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",y)});let x=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.showArtifacts()},k=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.hideArtifacts()},q=ne=>{let pe=ne.detail;pe?.instanceId&&pe.instanceId!==i||pe?.artifact&&Xt.upsertArtifact(pe.artifact)},te=ne=>{let pe=ne.detail;pe?.instanceId&&pe.instanceId!==i||typeof pe?.id=="string"&&Xt.selectArtifact(pe.id)},Z=ne=>{let pe=ne.detail;(!pe?.instanceId||pe.instanceId===i)&&Xt.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",te),window.addEventListener("persona:clearArtifacts",Z),De.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",te),window.removeEventListener("persona:clearArtifacts",Z)})}let Ao=WB(o.persistState);if(Ao&&Ne()){let i=BB(Ao.storage),c=`${Ao.keyPrefix}widget-open`,f=`${Ao.keyPrefix}widget-voice`,y=`${Ao.keyPrefix}widget-voice-mode`;if(i){let x=Ao.persist?.openState&&i.getItem(c)==="true",k=Ao.persist?.voiceState&&i.getItem(f)==="true",q=Ao.persist?.voiceState&&i.getItem(y)==="true";if(x&&(Qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Xt.open(),setTimeout(()=>{if(k||q)Xt.startVoiceRecognition();else if(Ao.persist?.focusInput){let te=t.querySelector("textarea");te&&te.focus()}},100)},0)),Ao.persist?.openState&&(E.on("widget:opened",()=>{i.setItem(c,"true")}),E.on("widget:closed",()=>{i.setItem(c,"false")})),Ao.persist?.voiceState&&(E.on("voice:state",te=>{i.setItem(f,te.active?"true":"false")}),E.on("user:message",te=>{i.setItem(y,te.viaVoice?"true":"false")})),Ao.clearOnChatClear){let te=()=>{i.removeItem(c),i.removeItem(f),i.removeItem(y)},Z=()=>te();window.addEventListener("persona:clear-chat",Z),De.push(()=>{window.removeEventListener("persona:clear-chat",Z)})}}}if(G&&Ne()&&(Qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Xt.open()},0)),Di(),!kE){let i=ea(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))});De.push(i)}C=()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))},_.getMessages().length>0&&dd(),A=()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))};let y0=Jw(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge))});De.push(y0);let b0=Xh(()=>{_&&(Os++,cn.clear(),bo(Re,_.getMessages(),Ge),Dr()?.updateInlineArtifactBlocks(Re,yo.artifacts,{suppressTransition:!0}),Wo())});return De.push(b0),Xt};fs();var QT=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},_B=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},NB=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},FB=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},XT=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Ey=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},JT=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Ey(t)},Ay=t=>{t.style.transition=""},My=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Ty=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},nm=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},VB=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},$B=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},zB=t=>{let e=Ca(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:zn(e,r)??r;return{inset:o(n?.inset,ou),canvasBackground:o(n?.canvasBackground,ru)}},ZT=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},UB=(t,e,n,o,r,s,a,l)=>{let d=Lo(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",h=l?.canvasBackground??"";VB(t,e,n,o,p),$B(t,e,n,o,d.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.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 g=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,S=g!=null?g.innerWidth<=C:!1;if(b&&S&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),My(e),Ay(o),JT(o),Ty(n),nm(r,o),ZT(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Hn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),JT(o),_B(o,d.maxHeight),ZT(o,u&&a,m,h),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",My(e),Ay(o),Ty(n),nm(r,o);let M=d.animate?"transform 180ms ease":"none",B=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Ay(o),Ey(o),nm(r,o);let M=QT(d.width,t.clientWidth),B=Math.max(0,t.clientWidth),A=d.animate?"margin-left 180ms ease":"none",O=d.side==="right"?a?-M:0:a?0:-M;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${B+M}px`,e.style.transition=A,e.style.marginLeft=`${O}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",My(e),Ey(o),Ty(n),nm(r,o);let M=d.reveal==="emerge";M?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let B=a?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",O=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",NB(o,d.maxHeight),o.style.overflow=M||O?"hidden":"visible",o.style.transition=A,M){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let E=u?`calc(${QT(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=E,r.style.minWidth=E,r.style.maxWidth=E,r.style.boxSizing="border-box"}}},qB=(t,e)=>{let n=t.ownerDocument.createElement("div");return XT(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){XT(n,o)},destroy(){n.remove()}}},jB=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,t),d.appendChild(t);let h=null,g=()=>{h?.disconnect(),h=null},b=null,C=()=>{b=e?.launcher?.detachedPanel===!0?zB(e):null};C();let S=()=>{UB(a,l,d,p,u,e,m,b)},P=null,M=()=>{P?.(),P=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(P=su(()=>{C(),S()}))},B=()=>{g(),Lo(e).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{S()}),h.observe(a)))},A=!1,O=()=>{S(),B(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,FB(a,Lo(e)))},E=a.ownerDocument.defaultView,W=()=>{O()};return E?.addEventListener("resize",W),Lo(e).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),O(),M(),{mode:"docked",host:u,shell:a,syncWidgetState(R){let V=R.launcherEnabled?R.open:!0;m!==V&&(m=V,O())},updateConfig(R){e=R,(e?.launcher?.enabled??!0)===!1&&(m=!0),C(),O(),M()},destroy(){E?.removeEventListener("resize",W),P?.(),P=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},eE=(t,e)=>rn(e)?jB(t,e):qB(t,e);var Oc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},tE=.15,nE=1.5,ky="persona-preview-shell-theme",KB={load:()=>null,save:()=>{},clear:()=>{}},GB=["How do I get started?","Pricing & plans","Talk to support"];function Ly(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function YB(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function oE(t){let e=YB(t);return`* { box-sizing: border-box; }
1268
1268
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
1269
1269
  html { color-scheme: ${t}; }
1270
1270
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }